From 7e6e38b106e5712bf52e6fc2ac036e5c8af25580 Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Tue, 25 May 2021 10:30:55 -0400 Subject: [PATCH 1/6] Fix typo in docs --- esm/layouts/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esm/layouts/index.js b/esm/layouts/index.js index ea8c5df1..f15346e8 100644 --- a/esm/layouts/index.js +++ b/esm/layouts/index.js @@ -855,7 +855,7 @@ const genes_panel = { }; /** - * A pael that displays PheWAS scatter plots and automatically generates a color scheme + * A panel that displays PheWAS scatter plots and automatically generates a color scheme * @type panel */ const phewas_panel = { From ea3894e8d06a040a0036844d83a222b577a3ca40 Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Thu, 17 Jun 2021 15:49:28 -0400 Subject: [PATCH 2/6] Use new color scheme for LD, "Turbo": a rainbow replacement with better support for colorblind users --- esm/layouts/index.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/esm/layouts/index.js b/esm/layouts/index.js index f15346e8..aedf82ce 100644 --- a/esm/layouts/index.js +++ b/esm/layouts/index.js @@ -183,19 +183,20 @@ const association_pvalues_layer = { field: '{{namespace[ld]}}state', parameters: { breaks: [0, 0.2, 0.4, 0.6, 0.8], - values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'], + // Derived from Google "Turbo" colormap, breakpoints [0.05, 0.25, 0.45, 0.65, 0.85] + values: ['rgb(70, 54, 153)', 'rgb(38, 188, 225)', 'rgb(110, 254, 104)', 'rgb(248, 195, 42)', 'rgb(219, 61, 17)'], }, }, - '#B8B8B8', + '#AAAAAA', ], legend: [ { shape: 'diamond', color: '#9632b8', size: 40, label: 'LD Ref Var', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#d43f3a', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#eea236', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#5cb85c', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#46b8da', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#357ebd', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#B8B8B8', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(219, 61, 17)', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(248, 195, 42)', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(110, 254, 104)', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(38, 188, 225)', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(70, 54, 153)', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: '#AAAAAA', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' }, ], label: null, z_index: 2, From e4c6fb9861249a31471362ffbbc5eae2fa6d82b2 Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Thu, 29 Jul 2021 16:42:03 -0400 Subject: [PATCH 3/6] Add citation (CFF) file used by new GitHub link feature --- citation.cff | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 citation.cff diff --git a/citation.cff b/citation.cff new file mode 100644 index 00000000..84542c18 --- /dev/null +++ b/citation.cff @@ -0,0 +1,32 @@ +# YAML 1.2 +--- +abstract: "LocusZoom.js is a JavaScript library for creating interactive web-based visualizations of genetic association study results. It can display one or more traits in the context of relevant biological data (such as gene models and other genomic annotation), and allows interactive refinement of analysis models (by selecting linkage disequilibrium reference panels, identifying sets of likely causal variants, or comparisons to the GWAS catalog). It can be embedded in web pages to enable data sharing and exploration. Views can be customized and extended to display other data types such as phenome-wide association study (PheWAS) results, chromatin co-accessibility, or eQTL measurements. A new web upload service harmonizes datasets, adds annotations, and makes it easy to explore user-provided result sets." +authors: + - + family-names: Boughton + given-names: Andrew + orcid: "https://orcid.org/0000-0002-0318-4912" + - + family-names: Welch + given-names: Ryan + - + family-names: Matthew + given-names: Flickinger + - + family-names: VandeHaar + given-names: Peter + - + family-names: Taliun + given-names: Daniel + - + family-names: Abecasis + given-names: "Gonçalo" + - + family-names: Boehnke + given-names: Michael +cff-version: "1.1.0" +date-published: "2021-03-18" +doi: "10.1093/bioinformatics/btab186" +journal: "Bioinformatics" +message: "If you use this software, please cite the paper." +title: " LocusZoom.js: interactive and embeddable visualization of genetic association study results" From d26ddee9d04010139f2941a3117466836da9f967 Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Thu, 29 Jul 2021 16:46:52 -0400 Subject: [PATCH 4/6] Add dummy version tag to appease GitHub CFF parser --- citation.cff | 2 ++ 1 file changed, 2 insertions(+) diff --git a/citation.cff b/citation.cff index 84542c18..7dc426d7 100644 --- a/citation.cff +++ b/citation.cff @@ -30,3 +30,5 @@ doi: "10.1093/bioinformatics/btab186" journal: "Bioinformatics" message: "If you use this software, please cite the paper." title: " LocusZoom.js: interactive and embeddable visualization of genetic association study results" +# Insert dummy version b/c the paper reports ongoing efforts +version: 1.0 From 75bad9f6fe75b71a85a959f76c1f21ca917c189a Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Fri, 20 Aug 2021 16:55:29 -0400 Subject: [PATCH 5/6] Update dependencies --- package-lock.json | 132 ++++++++++++++++++++++++---------------------- package.json | 2 +- 2 files changed, 71 insertions(+), 63 deletions(-) diff --git a/package-lock.json b/package-lock.json index 474f4b6a..df5a0be6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -371,9 +371,9 @@ } }, "@babel/parser": { - "version": "7.12.10", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.10.tgz", - "integrity": "sha512-PJdRPwyoOqFAWfLytxrWwGrAxghCgh/yTNCYciOz8QgjflA7aZhECPZAa2VUedKg2+QMWkI0L9lynh2SNmNEgA==", + "version": "7.15.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.3.tgz", + "integrity": "sha512-O0L6v/HvqbdJawj0iBEfVQMc3/6WP+AeOsovsIgBFyJaG+W2w7eqvZB7puddATmWuARlm1SX7DwxJ/JJUnDpEA==", "dev": true }, "@babel/plugin-proposal-async-generator-functions": { @@ -2004,16 +2004,42 @@ "dev": true }, "browserslist": { - "version": "4.16.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.3.tgz", - "integrity": "sha512-vIyhWmIkULaq04Gt93txdh+j02yX/JzlyhLYbV3YQCn/zvES3JnY7TifHHvvr1w5hTDluNKMkV05cs4vy8Q7sw==", + "version": "4.16.8", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.8.tgz", + "integrity": "sha512-sc2m9ohR/49sWEbPj14ZSSZqp+kbi16aLao42Hmn3Z8FpjuMaq2xCA2l4zl9ITfyzvnvyE0hcg62YkIGKxgaNQ==", "dev": true, "requires": { - "caniuse-lite": "^1.0.30001181", - "colorette": "^1.2.1", - "electron-to-chromium": "^1.3.649", + "caniuse-lite": "^1.0.30001251", + "colorette": "^1.3.0", + "electron-to-chromium": "^1.3.811", "escalade": "^3.1.1", - "node-releases": "^1.1.70" + "node-releases": "^1.1.75" + }, + "dependencies": { + "caniuse-lite": { + "version": "1.0.30001251", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001251.tgz", + "integrity": "sha512-HOe1r+9VkU4TFmnU70z+r7OLmtR+/chB1rdcJUeQlAinjEeb0cKL20tlAtOagNZhbrtLnCvV19B4FmF1rgzl6A==", + "dev": true + }, + "colorette": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.3.0.tgz", + "integrity": "sha512-ecORCqbSFP7Wm8Y6lyqMJjexBQqXSF7SSeaTyGGphogUjBlFP9m9o08wy86HL2uB7fMTxtOUzLMk7ogKcxMg1w==", + "dev": true + }, + "electron-to-chromium": { + "version": "1.3.813", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.813.tgz", + "integrity": "sha512-YcSRImHt6JZZ2sSuQ4Bzajtk98igQ0iKkksqlzZLzbh4p0OIyJRSvUbsgqfcR8txdfsoYCc4ym306t4p2kP/aw==", + "dev": true + }, + "node-releases": { + "version": "1.1.75", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.75.tgz", + "integrity": "sha512-Qe5OUajvqrqDSy6wrWFmMwfJ0jVgwiw4T3KqmbTcZ62qW0gQkheXYhcFM1+lOVcGUoRxcEcfyvFMAnDgaF1VWw==", + "dev": true + } } }, "buffer-from": { @@ -2073,12 +2099,6 @@ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, - "caniuse-lite": { - "version": "1.0.30001191", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001191.tgz", - "integrity": "sha512-xJJqzyd+7GCJXkcoBiQ1GuxEiOBCLQ0aVW9HMekifZsAVGdj5eJ4mFB9fEhSHipq9IOk/QXFJUiIr9lZT+EsGw==", - "dev": true - }, "caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", @@ -2086,12 +2106,12 @@ "dev": true }, "catharsis": { - "version": "0.8.11", - "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz", - "integrity": "sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g==", + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.9.0.tgz", + "integrity": "sha512-prMTQVpcns/tzFgFVkVp6ak6RykZyWb3gu8ckUpd6YkTlacOd3DXGJjIpD4Q6zJirizvaiAjSSHlOsA+6sNh2A==", "dev": true, "requires": { - "lodash": "^4.17.14" + "lodash": "^4.17.15" } }, "chai": { @@ -2750,12 +2770,6 @@ "safer-buffer": "^2.1.0" } }, - "electron-to-chromium": { - "version": "1.3.673", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.673.tgz", - "integrity": "sha512-ms+QR2ckfrrpEAjXweLx6kNCbpAl66DcW//3BZD4BV5KhUgr0RZRce1ON/9J3QyA3JO28nzgb5Xv8DnPr05ILg==", - "dev": true - }, "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3467,9 +3481,9 @@ } }, "glob-parent": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", - "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "requires": { "is-glob": "^4.0.1" @@ -4108,25 +4122,25 @@ "dev": true }, "jsdoc": { - "version": "3.6.6", - "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.6.tgz", - "integrity": "sha512-znR99e1BHeyEkSvgDDpX0sTiTu+8aQyDl9DawrkOGZTTW8hv0deIFXx87114zJ7gRaDZKVQD/4tr1ifmJp9xhQ==", + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.7.tgz", + "integrity": "sha512-sxKt7h0vzCd+3Y81Ey2qinupL6DpRSZJclS04ugHDNmRUXGzqicMJ6iwayhSA0S0DwwX30c5ozyUthr1QKF6uw==", "dev": true, "requires": { "@babel/parser": "^7.9.4", "bluebird": "^3.7.2", - "catharsis": "^0.8.11", + "catharsis": "^0.9.0", "escape-string-regexp": "^2.0.0", "js2xmlparser": "^4.0.1", "klaw": "^3.0.0", "markdown-it": "^10.0.0", "markdown-it-anchor": "^5.2.7", - "marked": "^0.8.2", + "marked": "^2.0.3", "mkdirp": "^1.0.4", "requizzle": "^0.2.3", "strip-json-comments": "^3.1.0", "taffydb": "2.6.2", - "underscore": "~1.10.2" + "underscore": "~1.13.1" }, "dependencies": { "escape-string-regexp": { @@ -4134,12 +4148,6 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true - }, - "mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true } } }, @@ -4333,9 +4341,9 @@ } }, "lodash": { - "version": "4.17.20", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", - "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "lodash.debounce": { @@ -4467,9 +4475,9 @@ "dev": true }, "marked": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/marked/-/marked-0.8.2.tgz", - "integrity": "sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/marked/-/marked-2.1.3.tgz", + "integrity": "sha512-/Q+7MGzaETqifOMWYEA7HVMaZb4XbcRfaOzcSsHZEith83KGlvaSG33u0SKu89Mj5h+T8V2hM+8O45Qc5XTgwA==", "dev": true }, "mdurl": { @@ -4520,6 +4528,12 @@ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "dev": true }, + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true + }, "mocha": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.3.0.tgz", @@ -4746,12 +4760,6 @@ "process-on-spawn": "^1.0.0" } }, - "node-releases": { - "version": "1.1.71", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.71.tgz", - "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==", - "dev": true - }, "normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -5186,9 +5194,9 @@ "dev": true }, "path-parse": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", - "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, "path-to-regexp": { @@ -6241,9 +6249,9 @@ "dev": true }, "underscore": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.10.2.tgz", - "integrity": "sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.1.tgz", + "integrity": "sha512-hzSoAVtJF+3ZtiFX0VgfFPHEDRm7Y/QPjGyNo4TVdnDTdft3tr8hEkD25a1jC+TjTuE7tkHGKkhwCgs9dgBB2g==", "dev": true }, "unicode-canonical-property-names-ecmascript": { @@ -6672,9 +6680,9 @@ } }, "ws": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.3.1.tgz", - "integrity": "sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA==", + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.3.tgz", + "integrity": "sha512-kQ/dHIzuLrS6Je9+uv81ueZomEwH0qVYstcAQ4/Z93K8zeko9gtAbttJWzoC5ukqXY1PpoouV3+VSOqEAFt5wg==", "dev": true }, "xml-name-validator": { diff --git a/package.json b/package.json index 2e023409..064b89b2 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "eslint": "^7.20.0", "eslint-webpack-plugin": "^2.5.2", "friendly-errors-webpack-plugin": "^1.7.0", - "jsdoc": "^3.6.6", + "jsdoc": "^3.6.7", "jsdom": "^16.4.0", "jsdom-global": "^3.0.2", "mocha": "^8.3.0", From b8fed64eed3c648d441d9c3e36bfb9e5247ded42 Mon Sep 17 00:00:00 2001 From: Andy Boughton Date: Tue, 21 Sep 2021 14:37:52 -0400 Subject: [PATCH 6/6] Bump for v0.13.4 --- README.md | 4 +- dist/ext/lz-aggregation-tests.min.js | 2 +- dist/ext/lz-credible-sets.min.js | 2 +- dist/ext/lz-dynamic-urls.min.js | 2 +- dist/ext/lz-forest-track.min.js | 2 +- dist/ext/lz-intervals-enrichment.min.js | 2 +- dist/ext/lz-intervals-track.min.js | 2 +- dist/ext/lz-tabix-source.min.js | 2 +- dist/ext/lz-widget-addons.min.js | 2 +- dist/ext/lz-widget-addons.min.js.map | 2 +- dist/locuszoom.app.min.js | 4 +- dist/locuszoom.app.min.js.map | 2 +- docs/api/LayoutRegistry.html | 2 +- docs/api/Line.html | 2 +- docs/api/Panel.html | 2 +- docs/api/Plot.html | 2 +- docs/api/TransformationFunctionsRegistry.html | 2 +- ...onents_data_layer_annotation_track.js.html | 2 +- docs/api/components_data_layer_arcs.js.html | 2 +- docs/api/components_data_layer_base.js.html | 2 +- docs/api/components_data_layer_genes.js.html | 2 +- ...nents_data_layer_highlight_regions.js.html | 2 +- docs/api/components_data_layer_line.js.html | 2 +- .../api/components_data_layer_scatter.js.html | 2 +- docs/api/components_legend.js.html | 2 +- docs/api/components_panel.js.html | 2 +- docs/api/components_plot.js.html | 2 +- docs/api/components_toolbar_index.js.html | 2 +- docs/api/components_toolbar_widgets.js.html | 2 +- docs/api/data_adapters.js.html | 2 +- docs/api/data_field.js.html | 2 +- docs/api/data_requester.js.html | 2 +- docs/api/data_sources.js.html | 2 +- docs/api/ext_lz-credible-sets.js.html | 2 +- docs/api/ext_lz-dynamic-urls.js.html | 2 +- docs/api/ext_lz-forest-track.js.html | 2 +- docs/api/ext_lz-intervals-enrichment.js.html | 2 +- docs/api/ext_lz-intervals-track.js.html | 2 +- docs/api/ext_lz-tabix-source.js.html | 2 +- docs/api/ext_lz-widget-addons.js.html | 2 +- docs/api/global.html | 2 +- docs/api/helpers_common.js.html | 2 +- docs/api/helpers_display.js.html | 2 +- docs/api/helpers_jsonpath.js.html | 2 +- docs/api/helpers_layouts.js.html | 2 +- docs/api/helpers_render.js.html | 2 +- docs/api/helpers_scalable.js.html | 2 +- docs/api/helpers_transforms.js.html | 2 +- docs/api/index.html | 4 +- docs/api/index.js.html | 2 +- docs/api/layouts_index.js.html | 21 ++++---- docs/api/module-LocusZoom-DataSources.html | 2 +- docs/api/module-LocusZoom.html | 2 +- ...dule-LocusZoom_Adapters-AssociationLZ.html | 2 +- ...module-LocusZoom_Adapters-BaseAdapter.html | 2 +- ...ule-LocusZoom_Adapters-BaseApiAdapter.html | 2 +- ...le-LocusZoom_Adapters-ConnectorSource.html | 2 +- ...dule-LocusZoom_Adapters-CredibleSetLZ.html | 2 +- ...e-LocusZoom_Adapters-GeneConstraintLZ.html | 2 +- .../api/module-LocusZoom_Adapters-GeneLZ.html | 2 +- ...dule-LocusZoom_Adapters-GwasCatalogLZ.html | 2 +- .../module-LocusZoom_Adapters-IntervalLZ.html | 2 +- .../module-LocusZoom_Adapters-LDServer.html | 2 +- .../module-LocusZoom_Adapters-PheWASLZ.html | 2 +- .../module-LocusZoom_Adapters-RecombLZ.html | 2 +- ...odule-LocusZoom_Adapters-StaticSource.html | 2 +- ...ule-LocusZoom_Adapters-TabixUrlSource.html | 2 +- docs/api/module-LocusZoom_Adapters.html | 2 +- ...le-LocusZoom_DataLayers-BaseDataLayer.html | 2 +- ...LocusZoom_DataLayers-annotation_track.html | 2 +- .../api/module-LocusZoom_DataLayers-arcs.html | 2 +- ...-LocusZoom_DataLayers-category_forest.html | 2 +- ...LocusZoom_DataLayers-category_scatter.html | 2 +- .../module-LocusZoom_DataLayers-forest.html | 2 +- .../module-LocusZoom_DataLayers-genes.html | 2 +- ...ocusZoom_DataLayers-highlight_regions.html | 2 +- ...module-LocusZoom_DataLayers-intervals.html | 2 +- ...sZoom_DataLayers-intervals_enrichment.html | 2 +- ...-LocusZoom_DataLayers-orthogonal_line.html | 2 +- .../module-LocusZoom_DataLayers-scatter.html | 2 +- docs/api/module-LocusZoom_DataLayers.html | 2 +- docs/api/module-LocusZoom_Layouts.html | 48 +++++++++---------- docs/api/module-LocusZoom_MatchFunctions.html | 2 +- docs/api/module-LocusZoom_ScaleFunctions.html | 2 +- ...ule-LocusZoom_TransformationFunctions.html | 2 +- .../module-LocusZoom_Widgets-BaseWidget.html | 2 +- .../api/module-LocusZoom_Widgets-_Button.html | 2 +- ...ule-LocusZoom_Widgets-display_options.html | 2 +- ...module-LocusZoom_Widgets-download_png.html | 2 +- ...module-LocusZoom_Widgets-download_svg.html | 2 +- ...module-LocusZoom_Widgets-filter_field.html | 2 +- docs/api/module-LocusZoom_Widgets-menu.html | 2 +- ...ule-LocusZoom_Widgets-move_panel_down.html | 2 +- ...odule-LocusZoom_Widgets-move_panel_up.html | 2 +- ...module-LocusZoom_Widgets-region_scale.html | 2 +- ...module-LocusZoom_Widgets-remove_panel.html | 2 +- ...dule-LocusZoom_Widgets-resize_to_data.html | 2 +- .../module-LocusZoom_Widgets-set_state.html | 2 +- ...module-LocusZoom_Widgets-shift_region.html | 2 +- docs/api/module-LocusZoom_Widgets-title.html | 2 +- ...odule-LocusZoom_Widgets-toggle_legend.html | 2 +- ...LocusZoom_Widgets-toggle_split_tracks.html | 2 +- .../module-LocusZoom_Widgets-zoom_region.html | 2 +- docs/api/module-LocusZoom_Widgets.html | 2 +- docs/api/module-components_legend-Legend.html | 2 +- docs/api/module-ext_lz-credible-sets.html | 2 +- docs/api/module-ext_lz-dynamic-urls.html | 2 +- docs/api/module-ext_lz-forest-track.html | 2 +- .../module-ext_lz-intervals-enrichment.html | 2 +- docs/api/module-ext_lz-intervals-track.html | 2 +- docs/api/module-ext_lz-tabix-source.html | 2 +- ...ext_lz-widget-addons-covariates_model.html | 2 +- ...dule-ext_lz-widget-addons-data_layers.html | 2 +- docs/api/module-ext_lz-widget-addons.html | 2 +- .../module-registry_base-RegistryBase.html | 2 +- docs/api/registry_adapters.js.html | 2 +- docs/api/registry_base.js.html | 2 +- docs/api/registry_data_layers.js.html | 2 +- docs/api/registry_layouts.js.html | 2 +- docs/api/registry_matchers.js.html | 2 +- docs/api/registry_transforms.js.html | 2 +- docs/api/registry_widgets.js.html | 2 +- esm/version.js | 2 +- package-lock.json | 2 +- package.json | 4 +- 125 files changed, 162 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index 5d4a80a6..126d5c98 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ LocusZoom is a Javascript/d3 embeddable plugin for interactively visualizing sta ![Build Status](https://github.com/statgen/locuszoom/workflows/Unit%20tests/badge.svg?branch=develop) -See [github.com/statgen/locuszoom/wiki](https://github.com/statgen/locuszoom/wiki) for full documentation and API reference. +See [https://statgen.github.io/locuszoom/docs/](https://statgen.github.io/locuszoom/docs/) for full documentation and API reference. To see functional examples of plots generated with LocusZoom.js see [statgen.github.io/locuszoom](http://statgen.github.io/locuszoom/) and [statgen.github.io/locuszoom/#examples](http://statgen.github.io/locuszoom/#examples). @@ -32,7 +32,7 @@ Instead of copying the files to your project, **we recommend using CDN links are ```javascript import LocusZoom from 'locuszoom'; import 'locuszoom/dist/locuszoom.css'; -```` +``` ### 2. Define Data Sources diff --git a/dist/ext/lz-aggregation-tests.min.js b/dist/ext/lz-aggregation-tests.min.js index 0dc43703..7b4c436c 100644 --- a/dist/ext/lz-aggregation-tests.min.js +++ b/dist/ext/lz-aggregation-tests.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzAggregationTests;(()=>{"use strict";var e={d:(t,r)=>{for(var a in r)e.o(r,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:r[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>n});const r=raremetal;function a(e){const t=e.Adapters.get("BaseAdapter"),a=e.Adapters.get("BaseApiAdapter"),n=e.Adapters.get("ConnectorSource");e.Adapters.add("AggregationTestSourceLZ",class extends a{getURL(e,t,r){const a=e.aggregation_tests||{};t.header||(t.header={}),t.header.aggregation_genoset_id=a.genoset_id||null,t.header.aggregation_genoset_build=a.genoset_build||null,t.header.aggregation_phenoset_id=a.phenoset_id||null,t.header.aggregation_pheno=a.pheno||null,t.header.aggregation_calcs=a.calcs||{};const n=a.masks||[];return t.header.aggregation_masks=n,t.header.aggregation_mask_ids=n.map((function(e){return e.name})),this.url}getCacheKey(e,t,r){return this.getURL(e,t,r),JSON.stringify({chrom:e.chr,start:e.start,stop:e.end,genotypeDataset:t.header.aggregation_genoset_id,phenotypeDataset:t.header.aggregation_phenoset_id,phenotype:t.header.aggregation_pheno,samples:"ALL",genomeBuild:t.header.aggregation_genoset_build,masks:t.header.aggregation_mask_ids})}fetchRequest(e,t,r){const a=this.getURL(e,t,r),n=this.getCacheKey(e,t,r);return fetch(a,{method:"POST",body:n,headers:{"Content-Type":"application/json"}}).then((e=>{if(!e.ok)throw new Error(e.statusText);return e.text()})).then((function(e){const t="string"==typeof e?JSON.parse(e):e;if(t.error)throw new Error(t.error);return t}))}annotateData(e,t){if(!e.groups)return{groups:[],variants:[]};e.groups=e.groups.filter((function(e){return"GENE"===e.groupType}));const a=r.helpers.parsePortalJSON(e);let n=a[0];const o=a[1];n=n.byMask(t.header.aggregation_mask_ids);const s=t.header.aggregation_calcs;if(!s||0===Object.keys(s).length)return{variants:[],groups:[],results:[]};return new r.helpers.PortalTestRunner(n,o,s).toJSON().then((function(e){const r=t.header.aggregation_masks.reduce((function(e,t){return e[t.name]=t.description,e}),{});return e.data.groups.forEach((function(e){e.mask_name=r[e.mask]})),e.data})).catch((function(e){throw console.error(e),new Error("Failed to calculate aggregation test results")}))}normalizeResponse(e){return e}combineChainBody(e,t){return t.body}}),e.Adapters.add("AssocFromAggregationLZ",class extends t{constructor(e){if(!e||!e.from)throw"Must specify the name of the source that contains association data";super(...arguments)}parseInit(e){super.parseInit(e),this._from=e.from}getRequest(e,t,r){if(t.discrete&&!t.discrete[this._from])throw`${this.constructor.SOURCE_NAME} cannot be used before loading required data for: ${this._from}`;return Promise.resolve(JSON.parse(JSON.stringify(t.discrete[this._from].variants)))}normalizeResponse(e){const t=new RegExp("(?:chr)?(.+):(\\d+)_?(\\w+)?/?([^_]+)?_?(.*)?");return e.map((e=>{const r=e.variant.match(t);return{variant:e.variant,chromosome:r[1],position:+r[2],ref_allele:r[3],ref_allele_freq:1-e.altFreq,log_pvalue:-Math.log10(e.pvalue)}})).sort(((e,t)=>(e=e.variant)<(t=t.variant)?-1:e>t?1:0))}}),e.Adapters.add("GeneAggregationConnectorLZ",class extends n{_getRequiredSources(){return["gene_ns","aggregation_ns"]}combineChainBody(e,t){const r=this._source_name_mapping.aggregation_ns,a=this._source_name_mapping.gene_ns,n=t.discrete[r],o=t.discrete[a],s={};return n.groups.forEach((function(e){Object.prototype.hasOwnProperty.call(s,e.group)||(s[e.group]=[]),s[e.group].push(e.pvalue)})),o.forEach((function(e){const t=e.gene_name,r=s[t];r&&(e.aggregation_best_pvalue=Math.min.apply(null,r))})),o}})}"undefined"!=typeof LocusZoom&&LocusZoom.use(a);const n=a;LzAggregationTests=t.default})(); //# sourceMappingURL=lz-aggregation-tests.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-credible-sets.min.js b/dist/ext/lz-credible-sets.min.js index 50c3670e..9b7edae7 100644 --- a/dist/ext/lz-credible-sets.min.js +++ b/dist/ext/lz-credible-sets.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzCredibleSets;(()=>{"use strict";var e={d:(a,s)=>{for(var t in s)e.o(s,t)&&!e.o(a,t)&&Object.defineProperty(a,t,{enumerable:!0,get:s[t]})},o:(e,a)=>Object.prototype.hasOwnProperty.call(e,a)},a={};e.d(a,{default:()=>o});const s=gwasCredibleSets;function t(e){const a=e.Adapters.get("BaseAdapter");e.Adapters.add("CredibleSetLZ",class extends a{constructor(e){super(...arguments),this.dependentSource=!0}parseInit(e){if(super.parseInit(...arguments),!this.params.fields||!this.params.fields.log_pvalue)throw new Error(`Source config for ${this.constructor.SOURCE_NAME} must specify how to find 'fields.log_pvalue'`);this.params=Object.assign({threshold:.95,significance_threshold:7.301},this.params)}getCacheKey(e,a,s){return[e.credible_set_threshold||this.params.threshold,e.chr,e.start,e.end].join("_")}fetchRequest(e,a){if(!a.body.length)return Promise.resolve([]);const t=this,o=e.credible_set_threshold||this.params.threshold;if(void 0===a.body[0][t.params.fields.log_pvalue])throw new Error("Credible set source could not locate the required fields from a previous request.");const i=a.body.map((e=>e[t.params.fields.log_pvalue]));if(!i.some((e=>e>=t.params.significance_threshold)))return Promise.resolve([]);const n=[];try{const e=s.scoring.bayesFactors(i),t=s.scoring.normalizeProbabilities(e),r=s.marking.findCredibleSet(t,o),c=s.marking.rescaleCredibleSet(r),l=s.marking.markBoolean(r);for(let e=0;e{{{{namespace[assoc]}}variant|htmlescape}}
P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
{{#if {{namespace[credset]}}posterior_prob}}
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}{{/if}}"});const o=function(){const a=e.Layouts.get("data_layer","association_pvalues",{unnamespaced:!0,id:"associationcredibleset",namespace:{assoc:"assoc",credset:"credset",ld:"ld"},fill_opacity:.7,tooltip:e.Layouts.get("tooltip","association_credible_set",{unnamespaced:!0}),fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"}});return a.color.unshift({field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#FFf000"}}),a}();e.Layouts.add("data_layer","association_credible_set",o);const i={namespace:{assoc:"assoc",credset:"credset"},id:"annotationcredibleset",type:"annotation_track",id_field:"{{namespace[assoc]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#001cee"}},"#00CC00"],fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[credset]}}posterior_prob","{{namespace[credset]}}contrib_fraction","{{namespace[credset]}}is_member"],match:{send:"{{namespace[assoc]}}variant",receive:"{{namespace[assoc]}}variant"},filters:[{field:"{{namespace[credset]}}is_member",operator:"=",value:!0}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:e.Layouts.get("tooltip","annotation_credible_set",{unnamespaced:!0}),tooltip_positioning:"top"};e.Layouts.add("data_layer","annotation_credible_set",i);const n={id:"annotationcredibleset",title:{text:"SNPs in 95% credible set",x:50,style:{"font-size":"14px"}},min_height:50,height:50,margin:{top:25,right:50,bottom:10,left:50},inner_border:"rgb(210, 210, 210)",toolbar:e.Layouts.get("toolbar","standard_panel",{unnamespaced:!0}),axes:{x:{extent:"state",render:!1}},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[e.Layouts.get("data_layer","annotation_credible_set",{unnamespaced:!0})]};e.Layouts.add("panel","annotation_credible_set",n);const r=function(){const a=e.Layouts.get("panel","association",{unnamespaced:!0,id:"associationcrediblesets",namespace:{assoc:"assoc",credset:"credset"},data_layers:[e.Layouts.get("data_layer","significance",{unnamespaced:!0}),e.Layouts.get("data_layer","recomb_rate",{unnamespaced:!0}),e.Layouts.get("data_layer","association_credible_set",{unnamespaced:!0})]});return a.toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationcredibleset",default_config_display_name:"Linkage Disequilibrium (default)",options:[{display_name:"95% credible set (boolean)",display:{point_shape:"circle",point_size:40,color:{field:"{{namespace[credset]}}is_member",scale_function:"if",parameters:{field_value:!0,then:"#00CC00",else:"#CCCCCC"}},legend:[{shape:"circle",color:"#00CC00",size:40,label:"In credible set",class:"lz-data_layer-scatter"},{shape:"circle",color:"#CCCCCC",size:40,label:"Not in credible set",class:"lz-data_layer-scatter"}]}},{display_name:"95% credible set (gradient by contribution)",display:{point_shape:"circle",point_size:40,color:[{field:"{{namespace[credset]}}contrib_fraction",scale_function:"if",parameters:{field_value:0,then:"#777777"}},{scale_function:"interpolate",field:"{{namespace[credset]}}contrib_fraction",parameters:{breaks:[0,1],values:["#fafe87","#9c0000"]}}],legend:[{shape:"circle",color:"#777777",size:40,label:"No contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#fafe87",size:40,label:"Some contribution",class:"lz-data_layer-scatter"},{shape:"circle",color:"#9c0000",size:40,label:"Most contribution",class:"lz-data_layer-scatter"}]}}]}),a}();e.Layouts.add("panel","association_credible_set",r);const c={state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:e.Layouts.get("toolbar","standard_association",{unnamespaced:!0}),panels:[e.Layouts.get("panel","association_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","annotation_credible_set",{unnamespaced:!0}),e.Layouts.get("panel","genes",{unnamespaced:!0})]};e.Layouts.add("plot","association_credible_set",c)}"undefined"!=typeof LocusZoom&&LocusZoom.use(t);const o=t;LzCredibleSets=a.default})(); //# sourceMappingURL=lz-credible-sets.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-dynamic-urls.min.js b/dist/ext/lz-dynamic-urls.min.js index 2ebb54f6..5aad6d90 100644 --- a/dist/ext/lz-dynamic-urls.min.js +++ b/dist/ext/lz-dynamic-urls.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzDynamicUrls;(()=>{"use strict";var t={d:(n,e)=>{for(var o in e)t.o(e,o)&&!t.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:e[o]})},o:(t,n)=>Object.prototype.hasOwnProperty.call(t,n)},n={};function e(t){const n={};if(t){const e=("?"===t[0]?t.substr(1):t).split("&");for(let t=0;ta});const a={paramsFromUrl:s,extractValues:o,plotUpdatesUrl:function(t,n,o){o=o||r;const c=function(c){const r=e(window.location.search),s=o(t,n,c),a=Object.assign({},r,s);if(Object.keys(a).some((function(t){return r[t]!=a[t]}))){const t=(i=a,`?${Object.keys(i).map((function(t){return`${encodeURIComponent(t)}=${encodeURIComponent(i[t])}`})).join("&")}`);Object.keys(r).length?history.pushState({},document.title,t):history.replaceState({},document.title,t)}var i};return t.on("state_changed",c),c},plotWatchesUrl:function(t,n,e){e=e||c;const o=function(o){const c=s(n);e(t,c)};return window.addEventListener("popstate",o),t.trackExternalListener(window,"popstate",o),o}};LzDynamicUrls=n.default})(); //# sourceMappingURL=lz-dynamic-urls.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-forest-track.min.js b/dist/ext/lz-forest-track.min.js index b513dd09..01e5e2a5 100644 --- a/dist/ext/lz-forest-track.min.js +++ b/dist/ext/lz-forest-track.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzForestTrack;(()=>{"use strict";var t={d:(e,a)=>{for(var i in a)t.o(a,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:a[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>s});const a=d3;function i(t){const e=t.DataLayers.get("BaseDataLayer"),i={point_size:40,point_shape:"square",color:"#888888",fill_opacity:1,y_axis:{axis:2},id_field:"id",confidence_intervals:{start_field:"ci_start",end_field:"ci_end"}};class s extends e{constructor(e){e=t.Layouts.merge(e,i),super(...arguments)}_getTooltipPosition(t){const e=this.parent.x_scale(t.data[this.layout.x_axis.field]),a=`y${this.layout.y_axis.axis}_scale`,i=this.parent[a](t.data[this.layout.y_axis.field]),s=this.resolveScalableParameter(this.layout.point_size,t.data),r=Math.sqrt(s/Math.PI);return{x_min:e-r,x_max:e+r,y_min:i-r,y_max:i+r}}render(){const t=this._applyFilters(),e=`y${this.layout.y_axis.axis}_scale`;if(this.layout.confidence_intervals&&this.layout.fields.includes(this.layout.confidence_intervals.start_field)&&this.layout.fields.includes(this.layout.confidence_intervals.end_field)){const a=this.svg.group.selectAll("rect.lz-data_layer-forest.lz-data_layer-forest-ci").data(t,(t=>t[this.layout.id_field])),i=t=>{let a=this.parent.x_scale(t[this.layout.confidence_intervals.start_field]),i=this.parent[e](t[this.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),isNaN(i)&&(i=-1e3),`translate(${a}, ${i})`},s=t=>this.parent.x_scale(t[this.layout.confidence_intervals.end_field])-this.parent.x_scale(t[this.layout.confidence_intervals.start_field]),r=1;a.enter().append("rect").attr("class","lz-data_layer-forest lz-data_layer-forest-ci").attr("id",(t=>`${this.getElementId(t)}_ci`)).attr("transform",`translate(0, ${isNaN(this.parent.layout.height)?0:this.parent.layout.height})`).merge(a).attr("transform",i).attr("width",s).attr("height",r),a.exit().remove()}const i=this.svg.group.selectAll("path.lz-data_layer-forest.lz-data_layer-forest-point").data(t,(t=>t[this.layout.id_field])),s=isNaN(this.parent.layout.height)?0:this.parent.layout.height,r=a.symbol().size(((t,e)=>this.resolveScalableParameter(this.layout.point_size,t,e))).type(((t,e)=>{const i=this.resolveScalableParameter(this.layout.point_shape,t,e),s=`symbol${i.charAt(0).toUpperCase()+i.slice(1)}`;return a[s]||null}));i.enter().append("path").attr("class","lz-data_layer-forest lz-data_layer-forest-point").attr("id",(t=>this.getElementId(t))).attr("transform",`translate(0, ${s})`).merge(i).attr("transform",(t=>{let a=this.parent.x_scale(t[this.layout.x_axis.field]),i=this.parent[e](t[this.layout.y_axis.field]);return isNaN(a)&&(a=-1e3),isNaN(i)&&(i=-1e3),`translate(${a}, ${i})`})).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))).attr("d",r),i.exit().remove(),this.svg.group.on("click.event_emitter",(t=>{this.parent.emit("element_clicked",t,!0)})).call(this.applyBehaviors.bind(this))}}t.DataLayers.add("forest",s),t.DataLayers.add("category_forest",class extends s{_getDataExtent(t,e){const i=this.layout.confidence_intervals;if(i&&this.layout.fields.includes(i.start_field)&&this.layout.fields.includes(i.end_field)){const e=t=>+t[i.start_field],s=t=>+t[i.end_field];return[a.min(t,e),a.max(t,s)]}return super._getDataExtent(t,e)}getTicks(t,e){if(!["x","y1","y2"].includes(t))throw new Error(`Invalid dimension identifier ${t}`);if(t===`y${this.layout.y_axis.axis}`){const t=this.layout.y_axis.category_field;if(!t)throw new Error(`Layout for ${this.layout.id} must specify category_field`);return this.data.map(((e,a)=>({y:a+1,text:e[t]})))}return[]}applyCustomDataMethods(){const t=this.layout.y_axis.field;if(!t)throw new Error(`Layout for ${this.layout.id} must specify yaxis.field`);return this.data=this.data.map(((e,a)=>(e[t]=a+1,e))),this.layout.y_axis.floor=0,this.layout.y_axis.ceiling=this.data.length+1,this}})}"undefined"!=typeof LocusZoom&&LocusZoom.use(i);const s=i;LzForestTrack=e.default})(); //# sourceMappingURL=lz-forest-track.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-intervals-enrichment.min.js b/dist/ext/lz-intervals-enrichment.min.js index 8b6ed23c..2a9e431a 100644 --- a/dist/ext/lz-intervals-enrichment.min.js +++ b/dist/ext/lz-intervals-enrichment.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzIntervalsEnrichment;(()=>{"use strict";var e={d:(a,t)=>{for(var s in t)e.o(t,s)&&!e.o(a,s)&&Object.defineProperty(a,s,{enumerable:!0,get:t[s]})},o:(e,a)=>Object.prototype.hasOwnProperty.call(e,a)},a={};e.d(a,{default:()=>r});const t=Symbol.for("lzXCS"),s=Symbol.for("lzYCS"),n=Symbol.for("lzXCE"),i=Symbol.for("lzYCE");function l(e){const a={start_field:"start",end_field:"end",track_height:10,track_vertical_spacing:3,bounding_box_padding:2,color:"#B8B8B8",fill_opacity:.5,tooltip_positioning:"vertical"},l=e.DataLayers.get("BaseDataLayer");const r={namespace:{intervals:"intervals"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Tissue: {{{{namespace[intervals]}}tissueId|htmlescape}}
\n Range: {{{{namespace[intervals]}}chromosome|htmlescape}}: {{{{namespace[intervals]}}start|htmlescape}}-{{{{namespace[intervals]}}end|htmlescape}}
\n -log10 p: {{{{namespace[intervals]}}pValue|neglog10|scinotation|htmlescape}}
\n Enrichment (n-fold): {{{{namespace[intervals]}}fold|scinotation|htmlescape}}"},c={namespace:{intervals:"intervals"},id:"intervals_enrichment",type:"intervals_enrichment",tag:"intervals_enrichment",match:{send:"{{namespace[intervals]}}tissueId"},fields:["{{namespace[intervals]}}chromosome","{{namespace[intervals]}}start","{{namespace[intervals]}}end","{{namespace[intervals]}}pValue","{{namespace[intervals]}}fold","{{namespace[intervals]}}tissueId","{{namespace[intervals]}}ancestry"],id_field:"{{namespace[intervals]}}start",start_field:"{{namespace[intervals]}}start",end_field:"{{namespace[intervals]}}end",filters:[{field:"{{namespace[intervals]}}ancestry",operator:"=",value:"EU"},{field:"{{namespace[intervals]}}pValue",operator:"<=",value:.05},{field:"{{namespace[intervals]}}fold",operator:">",value:2}],y_axis:{axis:1,field:"{{namespace[intervals]}}fold",floor:0,upper_buffer:.1,min_extent:[0,10]},fill_opacity:.5,color:[{field:"{{namespace[intervals]}}tissueId",scale_function:"stable_choice",parameters:{values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"]}}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:r},o={id:"interval_matches",type:"highlight_regions",namespace:{intervals:"intervals"},match:{receive:"{{namespace[intervals]}}tissueId"},fields:["{{namespace[intervals]}}start","{{namespace[intervals]}}end","{{namespace[intervals]}}tissueId","{{namespace[intervals]}}ancestry","{{namespace[intervals]}}pValue","{{namespace[intervals]}}fold"],start_field:"{{namespace[intervals]}}start",end_field:"{{namespace[intervals]}}end",merge_field:"{{namespace[intervals]}}tissueId",filters:[{field:"lz_is_match",operator:"=",value:!0},{field:"{{namespace[intervals]}}ancestry",operator:"=",value:"EU"},{field:"{{namespace[intervals]}}pValue",operator:"<=",value:.05},{field:"{{namespace[intervals]}}fold",operator:">",value:2}],color:[{field:"{{namespace[intervals]}}tissueId",scale_function:"stable_choice",parameters:{values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"]}}],fill_opacity:.1},d={id:"intervals_enrichment",tag:"intervals_enrichment",min_height:250,height:250,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"enrichment (n-fold)",label_offset:28}},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[c]},p={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:e.Layouts.get("toolbar","standard_association",{unnamespaced:!0}),panels:[function(){const a=e.Layouts.get("panel","association",{unnamespaced:!0});return a.data_layers.unshift(o),a}(),d,e.Layouts.get("panel","genes")]};e.DataLayers.add("intervals_enrichment",class extends l{constructor(t){e.Layouts.merge(t,a),super(...arguments)}getTrackHeight(){return this.layout.track_height+this.layout.track_vertical_spacing+2*this.layout.bounding_box_padding}render(){const e=this._applyFilters(this.data),{start_field:a,end_field:l,bounding_box_padding:r,track_height:c}=this.layout,o=this.layout.y_axis.field,d=`y${this.layout.y_axis.axis}_scale`,{x_scale:p,[d]:m}=this.parent;e.forEach((e=>{e[t]=p(e[a]),e[n]=p(e[l]),e[s]=m(e[o])-this.getTrackHeight()/2+r,e[i]=e[s]+c})),e.sort(((e,a)=>{const s=e[n]-e[t];return a[n]-a[t]-s}));const f=this.svg.group.selectAll("rect").data(e);f.enter().append("rect").merge(f).attr("id",(e=>this.getElementId(e))).attr("x",(e=>e[t])).attr("y",(e=>e[s])).attr("width",(e=>e[n]-e[t])).attr("height",this.layout.track_height).attr("fill",((e,a)=>this.resolveScalableParameter(this.layout.color,e,a))).attr("fill-opacity",((e,a)=>this.resolveScalableParameter(this.layout.fill_opacity,e,a))),f.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this))}_getTooltipPosition(e){return{x_min:e.data[t],x_max:e.data[n],y_min:e.data[s],y_max:e.data[i]}}}),e.Layouts.add("tooltip","intervals_enrichment",r),e.Layouts.add("data_layer","intervals_enrichment",c),e.Layouts.add("panel","intervals_enrichment",d),e.Layouts.add("plot","intervals_association_enrichment",p)}"undefined"!=typeof LocusZoom&&LocusZoom.use(l);const r=l;LzIntervalsEnrichment=a.default})(); //# sourceMappingURL=lz-intervals-enrichment.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-intervals-track.min.js b/dist/ext/lz-intervals-track.min.js index 9143159e..bf224e6a 100644 --- a/dist/ext/lz-intervals-track.min.js +++ b/dist/ext/lz-intervals-track.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzIntervalsTrack;(()=>{"use strict";var t={d:(e,a)=>{for(var s in a)t.o(a,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:a[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>o});const a=d3,s=Symbol.for("lzXCS"),r=Symbol.for("lzYCS"),i=Symbol.for("lzXCE"),l=Symbol.for("lzYCE");function n(t){const e=t.Adapters.get("BaseApiAdapter"),n=t.Widgets.get("_Button"),o=t.Widgets.get("BaseWidget");const c={start_field:"start",end_field:"end",track_label_field:"state_name",track_split_field:"state_id",track_split_order:"DESC",track_split_legend_to_y_axis:2,split_tracks:!0,track_height:15,track_vertical_spacing:3,bounding_box_padding:2,always_hide_legend:!1,color:"#B8B8B8",fill_opacity:1,tooltip_positioning:"vertical"},d=t.DataLayers.get("BaseDataLayer");const g={namespace:{intervals:"intervals"},closable:!1,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"{{{{namespace[intervals]}}state_name|htmlescape}}
{{{{namespace[intervals]}}start|htmlescape}}-{{{{namespace[intervals]}}end|htmlescape}}"},h={namespace:{intervals:"intervals"},id:"intervals",type:"intervals",tag:"intervals",fields:["{{namespace[intervals]}}start","{{namespace[intervals]}}end","{{namespace[intervals]}}state_id","{{namespace[intervals]}}state_name","{{namespace[intervals]}}itemRgb"],id_field:"{{namespace[intervals]}}start",start_field:"{{namespace[intervals]}}start",end_field:"{{namespace[intervals]}}end",track_split_field:"{{namespace[intervals]}}state_name",track_label_field:"{{namespace[intervals]}}state_name",split_tracks:!1,always_hide_legend:!0,color:[{field:"{{namespace[intervals]}}itemRgb",scale_function:"to_rgb"},{field:"{{namespace[intervals]}}state_name",scale_function:"categorical_bin",parameters:{categories:[],values:[],null_value:"#B8B8B8"}}],legend:[],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}],onshiftclick:[{action:"toggle",status:"selected"}]},tooltip:g},_={id:"intervals",tag:"intervals",min_height:50,height:50,margin:{top:25,right:150,bottom:5,left:50},toolbar:function(){const e=t.Layouts.get("toolbar","standard_panel",{unnamespaced:!0});return e.widgets.push({type:"toggle_split_tracks",data_layer_id:"intervals",position:"right"}),e}(),axes:{},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},legend:{hidden:!0,orientation:"horizontal",origin:{x:50,y:0},pad_from_bottom:5},data_layers:[h]},u={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:t.Layouts.get("toolbar","standard_association",{unnamespaced:!0}),panels:[t.Layouts.get("panel","association"),t.Layouts.merge({unnamespaced:!0,min_height:120,height:120},_),t.Layouts.get("panel","genes")]};t.Adapters.add("IntervalLZ",class extends e{getURL(t,e,a){const s=`?filter=id in ${e.header.bedtracksource||this.params.source} and chromosome eq '${t.chr}' and start le ${t.end} and end ge ${t.start}`;return`${this.url}${s}`}}),t.DataLayers.add("intervals",class extends d{constructor(e){t.Layouts.merge(e,c),super(...arguments),this._previous_categories=[],this._categories=[]}initialize(){super.initialize(),this._statusnodes_group=this.svg.group.append("g").attr("class","lz-data-layer-intervals lz-data-layer-intervals-statusnode"),this._datanodes_group=this.svg.group.append("g").attr("class","lz-data_layer-intervals")}_arrangeTrackSplit(t){const{track_split_field:e}=this.layout,a={};return t.forEach((t=>{const s=t[e];Object.prototype.hasOwnProperty.call(a,s)||(a[s]=[]),a[s].push(t)})),a}_arrangeTracksLinear(t,e=!0){if(e)return[t];const{start_field:a,end_field:s}=this.layout,r=[[]];return t.forEach(((t,e)=>{for(let e=0;e{d[t].forEach((t=>{t[s]=e(t[a]),t[i]=e(t[n]),t[r]=g*this.getTrackHeight()+o,t[l]=t[r]+c,t.track=g}))})),[g,Object.values(d).reduce(((t,e)=>t.concat(e)),[])]}getElementStatusNodeId(t){if(this.layout.split_tracks){const e="object"==typeof t?t.track:t;return`${this.getBaseId()}-statusnode-${e}`.replace(/[^\w]/g,"_")}return null}getTrackHeight(){return this.layout.track_height+this.layout.track_vertical_spacing+2*this.layout.bounding_box_padding}_applyLayoutOptions(){const t=this,e=this._base_layout,a=this.layout,s=e.color.find((function(t){return t.scale_function&&"categorical_bin"===t.scale_function})),r=a.color.find((function(t){return t.scale_function&&"categorical_bin"===t.scale_function}));if(!s)throw new Error("Interval tracks must define a `categorical_bin` color scale");const i=s.parameters.categories.length&&s.parameters.values.length,l=e.legend&&e.legend.length;if(!!i^!!l)throw new Error("To use a manually specified color scheme, both color and legend options must be set.");const n=e.color.find((function(t){return t.scale_function&&"to_rgb"===t.scale_function})),o=n&&n.field,c=this._generateCategoriesFromData(this.data,o);if(!i&&!l){const e=this._makeColorScheme(c);r.parameters.categories=c.map((function(t){return t[0]})),r.parameters.values=e,this.layout.legend=c.map((function(e,a){const s=e[0],i={shape:"rect",width:9,label:e[1],color:r.parameters.values[a]};return i[t.layout.track_split_field]=s,i}))}}render(){this._applyLayoutOptions(),this._previous_categories=this._categories;const[t,e]=this._assignTracks(this.data);this._categories=t;if(!t.every(((t,e)=>t===this._previous_categories[e])))return void this.updateSplitTrackAxis(t);const l=this._applyFilters(e);this._statusnodes_group.selectAll("rect").remove();const n=this._statusnodes_group.selectAll("rect").data(a.range(t.length));if(this.layout.split_tracks){const t=this.getTrackHeight();n.enter().append("rect").attr("class","lz-data_layer-intervals lz-data_layer-intervals-statusnode lz-data_layer-intervals-shared").attr("rx",this.layout.bounding_box_padding).attr("ry",this.layout.bounding_box_padding).merge(n).attr("id",(t=>this.getElementStatusNodeId(t))).attr("x",0).attr("y",(e=>e*t)).attr("width",this.parent.layout.cliparea.width).attr("height",t-this.layout.track_vertical_spacing)}n.exit().remove();const o=this._datanodes_group.selectAll("rect").data(l,(t=>t[this.layout.id_field]));o.enter().append("rect").merge(o).attr("id",(t=>this.getElementId(t))).attr("x",(t=>t[s])).attr("y",(t=>t[r])).attr("width",(t=>t[i]-t[s])).attr("height",this.layout.track_height).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))),o.exit().remove(),this._datanodes_group.call(this.applyBehaviors.bind(this)),this.parent&&this.parent.legend&&this.parent.legend.render()}_getTooltipPosition(t){return{x_min:t.data[s],x_max:t.data[i],y_min:t.data[r],y_max:t.data[l]}}updateSplitTrackAxis(t){const e=!!this.layout.track_split_legend_to_y_axis&&`y${this.layout.track_split_legend_to_y_axis}`;if(this.layout.split_tracks){const a=+t.length||0,s=+this.layout.track_height||0,r=2*(+this.layout.bounding_box_padding||0)+(+this.layout.track_vertical_spacing||0),i=a*s+(a-1)*r;this.parent.scaleHeightToData(i),e&&this.parent.legend&&(this.parent.legend.hide(),this.parent.layout.axes[e]={render:!0,ticks:[],range:{start:i-this.layout.track_height/2,end:this.layout.track_height/2}},this.layout.legend.forEach((s=>{const r=s[this.layout.track_split_field];let i=t.findIndex((t=>t===r));-1!==i&&("DESC"===this.layout.track_split_order&&(i=Math.abs(i-a-1)),this.parent.layout.axes[e].ticks.push({y:i-1,text:s.label}))})),this.layout.y_axis={axis:this.layout.track_split_legend_to_y_axis,floor:1,ceiling:a}),this.parent_plot.positionPanels()}else e&&this.parent.legend&&(this.layout.always_hide_legend||this.parent.legend.show(),this.parent.layout.axes[e]={render:!1},this.parent.render());return this}toggleSplitTracks(){return this.layout.split_tracks=!this.layout.split_tracks,this.parent.legend&&!this.layout.always_hide_legend&&(this.parent.layout.margin.bottom=5+(this.layout.split_tracks?0:this.parent.legend.layout.height+5)),this.render(),this}_makeColorScheme(t){if(t.find((t=>t[2])))return t.map((t=>t[2]));const e=t.length;return e<=15?["rgb(212,212,212)","rgb(192,192,192)","rgb(128,128,128)","rgb(189,183,107)","rgb(233,150,122)","rgb(205,92,92)","rgb(138,145,208)","rgb(102,205,170)","rgb(255,255,0)","rgb(194,225,5)","rgb(0,100,0)","rgb(0,128,0)","rgb(50,205,50)","rgb(255,69,0)","rgb(255,0,0)"]:e<=18?["rgb(212,212,212)","rgb(192,192,192)","rgb(128,128,128)","rgb(189,183,107)","rgb(205,92,92)","rgb(138,145,208)","rgb(102,205,170)","rgb(255,255,0)","rgb(255,195,77)","rgb(255,195,77)","rgb(194,225,5)","rgb(194,225,5)","rgb(0,100,0)","rgb(0,128,0)","rgb(255,69,0)","rgb(255,69,0)","rgb(255,69,0)","rgb(255,0,0)"]:["rgb(212,212,212)","rgb(128,128,128)","rgb(112,48,160)","rgb(230,184,183)","rgb(138,145,208)","rgb(102,205,170)","rgb(255,255,102)","rgb(255,255,0)","rgb(255,255,0)","rgb(255,255,0)","rgb(255,195,77)","rgb(255,195,77)","rgb(255,195,77)","rgb(194,225,5)","rgb(194,225,5)","rgb(194,225,5)","rgb(194,225,5)","rgb(0,150,0)","rgb(0,128,0)","rgb(0,128,0)","rgb(0,128,0)","rgb(255,69,0)","rgb(255,69,0)","rgb(255,69,0)","rgb(255,0,0)"]}_generateCategoriesFromData(t,e){const a=this,s=this._base_layout.legend;if(s&&s.length)return s.map((t=>[t[this.layout.track_split_field],t.label,t.color]));const r={},i=[];return t.forEach((t=>{const s=t[a.layout.track_split_field];Object.prototype.hasOwnProperty.call(r,s)||(r[s]=null,i.push([s,t[this.layout.track_label_field],t[e]]))})),i}}),t.Layouts.add("tooltip","standard_intervals",g),t.Layouts.add("data_layer","intervals",h),t.Layouts.add("panel","intervals",_),t.Layouts.add("plot","interval_association",u),t.ScaleFunctions.add("to_rgb",(function(t,e){return e?`rgb(${e})`:null})),t.Widgets.add("toggle_split_tracks",class extends o{constructor(t){if(super(...arguments),t.data_layer_id||(t.data_layer_id="intervals"),!this.parent_panel.data_layers[t.data_layer_id])throw new Error("Toggle split tracks widget specifies an invalid data layer ID")}update(){const t=this.parent_panel.data_layers[this.layout.data_layer_id],e=t.layout.split_tracks?"Merge Tracks":"Split Tracks";return this.button?(this.button.setHtml(e),this.button.show(),this.parent.position(),this):(this.button=new n(this).setColor(this.layout.color).setHtml(e).setTitle("Toggle whether tracks are split apart or merged together").setOnclick((()=>{t.toggleSplitTracks(),this.scale_timeout&&clearTimeout(this.scale_timeout),this.scale_timeout=setTimeout((()=>{this.parent_panel.scaleHeightToData(),this.parent_plot.positionPanels()}),0),this.update()})),this.update())}})}"undefined"!=typeof LocusZoom&&LocusZoom.use(n);const o=n;LzIntervalsTrack=e.default})(); //# sourceMappingURL=lz-intervals-track.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-tabix-source.min.js b/dist/ext/lz-tabix-source.min.js index e32229fb..87d428b1 100644 --- a/dist/ext/lz-tabix-source.min.js +++ b/dist/ext/lz-tabix-source.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzTabix;(()=>{"use strict";var e={n:r=>{var t=r&&r.__esModule?()=>r.default:()=>r;return e.d(t,{a:t}),t},d:(r,t)=>{for(var a in t)e.o(t,a)&&!e.o(r,a)&&Object.defineProperty(r,a,{enumerable:!0,get:t[a]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)},r={};e.d(r,{default:()=>s});const t=tabix;var a=e.n(t);function i(e){const r=e.Adapters.get("BaseAdapter");e.Adapters.add("TabixUrlSource",class extends r{parseInit(e){if(!e.parser_func||!e.url_data)throw new Error("Tabix source is missing required configuration options");this.parser=e.parser_func,this.url_data=e.url_data,this.url_tbi=e.url_tbi||`${this.url_data}.tbi`;const r=e.params||{};if(this.params=r,this._overfetch=r.overfetch||0,this._overfetch<0||this._overfetch>1)throw new Error("Overfetch must be specified as a fraction (0-1) of the requested region size");this._reader_promise=a().urlReader(this.url_data,this.url_tbi).catch((function(){throw new Error("Failed to create a tabix reader from the provided URL")}))}fetchRequest(e){return new Promise(((r,t)=>{const a=e.start,i=e.end,s=this._overfetch*(i-a),o=e.start-s,n=e.end+s;this._reader_promise.then((a=>{a.fetch(e.chr,o,n,(function(e,a){a&&t(new Error("Could not read requested region. This may indicate an error with the .tbi index.")),r(e)}))}))}))}normalizeResponse(e){return e.map(this.parser)}})}"undefined"!=typeof LocusZoom&&LocusZoom.use(i);const s=i;LzTabix=r.default})(); //# sourceMappingURL=lz-tabix-source.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-widget-addons.min.js b/dist/ext/lz-widget-addons.min.js index 0f667cc3..c5b86e27 100644 --- a/dist/ext/lz-widget-addons.min.js +++ b/dist/ext/lz-widget-addons.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ +/*! Locuszoom 0.13.4 */ var LzWidgetAddons;(()=>{"use strict";var t={d:(e,o)=>{for(var a in o)t.o(o,a)&&!t.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:o[a]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>i});d3;Math.sqrt(3);function o(t){return JSON.parse(JSON.stringify(t))}const a=["highlight","select","fade","hide"],l=["highlighted","selected","faded","hidden"],s=["unhighlight","deselect","unfade","show"];function n(t){const e=t.Widgets.get("_Button"),n=t.Widgets.get("BaseWidget");const i=function(){const e=t.Layouts.get("tooltip","standard_association",{unnamespaced:!0});return e.html+='Condition on Variant
',e}(),r=function(){const e=t.Layouts.get("toolbar","standard_association",{unnamespaced:!0});return e.widgets.push({type:"covariates_model",button_html:"Model",button_title:"Show and edit covariates currently in model",position:"left"}),e}();t.Widgets.add("covariates_model",class extends n{initialize(){this.parent_plot.state.model=this.parent_plot.state.model||{},this.parent_plot.state.model.covariates=this.parent_plot.state.model.covariates||[],this.parent_plot.CovariatesModel={button:this,add:t=>{const e=this.parent_plot,a=o(t);"object"==typeof t&&"string"!=typeof a.html&&(a.html="function"==typeof t.toHTML?t.toHTML():t.toString());for(let t=0;t{const e=this.parent_plot;if(void 0===e.state.model.covariates[t])throw new Error(`Unable to remove model covariate, invalid index: ${t.toString()}`);return e.state.model.covariates.splice(t,1),e.applyState(),e.CovariatesModel.updateWidget(),e},removeAll:()=>{const t=this.parent_plot;return t.state.model.covariates=[],t.applyState(),t.CovariatesModel.updateWidget(),t},updateWidget:()=>{this.button.update(),this.button.menu.update()}}}update(){return this.button||(this.button=new e(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{const t=this.button.menu.inner_selector;if(t.html(""),void 0!==this.parent_plot.state.model.html&&t.append("div").html(this.parent_plot.state.model.html),this.parent_plot.state.model.covariates.length){t.append("h5").html(`Model Covariates (${this.parent_plot.state.model.covariates.length})`);const e=t.append("table");this.parent_plot.state.model.covariates.forEach(((t,o)=>{const a="object"==typeof t&&"string"==typeof t.html?t.html:t.toString(),l=e.append("tr");l.append("td").append("button").attr("class",`lz-toolbar-button lz-toolbar-button-${this.layout.color}`).style("margin-left","0em").on("click",(()=>this.parent_plot.CovariatesModel.removeByIdx(o))).html("×"),l.append("td").html(a)})),t.append("button").attr("class",`lz-toolbar-button lz-toolbar-button-${this.layout.color}`).style("margin-left","4px").html("× Remove All Covariates").on("click",(()=>this.parent_plot.CovariatesModel.removeAll()))}else t.append("i").html("no covariates in model")})),this.button.preUpdate=()=>{let t="Model";const e=this.parent_plot.state.model.covariates.length;if(e){t+=` (${e} ${e>1?"covariates":"covariate"})`}this.button.setHtml(t).disable(!1)},this.button.show()),this}}),t.Widgets.add("data_layers",class extends n{update(){return"string"!=typeof this.layout.button_html&&(this.layout.button_html="Data Layers"),"string"!=typeof this.layout.button_title&&(this.layout.button_title="Manipulate Data Layers (sort, dim, show/hide, etc.)"),this.button||(this.button=new e(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{this.button.menu.inner_selector.html("");const t=this.button.menu.inner_selector.append("table");return this.parent_panel.data_layer_ids_by_z_index.slice().reverse().forEach(((e,o)=>{const n=this.parent_panel.data_layers[e],i="string"!=typeof n.layout.name?n.id:n.layout.name,r=t.append("tr");r.append("td").html(i),this.layout.statuses.forEach((t=>{const e=l.indexOf(t),o=a[e];let i,d,u;n.global_statuses[t]?(i=s[e],d=`un${o}AllElements`,u="-highlighted"):(i=a[e],d=`${o}AllElements`,u=""),r.append("td").append("a").attr("class",`lz-toolbar-button lz-toolbar-button-${this.layout.color}${u}`).style("margin-left","0em").on("click",(()=>{n[d](),this.button.menu.populate()})).html(i)}));const d=0===o,u=o===this.parent_panel.data_layer_ids_by_z_index.length-1,p=r.append("td");p.append("a").attr("class",`lz-toolbar-button lz-toolbar-button-group-start lz-toolbar-button-${this.layout.color}${u?"-disabled":""}`).style("margin-left","0em").on("click",(()=>{n.moveBack(),this.button.menu.populate()})).html("▾").attr("title","Move layer down (further back)"),p.append("a").attr("class",`lz-toolbar-button lz-toolbar-button-group-middle lz-toolbar-button-${this.layout.color}${d?"-disabled":""}`).style("margin-left","0em").on("click",(()=>{n.moveForward(),this.button.menu.populate()})).html("▴").attr("title","Move layer up (further front)"),p.append("a").attr("class","lz-toolbar-button lz-toolbar-button-group-end lz-toolbar-button-red").style("margin-left","0em").on("click",(()=>(confirm(`Are you sure you want to remove the ${i} layer? This cannot be undone.`)&&n.parent.removeDataLayer(e),this.button.menu.populate()))).html("×").attr("title","Remove layer")})),this})),this.button.show()),this}}),t.Layouts.add("tooltip","covariates_model_association",i),t.Layouts.add("toolbar","covariates_model_plot",r)}"undefined"!=typeof LocusZoom&&LocusZoom.use(n);const i=n;LzWidgetAddons=e.default})(); //# sourceMappingURL=lz-widget-addons.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-widget-addons.min.js.map b/dist/ext/lz-widget-addons.min.js.map index 45ee3fb4..1e7b9d05 100644 --- a/dist/ext/lz-widget-addons.min.js.map +++ b/dist/ext/lz-widget-addons.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/external \"d3\"","webpack://[name]/./esm/helpers/layouts.js","webpack://[name]/./esm/ext/lz-widget-addons.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","Math","sqrt","deepCopy","item","JSON","parse","stringify","STATUS_VERBS","STATUS_ADJECTIVES","STATUS_ANTIVERBS","install","LocusZoom","_Button","Widgets","_BaseWidget","covariates_model_tooltip","covariates_model_association","Layouts","unnamespaced","html","covariates_model_plot","covariates_model_plot_toolbar","widgets","push","type","button_html","button_title","position","add","this","parent_plot","state","model","covariates","CovariatesModel","button","element_reference","plot","element","toHTML","toString","i","length","applyState","updateWidget","removeByIdx","idx","Error","splice","removeAll","update","menu","setColor","layout","color","setHtml","setTitle","setOnclick","populate","setPopulate","selector","inner_selector","append","table","forEach","covariate","row","attr","style","on","preUpdate","count","disable","show","parent_panel","data_layer_ids_by_z_index","slice","reverse","id","data_layer","data_layers","name","statuses","status_adj","status_idx","indexOf","status_verb","onclick","highlight","global_statuses","at_top","at_bottom","td","moveBack","moveForward","confirm","parent","removeDataLayer","use"],"mappings":";sCACA,IAAIA,EAAsB,CCA1B,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3E,EAAwB,CAACM,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,I,4BCA7CI,GCSvBC,KAAKC,KAAK,GA8GxB,SAASC,EAASC,GACd,OAAOC,KAAKC,MAAMD,KAAKE,UAAUH,ICrFrC,MAAMI,EAAe,CAAC,YAAa,SAAU,OAAQ,QAC/CC,EAAoB,CAAC,cAAe,WAAY,QAAS,UACzDC,EAAm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/CF,EAAWiB,OAAOC,gBAAgBnB,GAE/BjD,KAAKM,OAAOgB,KAAKO,cAE3BvC,KAAK,KACLgD,KAAK,QAAS,mBAEhBtC,QAGXA,KAAKM,OAAOsC,QA9ED5C,QAwGnBlB,EAAUM,QAAQW,IAAI,UAAW,+BAAgCb,GACjEJ,EAAUM,QAAQW,IAAI,UAAW,wBAAyBR,GAGrC,oBAAdT,WAGPA,UAAUuF,IAAIxF,GAIlB,U","file":"ext/lz-widget-addons.min.js","sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","const __WEBPACK_NAMESPACE_OBJECT__ = d3;","/**\n * Utilities for modifying or working with layout objects\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport {mutate, query} from './jsonpath';\n\nconst sqrt3 = Math.sqrt(3);\n// D3 v5 does not provide a triangle down symbol shape, but it is very useful for showing direction of effect.\n// Modified from https://github.com/d3/d3-shape/blob/master/src/symbol/triangle.js\nconst triangledown = {\n draw(context, size) {\n const y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, -y * 2);\n context.lineTo(-sqrt3 * y, y);\n context.lineTo(sqrt3 * y, y);\n context.closePath();\n },\n};\n\n/**\n * Apply namespaces to layout, recursively\n * @private\n */\nfunction applyNamespaces(element, namespace, default_namespace) {\n if (namespace) {\n if (typeof namespace == 'string') {\n namespace = { default: namespace };\n }\n } else {\n namespace = { default: '' };\n }\n if (typeof element == 'string') {\n const re = /\\{\\{namespace(\\[[A-Za-z_0-9]+\\]|)\\}\\}/g;\n let match, base, key, resolved_namespace;\n const replace = [];\n while ((match = re.exec(element)) !== null) {\n base = match[0];\n key = match[1].length ? match[1].replace(/(\\[|\\])/g, '') : null;\n resolved_namespace = default_namespace;\n if (namespace != null && typeof namespace == 'object' && typeof namespace[key] != 'undefined') {\n resolved_namespace = namespace[key] + (namespace[key].length ? ':' : '');\n }\n replace.push({ base: base, namespace: resolved_namespace });\n }\n for (let r in replace) {\n element = element.replace(replace[r].base, replace[r].namespace);\n }\n } else if (typeof element == 'object' && element != null) {\n if (typeof element.namespace != 'undefined') {\n const merge_namespace = (typeof element.namespace == 'string') ? { default: element.namespace } : element.namespace;\n namespace = merge(namespace, merge_namespace);\n }\n let namespaced_element, namespaced_property;\n for (let property in element) {\n if (property === 'namespace') {\n continue;\n }\n namespaced_element = applyNamespaces(element[property], namespace, default_namespace);\n namespaced_property = applyNamespaces(property, namespace, default_namespace);\n if (property !== namespaced_property) {\n delete element[property];\n }\n element[namespaced_property] = namespaced_element;\n }\n }\n return element;\n}\n\n/**\n * A helper method used for merging two objects. If a key is present in both, takes the value from the first object.\n * Values from `default_layout` will be cleanly copied over, ensuring no references or shared state.\n *\n * Frequently used for preparing custom layouts. Both objects should be JSON-serializable.\n *\n * @alias LayoutRegistry.merge\n * @param {object} custom_layout An object containing configuration parameters that override or add to defaults\n * @param {object} default_layout An object containing default settings.\n * @returns {object} The custom layout is modified in place and also returned from this method.\n */\nfunction merge(custom_layout, default_layout) {\n if (typeof custom_layout !== 'object' || typeof default_layout !== 'object') {\n throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof custom_layout}, ${typeof default_layout} given`);\n }\n for (let property in default_layout) {\n if (!Object.prototype.hasOwnProperty.call(default_layout, property)) {\n continue;\n }\n // Get types for comparison. Treat nulls in the custom layout as undefined for simplicity.\n // (javascript treats nulls as \"object\" when we just want to overwrite them as if they're undefined)\n // Also separate arrays from objects as a discrete type.\n let custom_type = custom_layout[property] === null ? 'undefined' : typeof custom_layout[property];\n let default_type = typeof default_layout[property];\n if (custom_type === 'object' && Array.isArray(custom_layout[property])) {\n custom_type = 'array';\n }\n if (default_type === 'object' && Array.isArray(default_layout[property])) {\n default_type = 'array';\n }\n // Unsupported property types: throw an exception\n if (custom_type === 'function' || default_type === 'function') {\n throw new Error('LocusZoom.Layouts.merge encountered an unsupported property type');\n }\n // Undefined custom value: pull the default value\n if (custom_type === 'undefined') {\n custom_layout[property] = deepCopy(default_layout[property]);\n continue;\n }\n // Both values are objects: merge recursively\n if (custom_type === 'object' && default_type === 'object') {\n custom_layout[property] = merge(custom_layout[property], default_layout[property]);\n continue;\n }\n }\n return custom_layout;\n}\n\nfunction deepCopy(item) {\n return JSON.parse(JSON.stringify(item));\n}\n\n/**\n * Convert name to symbol\n * Layout objects accept symbol names as strings (circle, triangle, etc). Convert to symbol objects.\n * @return {object|null} An object that implements a draw method (eg d3-shape symbols or extra LZ items)\n */\nfunction nameToSymbol(shape) {\n if (!shape) {\n return null;\n }\n if (shape === 'triangledown') {\n // D3 does not provide this symbol natively\n return triangledown;\n }\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const factory_name = `symbol${shape.charAt(0).toUpperCase() + shape.slice(1)}`;\n return d3[factory_name] || null;\n}\n\n/**\n * A utility helper for customizing one part of a pre-made layout. Whenever a primitive value is found (eg string),\n * replaces *exact match*\n *\n * This method works by comparing whether strings are a match. As a result, the \"old\" and \"new\" names must match\n * whatever namespacing is used in the input layout.\n * Note: this utility *can* replace values with filters, but will not do so by default.\n *\n * @alias LayoutRegistry.renameField\n *\n * @param {object} layout The layout object to be transformed.\n * @param {string} old_name The old field name that will be replaced\n * @param {string} new_name The new field name that will be substituted in\n * @param {boolean} [warn_transforms=true] Sometimes, a field name is used with transforms appended, eg `label|htmlescape`.\n * In some cases a rename could change the meaning of the field, and by default this method will print a warning to\n * the console, encouraging the developer to check the relevant usages. This warning can be silenced via an optional function argument.\n */\nfunction renameField(layout, old_name, new_name, warn_transforms = true) {\n const this_type = typeof layout;\n // Handle nested types by recursion (in which case, `layout` may be something other than an object)\n if (Array.isArray(layout)) {\n return layout.map((item) => renameField(item, old_name, new_name, warn_transforms));\n } else if (this_type === 'object' && layout !== null) {\n return Object.keys(layout).reduce(\n (acc, key) => {\n acc[key] = renameField(layout[key], old_name, new_name, warn_transforms);\n return acc;\n }, {}\n );\n } else if (this_type !== 'string') {\n // Field names are always strings. If the value isn't a string, don't even try to change it.\n return layout;\n } else {\n // If we encounter a field we are trying to rename, then do so!\n // Rules:\n // 1. Try to avoid renaming part of a field, by checking token boundaries (field1 should not rename field1_displayvalue)\n // 2. Warn the user if filter functions are being used with the specified field, so they can audit for changes in meaning\n const escaped = old_name.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n if (warn_transforms) {\n // Warn the user that they might be renaming, eg, `pvalue|neg_log` to `log_pvalue|neg_log`. Let them decide\n // whether the new field name has a meaning that is compatible with the specified transforms.\n const filter_regex = new RegExp(`${escaped}\\\\|\\\\w+`, 'g');\n const filter_matches = (layout.match(filter_regex) || []);\n filter_matches.forEach((match_val) => console.warn(`renameFields is renaming a field that uses transform functions: was '${match_val}' . Verify that these transforms are still appropriate.`));\n }\n\n // Find and replace any substring, so long as it is at the end of a valid token\n const regex = new RegExp(`${escaped}(?!\\\\w+)`, 'g');\n return layout.replace(regex, new_name);\n }\n}\n\n/**\n * Modify any and all attributes at the specified path in the object\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which field(s) to change.\n * The callback will be applied to ALL matching selectors\n * (see Interactivity guide for syntax and limitations)\n * @param {*|function} value_or_callable The new value, or a function that receives the old value and returns a new one\n * @alias LayoutRegistry.mutate_attrs\n */\nfunction mutate_attrs(layout, selector, value_or_callable) {\n return mutate(\n layout,\n selector,\n value_or_callable\n );\n}\n\n/**\n * Query any and all attributes at the specified path in the object.\n * This is mostly only useful for debugging, to verify that a particular selector matches the intended field.\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which values to return. (see Interactivity guide for limits)\n * @alias LayoutRegistry.query_attrs\n */\nfunction query_attrs(layout, selector) {\n return query(layout, selector);\n}\n\nexport { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, renameField };\n","/**\n * Optional LocusZoom extension: must be included separately, and after LocusZoom has been loaded\n *\n * This contains (reusable) code to power some (rarely used) demo features:\n * - The \"covariates model\" demo, in which an LZ toolbar widget is populated\n * with information by selecting points on the plot (see \"covariates model\" demo)\n * - The \"data layers\" button, which allows fine control over multiple data layers shown in the same panel\n * (show/hide, fade, change order, etc). This is powerful, but rarely used because showing many datasets in a small\n * space makes data hard to see. (see \"multiple phenotypes layered\" demo)\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - LocusZoom\n *\n * To use in an environment without special JS build tooling, simply load the extension file as JS from a CDN (after any dependencies):\n *\n * ```javascript\n * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```javascript\n * import LocusZoom from 'locuszoom';\n * import WidgetAddons from 'locuszoom/esm/ext/lz-widget-addons';\n * LocusZoom.use(WidgetAddons);\n * ```\n *\n * Then use the features made available by this extension. (see demos and documentation for guidance)\n *\n * @module\n */\nimport {deepCopy} from '../helpers/layouts';\n\n// In order to work in a UMD context, this module imports the top-level LocusZoom symbol\n\nconst STATUS_VERBS = ['highlight', 'select', 'fade', 'hide'];\nconst STATUS_ADJECTIVES = ['highlighted', 'selected', 'faded', 'hidden'];\nconst STATUS_ANTIVERBS = ['unhighlight', 'deselect', 'unfade', 'show'];\n\n\n// LocusZoom plugins work by exporting a function that receives the `LocusZoom` object\n// This allows them to work in many contexts (including script tags and ES6 imports)\nfunction install(LocusZoom) {\n const _Button = LocusZoom.Widgets.get('_Button');\n const _BaseWidget = LocusZoom.Widgets.get('BaseWidget');\n\n\n /**\n * Special button/menu to allow model building by tracking individual covariants. Will track a list of covariate\n * objects and store them in the special `model.covariates` field of plot `state`.\n *\n * This is a prototype widget for building a conditional analysis model, but it performs no calculation\n * functionality beyond building a list of items.\n * @alias module:ext/lz-widget-addons~covariates_model\n * @see module:LocusZoom_Widgets~BaseWidget\n * @param {object} layout\n * @param {string} layout.button_html The HTML to render inside the button\n * @param {string} layout.button_title Text to display as a tooltip when hovering over the button\n */\n class CovariatesModel extends _BaseWidget {\n initialize() {\n // Initialize state.model.covariates\n this.parent_plot.state.model = this.parent_plot.state.model || {};\n this.parent_plot.state.model.covariates = this.parent_plot.state.model.covariates || [];\n // Create an object at the plot level for easy access to interface methods in custom client-side JS\n /**\n * When a covariates model toolbar element is present, create (one) object at the plot level that exposes\n * widget data and state for custom interactions with other plot elements.\n */\n this.parent_plot.CovariatesModel = {\n /** @member {Button} */\n button: this,\n /**\n * Add an element to the model and show a representation of it in the toolbar widget menu. If the\n * element is already part of the model, do nothing (to avoid adding duplicates).\n * When plot state is changed, this will automatically trigger requests for new data accordingly.\n * @param {string|object} element_reference Can be any value that can be put through JSON.stringify()\n * to create a serialized representation of itself.\n */\n add: (element_reference) => {\n const plot = this.parent_plot;\n const element = deepCopy(element_reference);\n if (typeof element_reference == 'object' && typeof element.html != 'string') {\n element.html = ( (typeof element_reference.toHTML == 'function') ? element_reference.toHTML() : element_reference.toString());\n }\n // Check if the element is already in the model covariates array and return if it is.\n for (let i = 0; i < plot.state.model.covariates.length; i++) {\n if (JSON.stringify(plot.state.model.covariates[i]) === JSON.stringify(element)) {\n return plot;\n }\n }\n plot.state.model.covariates.push(element);\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Remove an element from `state.model.covariates` (and from the toolbar widget menu's\n * representation of the state model). When plot state is changed, this will automatically trigger\n * requests for new data accordingly.\n * @param {number} idx Array index of the element, in the `state.model.covariates array`.\n */\n removeByIdx: (idx) => {\n const plot = this.parent_plot;\n if (typeof plot.state.model.covariates[idx] == 'undefined') {\n throw new Error(`Unable to remove model covariate, invalid index: ${idx.toString()}`);\n }\n plot.state.model.covariates.splice(idx, 1);\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Empty the `state.model.covariates` array (and toolbar widget menu representation thereof) of all\n * elements. When plot state is changed, this will automatically trigger requests for new data accordingly\n */\n removeAll: () => {\n const plot = this.parent_plot;\n plot.state.model.covariates = [];\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Manually trigger the update methods on the toolbar widget's button and menu elements to force\n * display of most up-to-date content. Can be used to force the toolbar to reflect changes made, eg if\n * modifying `state.model.covariates` directly instead of via `plot.CovariatesModel`\n */\n updateWidget: () => {\n this.button.update();\n this.button.menu.update();\n },\n };\n }\n\n update() {\n\n if (this.button) {\n return this;\n }\n\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n\n this.button.menu.setPopulate(() => {\n const selector = this.button.menu.inner_selector;\n selector.html('');\n // General model HTML representation\n if (typeof this.parent_plot.state.model.html != 'undefined') {\n selector.append('div').html(this.parent_plot.state.model.html);\n }\n // Model covariates table\n if (!this.parent_plot.state.model.covariates.length) {\n selector.append('i').html('no covariates in model');\n } else {\n selector.append('h5').html(`Model Covariates (${this.parent_plot.state.model.covariates.length})`);\n const table = selector.append('table');\n this.parent_plot.state.model.covariates.forEach((covariate, idx) => {\n const html = ((typeof covariate == 'object' && typeof covariate.html == 'string') ? covariate.html : covariate.toString());\n const row = table.append('tr');\n row.append('td').append('button')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}`)\n .style('margin-left', '0em')\n .on('click', () => this.parent_plot.CovariatesModel.removeByIdx(idx))\n .html('×');\n row.append('td')\n .html(html);\n });\n selector.append('button')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}`)\n .style('margin-left', '4px')\n .html('× Remove All Covariates')\n .on('click', () => this.parent_plot.CovariatesModel.removeAll());\n }\n });\n\n this.button.preUpdate = () => {\n let html = 'Model';\n const count = this.parent_plot.state.model.covariates.length;\n if (count) {\n const noun = count > 1 ? 'covariates' : 'covariate';\n html += ` (${count} ${noun})`;\n }\n this.button.setHtml(html).disable(false);\n };\n\n this.button.show();\n\n return this;\n }\n }\n\n\n /**\n * Menu for manipulating multiple data layers in a single panel: show/hide, change order, etc.\n * @alias module:ext/lz-widget-addons~data_layers\n * @see module:LocusZoom_Widgets~BaseWidget\n */\n class DataLayersWidget extends _BaseWidget {\n update() {\n\n if (typeof this.layout.button_html != 'string') {\n this.layout.button_html = 'Data Layers';\n }\n if (typeof this.layout.button_title != 'string') {\n this.layout.button_title = 'Manipulate Data Layers (sort, dim, show/hide, etc.)';\n }\n\n if (this.button) {\n return this;\n }\n\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n\n this.button.menu.setPopulate(() => {\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n this.parent_panel.data_layer_ids_by_z_index.slice().reverse().forEach((id, idx) => {\n const data_layer = this.parent_panel.data_layers[id];\n const name = (typeof data_layer.layout.name != 'string') ? data_layer.id : data_layer.layout.name;\n const row = table.append('tr');\n // Layer name\n row.append('td').html(name);\n // Status toggle buttons\n this.layout.statuses.forEach((status_adj) => {\n const status_idx = STATUS_ADJECTIVES.indexOf(status_adj);\n const status_verb = STATUS_VERBS[status_idx];\n let html, onclick, highlight;\n if (data_layer.global_statuses[status_adj]) {\n html = STATUS_ANTIVERBS[status_idx];\n onclick = `un${status_verb}AllElements`;\n highlight = '-highlighted';\n } else {\n html = STATUS_VERBS[status_idx];\n onclick = `${status_verb}AllElements`;\n highlight = '';\n }\n row.append('td').append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}${highlight}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer[onclick]();\n this.button.menu.populate();\n })\n .html(html);\n });\n // Sort layer buttons\n const at_top = (idx === 0);\n const at_bottom = (idx === (this.parent_panel.data_layer_ids_by_z_index.length - 1));\n const td = row.append('td');\n td.append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-group-start lz-toolbar-button-${this.layout.color}${at_bottom ? '-disabled' : ''}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer.moveBack(); this.button.menu.populate();\n })\n .html('▾')\n .attr('title', 'Move layer down (further back)');\n td.append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-group-middle lz-toolbar-button-${this.layout.color}${at_top ? '-disabled' : ''}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer.moveForward(); this.button.menu.populate();\n })\n .html('▴')\n .attr('title', 'Move layer up (further front)');\n td.append('a')\n .attr('class', 'lz-toolbar-button lz-toolbar-button-group-end lz-toolbar-button-red')\n .style('margin-left', '0em')\n .on('click', () => {\n if (confirm(`Are you sure you want to remove the ${name} layer? This cannot be undone.`)) {\n data_layer.parent.removeDataLayer(id);\n }\n return this.button.menu.populate();\n })\n .html('×')\n .attr('title', 'Remove layer');\n });\n return this;\n });\n\n this.button.show();\n\n return this;\n }\n }\n\n const covariates_model_tooltip = function () {\n const covariates_model_association = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true });\n covariates_model_association.html += 'Condition on Variant
';\n return covariates_model_association;\n }();\n\n const covariates_model_plot = function () {\n const covariates_model_plot_toolbar = LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true });\n covariates_model_plot_toolbar.widgets.push({\n type: 'covariates_model',\n button_html: 'Model',\n button_title: 'Show and edit covariates currently in model',\n position: 'left',\n });\n return covariates_model_plot_toolbar;\n }();\n\n LocusZoom.Widgets.add('covariates_model', CovariatesModel);\n LocusZoom.Widgets.add('data_layers', DataLayersWidget);\n\n LocusZoom.Layouts.add('tooltip', 'covariates_model_association', covariates_model_tooltip);\n LocusZoom.Layouts.add('toolbar', 'covariates_model_plot', covariates_model_plot);\n}\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/external \"d3\"","webpack://[name]/./esm/helpers/layouts.js","webpack://[name]/./esm/ext/lz-widget-addons.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","Math","sqrt","deepCopy","item","JSON","parse","stringify","STATUS_VERBS","STATUS_ADJECTIVES","STATUS_ANTIVERBS","install","LocusZoom","_Button","Widgets","_BaseWidget","covariates_model_tooltip","covariates_model_association","Layouts","unnamespaced","html","covariates_model_plot","covariates_model_plot_toolbar","widgets","push","type","button_html","button_title","position","add","this","parent_plot","state","model","covariates","CovariatesModel","button","element_reference","plot","element","toHTML","toString","i","length","applyState","updateWidget","removeByIdx","idx","Error","splice","removeAll","update","menu","setColor","layout","color","setHtml","setTitle","setOnclick","populate","setPopulate","selector","inner_selector","append","table","forEach","covariate","row","attr","style","on","preUpdate","count","disable","show","parent_panel","data_layer_ids_by_z_index","slice","reverse","id","data_layer","data_layers","name","statuses","status_adj","status_idx","indexOf","status_verb","onclick","highlight","global_statuses","at_top","at_bottom","td","moveBack","moveForward","confirm","parent","removeDataLayer","use"],"mappings":";sCACA,IAAIA,EAAsB,CCA1B,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3E,EAAwB,CAACM,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,I,4BCA7CI,GCSvBC,KAAKC,KAAK,GA8GxB,SAASC,EAASC,GACd,OAAOC,KAAKC,MAAMD,KAAKE,UAAUH,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AAG9B,OAAO,KACLK,KAAK,QAAS,uEACdC,MAAM,cAAe,OACrBC,GAAG,SAAS,KACL0B,QAAQ,uCAAuCd,oCAC/CF,EAAWiB,OAAOC,gBAAgBnB,GAE/BjD,KAAKM,OAAOgB,KAAKO,cAE3BvC,KAAK,KACLgD,KAAK,QAAS,mBAEhBtC,QAGXA,KAAKM,OAAOsC,QA9ED5C,QAwGnBlB,EAAUM,QAAQW,IAAI,UAAW,+BAAgCb,GACjEJ,EAAUM,QAAQW,IAAI,UAAW,wBAAyBR,GAGrC,oBAAdT,WAGPA,UAAUuF,IAAIxF,GAIlB,U","file":"ext/lz-widget-addons.min.js","sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","const __WEBPACK_NAMESPACE_OBJECT__ = d3;","/**\n * Utilities for modifying or working with layout objects\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport {mutate, query} from './jsonpath';\n\nconst sqrt3 = Math.sqrt(3);\n// D3 v5 does not provide a triangle down symbol shape, but it is very useful for showing direction of effect.\n// Modified from https://github.com/d3/d3-shape/blob/master/src/symbol/triangle.js\nconst triangledown = {\n draw(context, size) {\n const y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, -y * 2);\n context.lineTo(-sqrt3 * y, y);\n context.lineTo(sqrt3 * y, y);\n context.closePath();\n },\n};\n\n/**\n * Apply namespaces to layout, recursively\n * @private\n */\nfunction applyNamespaces(element, namespace, default_namespace) {\n if (namespace) {\n if (typeof namespace == 'string') {\n namespace = { default: namespace };\n }\n } else {\n namespace = { default: '' };\n }\n if (typeof element == 'string') {\n const re = /\\{\\{namespace(\\[[A-Za-z_0-9]+\\]|)\\}\\}/g;\n let match, base, key, resolved_namespace;\n const replace = [];\n while ((match = re.exec(element)) !== null) {\n base = match[0];\n key = match[1].length ? match[1].replace(/(\\[|\\])/g, '') : null;\n resolved_namespace = default_namespace;\n if (namespace != null && typeof namespace == 'object' && typeof namespace[key] != 'undefined') {\n resolved_namespace = namespace[key] + (namespace[key].length ? ':' : '');\n }\n replace.push({ base: base, namespace: resolved_namespace });\n }\n for (let r in replace) {\n element = element.replace(replace[r].base, replace[r].namespace);\n }\n } else if (typeof element == 'object' && element != null) {\n if (typeof element.namespace != 'undefined') {\n const merge_namespace = (typeof element.namespace == 'string') ? { default: element.namespace } : element.namespace;\n namespace = merge(namespace, merge_namespace);\n }\n let namespaced_element, namespaced_property;\n for (let property in element) {\n if (property === 'namespace') {\n continue;\n }\n namespaced_element = applyNamespaces(element[property], namespace, default_namespace);\n namespaced_property = applyNamespaces(property, namespace, default_namespace);\n if (property !== namespaced_property) {\n delete element[property];\n }\n element[namespaced_property] = namespaced_element;\n }\n }\n return element;\n}\n\n/**\n * A helper method used for merging two objects. If a key is present in both, takes the value from the first object.\n * Values from `default_layout` will be cleanly copied over, ensuring no references or shared state.\n *\n * Frequently used for preparing custom layouts. Both objects should be JSON-serializable.\n *\n * @alias LayoutRegistry.merge\n * @param {object} custom_layout An object containing configuration parameters that override or add to defaults\n * @param {object} default_layout An object containing default settings.\n * @returns {object} The custom layout is modified in place and also returned from this method.\n */\nfunction merge(custom_layout, default_layout) {\n if (typeof custom_layout !== 'object' || typeof default_layout !== 'object') {\n throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof custom_layout}, ${typeof default_layout} given`);\n }\n for (let property in default_layout) {\n if (!Object.prototype.hasOwnProperty.call(default_layout, property)) {\n continue;\n }\n // Get types for comparison. Treat nulls in the custom layout as undefined for simplicity.\n // (javascript treats nulls as \"object\" when we just want to overwrite them as if they're undefined)\n // Also separate arrays from objects as a discrete type.\n let custom_type = custom_layout[property] === null ? 'undefined' : typeof custom_layout[property];\n let default_type = typeof default_layout[property];\n if (custom_type === 'object' && Array.isArray(custom_layout[property])) {\n custom_type = 'array';\n }\n if (default_type === 'object' && Array.isArray(default_layout[property])) {\n default_type = 'array';\n }\n // Unsupported property types: throw an exception\n if (custom_type === 'function' || default_type === 'function') {\n throw new Error('LocusZoom.Layouts.merge encountered an unsupported property type');\n }\n // Undefined custom value: pull the default value\n if (custom_type === 'undefined') {\n custom_layout[property] = deepCopy(default_layout[property]);\n continue;\n }\n // Both values are objects: merge recursively\n if (custom_type === 'object' && default_type === 'object') {\n custom_layout[property] = merge(custom_layout[property], default_layout[property]);\n continue;\n }\n }\n return custom_layout;\n}\n\nfunction deepCopy(item) {\n return JSON.parse(JSON.stringify(item));\n}\n\n/**\n * Convert name to symbol\n * Layout objects accept symbol names as strings (circle, triangle, etc). Convert to symbol objects.\n * @return {object|null} An object that implements a draw method (eg d3-shape symbols or extra LZ items)\n */\nfunction nameToSymbol(shape) {\n if (!shape) {\n return null;\n }\n if (shape === 'triangledown') {\n // D3 does not provide this symbol natively\n return triangledown;\n }\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const factory_name = `symbol${shape.charAt(0).toUpperCase() + shape.slice(1)}`;\n return d3[factory_name] || null;\n}\n\n/**\n * A utility helper for customizing one part of a pre-made layout. Whenever a primitive value is found (eg string),\n * replaces *exact match*\n *\n * This method works by comparing whether strings are a match. As a result, the \"old\" and \"new\" names must match\n * whatever namespacing is used in the input layout.\n * Note: this utility *can* replace values with filters, but will not do so by default.\n *\n * @alias LayoutRegistry.renameField\n *\n * @param {object} layout The layout object to be transformed.\n * @param {string} old_name The old field name that will be replaced\n * @param {string} new_name The new field name that will be substituted in\n * @param {boolean} [warn_transforms=true] Sometimes, a field name is used with transforms appended, eg `label|htmlescape`.\n * In some cases a rename could change the meaning of the field, and by default this method will print a warning to\n * the console, encouraging the developer to check the relevant usages. This warning can be silenced via an optional function argument.\n */\nfunction renameField(layout, old_name, new_name, warn_transforms = true) {\n const this_type = typeof layout;\n // Handle nested types by recursion (in which case, `layout` may be something other than an object)\n if (Array.isArray(layout)) {\n return layout.map((item) => renameField(item, old_name, new_name, warn_transforms));\n } else if (this_type === 'object' && layout !== null) {\n return Object.keys(layout).reduce(\n (acc, key) => {\n acc[key] = renameField(layout[key], old_name, new_name, warn_transforms);\n return acc;\n }, {}\n );\n } else if (this_type !== 'string') {\n // Field names are always strings. If the value isn't a string, don't even try to change it.\n return layout;\n } else {\n // If we encounter a field we are trying to rename, then do so!\n // Rules:\n // 1. Try to avoid renaming part of a field, by checking token boundaries (field1 should not rename field1_displayvalue)\n // 2. Warn the user if filter functions are being used with the specified field, so they can audit for changes in meaning\n const escaped = old_name.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n if (warn_transforms) {\n // Warn the user that they might be renaming, eg, `pvalue|neg_log` to `log_pvalue|neg_log`. Let them decide\n // whether the new field name has a meaning that is compatible with the specified transforms.\n const filter_regex = new RegExp(`${escaped}\\\\|\\\\w+`, 'g');\n const filter_matches = (layout.match(filter_regex) || []);\n filter_matches.forEach((match_val) => console.warn(`renameFields is renaming a field that uses transform functions: was '${match_val}' . Verify that these transforms are still appropriate.`));\n }\n\n // Find and replace any substring, so long as it is at the end of a valid token\n const regex = new RegExp(`${escaped}(?!\\\\w+)`, 'g');\n return layout.replace(regex, new_name);\n }\n}\n\n/**\n * Modify any and all attributes at the specified path in the object\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which field(s) to change.\n * The callback will be applied to ALL matching selectors\n * (see Interactivity guide for syntax and limitations)\n * @param {*|function} value_or_callable The new value, or a function that receives the old value and returns a new one\n * @returns {Array}\n * @alias LayoutRegistry.mutate_attrs\n */\nfunction mutate_attrs(layout, selector, value_or_callable) {\n return mutate(\n layout,\n selector,\n value_or_callable\n );\n}\n\n/**\n * Query any and all attributes at the specified path in the object.\n * This is mostly only useful for debugging, to verify that a particular selector matches the intended field.\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which values to return. (see Interactivity guide for limits)\n * @returns {Array}\n * @alias LayoutRegistry.query_attrs\n */\nfunction query_attrs(layout, selector) {\n return query(layout, selector);\n}\n\nexport { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, renameField };\n","/**\n * Optional LocusZoom extension: must be included separately, and after LocusZoom has been loaded\n *\n * This contains (reusable) code to power some (rarely used) demo features:\n * - The \"covariates model\" demo, in which an LZ toolbar widget is populated\n * with information by selecting points on the plot (see \"covariates model\" demo)\n * - The \"data layers\" button, which allows fine control over multiple data layers shown in the same panel\n * (show/hide, fade, change order, etc). This is powerful, but rarely used because showing many datasets in a small\n * space makes data hard to see. (see \"multiple phenotypes layered\" demo)\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - LocusZoom\n *\n * To use in an environment without special JS build tooling, simply load the extension file as JS from a CDN (after any dependencies):\n *\n * ```javascript\n * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```javascript\n * import LocusZoom from 'locuszoom';\n * import WidgetAddons from 'locuszoom/esm/ext/lz-widget-addons';\n * LocusZoom.use(WidgetAddons);\n * ```\n *\n * Then use the features made available by this extension. (see demos and documentation for guidance)\n *\n * @module\n */\nimport {deepCopy} from '../helpers/layouts';\n\n// In order to work in a UMD context, this module imports the top-level LocusZoom symbol\n\nconst STATUS_VERBS = ['highlight', 'select', 'fade', 'hide'];\nconst STATUS_ADJECTIVES = ['highlighted', 'selected', 'faded', 'hidden'];\nconst STATUS_ANTIVERBS = ['unhighlight', 'deselect', 'unfade', 'show'];\n\n\n// LocusZoom plugins work by exporting a function that receives the `LocusZoom` object\n// This allows them to work in many contexts (including script tags and ES6 imports)\nfunction install(LocusZoom) {\n const _Button = LocusZoom.Widgets.get('_Button');\n const _BaseWidget = LocusZoom.Widgets.get('BaseWidget');\n\n\n /**\n * Special button/menu to allow model building by tracking individual covariants. Will track a list of covariate\n * objects and store them in the special `model.covariates` field of plot `state`.\n *\n * This is a prototype widget for building a conditional analysis model, but it performs no calculation\n * functionality beyond building a list of items.\n * @alias module:ext/lz-widget-addons~covariates_model\n * @see module:LocusZoom_Widgets~BaseWidget\n * @param {object} layout\n * @param {string} layout.button_html The HTML to render inside the button\n * @param {string} layout.button_title Text to display as a tooltip when hovering over the button\n */\n class CovariatesModel extends _BaseWidget {\n initialize() {\n // Initialize state.model.covariates\n this.parent_plot.state.model = this.parent_plot.state.model || {};\n this.parent_plot.state.model.covariates = this.parent_plot.state.model.covariates || [];\n // Create an object at the plot level for easy access to interface methods in custom client-side JS\n /**\n * When a covariates model toolbar element is present, create (one) object at the plot level that exposes\n * widget data and state for custom interactions with other plot elements.\n */\n this.parent_plot.CovariatesModel = {\n /** @member {Button} */\n button: this,\n /**\n * Add an element to the model and show a representation of it in the toolbar widget menu. If the\n * element is already part of the model, do nothing (to avoid adding duplicates).\n * When plot state is changed, this will automatically trigger requests for new data accordingly.\n * @param {string|object} element_reference Can be any value that can be put through JSON.stringify()\n * to create a serialized representation of itself.\n */\n add: (element_reference) => {\n const plot = this.parent_plot;\n const element = deepCopy(element_reference);\n if (typeof element_reference == 'object' && typeof element.html != 'string') {\n element.html = ( (typeof element_reference.toHTML == 'function') ? element_reference.toHTML() : element_reference.toString());\n }\n // Check if the element is already in the model covariates array and return if it is.\n for (let i = 0; i < plot.state.model.covariates.length; i++) {\n if (JSON.stringify(plot.state.model.covariates[i]) === JSON.stringify(element)) {\n return plot;\n }\n }\n plot.state.model.covariates.push(element);\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Remove an element from `state.model.covariates` (and from the toolbar widget menu's\n * representation of the state model). When plot state is changed, this will automatically trigger\n * requests for new data accordingly.\n * @param {number} idx Array index of the element, in the `state.model.covariates array`.\n */\n removeByIdx: (idx) => {\n const plot = this.parent_plot;\n if (typeof plot.state.model.covariates[idx] == 'undefined') {\n throw new Error(`Unable to remove model covariate, invalid index: ${idx.toString()}`);\n }\n plot.state.model.covariates.splice(idx, 1);\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Empty the `state.model.covariates` array (and toolbar widget menu representation thereof) of all\n * elements. When plot state is changed, this will automatically trigger requests for new data accordingly\n */\n removeAll: () => {\n const plot = this.parent_plot;\n plot.state.model.covariates = [];\n plot.applyState();\n plot.CovariatesModel.updateWidget();\n return plot;\n },\n /**\n * Manually trigger the update methods on the toolbar widget's button and menu elements to force\n * display of most up-to-date content. Can be used to force the toolbar to reflect changes made, eg if\n * modifying `state.model.covariates` directly instead of via `plot.CovariatesModel`\n */\n updateWidget: () => {\n this.button.update();\n this.button.menu.update();\n },\n };\n }\n\n update() {\n\n if (this.button) {\n return this;\n }\n\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n\n this.button.menu.setPopulate(() => {\n const selector = this.button.menu.inner_selector;\n selector.html('');\n // General model HTML representation\n if (typeof this.parent_plot.state.model.html != 'undefined') {\n selector.append('div').html(this.parent_plot.state.model.html);\n }\n // Model covariates table\n if (!this.parent_plot.state.model.covariates.length) {\n selector.append('i').html('no covariates in model');\n } else {\n selector.append('h5').html(`Model Covariates (${this.parent_plot.state.model.covariates.length})`);\n const table = selector.append('table');\n this.parent_plot.state.model.covariates.forEach((covariate, idx) => {\n const html = ((typeof covariate == 'object' && typeof covariate.html == 'string') ? covariate.html : covariate.toString());\n const row = table.append('tr');\n row.append('td').append('button')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}`)\n .style('margin-left', '0em')\n .on('click', () => this.parent_plot.CovariatesModel.removeByIdx(idx))\n .html('×');\n row.append('td')\n .html(html);\n });\n selector.append('button')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}`)\n .style('margin-left', '4px')\n .html('× Remove All Covariates')\n .on('click', () => this.parent_plot.CovariatesModel.removeAll());\n }\n });\n\n this.button.preUpdate = () => {\n let html = 'Model';\n const count = this.parent_plot.state.model.covariates.length;\n if (count) {\n const noun = count > 1 ? 'covariates' : 'covariate';\n html += ` (${count} ${noun})`;\n }\n this.button.setHtml(html).disable(false);\n };\n\n this.button.show();\n\n return this;\n }\n }\n\n\n /**\n * Menu for manipulating multiple data layers in a single panel: show/hide, change order, etc.\n * @alias module:ext/lz-widget-addons~data_layers\n * @see module:LocusZoom_Widgets~BaseWidget\n */\n class DataLayersWidget extends _BaseWidget {\n update() {\n\n if (typeof this.layout.button_html != 'string') {\n this.layout.button_html = 'Data Layers';\n }\n if (typeof this.layout.button_title != 'string') {\n this.layout.button_title = 'Manipulate Data Layers (sort, dim, show/hide, etc.)';\n }\n\n if (this.button) {\n return this;\n }\n\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n\n this.button.menu.setPopulate(() => {\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n this.parent_panel.data_layer_ids_by_z_index.slice().reverse().forEach((id, idx) => {\n const data_layer = this.parent_panel.data_layers[id];\n const name = (typeof data_layer.layout.name != 'string') ? data_layer.id : data_layer.layout.name;\n const row = table.append('tr');\n // Layer name\n row.append('td').html(name);\n // Status toggle buttons\n this.layout.statuses.forEach((status_adj) => {\n const status_idx = STATUS_ADJECTIVES.indexOf(status_adj);\n const status_verb = STATUS_VERBS[status_idx];\n let html, onclick, highlight;\n if (data_layer.global_statuses[status_adj]) {\n html = STATUS_ANTIVERBS[status_idx];\n onclick = `un${status_verb}AllElements`;\n highlight = '-highlighted';\n } else {\n html = STATUS_VERBS[status_idx];\n onclick = `${status_verb}AllElements`;\n highlight = '';\n }\n row.append('td').append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-${this.layout.color}${highlight}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer[onclick]();\n this.button.menu.populate();\n })\n .html(html);\n });\n // Sort layer buttons\n const at_top = (idx === 0);\n const at_bottom = (idx === (this.parent_panel.data_layer_ids_by_z_index.length - 1));\n const td = row.append('td');\n td.append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-group-start lz-toolbar-button-${this.layout.color}${at_bottom ? '-disabled' : ''}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer.moveBack(); this.button.menu.populate();\n })\n .html('▾')\n .attr('title', 'Move layer down (further back)');\n td.append('a')\n .attr('class', `lz-toolbar-button lz-toolbar-button-group-middle lz-toolbar-button-${this.layout.color}${at_top ? '-disabled' : ''}`)\n .style('margin-left', '0em')\n .on('click', () => {\n data_layer.moveForward(); this.button.menu.populate();\n })\n .html('▴')\n .attr('title', 'Move layer up (further front)');\n td.append('a')\n .attr('class', 'lz-toolbar-button lz-toolbar-button-group-end lz-toolbar-button-red')\n .style('margin-left', '0em')\n .on('click', () => {\n if (confirm(`Are you sure you want to remove the ${name} layer? This cannot be undone.`)) {\n data_layer.parent.removeDataLayer(id);\n }\n return this.button.menu.populate();\n })\n .html('×')\n .attr('title', 'Remove layer');\n });\n return this;\n });\n\n this.button.show();\n\n return this;\n }\n }\n\n const covariates_model_tooltip = function () {\n const covariates_model_association = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true });\n covariates_model_association.html += 'Condition on Variant
';\n return covariates_model_association;\n }();\n\n const covariates_model_plot = function () {\n const covariates_model_plot_toolbar = LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true });\n covariates_model_plot_toolbar.widgets.push({\n type: 'covariates_model',\n button_html: 'Model',\n button_title: 'Show and edit covariates currently in model',\n position: 'left',\n });\n return covariates_model_plot_toolbar;\n }();\n\n LocusZoom.Widgets.add('covariates_model', CovariatesModel);\n LocusZoom.Widgets.add('data_layers', DataLayersWidget);\n\n LocusZoom.Layouts.add('tooltip', 'covariates_model_association', covariates_model_tooltip);\n LocusZoom.Layouts.add('toolbar', 'covariates_model_plot', covariates_model_plot);\n}\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/locuszoom.app.min.js b/dist/locuszoom.app.min.js index a1c0fd31..7368c255 100644 --- a/dist/locuszoom.app.min.js +++ b/dist/locuszoom.app.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.3 */ -var LocusZoom;(()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};(()=>{t.d(e,{default:()=>Je});var s={};t.r(s),t.d(s,{AssociationLZ:()=>_,BaseAdapter:()=>u,BaseApiAdapter:()=>p,ConnectorSource:()=>w,GeneConstraintLZ:()=>f,GeneLZ:()=>m,GwasCatalogLZ:()=>y,LDServer:()=>g,PheWASLZ:()=>v,RecombLZ:()=>b,StaticSource:()=>x});var i={};t.r(i),t.d(i,{htmlescape:()=>A,is_numeric:()=>L,log10:()=>M,logtoscinotation:()=>N,neglog10:()=>S,scinotation:()=>T,urlencode:()=>O});var a={};t.r(a),t.d(a,{BaseWidget:()=>st,_Button:()=>it,display_options:()=>mt,download:()=>rt,download_png:()=>lt,filter_field:()=>ot,menu:()=>_t,move_panel_down:()=>dt,move_panel_up:()=>ct,region_scale:()=>nt,remove_panel:()=>ht,resize_to_data:()=>gt,set_state:()=>ft,shift_region:()=>ut,title:()=>at,toggle_legend:()=>yt,zoom_region:()=>pt});var n={};t.r(n),t.d(n,{categorical_bin:()=>Pt,if_value:()=>Ot,interpolate:()=>It,numerical_bin:()=>Ct,ordinal_cycle:()=>Rt,stable_choice:()=>Dt});var o={};t.r(o),t.d(o,{BaseDataLayer:()=>Ft,annotation_track:()=>Gt,arcs:()=>Kt,category_scatter:()=>ie,genes:()=>Yt,highlight_regions:()=>Zt,line:()=>Xt,orthogonal_line:()=>te,scatter:()=>se});var r={};t.r(r),t.d(r,{data_layer:()=>Be,panel:()=>Ue,plot:()=>Fe,toolbar:()=>je,toolbar_widgets:()=>Ie,tooltip:()=>De});const l="0.13.3";class h{constructor(){this._items=new Map}get(t){if(!this._items.has(t))throw new Error(`Item not found: ${t}`);return this._items.get(t)}add(t,e,s=!1){if(!s&&this._items.has(t))throw new Error(`Item ${t} is already defined`);return this._items.set(t,e),e}remove(t){return this._items.delete(t)}has(t){return this._items.has(t)}list(){return Array.from(this._items.keys())}}class c extends h{create(t,...e){return new(this.get(t))(...e)}extend(t,e,s){if(console.warn("Deprecation warning: .extend method will be removed in future versions, in favor of explicit ES6 subclasses"),3!==arguments.length)throw new Error("Invalid arguments to .extend");const i=this.get(t);class a extends i{}return Object.assign(a.prototype,s,i),this.add(e,a),a}}function d(t,e,s){if(e&&s||!e&&!s)throw new Error(`${t} must provide a parameter specifying either "build" or "source". It should not specify both.`);if(e&&!["GRCh37","GRCh38"].includes(e))throw new Error(`${t} must specify a valid genome build number`)}class u{constructor(t){this._enableCache=!0,this._cachedKey=null,this._cache_pos_start=null,this._cache_pos_end=null,this.__dependentSource=!1,this.parseInit(t)}parseInit(t){this.params=t.params||{}}getCacheKey(t,e,s){this.getURL(t,e,s);const i=t.chr,{_cache_pos_start:a,_cache_pos_end:n}=this;return a&&t.start>=a&&n&&t.end<=n?`${i}_${a}_${n}`:`${t.chr}_${t.start}_${t.end}`}getURL(t,e,s){return this.url}fetchRequest(t,e,s){const i=this.getURL(t,e,s);return fetch(i).then((t=>{if(!t.ok)throw new Error(t.statusText);return t.text()}))}getRequest(t,e,s){let i;const a=this.getCacheKey(t,e,s);return this._enableCache&&void 0!==a&&a===this._cachedKey?i=Promise.resolve(this._cachedResponse):(i=this.fetchRequest(t,e,s),this._enableCache&&(this._cachedKey=a,this._cache_pos_start=t.start,this._cache_pos_end=t.end,this._cachedResponse=i)),i}normalizeResponse(t){if(Array.isArray(t))return t;const e=Object.keys(t),s=t[e[0]].length;if(!e.every((function(e){return t[e].length===s})))throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);const i=[],a=Object.keys(t);for(let e=0;ePromise.resolve(this.annotateData(t,e)))).then((t=>Promise.resolve(this.extractFields(t,s,i,a)))).then((t=>(e.discrete[n]=t,Promise.resolve(this.combineChainBody(t,e,s,i,a))))).then((t=>({header:e.header||{},discrete:e.discrete,body:t})))}getData(t,e,s,i){if(this.preGetData){const a=this.preGetData(t,e,s,i);this.pre&&(t=a.state||t,e=a.fields||e,s=a.outnames||s,i=a.trans||i)}return a=>this.__dependentSource&&a&&a.body&&!a.body.length?Promise.resolve(a):this.getRequest(t,a,e).then((t=>this.parseResponse(t,a,e,s,i)))}}class p extends u{parseInit(t){if(super.parseInit(t),this.url=t.url,!this.url)throw new Error("Source not initialized with required URL")}}class _ extends p{preGetData(t,e,s,i){return[this.params.id_field||"id","position"].forEach((function(t){e.includes(t)||(e.unshift(t),s.unshift(t),i.unshift(null))})),{fields:e,outnames:s,trans:i}}getURL(t,e,s){const i=e.header.analysis||this.params.source||this.params.analysis;if(void 0===i)throw new Error("Association source must specify an analysis ID to plot");return`${this.url}results/?filter=analysis in ${i} and chromosome in '${t.chr}' and position ge ${t.start} and position le ${t.end}`}normalizeResponse(t){return t=super.normalizeResponse(t),this.params&&this.params.sort&&t.length&&t[0].position&&t.sort((function(t,e){return t.position-e.position})),t}}class g extends p{constructor(t){super(t),this.__dependentSource=!0}preGetData(t,e){if(e.length>1&&(2!==e.length||!e.includes("isrefvar")))throw new Error(`LD does not know how to get all fields: ${e.join(", ")}`)}findMergeFields(t){let e={id:this.params.id_field,position:this.params.position_field,pvalue:this.params.pvalue_field,_names_:null};if(t&&t.body&&t.body.length>0){const i=Object.keys(t.body[0]),a=(s=i,function(){const t=arguments;for(let e=0;ee}:function(t,e){return t{if(!t.ok)throw new Error(t.statusText);return t.text()})).then((function(t){return t=JSON.parse(t),Object.keys(t.data).forEach((function(e){a.data[e]=(a.data[e]||[]).concat(t.data[e])})),t.next?n(t.next):a}))};return n(i)}}class y extends p{constructor(t){super(t),this.__dependentSource=!0}getURL(t,e,s){const i=t.genome_build||this.params.build,a=this.params.source;d(this.constructor.name,i,a);const n=i?`&build=${i}`:` and id eq ${a}`;return`${this.url}?format=objects&sort=pos&filter=chrom eq '${t.chr}' and pos ge ${t.start} and pos le ${t.end}${n}`}findMergeFields(t){const e=Object.keys(t).find((function(t){return t.match(/\b(position|pos)\b/i)}));if(!e)throw new Error("Could not find data to align with GWAS catalog results");return{pos:e}}extractFields(t,e,s,i){return t}combineChainBody(t,e,s,i,a){if(!t.length)return e.body;const n="log_pvalue",o=i[s.indexOf(n)];function r(t,e,s,i,a){const r=t.n_catalog_matches||0;if(t.n_catalog_matches=r+1,!(t[o]&&t[o]>e[n]))for(let n=0;n25||"GRCh38"===i)return Promise.resolve({data:null});n=`{${n.join(" ")} }`;const o=this.getURL(t,e,s),r=JSON.stringify({query:n});return fetch(o,{method:"POST",body:r,headers:{"Content-Type":"application/json"}}).then((t=>t.ok?t.text():[])).catch((t=>[]))}combineChainBody(t,e,s,i,a){return t?(e.body.forEach((function(e){const s=`_${e.gene_name.replace(/[^A-Za-z0-9_]/g,"_")}`,i=t[s]&&t[s].gnomad_constraint;i&&Object.keys(i).forEach((function(t){let s=i[t];void 0===e[t]&&("number"==typeof s&&s.toString().includes(".")&&(s=parseFloat(s.toFixed(2))),e[t]=s)}))})),e.body):e}}class b extends p{getURL(t,e,s){const i=t.genome_build||this.params.build;let a=this.params.source;d(this.constructor.SOURCE_NAME,i,a);const n=i?`&build=${i}`:` and id in ${a}`;return`${this.url}?filter=chromosome eq '${t.chr}' and position le ${t.end} and position ge ${t.start}${n}`}}class x extends u{parseInit(t){this._data=t}getRequest(t,e,s){return Promise.resolve(this._data)}}class v extends p{getURL(t,e,s){const i=(t.genome_build?[t.genome_build]:null)||this.params.build;if(!i||!Array.isArray(i)||!i.length)throw new Error(["Adapter",this.constructor.SOURCE_NAME,"requires that you specify array of one or more desired genome build names"].join(" "));return[this.url,"?filter=variant eq '",encodeURIComponent(t.variant),"'&format=objects&",i.map((function(t){return`build=${encodeURIComponent(t)}`})).join("&")].join("")}getCacheKey(t,e,s){return this.getURL(t,e,s)}}class w extends u{constructor(t){if(super(t),!t||!t.sources)throw new Error("Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs");this._source_name_mapping=t.sources;const e=Object.keys(t.sources);this._getRequiredSources().forEach((t=>{if(!e.includes(t))throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${t}`)}))}parseInit(){}getRequest(t,e,s){return Object.keys(this._source_name_mapping).forEach((t=>{const s=this._source_name_mapping[t];if(e.discrete&&!e.discrete[s])throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${s}`)})),Promise.resolve(e.body||[])}parseResponse(t,e,s,i,a){return Promise.resolve(this.combineChainBody(t,e,s,i,a)).then((function(t){return{header:e.header||{},discrete:e.discrete||{},body:t}}))}combineChainBody(t,e){throw new Error("This method must be implemented in a subclass")}_getRequiredSources(){throw new Error("Must specify an array that identifes the kind of data required by this source")}}const z=new c;for(let[t,e]of Object.entries(s))z.add(t,e);z.add("StaticJSON",x),z.add("LDLZ2",g);const $=z,k=d3,E={verbs:["highlight","select","fade","hide"],adjectives:["highlighted","selected","faded","hidden"]};function M(t){return isNaN(t)||t<=0?null:Math.log(t)/Math.LN10}function S(t){return isNaN(t)||t<=0?null:-Math.log(t)/Math.LN10}function N(t){if(isNaN(t))return"NaN";if(0===t)return"1";const e=Math.ceil(t),s=e-t,i=Math.pow(10,s);return 1===e?(i/10).toFixed(4):2===e?(i/100).toFixed(3):`${i.toFixed(2)} × 10^-${e}`}function T(t){if(isNaN(t))return"NaN";if(0===t)return"0";const e=Math.abs(t);let s;return s=e>1?Math.ceil(Math.log(e)/Math.LN10):Math.floor(Math.log(e)/Math.LN10),Math.abs(s)<=3?t.toFixed(3):t.toExponential(2).replace("+","").replace("e"," × 10^")}function A(t){return t?(t=`${t}`).replace(/['"<>&`]/g,(function(t){switch(t){case"'":return"'";case'"':return""";case"<":return"<";case">":return">";case"&":return"&";case"`":return"`"}})):""}function L(t){return"number"==typeof t}function O(t){return encodeURIComponent(t)}const C=new class extends h{_collectTransforms(t){const e=t.match(/\|([^|]+)/g).map((t=>super.get(t.substring(1))));return t=>e.reduce(((t,e)=>e(t)),t)}get(t){return t?"|"===t.substring(0,1)?this._collectTransforms(t):super.get(t):null}};for(let[t,e]of Object.entries(i))C.add(t,e);const P=C;class R{constructor(t){const e=/^(?:([^:]+):)?([^:|]*)(\|.+)*$/.exec(t);this.full_name=t,this.namespace=e[1]||null,this.name=e[2]||null,this.transformations=[],"string"==typeof e[3]&&e[3].length>1&&(this.transformations=e[3].substring(1).split("|"),this.transformations.forEach(((t,e)=>this.transformations[e]=P.get(t))))}_applyTransformations(t){return this.transformations.forEach((function(e){t=e(t)})),t}resolve(t,e){if(void 0===t[this.full_name]){let s=null;void 0!==t[`${this.namespace}:${this.name}`]?s=t[`${this.namespace}:${this.name}`]:void 0!==t[this.name]?s=t[this.name]:e&&void 0!==e[this.full_name]&&(s=e[this.full_name]),t[this.full_name]=this._applyTransformations(s)}return t[this.full_name]}}const D=/^(\*|[\w]+)/,I=/^\[\?\(@((?:\.[\w]+)+) *===? *([0-9.eE-]+|"[^"]*"|'[^']*')\)\]/;function j(t){if(".."===t.substr(0,2)){if("["===t[2])return{text:"..",attr:"*",depth:".."};const e=D.exec(t.substr(2));if(!e)throw`Cannot parse ${JSON.stringify(t)} as dotdot_attr.`;return{text:`..${e[0]}`,attr:e[1],depth:".."}}if("."===t[0]){const e=D.exec(t.substr(1));if(!e)throw`Cannot parse ${JSON.stringify(t)} as dot_attr.`;return{text:`.${e[0]}`,attr:e[1],depth:"."}}if("["===t[0]){const e=I.exec(t);if(!e)throw`Cannot parse ${JSON.stringify(t)} as expr.`;let s;try{s=JSON.parse(e[2])}catch(t){s=JSON.parse(e[2].replace(/^'|'$/g,'"'))}return{text:e[0],attrs:e[1].substr(1).split("."),value:s}}throw`The query ${JSON.stringify(t)} doesn't look valid.`}function B(t,e){let s;for(let i of e)s=t,t=t[i];return[s,e[e.length-1],t]}function U(t,e){if(!e.length)return[[]];const s=e[0],i=e.slice(1);let a=[];if(s.attr&&"."===s.depth&&"*"!==s.attr){const n=t[s.attr];1===e.length?void 0!==n&&a.push([s.attr]):a.push(...U(n,i).map((t=>[s.attr].concat(t))))}else if(s.attr&&"."===s.depth&&"*"===s.attr)for(let[e,s]of Object.entries(t))a.push(...U(s,i).map((t=>[e].concat(t))));else if(s.attr&&".."===s.depth){if("object"==typeof t&&null!==t){"*"!==s.attr&&s.attr in t&&a.push(...U(t[s.attr],i).map((t=>[s.attr].concat(t))));for(let[n,o]of Object.entries(t))a.push(...U(o,e).map((t=>[n].concat(t)))),"*"===s.attr&&a.push(...U(o,i).map((t=>[n].concat(t))))}}else if(s.attrs)for(let[e,n]of Object.entries(t)){const[t,o,r]=B(n,s.attrs);r===s.value&&a.push(...U(n,i).map((t=>[e].concat(t))))}const n=(o=a,r=JSON.stringify,[...new Map(o.map((t=>[r(t),t]))).values()]);var o,r;return n.sort(((t,e)=>e.length-t.length||JSON.stringify(t).localeCompare(JSON.stringify(e)))),n}function F(t,e){const s=function(t,e){let s=[];for(let i of U(t,e))s.push(B(t,i));return s}(t,function(t){t=function(t){return t?(["$","["].includes(t[0])||(t=`$.${t}`),"$"===t[0]&&(t=t.substr(1)),t):""}(t);let e=[];for(;t.length;){const s=j(t);t=t.substr(s.text.length),e.push(s)}return e}(e));return s.length||console.warn(`No items matched the specified query: '${e}'`),s}const q=Math.sqrt(3),G={draw(t,e){const s=-Math.sqrt(e/(3*q));t.moveTo(0,2*-s),t.lineTo(-q*s,s),t.lineTo(q*s,s),t.closePath()}};function H(t,e,s){if(e?"string"==typeof e&&(e={default:e}):e={default:""},"string"==typeof t){const i=/\{\{namespace(\[[A-Za-z_0-9]+\]|)\}\}/g;let a,n,o,r;const l=[];for(;null!==(a=i.exec(t));)n=a[0],o=a[1].length?a[1].replace(/(\[|\])/g,""):null,r=s,null!=e&&"object"==typeof e&&void 0!==e[o]&&(r=e[o]+(e[o].length?":":"")),l.push({base:n,namespace:r});for(let e in l)t=t.replace(l[e].base,l[e].namespace)}else if("object"==typeof t&&null!=t){if(void 0!==t.namespace){e=Z(e,"string"==typeof t.namespace?{default:t.namespace}:t.namespace)}let i,a;for(let n in t)"namespace"!==n&&(i=H(t[n],e,s),a=H(n,e,s),n!==a&&delete t[n],t[a]=i)}return t}function Z(t,e){if("object"!=typeof t||"object"!=typeof e)throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof t}, ${typeof e} given`);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=null===t[s]?"undefined":typeof t[s],a=typeof e[s];if("object"===i&&Array.isArray(t[s])&&(i="array"),"object"===a&&Array.isArray(e[s])&&(a="array"),"function"===i||"function"===a)throw new Error("LocusZoom.Layouts.merge encountered an unsupported property type");"undefined"!==i?"object"!==i||"object"!==a||(t[s]=Z(t[s],e[s])):t[s]=J(e[s])}return t}function J(t){return JSON.parse(JSON.stringify(t))}function K(t){if(!t)return null;if("triangledown"===t)return G;const e=`symbol${t.charAt(0).toUpperCase()+t.slice(1)}`;return k[e]||null}function V(t,e,s,i=!0){const a=typeof t;if(Array.isArray(t))return t.map((t=>V(t,e,s,i)));if("object"===a&&null!==t)return Object.keys(t).reduce(((a,n)=>(a[n]=V(t[n],e,s,i),a)),{});if("string"!==a)return t;{const a=e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");if(i){const e=new RegExp(`${a}\\|\\w+`,"g");(t.match(e)||[]).forEach((t=>console.warn(`renameFields is renaming a field that uses transform functions: was '${t}' . Verify that these transforms are still appropriate.`)))}const n=new RegExp(`${a}(?!\\w+)`,"g");return t.replace(n,s)}}function Y(t,e,s){return function(t,e,s){return F(t,e).map((([t,e,i])=>{const a="function"==typeof s?s(i):s;return t[e]=a,a}))}(t,e,s)}function W(t,e){return function(t,e){return F(t,e).map((t=>t[2]))}(t,e)}const X=class{constructor(t){this._sources=t}__split_requests(t){var e={},s=/^(?:([^:]+):)?([^:|]*)(\|.+)*$/;return t.forEach((function(t){var i=s.exec(t),a=i[1]||"base",n=i[2],o=P.get(i[3]);void 0===e[a]&&(e[a]={outnames:[],fields:[],trans:[]}),e[a].outnames.push(t),e[a].fields.push(n),e[a].trans.push(o)})),e}getData(t,e){for(var s=this.__split_requests(e),i=Object.keys(s).map((e=>{if(!this._sources.get(e))throw new Error(`Datasource for namespace ${e} not found`);return this._sources.get(e).getData(t,s[e].fields,s[e].outnames,s[e].trans)})),a=Promise.resolve({header:{},body:[],discrete:{}}),n=0;n(this.curtain.showing||(this.curtain.selector=k.select(this.parent_plot.svg.node().parentNode).insert("div").attr("class","lz-curtain").attr("id",`${this.id}.curtain`),this.curtain.content_selector=this.curtain.selector.append("div").attr("class","lz-curtain-content"),this.curtain.selector.append("div").attr("class","lz-curtain-dismiss").html("Dismiss").on("click",(()=>this.curtain.hide())),this.curtain.showing=!0),this.curtain.update(t,e)),update:(t,e)=>{if(!this.curtain.showing)return this.curtain;clearTimeout(this.curtain.hide_delay),"object"==typeof e&&et(this.curtain.selector,e);const s=this._getPageOrigin(),i=this.layout.height||this._total_height;return this.curtain.selector.style("top",`${s.y}px`).style("left",`${s.x}px`).style("width",`${this.parent_plot.layout.width}px`).style("height",`${i}px`),this.curtain.content_selector.style("max-width",this.parent_plot.layout.width-40+"px").style("max-height",i-40+"px"),"string"==typeof t&&this.curtain.content_selector.html(t),this.curtain},hide:t=>this.curtain.showing?"number"==typeof t?(clearTimeout(this.curtain.hide_delay),this.curtain.hide_delay=setTimeout(this.curtain.hide,t),this.curtain):(this.curtain.selector.remove(),this.curtain.selector=null,this.curtain.content_selector=null,this.curtain.showing=!1,this.curtain):this.curtain}}function tt(){return{showing:!1,selector:null,content_selector:null,progress_selector:null,cancel_selector:null,show:t=>(this.loader.showing||(this.loader.selector=k.select(this.parent_plot.svg.node().parentNode).insert("div").attr("class","lz-loader").attr("id",`${this.id}.loader`),this.loader.content_selector=this.loader.selector.append("div").attr("class","lz-loader-content"),this.loader.progress_selector=this.loader.selector.append("div").attr("class","lz-loader-progress-container").append("div").attr("class","lz-loader-progress"),this.loader.showing=!0,void 0===t&&(t="Loading...")),this.loader.update(t)),update:(t,e)=>{if(!this.loader.showing)return this.loader;clearTimeout(this.loader.hide_delay),"string"==typeof t&&this.loader.content_selector.html(t);const s=this._getPageOrigin(),i=this.loader.selector.node().getBoundingClientRect();return this.loader.selector.style("top",s.y+this.layout.height-i.height-6+"px").style("left",`${s.x+6}px`),"number"==typeof e&&this.loader.progress_selector.style("width",`${Math.min(Math.max(e,1),100)}%`),this.loader},animate:()=>(this.loader.progress_selector.classed("lz-loader-progress-animated",!0),this.loader),setPercentCompleted:t=>(this.loader.progress_selector.classed("lz-loader-progress-animated",!1),this.loader.update(null,t)),hide:t=>this.loader.showing?"number"==typeof t?(clearTimeout(this.loader.hide_delay),this.loader.hide_delay=setTimeout(this.loader.hide,t),this.loader):(this.loader.selector.remove(),this.loader.selector=null,this.loader.content_selector=null,this.loader.progress_selector=null,this.loader.cancel_selector=null,this.loader.showing=!1,this.loader):this.loader}}function et(t,e){e=e||{};for(let[s,i]of Object.entries(e))t.style(s,i)}class st{constructor(t,e){this.layout=t||{},this.layout.color||(this.layout.color="gray"),this.parent=e||null,this.parent_panel=null,this.parent_plot=null,this.parent_svg=null,this.parent&&("panel"===this.parent.type?(this.parent_panel=this.parent.parent,this.parent_plot=this.parent.parent.parent,this.parent_svg=this.parent_panel):(this.parent_plot=this.parent.parent,this.parent_svg=this.parent_plot)),this.selector=null,this.button=null,this.persist=!1,this.layout.position||(this.layout.position="left")}show(){if(this.parent&&this.parent.selector){if(!this.selector){const t=["start","middle","end"].includes(this.layout.group_position)?` lz-toolbar-group-${this.layout.group_position}`:"";this.selector=this.parent.selector.append("div").attr("class",`lz-toolbar-${this.layout.position}${t}`),this.layout.style&&et(this.selector,this.layout.style),"function"==typeof this.initialize&&this.initialize()}return this.button&&"highlighted"===this.button.status&&this.button.menu.show(),this.selector.style("visibility","visible"),this.update(),this.position()}}update(){}position(){return this.button&&this.button.menu.position(),this}shouldPersist(){return!!this.persist||!(!this.button||!this.button.persist)}hide(){return!this.selector||this.shouldPersist()||(this.button&&this.button.menu.hide(),this.selector.style("visibility","hidden")),this}destroy(t){return void 0===t&&(t=!1),this.selector?(this.shouldPersist()&&!t||(this.button&&this.button.menu&&this.button.menu.destroy(),this.selector.remove(),this.selector=null,this.button=null),this):this}}class it{constructor(t){if(!(t instanceof st))throw new Error("Unable to create toolbar widget button, invalid parent");this.parent=t,this.parent_panel=this.parent.parent_panel,this.parent_plot=this.parent.parent_plot,this.parent_svg=this.parent.parent_svg,this.parent_toolbar=this.parent.parent,this.selector=null,this.tag="a",this.html="",this.title="",this.color="gray",this.style={},this.persist=!1,this.permanent=!1,this.status="",this.menu={outer_selector:null,inner_selector:null,scroll_position:0,hidden:!0,show:()=>(this.menu.outer_selector||(this.menu.outer_selector=k.select(this.parent_plot.svg.node().parentNode).append("div").attr("class",`lz-toolbar-menu lz-toolbar-menu-${this.color}`).attr("id",`${this.parent_svg.getBaseId()}.toolbar.menu`),this.menu.inner_selector=this.menu.outer_selector.append("div").attr("class","lz-toolbar-menu-content"),this.menu.inner_selector.on("scroll",(()=>{this.menu.scroll_position=this.menu.inner_selector.node().scrollTop}))),this.menu.outer_selector.style("visibility","visible"),this.menu.hidden=!1,this.menu.update()),update:()=>this.menu.outer_selector?(this.menu.populate(),this.menu.inner_selector&&(this.menu.inner_selector.node().scrollTop=this.menu.scroll_position),this.menu.position()):this.menu,position:()=>{if(!this.menu.outer_selector)return this.menu;this.menu.outer_selector.style("height",null);const t=this.parent_svg._getPageOrigin(),e=document.documentElement.scrollTop||document.body.scrollTop,s=this.parent_plot.getContainerOffset(),i=this.parent_toolbar.selector.node().getBoundingClientRect(),a=this.selector.node().getBoundingClientRect(),n=this.menu.outer_selector.node().getBoundingClientRect(),o=this.menu.inner_selector.node().scrollHeight;let r,l;"panel"===this.parent_toolbar.type?(r=t.y+i.height+6,l=Math.max(t.x+this.parent_plot.layout.width-n.width-3,t.x+3)):(r=a.bottom+e+3-s.top,l=Math.max(a.left+a.width-n.width-s.left,t.x+3));const h=Math.max(this.parent_plot.layout.width-6-20,20),c=h,d=h-12,u=Math.max(this.parent_svg.layout.height-30-14,14),p=Math.min(o+14,u);return this.menu.outer_selector.style("top",`${r}px`).style("left",`${l}px`).style("max-width",`${c}px`).style("max-height",`${u}px`).style("height",`${p}px`),this.menu.inner_selector.style("max-width",`${d}px`),this.menu.inner_selector.node().scrollTop=this.menu.scroll_position,this.menu},hide:()=>this.menu.outer_selector?(this.menu.outer_selector.style("visibility","hidden"),this.menu.hidden=!0,this.menu):this.menu,destroy:()=>this.menu.outer_selector?(this.menu.inner_selector.remove(),this.menu.outer_selector.remove(),this.menu.inner_selector=null,this.menu.outer_selector=null,this.menu):this.menu,populate:()=>{throw new Error("Method must be implemented")},setPopulate:t=>("function"==typeof t?(this.menu.populate=t,this.setOnclick((()=>{this.menu.hidden?(this.menu.show(),this.highlight().update(),this.persist=!0):(this.menu.hide(),this.highlight(!1).update(),this.permanent||(this.persist=!1))}))):this.setOnclick(),this)}}setColor(t){return void 0!==t&&(["gray","red","orange","yellow","green","blue","purple"].includes(t)?this.color=t:this.color="gray"),this}setPermanent(t){return t=void 0===t||Boolean(t),this.permanent=t,this.permanent&&(this.persist=!0),this}shouldPersist(){return this.permanent||this.persist}setStyle(t){return void 0!==t&&(this.style=t),this}getClass(){const t=["start","middle","end"].includes(this.parent.layout.group_position)?` lz-toolbar-button-group-${this.parent.layout.group_position}`:"";return`lz-toolbar-button lz-toolbar-button-${this.color}${this.status?`-${this.status}`:""}${t}`}setStatus(t){return void 0!==t&&["","highlighted","disabled"].includes(t)&&(this.status=t),this.update()}highlight(t){return(t=void 0===t||Boolean(t))?this.setStatus("highlighted"):"highlighted"===this.status?this.setStatus(""):this}disable(t){return(t=void 0===t||Boolean(t))?this.setStatus("disabled"):"disabled"===this.status?this.setStatus(""):this}onmouseover(){}setOnMouseover(t){return this.onmouseover="function"==typeof t?t:function(){},this}onmouseout(){}setOnMouseout(t){return this.onmouseout="function"==typeof t?t:function(){},this}onclick(){}setOnclick(t){return this.onclick="function"==typeof t?t:function(){},this}setTitle(t){return void 0!==t&&(this.title=t.toString()),this}setHtml(t){return void 0!==t&&(this.html=t.toString()),this}show(){if(this.parent)return this.selector||(this.selector=this.parent.selector.append(this.tag).attr("class",this.getClass())),this.update()}preUpdate(){return this}update(){return this.selector?(this.preUpdate(),this.selector.attr("class",this.getClass()).attr("title",this.title).on("mouseover","disabled"===this.status?null:this.onmouseover).on("mouseout","disabled"===this.status?null:this.onmouseout).on("click","disabled"===this.status?null:this.onclick).html(this.html).call(et,this.style),this.menu.update(),this.postUpdate(),this):this}postUpdate(){return this}hide(){return this.selector&&!this.shouldPersist()&&(this.selector.remove(),this.selector=null),this}}class at extends st{show(){return this.div_selector||(this.div_selector=this.parent.selector.append("div").attr("class",`lz-toolbar-title lz-toolbar-${this.layout.position}`),this.title_selector=this.div_selector.append("h3")),this.update()}update(){let t=this.layout.title.toString();return this.layout.subtitle&&(t+=` ${this.layout.subtitle}`),this.title_selector.html(t),this}}class nt extends st{update(){return isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end)||null===this.parent_plot.state.start||null===this.parent_plot.state.end?this.selector.style("display","none"):(this.selector.style("display",null),this.selector.html(St(this.parent_plot.state.end-this.parent_plot.state.start,null,!0))),this.layout.class&&this.selector.attr("class",this.layout.class),this.layout.style&&et(this.selector,this.layout.style),this}}class ot extends st{constructor(t,e){if(super(t,e),!this.parent_panel)throw new Error("Filter widget can only be used in panel toolbars");if(this._data_layer=this.parent_panel.data_layers[t.layer_name],!this._data_layer)throw new Error(`Filter widget could not locate the specified layer_name: '${t.layer_name}'`);if(this._event_name=t.custom_event_name||"widget_filter_field_action",this._field=t.field,this._field_display_html=t.field_display_html,this._operator=t.operator,this._filter_id=null,this._data_type=t.data_type||"number",!["number","string"].includes(this._data_type))throw new Error("Filter must be either string or number");this._value_selector=null}_getTarget(){this._data_layer.layout.filters||(this._data_layer.layout.filters=[]);let t=this._data_layer.layout.filters.find((t=>t.field===this._field&&t.operator===this._operator&&(!this._filter_id||t.id===this._filter_id)));return t||(t={field:this._field,operator:this._operator,value:null},this._filter_id&&(t.id=this._filter_id),this._data_layer.layout.filters.push(t)),t}_clearFilter(){if(this._data_layer.layout.filters){const t=this._data_layer.layout.filters.indexOf(this._getTarget());this._data_layer.layout.filters.splice(t,1)}}_setFilter(t){if(null===t)this._value_selector.style("border","1px solid red").style("color","red"),this._clearFilter();else{this._getTarget().value=t}this.parent_svg.emit(this._event_name,{field:this._field,operator:this._operator,value:t,filter_id:this._filter_id},!0)}_getValue(){let t=this._value_selector.property("value");return null===t||""===t||"number"===this._data_type&&(t=+t,Number.isNaN(t))?null:t}update(){this._value_selector||(this.selector.style("padding","0 6px"),this.selector.append("span").html(this._field_display_html).style("background","#fff").style("padding-left","3px"),this.selector.append("span").text(this._operator).style("padding","0 3px").style("background","#fff"),this._value_selector=this.selector.append("input").attr("size",this.layout.input_size||4).on("input",function(t,e=500){let s;return()=>{clearTimeout(s),s=setTimeout((()=>t.apply(this,arguments)),e)}}((()=>{this._value_selector.style("border",null).style("color",null);const t=this._getValue();this._setFilter(t),this.parent_panel.render()}),750)))}}class rt extends st{constructor(t,e){super(t,e),this._filename=this.layout.filename||"locuszoom.svg",this._button_html=this.layout.button_html||"Save SVG",this._button_title=this.layout.button_title||"Download hi-res image",this._event_name=t.custom_event_name||"widget_save_svg"}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this._button_html).setTitle(this._button_title).setOnMouseover((()=>{this.button.selector.classed("lz-toolbar-button-gray-disabled",!0).html("Preparing Image"),this._getBlobUrl().then((t=>{const e=this.button.selector.attr("href");e&&URL.revokeObjectURL(e),this.button.selector.attr("href",t).classed("lz-toolbar-button-gray-disabled",!1).classed("lz-toolbar-button-gray-highlighted",!0).html(this._button_html)}))})).setOnMouseout((()=>{this.button.selector.classed("lz-toolbar-button-gray-highlighted",!1)})),this.button.show(),this.button.selector.attr("href-lang","image/svg+xml").attr("download",this._filename).on("click",(()=>this.parent_svg.emit(this._event_name,{filename:this._filename},!0)))),this}_getCSS(t){const e=/^svg\.lz-locuszoom\s*/;let s="";for(let t=0;t{let e=this.parent_plot.svg.node().cloneNode(!0);e.setAttribute("xlink","http://www.w3.org/1999/xlink"),e=k.select(e),e.selectAll("g.lz-curtain").remove(),e.selectAll("g.lz-mouse_guide").remove(),e.selectAll("g.tick text").each((function(){const t=10*+k.select(this).attr("dy").substring(-2).slice(0,-2);k.select(this).attr("dy",t)}));const s=new XMLSerializer;e=e.node();const[i,a]=this._getDimensions();e.setAttribute("width",i),e.setAttribute("height",a),this._appendCSS(this._getCSS(e),e),t(s.serializeToString(e))}))}_getBlobUrl(){return this._generateSVG().then((t=>{const e=new Blob([t],{type:"image/svg+xml"});return URL.createObjectURL(e)}))}}class lt extends rt{constructor(t,e){super(...arguments),this._filename=this.layout.filename||"locuszoom.png",this._button_html=this.layout.button_html||"Save PNG",this._button_title=this.layout.button_title||"Download image",this._event_name=t.custom_event_name||"widget_save_png"}_getBlobUrl(){return super._getBlobUrl().then((t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),[i,a]=this._getDimensions();return e.width=i,e.height=a,new Promise(((n,o)=>{const r=new Image;r.onload=()=>{s.drawImage(r,0,0,i,a),URL.revokeObjectURL(t),e.toBlob((t=>{n(URL.createObjectURL(t))}))},r.src=t}))}))}}class ht extends st{update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml("×").setTitle("Remove panel").setOnclick((()=>{if(!this.layout.suppress_confirm&&!confirm("Are you sure you want to remove this panel? This cannot be undone."))return!1;const t=this.parent_panel;return t.toolbar.hide(!0),k.select(t.parent.svg.node().parentNode).on(`mouseover.${t.getBaseId()}.toolbar`,null),k.select(t.parent.svg.node().parentNode).on(`mouseout.${t.getBaseId()}.toolbar`,null),t.parent.removePanel(t.id)})),this.button.show()),this}}class ct extends st{update(){if(this.button){const t=0===this.parent_panel.layout.y_index;return this.button.disable(t),this}return this.button=new it(this).setColor(this.layout.color).setHtml("▴").setTitle("Move panel up").setOnclick((()=>{this.parent_panel.moveUp(),this.update()})),this.button.show(),this.update()}}class dt extends st{update(){if(this.button){const t=this.parent_panel.layout.y_index===this.parent_plot.panel_ids_by_y_index.length-1;return this.button.disable(t),this}return this.button=new it(this).setColor(this.layout.color).setHtml("▾").setTitle("Move panel down").setOnclick((()=>{this.parent_panel.moveDown(),this.update()})),this.button.show(),this.update()}}class ut extends st{constructor(t,e){if((isNaN(t.step)||0===t.step)&&(t.step=5e4),"string"!=typeof t.button_html&&(t.button_html=t.step>0?">":"<"),"string"!=typeof t.button_title&&(t.button_title=`Shift region by ${t.step>0?"+":"-"}${St(Math.abs(t.step),null,!0)}`),super(t,e),isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end))throw new Error("Unable to add shift_region toolbar widget: plot state does not have region bounds")}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{this.parent_plot.applyState({start:Math.max(this.parent_plot.state.start+this.layout.step,1),end:this.parent_plot.state.end+this.layout.step})})),this.button.show()),this}}class pt extends st{constructor(t,e){if((isNaN(t.step)||0===t.step)&&(t.step=.2),"string"!=typeof t.button_html&&(t.button_html=t.step>0?"z–":"z+"),"string"!=typeof t.button_title&&(t.button_title=`Zoom region ${t.step>0?"out":"in"} by ${(100*Math.abs(t.step)).toFixed(1)}%`),super(t,e),isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end))throw new Error("Unable to add zoom_region toolbar widget: plot state does not have region bounds")}update(){if(this.button){let t=!0;const e=this.parent_plot.state.end-this.parent_plot.state.start;return this.layout.step>0&&!isNaN(this.parent_plot.layout.max_region_scale)&&e>=this.parent_plot.layout.max_region_scale&&(t=!1),this.layout.step<0&&!isNaN(this.parent_plot.layout.min_region_scale)&&e<=this.parent_plot.layout.min_region_scale&&(t=!1),this.button.disable(!t),this}return this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{const t=this.parent_plot.state.end-this.parent_plot.state.start;let e=t*(1+this.layout.step);isNaN(this.parent_plot.layout.max_region_scale)||(e=Math.min(e,this.parent_plot.layout.max_region_scale)),isNaN(this.parent_plot.layout.min_region_scale)||(e=Math.max(e,this.parent_plot.layout.min_region_scale));const s=Math.floor((e-t)/2);this.parent_plot.applyState({start:Math.max(this.parent_plot.state.start-s,1),end:this.parent_plot.state.end+s})})),this.button.show(),this}}class _t extends st{update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title),this.button.menu.setPopulate((()=>{this.button.menu.inner_selector.html(this.layout.menu_html)})),this.button.show()),this}}class gt extends st{constructor(t){super(...arguments)}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html||"Resize to Data").setTitle(this.layout.button_title||"Automatically resize this panel to show all data available").setOnclick((()=>{this.parent_panel.scaleHeightToData(),this.update()})),this.button.show()),this}}class yt extends st{update(){const t=this.parent_panel.legend.layout.hidden?"Show Legend":"Hide Legend";return this.button?(this.button.setHtml(t).show(),this.parent.position(),this):(this.button=new it(this).setColor(this.layout.color).setTitle("Show or hide the legend for this panel").setOnclick((()=>{this.parent_panel.legend.layout.hidden=!this.parent_panel.legend.layout.hidden,this.parent_panel.legend.render(),this.update()})),this.update())}}class mt extends st{constructor(t,e){"string"!=typeof t.button_html&&(t.button_html="Display options..."),"string"!=typeof t.button_title&&(t.button_title="Control how plot items are displayed"),super(...arguments),this._event_name=t.custom_event_name||"widget_display_options_choice";const s=t.fields_whitelist||["color","fill_opacity","filters","label","legend","point_shape","point_size","tooltip","tooltip_positioning"],i=this.parent_panel.data_layers[t.layer_name];if(!i)throw new Error(`Display options could not locate the specified layer_name: '${t.layer_name}'`);const a=i.layout,n={};s.forEach((t=>{const e=a[t];void 0!==e&&(n[t]=J(e))})),this._selected_item="default",this.button=new it(this).setColor(t.color).setHtml(t.button_html).setTitle(t.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{const t=Math.floor(1e4*Math.random()).toString();this.button.menu.inner_selector.html("");const e=this.button.menu.inner_selector.append("table"),a=this.layout,o=(a,o,r)=>{const l=e.append("tr"),h=`${t}${r}`;l.append("td").append("input").attr("id",h).attr("type","radio").attr("name",`display-option-${t}`).attr("value",r).style("margin",0).property("checked",r===this._selected_item).on("click",(()=>{s.forEach((t=>{const e=void 0!==o[t];i.layout[t]=e?o[t]:n[t]})),this.parent_svg.emit(this._event_name,{choice:a},!0),this._selected_item=r,this.parent_panel.render();const t=this.parent_panel.legend;t&&t.render()})),l.append("td").append("label").style("font-weight","normal").attr("for",h).text(a)},r=a.default_config_display_name||"Default style";return o(r,n,"default"),a.options.forEach(((t,e)=>o(t.display_name,t.display,e))),this}))}update(){return this.button.show(),this}}class ft extends st{constructor(t,e){if("string"!=typeof t.button_html&&(t.button_html="Set option..."),"string"!=typeof t.button_title&&(t.button_title="Choose an option to customize the plot"),super(t,e),this.parent_panel)throw new Error("This widget is designed to set global options, so it can only be used at the top (plot) level");if(!t.state_field)throw new Error("Must specify the `state_field` that this widget controls");if(this._event_name=t.custom_event_name||"widget_set_state_choice",this._selected_item=this.parent_plot.state[t.state_field]||t.options[0].value,!t.options.find((t=>t.value===this._selected_item)))throw new Error("There is an existing state value that does not match the known values in this widget");this.button=new it(this).setColor(t.color).setHtml(t.button_html+(t.show_selected?this._selected_item:"")).setTitle(t.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{const e=Math.floor(1e4*Math.random()).toString();this.button.menu.inner_selector.html("");const s=this.button.menu.inner_selector.append("table"),i=(i,a,n)=>{const o=s.append("tr"),r=`${e}${n}`;o.append("td").append("input").attr("id",r).attr("type","radio").attr("name",`set-state-${e}`).attr("value",n).style("margin",0).property("checked",a===this._selected_item).on("click",(()=>{const e={};e[t.state_field]=a,this._selected_item=a,this.parent_plot.applyState(e),this.button.setHtml(t.button_html+(t.show_selected?this._selected_item:"")),this.parent_svg.emit(this._event_name,{choice_name:i,choice_value:a,state_field:t.state_field},!0)})),o.append("td").append("label").style("font-weight","normal").attr("for",r).text(i)};return t.options.forEach(((t,e)=>i(t.display_name,t.value,e))),this}))}update(){return this.button.show(),this}}const bt=new c;for(let[t,e]of Object.entries(a))bt.add(t,e);const xt=bt;class vt{constructor(t){this.parent=t,this.id=`${this.parent.getBaseId()}.toolbar`,this.type=this.parent.parent?"panel":"plot",this.parent_plot=this.parent.parent_plot,this.selector=null,this.widgets=[],this.hide_timeout=null,this.persist=!1,this.initialize()}initialize(){const t=this.parent.layout.dashboard&&this.parent.layout.dashboard.components||this.parent.layout.toolbar.widgets;return Array.isArray(t)&&t.forEach((t=>{try{const e=xt.create(t.type,t,this);this.widgets.push(e)}catch(t){console.warn("Failed to create widget"),console.error(t)}})),"panel"===this.type&&k.select(this.parent.parent.svg.node().parentNode).on(`mouseover.${this.id}`,(()=>{clearTimeout(this.hide_timeout),this.selector&&"hidden"!==this.selector.style("visibility")||this.show()})).on(`mouseout.${this.id}`,(()=>{clearTimeout(this.hide_timeout),this.hide_timeout=setTimeout((()=>{this.hide()}),300)})),this}shouldPersist(){if(this.persist)return!0;let t=!1;return this.widgets.forEach((e=>{t=t||e.shouldPersist()})),t=t||this.parent_plot.panel_boundaries.dragging||this.parent_plot.interaction.dragging,!!t}show(){if(!this.selector){switch(this.type){case"plot":this.selector=k.select(this.parent.svg.node().parentNode).insert("div",":first-child");break;case"panel":this.selector=k.select(this.parent.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip, .lz-toolbar-menu, .lz-curtain").classed("lz-panel-toolbar",!0);break;default:throw new Error(`Toolbar cannot be a child of ${this.type}`)}this.selector.classed("lz-toolbar",!0).classed(`lz-${this.type}-toolbar`,!0).attr("id",this.id)}return this.widgets.forEach((t=>t.show())),this.selector.style("visibility","visible"),this.update()}update(){return this.selector?(this.widgets.forEach((t=>t.update())),this.position()):this}position(){if(!this.selector)return this;if("panel"===this.type){const t=this.parent._getPageOrigin(),e=`${(t.y+3.5).toString()}px`,s=`${t.x.toString()}px`,i=`${(this.parent_plot.layout.width-4).toString()}px`;this.selector.style("position","absolute").style("top",e).style("left",s).style("width",i)}return this.widgets.forEach((t=>t.position())),this}hide(){return!this.selector||this.shouldPersist()||(this.widgets.forEach((t=>t.hide())),this.selector.style("visibility","hidden")),this}destroy(t){return void 0===t&&(t=!1),this.selector?(this.shouldPersist()&&!t||(this.widgets.forEach((t=>t.destroy(!0))),this.widgets=[],this.selector.remove(),this.selector=null),this):this}}const wt={orientation:"vertical",origin:{x:0,y:0},width:10,height:10,padding:5,label_size:12,hidden:!1};class zt{constructor(t){return this.parent=t,this.id=`${this.parent.getBaseId()}.legend`,this.parent.layout.legend=Z(this.parent.layout.legend||{},wt),this.layout=this.parent.layout.legend,this.selector=null,this.background_rect=null,this.elements=[],this.elements_group=null,this.hidden=!1,this.render()}render(){this.selector||(this.selector=this.parent.svg.group.append("g").attr("id",`${this.parent.getBaseId()}.legend`).attr("class","lz-legend")),this.background_rect||(this.background_rect=this.selector.append("rect").attr("width",100).attr("height",100).attr("class","lz-legend-background")),this.elements_group||(this.elements_group=this.selector.append("g")),this.elements.forEach((t=>t.remove())),this.elements=[];const t=+this.layout.padding||1;let e=t,s=t,i=0;this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((a=>{Array.isArray(this.parent.data_layers[a].layout.legend)&&this.parent.data_layers[a].layout.legend.forEach((a=>{const n=this.elements_group.append("g").attr("transform",`translate(${e}, ${s})`),o=+a.label_size||+this.layout.label_size||12;let r=0,l=o/2+t/2;i=Math.max(i,o+t);const h=a.shape||"",c=K(h);if("line"===h){const e=+a.length||16,s=o/4+t/2;n.append("path").attr("class",a.class||"").attr("d",`M0,${s}L${e},${s}`).call(et,a.style||{}),r=e+t}else if("rect"===h){const e=+a.width||16,s=+a.height||e;n.append("rect").attr("class",a.class||"").attr("width",e).attr("height",s).attr("fill",a.color||{}).call(et,a.style||{}),r=e+t,i=Math.max(i,s+t)}else if(c){const e=+a.size||40,s=Math.ceil(Math.sqrt(e/Math.PI));n.append("path").attr("class",a.class||"").attr("d",k.symbol().size(e).type(c)).attr("transform",`translate(${s}, ${s+t/2})`).attr("fill",a.color||{}).call(et,a.style||{}),r=2*s+t,l=Math.max(2*s+t/2,l),i=Math.max(i,2*s+t)}n.append("text").attr("text-anchor","left").attr("class","lz-label").attr("x",r).attr("y",l).style("font-size",o).text(a.label);const d=n.node().getBoundingClientRect();if("vertical"===this.layout.orientation)s+=d.height+t,i=0;else{const a=this.layout.origin.x+e+d.width;e>t&&a>this.parent.parent.layout.width&&(s+=i,e=t,n.attr("transform",`translate(${e}, ${s})`)),e+=d.width+3*t}this.elements.push(n)}))}));const a=this.elements_group.node().getBoundingClientRect();return this.layout.width=a.width+2*this.layout.padding,this.layout.height=a.height+2*this.layout.padding,this.background_rect.attr("width",this.layout.width).attr("height",this.layout.height),this.selector.style("visibility",this.layout.hidden?"hidden":"visible"),this.position()}position(){if(!this.selector)return this;const t=this.selector.node().getBoundingClientRect();isNaN(+this.layout.pad_from_bottom)||(this.layout.origin.y=this.parent.layout.height-t.height-+this.layout.pad_from_bottom),isNaN(+this.layout.pad_from_right)||(this.layout.origin.x=this.parent.parent.layout.width-t.width-+this.layout.pad_from_right),this.selector.attr("transform",`translate(${this.layout.origin.x}, ${this.layout.origin.y})`)}hide(){this.layout.hidden=!0,this.render()}show(){this.layout.hidden=!1,this.render()}}const $t={id:"",tag:"custom_data_type",title:{text:"",style:{},x:10,y:22},y_index:null,min_height:1,height:1,origin:{x:0,y:null},margin:{top:0,right:0,bottom:0,left:0},background_click:"clear_selections",toolbar:{widgets:[]},cliparea:{height:0,width:0,origin:{x:0,y:0}},axes:{x:{},y1:{},y2:{}},legend:null,interaction:{drag_background_to_pan:!1,drag_x_ticks_to_scale:!1,drag_y1_ticks_to_scale:!1,drag_y2_ticks_to_scale:!1,scroll_to_zoom:!1,x_linked:!1,y1_linked:!1,y2_linked:!1},show_loading_indicator:!0,data_layers:[]};class kt{constructor(t,e){if("object"!=typeof t)throw new Error("Unable to create panel, invalid layout");if(this.parent=e||null,this.parent_plot=e,"string"==typeof t.id&&t.id.length){if(this.parent&&void 0!==this.parent.panels[t.id])throw new Error(`Cannot create panel with id [${t.id}]; panel with that id already exists`)}else if(this.parent){const e=()=>{let t=`p${Math.floor(Math.random()*Math.pow(10,8))}`;return null!==t&&void 0===this.parent.panels[t]||(t=e()),t};t.id=e()}else t.id=`p${Math.floor(Math.random()*Math.pow(10,8))}`;this.id=t.id,this.initialized=!1,this.layout_idx=null,this.svg={},this.layout=Z(t||{},$t),this.parent?(this.state=this.parent.state,this.state_id=this.id,this.state[this.state_id]=this.state[this.state_id]||{}):(this.state=null,this.state_id=null),this.data_layers={},this.data_layer_ids_by_z_index=[],this.data_promises=[],this.x_scale=null,this.y1_scale=null,this.y2_scale=null,this.x_extent=null,this.y1_extent=null,this.y2_extent=null,this.x_ticks=[],this.y1_ticks=[],this.y2_ticks=[],this.zoom_timeout=null,this.event_hooks={},this.initializeLayout()}on(t,e){if("string"!=typeof t)throw new Error(`Unable to register event hook. Event name must be a string: ${t.toString()}`);if("function"!=typeof e)throw new Error("Unable to register event hook, invalid hook function passed");return this.event_hooks[t]||(this.event_hooks[t]=[]),this.event_hooks[t].push(e),e}off(t,e){const s=this.event_hooks[t];if("string"!=typeof t||!Array.isArray(s))throw new Error(`Unable to remove event hook, invalid event: ${t.toString()}`);if(void 0===e)this.event_hooks[t]=[];else{const t=s.indexOf(e);if(-1===t)throw new Error("The specified event listener is not registered and therefore cannot be removed");s.splice(t,1)}return this}emit(t,e,s){if(s=s||!1,"string"!=typeof t)throw new Error(`LocusZoom attempted to throw an invalid event: ${t.toString()}`);"boolean"==typeof e&&2===arguments.length&&(s=e,e=null);const i={sourceID:this.getBaseId(),target:this,data:e||null};return this.event_hooks[t]&&this.event_hooks[t].forEach((t=>{t.call(this,i)})),s&&this.parent&&this.parent.emit(t,i),this}setTitle(t){if("string"==typeof this.layout.title){const t=this.layout.title;this.layout.title={text:t,x:0,y:0,style:{}}}return"string"==typeof t?this.layout.title.text=t:"object"==typeof t&&null!==t&&(this.layout.title=Z(t,this.layout.title)),this.layout.title.text.length?this.title.attr("display",null).attr("x",parseFloat(this.layout.title.x)).attr("y",parseFloat(this.layout.title.y)).text(this.layout.title.text).call(et,this.layout.title.style):this.title.attr("display","none"),this}addDataLayer(t){if("object"!=typeof t||"string"!=typeof t.id||!t.id.length)throw new Error("Invalid data layer layout");if(void 0!==this.data_layers[t.id])throw new Error(`Cannot create data_layer with id [${t.id}]; data layer with that id already exists in the panel`);if("string"!=typeof t.type)throw new Error("Invalid data layer type");"object"!=typeof t.y_axis||void 0!==t.y_axis.axis&&[1,2].includes(t.y_axis.axis)||(t.y_axis.axis=1);const e=ne.create(t.type,t,this);if(this.data_layers[e.id]=e,null!==e.layout.z_index&&!isNaN(e.layout.z_index)&&this.data_layer_ids_by_z_index.length>0)e.layout.z_index<0&&(e.layout.z_index=Math.max(this.data_layer_ids_by_z_index.length+e.layout.z_index,0)),this.data_layer_ids_by_z_index.splice(e.layout.z_index,0,e.id),this.data_layer_ids_by_z_index.forEach(((t,e)=>{this.data_layers[t].layout.z_index=e}));else{const t=this.data_layer_ids_by_z_index.push(e.id);this.data_layers[e.id].layout.z_index=t-1}let s=null;return this.layout.data_layers.forEach(((t,i)=>{t.id===e.id&&(s=i)})),null===s&&(s=this.layout.data_layers.push(this.data_layers[e.id].layout)-1),this.data_layers[e.id].layout_idx=s,this.data_layers[e.id]}removeDataLayer(t){if(!this.data_layers[t])throw new Error(`Unable to remove data layer, ID not found: ${t}`);return this.data_layers[t].destroyAllTooltips(),this.data_layers[t].svg.container&&this.data_layers[t].svg.container.remove(),this.layout.data_layers.splice(this.data_layers[t].layout_idx,1),delete this.state[this.data_layers[t].state_id],delete this.data_layers[t],this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(t),1),this.applyDataLayerZIndexesToDataLayerLayouts(),this.layout.data_layers.forEach(((t,e)=>{this.data_layers[t.id].layout_idx=e})),this}clearSelections(){return this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].setAllElementStatus("selected",!1)})),this}render(){this.svg.container.attr("transform",`translate(${this.layout.origin.x}, ${this.layout.origin.y})`),this.svg.clipRect.attr("width",this.parent_plot.layout.width).attr("height",this.layout.height),this.inner_border.attr("x",this.layout.margin.left).attr("y",this.layout.margin.top).attr("width",this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right)).attr("height",this.layout.height-(this.layout.margin.top+this.layout.margin.bottom)),this.layout.inner_border&&this.inner_border.style("stroke-width",1).style("stroke",this.layout.inner_border),this.setTitle(),this.generateExtents();const t=function(t,e){const s=Math.pow(-10,e),i=Math.pow(-10,-e),a=Math.pow(10,-e),n=Math.pow(10,e);return t===1/0&&(t=n),t===-1/0&&(t=s),0===t&&(t=a),t>0&&(t=Math.max(Math.min(t,n),a)),t<0&&(t=Math.max(Math.min(t,i),s)),t},e={};if(this.x_extent){const t={start:0,end:this.layout.cliparea.width};this.layout.axes.x.range&&(t.start=this.layout.axes.x.range.start||t.start,t.end=this.layout.axes.x.range.end||t.end),e.x=[t.start,t.end],e.x_shifted=[t.start,t.end]}if(this.y1_extent){const t={start:this.layout.cliparea.height,end:0};this.layout.axes.y1.range&&(t.start=this.layout.axes.y1.range.start||t.start,t.end=this.layout.axes.y1.range.end||t.end),e.y1=[t.start,t.end],e.y1_shifted=[t.start,t.end]}if(this.y2_extent){const t={start:this.layout.cliparea.height,end:0};this.layout.axes.y2.range&&(t.start=this.layout.axes.y2.range.start||t.start,t.end=this.layout.axes.y2.range.end||t.end),e.y2=[t.start,t.end],e.y2_shifted=[t.start,t.end]}if(this.parent.interaction.panel_id&&(this.parent.interaction.panel_id===this.id||this.parent.interaction.linked_panel_ids.includes(this.id))){let s,i=null;if(this.parent.interaction.zooming&&"function"==typeof this.x_scale){const t=Math.abs(this.x_extent[1]-this.x_extent[0]),i=Math.round(this.x_scale.invert(e.x_shifted[1]))-Math.round(this.x_scale.invert(e.x_shifted[0]));let a=this.parent.interaction.zooming.scale;const n=Math.floor(i*(1/a));a<1&&!isNaN(this.parent.layout.max_region_scale)?a=1/(Math.min(n,this.parent.layout.max_region_scale)/i):a>1&&!isNaN(this.parent.layout.min_region_scale)&&(a=1/(Math.max(n,this.parent.layout.min_region_scale)/i));const o=Math.floor(t*a);s=this.parent.interaction.zooming.center-this.layout.margin.left-this.layout.origin.x;const r=s/this.layout.cliparea.width,l=Math.max(Math.floor(this.x_scale.invert(e.x_shifted[0])-(o-i)*r),1);e.x_shifted=[this.x_scale(l),this.x_scale(l+o)]}else if(this.parent.interaction.dragging)switch(this.parent.interaction.dragging.method){case"background":e.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,e.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x;break;case"x_tick":k.event&&k.event.shiftKey?(e.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,e.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x):(s=this.parent.interaction.dragging.start_x-this.layout.margin.left-this.layout.origin.x,i=t(s/(s+this.parent.interaction.dragging.dragged_x),3),e.x_shifted[0]=0,e.x_shifted[1]=Math.max(this.layout.cliparea.width*(1/i),1));break;case"y1_tick":case"y2_tick":{const a=`y${this.parent.interaction.dragging.method[1]}_shifted`;k.event&&k.event.shiftKey?(e[a][0]=this.layout.cliparea.height+this.parent.interaction.dragging.dragged_y,e[a][1]=+this.parent.interaction.dragging.dragged_y):(s=this.layout.cliparea.height-(this.parent.interaction.dragging.start_y-this.layout.margin.top-this.layout.origin.y),i=t(s/(s-this.parent.interaction.dragging.dragged_y),3),e[a][0]=this.layout.cliparea.height,e[a][1]=this.layout.cliparea.height-this.layout.cliparea.height*(1/i))}}}if(["x","y1","y2"].forEach((t=>{this[`${t}_extent`]&&(this[`${t}_scale`]=k.scaleLinear().domain(this[`${t}_extent`]).range(e[`${t}_shifted`]),this[`${t}_extent`]=[this[`${t}_scale`].invert(e[t][0]),this[`${t}_scale`].invert(e[t][1])],this[`${t}_scale`]=k.scaleLinear().domain(this[`${t}_extent`]).range(e[t]),this.renderAxis(t))})),this.layout.interaction.scroll_to_zoom){const t=()=>{if(!k.event.shiftKey&&!k.event.altKey)return void(this.parent._canInteract(this.id)&&this.loader.show("Press [SHIFT] or [ALT] while scrolling to zoom").hide(1e3));if(k.event.preventDefault(),!this.parent._canInteract(this.id))return;const t=k.mouse(this.svg.container.node()),e=Math.max(-1,Math.min(1,k.event.wheelDelta||-k.event.detail||-k.event.deltaY));0!==e&&(this.parent.interaction={panel_id:this.id,linked_panel_ids:this.getLinkedPanelIds("x"),zooming:{scale:e<1?.9:1.1,center:t[0]}},this.render(),this.parent.interaction.linked_panel_ids.forEach((t=>{this.parent.panels[t].render()})),null!==this.zoom_timeout&&clearTimeout(this.zoom_timeout),this.zoom_timeout=setTimeout((()=>{this.parent.interaction={},this.parent.applyState({start:this.x_extent[0],end:this.x_extent[1]})}),500))};this.svg.container.on("wheel.zoom",t).on("mousewheel.zoom",t).on("DOMMouseScroll.zoom",t)}return this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].draw().render()})),this.legend&&this.legend.render(),this}addBasicLoader(t=!0){return this.layout.show_loading_indicator&&this.initialized||(t&&this.loader.show("Loading...").animate(),this.on("data_requested",(()=>{this.loader.show("Loading...").animate()})),this.on("data_rendered",(()=>{this.loader.hide()})),this.layout.show_loading_indicator=!0),this}applyDataLayerZIndexesToDataLayerLayouts(){this.data_layer_ids_by_z_index.forEach(((t,e)=>{this.data_layers[t].layout.z_index=e}))}getBaseId(){return`${this.parent.id}.${this.id}`}_getPageOrigin(){const t=this.parent._getPageOrigin();return{x:t.x+this.layout.origin.x,y:t.y+this.layout.origin.y}}initializeLayout(){return this.setDimensions(),this.setOrigin(),this.setMargin(),this.x_range=[0,this.layout.cliparea.width],this.y1_range=[this.layout.cliparea.height,0],this.y2_range=[this.layout.cliparea.height,0],["x","y1","y2"].forEach((t=>{Object.keys(this.layout.axes[t]).length&&!1!==this.layout.axes[t].render?(this.layout.axes[t].render=!0,this.layout.axes[t].label=this.layout.axes[t].label||null):this.layout.axes[t].render=!1})),this.layout.data_layers.forEach((t=>{this.addDataLayer(t)})),this}setDimensions(t,e){return void 0!==t&&void 0!==e&&!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0&&(this.parent.layout.width=Math.round(+t),this.layout.height=Math.max(Math.round(+e),this.layout.min_height)),this.layout.cliparea.width=Math.max(this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.svg.clipRect&&this.svg.clipRect.attr("width",this.parent.layout.width).attr("height",this.layout.height),this.initialized&&(this.render(),this.curtain.update(),this.loader.update(),this.toolbar.update(),this.legend&&this.legend.position()),this}setOrigin(t,e){return!isNaN(t)&&t>=0&&(this.layout.origin.x=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.origin.y=Math.max(Math.round(+e),0)),this.initialized&&this.render(),this}setMargin(t,e,s,i){let a;return!isNaN(t)&&t>=0&&(this.layout.margin.top=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.margin.right=Math.max(Math.round(+e),0)),!isNaN(s)&&s>=0&&(this.layout.margin.bottom=Math.max(Math.round(+s),0)),!isNaN(i)&&i>=0&&(this.layout.margin.left=Math.max(Math.round(+i),0)),this.layout.margin.top+this.layout.margin.bottom>this.layout.height&&(a=Math.floor((this.layout.margin.top+this.layout.margin.bottom-this.layout.height)/2),this.layout.margin.top-=a,this.layout.margin.bottom-=a),this.layout.margin.left+this.layout.margin.right>this.parent_plot.layout.width&&(a=Math.floor((this.layout.margin.left+this.layout.margin.right-this.parent_plot.layout.width)/2),this.layout.margin.left-=a,this.layout.margin.right-=a),["top","right","bottom","left"].forEach((t=>{this.layout.margin[t]=Math.max(this.layout.margin[t],0)})),this.layout.cliparea.width=Math.max(this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.layout.cliparea.origin.x=this.layout.margin.left,this.layout.cliparea.origin.y=this.layout.margin.top,this.initialized&&this.render(),this}initialize(){const t=this.getBaseId();this.svg.container=this.parent.svg.append("g").attr("id",`${t}.panel_container`).attr("transform",`translate(${this.layout.origin.x||0}, ${this.layout.origin.y||0})`);const e=this.svg.container.append("clipPath").attr("id",`${t}.clip`);if(this.svg.clipRect=e.append("rect").attr("width",this.parent_plot.layout.width).attr("height",this.layout.height),this.svg.group=this.svg.container.append("g").attr("id",`${t}.panel`).attr("clip-path",`url(#${t}.clip)`),this.curtain=Q.call(this),this.loader=tt.call(this),this.layout.show_loading_indicator&&this.addBasicLoader(!1),this.toolbar=new vt(this),this.inner_border=this.svg.group.append("rect").attr("class","lz-panel-background").on("click",(()=>{"clear_selections"===this.layout.background_click&&this.clearSelections()})),this.title=this.svg.group.append("text").attr("class","lz-panel-title"),void 0!==this.layout.title&&this.setTitle(),this.svg.x_axis=this.svg.group.append("g").attr("id",`${t}.x_axis`).attr("class","lz-x lz-axis"),this.layout.axes.x.render&&(this.svg.x_axis_label=this.svg.x_axis.append("text").attr("class","lz-x lz-axis lz-label").attr("text-anchor","middle")),this.svg.y1_axis=this.svg.group.append("g").attr("id",`${t}.y1_axis`).attr("class","lz-y lz-y1 lz-axis"),this.layout.axes.y1.render&&(this.svg.y1_axis_label=this.svg.y1_axis.append("text").attr("class","lz-y1 lz-axis lz-label").attr("text-anchor","middle")),this.svg.y2_axis=this.svg.group.append("g").attr("id",`${t}.y2_axis`).attr("class","lz-y lz-y2 lz-axis"),this.layout.axes.y2.render&&(this.svg.y2_axis_label=this.svg.y2_axis.append("text").attr("class","lz-y2 lz-axis lz-label").attr("text-anchor","middle")),this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].initialize()})),this.legend=null,this.layout.legend&&(this.legend=new zt(this)),this.layout.interaction.drag_background_to_pan){const t=`.${this.parent.id}.${this.id}.interaction.drag`,e=()=>this.parent.startDrag(this,"background");this.svg.container.select(".lz-panel-background").on(`mousedown${t}.background`,e).on(`touchstart${t}.background`,e)}return this}resortDataLayers(){const t=[];this.data_layer_ids_by_z_index.forEach((e=>{t.push(this.data_layers[e].layout.z_index)})),this.svg.group.selectAll("g.lz-data_layer-container").data(t).sort(k.ascending),this.applyDataLayerZIndexesToDataLayerLayouts()}getLinkedPanelIds(t){const e=[];return["x","y1","y2"].includes(t=t||null)&&this.layout.interaction[`${t}_linked`]?(this.parent.panel_ids_by_y_index.forEach((s=>{s!==this.id&&this.parent.panels[s].layout.interaction[`${t}_linked`]&&e.push(s)})),e):e}moveUp(){return this.parent.panel_ids_by_y_index[this.layout.y_index-1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index-1],this.parent.panel_ids_by_y_index[this.layout.y_index-1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}moveDown(){return this.parent.panel_ids_by_y_index[this.layout.y_index+1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index+1],this.parent.panel_ids_by_y_index[this.layout.y_index+1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}reMap(){this.emit("data_requested"),this.data_promises=[],this.curtain.hide();for(let t in this.data_layers)try{this.data_promises.push(this.data_layers[t].reMap())}catch(t){console.error(t),this.curtain.show(t.message||t)}return Promise.all(this.data_promises).then((()=>{this.initialized=!0,this.render(),this.emit("layout_changed",!0),this.emit("data_rendered")})).catch((t=>{console.error(t),this.curtain.show(t.message||t)}))}generateExtents(){["x","y1","y2"].forEach((t=>{this[`${t}_extent`]=null}));for(let t in this.data_layers){const e=this.data_layers[t];if(e.layout.x_axis&&!e.layout.x_axis.decoupled&&(this.x_extent=k.extent((this.x_extent||[]).concat(e.getAxisExtent("x")))),e.layout.y_axis&&!e.layout.y_axis.decoupled){const t=`y${e.layout.y_axis.axis}`;this[`${t}_extent`]=k.extent((this[`${t}_extent`]||[]).concat(e.getAxisExtent("y")))}}return this.layout.axes.x&&"state"===this.layout.axes.x.extent&&(this.x_extent=[this.state.start,this.state.end]),this}generateTicks(t){if(this.layout.axes[t].ticks){const e=this.layout.axes[t].ticks;if(Array.isArray(e))return e;if("object"==typeof e){const s=this,i={position:e.position};return this.data_layer_ids_by_z_index.reduce(((e,a)=>{const n=s.data_layers[a];return e.concat(n.getTicks(t,i))}),[]).map((t=>{let s={};return s=Z(s,e),Z(s,t)}))}}return this[`${t}_extent`]?function(t,e,s){(void 0===s||isNaN(parseInt(s)))&&(s=5);const i=(s=+s)/3,a=.75,n=1.5,o=.5+1.5*n,r=Math.abs(t[0]-t[1]);let l=r/s;Math.log(r)/Math.LN10<-2&&(l=Math.max(Math.abs(r))*a/i);const h=Math.pow(10,Math.floor(Math.log(l)/Math.LN10));let c=0;h<1&&0!==h&&(c=Math.abs(Math.round(Math.log(h)/Math.LN10)));let d=h;2*h-l0&&(p=parseFloat(p.toFixed(c)));u.push(p),(void 0===e||-1===["low","high","both","neither"].indexOf(e))&&(e="neither");"low"!==e&&"both"!==e||u[0]t[1]&&u.pop();return u}(this[`${t}_extent`],"both"):[]}renderAxis(t){if(!["x","y1","y2"].includes(t))throw new Error(`Unable to render axis; invalid axis identifier: ${t}`);const e=this.layout.axes[t].render&&"function"==typeof this[`${t}_scale`]&&!isNaN(this[`${t}_scale`](0));if(this[`${t}_axis`]&&this.svg.container.select(`g.lz-axis.lz-${t}`).style("display",e?null:"none"),!e)return this;const s={x:{position:`translate(${this.layout.margin.left}, ${this.layout.height-this.layout.margin.bottom})`,orientation:"bottom",label_x:this.layout.cliparea.width/2,label_y:this.layout.axes[t].label_offset||0,label_rotate:null},y1:{position:`translate(${this.layout.margin.left}, ${this.layout.margin.top})`,orientation:"left",label_x:-1*(this.layout.axes[t].label_offset||0),label_y:this.layout.cliparea.height/2,label_rotate:-90},y2:{position:`translate(${this.parent_plot.layout.width-this.layout.margin.right}, ${this.layout.margin.top})`,orientation:"right",label_x:this.layout.axes[t].label_offset||0,label_y:this.layout.cliparea.height/2,label_rotate:-90}};this[`${t}_ticks`]=this.generateTicks(t);const i=(t=>{for(let e=0;eSt(t,6)));else{let e=this[`${t}_ticks`].map((e=>e[t.substr(0,1)]));this[`${t}_axis`].tickValues(e).tickFormat(((e,s)=>this[`${t}_ticks`][s].text))}if(this.svg[`${t}_axis`].attr("transform",s[t].position).call(this[`${t}_axis`]),!i){const e=k.selectAll(`g#${this.getBaseId().replace(".","\\.")}\\.${t}_axis g.tick`),s=this;e.each((function(e,i){const a=k.select(this).select("text");s[`${t}_ticks`][i].style&&et(a,s[`${t}_ticks`][i].style),s[`${t}_ticks`][i].transform&&a.attr("transform",s[`${t}_ticks`][i].transform)}))}const n=this.layout.axes[t].label||null;return null!==n&&(this.svg[`${t}_axis_label`].attr("x",s[t].label_x).attr("y",s[t].label_y).text(Tt(n,this.state)).attr("fill","currentColor"),null!==s[t].label_rotate&&this.svg[`${t}_axis_label`].attr("transform",`rotate(${s[t].label_rotate} ${s[t].label_x}, ${s[t].label_y})`)),["x","y1","y2"].forEach((t=>{if(this.layout.interaction[`drag_${t}_ticks_to_scale`]){const e=`.${this.parent.id}.${this.id}.interaction.drag`,s=function(){"function"==typeof k.select(this).node().focus&&k.select(this).node().focus();let i="x"===t?"ew-resize":"ns-resize";k.event&&k.event.shiftKey&&(i="move"),k.select(this).style("font-weight","bold").style("cursor",i).on(`keydown${e}`,s).on(`keyup${e}`,s)};this.svg.container.selectAll(`.lz-axis.lz-${t} .tick text`).attr("tabindex",0).on(`mouseover${e}`,s).on(`mouseout${e}`,(function(){k.select(this).style("font-weight","normal").on(`keydown${e}`,null).on(`keyup${e}`,null)})).on(`mousedown${e}`,(()=>{this.parent.startDrag(this,`${t}_tick`)}))}})),this}scaleHeightToData(t){null===(t=+t||null)&&this.data_layer_ids_by_z_index.forEach((e=>{const s=this.data_layers[e].getAbsoluteDataHeight();+s&&(t=null===t?+s:Math.max(t,+s))})),+t&&(t+=+this.layout.margin.top+ +this.layout.margin.bottom,this.setDimensions(this.parent_plot.layout.width,t),this.parent.setDimensions(),this.parent.positionPanels())}setAllElementStatus(t,e){this.data_layer_ids_by_z_index.forEach((s=>{this.data_layers[s].setAllElementStatus(t,e)}))}}E.verbs.forEach(((t,e)=>{const s=E.adjectives[e],i=`un${t}`;kt.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},kt.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const Et={state:{},width:800,min_width:400,min_region_scale:null,max_region_scale:null,responsive_resize:!1,panels:[],toolbar:{widgets:[]},panel_boundaries:!0,mouse_guide:!0};class Mt{constructor(t,e,s){this.initialized=!1,this.parent_plot=this,this.id=t,this.container=null,this.svg=null,this.panels={},this.panel_ids_by_y_index=[],this.remap_promises=[],this.layout=s,Z(this.layout,Et),this._base_layout=J(this.layout),this.state=this.layout.state,this.lzd=new X(e),this._external_listeners=new Map,this.event_hooks={},this.interaction={},this.initializeLayout()}on(t,e){if("string"!=typeof t)throw new Error(`Unable to register event hook. Event name must be a string: ${t.toString()}`);if("function"!=typeof e)throw new Error("Unable to register event hook, invalid hook function passed");return this.event_hooks[t]||(this.event_hooks[t]=[]),this.event_hooks[t].push(e),e}off(t,e){const s=this.event_hooks[t];if("string"!=typeof t||!Array.isArray(s))throw new Error(`Unable to remove event hook, invalid event: ${t.toString()}`);if(void 0===e)this.event_hooks[t]=[];else{const t=s.indexOf(e);if(-1===t)throw new Error("The specified event listener is not registered and therefore cannot be removed");s.splice(t,1)}return this}emit(t,e){const s=this.event_hooks[t];if("string"!=typeof t)throw new Error(`LocusZoom attempted to throw an invalid event: ${t.toString()}`);if(!s&&!this.event_hooks.any_lz_event)return this;const i=this.getBaseId();let a;if(a=e&&e.sourceID?e:{sourceID:i,target:this,data:e||null},s&&s.forEach((t=>{t.call(this,a)})),"any_lz_event"!==t){const e=Object.assign({event_name:t},a);this.emit("any_lz_event",e)}return this}addPanel(t){if("object"!=typeof t)throw new Error("Invalid panel layout");const e=new kt(t,this);if(this.panels[e.id]=e,null!==e.layout.y_index&&!isNaN(e.layout.y_index)&&this.panel_ids_by_y_index.length>0)e.layout.y_index<0&&(e.layout.y_index=Math.max(this.panel_ids_by_y_index.length+e.layout.y_index,0)),this.panel_ids_by_y_index.splice(e.layout.y_index,0,e.id),this.applyPanelYIndexesToPanelLayouts();else{const t=this.panel_ids_by_y_index.push(e.id);this.panels[e.id].layout.y_index=t-1}let s=null;return this.layout.panels.forEach(((t,i)=>{t.id===e.id&&(s=i)})),null===s&&(s=this.layout.panels.push(this.panels[e.id].layout)-1),this.panels[e.id].layout_idx=s,this.initialized&&(this.positionPanels(),this.panels[e.id].initialize(),this.panels[e.id].reMap(),this.setDimensions(this.layout.width,this._total_height)),this.panels[e.id]}clearPanelData(t,e){let s;return e=e||"wipe",s=t?[t]:Object.keys(this.panels),s.forEach((t=>{this.panels[t].data_layer_ids_by_z_index.forEach((s=>{const i=this.panels[t].data_layers[s];i.destroyAllTooltips(),delete i.layer_state,delete this.layout.state[i.state_id],"reset"===e&&i._setDefaultState()}))})),this}removePanel(t){if(!this.panels[t])throw new Error(`Unable to remove panel, ID not found: ${t}`);return this.panel_boundaries.hide(),this.clearPanelData(t),this.panels[t].loader.hide(),this.panels[t].toolbar.destroy(!0),this.panels[t].curtain.hide(),this.panels[t].svg.container&&this.panels[t].svg.container.remove(),this.layout.panels.splice(this.panels[t].layout_idx,1),delete this.panels[t],delete this.layout.state[t],this.layout.panels.forEach(((t,e)=>{this.panels[t.id].layout_idx=e})),this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(t),1),this.applyPanelYIndexesToPanelLayouts(),this.initialized&&(this.positionPanels(),this.setDimensions(this.layout.width,this._total_height)),this.emit("panel_removed",t),this}refresh(){return this.applyState()}subscribeToData(t,e,s){const i=(s=s||{}).onerror||function(t){console.log("An error occurred while acting on an external callback",t)},a=()=>{try{this.lzd.getData(this.state,t).then((t=>e(s.discrete?t.discrete:t.body,this))).catch(i)}catch(t){i(t)}};return this.on("data_rendered",a),a}applyState(t){if("object"!=typeof(t=t||{}))throw new Error(`applyState only accepts an object; ${typeof t} given`);let e={chr:this.state.chr,start:this.state.start,end:this.state.end};for(let s in t)e[s]=t[s];e=function(t,e){e=e||{};let s,i=!1,a=null;if(void 0!==(t=t||{}).chr&&void 0!==t.start&&void 0!==t.end){if(t.start=Math.max(parseInt(t.start),1),t.end=Math.max(parseInt(t.end),1),isNaN(t.start)&&isNaN(t.end))t.start=1,t.end=1,a=.5,s=0;else if(isNaN(t.start)||isNaN(t.end))a=t.start||t.end,s=0,t.start=isNaN(t.start)?t.end:t.start,t.end=isNaN(t.end)?t.start:t.end;else{if(a=Math.round((t.start+t.end)/2),s=t.end-t.start,s<0){const e=t.start;t.end=t.start,t.start=e,s=t.end-t.start}a<0&&(t.start=1,t.end=1,s=0)}i=!0}return e.min_region_scale&&i&&se.max_region_scale&&(t.start=Math.max(a-Math.floor(e.max_region_scale/2),1),t.end=t.start+e.max_region_scale),t}(e,this.layout);for(let t in e)this.state[t]=e[t];this.emit("data_requested"),this.remap_promises=[],this.loading_data=!0;for(let t in this.panels)this.remap_promises.push(this.panels[t].reMap());return Promise.all(this.remap_promises).catch((t=>{console.error(t),this.curtain.show(t.message||t),this.loading_data=!1})).then((()=>{this.toolbar.update(),this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t];e.toolbar.update(),e.data_layer_ids_by_z_index.forEach((t=>{e.data_layers[t].applyAllElementStatus()}))})),this.emit("layout_changed"),this.emit("data_rendered"),this.emit("state_changed",t);const{chr:e,start:s,end:i}=this.state;Object.keys(t).some((t=>["chr","start","end"].includes(t)))&&this.emit("region_changed",{chr:e,start:s,end:i}),this.loading_data=!1}))}trackExternalListener(t,e,s){this._external_listeners.has(t)||this._external_listeners.set(t,new Map);const i=this._external_listeners.get(t),a=i.get(e)||[];a.includes(s)||a.push(s),i.set(e,a)}destroy(){for(let[t,e]of this._external_listeners.entries())for(let[s,i]of e)for(let e of i)t.removeEventListener(s,e);const t=this.svg.node().parentNode;if(!t)throw new Error("Plot has already been removed");for(;t.lastElementChild;)t.removeChild(t.lastElementChild);t.outerHTML=t.outerHTML,this.initialized=!1,this.svg=null,this.panels=null}_canInteract(t){return(t=t||null)?(void 0===this.interaction.panel_id||this.interaction.panel_id===t)&&!this.loading_data:!(this.interaction.dragging||this.interaction.zooming||this.loading_data)}_getPageOrigin(){const t=this.svg.node().getBoundingClientRect();let e=document.documentElement.scrollLeft||document.body.scrollLeft,s=document.documentElement.scrollTop||document.body.scrollTop,i=this.svg.node();for(;null!==i.parentNode;)if(i=i.parentNode,i!==document&&"static"!==k.select(i).style("position")){e=-1*i.getBoundingClientRect().left,s=-1*i.getBoundingClientRect().top;break}return{x:e+t.left,y:s+t.top,width:t.width,height:t.height}}getContainerOffset(){const t={top:0,left:0};let e=this.container.offsetParent||null;for(;null!==e;)t.top+=e.offsetTop,t.left+=e.offsetLeft,e=e.offsetParent||null;return t}applyPanelYIndexesToPanelLayouts(){this.panel_ids_by_y_index.forEach(((t,e)=>{this.panels[t].layout.y_index=e}))}getBaseId(){return this.id}rescaleSVG(){const t=this.svg.node().getBoundingClientRect();return this.setDimensions(t.width,t.height),this}initializeLayout(){if(isNaN(this.layout.width)||this.layout.width<=0)throw new Error("Plot layout parameter `width` must be a positive number");if(this.layout.responsive_resize=!!this.layout.responsive_resize,this.layout.responsive_resize){const t=()=>this.rescaleSVG();window.addEventListener("resize",t),this.trackExternalListener(window,"resize",t);const e=()=>this.setDimensions();window.addEventListener("load",e),this.trackExternalListener(window,"load",e)}return this.layout.panels.forEach((t=>{this.addPanel(t)})),this}setDimensions(t,e){if(!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0){const s=e/this._total_height;this.layout.width=Math.max(Math.round(+t),this.layout.min_width),this.layout.responsive_resize&&this.svg&&(this.layout.width=Math.max(this.svg.node().parentNode.getBoundingClientRect().width,this.layout.min_width));let i=0;this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t],a=this.layout.width,n=e.layout.height*s;e.setDimensions(a,n),e.setOrigin(0,i),i+=n,e.toolbar.update()}))}const s=this._total_height;return null!==this.svg&&(this.svg.attr("viewBox",`0 0 ${this.layout.width} ${s}`),this.svg.attr("width",this.layout.width).attr("height",s)),this.initialized&&(this.panel_boundaries.position(),this.toolbar.update(),this.curtain.update(),this.loader.update()),this.emit("layout_changed")}positionPanels(){const t={left:0,right:0};for(let e in this.panels)this.panels[e].layout.interaction.x_linked&&(t.left=Math.max(t.left,this.panels[e].layout.margin.left),t.right=Math.max(t.right,this.panels[e].layout.margin.right));let e=0;return this.panel_ids_by_y_index.forEach((s=>{const i=this.panels[s];if(i.setOrigin(0,e),e+=this.panels[s].layout.height,i.layout.interaction.x_linked){const e=Math.max(t.left-i.layout.margin.left,0)+Math.max(t.right-i.layout.margin.right,0);i.layout.width+=e,i.layout.margin.left=t.left,i.layout.margin.right=t.right,i.layout.cliparea.origin.x=t.left}})),this.setDimensions(),this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t];e.setDimensions(this.layout.width,e.layout.height)})),this}initialize(){if(this.layout.responsive_resize&&k.select(this.container).classed("lz-container-responsive",!0),this.layout.mouse_guide){const t=this.svg.append("g").attr("class","lz-mouse_guide").attr("id",`${this.id}.mouse_guide`),e=t.append("rect").attr("class","lz-mouse_guide-vertical").attr("x",-1),s=t.append("rect").attr("class","lz-mouse_guide-horizontal").attr("y",-1);this.mouse_guide={svg:t,vertical:e,horizontal:s}}this.curtain=Q.call(this),this.loader=tt.call(this),this.panel_boundaries={parent:this,hide_timeout:null,showing:!1,dragging:!1,selectors:[],corner_selector:null,show:function(){if(!this.showing&&!this.parent.curtain.showing){this.showing=!0,this.parent.panel_ids_by_y_index.forEach(((t,e)=>{const s=k.select(this.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-boundary").attr("title","Resize panel");s.append("span");const i=k.drag();i.on("start",(()=>{this.dragging=!0})),i.on("end",(()=>{this.dragging=!1})),i.on("drag",(()=>{const t=this.parent.panels[this.parent.panel_ids_by_y_index[e]],s=t.layout.height;t.setDimensions(this.parent.layout.width,t.layout.height+k.event.dy);const i=t.layout.height-s;this.parent.panel_ids_by_y_index.forEach(((t,s)=>{const a=this.parent.panels[this.parent.panel_ids_by_y_index[s]];s>e&&(a.setOrigin(a.layout.origin.x,a.layout.origin.y+i),a.toolbar.position())})),this.parent.positionPanels(),this.position()})),s.call(i),this.parent.panel_boundaries.selectors.push(s)}));const t=k.select(this.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-corner-boundary").attr("title","Resize plot");t.append("span").attr("class","lz-panel-corner-boundary-outer"),t.append("span").attr("class","lz-panel-corner-boundary-inner");const e=k.drag();e.on("start",(()=>{this.dragging=!0})),e.on("end",(()=>{this.dragging=!1})),e.on("drag",(()=>{this.parent.setDimensions(this.parent.layout.width+k.event.dx,this.parent._total_height+k.event.dy)})),t.call(e),this.parent.panel_boundaries.corner_selector=t}return this.position()},position:function(){if(!this.showing)return this;const t=this.parent._getPageOrigin();this.selectors.forEach(((e,s)=>{const i=this.parent.panels[this.parent.panel_ids_by_y_index[s]],a=i._getPageOrigin(),n=t.x,o=a.y+i.layout.height-12,r=this.parent.layout.width-1;e.style("top",`${o}px`).style("left",`${n}px`).style("width",`${r}px`),e.select("span").style("width",`${r}px`)}));return this.corner_selector.style("top",t.y+this.parent._total_height-10-16+"px").style("left",t.x+this.parent.layout.width-10-16+"px"),this},hide:function(){return this.showing?(this.showing=!1,this.selectors.forEach((t=>{t.remove()})),this.selectors=[],this.corner_selector.remove(),this.corner_selector=null,this):this}},this.layout.panel_boundaries&&k.select(this.svg.node().parentNode).on(`mouseover.${this.id}.panel_boundaries`,(()=>{clearTimeout(this.panel_boundaries.hide_timeout),this.panel_boundaries.show()})).on(`mouseout.${this.id}.panel_boundaries`,(()=>{this.panel_boundaries.hide_timeout=setTimeout((()=>{this.panel_boundaries.hide()}),300)})),this.toolbar=new vt(this).show();for(let t in this.panels)this.panels[t].initialize();const t=`.${this.id}`;if(this.layout.mouse_guide){const e=()=>{this.mouse_guide.vertical.attr("x",-1),this.mouse_guide.horizontal.attr("y",-1)},s=()=>{const t=k.mouse(this.svg.node());this.mouse_guide.vertical.attr("x",t[0]),this.mouse_guide.horizontal.attr("y",t[1])};this.svg.on(`mouseout${t}-mouse_guide`,e).on(`touchleave${t}-mouse_guide`,e).on(`mousemove${t}-mouse_guide`,s)}const e=()=>{this.stopDrag()},s=()=>{if(this.interaction.dragging){const t=k.mouse(this.svg.node());k.event&&k.event.preventDefault(),this.interaction.dragging.dragged_x=t[0]-this.interaction.dragging.start_x,this.interaction.dragging.dragged_y=t[1]-this.interaction.dragging.start_y,this.panels[this.interaction.panel_id].render(),this.interaction.linked_panel_ids.forEach((t=>{this.panels[t].render()}))}};this.svg.on(`mouseup${t}`,e).on(`touchend${t}`,e).on(`mousemove${t}`,s).on(`touchmove${t}`,s);const i=k.select("body").node();i&&(i.addEventListener("mouseup",e),i.addEventListener("touchend",e),this.trackExternalListener(i,"mouseup",e),this.trackExternalListener(i,"touchend",e)),this.on("match_requested",(t=>{const e=t.data,s=e.active?e.value:null,i=t.target.id;Object.values(this.panels).forEach((t=>{t.id!==i&&Object.values(t.data_layers).forEach((t=>t.destroyAllTooltips(!1)))})),this.applyState({lz_match_value:s})})),this.initialized=!0;const a=this.svg.node().getBoundingClientRect(),n=a.width?a.width:this.layout.width,o=a.height?a.height:this._total_height;return this.setDimensions(n,o),this}startDrag(t,e){t=t||null;let s=null;switch(e=e||null){case"background":case"x_tick":s="x";break;case"y1_tick":s="y1";break;case"y2_tick":s="y2"}if(!(t instanceof kt&&s&&this._canInteract()))return this.stopDrag();const i=k.mouse(this.svg.node());return this.interaction={panel_id:t.id,linked_panel_ids:t.getLinkedPanelIds(s),dragging:{method:e,start_x:i[0],start_y:i[1],dragged_x:0,dragged_y:0,axis:s}},this.svg.style("cursor","all-scroll"),this}stopDrag(){if(!this.interaction.dragging)return this;if("object"!=typeof this.panels[this.interaction.panel_id])return this.interaction={},this;const t=this.panels[this.interaction.panel_id],e=(e,s,i)=>{t.data_layer_ids_by_z_index.forEach((a=>{const n=t.data_layers[a].layout[`${e}_axis`];n.axis===s&&(n.floor=i[0],n.ceiling=i[1],delete n.lower_buffer,delete n.upper_buffer,delete n.min_extent,delete n.ticks)}))};switch(this.interaction.dragging.method){case"background":case"x_tick":0!==this.interaction.dragging.dragged_x&&(e("x",1,t.x_extent),this.applyState({start:t.x_extent[0],end:t.x_extent[1]}));break;case"y1_tick":case"y2_tick":if(0!==this.interaction.dragging.dragged_y){const s=parseInt(this.interaction.dragging.method[1]);e("y",s,t[`y${s}_extent`])}}return this.interaction={},this.svg.style("cursor",null),this}get _total_height(){return this.layout.panels.reduce(((t,e)=>e.height+t),0)}}function St(t,e,s){const i={0:"",3:"K",6:"M",9:"G"};if(s=s||!1,isNaN(e)||null===e){const s=Math.log(t)/Math.LN10;e=Math.min(Math.max(s-s%3,0),9)}const a=e-Math.floor((Math.log(t)/Math.LN10).toFixed(e+3)),n=Math.min(Math.max(e,0),2),o=Math.min(Math.max(a,n),12);let r=`${(t/Math.pow(10,e)).toFixed(o)}`;return s&&void 0!==i[e]&&(r+=` ${i[e]}b`),r}function Nt(t){let e=t.toUpperCase();e=e.replace(/,/g,"");const s=/([KMG])[B]*$/,i=s.exec(e);let a=1;return i&&(a="M"===i[1]?1e6:"G"===i[1]?1e9:1e3,e=e.replace(s,"")),e=Number(e)*a,e}function Tt(t,e,s){if("object"!=typeof e)throw new Error("invalid arguments: data is not an object");if("string"!=typeof t)throw new Error("invalid arguments: html is not a string");const i=[],a=/{{(?:(#if )?([A-Za-z0-9_:|]+)|(#else)|(\/if))}}/;for(;t.length>0;){const e=a.exec(t);e?0!==e.index?(i.push({text:t.slice(0,e.index)}),t=t.slice(e.index)):"#if "===e[1]?(i.push({condition:e[2]}),t=t.slice(e[0].length)):e[2]?(i.push({variable:e[2]}),t=t.slice(e[0].length)):"#else"===e[3]?(i.push({branch:"else"}),t=t.slice(e[0].length)):"/if"===e[4]?(i.push({close:"if"}),t=t.slice(e[0].length)):(console.error(`Error tokenizing tooltip when remaining template is ${JSON.stringify(t)} and previous tokens are ${JSON.stringify(i)} and current regex match is ${JSON.stringify([e[1],e[2],e[3]])}`),t=t.slice(e[0].length)):(i.push({text:t}),t="")}const n=function(){const t=i.shift();if(void 0!==t.text||t.variable)return t;if(t.condition){let e=t.then=[];for(t.else=[];i.length>0;){if("if"===i[0].close){i.shift();break}"else"===i[0].branch&&(i.shift(),e=t.else),e.push(n())}return t}return console.error(`Error making tooltip AST due to unknown token ${JSON.stringify(t)}`),{text:""}},o=[];for(;i.length>0;)o.push(n());const r=function(t){return Object.prototype.hasOwnProperty.call(r.cache,t)||(r.cache[t]=new R(t).resolve(e,s)),r.cache[t]};r.cache={};const l=function(t){if(void 0!==t.text)return t.text;if(t.variable){try{const e=r(t.variable);if(-1!==["string","number","boolean"].indexOf(typeof e))return e;if(null===e)return""}catch(e){console.error(`Error while processing variable ${JSON.stringify(t.variable)}`)}return`{{${t.variable}}}`}if(t.condition){try{if(r(t.condition))return t.then.map(l).join("");if(t.else)return t.else.map(l).join("")}catch(e){console.error(`Error while processing condition ${JSON.stringify(t.variable)}`)}return""}console.error(`Error rendering tooltip due to unknown AST node ${JSON.stringify(t)}`)};return o.map(l).join("")}const At=new h;At.add("=",((t,e)=>t===e)),At.add("!=",((t,e)=>t!=e)),At.add("<",((t,e)=>tt<=e)),At.add(">",((t,e)=>t>e)),At.add(">=",((t,e)=>t>=e)),At.add("%",((t,e)=>t%e)),At.add("in",((t,e)=>e&&e.includes(t))),At.add("match",((t,e)=>t&&t.includes(e)));const Lt=At,Ot=(t,e)=>void 0===e||t.field_value!==e?void 0!==t.else?t.else:null:t.then,Ct=(t,e)=>{const s=t.breaks||[],i=t.values||[];if(null==e||isNaN(+e))return t.null_value?t.null_value:null;const a=s.reduce((function(t,s){return+e=t&&+evoid 0!==e&&t.categories.includes(e)?t.values[t.categories.indexOf(e)]:t.null_value?t.null_value:null,Rt=(t,e,s)=>{const i=t.values;return i[s%i.length]};let Dt=(t,e,s)=>{const i=t._cache=t._cache||new Map,a=t.max_cache_size||500;if(i.size>=a&&i.clear(),i.has(e))return i.get(e);let n=0;e=String(e);for(let t=0;t{var s=t.breaks||[],i=t.values||[],a=t.null_value?t.null_value:null;if(s.length<2||s.length!==i.length)return a;if(null==e||isNaN(+e))return a;if(+e<=t.breaks[0])return i[0];if(+e>=t.breaks[t.breaks.length-1])return i[s.length-1];{var n=null;if(s.forEach((function(t,i){i&&s[i-1]<=+e&&s[i]>=+e&&(n=i)})),null===n)return a;const t=(+e-s[n-1])/(s[n]-s[n-1]);return isFinite(t)?k.interpolate(i[n-1],i[n])(t):a}},jt=new h;for(let[t,e]of Object.entries(n))jt.add(t,e);jt.add("if",Ot);const Bt=jt,Ut={id:"",type:"",tag:"custom_data_type",fields:[],id_field:"id",filters:null,match:{},x_axis:{},y_axis:{},legend:null,tooltip:{},tooltip_positioning:"horizontal",behaviors:{}};class Ft{constructor(t,e){this.initialized=!1,this.layout_idx=null,this.id=null,this._base_id=null,this.parent=e||null,this.svg={},this.parent_plot=null,e&&(this.parent_plot=e.parent),this.layout=Z(t||{},Ut),this.layout.id&&(this.id=this.layout.id),this._filter_func=null,this.layout.x_axis!=={}&&"number"!=typeof this.layout.x_axis.axis&&(this.layout.x_axis.axis=1),this.layout.y_axis!=={}&&"number"!=typeof this.layout.y_axis.axis&&(this.layout.y_axis.axis=1),this._base_layout=J(this.layout),this.state={},this.state_id=null,this.layer_state=null,this._setDefaultState(),this.data=[],this.layout.tooltip&&(this.tooltips={}),this.global_statuses={highlighted:!1,selected:!1,faded:!1,hidden:!1}}render(){throw new Error("Method must be implemented")}moveForward(){return this.parent.data_layer_ids_by_z_index[this.layout.z_index+1]&&(this.parent.data_layer_ids_by_z_index[this.layout.z_index]=this.parent.data_layer_ids_by_z_index[this.layout.z_index+1],this.parent.data_layer_ids_by_z_index[this.layout.z_index+1]=this.id,this.parent.resortDataLayers()),this}moveBack(){return this.parent.data_layer_ids_by_z_index[this.layout.z_index-1]&&(this.parent.data_layer_ids_by_z_index[this.layout.z_index]=this.parent.data_layer_ids_by_z_index[this.layout.z_index-1],this.parent.data_layer_ids_by_z_index[this.layout.z_index-1]=this.id,this.parent.resortDataLayers()),this}setElementAnnotation(t,e,s){const i=this.getElementId(t);return this.layer_state.extra_fields[i]||(this.layer_state.extra_fields[i]={}),this.layer_state.extra_fields[i][e]=s,this}setFilter(t){console.warn("The setFilter method is deprecated and will be removed in the future; please use the layout API with a custom filter function instead"),this._filter_func=t}_getDataExtent(t,e){return t=t||this.data,k.extent(t,(t=>+new R(e.field).resolve(t)))}getElementId(t){const e=Symbol.for("lzID");if(t[e])return t[e];const s=this.layout.id_field||"id";if(void 0===t[s])throw new Error("Unable to generate element ID");const i=t[s].toString().replace(/\W/g,""),a=`${this.getBaseId()}-${i}`.replace(/([:.[\],])/g,"_");return t[e]=a,a}getElementStatusNodeId(t){return null}getElementById(t){const e=k.select(`#${t.replace(/([:.[\],])/g,"\\$1")}`);return!e.empty()&&e.data()&&e.data().length?e.data()[0]:null}applyDataMethods(){const t=this.layout.match&&this.layout.match.receive,e=Lt.get(this.layout.match&&this.layout.match.operator||"="),s=this.parent_plot.state.lz_match_value,i=t?new R(t):null;return this.data.forEach(((a,n)=>{t&&null!=s&&(a.lz_is_match=e(i.resolve(a),s)),a.toHTML=()=>{const t=this.layout.id_field||"id";let e="";return a[t]&&(e=a[t].toString()),e},a.getDataLayer=()=>this,a.getPanel=()=>this.parent||null,a.getPlot=()=>{const t=this.parent;return t?t.parent:null},a.deselect=()=>{this.getDataLayer().unselectElement(this)}})),this.applyCustomDataMethods(),this}applyCustomDataMethods(){return this}resolveScalableParameter(t,e,s){let i=null;if(Array.isArray(t)){let a=0;for(;null===i&&ad-(_+v)?"top":"bottom"):"horizontal"===w&&(v=0,w=p<=r.width/2?"left":"right"),"top"===w||"bottom"===w){const t=Math.max(c.width/2-p,0),e=Math.max(c.width/2+p-u,0);y=h.x+p-c.width/2-e+t,b=h.x+p-y-7,"top"===w?(g=h.y+_-(v+c.height+8),m="down",f=c.height-1):(g=h.y+_+v+8,m="up",f=-8)}else{if("left"!==w&&"right"!==w)throw new Error("Unrecognized placement value");"left"===w?(y=h.x+p+x+8,m="left",b=-8):(y=h.x+p-c.width-x-8,m="right",b=c.width-1),_-c.height/2<=0?(g=h.y+_-10.5-6,f=6):_+c.height/2>=d?(g=h.y+_+7+6-c.height,f=c.height-14-6):(g=h.y+_-c.height/2,f=c.height/2-7)}return t.selector.style("left",`${y}px`).style("top",`${g}px`),t.arrow||(t.arrow=t.selector.append("div").style("position","absolute")),t.arrow.attr("class",`lz-data_layer-tooltip-arrow_${m}`).style("left",`${b}px`).style("top",`${f}px`),this}filter(t,e,s,i){let a=!0;return t.forEach((t=>{const{field:s,operator:i,value:n}=t,o=Lt.get(i),r=this.getElementAnnotation(e);o(s?new R(s).resolve(e,r):e,n)||(a=!1)})),a}getElementAnnotation(t,e){const s=this.getElementId(t),i=this.layer_state.extra_fields[s];return e?i&&i[e]:i}_applyFilters(t){return t=t||this.data,this._filter_func?t=t.filter(this._filter_func):this.layout.filters&&(t=t.filter(this.filter.bind(this,this.layout.filters))),t}_setDefaultState(){const t={status_flags:{},extra_fields:{}},e=t.status_flags;E.adjectives.forEach((t=>{e[t]=e[t]||new Set})),e.has_tooltip=e.has_tooltip||new Set,this.parent&&(this.state_id=`${this.parent.id}.${this.id}`,this.state=this.parent.state,this.state[this.state_id]=t),this.layer_state=t}getBaseId(){return this._base_id?this._base_id:this.parent?`${this.parent_plot.id}.${this.parent.id}.${this.id}`:(this.id||"").toString()}getAbsoluteDataHeight(){return this.svg.group.node().getBoundingClientRect().height}initialize(){this._base_id=this.getBaseId();const t=this.getBaseId();return this.svg.container=this.parent.svg.group.append("g").attr("class","lz-data_layer-container").attr("id",`${t}.data_layer_container`),this.svg.clipRect=this.svg.container.append("clipPath").attr("id",`${t}.clip`).append("rect"),this.svg.group=this.svg.container.append("g").attr("id",`${t}.data_layer`).attr("clip-path",`url(#${t}.clip)`),this}createTooltip(t){if("object"!=typeof this.layout.tooltip)throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`);const e=this.getElementId(t);if(!this.tooltips[e])return this.tooltips[e]={data:t,arrow:null,selector:k.select(this.parent_plot.svg.node().parentNode).append("div").attr("class","lz-data_layer-tooltip").attr("id",`${e}-tooltip`)},this.layer_state.status_flags.has_tooltip.add(e),this.updateTooltip(t),this;this.positionTooltip(e)}updateTooltip(t,e){return void 0===e&&(e=this.getElementId(t)),this.tooltips[e].selector.html(""),this.tooltips[e].arrow=null,this.layout.tooltip.html&&this.tooltips[e].selector.html(Tt(this.layout.tooltip.html,t,this.getElementAnnotation(t))),this.layout.tooltip.closable&&this.tooltips[e].selector.insert("button",":first-child").attr("class","lz-tooltip-close-button").attr("title","Close").text("×").on("click",(()=>{this.destroyTooltip(e)})),this.tooltips[e].selector.data([t]),this.positionTooltip(e),this}destroyTooltip(t,e){let s;if(s="string"==typeof t?t:this.getElementId(t),this.tooltips[s]&&("object"==typeof this.tooltips[s].selector&&this.tooltips[s].selector.remove(),delete this.tooltips[s]),!e){this.layer_state.status_flags.has_tooltip.delete(s)}return this}destroyAllTooltips(t=!0){for(let e in this.tooltips)this.destroyTooltip(e,t);return this}positionTooltip(t){if("string"!=typeof t)throw new Error("Unable to position tooltip: id is not a string");if(!this.tooltips[t])throw new Error("Unable to position tooltip: id does not point to a valid tooltip");const e=this.tooltips[t],s=this._getTooltipPosition(e);if(!s)return null;this._drawTooltip(e,this.layout.tooltip_positioning,s.x_min,s.x_max,s.y_min,s.y_max)}positionAllTooltips(){for(let t in this.tooltips)this.positionTooltip(t);return this}showOrHideTooltip(t,e){if("object"!=typeof this.layout.tooltip)return this;const s=this.getElementId(t),i=(t,e,s)=>{let a=null;if("object"!=typeof t||null===t)return null;if(Array.isArray(e))s=s||"and",a=1===e.length?t[e[0]]:e.reduce(((e,i)=>"and"===s?t[e]&&t[i]:"or"===s?t[e]||t[i]:null));else{if("object"!=typeof e)return!1;{let n;for(let o in e)n=i(t,e[o],o),null===a?a=n:"and"===s?a=a&&n:"or"===s&&(a=a||n)}}return a};let a={};"string"==typeof this.layout.tooltip.show?a={and:[this.layout.tooltip.show]}:"object"==typeof this.layout.tooltip.show&&(a=this.layout.tooltip.show);let n={};"string"==typeof this.layout.tooltip.hide?n={and:[this.layout.tooltip.hide]}:"object"==typeof this.layout.tooltip.hide&&(n=this.layout.tooltip.hide);const o=this.layer_state;var r={};E.adjectives.forEach((t=>{const e=`un${t}`;r[t]=o.status_flags[t].has(s),r[e]=!r[t]}));const l=i(r,a),h=i(r,n),c=o.status_flags.has_tooltip.has(s);return!l||!e&&!c||h?this.destroyTooltip(t):this.createTooltip(t),this}setElementStatus(t,e,s,i){if("has_tooltip"===t)return this;let a;void 0===s&&(s=!0);try{a=this.getElementId(e)}catch(t){return this}i&&this.setAllElementStatus(t,!s),k.select(`#${a}`).classed(`lz-data_layer-${this.layout.type}-${t}`,s);const n=this.getElementStatusNodeId(e);null!==n&&k.select(`#${n}`).classed(`lz-data_layer-${this.layout.type}-statusnode-${t}`,s);const o=!this.layer_state.status_flags[t].has(a);s&&o&&this.layer_state.status_flags[t].add(a),s||o||this.layer_state.status_flags[t].delete(a),this.showOrHideTooltip(e,o),o&&this.parent.emit("layout_changed",!0);const r="selected"===t;!r||!o&&s||this.parent.emit("element_selection",{element:e,active:s},!0);const l=this.layout.match&&this.layout.match.send;return!r||void 0===l||!o&&s||this.parent.emit("match_requested",{value:new R(l).resolve(e),active:s},!0),this}setAllElementStatus(t,e){if(void 0===t||!E.adjectives.includes(t))throw new Error("Invalid status");if(void 0===this.layer_state.status_flags[t])return this;if(void 0===e&&(e=!0),e)this.data.forEach((e=>this.setElementStatus(t,e,!0)));else{new Set(this.layer_state.status_flags[t]).forEach((e=>{const s=this.getElementById(e);"object"==typeof s&&null!==s&&this.setElementStatus(t,s,!1)})),this.layer_state.status_flags[t]=new Set}return this.global_statuses[t]=e,this}applyBehaviors(t){"object"==typeof this.layout.behaviors&&Object.keys(this.layout.behaviors).forEach((e=>{const s=/(click|mouseover|mouseout)/.exec(e);s&&t.on(`${s[0]}.${e}`,this.executeBehaviors(e,this.layout.behaviors[e]))}))}executeBehaviors(t,e){const s=t.includes("ctrl"),i=t.includes("shift"),a=this;return function(t){t=t||k.select(k.event.target).datum(),s===!!k.event.ctrlKey&&i===!!k.event.shiftKey&&e.forEach((e=>{if("object"==typeof e&&null!==e)switch(e.action){case"set":a.setElementStatus(e.status,t,!0,e.exclusive);break;case"unset":a.setElementStatus(e.status,t,!1,e.exclusive);break;case"toggle":var s=a.layer_state.status_flags[e.status].has(a.getElementId(t)),i=e.exclusive&&!s;a.setElementStatus(e.status,t,!s,i);break;case"link":if("string"==typeof e.href){const s=Tt(e.href,t,a.getElementAnnotation(t));"string"==typeof e.target?window.open(s,e.target):window.location.href=s}}}))}}_getPageOrigin(){const t=this.parent._getPageOrigin();return{x:t.x+this.parent.layout.margin.left,y:t.y+this.parent.layout.margin.top}}applyAllElementStatus(){const t=this.layer_state.status_flags,e=this;for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&t[s].forEach((t=>{try{this.setElementStatus(s,this.getElementById(t),!0)}catch(t){console.warn(`Unable to apply state: ${e.state_id}, ${s}`),console.error(t)}}))}draw(){return this.svg.container.attr("transform",`translate(${this.parent.layout.cliparea.origin.x}, ${this.parent.layout.cliparea.origin.y})`),this.svg.clipRect.attr("width",this.parent.layout.cliparea.width).attr("height",this.parent.layout.cliparea.height),this.positionAllTooltips(),this}reMap(){return this.destroyAllTooltips(),this.parent_plot.lzd.getData(this.state,this.layout.fields).then((t=>{this.data=t.body,this.applyDataMethods(),this.initialized=!0}))}}E.verbs.forEach(((t,e)=>{const s=E.adjectives[e],i=`un${t}`;Ft.prototype[`${t}Element`]=function(t,e=!1){return e=!!e,this.setElementStatus(s,t,!0,e),this},Ft.prototype[`${i}Element`]=function(t,e){return e=void 0!==e&&!!e,this.setElementStatus(s,t,!1,e),this},Ft.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},Ft.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const qt={color:"#000000",filters:null,tooltip_positioning:"vertical",hitarea_width:8};class Gt extends Ft{constructor(t){if(!Array.isArray(t.filters))throw new Error("Annotation track must specify array of filters for selecting points to annotate");Z(t,qt),super(...arguments)}initialize(){super.initialize(),this._hitareas_group=this.svg.group.append("g").attr("class",`lz-data_layer-${this.layout.type}-hit_areas`),this._visible_lines_group=this.svg.group.append("g").attr("class",`lz-data_layer-${this.layout.type}-visible_lines`)}render(){const t=this._applyFilters(),e=this._hitareas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(t,(t=>t[this.layout.id_field])),s=(e,s)=>{const i=this.parent.x_scale(e[this.layout.x_axis.field]);let a=i-this.layout.hitarea_width/2;if(s>=1){const e=t[s-1],n=this.parent.x_scale(e[this.layout.x_axis.field]);a=Math.max(a,(i+n)/2)}return[a,i]};e.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(e).attr("id",(t=>this.getElementId(t))).attr("height",this.parent.layout.height).attr("opacity",0).attr("x",((t,e)=>s(t,e)[0])).attr("width",((t,e)=>{const i=s(t,e);return i[1]-i[0]+this.layout.hitarea_width/2}));const i=this._visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(t,(t=>t[this.layout.id_field]));i.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(i).attr("id",(t=>this.getElementId(t))).attr("x",(t=>this.parent.x_scale(t[this.layout.x_axis.field])-.5)).attr("width",1).attr("height",this.parent.layout.height).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))),i.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this)),e.exit().remove()}_getTooltipPosition(t){const e=this.parent,s=e.layout.height-(e.layout.margin.top+e.layout.margin.bottom),i=e.x_scale(t.data[this.layout.x_axis.field]),a=s/2;return{x_min:i-1,x_max:i+1,y_min:a-e.layout.margin.top,y_max:a+e.layout.margin.bottom}}}const Ht={color:"#CCCCCC",fill_opacity:.5,filters:null,regions:[],id_field:"id",start_field:"start",end_field:"end",merge_field:null};class Zt extends Ft{constructor(t){if(Z(t,Ht),t.interaction||t.behaviors)throw new Error("highlight_regions layer does not support mouse events");if(t.regions&&t.regions.length&&t.fields&&t.fields.length)throw new Error('highlight_regions layer can specify "regions" in layout, OR external data "fields", but not both');super(...arguments)}_mergeNodes(t){const{end_field:e,merge_field:s,start_field:i}=this.layout;if(!s)return t;t.sort(((t,e)=>k.ascending(t[s],e[s])||k.ascending(t[i],e[i])));let a=[];return t.forEach((function(t,n){const o=a[a.length-1]||t;if(t[s]===o[s]&&t[i]<=o[e]){const s=Math.min(o[i],t[i]),n=Math.max(o[e],t[e]);t=Object.assign({},o,t,{[i]:s,[e]:n}),a.pop()}a.push(t)})),a}render(){const{x_scale:t}=this.parent;let e=this.layout.regions.length?this.layout.regions:this.data;e.forEach(((t,e)=>t.id||(t.id=e))),e=this._applyFilters(e),e=this._mergeNodes(e);const s=this.svg.group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(e);s.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(s).attr("id",(t=>this.getElementId(t))).attr("x",(e=>t(e[this.layout.start_field]))).attr("width",(e=>t(e[this.layout.end_field])-t(e[this.layout.start_field]))).attr("height",this.parent.layout.height).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))),s.exit().remove(),this.svg.group.style("pointer-events","none")}_getTooltipPosition(t){throw new Error("This layer does not support tooltips")}}const Jt={color:"seagreen",hitarea_width:"10px",style:{fill:"none","stroke-width":"1px","stroke-opacity":"100%"},tooltip_positioning:"top"};class Kt extends Ft{constructor(t){t=Z(t,Jt),super(...arguments)}render(){const t=this,e=t.layout,s=t.parent.x_scale,i=t.parent[`y${e.y_axis.axis}_scale`],a=this._applyFilters();function n(t){const a=t[e.x_axis.field1],n=t[e.x_axis.field2],o=(a+n)/2,r=[[s(a),i(0)],[s(o),i(t[e.y_axis.field])],[s(n),i(0)]];return k.line().x((t=>t[0])).y((t=>t[1])).curve(k.curveNatural)(r)}const o=this.svg.group.selectAll("path.lz-data_layer-arcs-hitarea").data(a,(t=>this.getElementId(t))),r=this.svg.group.selectAll("path.lz-data_layer-arcs").data(a,(t=>this.getElementId(t)));return this.svg.group.call(et,e.style),o.enter().append("path").attr("class","lz-data_layer-arcs-hitarea").merge(o).attr("id",(t=>this.getElementId(t))).style("fill","none").style("stroke-width",e.hitarea_width).style("stroke-opacity",0).style("stroke","transparent").attr("d",(t=>n(t))),r.enter().append("path").attr("class","lz-data_layer-arcs").merge(r).attr("id",(t=>this.getElementId(t))).attr("stroke",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("d",((t,e)=>n(t))),r.exit().remove(),o.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this)),this}_getTooltipPosition(t){const e=this.parent,s=this.layout,i=t.data[s.x_axis.field1],a=t.data[s.x_axis.field2],n=e[`y${s.y_axis.axis}_scale`];return{x_min:e.x_scale(Math.min(i,a)),x_max:e.x_scale(Math.max(i,a)),y_min:n(t.data[s.y_axis.field]),y_max:n(0)}}}const Vt={stroke:"rgb(54, 54, 150)",color:"#363696",label_font_size:12,label_exon_spacing:3,exon_height:10,bounding_box_padding:3,track_vertical_spacing:5,tooltip_positioning:"top"};class Yt extends Ft{constructor(t){t=Z(t,Vt),super(...arguments),this.transcript_idx=0,this.tracks=1,this.gene_track_index={1:[]}}getElementStatusNodeId(t){return`${this.getElementId(t)}-statusnode`}getTrackHeight(){return 2*this.layout.bounding_box_padding+this.layout.label_font_size+this.layout.label_exon_spacing+this.layout.exon_height+this.layout.track_vertical_spacing}assignTracks(t){const e=(t,e)=>{try{const s=this.svg.group.append("text").attr("x",0).attr("y",0).attr("class","lz-data_layer-genes lz-label").style("font-size",e).text(`${t}→`),i=s.node().getBBox().width;return s.remove(),i}catch(t){return 0}};return this.tracks=1,this.gene_track_index={1:[]},t.filter((t=>!(t.endthis.state.end))).map((t=>{if(t.gene_id&&t.gene_id.indexOf(".")){const e=t.gene_id.split(".");t.gene_id=e[0],t.gene_version=e[1]}if(t.transcript_id=t.transcripts[this.transcript_idx].transcript_id,t.display_range={start:this.parent.x_scale(Math.max(t.start,this.state.start)),end:this.parent.x_scale(Math.min(t.end,this.state.end))},t.display_range.label_width=e(t.gene_name,this.layout.label_font_size),t.display_range.width=t.display_range.end-t.display_range.start,t.display_range.text_anchor="middle",t.display_range.widththis.state.end)t.display_range.start=t.display_range.end-t.display_range.label_width-this.layout.label_font_size,t.display_range.text_anchor="end";else{const e=(t.display_range.label_width-t.display_range.width)/2+this.layout.label_font_size;t.display_range.start-ethis.parent.x_scale(this.state.end)?(t.display_range.end=this.parent.x_scale(this.state.end),t.display_range.start=t.display_range.end-t.display_range.label_width,t.display_range.text_anchor="end"):(t.display_range.start-=e,t.display_range.end+=e)}t.display_range.width=t.display_range.end-t.display_range.start}t.display_range.start-=this.layout.bounding_box_padding,t.display_range.end+=this.layout.bounding_box_padding,t.display_range.width+=2*this.layout.bounding_box_padding,t.display_domain={start:this.parent.x_scale.invert(t.display_range.start),end:this.parent.x_scale.invert(t.display_range.end)},t.display_domain.width=t.display_domain.end-t.display_domain.start,t.track=null;let s=1;for(;null===t.track;){let e=!1;this.gene_track_index[s].map((s=>{if(!e){const i=Math.min(s.display_range.start,t.display_range.start);Math.max(s.display_range.end,t.display_range.end)-ithis.tracks&&(this.tracks=s,this.gene_track_index[s]=[])):(t.track=s,this.gene_track_index[s].push(t))}return t.parent=this,t.transcripts.map(((e,s)=>{t.transcripts[s].parent=t,t.transcripts[s].exons.map(((e,i)=>t.transcripts[s].exons[i].parent=t.transcripts[s]))})),t}))}render(){const t=this;let e,s=this._applyFilters();s=this.assignTracks(s);const i=this.svg.group.selectAll("g.lz-data_layer-genes").data(s,(t=>t.gene_name));i.enter().append("g").attr("class","lz-data_layer-genes").merge(i).attr("id",(t=>this.getElementId(t))).each((function(s){const i=s.parent,a=k.select(this).selectAll("rect.lz-data_layer-genes.lz-data_layer-genes-statusnode").data([s],(t=>i.getElementStatusNodeId(t)));e=i.getTrackHeight()-i.layout.track_vertical_spacing,a.enter().append("rect").attr("class","lz-data_layer-genes lz-data_layer-genes-statusnode").merge(a).attr("id",(t=>i.getElementStatusNodeId(t))).attr("rx",i.layout.bounding_box_padding).attr("ry",i.layout.bounding_box_padding).attr("width",(t=>t.display_range.width)).attr("height",e).attr("x",(t=>t.display_range.start)).attr("y",(t=>(t.track-1)*i.getTrackHeight())),a.exit().remove();const n=k.select(this).selectAll("rect.lz-data_layer-genes.lz-boundary").data([s],(t=>`${t.gene_name}_boundary`));e=1,n.enter().append("rect").attr("class","lz-data_layer-genes lz-boundary").merge(n).attr("width",(t=>i.parent.x_scale(t.end)-i.parent.x_scale(t.start))).attr("height",e).attr("x",(t=>i.parent.x_scale(t.start))).attr("y",(t=>(t.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size+i.layout.label_exon_spacing+Math.max(i.layout.exon_height,3)/2)).style("fill",((e,s)=>t.resolveScalableParameter(t.layout.color,e,s))).style("stroke",((e,s)=>t.resolveScalableParameter(t.layout.stroke,e,s))),n.exit().remove();const o=k.select(this).selectAll("text.lz-data_layer-genes.lz-label").data([s],(t=>`${t.gene_name}_label`));o.enter().append("text").attr("class","lz-data_layer-genes lz-label").merge(o).attr("text-anchor",(t=>t.display_range.text_anchor)).text((t=>"+"===t.strand?`${t.gene_name}→`:`←${t.gene_name}`)).style("font-size",s.parent.layout.label_font_size).attr("x",(t=>"middle"===t.display_range.text_anchor?t.display_range.start+t.display_range.width/2:"start"===t.display_range.text_anchor?t.display_range.start+i.layout.bounding_box_padding:"end"===t.display_range.text_anchor?t.display_range.end-i.layout.bounding_box_padding:void 0)).attr("y",(t=>(t.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size)),o.exit().remove();const r=k.select(this).selectAll("rect.lz-data_layer-genes.lz-exon").data(s.transcripts[s.parent.transcript_idx].exons,(t=>t.exon_id));e=i.layout.exon_height,r.enter().append("rect").attr("class","lz-data_layer-genes lz-exon").merge(r).style("fill",((e,s)=>t.resolveScalableParameter(t.layout.color,e.parent.parent,s))).style("stroke",((e,s)=>t.resolveScalableParameter(t.layout.stroke,e.parent.parent,s))).attr("width",(t=>i.parent.x_scale(t.end)-i.parent.x_scale(t.start))).attr("height",e).attr("x",(t=>i.parent.x_scale(t.start))).attr("y",(()=>(s.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size+i.layout.label_exon_spacing)),r.exit().remove();const l=k.select(this).selectAll("rect.lz-data_layer-genes.lz-clickarea").data([s],(t=>`${t.gene_name}_clickarea`));e=i.getTrackHeight()-i.layout.track_vertical_spacing,l.enter().append("rect").attr("class","lz-data_layer-genes lz-clickarea").merge(l).attr("id",(t=>`${i.getElementId(t)}_clickarea`)).attr("rx",i.layout.bounding_box_padding).attr("ry",i.layout.bounding_box_padding).attr("width",(t=>t.display_range.width)).attr("height",e).attr("x",(t=>t.display_range.start)).attr("y",(t=>(t.track-1)*i.getTrackHeight())),l.exit().remove()})),i.exit().remove(),this.svg.group.on("click.event_emitter",(t=>this.parent.emit("element_clicked",t,!0))).call(this.applyBehaviors.bind(this))}_getTooltipPosition(t){const e=this.getElementStatusNodeId(t.data),s=k.select(`#${e}`).node().getBBox();return{x_min:this.parent.x_scale(t.data.start),x_max:this.parent.x_scale(t.data.end),y_min:s.y,y_max:s.y+s.height}}}const Wt={style:{fill:"none","stroke-width":"2px"},interpolate:"curveLinear",x_axis:{field:"x"},y_axis:{field:"y",axis:1},hitarea_width:5};class Xt extends Ft{constructor(t){if((t=Z(t,Wt)).tooltip)throw new Error("The line / filled curve layer does not support tooltips");super(...arguments)}render(){const t=this.parent,e=this.layout.x_axis.field,s=this.layout.y_axis.field,i=this.svg.group.selectAll("path.lz-data_layer-line").data([this.data]);let a;this.path=i.enter().append("path").attr("class","lz-data_layer-line");const n=t.x_scale,o=t[`y${this.layout.y_axis.axis}_scale`];a=this.layout.style.fill&&"none"!==this.layout.style.fill?k.area().x((t=>+n(t[e]))).y0(+o(0)).y1((t=>+o(t[s]))):k.line().x((t=>+n(t[e]))).y((t=>+o(t[s]))).curve(k[this.layout.interpolate]),i.merge(this.path).attr("d",a).call(et,this.layout.style),i.exit().remove()}setElementStatus(t,e,s){return this.setAllElementStatus(t,s)}setAllElementStatus(t,e){if(void 0===t||!E.adjectives.includes(t))throw new Error("Invalid status");if(void 0===this.layer_state.status_flags[t])return this;void 0===e&&(e=!0),this.global_statuses[t]=e;let s="lz-data_layer-line";return Object.keys(this.global_statuses).forEach((t=>{this.global_statuses[t]&&(s+=` lz-data_layer-line-${t}`)})),this.path.attr("class",s),this.parent.emit("layout_changed",!0),this}}const Qt={style:{stroke:"#D3D3D3","stroke-width":"3px","stroke-dasharray":"10px 10px"},orientation:"horizontal",x_axis:{axis:1,decoupled:!0},y_axis:{axis:1,decoupled:!0},tooltip_positioning:"vertical",offset:0};class te extends Ft{constructor(t){t=Z(t,Qt),["horizontal","vertical"].includes(t.orientation)||(t.orientation="horizontal"),super(...arguments),this.data=[]}getElementId(t){return this.getBaseId()}render(){const t=this.parent,e=`y${this.layout.y_axis.axis}_scale`,s=`y${this.layout.y_axis.axis}_extent`;if("horizontal"===this.layout.orientation)this.data=[{x:t.x_extent[0],y:this.layout.offset},{x:t.x_extent[1],y:this.layout.offset}];else{if("vertical"!==this.layout.orientation)throw new Error('Unrecognized vertical line type. Must be "vertical" or "horizontal"');this.data=[{x:this.layout.offset,y:t[s][0]},{x:this.layout.offset,y:t[s][1]}]}const i=this.svg.group.selectAll("path.lz-data_layer-line").data([this.data]),a=[t.layout.cliparea.height,0],n=k.line().x(((e,s)=>{const i=+t.x_scale(e.x);return isNaN(i)?t.x_range[s]:i})).y(((s,i)=>{const n=+t[e](s.y);return isNaN(n)?a[i]:n}));this.path=i.enter().append("path").attr("class","lz-data_layer-line").merge(i).attr("d",n).call(et,this.layout.style).call(this.applyBehaviors.bind(this)),i.exit().remove()}_getTooltipPosition(t){try{const t=k.mouse(this.svg.container.node()),e=t[0],s=t[1];return{x_min:e-1,x_max:e+1,y_min:s-1,y_max:s+1}}catch(t){return null}}}const ee={point_size:40,point_shape:"circle",tooltip_positioning:"horizontal",color:"#888888",coalesce:{active:!1,max_points:800,x_min:"-Infinity",x_max:"Infinity",y_min:0,y_max:3,x_gap:7,y_gap:7},fill_opacity:1,y_axis:{axis:1},id_field:"id"};class se extends Ft{constructor(t){(t=Z(t,ee)).label&&isNaN(t.label.spacing)&&(t.label.spacing=4),super(...arguments)}_getTooltipPosition(t){const e=this.parent.x_scale(t.data[this.layout.x_axis.field]),s=`y${this.layout.y_axis.axis}_scale`,i=this.parent[s](t.data[this.layout.y_axis.field]),a=this.resolveScalableParameter(this.layout.point_size,t.data),n=Math.sqrt(a/Math.PI);return{x_min:e-n,x_max:e+n,y_min:i-n,y_max:i+n}}flip_labels(){const t=this,e=t.resolveScalableParameter(t.layout.point_size,{}),s=t.layout.label.spacing,i=Boolean(t.layout.label.lines),a=2*s,n=this.parent_plot.layout.width-this.parent.layout.margin.left-this.parent.layout.margin.right-2*s,o=(t,a)=>{const n=+t.attr("x"),o=2*s+2*Math.sqrt(e);let r,l;i&&(r=+a.attr("x2"),l=s+2*Math.sqrt(e)),"start"===t.style("text-anchor")?(t.style("text-anchor","end"),t.attr("x",n-o),i&&a.attr("x2",r-l)):(t.style("text-anchor","start"),t.attr("x",n+o),i&&a.attr("x2",r+l))};t.label_texts.each((function(e,a){const r=k.select(this);if(+r.attr("x")+r.node().getBoundingClientRect().width+s>n){const e=i?k.select(t.label_lines.nodes()[a]):null;o(r,e)}})),t.label_texts.each((function(e,n){const r=k.select(this);if("end"===r.style("text-anchor"))return;let l=+r.attr("x");const h=r.node().getBoundingClientRect(),c=i?k.select(t.label_lines.nodes()[n]):null;t.label_texts.each((function(){const t=k.select(this).node().getBoundingClientRect();h.leftt.left&&h.topt.top&&(o(r,c),l=+r.attr("x"),l-h.width-sl.left&&r.topl.top))return;s=!0;const h=o.attr("y"),c=.5*(r.top_?(g=d-+n,d=+n,u-=g):u+l.height/2>_&&(g=u-+h,u=+h,d-=g),a.attr("y",d),o.attr("y",u)}))})),s){if(t.layout.label.lines){const e=t.label_texts.nodes();t.label_lines.attr("y2",((t,s)=>k.select(e[s]).attr("y")))}this.seperate_iterations<150&&setTimeout((()=>{this.separate_labels()}),1)}}render(){const t=this,e=this.parent.x_scale,s=this.parent[`y${this.layout.y_axis.axis}_scale`],i=Symbol.for("lzX"),a=Symbol.for("lzY");let n=this._applyFilters();if(n.forEach((t=>{let n=e(t[this.layout.x_axis.field]),o=s(t[this.layout.y_axis.field]);isNaN(n)&&(n=-1e3),isNaN(o)&&(o=-1e3),t[i]=n,t[a]=o})),this.layout.coalesce.active&&n.length>this.layout.coalesce.max_points){let{x_min:t,x_max:i,y_min:a,y_max:o,x_gap:r,y_gap:l}=this.layout.coalesce;n=function(t,e,s,i,a,n,o){let r=[];const l=Symbol.for("lzX"),h=Symbol.for("lzY");let c=null,d=null,u=[];function p(){if(u.length){const t=u[Math.floor((u.length-1)/2)];r.push(t)}c=d=null,u=[]}function _(t,e,s){c=t,d=e,u.push(s)}return t.forEach((t=>{const g=t[l],y=t[h],m=g>=e&&g<=s&&y>=a&&y<=n;t.lz_is_match||!m?(p(),r.push(t)):null===c?_(g,y,t):Math.abs(g-c)<=i&&Math.abs(y-d)<=o?u.push(t):(p(),_(g,y,t))})),p(),r}(n,isFinite(t)?e(+t):-1/0,isFinite(i)?e(+i):1/0,r,isFinite(o)?s(+o):-1/0,isFinite(a)?s(+a):1/0,l)}if(this.layout.label){let e;const s=t.layout.label.filters||[];if(s.length){const t=this.filter.bind(this,s);e=n.filter(t)}else e=n;this.label_groups=this.svg.group.selectAll(`g.lz-data_layer-${this.layout.type}-label`).data(e,(t=>`${t[this.layout.id_field]}_label`));const o=`lz-data_layer-${this.layout.type}-label`,r=this.label_groups.enter().append("g").attr("class",o);this.label_texts&&this.label_texts.remove(),this.label_texts=this.label_groups.merge(r).append("text").text((e=>Tt(t.layout.label.text||"",e,this.getElementAnnotation(e)))).attr("x",(e=>e[i]+Math.sqrt(t.resolveScalableParameter(t.layout.point_size,e))+t.layout.label.spacing)).attr("y",(t=>t[a])).attr("text-anchor","start").call(et,t.layout.label.style||{}),t.layout.label.lines&&(this.label_lines&&this.label_lines.remove(),this.label_lines=this.label_groups.merge(r).append("line").attr("x1",(t=>t[i])).attr("y1",(t=>t[a])).attr("x2",(e=>e[i]+Math.sqrt(t.resolveScalableParameter(t.layout.point_size,e))+t.layout.label.spacing/2)).attr("y2",(t=>t[a])).call(et,t.layout.label.lines.style||{})),this.label_groups.exit().remove()}else this.label_texts&&this.label_texts.remove(),this.label_lines&&this.label_lines.remove(),this.label_groups&&this.label_groups.remove();const o=this.svg.group.selectAll(`path.lz-data_layer-${this.layout.type}`).data(n,(t=>t[this.layout.id_field])),r=k.symbol().size(((t,e)=>this.resolveScalableParameter(this.layout.point_size,t,e))).type(((t,e)=>K(this.resolveScalableParameter(this.layout.point_shape,t,e)))),l=`lz-data_layer-${this.layout.type}`;o.enter().append("path").attr("class",l).attr("id",(t=>this.getElementId(t))).merge(o).attr("transform",(t=>`translate(${t[i]}, ${t[a]})`)).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))).attr("d",r),o.exit().remove(),this.layout.label&&(this.flip_labels(),this.seperate_iterations=0,this.separate_labels()),this.svg.group.on("click.event_emitter",(()=>{const t=k.select(k.event.target).datum();this.parent.emit("element_clicked",t,!0)})).call(this.applyBehaviors.bind(this))}makeLDReference(t){let e=null;if(void 0===t)throw new Error("makeLDReference requires one argument of any type");return e="object"==typeof t?this.layout.id_field&&void 0!==t[this.layout.id_field]?t[this.layout.id_field].toString():void 0!==t.id?t.id.toString():t.toString():t.toString(),this.parent.emit("set_ldrefvar",{ldrefvar:e},!0),this.parent_plot.applyState({ldrefvar:e})}}class ie extends se{constructor(t){super(...arguments),this._categories={}}_prepareData(){const t=this.layout.x_axis.field||"x",e=this.layout.x_axis.category_field;if(!e)throw new Error(`Layout for ${this.layout.id} must specify category_field`);const s=this.data.sort(((t,s)=>{const i=t[e],a=s[e],n="string"==typeof i?i.toLowerCase():i,o="string"==typeof a?a.toLowerCase():a;return n===o?0:n{e[t]=e[t]||s})),s}_generateCategoryBounds(){const t=this.layout.x_axis.category_field,e=this.layout.x_axis.field||"x",s={};this.data.forEach((i=>{const a=i[t],n=i[e],o=s[a]||[n,n];s[a]=[Math.min(o[0],n),Math.max(o[1],n)]}));const i=Object.keys(s);return this._setDynamicColorScheme(i),s}_getColorScale(t){let e=(t=t||this.layout).color||[];if(Array.isArray(e)&&(e=e.find((t=>"categorical_bin"===t.scale_function))),!e||"categorical_bin"!==e.scale_function)throw new Error("This layer requires that color options be provided as a `categorical_bin`");return e}_setDynamicColorScheme(t){const e=this._getColorScale(this.layout).parameters,s=this._getColorScale(this._base_layout).parameters;if(s.categories.length&&s.values.length){const i={};s.categories.forEach((t=>{i[t]=1})),t.every((t=>Object.prototype.hasOwnProperty.call(i,t)))?e.categories=s.categories:e.categories=t}else e.categories=t;let i;for(i=s.values.length?s.values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];i.length{const o=i[t];let r;switch(s){case"left":r=o[0];break;case"center":const t=o[1]-o[0];r=o[0]+(0!==t?t:o[0])/2;break;case"right":r=o[1]}return{x:r,text:t,style:{fill:a[e.indexOf(t)]||"#000000"}}}))}}applyCustomDataMethods(){return this.data=this._prepareData(),this._categories=this._generateCategoryBounds(),this}}const ae=new c;for(let[t,e]of Object.entries(o))ae.add(t,e);const ne=ae,oe=7.301,re={namespace:{assoc:"assoc"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n {{#if {{namespace[ld]}}isrefvar}}LD Reference Variant{{#else}}\n Make LD Reference{{/if}}
'},le=function(){const t=J(re);return t.html+="{{#if lz_show_label}}Hide{{#else}}Show{{/if}} label",t}(),he={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'

{{gene_name|htmlescape}}

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

{{/if}}More data on gnomAD'},ce={namespace:{assoc:"assoc",catalog:"catalog"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{{{namespace[catalog]}}variant|htmlescape}}
Catalog entries: {{n_catalog_matches|htmlescape}}
Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
More: GWAS catalog / dbSNP'},de={namespace:{access:"access"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Regulatory element
{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
Promoter
{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}Score: {{{{namespace[access]}}score|htmlescape}}"},ue={id:"significance",type:"orthogonal_line",tag:"significance",orientation:"horizontal",offset:oe},pe={namespace:{recomb:"recomb"},id:"recombrate",type:"line",tag:"recombination",fields:["{{namespace[recomb]}}position","{{namespace[recomb]}}recomb_rate"],z_index:1,style:{stroke:"#0000FF","stroke-width":"1.5px"},x_axis:{field:"{{namespace[recomb]}}position"},y_axis:{axis:2,field:"{{namespace[recomb]}}recomb_rate",floor:0,ceiling:100}},_e={namespace:{assoc:"assoc",ld:"ld"},id:"associationpvalues",type:"scatter",tag:"association",fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],id_field:"{{namespace[assoc]}}variant",coalesce:{active:!0},point_shape:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"diamond",else:"circle"}},point_size:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:80,else:40}},color:[{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"#9632b8"}},{scale_function:"numerical_bin",field:"{{namespace[ld]}}state",parameters:{breaks:[0,.2,.4,.6,.8],values:["#357ebd","#46b8da","#5cb85c","#eea236","#d43f3a"]}},"#B8B8B8"],legend:[{shape:"diamond",color:"#9632b8",size:40,label:"LD Ref Var",class:"lz-data_layer-scatter"},{shape:"circle",color:"#d43f3a",size:40,label:"1.0 > r² ≥ 0.8",class:"lz-data_layer-scatter"},{shape:"circle",color:"#eea236",size:40,label:"0.8 > r² ≥ 0.6",class:"lz-data_layer-scatter"},{shape:"circle",color:"#5cb85c",size:40,label:"0.6 > r² ≥ 0.4",class:"lz-data_layer-scatter"},{shape:"circle",color:"#46b8da",size:40,label:"0.4 > r² ≥ 0.2",class:"lz-data_layer-scatter"},{shape:"circle",color:"#357ebd",size:40,label:"0.2 > r² ≥ 0.0",class:"lz-data_layer-scatter"},{shape:"circle",color:"#B8B8B8",size:40,label:"no r² data",class:"lz-data_layer-scatter"}],label:null,z_index:2,x_axis:{field:"{{namespace[assoc]}}position"},y_axis:{axis:1,field:"{{namespace[assoc]}}log_pvalue",floor:0,upper_buffer:.1,min_extent:[0,10]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(re)},ge={namespace:{access:"access"},id:"coaccessibility",type:"arcs",tag:"coaccessibility",fields:["{{namespace[access]}}start1","{{namespace[access]}}end1","{{namespace[access]}}start2","{{namespace[access]}}end2","{{namespace[access]}}id","{{namespace[access]}}target","{{namespace[access]}}score"],match:{send:"{{namespace[access]}}target",receive:"{{namespace[access]}}target"},id_field:"{{namespace[access]}}id",filters:[{field:"{{namespace[access]}}score",operator:"!=",value:null}],color:[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#4285f4"}},{field:"lz_is_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},{scale_function:"ordinal_cycle",parameters:{values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"]}}],x_axis:{field1:"{{namespace[access]}}start1",field2:"{{namespace[access]}}start2"},y_axis:{axis:1,field:"{{namespace[access]}}score",upper_buffer:.1,min_extent:[0,1]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(de)},ye=function(){let t=J(_e);return t=Z({id:"associationpvaluescatalog",fill_opacity:.7},t),t.tooltip.html+='{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}',t.namespace.catalog="catalog",t.fields.push("{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue"),t}(),me={namespace:{phewas:"phewas"},id:"phewaspvalues",type:"category_scatter",tag:"phewas",point_shape:"circle",point_size:70,tooltip_positioning:"vertical",id_field:"{{namespace[phewas]}}id",fields:["{{namespace[phewas]}}id","{{namespace[phewas]}}log_pvalue","{{namespace[phewas]}}trait_group","{{namespace[phewas]}}trait_label"],x_axis:{field:"{{namespace[phewas]}}x",category_field:"{{namespace[phewas]}}trait_group",lower_buffer:.025,upper_buffer:.025},y_axis:{axis:1,field:"{{namespace[phewas]}}log_pvalue",floor:0,upper_buffer:.15},color:[{field:"{{namespace[phewas]}}trait_group",scale_function:"categorical_bin",parameters:{categories:[],values:[],null_value:"#B8B8B8"}}],fill_opacity:.7,tooltip:{closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:["Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
","Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
","P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
"].join("")},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},label:{text:"{{{{namespace[phewas]}}trait_label}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[phewas]}}log_pvalue",operator:">=",value:20}],style:{"font-size":"14px","font-weight":"bold",fill:"#333333"}}},fe={namespace:{gene:"gene",constraint:"constraint"},id:"genes",type:"genes",tag:"genes",fields:["{{namespace[gene]}}all","{{namespace[constraint]}}all"],id_field:"gene_id",behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(he)},be=Z({filters:[{field:"gene_type",operator:"in",value:["protein_coding","IG_C_gene","IG_D_gene","IG_J_gene","IG_V_gene","TR_C_gene","TR_D_gene","TR_J_gene","TR_V_gene","rRNA","Mt_rRNA","Mt_tRNA"]}]},J(fe)),xe={namespace:{assoc:"assoc",catalog:"catalog"},id:"annotation_catalog",type:"annotation_track",tag:"gwascatalog",id_field:"{{namespace[assoc]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:"#0000CC",fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}chromosome","{{namespace[assoc]}}position","{{namespace[catalog]}}variant","{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue","{{namespace[catalog]}}pos"],filters:[{field:"{{namespace[catalog]}}rsid",operator:"!=",value:null},{field:"{{namespace[catalog]}}log_pvalue",operator:">",value:oe}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(ce),tooltip_positioning:"top"},ve={type:"set_state",tag:"ld_population",position:"right",color:"blue",button_html:"LD Population: ",show_selected:!0,button_title:"Select LD Population: ",custom_event_name:"widget_set_ldpop",state_field:"ld_pop",options:[{display_name:"ALL (default)",value:"ALL"},{display_name:"AFR",value:"AFR"},{display_name:"AMR",value:"AMR"},{display_name:"EAS",value:"EAS"},{display_name:"EUR",value:"EUR"},{display_name:"SAS",value:"SAS"}]},we={type:"display_options",tag:"gene_filter",custom_event_name:"widget_gene_filter_choice",position:"right",color:"blue",button_html:"Filter...",button_title:"Choose which genes to show",layer_name:"genes",default_config_display_name:"Coding genes & rRNA",options:[{display_name:"All features",display:{filters:null}}]},ze={widgets:[{type:"remove_panel",position:"right",color:"red",group_position:"end"},{type:"move_panel_up",position:"right",group_position:"middle"},{type:"move_panel_down",position:"right",group_position:"start",style:{"margin-left":"0.75em"}}]},$e={widgets:[{type:"title",title:"LocusZoom",subtitle:'v0.13.3',position:"left"},{type:"download",position:"right",group_position:"end"},{type:"download_png",position:"right",group_position:"start"}]},ke=function(){const t=J($e);return t.widgets.push(J(ve)),t}(),Ee=function(){const t=J($e);return t.widgets.push({type:"shift_region",step:5e5,button_html:">>",position:"right",group_position:"end"},{type:"shift_region",step:5e4,button_html:">",position:"right",group_position:"middle"},{type:"zoom_region",step:.2,position:"right",group_position:"middle"},{type:"zoom_region",step:-.2,position:"right",group_position:"middle"},{type:"shift_region",step:-5e4,button_html:"<",position:"right",group_position:"middle"},{type:"shift_region",step:-5e5,button_html:"<<",position:"right",group_position:"start"}),t}(),Me={id:"association",tag:"association",min_height:200,height:225,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:function(){const t=J(ze);return t.widgets.push({type:"toggle_legend",position:"right"}),t}(),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"-log10 p-value",label_offset:28},y2:{label:"Recombination Rate (cM/Mb)",label_offset:40}},legend:{orientation:"vertical",origin:{x:55,y:40},hidden:!0},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,drag_y2_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(ue),J(pe),J(_e)]},Se={id:"coaccessibility",tag:"coaccessibility",min_height:150,height:180,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:J(ze),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"Score",label_offset:28,render:!1}},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(ge)]},Ne=function(){let t=J(Me);return t=Z({id:"associationcatalog",namespace:{assoc:"assoc",ld:"ld",catalog:"catalog"}},t),t.toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationpvaluescatalog",default_config_display_name:"No catalog labels (default)",options:[{display_name:"Label catalog traits",display:{label:{text:"{{{{namespace[catalog]}}trait}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[catalog]}}trait",operator:"!=",value:null},{field:"{{namespace[catalog]}}log_pvalue",operator:">",value:oe},{field:"{{namespace[ld]}}state",operator:">",value:.4}],style:{"font-size":"10px","font-weight":"bold",fill:"#333333"}}}}]}),t.data_layers=[J(ue),J(pe),J(ye)],t}(),Te={id:"genes",tag:"genes",min_height:150,height:225,margin:{top:20,right:50,bottom:20,left:50},axes:{},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},toolbar:function(){const t=J(ze);return t.widgets.push({type:"resize_to_data",position:"right",button_html:"Resize"},J(we)),t}(),data_layers:[J(be)]},Ae={id:"phewas",tag:"phewas",min_height:300,height:300,margin:{top:20,right:50,bottom:120,left:50},inner_border:"rgb(210, 210, 210)",axes:{x:{ticks:{style:{"font-weight":"bold","font-size":"11px","text-anchor":"start"},transform:"rotate(50)",position:"left"}},y1:{label:"-log10 p-value",label_offset:28}},data_layers:[J(ue),J(me)]},Le={id:"annotationcatalog",tag:"gwascatalog",min_height:50,height:50,margin:{top:25,right:50,bottom:10,left:50},inner_border:"rgb(210, 210, 210)",toolbar:J(ze),axes:{x:{extent:"state",render:!1}},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(xe)]},Oe={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:ke,panels:[J(Me),J(Te)]},Ce={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:ke,panels:[Le,Ne,Te]},Pe={width:800,responsive_resize:!0,toolbar:$e,panels:[J(Ae),Z({height:300,margin:{bottom:40},axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"}}},J(Te))],mouse_guide:!1},Re={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:J($e),panels:[J(Se),function(){const t=Object.assign({height:270},J(Te)),e=t.data_layers[0];e.match={send:"gene_name",receive:"gene_name"};const s=[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#4285f4"}},{field:"lz_is_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},"#363696"];return e.color=s,e.stroke=s,t}()]},De={standard_association:re,standard_association_with_label:le,standard_genes:he,catalog_variant:ce,coaccessibility:de},Ie={ldlz2_pop_selector:ve,gene_selector_menu:we},je={standard_panel:ze,standard_plot:$e,standard_association:ke,region_nav_plot:Ee},Be={significance:ue,recomb_rate:pe,association_pvalues:_e,coaccessibility:ge,association_pvalues_catalog:ye,phewas_pvalues:me,genes:fe,genes_filtered:be,annotation_catalog:xe},Ue={association:Me,coaccessibility:Se,association_catalog:Ne,genes:Te,phewas:Ae,annotation_catalog:Le},Fe={standard_association:Oe,association_catalog:Ce,standard_phewas:Pe,coaccessibility:Re};const qe=new class extends h{get(t,e,s={}){if(!t||!e)throw new Error("Must specify both the type and name for the layout desired. See .list() for available options");let i=super.get(t).get(e);if(i=Z(s,i),i.unnamespaced)return delete i.unnamespaced,J(i);let a="";"string"==typeof i.namespace?a=i.namespace:"object"==typeof i.namespace&&Object.keys(i.namespace).length&&(a=void 0!==i.namespace.default?i.namespace.default:i.namespace[Object.keys(i.namespace)[0]].toString()),a+=a.length?":":"";return J(H(i,i.namespace,a))}add(t,e,s,i=!1){if(!(t&&e&&s))throw new Error("To add a layout, type, name, and item must all be specified");if("object"!=typeof s)throw new Error("The configuration to be added must be an object");this.has(t)||super.add(t,new h);const a=J(s);return super.get(t).add(e,a,i)}list(t){if(!t){let t={};for(let[e,s]of this._items)t[e]=s.list();return t}return super.get(t).list()}merge(t,e){return Z(t,e)}renameField(){return V(...arguments)}mutate_attrs(){return Y(...arguments)}query_attrs(){return W(...arguments)}};for(let[t,e]of Object.entries(r))for(let[s,i]of Object.entries(e))qe.add(t,s,i);const Ge=qe;const He={version:l,populate:function(t,e,s){if(void 0===t)throw new Error("LocusZoom.populate selector not defined");let i;return k.select(t).html(""),k.select(t).call((function(t){if(void 0===t.node().id){let e=0;for(;!k.select(`#lz-${e}`).empty();)e++;t.attr("id",`#lz-${e}`)}if(i=new Mt(t.node().id,e,s),i.container=t.node(),void 0!==t.node().dataset&&void 0!==t.node().dataset.region){const e=function(t){const e=/^(\w+):([\d,.]+[kmgbKMGB]*)$/;let s=/^(\w+):([\d,.]+[kmgbKMGB]*)([-+])([\d,.]+[kmgbKMGB]*)$/.exec(t);if(s){if("+"===s[3]){const t=Nt(s[2]),e=Nt(s[4]);return{chr:s[1],start:t-e,end:t+e}}return{chr:s[1],start:Nt(s[2]),end:Nt(s[4])}}if(s=e.exec(t),s)return{chr:s[1],position:Nt(s[2])};return null}(t.node().dataset.region);Object.keys(e).forEach((function(t){i.state[t]=e[t]}))}i.svg=k.select(`div#${i.id}`).append("svg").attr("version","1.1").attr("xmlns","http://www.w3.org/2000/svg").attr("id",`${i.id}_svg`).attr("class","lz-locuszoom").call(et,i.layout.style),i.setDimensions(),i.positionPanels(),i.initialize(),e&&i.refresh()})),i},DataSources:class extends h{constructor(t){super(),this._registry=t||$}add(t,e,s=!1){if(this._registry.has(t))throw new Error(`The namespace ${t} is already in use by another source`);if(t.match(/[^A-Za-z0-9_]/))throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores. Invalid name: ${t}`);if(Array.isArray(e)){const[t,s]=e;e=this._registry.create(t,s)}return e.source_id=t,super.add(t,e,s),this}},Adapters:$,DataLayers:ne,Layouts:Ge,MatchFunctions:Lt,ScaleFunctions:Bt,TransformationFunctions:P,Widgets:xt,get KnownDataSources(){return console.warn('Deprecation warning: KnownDataSources has been renamed to "Adapters"'),$}},Ze=[];He.use=function(t,...e){if(!Ze.includes(t)){if(e.unshift(He),"function"==typeof t.install)t.install.apply(t,e);else{if("function"!=typeof t)throw new Error("Plugin must export a function that receives the LocusZoom object as an argument");t.apply(null,e)}Ze.push(t)}};const Je=He})(),LocusZoom=e.default})(); +/*! Locuszoom 0.13.4 */ +var LocusZoom;(()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};(()=>{t.d(e,{default:()=>Je});var s={};t.r(s),t.d(s,{AssociationLZ:()=>_,BaseAdapter:()=>u,BaseApiAdapter:()=>p,ConnectorSource:()=>w,GeneConstraintLZ:()=>f,GeneLZ:()=>m,GwasCatalogLZ:()=>y,LDServer:()=>g,PheWASLZ:()=>v,RecombLZ:()=>b,StaticSource:()=>x});var i={};t.r(i),t.d(i,{htmlescape:()=>T,is_numeric:()=>L,log10:()=>M,logtoscinotation:()=>N,neglog10:()=>S,scinotation:()=>A,urlencode:()=>O});var a={};t.r(a),t.d(a,{BaseWidget:()=>st,_Button:()=>it,display_options:()=>mt,download:()=>rt,download_png:()=>lt,filter_field:()=>ot,menu:()=>_t,move_panel_down:()=>dt,move_panel_up:()=>ct,region_scale:()=>nt,remove_panel:()=>ht,resize_to_data:()=>gt,set_state:()=>ft,shift_region:()=>ut,title:()=>at,toggle_legend:()=>yt,zoom_region:()=>pt});var n={};t.r(n),t.d(n,{categorical_bin:()=>Pt,if_value:()=>Ot,interpolate:()=>It,numerical_bin:()=>Ct,ordinal_cycle:()=>Rt,stable_choice:()=>Dt});var o={};t.r(o),t.d(o,{BaseDataLayer:()=>Ft,annotation_track:()=>Gt,arcs:()=>Kt,category_scatter:()=>ie,genes:()=>Yt,highlight_regions:()=>Zt,line:()=>Xt,orthogonal_line:()=>te,scatter:()=>se});var r={};t.r(r),t.d(r,{data_layer:()=>Be,panel:()=>Ue,plot:()=>Fe,toolbar:()=>je,toolbar_widgets:()=>Ie,tooltip:()=>De});const l="0.13.4";class h{constructor(){this._items=new Map}get(t){if(!this._items.has(t))throw new Error(`Item not found: ${t}`);return this._items.get(t)}add(t,e,s=!1){if(!s&&this._items.has(t))throw new Error(`Item ${t} is already defined`);return this._items.set(t,e),e}remove(t){return this._items.delete(t)}has(t){return this._items.has(t)}list(){return Array.from(this._items.keys())}}class c extends h{create(t,...e){return new(this.get(t))(...e)}extend(t,e,s){if(console.warn("Deprecation warning: .extend method will be removed in future versions, in favor of explicit ES6 subclasses"),3!==arguments.length)throw new Error("Invalid arguments to .extend");const i=this.get(t);class a extends i{}return Object.assign(a.prototype,s,i),this.add(e,a),a}}function d(t,e,s){if(e&&s||!e&&!s)throw new Error(`${t} must provide a parameter specifying either "build" or "source". It should not specify both.`);if(e&&!["GRCh37","GRCh38"].includes(e))throw new Error(`${t} must specify a valid genome build number`)}class u{constructor(t){this._enableCache=!0,this._cachedKey=null,this._cache_pos_start=null,this._cache_pos_end=null,this.__dependentSource=!1,this.parseInit(t)}parseInit(t){this.params=t.params||{}}getCacheKey(t,e,s){this.getURL(t,e,s);const i=t.chr,{_cache_pos_start:a,_cache_pos_end:n}=this;return a&&t.start>=a&&n&&t.end<=n?`${i}_${a}_${n}`:`${t.chr}_${t.start}_${t.end}`}getURL(t,e,s){return this.url}fetchRequest(t,e,s){const i=this.getURL(t,e,s);return fetch(i).then((t=>{if(!t.ok)throw new Error(t.statusText);return t.text()}))}getRequest(t,e,s){let i;const a=this.getCacheKey(t,e,s);return this._enableCache&&void 0!==a&&a===this._cachedKey?i=Promise.resolve(this._cachedResponse):(i=this.fetchRequest(t,e,s),this._enableCache&&(this._cachedKey=a,this._cache_pos_start=t.start,this._cache_pos_end=t.end,this._cachedResponse=i)),i}normalizeResponse(t){if(Array.isArray(t))return t;const e=Object.keys(t),s=t[e[0]].length;if(!e.every((function(e){return t[e].length===s})))throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);const i=[],a=Object.keys(t);for(let e=0;ePromise.resolve(this.annotateData(t,e)))).then((t=>Promise.resolve(this.extractFields(t,s,i,a)))).then((t=>(e.discrete[n]=t,Promise.resolve(this.combineChainBody(t,e,s,i,a))))).then((t=>({header:e.header||{},discrete:e.discrete,body:t})))}getData(t,e,s,i){if(this.preGetData){const a=this.preGetData(t,e,s,i);this.pre&&(t=a.state||t,e=a.fields||e,s=a.outnames||s,i=a.trans||i)}return a=>this.__dependentSource&&a&&a.body&&!a.body.length?Promise.resolve(a):this.getRequest(t,a,e).then((t=>this.parseResponse(t,a,e,s,i)))}}class p extends u{parseInit(t){if(super.parseInit(t),this.url=t.url,!this.url)throw new Error("Source not initialized with required URL")}}class _ extends p{preGetData(t,e,s,i){return[this.params.id_field||"id","position"].forEach((function(t){e.includes(t)||(e.unshift(t),s.unshift(t),i.unshift(null))})),{fields:e,outnames:s,trans:i}}getURL(t,e,s){const i=e.header.analysis||this.params.source||this.params.analysis;if(void 0===i)throw new Error("Association source must specify an analysis ID to plot");return`${this.url}results/?filter=analysis in ${i} and chromosome in '${t.chr}' and position ge ${t.start} and position le ${t.end}`}normalizeResponse(t){return t=super.normalizeResponse(t),this.params&&this.params.sort&&t.length&&t[0].position&&t.sort((function(t,e){return t.position-e.position})),t}}class g extends p{constructor(t){super(t),this.__dependentSource=!0}preGetData(t,e){if(e.length>1&&(2!==e.length||!e.includes("isrefvar")))throw new Error(`LD does not know how to get all fields: ${e.join(", ")}`)}findMergeFields(t){let e={id:this.params.id_field,position:this.params.position_field,pvalue:this.params.pvalue_field,_names_:null};if(t&&t.body&&t.body.length>0){const i=Object.keys(t.body[0]),a=(s=i,function(){const t=arguments;for(let e=0;ee}:function(t,e){return t{if(!t.ok)throw new Error(t.statusText);return t.text()})).then((function(t){return t=JSON.parse(t),Object.keys(t.data).forEach((function(e){a.data[e]=(a.data[e]||[]).concat(t.data[e])})),t.next?n(t.next):a}))};return n(i)}}class y extends p{constructor(t){super(t),this.__dependentSource=!0}getURL(t,e,s){const i=t.genome_build||this.params.build,a=this.params.source;d(this.constructor.name,i,a);const n=i?`&build=${i}`:` and id eq ${a}`;return`${this.url}?format=objects&sort=pos&filter=chrom eq '${t.chr}' and pos ge ${t.start} and pos le ${t.end}${n}`}findMergeFields(t){const e=Object.keys(t).find((function(t){return t.match(/\b(position|pos)\b/i)}));if(!e)throw new Error("Could not find data to align with GWAS catalog results");return{pos:e}}extractFields(t,e,s,i){return t}combineChainBody(t,e,s,i,a){if(!t.length)return e.body;const n="log_pvalue",o=i[s.indexOf(n)];function r(t,e,s,i,a){const r=t.n_catalog_matches||0;if(t.n_catalog_matches=r+1,!(t[o]&&t[o]>e[n]))for(let n=0;n25||"GRCh38"===i)return Promise.resolve({data:null});n=`{${n.join(" ")} }`;const o=this.getURL(t,e,s),r=JSON.stringify({query:n});return fetch(o,{method:"POST",body:r,headers:{"Content-Type":"application/json"}}).then((t=>t.ok?t.text():[])).catch((t=>[]))}combineChainBody(t,e,s,i,a){return t?(e.body.forEach((function(e){const s=`_${e.gene_name.replace(/[^A-Za-z0-9_]/g,"_")}`,i=t[s]&&t[s].gnomad_constraint;i&&Object.keys(i).forEach((function(t){let s=i[t];void 0===e[t]&&("number"==typeof s&&s.toString().includes(".")&&(s=parseFloat(s.toFixed(2))),e[t]=s)}))})),e.body):e}}class b extends p{getURL(t,e,s){const i=t.genome_build||this.params.build;let a=this.params.source;d(this.constructor.SOURCE_NAME,i,a);const n=i?`&build=${i}`:` and id in ${a}`;return`${this.url}?filter=chromosome eq '${t.chr}' and position le ${t.end} and position ge ${t.start}${n}`}}class x extends u{parseInit(t){this._data=t}getRequest(t,e,s){return Promise.resolve(this._data)}}class v extends p{getURL(t,e,s){const i=(t.genome_build?[t.genome_build]:null)||this.params.build;if(!i||!Array.isArray(i)||!i.length)throw new Error(["Adapter",this.constructor.SOURCE_NAME,"requires that you specify array of one or more desired genome build names"].join(" "));return[this.url,"?filter=variant eq '",encodeURIComponent(t.variant),"'&format=objects&",i.map((function(t){return`build=${encodeURIComponent(t)}`})).join("&")].join("")}getCacheKey(t,e,s){return this.getURL(t,e,s)}}class w extends u{constructor(t){if(super(t),!t||!t.sources)throw new Error("Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs");this._source_name_mapping=t.sources;const e=Object.keys(t.sources);this._getRequiredSources().forEach((t=>{if(!e.includes(t))throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${t}`)}))}parseInit(){}getRequest(t,e,s){return Object.keys(this._source_name_mapping).forEach((t=>{const s=this._source_name_mapping[t];if(e.discrete&&!e.discrete[s])throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${s}`)})),Promise.resolve(e.body||[])}parseResponse(t,e,s,i,a){return Promise.resolve(this.combineChainBody(t,e,s,i,a)).then((function(t){return{header:e.header||{},discrete:e.discrete||{},body:t}}))}combineChainBody(t,e){throw new Error("This method must be implemented in a subclass")}_getRequiredSources(){throw new Error("Must specify an array that identifes the kind of data required by this source")}}const z=new c;for(let[t,e]of Object.entries(s))z.add(t,e);z.add("StaticJSON",x),z.add("LDLZ2",g);const $=z,k=d3,E={verbs:["highlight","select","fade","hide"],adjectives:["highlighted","selected","faded","hidden"]};function M(t){return isNaN(t)||t<=0?null:Math.log(t)/Math.LN10}function S(t){return isNaN(t)||t<=0?null:-Math.log(t)/Math.LN10}function N(t){if(isNaN(t))return"NaN";if(0===t)return"1";const e=Math.ceil(t),s=e-t,i=Math.pow(10,s);return 1===e?(i/10).toFixed(4):2===e?(i/100).toFixed(3):`${i.toFixed(2)} × 10^-${e}`}function A(t){if(isNaN(t))return"NaN";if(0===t)return"0";const e=Math.abs(t);let s;return s=e>1?Math.ceil(Math.log(e)/Math.LN10):Math.floor(Math.log(e)/Math.LN10),Math.abs(s)<=3?t.toFixed(3):t.toExponential(2).replace("+","").replace("e"," × 10^")}function T(t){return t?(t=`${t}`).replace(/['"<>&`]/g,(function(t){switch(t){case"'":return"'";case'"':return""";case"<":return"<";case">":return">";case"&":return"&";case"`":return"`"}})):""}function L(t){return"number"==typeof t}function O(t){return encodeURIComponent(t)}const C=new class extends h{_collectTransforms(t){const e=t.match(/\|([^|]+)/g).map((t=>super.get(t.substring(1))));return t=>e.reduce(((t,e)=>e(t)),t)}get(t){return t?"|"===t.substring(0,1)?this._collectTransforms(t):super.get(t):null}};for(let[t,e]of Object.entries(i))C.add(t,e);const P=C;class R{constructor(t){const e=/^(?:([^:]+):)?([^:|]*)(\|.+)*$/.exec(t);this.full_name=t,this.namespace=e[1]||null,this.name=e[2]||null,this.transformations=[],"string"==typeof e[3]&&e[3].length>1&&(this.transformations=e[3].substring(1).split("|"),this.transformations.forEach(((t,e)=>this.transformations[e]=P.get(t))))}_applyTransformations(t){return this.transformations.forEach((function(e){t=e(t)})),t}resolve(t,e){if(void 0===t[this.full_name]){let s=null;void 0!==t[`${this.namespace}:${this.name}`]?s=t[`${this.namespace}:${this.name}`]:void 0!==t[this.name]?s=t[this.name]:e&&void 0!==e[this.full_name]&&(s=e[this.full_name]),t[this.full_name]=this._applyTransformations(s)}return t[this.full_name]}}const D=/^(\*|[\w]+)/,I=/^\[\?\(@((?:\.[\w]+)+) *===? *([0-9.eE-]+|"[^"]*"|'[^']*')\)\]/;function j(t){if(".."===t.substr(0,2)){if("["===t[2])return{text:"..",attr:"*",depth:".."};const e=D.exec(t.substr(2));if(!e)throw`Cannot parse ${JSON.stringify(t)} as dotdot_attr.`;return{text:`..${e[0]}`,attr:e[1],depth:".."}}if("."===t[0]){const e=D.exec(t.substr(1));if(!e)throw`Cannot parse ${JSON.stringify(t)} as dot_attr.`;return{text:`.${e[0]}`,attr:e[1],depth:"."}}if("["===t[0]){const e=I.exec(t);if(!e)throw`Cannot parse ${JSON.stringify(t)} as expr.`;let s;try{s=JSON.parse(e[2])}catch(t){s=JSON.parse(e[2].replace(/^'|'$/g,'"'))}return{text:e[0],attrs:e[1].substr(1).split("."),value:s}}throw`The query ${JSON.stringify(t)} doesn't look valid.`}function B(t,e){let s;for(let i of e)s=t,t=t[i];return[s,e[e.length-1],t]}function U(t,e){if(!e.length)return[[]];const s=e[0],i=e.slice(1);let a=[];if(s.attr&&"."===s.depth&&"*"!==s.attr){const n=t[s.attr];1===e.length?void 0!==n&&a.push([s.attr]):a.push(...U(n,i).map((t=>[s.attr].concat(t))))}else if(s.attr&&"."===s.depth&&"*"===s.attr)for(let[e,s]of Object.entries(t))a.push(...U(s,i).map((t=>[e].concat(t))));else if(s.attr&&".."===s.depth){if("object"==typeof t&&null!==t){"*"!==s.attr&&s.attr in t&&a.push(...U(t[s.attr],i).map((t=>[s.attr].concat(t))));for(let[n,o]of Object.entries(t))a.push(...U(o,e).map((t=>[n].concat(t)))),"*"===s.attr&&a.push(...U(o,i).map((t=>[n].concat(t))))}}else if(s.attrs)for(let[e,n]of Object.entries(t)){const[t,o,r]=B(n,s.attrs);r===s.value&&a.push(...U(n,i).map((t=>[e].concat(t))))}const n=(o=a,r=JSON.stringify,[...new Map(o.map((t=>[r(t),t]))).values()]);var o,r;return n.sort(((t,e)=>e.length-t.length||JSON.stringify(t).localeCompare(JSON.stringify(e)))),n}function F(t,e){const s=function(t,e){let s=[];for(let i of U(t,e))s.push(B(t,i));return s}(t,function(t){t=function(t){return t?(["$","["].includes(t[0])||(t=`$.${t}`),"$"===t[0]&&(t=t.substr(1)),t):""}(t);let e=[];for(;t.length;){const s=j(t);t=t.substr(s.text.length),e.push(s)}return e}(e));return s.length||console.warn(`No items matched the specified query: '${e}'`),s}const q=Math.sqrt(3),G={draw(t,e){const s=-Math.sqrt(e/(3*q));t.moveTo(0,2*-s),t.lineTo(-q*s,s),t.lineTo(q*s,s),t.closePath()}};function H(t,e,s){if(e?"string"==typeof e&&(e={default:e}):e={default:""},"string"==typeof t){const i=/\{\{namespace(\[[A-Za-z_0-9]+\]|)\}\}/g;let a,n,o,r;const l=[];for(;null!==(a=i.exec(t));)n=a[0],o=a[1].length?a[1].replace(/(\[|\])/g,""):null,r=s,null!=e&&"object"==typeof e&&void 0!==e[o]&&(r=e[o]+(e[o].length?":":"")),l.push({base:n,namespace:r});for(let e in l)t=t.replace(l[e].base,l[e].namespace)}else if("object"==typeof t&&null!=t){if(void 0!==t.namespace){e=Z(e,"string"==typeof t.namespace?{default:t.namespace}:t.namespace)}let i,a;for(let n in t)"namespace"!==n&&(i=H(t[n],e,s),a=H(n,e,s),n!==a&&delete t[n],t[a]=i)}return t}function Z(t,e){if("object"!=typeof t||"object"!=typeof e)throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof t}, ${typeof e} given`);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=null===t[s]?"undefined":typeof t[s],a=typeof e[s];if("object"===i&&Array.isArray(t[s])&&(i="array"),"object"===a&&Array.isArray(e[s])&&(a="array"),"function"===i||"function"===a)throw new Error("LocusZoom.Layouts.merge encountered an unsupported property type");"undefined"!==i?"object"!==i||"object"!==a||(t[s]=Z(t[s],e[s])):t[s]=J(e[s])}return t}function J(t){return JSON.parse(JSON.stringify(t))}function K(t){if(!t)return null;if("triangledown"===t)return G;const e=`symbol${t.charAt(0).toUpperCase()+t.slice(1)}`;return k[e]||null}function V(t,e,s,i=!0){const a=typeof t;if(Array.isArray(t))return t.map((t=>V(t,e,s,i)));if("object"===a&&null!==t)return Object.keys(t).reduce(((a,n)=>(a[n]=V(t[n],e,s,i),a)),{});if("string"!==a)return t;{const a=e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");if(i){const e=new RegExp(`${a}\\|\\w+`,"g");(t.match(e)||[]).forEach((t=>console.warn(`renameFields is renaming a field that uses transform functions: was '${t}' . Verify that these transforms are still appropriate.`)))}const n=new RegExp(`${a}(?!\\w+)`,"g");return t.replace(n,s)}}function Y(t,e,s){return function(t,e,s){return F(t,e).map((([t,e,i])=>{const a="function"==typeof s?s(i):s;return t[e]=a,a}))}(t,e,s)}function W(t,e){return function(t,e){return F(t,e).map((t=>t[2]))}(t,e)}const X=class{constructor(t){this._sources=t}__split_requests(t){var e={},s=/^(?:([^:]+):)?([^:|]*)(\|.+)*$/;return t.forEach((function(t){var i=s.exec(t),a=i[1]||"base",n=i[2],o=P.get(i[3]);void 0===e[a]&&(e[a]={outnames:[],fields:[],trans:[]}),e[a].outnames.push(t),e[a].fields.push(n),e[a].trans.push(o)})),e}getData(t,e){for(var s=this.__split_requests(e),i=Object.keys(s).map((e=>{if(!this._sources.get(e))throw new Error(`Datasource for namespace ${e} not found`);return this._sources.get(e).getData(t,s[e].fields,s[e].outnames,s[e].trans)})),a=Promise.resolve({header:{},body:[],discrete:{}}),n=0;n(this.curtain.showing||(this.curtain.selector=k.select(this.parent_plot.svg.node().parentNode).insert("div").attr("class","lz-curtain").attr("id",`${this.id}.curtain`),this.curtain.content_selector=this.curtain.selector.append("div").attr("class","lz-curtain-content"),this.curtain.selector.append("div").attr("class","lz-curtain-dismiss").html("Dismiss").on("click",(()=>this.curtain.hide())),this.curtain.showing=!0),this.curtain.update(t,e)),update:(t,e)=>{if(!this.curtain.showing)return this.curtain;clearTimeout(this.curtain.hide_delay),"object"==typeof e&&et(this.curtain.selector,e);const s=this._getPageOrigin(),i=this.layout.height||this._total_height;return this.curtain.selector.style("top",`${s.y}px`).style("left",`${s.x}px`).style("width",`${this.parent_plot.layout.width}px`).style("height",`${i}px`),this.curtain.content_selector.style("max-width",this.parent_plot.layout.width-40+"px").style("max-height",i-40+"px"),"string"==typeof t&&this.curtain.content_selector.html(t),this.curtain},hide:t=>this.curtain.showing?"number"==typeof t?(clearTimeout(this.curtain.hide_delay),this.curtain.hide_delay=setTimeout(this.curtain.hide,t),this.curtain):(this.curtain.selector.remove(),this.curtain.selector=null,this.curtain.content_selector=null,this.curtain.showing=!1,this.curtain):this.curtain}}function tt(){return{showing:!1,selector:null,content_selector:null,progress_selector:null,cancel_selector:null,show:t=>(this.loader.showing||(this.loader.selector=k.select(this.parent_plot.svg.node().parentNode).insert("div").attr("class","lz-loader").attr("id",`${this.id}.loader`),this.loader.content_selector=this.loader.selector.append("div").attr("class","lz-loader-content"),this.loader.progress_selector=this.loader.selector.append("div").attr("class","lz-loader-progress-container").append("div").attr("class","lz-loader-progress"),this.loader.showing=!0,void 0===t&&(t="Loading...")),this.loader.update(t)),update:(t,e)=>{if(!this.loader.showing)return this.loader;clearTimeout(this.loader.hide_delay),"string"==typeof t&&this.loader.content_selector.html(t);const s=this._getPageOrigin(),i=this.loader.selector.node().getBoundingClientRect();return this.loader.selector.style("top",s.y+this.layout.height-i.height-6+"px").style("left",`${s.x+6}px`),"number"==typeof e&&this.loader.progress_selector.style("width",`${Math.min(Math.max(e,1),100)}%`),this.loader},animate:()=>(this.loader.progress_selector.classed("lz-loader-progress-animated",!0),this.loader),setPercentCompleted:t=>(this.loader.progress_selector.classed("lz-loader-progress-animated",!1),this.loader.update(null,t)),hide:t=>this.loader.showing?"number"==typeof t?(clearTimeout(this.loader.hide_delay),this.loader.hide_delay=setTimeout(this.loader.hide,t),this.loader):(this.loader.selector.remove(),this.loader.selector=null,this.loader.content_selector=null,this.loader.progress_selector=null,this.loader.cancel_selector=null,this.loader.showing=!1,this.loader):this.loader}}function et(t,e){e=e||{};for(let[s,i]of Object.entries(e))t.style(s,i)}class st{constructor(t,e){this.layout=t||{},this.layout.color||(this.layout.color="gray"),this.parent=e||null,this.parent_panel=null,this.parent_plot=null,this.parent_svg=null,this.parent&&("panel"===this.parent.type?(this.parent_panel=this.parent.parent,this.parent_plot=this.parent.parent.parent,this.parent_svg=this.parent_panel):(this.parent_plot=this.parent.parent,this.parent_svg=this.parent_plot)),this.selector=null,this.button=null,this.persist=!1,this.layout.position||(this.layout.position="left")}show(){if(this.parent&&this.parent.selector){if(!this.selector){const t=["start","middle","end"].includes(this.layout.group_position)?` lz-toolbar-group-${this.layout.group_position}`:"";this.selector=this.parent.selector.append("div").attr("class",`lz-toolbar-${this.layout.position}${t}`),this.layout.style&&et(this.selector,this.layout.style),"function"==typeof this.initialize&&this.initialize()}return this.button&&"highlighted"===this.button.status&&this.button.menu.show(),this.selector.style("visibility","visible"),this.update(),this.position()}}update(){}position(){return this.button&&this.button.menu.position(),this}shouldPersist(){return!!this.persist||!(!this.button||!this.button.persist)}hide(){return!this.selector||this.shouldPersist()||(this.button&&this.button.menu.hide(),this.selector.style("visibility","hidden")),this}destroy(t){return void 0===t&&(t=!1),this.selector?(this.shouldPersist()&&!t||(this.button&&this.button.menu&&this.button.menu.destroy(),this.selector.remove(),this.selector=null,this.button=null),this):this}}class it{constructor(t){if(!(t instanceof st))throw new Error("Unable to create toolbar widget button, invalid parent");this.parent=t,this.parent_panel=this.parent.parent_panel,this.parent_plot=this.parent.parent_plot,this.parent_svg=this.parent.parent_svg,this.parent_toolbar=this.parent.parent,this.selector=null,this.tag="a",this.html="",this.title="",this.color="gray",this.style={},this.persist=!1,this.permanent=!1,this.status="",this.menu={outer_selector:null,inner_selector:null,scroll_position:0,hidden:!0,show:()=>(this.menu.outer_selector||(this.menu.outer_selector=k.select(this.parent_plot.svg.node().parentNode).append("div").attr("class",`lz-toolbar-menu lz-toolbar-menu-${this.color}`).attr("id",`${this.parent_svg.getBaseId()}.toolbar.menu`),this.menu.inner_selector=this.menu.outer_selector.append("div").attr("class","lz-toolbar-menu-content"),this.menu.inner_selector.on("scroll",(()=>{this.menu.scroll_position=this.menu.inner_selector.node().scrollTop}))),this.menu.outer_selector.style("visibility","visible"),this.menu.hidden=!1,this.menu.update()),update:()=>this.menu.outer_selector?(this.menu.populate(),this.menu.inner_selector&&(this.menu.inner_selector.node().scrollTop=this.menu.scroll_position),this.menu.position()):this.menu,position:()=>{if(!this.menu.outer_selector)return this.menu;this.menu.outer_selector.style("height",null);const t=this.parent_svg._getPageOrigin(),e=document.documentElement.scrollTop||document.body.scrollTop,s=this.parent_plot.getContainerOffset(),i=this.parent_toolbar.selector.node().getBoundingClientRect(),a=this.selector.node().getBoundingClientRect(),n=this.menu.outer_selector.node().getBoundingClientRect(),o=this.menu.inner_selector.node().scrollHeight;let r,l;"panel"===this.parent_toolbar.type?(r=t.y+i.height+6,l=Math.max(t.x+this.parent_plot.layout.width-n.width-3,t.x+3)):(r=a.bottom+e+3-s.top,l=Math.max(a.left+a.width-n.width-s.left,t.x+3));const h=Math.max(this.parent_plot.layout.width-6-20,20),c=h,d=h-12,u=Math.max(this.parent_svg.layout.height-30-14,14),p=Math.min(o+14,u);return this.menu.outer_selector.style("top",`${r}px`).style("left",`${l}px`).style("max-width",`${c}px`).style("max-height",`${u}px`).style("height",`${p}px`),this.menu.inner_selector.style("max-width",`${d}px`),this.menu.inner_selector.node().scrollTop=this.menu.scroll_position,this.menu},hide:()=>this.menu.outer_selector?(this.menu.outer_selector.style("visibility","hidden"),this.menu.hidden=!0,this.menu):this.menu,destroy:()=>this.menu.outer_selector?(this.menu.inner_selector.remove(),this.menu.outer_selector.remove(),this.menu.inner_selector=null,this.menu.outer_selector=null,this.menu):this.menu,populate:()=>{throw new Error("Method must be implemented")},setPopulate:t=>("function"==typeof t?(this.menu.populate=t,this.setOnclick((()=>{this.menu.hidden?(this.menu.show(),this.highlight().update(),this.persist=!0):(this.menu.hide(),this.highlight(!1).update(),this.permanent||(this.persist=!1))}))):this.setOnclick(),this)}}setColor(t){return void 0!==t&&(["gray","red","orange","yellow","green","blue","purple"].includes(t)?this.color=t:this.color="gray"),this}setPermanent(t){return t=void 0===t||Boolean(t),this.permanent=t,this.permanent&&(this.persist=!0),this}shouldPersist(){return this.permanent||this.persist}setStyle(t){return void 0!==t&&(this.style=t),this}getClass(){const t=["start","middle","end"].includes(this.parent.layout.group_position)?` lz-toolbar-button-group-${this.parent.layout.group_position}`:"";return`lz-toolbar-button lz-toolbar-button-${this.color}${this.status?`-${this.status}`:""}${t}`}setStatus(t){return void 0!==t&&["","highlighted","disabled"].includes(t)&&(this.status=t),this.update()}highlight(t){return(t=void 0===t||Boolean(t))?this.setStatus("highlighted"):"highlighted"===this.status?this.setStatus(""):this}disable(t){return(t=void 0===t||Boolean(t))?this.setStatus("disabled"):"disabled"===this.status?this.setStatus(""):this}onmouseover(){}setOnMouseover(t){return this.onmouseover="function"==typeof t?t:function(){},this}onmouseout(){}setOnMouseout(t){return this.onmouseout="function"==typeof t?t:function(){},this}onclick(){}setOnclick(t){return this.onclick="function"==typeof t?t:function(){},this}setTitle(t){return void 0!==t&&(this.title=t.toString()),this}setHtml(t){return void 0!==t&&(this.html=t.toString()),this}show(){if(this.parent)return this.selector||(this.selector=this.parent.selector.append(this.tag).attr("class",this.getClass())),this.update()}preUpdate(){return this}update(){return this.selector?(this.preUpdate(),this.selector.attr("class",this.getClass()).attr("title",this.title).on("mouseover","disabled"===this.status?null:this.onmouseover).on("mouseout","disabled"===this.status?null:this.onmouseout).on("click","disabled"===this.status?null:this.onclick).html(this.html).call(et,this.style),this.menu.update(),this.postUpdate(),this):this}postUpdate(){return this}hide(){return this.selector&&!this.shouldPersist()&&(this.selector.remove(),this.selector=null),this}}class at extends st{show(){return this.div_selector||(this.div_selector=this.parent.selector.append("div").attr("class",`lz-toolbar-title lz-toolbar-${this.layout.position}`),this.title_selector=this.div_selector.append("h3")),this.update()}update(){let t=this.layout.title.toString();return this.layout.subtitle&&(t+=` ${this.layout.subtitle}`),this.title_selector.html(t),this}}class nt extends st{update(){return isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end)||null===this.parent_plot.state.start||null===this.parent_plot.state.end?this.selector.style("display","none"):(this.selector.style("display",null),this.selector.html(St(this.parent_plot.state.end-this.parent_plot.state.start,null,!0))),this.layout.class&&this.selector.attr("class",this.layout.class),this.layout.style&&et(this.selector,this.layout.style),this}}class ot extends st{constructor(t,e){if(super(t,e),!this.parent_panel)throw new Error("Filter widget can only be used in panel toolbars");if(this._data_layer=this.parent_panel.data_layers[t.layer_name],!this._data_layer)throw new Error(`Filter widget could not locate the specified layer_name: '${t.layer_name}'`);if(this._event_name=t.custom_event_name||"widget_filter_field_action",this._field=t.field,this._field_display_html=t.field_display_html,this._operator=t.operator,this._filter_id=null,this._data_type=t.data_type||"number",!["number","string"].includes(this._data_type))throw new Error("Filter must be either string or number");this._value_selector=null}_getTarget(){this._data_layer.layout.filters||(this._data_layer.layout.filters=[]);let t=this._data_layer.layout.filters.find((t=>t.field===this._field&&t.operator===this._operator&&(!this._filter_id||t.id===this._filter_id)));return t||(t={field:this._field,operator:this._operator,value:null},this._filter_id&&(t.id=this._filter_id),this._data_layer.layout.filters.push(t)),t}_clearFilter(){if(this._data_layer.layout.filters){const t=this._data_layer.layout.filters.indexOf(this._getTarget());this._data_layer.layout.filters.splice(t,1)}}_setFilter(t){if(null===t)this._value_selector.style("border","1px solid red").style("color","red"),this._clearFilter();else{this._getTarget().value=t}this.parent_svg.emit(this._event_name,{field:this._field,operator:this._operator,value:t,filter_id:this._filter_id},!0)}_getValue(){let t=this._value_selector.property("value");return null===t||""===t||"number"===this._data_type&&(t=+t,Number.isNaN(t))?null:t}update(){this._value_selector||(this.selector.style("padding","0 6px"),this.selector.append("span").html(this._field_display_html).style("background","#fff").style("padding-left","3px"),this.selector.append("span").text(this._operator).style("padding","0 3px").style("background","#fff"),this._value_selector=this.selector.append("input").attr("size",this.layout.input_size||4).on("input",function(t,e=500){let s;return()=>{clearTimeout(s),s=setTimeout((()=>t.apply(this,arguments)),e)}}((()=>{this._value_selector.style("border",null).style("color",null);const t=this._getValue();this._setFilter(t),this.parent_panel.render()}),750)))}}class rt extends st{constructor(t,e){super(t,e),this._filename=this.layout.filename||"locuszoom.svg",this._button_html=this.layout.button_html||"Save SVG",this._button_title=this.layout.button_title||"Download hi-res image",this._event_name=t.custom_event_name||"widget_save_svg"}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this._button_html).setTitle(this._button_title).setOnMouseover((()=>{this.button.selector.classed("lz-toolbar-button-gray-disabled",!0).html("Preparing Image"),this._getBlobUrl().then((t=>{const e=this.button.selector.attr("href");e&&URL.revokeObjectURL(e),this.button.selector.attr("href",t).classed("lz-toolbar-button-gray-disabled",!1).classed("lz-toolbar-button-gray-highlighted",!0).html(this._button_html)}))})).setOnMouseout((()=>{this.button.selector.classed("lz-toolbar-button-gray-highlighted",!1)})),this.button.show(),this.button.selector.attr("href-lang","image/svg+xml").attr("download",this._filename).on("click",(()=>this.parent_svg.emit(this._event_name,{filename:this._filename},!0)))),this}_getCSS(t){const e=/^svg\.lz-locuszoom\s*/;let s="";for(let t=0;t{let e=this.parent_plot.svg.node().cloneNode(!0);e.setAttribute("xlink","http://www.w3.org/1999/xlink"),e=k.select(e),e.selectAll("g.lz-curtain").remove(),e.selectAll("g.lz-mouse_guide").remove(),e.selectAll("g.tick text").each((function(){const t=10*+k.select(this).attr("dy").substring(-2).slice(0,-2);k.select(this).attr("dy",t)}));const s=new XMLSerializer;e=e.node();const[i,a]=this._getDimensions();e.setAttribute("width",i),e.setAttribute("height",a),this._appendCSS(this._getCSS(e),e),t(s.serializeToString(e))}))}_getBlobUrl(){return this._generateSVG().then((t=>{const e=new Blob([t],{type:"image/svg+xml"});return URL.createObjectURL(e)}))}}class lt extends rt{constructor(t,e){super(...arguments),this._filename=this.layout.filename||"locuszoom.png",this._button_html=this.layout.button_html||"Save PNG",this._button_title=this.layout.button_title||"Download image",this._event_name=t.custom_event_name||"widget_save_png"}_getBlobUrl(){return super._getBlobUrl().then((t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),[i,a]=this._getDimensions();return e.width=i,e.height=a,new Promise(((n,o)=>{const r=new Image;r.onload=()=>{s.drawImage(r,0,0,i,a),URL.revokeObjectURL(t),e.toBlob((t=>{n(URL.createObjectURL(t))}))},r.src=t}))}))}}class ht extends st{update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml("×").setTitle("Remove panel").setOnclick((()=>{if(!this.layout.suppress_confirm&&!confirm("Are you sure you want to remove this panel? This cannot be undone."))return!1;const t=this.parent_panel;return t.toolbar.hide(!0),k.select(t.parent.svg.node().parentNode).on(`mouseover.${t.getBaseId()}.toolbar`,null),k.select(t.parent.svg.node().parentNode).on(`mouseout.${t.getBaseId()}.toolbar`,null),t.parent.removePanel(t.id)})),this.button.show()),this}}class ct extends st{update(){if(this.button){const t=0===this.parent_panel.layout.y_index;return this.button.disable(t),this}return this.button=new it(this).setColor(this.layout.color).setHtml("▴").setTitle("Move panel up").setOnclick((()=>{this.parent_panel.moveUp(),this.update()})),this.button.show(),this.update()}}class dt extends st{update(){if(this.button){const t=this.parent_panel.layout.y_index===this.parent_plot.panel_ids_by_y_index.length-1;return this.button.disable(t),this}return this.button=new it(this).setColor(this.layout.color).setHtml("▾").setTitle("Move panel down").setOnclick((()=>{this.parent_panel.moveDown(),this.update()})),this.button.show(),this.update()}}class ut extends st{constructor(t,e){if((isNaN(t.step)||0===t.step)&&(t.step=5e4),"string"!=typeof t.button_html&&(t.button_html=t.step>0?">":"<"),"string"!=typeof t.button_title&&(t.button_title=`Shift region by ${t.step>0?"+":"-"}${St(Math.abs(t.step),null,!0)}`),super(t,e),isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end))throw new Error("Unable to add shift_region toolbar widget: plot state does not have region bounds")}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{this.parent_plot.applyState({start:Math.max(this.parent_plot.state.start+this.layout.step,1),end:this.parent_plot.state.end+this.layout.step})})),this.button.show()),this}}class pt extends st{constructor(t,e){if((isNaN(t.step)||0===t.step)&&(t.step=.2),"string"!=typeof t.button_html&&(t.button_html=t.step>0?"z–":"z+"),"string"!=typeof t.button_title&&(t.button_title=`Zoom region ${t.step>0?"out":"in"} by ${(100*Math.abs(t.step)).toFixed(1)}%`),super(t,e),isNaN(this.parent_plot.state.start)||isNaN(this.parent_plot.state.end))throw new Error("Unable to add zoom_region toolbar widget: plot state does not have region bounds")}update(){if(this.button){let t=!0;const e=this.parent_plot.state.end-this.parent_plot.state.start;return this.layout.step>0&&!isNaN(this.parent_plot.layout.max_region_scale)&&e>=this.parent_plot.layout.max_region_scale&&(t=!1),this.layout.step<0&&!isNaN(this.parent_plot.layout.min_region_scale)&&e<=this.parent_plot.layout.min_region_scale&&(t=!1),this.button.disable(!t),this}return this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title).setOnclick((()=>{const t=this.parent_plot.state.end-this.parent_plot.state.start;let e=t*(1+this.layout.step);isNaN(this.parent_plot.layout.max_region_scale)||(e=Math.min(e,this.parent_plot.layout.max_region_scale)),isNaN(this.parent_plot.layout.min_region_scale)||(e=Math.max(e,this.parent_plot.layout.min_region_scale));const s=Math.floor((e-t)/2);this.parent_plot.applyState({start:Math.max(this.parent_plot.state.start-s,1),end:this.parent_plot.state.end+s})})),this.button.show(),this}}class _t extends st{update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html).setTitle(this.layout.button_title),this.button.menu.setPopulate((()=>{this.button.menu.inner_selector.html(this.layout.menu_html)})),this.button.show()),this}}class gt extends st{constructor(t){super(...arguments)}update(){return this.button||(this.button=new it(this).setColor(this.layout.color).setHtml(this.layout.button_html||"Resize to Data").setTitle(this.layout.button_title||"Automatically resize this panel to show all data available").setOnclick((()=>{this.parent_panel.scaleHeightToData(),this.update()})),this.button.show()),this}}class yt extends st{update(){const t=this.parent_panel.legend.layout.hidden?"Show Legend":"Hide Legend";return this.button?(this.button.setHtml(t).show(),this.parent.position(),this):(this.button=new it(this).setColor(this.layout.color).setTitle("Show or hide the legend for this panel").setOnclick((()=>{this.parent_panel.legend.layout.hidden=!this.parent_panel.legend.layout.hidden,this.parent_panel.legend.render(),this.update()})),this.update())}}class mt extends st{constructor(t,e){"string"!=typeof t.button_html&&(t.button_html="Display options..."),"string"!=typeof t.button_title&&(t.button_title="Control how plot items are displayed"),super(...arguments),this._event_name=t.custom_event_name||"widget_display_options_choice";const s=t.fields_whitelist||["color","fill_opacity","filters","label","legend","point_shape","point_size","tooltip","tooltip_positioning"],i=this.parent_panel.data_layers[t.layer_name];if(!i)throw new Error(`Display options could not locate the specified layer_name: '${t.layer_name}'`);const a=i.layout,n={};s.forEach((t=>{const e=a[t];void 0!==e&&(n[t]=J(e))})),this._selected_item="default",this.button=new it(this).setColor(t.color).setHtml(t.button_html).setTitle(t.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{const t=Math.floor(1e4*Math.random()).toString();this.button.menu.inner_selector.html("");const e=this.button.menu.inner_selector.append("table"),a=this.layout,o=(a,o,r)=>{const l=e.append("tr"),h=`${t}${r}`;l.append("td").append("input").attr("id",h).attr("type","radio").attr("name",`display-option-${t}`).attr("value",r).style("margin",0).property("checked",r===this._selected_item).on("click",(()=>{s.forEach((t=>{const e=void 0!==o[t];i.layout[t]=e?o[t]:n[t]})),this.parent_svg.emit(this._event_name,{choice:a},!0),this._selected_item=r,this.parent_panel.render();const t=this.parent_panel.legend;t&&t.render()})),l.append("td").append("label").style("font-weight","normal").attr("for",h).text(a)},r=a.default_config_display_name||"Default style";return o(r,n,"default"),a.options.forEach(((t,e)=>o(t.display_name,t.display,e))),this}))}update(){return this.button.show(),this}}class ft extends st{constructor(t,e){if("string"!=typeof t.button_html&&(t.button_html="Set option..."),"string"!=typeof t.button_title&&(t.button_title="Choose an option to customize the plot"),super(t,e),this.parent_panel)throw new Error("This widget is designed to set global options, so it can only be used at the top (plot) level");if(!t.state_field)throw new Error("Must specify the `state_field` that this widget controls");if(this._event_name=t.custom_event_name||"widget_set_state_choice",this._selected_item=this.parent_plot.state[t.state_field]||t.options[0].value,!t.options.find((t=>t.value===this._selected_item)))throw new Error("There is an existing state value that does not match the known values in this widget");this.button=new it(this).setColor(t.color).setHtml(t.button_html+(t.show_selected?this._selected_item:"")).setTitle(t.button_title).setOnclick((()=>{this.button.menu.populate()})),this.button.menu.setPopulate((()=>{const e=Math.floor(1e4*Math.random()).toString();this.button.menu.inner_selector.html("");const s=this.button.menu.inner_selector.append("table"),i=(i,a,n)=>{const o=s.append("tr"),r=`${e}${n}`;o.append("td").append("input").attr("id",r).attr("type","radio").attr("name",`set-state-${e}`).attr("value",n).style("margin",0).property("checked",a===this._selected_item).on("click",(()=>{const e={};e[t.state_field]=a,this._selected_item=a,this.parent_plot.applyState(e),this.button.setHtml(t.button_html+(t.show_selected?this._selected_item:"")),this.parent_svg.emit(this._event_name,{choice_name:i,choice_value:a,state_field:t.state_field},!0)})),o.append("td").append("label").style("font-weight","normal").attr("for",r).text(i)};return t.options.forEach(((t,e)=>i(t.display_name,t.value,e))),this}))}update(){return this.button.show(),this}}const bt=new c;for(let[t,e]of Object.entries(a))bt.add(t,e);const xt=bt;class vt{constructor(t){this.parent=t,this.id=`${this.parent.getBaseId()}.toolbar`,this.type=this.parent.parent?"panel":"plot",this.parent_plot=this.parent.parent_plot,this.selector=null,this.widgets=[],this.hide_timeout=null,this.persist=!1,this.initialize()}initialize(){const t=this.parent.layout.dashboard&&this.parent.layout.dashboard.components||this.parent.layout.toolbar.widgets;return Array.isArray(t)&&t.forEach((t=>{try{const e=xt.create(t.type,t,this);this.widgets.push(e)}catch(t){console.warn("Failed to create widget"),console.error(t)}})),"panel"===this.type&&k.select(this.parent.parent.svg.node().parentNode).on(`mouseover.${this.id}`,(()=>{clearTimeout(this.hide_timeout),this.selector&&"hidden"!==this.selector.style("visibility")||this.show()})).on(`mouseout.${this.id}`,(()=>{clearTimeout(this.hide_timeout),this.hide_timeout=setTimeout((()=>{this.hide()}),300)})),this}shouldPersist(){if(this.persist)return!0;let t=!1;return this.widgets.forEach((e=>{t=t||e.shouldPersist()})),t=t||this.parent_plot.panel_boundaries.dragging||this.parent_plot.interaction.dragging,!!t}show(){if(!this.selector){switch(this.type){case"plot":this.selector=k.select(this.parent.svg.node().parentNode).insert("div",":first-child");break;case"panel":this.selector=k.select(this.parent.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip, .lz-toolbar-menu, .lz-curtain").classed("lz-panel-toolbar",!0);break;default:throw new Error(`Toolbar cannot be a child of ${this.type}`)}this.selector.classed("lz-toolbar",!0).classed(`lz-${this.type}-toolbar`,!0).attr("id",this.id)}return this.widgets.forEach((t=>t.show())),this.selector.style("visibility","visible"),this.update()}update(){return this.selector?(this.widgets.forEach((t=>t.update())),this.position()):this}position(){if(!this.selector)return this;if("panel"===this.type){const t=this.parent._getPageOrigin(),e=`${(t.y+3.5).toString()}px`,s=`${t.x.toString()}px`,i=`${(this.parent_plot.layout.width-4).toString()}px`;this.selector.style("position","absolute").style("top",e).style("left",s).style("width",i)}return this.widgets.forEach((t=>t.position())),this}hide(){return!this.selector||this.shouldPersist()||(this.widgets.forEach((t=>t.hide())),this.selector.style("visibility","hidden")),this}destroy(t){return void 0===t&&(t=!1),this.selector?(this.shouldPersist()&&!t||(this.widgets.forEach((t=>t.destroy(!0))),this.widgets=[],this.selector.remove(),this.selector=null),this):this}}const wt={orientation:"vertical",origin:{x:0,y:0},width:10,height:10,padding:5,label_size:12,hidden:!1};class zt{constructor(t){return this.parent=t,this.id=`${this.parent.getBaseId()}.legend`,this.parent.layout.legend=Z(this.parent.layout.legend||{},wt),this.layout=this.parent.layout.legend,this.selector=null,this.background_rect=null,this.elements=[],this.elements_group=null,this.hidden=!1,this.render()}render(){this.selector||(this.selector=this.parent.svg.group.append("g").attr("id",`${this.parent.getBaseId()}.legend`).attr("class","lz-legend")),this.background_rect||(this.background_rect=this.selector.append("rect").attr("width",100).attr("height",100).attr("class","lz-legend-background")),this.elements_group||(this.elements_group=this.selector.append("g")),this.elements.forEach((t=>t.remove())),this.elements=[];const t=+this.layout.padding||1;let e=t,s=t,i=0;this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((a=>{Array.isArray(this.parent.data_layers[a].layout.legend)&&this.parent.data_layers[a].layout.legend.forEach((a=>{const n=this.elements_group.append("g").attr("transform",`translate(${e}, ${s})`),o=+a.label_size||+this.layout.label_size||12;let r=0,l=o/2+t/2;i=Math.max(i,o+t);const h=a.shape||"",c=K(h);if("line"===h){const e=+a.length||16,s=o/4+t/2;n.append("path").attr("class",a.class||"").attr("d",`M0,${s}L${e},${s}`).call(et,a.style||{}),r=e+t}else if("rect"===h){const e=+a.width||16,s=+a.height||e;n.append("rect").attr("class",a.class||"").attr("width",e).attr("height",s).attr("fill",a.color||{}).call(et,a.style||{}),r=e+t,i=Math.max(i,s+t)}else if(c){const e=+a.size||40,s=Math.ceil(Math.sqrt(e/Math.PI));n.append("path").attr("class",a.class||"").attr("d",k.symbol().size(e).type(c)).attr("transform",`translate(${s}, ${s+t/2})`).attr("fill",a.color||{}).call(et,a.style||{}),r=2*s+t,l=Math.max(2*s+t/2,l),i=Math.max(i,2*s+t)}n.append("text").attr("text-anchor","left").attr("class","lz-label").attr("x",r).attr("y",l).style("font-size",o).text(a.label);const d=n.node().getBoundingClientRect();if("vertical"===this.layout.orientation)s+=d.height+t,i=0;else{const a=this.layout.origin.x+e+d.width;e>t&&a>this.parent.parent.layout.width&&(s+=i,e=t,n.attr("transform",`translate(${e}, ${s})`)),e+=d.width+3*t}this.elements.push(n)}))}));const a=this.elements_group.node().getBoundingClientRect();return this.layout.width=a.width+2*this.layout.padding,this.layout.height=a.height+2*this.layout.padding,this.background_rect.attr("width",this.layout.width).attr("height",this.layout.height),this.selector.style("visibility",this.layout.hidden?"hidden":"visible"),this.position()}position(){if(!this.selector)return this;const t=this.selector.node().getBoundingClientRect();isNaN(+this.layout.pad_from_bottom)||(this.layout.origin.y=this.parent.layout.height-t.height-+this.layout.pad_from_bottom),isNaN(+this.layout.pad_from_right)||(this.layout.origin.x=this.parent.parent.layout.width-t.width-+this.layout.pad_from_right),this.selector.attr("transform",`translate(${this.layout.origin.x}, ${this.layout.origin.y})`)}hide(){this.layout.hidden=!0,this.render()}show(){this.layout.hidden=!1,this.render()}}const $t={id:"",tag:"custom_data_type",title:{text:"",style:{},x:10,y:22},y_index:null,min_height:1,height:1,origin:{x:0,y:null},margin:{top:0,right:0,bottom:0,left:0},background_click:"clear_selections",toolbar:{widgets:[]},cliparea:{height:0,width:0,origin:{x:0,y:0}},axes:{x:{},y1:{},y2:{}},legend:null,interaction:{drag_background_to_pan:!1,drag_x_ticks_to_scale:!1,drag_y1_ticks_to_scale:!1,drag_y2_ticks_to_scale:!1,scroll_to_zoom:!1,x_linked:!1,y1_linked:!1,y2_linked:!1},show_loading_indicator:!0,data_layers:[]};class kt{constructor(t,e){if("object"!=typeof t)throw new Error("Unable to create panel, invalid layout");if(this.parent=e||null,this.parent_plot=e,"string"==typeof t.id&&t.id.length){if(this.parent&&void 0!==this.parent.panels[t.id])throw new Error(`Cannot create panel with id [${t.id}]; panel with that id already exists`)}else if(this.parent){const e=()=>{let t=`p${Math.floor(Math.random()*Math.pow(10,8))}`;return null!==t&&void 0===this.parent.panels[t]||(t=e()),t};t.id=e()}else t.id=`p${Math.floor(Math.random()*Math.pow(10,8))}`;this.id=t.id,this.initialized=!1,this.layout_idx=null,this.svg={},this.layout=Z(t||{},$t),this.parent?(this.state=this.parent.state,this.state_id=this.id,this.state[this.state_id]=this.state[this.state_id]||{}):(this.state=null,this.state_id=null),this.data_layers={},this.data_layer_ids_by_z_index=[],this.data_promises=[],this.x_scale=null,this.y1_scale=null,this.y2_scale=null,this.x_extent=null,this.y1_extent=null,this.y2_extent=null,this.x_ticks=[],this.y1_ticks=[],this.y2_ticks=[],this.zoom_timeout=null,this.event_hooks={},this.initializeLayout()}on(t,e){if("string"!=typeof t)throw new Error(`Unable to register event hook. Event name must be a string: ${t.toString()}`);if("function"!=typeof e)throw new Error("Unable to register event hook, invalid hook function passed");return this.event_hooks[t]||(this.event_hooks[t]=[]),this.event_hooks[t].push(e),e}off(t,e){const s=this.event_hooks[t];if("string"!=typeof t||!Array.isArray(s))throw new Error(`Unable to remove event hook, invalid event: ${t.toString()}`);if(void 0===e)this.event_hooks[t]=[];else{const t=s.indexOf(e);if(-1===t)throw new Error("The specified event listener is not registered and therefore cannot be removed");s.splice(t,1)}return this}emit(t,e,s){if(s=s||!1,"string"!=typeof t)throw new Error(`LocusZoom attempted to throw an invalid event: ${t.toString()}`);"boolean"==typeof e&&2===arguments.length&&(s=e,e=null);const i={sourceID:this.getBaseId(),target:this,data:e||null};return this.event_hooks[t]&&this.event_hooks[t].forEach((t=>{t.call(this,i)})),s&&this.parent&&this.parent.emit(t,i),this}setTitle(t){if("string"==typeof this.layout.title){const t=this.layout.title;this.layout.title={text:t,x:0,y:0,style:{}}}return"string"==typeof t?this.layout.title.text=t:"object"==typeof t&&null!==t&&(this.layout.title=Z(t,this.layout.title)),this.layout.title.text.length?this.title.attr("display",null).attr("x",parseFloat(this.layout.title.x)).attr("y",parseFloat(this.layout.title.y)).text(this.layout.title.text).call(et,this.layout.title.style):this.title.attr("display","none"),this}addDataLayer(t){if("object"!=typeof t||"string"!=typeof t.id||!t.id.length)throw new Error("Invalid data layer layout");if(void 0!==this.data_layers[t.id])throw new Error(`Cannot create data_layer with id [${t.id}]; data layer with that id already exists in the panel`);if("string"!=typeof t.type)throw new Error("Invalid data layer type");"object"!=typeof t.y_axis||void 0!==t.y_axis.axis&&[1,2].includes(t.y_axis.axis)||(t.y_axis.axis=1);const e=ne.create(t.type,t,this);if(this.data_layers[e.id]=e,null!==e.layout.z_index&&!isNaN(e.layout.z_index)&&this.data_layer_ids_by_z_index.length>0)e.layout.z_index<0&&(e.layout.z_index=Math.max(this.data_layer_ids_by_z_index.length+e.layout.z_index,0)),this.data_layer_ids_by_z_index.splice(e.layout.z_index,0,e.id),this.data_layer_ids_by_z_index.forEach(((t,e)=>{this.data_layers[t].layout.z_index=e}));else{const t=this.data_layer_ids_by_z_index.push(e.id);this.data_layers[e.id].layout.z_index=t-1}let s=null;return this.layout.data_layers.forEach(((t,i)=>{t.id===e.id&&(s=i)})),null===s&&(s=this.layout.data_layers.push(this.data_layers[e.id].layout)-1),this.data_layers[e.id].layout_idx=s,this.data_layers[e.id]}removeDataLayer(t){if(!this.data_layers[t])throw new Error(`Unable to remove data layer, ID not found: ${t}`);return this.data_layers[t].destroyAllTooltips(),this.data_layers[t].svg.container&&this.data_layers[t].svg.container.remove(),this.layout.data_layers.splice(this.data_layers[t].layout_idx,1),delete this.state[this.data_layers[t].state_id],delete this.data_layers[t],this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(t),1),this.applyDataLayerZIndexesToDataLayerLayouts(),this.layout.data_layers.forEach(((t,e)=>{this.data_layers[t.id].layout_idx=e})),this}clearSelections(){return this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].setAllElementStatus("selected",!1)})),this}render(){this.svg.container.attr("transform",`translate(${this.layout.origin.x}, ${this.layout.origin.y})`),this.svg.clipRect.attr("width",this.parent_plot.layout.width).attr("height",this.layout.height),this.inner_border.attr("x",this.layout.margin.left).attr("y",this.layout.margin.top).attr("width",this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right)).attr("height",this.layout.height-(this.layout.margin.top+this.layout.margin.bottom)),this.layout.inner_border&&this.inner_border.style("stroke-width",1).style("stroke",this.layout.inner_border),this.setTitle(),this.generateExtents();const t=function(t,e){const s=Math.pow(-10,e),i=Math.pow(-10,-e),a=Math.pow(10,-e),n=Math.pow(10,e);return t===1/0&&(t=n),t===-1/0&&(t=s),0===t&&(t=a),t>0&&(t=Math.max(Math.min(t,n),a)),t<0&&(t=Math.max(Math.min(t,i),s)),t},e={};if(this.x_extent){const t={start:0,end:this.layout.cliparea.width};this.layout.axes.x.range&&(t.start=this.layout.axes.x.range.start||t.start,t.end=this.layout.axes.x.range.end||t.end),e.x=[t.start,t.end],e.x_shifted=[t.start,t.end]}if(this.y1_extent){const t={start:this.layout.cliparea.height,end:0};this.layout.axes.y1.range&&(t.start=this.layout.axes.y1.range.start||t.start,t.end=this.layout.axes.y1.range.end||t.end),e.y1=[t.start,t.end],e.y1_shifted=[t.start,t.end]}if(this.y2_extent){const t={start:this.layout.cliparea.height,end:0};this.layout.axes.y2.range&&(t.start=this.layout.axes.y2.range.start||t.start,t.end=this.layout.axes.y2.range.end||t.end),e.y2=[t.start,t.end],e.y2_shifted=[t.start,t.end]}if(this.parent.interaction.panel_id&&(this.parent.interaction.panel_id===this.id||this.parent.interaction.linked_panel_ids.includes(this.id))){let s,i=null;if(this.parent.interaction.zooming&&"function"==typeof this.x_scale){const t=Math.abs(this.x_extent[1]-this.x_extent[0]),i=Math.round(this.x_scale.invert(e.x_shifted[1]))-Math.round(this.x_scale.invert(e.x_shifted[0]));let a=this.parent.interaction.zooming.scale;const n=Math.floor(i*(1/a));a<1&&!isNaN(this.parent.layout.max_region_scale)?a=1/(Math.min(n,this.parent.layout.max_region_scale)/i):a>1&&!isNaN(this.parent.layout.min_region_scale)&&(a=1/(Math.max(n,this.parent.layout.min_region_scale)/i));const o=Math.floor(t*a);s=this.parent.interaction.zooming.center-this.layout.margin.left-this.layout.origin.x;const r=s/this.layout.cliparea.width,l=Math.max(Math.floor(this.x_scale.invert(e.x_shifted[0])-(o-i)*r),1);e.x_shifted=[this.x_scale(l),this.x_scale(l+o)]}else if(this.parent.interaction.dragging)switch(this.parent.interaction.dragging.method){case"background":e.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,e.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x;break;case"x_tick":k.event&&k.event.shiftKey?(e.x_shifted[0]=+this.parent.interaction.dragging.dragged_x,e.x_shifted[1]=this.layout.cliparea.width+this.parent.interaction.dragging.dragged_x):(s=this.parent.interaction.dragging.start_x-this.layout.margin.left-this.layout.origin.x,i=t(s/(s+this.parent.interaction.dragging.dragged_x),3),e.x_shifted[0]=0,e.x_shifted[1]=Math.max(this.layout.cliparea.width*(1/i),1));break;case"y1_tick":case"y2_tick":{const a=`y${this.parent.interaction.dragging.method[1]}_shifted`;k.event&&k.event.shiftKey?(e[a][0]=this.layout.cliparea.height+this.parent.interaction.dragging.dragged_y,e[a][1]=+this.parent.interaction.dragging.dragged_y):(s=this.layout.cliparea.height-(this.parent.interaction.dragging.start_y-this.layout.margin.top-this.layout.origin.y),i=t(s/(s-this.parent.interaction.dragging.dragged_y),3),e[a][0]=this.layout.cliparea.height,e[a][1]=this.layout.cliparea.height-this.layout.cliparea.height*(1/i))}}}if(["x","y1","y2"].forEach((t=>{this[`${t}_extent`]&&(this[`${t}_scale`]=k.scaleLinear().domain(this[`${t}_extent`]).range(e[`${t}_shifted`]),this[`${t}_extent`]=[this[`${t}_scale`].invert(e[t][0]),this[`${t}_scale`].invert(e[t][1])],this[`${t}_scale`]=k.scaleLinear().domain(this[`${t}_extent`]).range(e[t]),this.renderAxis(t))})),this.layout.interaction.scroll_to_zoom){const t=()=>{if(!k.event.shiftKey&&!k.event.altKey)return void(this.parent._canInteract(this.id)&&this.loader.show("Press [SHIFT] or [ALT] while scrolling to zoom").hide(1e3));if(k.event.preventDefault(),!this.parent._canInteract(this.id))return;const t=k.mouse(this.svg.container.node()),e=Math.max(-1,Math.min(1,k.event.wheelDelta||-k.event.detail||-k.event.deltaY));0!==e&&(this.parent.interaction={panel_id:this.id,linked_panel_ids:this.getLinkedPanelIds("x"),zooming:{scale:e<1?.9:1.1,center:t[0]}},this.render(),this.parent.interaction.linked_panel_ids.forEach((t=>{this.parent.panels[t].render()})),null!==this.zoom_timeout&&clearTimeout(this.zoom_timeout),this.zoom_timeout=setTimeout((()=>{this.parent.interaction={},this.parent.applyState({start:this.x_extent[0],end:this.x_extent[1]})}),500))};this.svg.container.on("wheel.zoom",t).on("mousewheel.zoom",t).on("DOMMouseScroll.zoom",t)}return this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].draw().render()})),this.legend&&this.legend.render(),this}addBasicLoader(t=!0){return this.layout.show_loading_indicator&&this.initialized||(t&&this.loader.show("Loading...").animate(),this.on("data_requested",(()=>{this.loader.show("Loading...").animate()})),this.on("data_rendered",(()=>{this.loader.hide()})),this.layout.show_loading_indicator=!0),this}applyDataLayerZIndexesToDataLayerLayouts(){this.data_layer_ids_by_z_index.forEach(((t,e)=>{this.data_layers[t].layout.z_index=e}))}getBaseId(){return`${this.parent.id}.${this.id}`}_getPageOrigin(){const t=this.parent._getPageOrigin();return{x:t.x+this.layout.origin.x,y:t.y+this.layout.origin.y}}initializeLayout(){return this.setDimensions(),this.setOrigin(),this.setMargin(),this.x_range=[0,this.layout.cliparea.width],this.y1_range=[this.layout.cliparea.height,0],this.y2_range=[this.layout.cliparea.height,0],["x","y1","y2"].forEach((t=>{Object.keys(this.layout.axes[t]).length&&!1!==this.layout.axes[t].render?(this.layout.axes[t].render=!0,this.layout.axes[t].label=this.layout.axes[t].label||null):this.layout.axes[t].render=!1})),this.layout.data_layers.forEach((t=>{this.addDataLayer(t)})),this}setDimensions(t,e){return void 0!==t&&void 0!==e&&!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0&&(this.parent.layout.width=Math.round(+t),this.layout.height=Math.max(Math.round(+e),this.layout.min_height)),this.layout.cliparea.width=Math.max(this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.svg.clipRect&&this.svg.clipRect.attr("width",this.parent.layout.width).attr("height",this.layout.height),this.initialized&&(this.render(),this.curtain.update(),this.loader.update(),this.toolbar.update(),this.legend&&this.legend.position()),this}setOrigin(t,e){return!isNaN(t)&&t>=0&&(this.layout.origin.x=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.origin.y=Math.max(Math.round(+e),0)),this.initialized&&this.render(),this}setMargin(t,e,s,i){let a;return!isNaN(t)&&t>=0&&(this.layout.margin.top=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(this.layout.margin.right=Math.max(Math.round(+e),0)),!isNaN(s)&&s>=0&&(this.layout.margin.bottom=Math.max(Math.round(+s),0)),!isNaN(i)&&i>=0&&(this.layout.margin.left=Math.max(Math.round(+i),0)),this.layout.margin.top+this.layout.margin.bottom>this.layout.height&&(a=Math.floor((this.layout.margin.top+this.layout.margin.bottom-this.layout.height)/2),this.layout.margin.top-=a,this.layout.margin.bottom-=a),this.layout.margin.left+this.layout.margin.right>this.parent_plot.layout.width&&(a=Math.floor((this.layout.margin.left+this.layout.margin.right-this.parent_plot.layout.width)/2),this.layout.margin.left-=a,this.layout.margin.right-=a),["top","right","bottom","left"].forEach((t=>{this.layout.margin[t]=Math.max(this.layout.margin[t],0)})),this.layout.cliparea.width=Math.max(this.parent_plot.layout.width-(this.layout.margin.left+this.layout.margin.right),0),this.layout.cliparea.height=Math.max(this.layout.height-(this.layout.margin.top+this.layout.margin.bottom),0),this.layout.cliparea.origin.x=this.layout.margin.left,this.layout.cliparea.origin.y=this.layout.margin.top,this.initialized&&this.render(),this}initialize(){const t=this.getBaseId();this.svg.container=this.parent.svg.append("g").attr("id",`${t}.panel_container`).attr("transform",`translate(${this.layout.origin.x||0}, ${this.layout.origin.y||0})`);const e=this.svg.container.append("clipPath").attr("id",`${t}.clip`);if(this.svg.clipRect=e.append("rect").attr("width",this.parent_plot.layout.width).attr("height",this.layout.height),this.svg.group=this.svg.container.append("g").attr("id",`${t}.panel`).attr("clip-path",`url(#${t}.clip)`),this.curtain=Q.call(this),this.loader=tt.call(this),this.layout.show_loading_indicator&&this.addBasicLoader(!1),this.toolbar=new vt(this),this.inner_border=this.svg.group.append("rect").attr("class","lz-panel-background").on("click",(()=>{"clear_selections"===this.layout.background_click&&this.clearSelections()})),this.title=this.svg.group.append("text").attr("class","lz-panel-title"),void 0!==this.layout.title&&this.setTitle(),this.svg.x_axis=this.svg.group.append("g").attr("id",`${t}.x_axis`).attr("class","lz-x lz-axis"),this.layout.axes.x.render&&(this.svg.x_axis_label=this.svg.x_axis.append("text").attr("class","lz-x lz-axis lz-label").attr("text-anchor","middle")),this.svg.y1_axis=this.svg.group.append("g").attr("id",`${t}.y1_axis`).attr("class","lz-y lz-y1 lz-axis"),this.layout.axes.y1.render&&(this.svg.y1_axis_label=this.svg.y1_axis.append("text").attr("class","lz-y1 lz-axis lz-label").attr("text-anchor","middle")),this.svg.y2_axis=this.svg.group.append("g").attr("id",`${t}.y2_axis`).attr("class","lz-y lz-y2 lz-axis"),this.layout.axes.y2.render&&(this.svg.y2_axis_label=this.svg.y2_axis.append("text").attr("class","lz-y2 lz-axis lz-label").attr("text-anchor","middle")),this.data_layer_ids_by_z_index.forEach((t=>{this.data_layers[t].initialize()})),this.legend=null,this.layout.legend&&(this.legend=new zt(this)),this.layout.interaction.drag_background_to_pan){const t=`.${this.parent.id}.${this.id}.interaction.drag`,e=()=>this.parent.startDrag(this,"background");this.svg.container.select(".lz-panel-background").on(`mousedown${t}.background`,e).on(`touchstart${t}.background`,e)}return this}resortDataLayers(){const t=[];this.data_layer_ids_by_z_index.forEach((e=>{t.push(this.data_layers[e].layout.z_index)})),this.svg.group.selectAll("g.lz-data_layer-container").data(t).sort(k.ascending),this.applyDataLayerZIndexesToDataLayerLayouts()}getLinkedPanelIds(t){const e=[];return["x","y1","y2"].includes(t=t||null)&&this.layout.interaction[`${t}_linked`]?(this.parent.panel_ids_by_y_index.forEach((s=>{s!==this.id&&this.parent.panels[s].layout.interaction[`${t}_linked`]&&e.push(s)})),e):e}moveUp(){return this.parent.panel_ids_by_y_index[this.layout.y_index-1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index-1],this.parent.panel_ids_by_y_index[this.layout.y_index-1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}moveDown(){return this.parent.panel_ids_by_y_index[this.layout.y_index+1]&&(this.parent.panel_ids_by_y_index[this.layout.y_index]=this.parent.panel_ids_by_y_index[this.layout.y_index+1],this.parent.panel_ids_by_y_index[this.layout.y_index+1]=this.id,this.parent.applyPanelYIndexesToPanelLayouts(),this.parent.positionPanels()),this}reMap(){this.emit("data_requested"),this.data_promises=[],this.curtain.hide();for(let t in this.data_layers)try{this.data_promises.push(this.data_layers[t].reMap())}catch(t){console.error(t),this.curtain.show(t.message||t)}return Promise.all(this.data_promises).then((()=>{this.initialized=!0,this.render(),this.emit("layout_changed",!0),this.emit("data_rendered")})).catch((t=>{console.error(t),this.curtain.show(t.message||t)}))}generateExtents(){["x","y1","y2"].forEach((t=>{this[`${t}_extent`]=null}));for(let t in this.data_layers){const e=this.data_layers[t];if(e.layout.x_axis&&!e.layout.x_axis.decoupled&&(this.x_extent=k.extent((this.x_extent||[]).concat(e.getAxisExtent("x")))),e.layout.y_axis&&!e.layout.y_axis.decoupled){const t=`y${e.layout.y_axis.axis}`;this[`${t}_extent`]=k.extent((this[`${t}_extent`]||[]).concat(e.getAxisExtent("y")))}}return this.layout.axes.x&&"state"===this.layout.axes.x.extent&&(this.x_extent=[this.state.start,this.state.end]),this}generateTicks(t){if(this.layout.axes[t].ticks){const e=this.layout.axes[t].ticks;if(Array.isArray(e))return e;if("object"==typeof e){const s=this,i={position:e.position};return this.data_layer_ids_by_z_index.reduce(((e,a)=>{const n=s.data_layers[a];return e.concat(n.getTicks(t,i))}),[]).map((t=>{let s={};return s=Z(s,e),Z(s,t)}))}}return this[`${t}_extent`]?function(t,e,s){(void 0===s||isNaN(parseInt(s)))&&(s=5);const i=(s=+s)/3,a=.75,n=1.5,o=.5+1.5*n,r=Math.abs(t[0]-t[1]);let l=r/s;Math.log(r)/Math.LN10<-2&&(l=Math.max(Math.abs(r))*a/i);const h=Math.pow(10,Math.floor(Math.log(l)/Math.LN10));let c=0;h<1&&0!==h&&(c=Math.abs(Math.round(Math.log(h)/Math.LN10)));let d=h;2*h-l0&&(p=parseFloat(p.toFixed(c)));u.push(p),(void 0===e||-1===["low","high","both","neither"].indexOf(e))&&(e="neither");"low"!==e&&"both"!==e||u[0]t[1]&&u.pop();return u}(this[`${t}_extent`],"both"):[]}renderAxis(t){if(!["x","y1","y2"].includes(t))throw new Error(`Unable to render axis; invalid axis identifier: ${t}`);const e=this.layout.axes[t].render&&"function"==typeof this[`${t}_scale`]&&!isNaN(this[`${t}_scale`](0));if(this[`${t}_axis`]&&this.svg.container.select(`g.lz-axis.lz-${t}`).style("display",e?null:"none"),!e)return this;const s={x:{position:`translate(${this.layout.margin.left}, ${this.layout.height-this.layout.margin.bottom})`,orientation:"bottom",label_x:this.layout.cliparea.width/2,label_y:this.layout.axes[t].label_offset||0,label_rotate:null},y1:{position:`translate(${this.layout.margin.left}, ${this.layout.margin.top})`,orientation:"left",label_x:-1*(this.layout.axes[t].label_offset||0),label_y:this.layout.cliparea.height/2,label_rotate:-90},y2:{position:`translate(${this.parent_plot.layout.width-this.layout.margin.right}, ${this.layout.margin.top})`,orientation:"right",label_x:this.layout.axes[t].label_offset||0,label_y:this.layout.cliparea.height/2,label_rotate:-90}};this[`${t}_ticks`]=this.generateTicks(t);const i=(t=>{for(let e=0;eSt(t,6)));else{let e=this[`${t}_ticks`].map((e=>e[t.substr(0,1)]));this[`${t}_axis`].tickValues(e).tickFormat(((e,s)=>this[`${t}_ticks`][s].text))}if(this.svg[`${t}_axis`].attr("transform",s[t].position).call(this[`${t}_axis`]),!i){const e=k.selectAll(`g#${this.getBaseId().replace(".","\\.")}\\.${t}_axis g.tick`),s=this;e.each((function(e,i){const a=k.select(this).select("text");s[`${t}_ticks`][i].style&&et(a,s[`${t}_ticks`][i].style),s[`${t}_ticks`][i].transform&&a.attr("transform",s[`${t}_ticks`][i].transform)}))}const n=this.layout.axes[t].label||null;return null!==n&&(this.svg[`${t}_axis_label`].attr("x",s[t].label_x).attr("y",s[t].label_y).text(At(n,this.state)).attr("fill","currentColor"),null!==s[t].label_rotate&&this.svg[`${t}_axis_label`].attr("transform",`rotate(${s[t].label_rotate} ${s[t].label_x}, ${s[t].label_y})`)),["x","y1","y2"].forEach((t=>{if(this.layout.interaction[`drag_${t}_ticks_to_scale`]){const e=`.${this.parent.id}.${this.id}.interaction.drag`,s=function(){"function"==typeof k.select(this).node().focus&&k.select(this).node().focus();let i="x"===t?"ew-resize":"ns-resize";k.event&&k.event.shiftKey&&(i="move"),k.select(this).style("font-weight","bold").style("cursor",i).on(`keydown${e}`,s).on(`keyup${e}`,s)};this.svg.container.selectAll(`.lz-axis.lz-${t} .tick text`).attr("tabindex",0).on(`mouseover${e}`,s).on(`mouseout${e}`,(function(){k.select(this).style("font-weight","normal").on(`keydown${e}`,null).on(`keyup${e}`,null)})).on(`mousedown${e}`,(()=>{this.parent.startDrag(this,`${t}_tick`)}))}})),this}scaleHeightToData(t){null===(t=+t||null)&&this.data_layer_ids_by_z_index.forEach((e=>{const s=this.data_layers[e].getAbsoluteDataHeight();+s&&(t=null===t?+s:Math.max(t,+s))})),+t&&(t+=+this.layout.margin.top+ +this.layout.margin.bottom,this.setDimensions(this.parent_plot.layout.width,t),this.parent.setDimensions(),this.parent.positionPanels())}setAllElementStatus(t,e){this.data_layer_ids_by_z_index.forEach((s=>{this.data_layers[s].setAllElementStatus(t,e)}))}}E.verbs.forEach(((t,e)=>{const s=E.adjectives[e],i=`un${t}`;kt.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},kt.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const Et={state:{},width:800,min_width:400,min_region_scale:null,max_region_scale:null,responsive_resize:!1,panels:[],toolbar:{widgets:[]},panel_boundaries:!0,mouse_guide:!0};class Mt{constructor(t,e,s){this.initialized=!1,this.parent_plot=this,this.id=t,this.container=null,this.svg=null,this.panels={},this.panel_ids_by_y_index=[],this.remap_promises=[],this.layout=s,Z(this.layout,Et),this._base_layout=J(this.layout),this.state=this.layout.state,this.lzd=new X(e),this._external_listeners=new Map,this.event_hooks={},this.interaction={},this.initializeLayout()}on(t,e){if("string"!=typeof t)throw new Error(`Unable to register event hook. Event name must be a string: ${t.toString()}`);if("function"!=typeof e)throw new Error("Unable to register event hook, invalid hook function passed");return this.event_hooks[t]||(this.event_hooks[t]=[]),this.event_hooks[t].push(e),e}off(t,e){const s=this.event_hooks[t];if("string"!=typeof t||!Array.isArray(s))throw new Error(`Unable to remove event hook, invalid event: ${t.toString()}`);if(void 0===e)this.event_hooks[t]=[];else{const t=s.indexOf(e);if(-1===t)throw new Error("The specified event listener is not registered and therefore cannot be removed");s.splice(t,1)}return this}emit(t,e){const s=this.event_hooks[t];if("string"!=typeof t)throw new Error(`LocusZoom attempted to throw an invalid event: ${t.toString()}`);if(!s&&!this.event_hooks.any_lz_event)return this;const i=this.getBaseId();let a;if(a=e&&e.sourceID?e:{sourceID:i,target:this,data:e||null},s&&s.forEach((t=>{t.call(this,a)})),"any_lz_event"!==t){const e=Object.assign({event_name:t},a);this.emit("any_lz_event",e)}return this}addPanel(t){if("object"!=typeof t)throw new Error("Invalid panel layout");const e=new kt(t,this);if(this.panels[e.id]=e,null!==e.layout.y_index&&!isNaN(e.layout.y_index)&&this.panel_ids_by_y_index.length>0)e.layout.y_index<0&&(e.layout.y_index=Math.max(this.panel_ids_by_y_index.length+e.layout.y_index,0)),this.panel_ids_by_y_index.splice(e.layout.y_index,0,e.id),this.applyPanelYIndexesToPanelLayouts();else{const t=this.panel_ids_by_y_index.push(e.id);this.panels[e.id].layout.y_index=t-1}let s=null;return this.layout.panels.forEach(((t,i)=>{t.id===e.id&&(s=i)})),null===s&&(s=this.layout.panels.push(this.panels[e.id].layout)-1),this.panels[e.id].layout_idx=s,this.initialized&&(this.positionPanels(),this.panels[e.id].initialize(),this.panels[e.id].reMap(),this.setDimensions(this.layout.width,this._total_height)),this.panels[e.id]}clearPanelData(t,e){let s;return e=e||"wipe",s=t?[t]:Object.keys(this.panels),s.forEach((t=>{this.panels[t].data_layer_ids_by_z_index.forEach((s=>{const i=this.panels[t].data_layers[s];i.destroyAllTooltips(),delete i.layer_state,delete this.layout.state[i.state_id],"reset"===e&&i._setDefaultState()}))})),this}removePanel(t){if(!this.panels[t])throw new Error(`Unable to remove panel, ID not found: ${t}`);return this.panel_boundaries.hide(),this.clearPanelData(t),this.panels[t].loader.hide(),this.panels[t].toolbar.destroy(!0),this.panels[t].curtain.hide(),this.panels[t].svg.container&&this.panels[t].svg.container.remove(),this.layout.panels.splice(this.panels[t].layout_idx,1),delete this.panels[t],delete this.layout.state[t],this.layout.panels.forEach(((t,e)=>{this.panels[t.id].layout_idx=e})),this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(t),1),this.applyPanelYIndexesToPanelLayouts(),this.initialized&&(this.positionPanels(),this.setDimensions(this.layout.width,this._total_height)),this.emit("panel_removed",t),this}refresh(){return this.applyState()}subscribeToData(t,e,s){const i=(s=s||{}).onerror||function(t){console.log("An error occurred while acting on an external callback",t)},a=()=>{try{this.lzd.getData(this.state,t).then((t=>e(s.discrete?t.discrete:t.body,this))).catch(i)}catch(t){i(t)}};return this.on("data_rendered",a),a}applyState(t){if("object"!=typeof(t=t||{}))throw new Error(`applyState only accepts an object; ${typeof t} given`);let e={chr:this.state.chr,start:this.state.start,end:this.state.end};for(let s in t)e[s]=t[s];e=function(t,e){e=e||{};let s,i=!1,a=null;if(void 0!==(t=t||{}).chr&&void 0!==t.start&&void 0!==t.end){if(t.start=Math.max(parseInt(t.start),1),t.end=Math.max(parseInt(t.end),1),isNaN(t.start)&&isNaN(t.end))t.start=1,t.end=1,a=.5,s=0;else if(isNaN(t.start)||isNaN(t.end))a=t.start||t.end,s=0,t.start=isNaN(t.start)?t.end:t.start,t.end=isNaN(t.end)?t.start:t.end;else{if(a=Math.round((t.start+t.end)/2),s=t.end-t.start,s<0){const e=t.start;t.end=t.start,t.start=e,s=t.end-t.start}a<0&&(t.start=1,t.end=1,s=0)}i=!0}return e.min_region_scale&&i&&se.max_region_scale&&(t.start=Math.max(a-Math.floor(e.max_region_scale/2),1),t.end=t.start+e.max_region_scale),t}(e,this.layout);for(let t in e)this.state[t]=e[t];this.emit("data_requested"),this.remap_promises=[],this.loading_data=!0;for(let t in this.panels)this.remap_promises.push(this.panels[t].reMap());return Promise.all(this.remap_promises).catch((t=>{console.error(t),this.curtain.show(t.message||t),this.loading_data=!1})).then((()=>{this.toolbar.update(),this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t];e.toolbar.update(),e.data_layer_ids_by_z_index.forEach((t=>{e.data_layers[t].applyAllElementStatus()}))})),this.emit("layout_changed"),this.emit("data_rendered"),this.emit("state_changed",t);const{chr:e,start:s,end:i}=this.state;Object.keys(t).some((t=>["chr","start","end"].includes(t)))&&this.emit("region_changed",{chr:e,start:s,end:i}),this.loading_data=!1}))}trackExternalListener(t,e,s){this._external_listeners.has(t)||this._external_listeners.set(t,new Map);const i=this._external_listeners.get(t),a=i.get(e)||[];a.includes(s)||a.push(s),i.set(e,a)}destroy(){for(let[t,e]of this._external_listeners.entries())for(let[s,i]of e)for(let e of i)t.removeEventListener(s,e);const t=this.svg.node().parentNode;if(!t)throw new Error("Plot has already been removed");for(;t.lastElementChild;)t.removeChild(t.lastElementChild);t.outerHTML=t.outerHTML,this.initialized=!1,this.svg=null,this.panels=null}_canInteract(t){return(t=t||null)?(void 0===this.interaction.panel_id||this.interaction.panel_id===t)&&!this.loading_data:!(this.interaction.dragging||this.interaction.zooming||this.loading_data)}_getPageOrigin(){const t=this.svg.node().getBoundingClientRect();let e=document.documentElement.scrollLeft||document.body.scrollLeft,s=document.documentElement.scrollTop||document.body.scrollTop,i=this.svg.node();for(;null!==i.parentNode;)if(i=i.parentNode,i!==document&&"static"!==k.select(i).style("position")){e=-1*i.getBoundingClientRect().left,s=-1*i.getBoundingClientRect().top;break}return{x:e+t.left,y:s+t.top,width:t.width,height:t.height}}getContainerOffset(){const t={top:0,left:0};let e=this.container.offsetParent||null;for(;null!==e;)t.top+=e.offsetTop,t.left+=e.offsetLeft,e=e.offsetParent||null;return t}applyPanelYIndexesToPanelLayouts(){this.panel_ids_by_y_index.forEach(((t,e)=>{this.panels[t].layout.y_index=e}))}getBaseId(){return this.id}rescaleSVG(){const t=this.svg.node().getBoundingClientRect();return this.setDimensions(t.width,t.height),this}initializeLayout(){if(isNaN(this.layout.width)||this.layout.width<=0)throw new Error("Plot layout parameter `width` must be a positive number");if(this.layout.responsive_resize=!!this.layout.responsive_resize,this.layout.responsive_resize){const t=()=>this.rescaleSVG();window.addEventListener("resize",t),this.trackExternalListener(window,"resize",t);const e=()=>this.setDimensions();window.addEventListener("load",e),this.trackExternalListener(window,"load",e)}return this.layout.panels.forEach((t=>{this.addPanel(t)})),this}setDimensions(t,e){if(!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0){const s=e/this._total_height;this.layout.width=Math.max(Math.round(+t),this.layout.min_width),this.layout.responsive_resize&&this.svg&&(this.layout.width=Math.max(this.svg.node().parentNode.getBoundingClientRect().width,this.layout.min_width));let i=0;this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t],a=this.layout.width,n=e.layout.height*s;e.setDimensions(a,n),e.setOrigin(0,i),i+=n,e.toolbar.update()}))}const s=this._total_height;return null!==this.svg&&(this.svg.attr("viewBox",`0 0 ${this.layout.width} ${s}`),this.svg.attr("width",this.layout.width).attr("height",s)),this.initialized&&(this.panel_boundaries.position(),this.toolbar.update(),this.curtain.update(),this.loader.update()),this.emit("layout_changed")}positionPanels(){const t={left:0,right:0};for(let e in this.panels)this.panels[e].layout.interaction.x_linked&&(t.left=Math.max(t.left,this.panels[e].layout.margin.left),t.right=Math.max(t.right,this.panels[e].layout.margin.right));let e=0;return this.panel_ids_by_y_index.forEach((s=>{const i=this.panels[s];if(i.setOrigin(0,e),e+=this.panels[s].layout.height,i.layout.interaction.x_linked){const e=Math.max(t.left-i.layout.margin.left,0)+Math.max(t.right-i.layout.margin.right,0);i.layout.width+=e,i.layout.margin.left=t.left,i.layout.margin.right=t.right,i.layout.cliparea.origin.x=t.left}})),this.setDimensions(),this.panel_ids_by_y_index.forEach((t=>{const e=this.panels[t];e.setDimensions(this.layout.width,e.layout.height)})),this}initialize(){if(this.layout.responsive_resize&&k.select(this.container).classed("lz-container-responsive",!0),this.layout.mouse_guide){const t=this.svg.append("g").attr("class","lz-mouse_guide").attr("id",`${this.id}.mouse_guide`),e=t.append("rect").attr("class","lz-mouse_guide-vertical").attr("x",-1),s=t.append("rect").attr("class","lz-mouse_guide-horizontal").attr("y",-1);this.mouse_guide={svg:t,vertical:e,horizontal:s}}this.curtain=Q.call(this),this.loader=tt.call(this),this.panel_boundaries={parent:this,hide_timeout:null,showing:!1,dragging:!1,selectors:[],corner_selector:null,show:function(){if(!this.showing&&!this.parent.curtain.showing){this.showing=!0,this.parent.panel_ids_by_y_index.forEach(((t,e)=>{const s=k.select(this.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-boundary").attr("title","Resize panel");s.append("span");const i=k.drag();i.on("start",(()=>{this.dragging=!0})),i.on("end",(()=>{this.dragging=!1})),i.on("drag",(()=>{const t=this.parent.panels[this.parent.panel_ids_by_y_index[e]],s=t.layout.height;t.setDimensions(this.parent.layout.width,t.layout.height+k.event.dy);const i=t.layout.height-s;this.parent.panel_ids_by_y_index.forEach(((t,s)=>{const a=this.parent.panels[this.parent.panel_ids_by_y_index[s]];s>e&&(a.setOrigin(a.layout.origin.x,a.layout.origin.y+i),a.toolbar.position())})),this.parent.positionPanels(),this.position()})),s.call(i),this.parent.panel_boundaries.selectors.push(s)}));const t=k.select(this.parent.svg.node().parentNode).insert("div",".lz-data_layer-tooltip").attr("class","lz-panel-corner-boundary").attr("title","Resize plot");t.append("span").attr("class","lz-panel-corner-boundary-outer"),t.append("span").attr("class","lz-panel-corner-boundary-inner");const e=k.drag();e.on("start",(()=>{this.dragging=!0})),e.on("end",(()=>{this.dragging=!1})),e.on("drag",(()=>{this.parent.setDimensions(this.parent.layout.width+k.event.dx,this.parent._total_height+k.event.dy)})),t.call(e),this.parent.panel_boundaries.corner_selector=t}return this.position()},position:function(){if(!this.showing)return this;const t=this.parent._getPageOrigin();this.selectors.forEach(((e,s)=>{const i=this.parent.panels[this.parent.panel_ids_by_y_index[s]],a=i._getPageOrigin(),n=t.x,o=a.y+i.layout.height-12,r=this.parent.layout.width-1;e.style("top",`${o}px`).style("left",`${n}px`).style("width",`${r}px`),e.select("span").style("width",`${r}px`)}));return this.corner_selector.style("top",t.y+this.parent._total_height-10-16+"px").style("left",t.x+this.parent.layout.width-10-16+"px"),this},hide:function(){return this.showing?(this.showing=!1,this.selectors.forEach((t=>{t.remove()})),this.selectors=[],this.corner_selector.remove(),this.corner_selector=null,this):this}},this.layout.panel_boundaries&&k.select(this.svg.node().parentNode).on(`mouseover.${this.id}.panel_boundaries`,(()=>{clearTimeout(this.panel_boundaries.hide_timeout),this.panel_boundaries.show()})).on(`mouseout.${this.id}.panel_boundaries`,(()=>{this.panel_boundaries.hide_timeout=setTimeout((()=>{this.panel_boundaries.hide()}),300)})),this.toolbar=new vt(this).show();for(let t in this.panels)this.panels[t].initialize();const t=`.${this.id}`;if(this.layout.mouse_guide){const e=()=>{this.mouse_guide.vertical.attr("x",-1),this.mouse_guide.horizontal.attr("y",-1)},s=()=>{const t=k.mouse(this.svg.node());this.mouse_guide.vertical.attr("x",t[0]),this.mouse_guide.horizontal.attr("y",t[1])};this.svg.on(`mouseout${t}-mouse_guide`,e).on(`touchleave${t}-mouse_guide`,e).on(`mousemove${t}-mouse_guide`,s)}const e=()=>{this.stopDrag()},s=()=>{if(this.interaction.dragging){const t=k.mouse(this.svg.node());k.event&&k.event.preventDefault(),this.interaction.dragging.dragged_x=t[0]-this.interaction.dragging.start_x,this.interaction.dragging.dragged_y=t[1]-this.interaction.dragging.start_y,this.panels[this.interaction.panel_id].render(),this.interaction.linked_panel_ids.forEach((t=>{this.panels[t].render()}))}};this.svg.on(`mouseup${t}`,e).on(`touchend${t}`,e).on(`mousemove${t}`,s).on(`touchmove${t}`,s);const i=k.select("body").node();i&&(i.addEventListener("mouseup",e),i.addEventListener("touchend",e),this.trackExternalListener(i,"mouseup",e),this.trackExternalListener(i,"touchend",e)),this.on("match_requested",(t=>{const e=t.data,s=e.active?e.value:null,i=t.target.id;Object.values(this.panels).forEach((t=>{t.id!==i&&Object.values(t.data_layers).forEach((t=>t.destroyAllTooltips(!1)))})),this.applyState({lz_match_value:s})})),this.initialized=!0;const a=this.svg.node().getBoundingClientRect(),n=a.width?a.width:this.layout.width,o=a.height?a.height:this._total_height;return this.setDimensions(n,o),this}startDrag(t,e){t=t||null;let s=null;switch(e=e||null){case"background":case"x_tick":s="x";break;case"y1_tick":s="y1";break;case"y2_tick":s="y2"}if(!(t instanceof kt&&s&&this._canInteract()))return this.stopDrag();const i=k.mouse(this.svg.node());return this.interaction={panel_id:t.id,linked_panel_ids:t.getLinkedPanelIds(s),dragging:{method:e,start_x:i[0],start_y:i[1],dragged_x:0,dragged_y:0,axis:s}},this.svg.style("cursor","all-scroll"),this}stopDrag(){if(!this.interaction.dragging)return this;if("object"!=typeof this.panels[this.interaction.panel_id])return this.interaction={},this;const t=this.panels[this.interaction.panel_id],e=(e,s,i)=>{t.data_layer_ids_by_z_index.forEach((a=>{const n=t.data_layers[a].layout[`${e}_axis`];n.axis===s&&(n.floor=i[0],n.ceiling=i[1],delete n.lower_buffer,delete n.upper_buffer,delete n.min_extent,delete n.ticks)}))};switch(this.interaction.dragging.method){case"background":case"x_tick":0!==this.interaction.dragging.dragged_x&&(e("x",1,t.x_extent),this.applyState({start:t.x_extent[0],end:t.x_extent[1]}));break;case"y1_tick":case"y2_tick":if(0!==this.interaction.dragging.dragged_y){const s=parseInt(this.interaction.dragging.method[1]);e("y",s,t[`y${s}_extent`])}}return this.interaction={},this.svg.style("cursor",null),this}get _total_height(){return this.layout.panels.reduce(((t,e)=>e.height+t),0)}}function St(t,e,s){const i={0:"",3:"K",6:"M",9:"G"};if(s=s||!1,isNaN(e)||null===e){const s=Math.log(t)/Math.LN10;e=Math.min(Math.max(s-s%3,0),9)}const a=e-Math.floor((Math.log(t)/Math.LN10).toFixed(e+3)),n=Math.min(Math.max(e,0),2),o=Math.min(Math.max(a,n),12);let r=`${(t/Math.pow(10,e)).toFixed(o)}`;return s&&void 0!==i[e]&&(r+=` ${i[e]}b`),r}function Nt(t){let e=t.toUpperCase();e=e.replace(/,/g,"");const s=/([KMG])[B]*$/,i=s.exec(e);let a=1;return i&&(a="M"===i[1]?1e6:"G"===i[1]?1e9:1e3,e=e.replace(s,"")),e=Number(e)*a,e}function At(t,e,s){if("object"!=typeof e)throw new Error("invalid arguments: data is not an object");if("string"!=typeof t)throw new Error("invalid arguments: html is not a string");const i=[],a=/{{(?:(#if )?([A-Za-z0-9_:|]+)|(#else)|(\/if))}}/;for(;t.length>0;){const e=a.exec(t);e?0!==e.index?(i.push({text:t.slice(0,e.index)}),t=t.slice(e.index)):"#if "===e[1]?(i.push({condition:e[2]}),t=t.slice(e[0].length)):e[2]?(i.push({variable:e[2]}),t=t.slice(e[0].length)):"#else"===e[3]?(i.push({branch:"else"}),t=t.slice(e[0].length)):"/if"===e[4]?(i.push({close:"if"}),t=t.slice(e[0].length)):(console.error(`Error tokenizing tooltip when remaining template is ${JSON.stringify(t)} and previous tokens are ${JSON.stringify(i)} and current regex match is ${JSON.stringify([e[1],e[2],e[3]])}`),t=t.slice(e[0].length)):(i.push({text:t}),t="")}const n=function(){const t=i.shift();if(void 0!==t.text||t.variable)return t;if(t.condition){let e=t.then=[];for(t.else=[];i.length>0;){if("if"===i[0].close){i.shift();break}"else"===i[0].branch&&(i.shift(),e=t.else),e.push(n())}return t}return console.error(`Error making tooltip AST due to unknown token ${JSON.stringify(t)}`),{text:""}},o=[];for(;i.length>0;)o.push(n());const r=function(t){return Object.prototype.hasOwnProperty.call(r.cache,t)||(r.cache[t]=new R(t).resolve(e,s)),r.cache[t]};r.cache={};const l=function(t){if(void 0!==t.text)return t.text;if(t.variable){try{const e=r(t.variable);if(-1!==["string","number","boolean"].indexOf(typeof e))return e;if(null===e)return""}catch(e){console.error(`Error while processing variable ${JSON.stringify(t.variable)}`)}return`{{${t.variable}}}`}if(t.condition){try{if(r(t.condition))return t.then.map(l).join("");if(t.else)return t.else.map(l).join("")}catch(e){console.error(`Error while processing condition ${JSON.stringify(t.variable)}`)}return""}console.error(`Error rendering tooltip due to unknown AST node ${JSON.stringify(t)}`)};return o.map(l).join("")}const Tt=new h;Tt.add("=",((t,e)=>t===e)),Tt.add("!=",((t,e)=>t!=e)),Tt.add("<",((t,e)=>tt<=e)),Tt.add(">",((t,e)=>t>e)),Tt.add(">=",((t,e)=>t>=e)),Tt.add("%",((t,e)=>t%e)),Tt.add("in",((t,e)=>e&&e.includes(t))),Tt.add("match",((t,e)=>t&&t.includes(e)));const Lt=Tt,Ot=(t,e)=>void 0===e||t.field_value!==e?void 0!==t.else?t.else:null:t.then,Ct=(t,e)=>{const s=t.breaks||[],i=t.values||[];if(null==e||isNaN(+e))return t.null_value?t.null_value:null;const a=s.reduce((function(t,s){return+e=t&&+evoid 0!==e&&t.categories.includes(e)?t.values[t.categories.indexOf(e)]:t.null_value?t.null_value:null,Rt=(t,e,s)=>{const i=t.values;return i[s%i.length]};let Dt=(t,e,s)=>{const i=t._cache=t._cache||new Map,a=t.max_cache_size||500;if(i.size>=a&&i.clear(),i.has(e))return i.get(e);let n=0;e=String(e);for(let t=0;t{var s=t.breaks||[],i=t.values||[],a=t.null_value?t.null_value:null;if(s.length<2||s.length!==i.length)return a;if(null==e||isNaN(+e))return a;if(+e<=t.breaks[0])return i[0];if(+e>=t.breaks[t.breaks.length-1])return i[s.length-1];{var n=null;if(s.forEach((function(t,i){i&&s[i-1]<=+e&&s[i]>=+e&&(n=i)})),null===n)return a;const t=(+e-s[n-1])/(s[n]-s[n-1]);return isFinite(t)?k.interpolate(i[n-1],i[n])(t):a}},jt=new h;for(let[t,e]of Object.entries(n))jt.add(t,e);jt.add("if",Ot);const Bt=jt,Ut={id:"",type:"",tag:"custom_data_type",fields:[],id_field:"id",filters:null,match:{},x_axis:{},y_axis:{},legend:null,tooltip:{},tooltip_positioning:"horizontal",behaviors:{}};class Ft{constructor(t,e){this.initialized=!1,this.layout_idx=null,this.id=null,this._base_id=null,this.parent=e||null,this.svg={},this.parent_plot=null,e&&(this.parent_plot=e.parent),this.layout=Z(t||{},Ut),this.layout.id&&(this.id=this.layout.id),this._filter_func=null,this.layout.x_axis!=={}&&"number"!=typeof this.layout.x_axis.axis&&(this.layout.x_axis.axis=1),this.layout.y_axis!=={}&&"number"!=typeof this.layout.y_axis.axis&&(this.layout.y_axis.axis=1),this._base_layout=J(this.layout),this.state={},this.state_id=null,this.layer_state=null,this._setDefaultState(),this.data=[],this.layout.tooltip&&(this.tooltips={}),this.global_statuses={highlighted:!1,selected:!1,faded:!1,hidden:!1}}render(){throw new Error("Method must be implemented")}moveForward(){return this.parent.data_layer_ids_by_z_index[this.layout.z_index+1]&&(this.parent.data_layer_ids_by_z_index[this.layout.z_index]=this.parent.data_layer_ids_by_z_index[this.layout.z_index+1],this.parent.data_layer_ids_by_z_index[this.layout.z_index+1]=this.id,this.parent.resortDataLayers()),this}moveBack(){return this.parent.data_layer_ids_by_z_index[this.layout.z_index-1]&&(this.parent.data_layer_ids_by_z_index[this.layout.z_index]=this.parent.data_layer_ids_by_z_index[this.layout.z_index-1],this.parent.data_layer_ids_by_z_index[this.layout.z_index-1]=this.id,this.parent.resortDataLayers()),this}setElementAnnotation(t,e,s){const i=this.getElementId(t);return this.layer_state.extra_fields[i]||(this.layer_state.extra_fields[i]={}),this.layer_state.extra_fields[i][e]=s,this}setFilter(t){console.warn("The setFilter method is deprecated and will be removed in the future; please use the layout API with a custom filter function instead"),this._filter_func=t}_getDataExtent(t,e){return t=t||this.data,k.extent(t,(t=>+new R(e.field).resolve(t)))}getElementId(t){const e=Symbol.for("lzID");if(t[e])return t[e];const s=this.layout.id_field||"id";if(void 0===t[s])throw new Error("Unable to generate element ID");const i=t[s].toString().replace(/\W/g,""),a=`${this.getBaseId()}-${i}`.replace(/([:.[\],])/g,"_");return t[e]=a,a}getElementStatusNodeId(t){return null}getElementById(t){const e=k.select(`#${t.replace(/([:.[\],])/g,"\\$1")}`);return!e.empty()&&e.data()&&e.data().length?e.data()[0]:null}applyDataMethods(){const t=this.layout.match&&this.layout.match.receive,e=Lt.get(this.layout.match&&this.layout.match.operator||"="),s=this.parent_plot.state.lz_match_value,i=t?new R(t):null;return this.data.forEach(((a,n)=>{t&&null!=s&&(a.lz_is_match=e(i.resolve(a),s)),a.toHTML=()=>{const t=this.layout.id_field||"id";let e="";return a[t]&&(e=a[t].toString()),e},a.getDataLayer=()=>this,a.getPanel=()=>this.parent||null,a.getPlot=()=>{const t=this.parent;return t?t.parent:null},a.deselect=()=>{this.getDataLayer().unselectElement(this)}})),this.applyCustomDataMethods(),this}applyCustomDataMethods(){return this}resolveScalableParameter(t,e,s){let i=null;if(Array.isArray(t)){let a=0;for(;null===i&&ad-(_+v)?"top":"bottom"):"horizontal"===w&&(v=0,w=p<=r.width/2?"left":"right"),"top"===w||"bottom"===w){const t=Math.max(c.width/2-p,0),e=Math.max(c.width/2+p-u,0);y=h.x+p-c.width/2-e+t,b=h.x+p-y-7,"top"===w?(g=h.y+_-(v+c.height+8),m="down",f=c.height-1):(g=h.y+_+v+8,m="up",f=-8)}else{if("left"!==w&&"right"!==w)throw new Error("Unrecognized placement value");"left"===w?(y=h.x+p+x+8,m="left",b=-8):(y=h.x+p-c.width-x-8,m="right",b=c.width-1),_-c.height/2<=0?(g=h.y+_-10.5-6,f=6):_+c.height/2>=d?(g=h.y+_+7+6-c.height,f=c.height-14-6):(g=h.y+_-c.height/2,f=c.height/2-7)}return t.selector.style("left",`${y}px`).style("top",`${g}px`),t.arrow||(t.arrow=t.selector.append("div").style("position","absolute")),t.arrow.attr("class",`lz-data_layer-tooltip-arrow_${m}`).style("left",`${b}px`).style("top",`${f}px`),this}filter(t,e,s,i){let a=!0;return t.forEach((t=>{const{field:s,operator:i,value:n}=t,o=Lt.get(i),r=this.getElementAnnotation(e);o(s?new R(s).resolve(e,r):e,n)||(a=!1)})),a}getElementAnnotation(t,e){const s=this.getElementId(t),i=this.layer_state.extra_fields[s];return e?i&&i[e]:i}_applyFilters(t){return t=t||this.data,this._filter_func?t=t.filter(this._filter_func):this.layout.filters&&(t=t.filter(this.filter.bind(this,this.layout.filters))),t}_setDefaultState(){const t={status_flags:{},extra_fields:{}},e=t.status_flags;E.adjectives.forEach((t=>{e[t]=e[t]||new Set})),e.has_tooltip=e.has_tooltip||new Set,this.parent&&(this.state_id=`${this.parent.id}.${this.id}`,this.state=this.parent.state,this.state[this.state_id]=t),this.layer_state=t}getBaseId(){return this._base_id?this._base_id:this.parent?`${this.parent_plot.id}.${this.parent.id}.${this.id}`:(this.id||"").toString()}getAbsoluteDataHeight(){return this.svg.group.node().getBoundingClientRect().height}initialize(){this._base_id=this.getBaseId();const t=this.getBaseId();return this.svg.container=this.parent.svg.group.append("g").attr("class","lz-data_layer-container").attr("id",`${t}.data_layer_container`),this.svg.clipRect=this.svg.container.append("clipPath").attr("id",`${t}.clip`).append("rect"),this.svg.group=this.svg.container.append("g").attr("id",`${t}.data_layer`).attr("clip-path",`url(#${t}.clip)`),this}createTooltip(t){if("object"!=typeof this.layout.tooltip)throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`);const e=this.getElementId(t);if(!this.tooltips[e])return this.tooltips[e]={data:t,arrow:null,selector:k.select(this.parent_plot.svg.node().parentNode).append("div").attr("class","lz-data_layer-tooltip").attr("id",`${e}-tooltip`)},this.layer_state.status_flags.has_tooltip.add(e),this.updateTooltip(t),this;this.positionTooltip(e)}updateTooltip(t,e){return void 0===e&&(e=this.getElementId(t)),this.tooltips[e].selector.html(""),this.tooltips[e].arrow=null,this.layout.tooltip.html&&this.tooltips[e].selector.html(At(this.layout.tooltip.html,t,this.getElementAnnotation(t))),this.layout.tooltip.closable&&this.tooltips[e].selector.insert("button",":first-child").attr("class","lz-tooltip-close-button").attr("title","Close").text("×").on("click",(()=>{this.destroyTooltip(e)})),this.tooltips[e].selector.data([t]),this.positionTooltip(e),this}destroyTooltip(t,e){let s;if(s="string"==typeof t?t:this.getElementId(t),this.tooltips[s]&&("object"==typeof this.tooltips[s].selector&&this.tooltips[s].selector.remove(),delete this.tooltips[s]),!e){this.layer_state.status_flags.has_tooltip.delete(s)}return this}destroyAllTooltips(t=!0){for(let e in this.tooltips)this.destroyTooltip(e,t);return this}positionTooltip(t){if("string"!=typeof t)throw new Error("Unable to position tooltip: id is not a string");if(!this.tooltips[t])throw new Error("Unable to position tooltip: id does not point to a valid tooltip");const e=this.tooltips[t],s=this._getTooltipPosition(e);if(!s)return null;this._drawTooltip(e,this.layout.tooltip_positioning,s.x_min,s.x_max,s.y_min,s.y_max)}positionAllTooltips(){for(let t in this.tooltips)this.positionTooltip(t);return this}showOrHideTooltip(t,e){if("object"!=typeof this.layout.tooltip)return this;const s=this.getElementId(t),i=(t,e,s)=>{let a=null;if("object"!=typeof t||null===t)return null;if(Array.isArray(e))s=s||"and",a=1===e.length?t[e[0]]:e.reduce(((e,i)=>"and"===s?t[e]&&t[i]:"or"===s?t[e]||t[i]:null));else{if("object"!=typeof e)return!1;{let n;for(let o in e)n=i(t,e[o],o),null===a?a=n:"and"===s?a=a&&n:"or"===s&&(a=a||n)}}return a};let a={};"string"==typeof this.layout.tooltip.show?a={and:[this.layout.tooltip.show]}:"object"==typeof this.layout.tooltip.show&&(a=this.layout.tooltip.show);let n={};"string"==typeof this.layout.tooltip.hide?n={and:[this.layout.tooltip.hide]}:"object"==typeof this.layout.tooltip.hide&&(n=this.layout.tooltip.hide);const o=this.layer_state;var r={};E.adjectives.forEach((t=>{const e=`un${t}`;r[t]=o.status_flags[t].has(s),r[e]=!r[t]}));const l=i(r,a),h=i(r,n),c=o.status_flags.has_tooltip.has(s);return!l||!e&&!c||h?this.destroyTooltip(t):this.createTooltip(t),this}setElementStatus(t,e,s,i){if("has_tooltip"===t)return this;let a;void 0===s&&(s=!0);try{a=this.getElementId(e)}catch(t){return this}i&&this.setAllElementStatus(t,!s),k.select(`#${a}`).classed(`lz-data_layer-${this.layout.type}-${t}`,s);const n=this.getElementStatusNodeId(e);null!==n&&k.select(`#${n}`).classed(`lz-data_layer-${this.layout.type}-statusnode-${t}`,s);const o=!this.layer_state.status_flags[t].has(a);s&&o&&this.layer_state.status_flags[t].add(a),s||o||this.layer_state.status_flags[t].delete(a),this.showOrHideTooltip(e,o),o&&this.parent.emit("layout_changed",!0);const r="selected"===t;!r||!o&&s||this.parent.emit("element_selection",{element:e,active:s},!0);const l=this.layout.match&&this.layout.match.send;return!r||void 0===l||!o&&s||this.parent.emit("match_requested",{value:new R(l).resolve(e),active:s},!0),this}setAllElementStatus(t,e){if(void 0===t||!E.adjectives.includes(t))throw new Error("Invalid status");if(void 0===this.layer_state.status_flags[t])return this;if(void 0===e&&(e=!0),e)this.data.forEach((e=>this.setElementStatus(t,e,!0)));else{new Set(this.layer_state.status_flags[t]).forEach((e=>{const s=this.getElementById(e);"object"==typeof s&&null!==s&&this.setElementStatus(t,s,!1)})),this.layer_state.status_flags[t]=new Set}return this.global_statuses[t]=e,this}applyBehaviors(t){"object"==typeof this.layout.behaviors&&Object.keys(this.layout.behaviors).forEach((e=>{const s=/(click|mouseover|mouseout)/.exec(e);s&&t.on(`${s[0]}.${e}`,this.executeBehaviors(e,this.layout.behaviors[e]))}))}executeBehaviors(t,e){const s=t.includes("ctrl"),i=t.includes("shift"),a=this;return function(t){t=t||k.select(k.event.target).datum(),s===!!k.event.ctrlKey&&i===!!k.event.shiftKey&&e.forEach((e=>{if("object"==typeof e&&null!==e)switch(e.action){case"set":a.setElementStatus(e.status,t,!0,e.exclusive);break;case"unset":a.setElementStatus(e.status,t,!1,e.exclusive);break;case"toggle":var s=a.layer_state.status_flags[e.status].has(a.getElementId(t)),i=e.exclusive&&!s;a.setElementStatus(e.status,t,!s,i);break;case"link":if("string"==typeof e.href){const s=At(e.href,t,a.getElementAnnotation(t));"string"==typeof e.target?window.open(s,e.target):window.location.href=s}}}))}}_getPageOrigin(){const t=this.parent._getPageOrigin();return{x:t.x+this.parent.layout.margin.left,y:t.y+this.parent.layout.margin.top}}applyAllElementStatus(){const t=this.layer_state.status_flags,e=this;for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&t[s].forEach((t=>{try{this.setElementStatus(s,this.getElementById(t),!0)}catch(t){console.warn(`Unable to apply state: ${e.state_id}, ${s}`),console.error(t)}}))}draw(){return this.svg.container.attr("transform",`translate(${this.parent.layout.cliparea.origin.x}, ${this.parent.layout.cliparea.origin.y})`),this.svg.clipRect.attr("width",this.parent.layout.cliparea.width).attr("height",this.parent.layout.cliparea.height),this.positionAllTooltips(),this}reMap(){return this.destroyAllTooltips(),this.parent_plot.lzd.getData(this.state,this.layout.fields).then((t=>{this.data=t.body,this.applyDataMethods(),this.initialized=!0}))}}E.verbs.forEach(((t,e)=>{const s=E.adjectives[e],i=`un${t}`;Ft.prototype[`${t}Element`]=function(t,e=!1){return e=!!e,this.setElementStatus(s,t,!0,e),this},Ft.prototype[`${i}Element`]=function(t,e){return e=void 0!==e&&!!e,this.setElementStatus(s,t,!1,e),this},Ft.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},Ft.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const qt={color:"#000000",filters:null,tooltip_positioning:"vertical",hitarea_width:8};class Gt extends Ft{constructor(t){if(!Array.isArray(t.filters))throw new Error("Annotation track must specify array of filters for selecting points to annotate");Z(t,qt),super(...arguments)}initialize(){super.initialize(),this._hitareas_group=this.svg.group.append("g").attr("class",`lz-data_layer-${this.layout.type}-hit_areas`),this._visible_lines_group=this.svg.group.append("g").attr("class",`lz-data_layer-${this.layout.type}-visible_lines`)}render(){const t=this._applyFilters(),e=this._hitareas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(t,(t=>t[this.layout.id_field])),s=(e,s)=>{const i=this.parent.x_scale(e[this.layout.x_axis.field]);let a=i-this.layout.hitarea_width/2;if(s>=1){const e=t[s-1],n=this.parent.x_scale(e[this.layout.x_axis.field]);a=Math.max(a,(i+n)/2)}return[a,i]};e.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(e).attr("id",(t=>this.getElementId(t))).attr("height",this.parent.layout.height).attr("opacity",0).attr("x",((t,e)=>s(t,e)[0])).attr("width",((t,e)=>{const i=s(t,e);return i[1]-i[0]+this.layout.hitarea_width/2}));const i=this._visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(t,(t=>t[this.layout.id_field]));i.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(i).attr("id",(t=>this.getElementId(t))).attr("x",(t=>this.parent.x_scale(t[this.layout.x_axis.field])-.5)).attr("width",1).attr("height",this.parent.layout.height).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))),i.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this)),e.exit().remove()}_getTooltipPosition(t){const e=this.parent,s=e.layout.height-(e.layout.margin.top+e.layout.margin.bottom),i=e.x_scale(t.data[this.layout.x_axis.field]),a=s/2;return{x_min:i-1,x_max:i+1,y_min:a-e.layout.margin.top,y_max:a+e.layout.margin.bottom}}}const Ht={color:"#CCCCCC",fill_opacity:.5,filters:null,regions:[],id_field:"id",start_field:"start",end_field:"end",merge_field:null};class Zt extends Ft{constructor(t){if(Z(t,Ht),t.interaction||t.behaviors)throw new Error("highlight_regions layer does not support mouse events");if(t.regions&&t.regions.length&&t.fields&&t.fields.length)throw new Error('highlight_regions layer can specify "regions" in layout, OR external data "fields", but not both');super(...arguments)}_mergeNodes(t){const{end_field:e,merge_field:s,start_field:i}=this.layout;if(!s)return t;t.sort(((t,e)=>k.ascending(t[s],e[s])||k.ascending(t[i],e[i])));let a=[];return t.forEach((function(t,n){const o=a[a.length-1]||t;if(t[s]===o[s]&&t[i]<=o[e]){const s=Math.min(o[i],t[i]),n=Math.max(o[e],t[e]);t=Object.assign({},o,t,{[i]:s,[e]:n}),a.pop()}a.push(t)})),a}render(){const{x_scale:t}=this.parent;let e=this.layout.regions.length?this.layout.regions:this.data;e.forEach(((t,e)=>t.id||(t.id=e))),e=this._applyFilters(e),e=this._mergeNodes(e);const s=this.svg.group.selectAll(`rect.lz-data_layer-${this.layout.type}`).data(e);s.enter().append("rect").attr("class",`lz-data_layer-${this.layout.type}`).merge(s).attr("id",(t=>this.getElementId(t))).attr("x",(e=>t(e[this.layout.start_field]))).attr("width",(e=>t(e[this.layout.end_field])-t(e[this.layout.start_field]))).attr("height",this.parent.layout.height).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))),s.exit().remove(),this.svg.group.style("pointer-events","none")}_getTooltipPosition(t){throw new Error("This layer does not support tooltips")}}const Jt={color:"seagreen",hitarea_width:"10px",style:{fill:"none","stroke-width":"1px","stroke-opacity":"100%"},tooltip_positioning:"top"};class Kt extends Ft{constructor(t){t=Z(t,Jt),super(...arguments)}render(){const t=this,e=t.layout,s=t.parent.x_scale,i=t.parent[`y${e.y_axis.axis}_scale`],a=this._applyFilters();function n(t){const a=t[e.x_axis.field1],n=t[e.x_axis.field2],o=(a+n)/2,r=[[s(a),i(0)],[s(o),i(t[e.y_axis.field])],[s(n),i(0)]];return k.line().x((t=>t[0])).y((t=>t[1])).curve(k.curveNatural)(r)}const o=this.svg.group.selectAll("path.lz-data_layer-arcs-hitarea").data(a,(t=>this.getElementId(t))),r=this.svg.group.selectAll("path.lz-data_layer-arcs").data(a,(t=>this.getElementId(t)));return this.svg.group.call(et,e.style),o.enter().append("path").attr("class","lz-data_layer-arcs-hitarea").merge(o).attr("id",(t=>this.getElementId(t))).style("fill","none").style("stroke-width",e.hitarea_width).style("stroke-opacity",0).style("stroke","transparent").attr("d",(t=>n(t))),r.enter().append("path").attr("class","lz-data_layer-arcs").merge(r).attr("id",(t=>this.getElementId(t))).attr("stroke",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("d",((t,e)=>n(t))),r.exit().remove(),o.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this)),this}_getTooltipPosition(t){const e=this.parent,s=this.layout,i=t.data[s.x_axis.field1],a=t.data[s.x_axis.field2],n=e[`y${s.y_axis.axis}_scale`];return{x_min:e.x_scale(Math.min(i,a)),x_max:e.x_scale(Math.max(i,a)),y_min:n(t.data[s.y_axis.field]),y_max:n(0)}}}const Vt={stroke:"rgb(54, 54, 150)",color:"#363696",label_font_size:12,label_exon_spacing:3,exon_height:10,bounding_box_padding:3,track_vertical_spacing:5,tooltip_positioning:"top"};class Yt extends Ft{constructor(t){t=Z(t,Vt),super(...arguments),this.transcript_idx=0,this.tracks=1,this.gene_track_index={1:[]}}getElementStatusNodeId(t){return`${this.getElementId(t)}-statusnode`}getTrackHeight(){return 2*this.layout.bounding_box_padding+this.layout.label_font_size+this.layout.label_exon_spacing+this.layout.exon_height+this.layout.track_vertical_spacing}assignTracks(t){const e=(t,e)=>{try{const s=this.svg.group.append("text").attr("x",0).attr("y",0).attr("class","lz-data_layer-genes lz-label").style("font-size",e).text(`${t}→`),i=s.node().getBBox().width;return s.remove(),i}catch(t){return 0}};return this.tracks=1,this.gene_track_index={1:[]},t.filter((t=>!(t.endthis.state.end))).map((t=>{if(t.gene_id&&t.gene_id.indexOf(".")){const e=t.gene_id.split(".");t.gene_id=e[0],t.gene_version=e[1]}if(t.transcript_id=t.transcripts[this.transcript_idx].transcript_id,t.display_range={start:this.parent.x_scale(Math.max(t.start,this.state.start)),end:this.parent.x_scale(Math.min(t.end,this.state.end))},t.display_range.label_width=e(t.gene_name,this.layout.label_font_size),t.display_range.width=t.display_range.end-t.display_range.start,t.display_range.text_anchor="middle",t.display_range.widththis.state.end)t.display_range.start=t.display_range.end-t.display_range.label_width-this.layout.label_font_size,t.display_range.text_anchor="end";else{const e=(t.display_range.label_width-t.display_range.width)/2+this.layout.label_font_size;t.display_range.start-ethis.parent.x_scale(this.state.end)?(t.display_range.end=this.parent.x_scale(this.state.end),t.display_range.start=t.display_range.end-t.display_range.label_width,t.display_range.text_anchor="end"):(t.display_range.start-=e,t.display_range.end+=e)}t.display_range.width=t.display_range.end-t.display_range.start}t.display_range.start-=this.layout.bounding_box_padding,t.display_range.end+=this.layout.bounding_box_padding,t.display_range.width+=2*this.layout.bounding_box_padding,t.display_domain={start:this.parent.x_scale.invert(t.display_range.start),end:this.parent.x_scale.invert(t.display_range.end)},t.display_domain.width=t.display_domain.end-t.display_domain.start,t.track=null;let s=1;for(;null===t.track;){let e=!1;this.gene_track_index[s].map((s=>{if(!e){const i=Math.min(s.display_range.start,t.display_range.start);Math.max(s.display_range.end,t.display_range.end)-ithis.tracks&&(this.tracks=s,this.gene_track_index[s]=[])):(t.track=s,this.gene_track_index[s].push(t))}return t.parent=this,t.transcripts.map(((e,s)=>{t.transcripts[s].parent=t,t.transcripts[s].exons.map(((e,i)=>t.transcripts[s].exons[i].parent=t.transcripts[s]))})),t}))}render(){const t=this;let e,s=this._applyFilters();s=this.assignTracks(s);const i=this.svg.group.selectAll("g.lz-data_layer-genes").data(s,(t=>t.gene_name));i.enter().append("g").attr("class","lz-data_layer-genes").merge(i).attr("id",(t=>this.getElementId(t))).each((function(s){const i=s.parent,a=k.select(this).selectAll("rect.lz-data_layer-genes.lz-data_layer-genes-statusnode").data([s],(t=>i.getElementStatusNodeId(t)));e=i.getTrackHeight()-i.layout.track_vertical_spacing,a.enter().append("rect").attr("class","lz-data_layer-genes lz-data_layer-genes-statusnode").merge(a).attr("id",(t=>i.getElementStatusNodeId(t))).attr("rx",i.layout.bounding_box_padding).attr("ry",i.layout.bounding_box_padding).attr("width",(t=>t.display_range.width)).attr("height",e).attr("x",(t=>t.display_range.start)).attr("y",(t=>(t.track-1)*i.getTrackHeight())),a.exit().remove();const n=k.select(this).selectAll("rect.lz-data_layer-genes.lz-boundary").data([s],(t=>`${t.gene_name}_boundary`));e=1,n.enter().append("rect").attr("class","lz-data_layer-genes lz-boundary").merge(n).attr("width",(t=>i.parent.x_scale(t.end)-i.parent.x_scale(t.start))).attr("height",e).attr("x",(t=>i.parent.x_scale(t.start))).attr("y",(t=>(t.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size+i.layout.label_exon_spacing+Math.max(i.layout.exon_height,3)/2)).style("fill",((e,s)=>t.resolveScalableParameter(t.layout.color,e,s))).style("stroke",((e,s)=>t.resolveScalableParameter(t.layout.stroke,e,s))),n.exit().remove();const o=k.select(this).selectAll("text.lz-data_layer-genes.lz-label").data([s],(t=>`${t.gene_name}_label`));o.enter().append("text").attr("class","lz-data_layer-genes lz-label").merge(o).attr("text-anchor",(t=>t.display_range.text_anchor)).text((t=>"+"===t.strand?`${t.gene_name}→`:`←${t.gene_name}`)).style("font-size",s.parent.layout.label_font_size).attr("x",(t=>"middle"===t.display_range.text_anchor?t.display_range.start+t.display_range.width/2:"start"===t.display_range.text_anchor?t.display_range.start+i.layout.bounding_box_padding:"end"===t.display_range.text_anchor?t.display_range.end-i.layout.bounding_box_padding:void 0)).attr("y",(t=>(t.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size)),o.exit().remove();const r=k.select(this).selectAll("rect.lz-data_layer-genes.lz-exon").data(s.transcripts[s.parent.transcript_idx].exons,(t=>t.exon_id));e=i.layout.exon_height,r.enter().append("rect").attr("class","lz-data_layer-genes lz-exon").merge(r).style("fill",((e,s)=>t.resolveScalableParameter(t.layout.color,e.parent.parent,s))).style("stroke",((e,s)=>t.resolveScalableParameter(t.layout.stroke,e.parent.parent,s))).attr("width",(t=>i.parent.x_scale(t.end)-i.parent.x_scale(t.start))).attr("height",e).attr("x",(t=>i.parent.x_scale(t.start))).attr("y",(()=>(s.track-1)*i.getTrackHeight()+i.layout.bounding_box_padding+i.layout.label_font_size+i.layout.label_exon_spacing)),r.exit().remove();const l=k.select(this).selectAll("rect.lz-data_layer-genes.lz-clickarea").data([s],(t=>`${t.gene_name}_clickarea`));e=i.getTrackHeight()-i.layout.track_vertical_spacing,l.enter().append("rect").attr("class","lz-data_layer-genes lz-clickarea").merge(l).attr("id",(t=>`${i.getElementId(t)}_clickarea`)).attr("rx",i.layout.bounding_box_padding).attr("ry",i.layout.bounding_box_padding).attr("width",(t=>t.display_range.width)).attr("height",e).attr("x",(t=>t.display_range.start)).attr("y",(t=>(t.track-1)*i.getTrackHeight())),l.exit().remove()})),i.exit().remove(),this.svg.group.on("click.event_emitter",(t=>this.parent.emit("element_clicked",t,!0))).call(this.applyBehaviors.bind(this))}_getTooltipPosition(t){const e=this.getElementStatusNodeId(t.data),s=k.select(`#${e}`).node().getBBox();return{x_min:this.parent.x_scale(t.data.start),x_max:this.parent.x_scale(t.data.end),y_min:s.y,y_max:s.y+s.height}}}const Wt={style:{fill:"none","stroke-width":"2px"},interpolate:"curveLinear",x_axis:{field:"x"},y_axis:{field:"y",axis:1},hitarea_width:5};class Xt extends Ft{constructor(t){if((t=Z(t,Wt)).tooltip)throw new Error("The line / filled curve layer does not support tooltips");super(...arguments)}render(){const t=this.parent,e=this.layout.x_axis.field,s=this.layout.y_axis.field,i=this.svg.group.selectAll("path.lz-data_layer-line").data([this.data]);let a;this.path=i.enter().append("path").attr("class","lz-data_layer-line");const n=t.x_scale,o=t[`y${this.layout.y_axis.axis}_scale`];a=this.layout.style.fill&&"none"!==this.layout.style.fill?k.area().x((t=>+n(t[e]))).y0(+o(0)).y1((t=>+o(t[s]))):k.line().x((t=>+n(t[e]))).y((t=>+o(t[s]))).curve(k[this.layout.interpolate]),i.merge(this.path).attr("d",a).call(et,this.layout.style),i.exit().remove()}setElementStatus(t,e,s){return this.setAllElementStatus(t,s)}setAllElementStatus(t,e){if(void 0===t||!E.adjectives.includes(t))throw new Error("Invalid status");if(void 0===this.layer_state.status_flags[t])return this;void 0===e&&(e=!0),this.global_statuses[t]=e;let s="lz-data_layer-line";return Object.keys(this.global_statuses).forEach((t=>{this.global_statuses[t]&&(s+=` lz-data_layer-line-${t}`)})),this.path.attr("class",s),this.parent.emit("layout_changed",!0),this}}const Qt={style:{stroke:"#D3D3D3","stroke-width":"3px","stroke-dasharray":"10px 10px"},orientation:"horizontal",x_axis:{axis:1,decoupled:!0},y_axis:{axis:1,decoupled:!0},tooltip_positioning:"vertical",offset:0};class te extends Ft{constructor(t){t=Z(t,Qt),["horizontal","vertical"].includes(t.orientation)||(t.orientation="horizontal"),super(...arguments),this.data=[]}getElementId(t){return this.getBaseId()}render(){const t=this.parent,e=`y${this.layout.y_axis.axis}_scale`,s=`y${this.layout.y_axis.axis}_extent`;if("horizontal"===this.layout.orientation)this.data=[{x:t.x_extent[0],y:this.layout.offset},{x:t.x_extent[1],y:this.layout.offset}];else{if("vertical"!==this.layout.orientation)throw new Error('Unrecognized vertical line type. Must be "vertical" or "horizontal"');this.data=[{x:this.layout.offset,y:t[s][0]},{x:this.layout.offset,y:t[s][1]}]}const i=this.svg.group.selectAll("path.lz-data_layer-line").data([this.data]),a=[t.layout.cliparea.height,0],n=k.line().x(((e,s)=>{const i=+t.x_scale(e.x);return isNaN(i)?t.x_range[s]:i})).y(((s,i)=>{const n=+t[e](s.y);return isNaN(n)?a[i]:n}));this.path=i.enter().append("path").attr("class","lz-data_layer-line").merge(i).attr("d",n).call(et,this.layout.style).call(this.applyBehaviors.bind(this)),i.exit().remove()}_getTooltipPosition(t){try{const t=k.mouse(this.svg.container.node()),e=t[0],s=t[1];return{x_min:e-1,x_max:e+1,y_min:s-1,y_max:s+1}}catch(t){return null}}}const ee={point_size:40,point_shape:"circle",tooltip_positioning:"horizontal",color:"#888888",coalesce:{active:!1,max_points:800,x_min:"-Infinity",x_max:"Infinity",y_min:0,y_max:3,x_gap:7,y_gap:7},fill_opacity:1,y_axis:{axis:1},id_field:"id"};class se extends Ft{constructor(t){(t=Z(t,ee)).label&&isNaN(t.label.spacing)&&(t.label.spacing=4),super(...arguments)}_getTooltipPosition(t){const e=this.parent.x_scale(t.data[this.layout.x_axis.field]),s=`y${this.layout.y_axis.axis}_scale`,i=this.parent[s](t.data[this.layout.y_axis.field]),a=this.resolveScalableParameter(this.layout.point_size,t.data),n=Math.sqrt(a/Math.PI);return{x_min:e-n,x_max:e+n,y_min:i-n,y_max:i+n}}flip_labels(){const t=this,e=t.resolveScalableParameter(t.layout.point_size,{}),s=t.layout.label.spacing,i=Boolean(t.layout.label.lines),a=2*s,n=this.parent_plot.layout.width-this.parent.layout.margin.left-this.parent.layout.margin.right-2*s,o=(t,a)=>{const n=+t.attr("x"),o=2*s+2*Math.sqrt(e);let r,l;i&&(r=+a.attr("x2"),l=s+2*Math.sqrt(e)),"start"===t.style("text-anchor")?(t.style("text-anchor","end"),t.attr("x",n-o),i&&a.attr("x2",r-l)):(t.style("text-anchor","start"),t.attr("x",n+o),i&&a.attr("x2",r+l))};t.label_texts.each((function(e,a){const r=k.select(this);if(+r.attr("x")+r.node().getBoundingClientRect().width+s>n){const e=i?k.select(t.label_lines.nodes()[a]):null;o(r,e)}})),t.label_texts.each((function(e,n){const r=k.select(this);if("end"===r.style("text-anchor"))return;let l=+r.attr("x");const h=r.node().getBoundingClientRect(),c=i?k.select(t.label_lines.nodes()[n]):null;t.label_texts.each((function(){const t=k.select(this).node().getBoundingClientRect();h.leftt.left&&h.topt.top&&(o(r,c),l=+r.attr("x"),l-h.width-sl.left&&r.topl.top))return;s=!0;const h=o.attr("y"),c=.5*(r.top_?(g=d-+n,d=+n,u-=g):u+l.height/2>_&&(g=u-+h,u=+h,d-=g),a.attr("y",d),o.attr("y",u)}))})),s){if(t.layout.label.lines){const e=t.label_texts.nodes();t.label_lines.attr("y2",((t,s)=>k.select(e[s]).attr("y")))}this.seperate_iterations<150&&setTimeout((()=>{this.separate_labels()}),1)}}render(){const t=this,e=this.parent.x_scale,s=this.parent[`y${this.layout.y_axis.axis}_scale`],i=Symbol.for("lzX"),a=Symbol.for("lzY");let n=this._applyFilters();if(n.forEach((t=>{let n=e(t[this.layout.x_axis.field]),o=s(t[this.layout.y_axis.field]);isNaN(n)&&(n=-1e3),isNaN(o)&&(o=-1e3),t[i]=n,t[a]=o})),this.layout.coalesce.active&&n.length>this.layout.coalesce.max_points){let{x_min:t,x_max:i,y_min:a,y_max:o,x_gap:r,y_gap:l}=this.layout.coalesce;n=function(t,e,s,i,a,n,o){let r=[];const l=Symbol.for("lzX"),h=Symbol.for("lzY");let c=null,d=null,u=[];function p(){if(u.length){const t=u[Math.floor((u.length-1)/2)];r.push(t)}c=d=null,u=[]}function _(t,e,s){c=t,d=e,u.push(s)}return t.forEach((t=>{const g=t[l],y=t[h],m=g>=e&&g<=s&&y>=a&&y<=n;t.lz_is_match||!m?(p(),r.push(t)):null===c?_(g,y,t):Math.abs(g-c)<=i&&Math.abs(y-d)<=o?u.push(t):(p(),_(g,y,t))})),p(),r}(n,isFinite(t)?e(+t):-1/0,isFinite(i)?e(+i):1/0,r,isFinite(o)?s(+o):-1/0,isFinite(a)?s(+a):1/0,l)}if(this.layout.label){let e;const s=t.layout.label.filters||[];if(s.length){const t=this.filter.bind(this,s);e=n.filter(t)}else e=n;this.label_groups=this.svg.group.selectAll(`g.lz-data_layer-${this.layout.type}-label`).data(e,(t=>`${t[this.layout.id_field]}_label`));const o=`lz-data_layer-${this.layout.type}-label`,r=this.label_groups.enter().append("g").attr("class",o);this.label_texts&&this.label_texts.remove(),this.label_texts=this.label_groups.merge(r).append("text").text((e=>At(t.layout.label.text||"",e,this.getElementAnnotation(e)))).attr("x",(e=>e[i]+Math.sqrt(t.resolveScalableParameter(t.layout.point_size,e))+t.layout.label.spacing)).attr("y",(t=>t[a])).attr("text-anchor","start").call(et,t.layout.label.style||{}),t.layout.label.lines&&(this.label_lines&&this.label_lines.remove(),this.label_lines=this.label_groups.merge(r).append("line").attr("x1",(t=>t[i])).attr("y1",(t=>t[a])).attr("x2",(e=>e[i]+Math.sqrt(t.resolveScalableParameter(t.layout.point_size,e))+t.layout.label.spacing/2)).attr("y2",(t=>t[a])).call(et,t.layout.label.lines.style||{})),this.label_groups.exit().remove()}else this.label_texts&&this.label_texts.remove(),this.label_lines&&this.label_lines.remove(),this.label_groups&&this.label_groups.remove();const o=this.svg.group.selectAll(`path.lz-data_layer-${this.layout.type}`).data(n,(t=>t[this.layout.id_field])),r=k.symbol().size(((t,e)=>this.resolveScalableParameter(this.layout.point_size,t,e))).type(((t,e)=>K(this.resolveScalableParameter(this.layout.point_shape,t,e)))),l=`lz-data_layer-${this.layout.type}`;o.enter().append("path").attr("class",l).attr("id",(t=>this.getElementId(t))).merge(o).attr("transform",(t=>`translate(${t[i]}, ${t[a]})`)).attr("fill",((t,e)=>this.resolveScalableParameter(this.layout.color,t,e))).attr("fill-opacity",((t,e)=>this.resolveScalableParameter(this.layout.fill_opacity,t,e))).attr("d",r),o.exit().remove(),this.layout.label&&(this.flip_labels(),this.seperate_iterations=0,this.separate_labels()),this.svg.group.on("click.event_emitter",(()=>{const t=k.select(k.event.target).datum();this.parent.emit("element_clicked",t,!0)})).call(this.applyBehaviors.bind(this))}makeLDReference(t){let e=null;if(void 0===t)throw new Error("makeLDReference requires one argument of any type");return e="object"==typeof t?this.layout.id_field&&void 0!==t[this.layout.id_field]?t[this.layout.id_field].toString():void 0!==t.id?t.id.toString():t.toString():t.toString(),this.parent.emit("set_ldrefvar",{ldrefvar:e},!0),this.parent_plot.applyState({ldrefvar:e})}}class ie extends se{constructor(t){super(...arguments),this._categories={}}_prepareData(){const t=this.layout.x_axis.field||"x",e=this.layout.x_axis.category_field;if(!e)throw new Error(`Layout for ${this.layout.id} must specify category_field`);const s=this.data.sort(((t,s)=>{const i=t[e],a=s[e],n="string"==typeof i?i.toLowerCase():i,o="string"==typeof a?a.toLowerCase():a;return n===o?0:n{e[t]=e[t]||s})),s}_generateCategoryBounds(){const t=this.layout.x_axis.category_field,e=this.layout.x_axis.field||"x",s={};this.data.forEach((i=>{const a=i[t],n=i[e],o=s[a]||[n,n];s[a]=[Math.min(o[0],n),Math.max(o[1],n)]}));const i=Object.keys(s);return this._setDynamicColorScheme(i),s}_getColorScale(t){let e=(t=t||this.layout).color||[];if(Array.isArray(e)&&(e=e.find((t=>"categorical_bin"===t.scale_function))),!e||"categorical_bin"!==e.scale_function)throw new Error("This layer requires that color options be provided as a `categorical_bin`");return e}_setDynamicColorScheme(t){const e=this._getColorScale(this.layout).parameters,s=this._getColorScale(this._base_layout).parameters;if(s.categories.length&&s.values.length){const i={};s.categories.forEach((t=>{i[t]=1})),t.every((t=>Object.prototype.hasOwnProperty.call(i,t)))?e.categories=s.categories:e.categories=t}else e.categories=t;let i;for(i=s.values.length?s.values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];i.length{const o=i[t];let r;switch(s){case"left":r=o[0];break;case"center":const t=o[1]-o[0];r=o[0]+(0!==t?t:o[0])/2;break;case"right":r=o[1]}return{x:r,text:t,style:{fill:a[e.indexOf(t)]||"#000000"}}}))}}applyCustomDataMethods(){return this.data=this._prepareData(),this._categories=this._generateCategoryBounds(),this}}const ae=new c;for(let[t,e]of Object.entries(o))ae.add(t,e);const ne=ae,oe=7.301,re={namespace:{assoc:"assoc"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n {{#if {{namespace[ld]}}isrefvar}}LD Reference Variant{{#else}}\n Make LD Reference{{/if}}
'},le=function(){const t=J(re);return t.html+="{{#if lz_show_label}}Hide{{#else}}Show{{/if}} label",t}(),he={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'

{{gene_name|htmlescape}}

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

{{/if}}More data on gnomAD'},ce={namespace:{assoc:"assoc",catalog:"catalog"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{{{namespace[catalog]}}variant|htmlescape}}
Catalog entries: {{n_catalog_matches|htmlescape}}
Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
More: GWAS catalog / dbSNP'},de={namespace:{access:"access"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Regulatory element
{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
Promoter
{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}Score: {{{{namespace[access]}}score|htmlescape}}"},ue={id:"significance",type:"orthogonal_line",tag:"significance",orientation:"horizontal",offset:oe},pe={namespace:{recomb:"recomb"},id:"recombrate",type:"line",tag:"recombination",fields:["{{namespace[recomb]}}position","{{namespace[recomb]}}recomb_rate"],z_index:1,style:{stroke:"#0000FF","stroke-width":"1.5px"},x_axis:{field:"{{namespace[recomb]}}position"},y_axis:{axis:2,field:"{{namespace[recomb]}}recomb_rate",floor:0,ceiling:100}},_e={namespace:{assoc:"assoc",ld:"ld"},id:"associationpvalues",type:"scatter",tag:"association",fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}position","{{namespace[assoc]}}log_pvalue","{{namespace[assoc]}}log_pvalue|logtoscinotation","{{namespace[assoc]}}ref_allele","{{namespace[ld]}}state","{{namespace[ld]}}isrefvar"],id_field:"{{namespace[assoc]}}variant",coalesce:{active:!0},point_shape:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"diamond",else:"circle"}},point_size:{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:80,else:40}},color:[{scale_function:"if",field:"{{namespace[ld]}}isrefvar",parameters:{field_value:1,then:"#9632b8"}},{scale_function:"numerical_bin",field:"{{namespace[ld]}}state",parameters:{breaks:[0,.2,.4,.6,.8],values:["rgb(70, 54, 153)","rgb(38, 188, 225)","rgb(110, 254, 104)","rgb(248, 195, 42)","rgb(219, 61, 17)"]}},"#AAAAAA"],legend:[{shape:"diamond",color:"#9632b8",size:40,label:"LD Ref Var",class:"lz-data_layer-scatter"},{shape:"circle",color:"rgb(219, 61, 17)",size:40,label:"1.0 > r² ≥ 0.8",class:"lz-data_layer-scatter"},{shape:"circle",color:"rgb(248, 195, 42)",size:40,label:"0.8 > r² ≥ 0.6",class:"lz-data_layer-scatter"},{shape:"circle",color:"rgb(110, 254, 104)",size:40,label:"0.6 > r² ≥ 0.4",class:"lz-data_layer-scatter"},{shape:"circle",color:"rgb(38, 188, 225)",size:40,label:"0.4 > r² ≥ 0.2",class:"lz-data_layer-scatter"},{shape:"circle",color:"rgb(70, 54, 153)",size:40,label:"0.2 > r² ≥ 0.0",class:"lz-data_layer-scatter"},{shape:"circle",color:"#AAAAAA",size:40,label:"no r² data",class:"lz-data_layer-scatter"}],label:null,z_index:2,x_axis:{field:"{{namespace[assoc]}}position"},y_axis:{axis:1,field:"{{namespace[assoc]}}log_pvalue",floor:0,upper_buffer:.1,min_extent:[0,10]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(re)},ge={namespace:{access:"access"},id:"coaccessibility",type:"arcs",tag:"coaccessibility",fields:["{{namespace[access]}}start1","{{namespace[access]}}end1","{{namespace[access]}}start2","{{namespace[access]}}end2","{{namespace[access]}}id","{{namespace[access]}}target","{{namespace[access]}}score"],match:{send:"{{namespace[access]}}target",receive:"{{namespace[access]}}target"},id_field:"{{namespace[access]}}id",filters:[{field:"{{namespace[access]}}score",operator:"!=",value:null}],color:[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#4285f4"}},{field:"lz_is_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},{scale_function:"ordinal_cycle",parameters:{values:["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"]}}],x_axis:{field1:"{{namespace[access]}}start1",field2:"{{namespace[access]}}start2"},y_axis:{axis:1,field:"{{namespace[access]}}score",upper_buffer:.1,min_extent:[0,1]},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(de)},ye=function(){let t=J(_e);return t=Z({id:"associationpvaluescatalog",fill_opacity:.7},t),t.tooltip.html+='{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}',t.namespace.catalog="catalog",t.fields.push("{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue"),t}(),me={namespace:{phewas:"phewas"},id:"phewaspvalues",type:"category_scatter",tag:"phewas",point_shape:"circle",point_size:70,tooltip_positioning:"vertical",id_field:"{{namespace[phewas]}}id",fields:["{{namespace[phewas]}}id","{{namespace[phewas]}}log_pvalue","{{namespace[phewas]}}trait_group","{{namespace[phewas]}}trait_label"],x_axis:{field:"{{namespace[phewas]}}x",category_field:"{{namespace[phewas]}}trait_group",lower_buffer:.025,upper_buffer:.025},y_axis:{axis:1,field:"{{namespace[phewas]}}log_pvalue",floor:0,upper_buffer:.15},color:[{field:"{{namespace[phewas]}}trait_group",scale_function:"categorical_bin",parameters:{categories:[],values:[],null_value:"#B8B8B8"}}],fill_opacity:.7,tooltip:{closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:["Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
","Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
","P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
"].join("")},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},label:{text:"{{{{namespace[phewas]}}trait_label}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[phewas]}}log_pvalue",operator:">=",value:20}],style:{"font-size":"14px","font-weight":"bold",fill:"#333333"}}},fe={namespace:{gene:"gene",constraint:"constraint"},id:"genes",type:"genes",tag:"genes",fields:["{{namespace[gene]}}all","{{namespace[constraint]}}all"],id_field:"gene_id",behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(he)},be=Z({filters:[{field:"gene_type",operator:"in",value:["protein_coding","IG_C_gene","IG_D_gene","IG_J_gene","IG_V_gene","TR_C_gene","TR_D_gene","TR_J_gene","TR_V_gene","rRNA","Mt_rRNA","Mt_tRNA"]}]},J(fe)),xe={namespace:{assoc:"assoc",catalog:"catalog"},id:"annotation_catalog",type:"annotation_track",tag:"gwascatalog",id_field:"{{namespace[assoc]}}variant",x_axis:{field:"{{namespace[assoc]}}position"},color:"#0000CC",fields:["{{namespace[assoc]}}variant","{{namespace[assoc]}}chromosome","{{namespace[assoc]}}position","{{namespace[catalog]}}variant","{{namespace[catalog]}}rsid","{{namespace[catalog]}}trait","{{namespace[catalog]}}log_pvalue","{{namespace[catalog]}}pos"],filters:[{field:"{{namespace[catalog]}}rsid",operator:"!=",value:null},{field:"{{namespace[catalog]}}log_pvalue",operator:">",value:oe}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:J(ce),tooltip_positioning:"top"},ve={type:"set_state",tag:"ld_population",position:"right",color:"blue",button_html:"LD Population: ",show_selected:!0,button_title:"Select LD Population: ",custom_event_name:"widget_set_ldpop",state_field:"ld_pop",options:[{display_name:"ALL (default)",value:"ALL"},{display_name:"AFR",value:"AFR"},{display_name:"AMR",value:"AMR"},{display_name:"EAS",value:"EAS"},{display_name:"EUR",value:"EUR"},{display_name:"SAS",value:"SAS"}]},we={type:"display_options",tag:"gene_filter",custom_event_name:"widget_gene_filter_choice",position:"right",color:"blue",button_html:"Filter...",button_title:"Choose which genes to show",layer_name:"genes",default_config_display_name:"Coding genes & rRNA",options:[{display_name:"All features",display:{filters:null}}]},ze={widgets:[{type:"remove_panel",position:"right",color:"red",group_position:"end"},{type:"move_panel_up",position:"right",group_position:"middle"},{type:"move_panel_down",position:"right",group_position:"start",style:{"margin-left":"0.75em"}}]},$e={widgets:[{type:"title",title:"LocusZoom",subtitle:'v0.13.4',position:"left"},{type:"download",position:"right",group_position:"end"},{type:"download_png",position:"right",group_position:"start"}]},ke=function(){const t=J($e);return t.widgets.push(J(ve)),t}(),Ee=function(){const t=J($e);return t.widgets.push({type:"shift_region",step:5e5,button_html:">>",position:"right",group_position:"end"},{type:"shift_region",step:5e4,button_html:">",position:"right",group_position:"middle"},{type:"zoom_region",step:.2,position:"right",group_position:"middle"},{type:"zoom_region",step:-.2,position:"right",group_position:"middle"},{type:"shift_region",step:-5e4,button_html:"<",position:"right",group_position:"middle"},{type:"shift_region",step:-5e5,button_html:"<<",position:"right",group_position:"start"}),t}(),Me={id:"association",tag:"association",min_height:200,height:225,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:function(){const t=J(ze);return t.widgets.push({type:"toggle_legend",position:"right"}),t}(),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"-log10 p-value",label_offset:28},y2:{label:"Recombination Rate (cM/Mb)",label_offset:40}},legend:{orientation:"vertical",origin:{x:55,y:40},hidden:!0},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,drag_y2_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(ue),J(pe),J(_e)]},Se={id:"coaccessibility",tag:"coaccessibility",min_height:150,height:180,margin:{top:35,right:50,bottom:40,left:50},inner_border:"rgb(210, 210, 210)",toolbar:J(ze),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"},y1:{label:"Score",label_offset:28,render:!1}},interaction:{drag_background_to_pan:!0,drag_x_ticks_to_scale:!0,drag_y1_ticks_to_scale:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(ge)]},Ne=function(){let t=J(Me);return t=Z({id:"associationcatalog",namespace:{assoc:"assoc",ld:"ld",catalog:"catalog"}},t),t.toolbar.widgets.push({type:"display_options",position:"right",color:"blue",button_html:"Display options...",button_title:"Control how plot items are displayed",layer_name:"associationpvaluescatalog",default_config_display_name:"No catalog labels (default)",options:[{display_name:"Label catalog traits",display:{label:{text:"{{{{namespace[catalog]}}trait}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"{{namespace[catalog]}}trait",operator:"!=",value:null},{field:"{{namespace[catalog]}}log_pvalue",operator:">",value:oe},{field:"{{namespace[ld]}}state",operator:">",value:.4}],style:{"font-size":"10px","font-weight":"bold",fill:"#333333"}}}}]}),t.data_layers=[J(ue),J(pe),J(ye)],t}(),Ae={id:"genes",tag:"genes",min_height:150,height:225,margin:{top:20,right:50,bottom:20,left:50},axes:{},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},toolbar:function(){const t=J(ze);return t.widgets.push({type:"resize_to_data",position:"right",button_html:"Resize"},J(we)),t}(),data_layers:[J(be)]},Te={id:"phewas",tag:"phewas",min_height:300,height:300,margin:{top:20,right:50,bottom:120,left:50},inner_border:"rgb(210, 210, 210)",axes:{x:{ticks:{style:{"font-weight":"bold","font-size":"11px","text-anchor":"start"},transform:"rotate(50)",position:"left"}},y1:{label:"-log10 p-value",label_offset:28}},data_layers:[J(ue),J(me)]},Le={id:"annotationcatalog",tag:"gwascatalog",min_height:50,height:50,margin:{top:25,right:50,bottom:10,left:50},inner_border:"rgb(210, 210, 210)",toolbar:J(ze),axes:{x:{extent:"state",render:!1}},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[J(xe)]},Oe={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:ke,panels:[J(Me),J(Ae)]},Ce={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:ke,panels:[Le,Ne,Ae]},Pe={width:800,responsive_resize:!0,toolbar:$e,panels:[J(Te),Z({height:300,margin:{bottom:40},axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:32,tick_format:"region",extent:"state"}}},J(Ae))],mouse_guide:!1},Re={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:J($e),panels:[J(Se),function(){const t=Object.assign({height:270},J(Ae)),e=t.data_layers[0];e.match={send:"gene_name",receive:"gene_name"};const s=[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#4285f4"}},{field:"lz_is_match",scale_function:"if",parameters:{field_value:!1,then:"#EAE6E6"}},"#363696"];return e.color=s,e.stroke=s,t}()]},De={standard_association:re,standard_association_with_label:le,standard_genes:he,catalog_variant:ce,coaccessibility:de},Ie={ldlz2_pop_selector:ve,gene_selector_menu:we},je={standard_panel:ze,standard_plot:$e,standard_association:ke,region_nav_plot:Ee},Be={significance:ue,recomb_rate:pe,association_pvalues:_e,coaccessibility:ge,association_pvalues_catalog:ye,phewas_pvalues:me,genes:fe,genes_filtered:be,annotation_catalog:xe},Ue={association:Me,coaccessibility:Se,association_catalog:Ne,genes:Ae,phewas:Te,annotation_catalog:Le},Fe={standard_association:Oe,association_catalog:Ce,standard_phewas:Pe,coaccessibility:Re};const qe=new class extends h{get(t,e,s={}){if(!t||!e)throw new Error("Must specify both the type and name for the layout desired. See .list() for available options");let i=super.get(t).get(e);if(i=Z(s,i),i.unnamespaced)return delete i.unnamespaced,J(i);let a="";"string"==typeof i.namespace?a=i.namespace:"object"==typeof i.namespace&&Object.keys(i.namespace).length&&(a=void 0!==i.namespace.default?i.namespace.default:i.namespace[Object.keys(i.namespace)[0]].toString()),a+=a.length?":":"";return J(H(i,i.namespace,a))}add(t,e,s,i=!1){if(!(t&&e&&s))throw new Error("To add a layout, type, name, and item must all be specified");if("object"!=typeof s)throw new Error("The configuration to be added must be an object");this.has(t)||super.add(t,new h);const a=J(s);return super.get(t).add(e,a,i)}list(t){if(!t){let t={};for(let[e,s]of this._items)t[e]=s.list();return t}return super.get(t).list()}merge(t,e){return Z(t,e)}renameField(){return V(...arguments)}mutate_attrs(){return Y(...arguments)}query_attrs(){return W(...arguments)}};for(let[t,e]of Object.entries(r))for(let[s,i]of Object.entries(e))qe.add(t,s,i);const Ge=qe;const He={version:l,populate:function(t,e,s){if(void 0===t)throw new Error("LocusZoom.populate selector not defined");let i;return k.select(t).html(""),k.select(t).call((function(t){if(void 0===t.node().id){let e=0;for(;!k.select(`#lz-${e}`).empty();)e++;t.attr("id",`#lz-${e}`)}if(i=new Mt(t.node().id,e,s),i.container=t.node(),void 0!==t.node().dataset&&void 0!==t.node().dataset.region){const e=function(t){const e=/^(\w+):([\d,.]+[kmgbKMGB]*)$/;let s=/^(\w+):([\d,.]+[kmgbKMGB]*)([-+])([\d,.]+[kmgbKMGB]*)$/.exec(t);if(s){if("+"===s[3]){const t=Nt(s[2]),e=Nt(s[4]);return{chr:s[1],start:t-e,end:t+e}}return{chr:s[1],start:Nt(s[2]),end:Nt(s[4])}}if(s=e.exec(t),s)return{chr:s[1],position:Nt(s[2])};return null}(t.node().dataset.region);Object.keys(e).forEach((function(t){i.state[t]=e[t]}))}i.svg=k.select(`div#${i.id}`).append("svg").attr("version","1.1").attr("xmlns","http://www.w3.org/2000/svg").attr("id",`${i.id}_svg`).attr("class","lz-locuszoom").call(et,i.layout.style),i.setDimensions(),i.positionPanels(),i.initialize(),e&&i.refresh()})),i},DataSources:class extends h{constructor(t){super(),this._registry=t||$}add(t,e,s=!1){if(this._registry.has(t))throw new Error(`The namespace ${t} is already in use by another source`);if(t.match(/[^A-Za-z0-9_]/))throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores. Invalid name: ${t}`);if(Array.isArray(e)){const[t,s]=e;e=this._registry.create(t,s)}return e.source_id=t,super.add(t,e,s),this}},Adapters:$,DataLayers:ne,Layouts:Ge,MatchFunctions:Lt,ScaleFunctions:Bt,TransformationFunctions:P,Widgets:xt,get KnownDataSources(){return console.warn('Deprecation warning: KnownDataSources has been renamed to "Adapters"'),$}},Ze=[];He.use=function(t,...e){if(!Ze.includes(t)){if(e.unshift(He),"function"==typeof t.install)t.install.apply(t,e);else{if("function"!=typeof t)throw new Error("Plugin must export a function that receives the LocusZoom object as an argument");t.apply(null,e)}Ze.push(t)}};const Je=He})(),LocusZoom=e.default})(); //# sourceMappingURL=locuszoom.app.min.js.map \ No newline at end of file diff --git a/dist/locuszoom.app.min.js.map b/dist/locuszoom.app.min.js.map index bc60c506..b4aed111 100644 --- a/dist/locuszoom.app.min.js.map +++ b/dist/locuszoom.app.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/webpack/runtime/make namespace object","webpack://[name]/./esm/version.js","webpack://[name]/./esm/registry/base.js","webpack://[name]/./esm/data/adapters.js","webpack://[name]/./esm/registry/adapters.js","webpack://[name]/external \"d3\"","webpack://[name]/./esm/components/constants.js","webpack://[name]/./esm/helpers/transforms.js","webpack://[name]/./esm/registry/transforms.js","webpack://[name]/./esm/data/field.js","webpack://[name]/./esm/helpers/jsonpath.js","webpack://[name]/./esm/helpers/layouts.js","webpack://[name]/./esm/data/requester.js","webpack://[name]/./esm/helpers/common.js","webpack://[name]/./esm/components/toolbar/widgets.js","webpack://[name]/./esm/registry/widgets.js","webpack://[name]/./esm/components/toolbar/index.js","webpack://[name]/./esm/components/legend.js","webpack://[name]/./esm/components/panel.js","webpack://[name]/./esm/helpers/display.js","webpack://[name]/./esm/components/plot.js","webpack://[name]/./esm/registry/matchers.js","webpack://[name]/./esm/helpers/scalable.js","webpack://[name]/./esm/registry/scalable.js","webpack://[name]/./esm/components/data_layer/base.js","webpack://[name]/./esm/components/data_layer/annotation_track.js","webpack://[name]/./esm/components/data_layer/highlight_regions.js","webpack://[name]/./esm/components/data_layer/arcs.js","webpack://[name]/./esm/components/data_layer/genes.js","webpack://[name]/./esm/components/data_layer/line.js","webpack://[name]/./esm/components/data_layer/scatter.js","webpack://[name]/./esm/helpers/render.js","webpack://[name]/./esm/registry/data_layers.js","webpack://[name]/./esm/layouts/index.js","webpack://[name]/./esm/registry/layouts.js","webpack://[name]/./esm/data/sources.js","webpack://[name]/./esm/index.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","RegistryBase","this","_items","Map","name","has","Error","item","override","set","delete","Array","from","keys","ClassRegistry","args","parent_name","source_name","overrides","console","warn","arguments","length","base","sub","assign","add","validateBuildSource","class_name","build","source","includes","BaseAdapter","config","_enableCache","_cachedKey","_cache_pos_start","_cache_pos_end","__dependentSource","parseInit","params","state","chain","fields","getURL","cache_pos_chr","chr","start","end","url","fetch","then","response","ok","statusText","text","req","cacheKey","getCacheKey","Promise","resolve","_cachedResponse","fetchRequest","data","isArray","N","every","constructor","records","i","record","j","push","outnames","trans","fieldFound","k","map","output_record","val","forEach","v","resp","source_id","discrete","json","JSON","parse","normalizeResponse","standardized","annotateData","extractFields","one_source_body","combineChainBody","new_body","header","body","preGetData","pre","getRequest","parseResponse","BaseApiAdapter","super","AssociationLZ","id_field","x","unshift","analysis","sort","a","b","LDServer","join","dataFields","id","position","position_field","pvalue","pvalue_field","_names_","names","nameMatch","arr","regexes","regex","m","filter","match","id_match","RegExp","isrefvarin","isrefvarout","ldin","ldout","refVar","findRequestedFields","ldrefvar","findMergeFields","columns","pval_field","cmp","test","extremeVal","extremeIdx","findExtremeValue","original","chrom","pos","ref","alt","refVar_formatted","genome_build","ld_source","population","ld_pop","method","refVar_raw","getRefvar","encodeURIComponent","_","reqFields","corrField","rsquare","left","right","lfield","rfield","position2","leftJoin","refvar","idfield","outrefname","outldname","tagRefVariant","combined","chainRequests","payload","concat","next","GwasCatalogLZ","source_query","posMatch","find","decider","decider_out","indexOf","n_matches","fn","outn","chainNames","catNames","GeneLZ","GeneConstraintLZ","unique_gene_names","reduce","acc","gene","gene_name","query","replace","stringify","headers","catch","err","alias","constraint","toString","parseFloat","toFixed","RecombLZ","SOURCE_NAME","StaticSource","_data","PheWASLZ","variant","ConnectorSource","sources","_source_name_mapping","specified_ids","_getRequiredSources","ns","chain_source_id","registry","type","entries","d3","STATUSES","verbs","adjectives","log10","isNaN","Math","log","LN10","neglog10","logtoscinotation","exp","ceil","diff","pow","scinotation","abs","floor","toExponential","htmlescape","s","is_numeric","urlencode","template_string","funcs","substring","func","_collectTransforms","Field","field","parts","exec","full_name","namespace","transformations","split","transform","transforms","extra","_applyTransformations","ATTR_REGEX","EXPR_REGEX","get_next_token","q","substr","attr","depth","e","attrs","get_item_at_deep_path","path","parent","tokens_to_keys","selectors","sel","remaining_selectors","slice","paths","d","undefined","p","__","subject","uniqPaths","elem","values","localeCompare","_query","matches","items","get_items_from_tokens","normalize_query","selector","tokenize","sqrt3","sqrt","triangledown","context","size","y","moveTo","lineTo","closePath","applyNamespaces","element","default_namespace","default","re","resolved_namespace","r","merge","namespaced_element","namespaced_property","property","custom_layout","default_layout","custom_type","default_type","deepCopy","nameToSymbol","shape","factory_name","charAt","toUpperCase","renameField","layout","old_name","new_name","warn_transforms","this_type","escaped","filter_regex","match_val","mutate_attrs","value_or_callable","value_or_callback","old_value","new_value","mutate","query_attrs","_sources","requests","raw","__split_requests","request_handles","getData","ret","generateCurtain","showing","content_selector","hide_delay","show","content","css","curtain","parent_plot","svg","node","parentNode","insert","append","html","on","hide","update","clearTimeout","applyStyles","page_origin","_getPageOrigin","height","_total_height","style","width","delay","setTimeout","remove","generateLoader","progress_selector","cancel_selector","loader","percent","loader_boundrect","getBoundingClientRect","min","max","animate","classed","setPercentCompleted","selection","styles","BaseWidget","color","parent_panel","parent_svg","button","persist","group_position","initialize","status","menu","shouldPersist","force","destroy","Button","parent_toolbar","tag","title","permanent","outer_selector","inner_selector","scroll_position","hidden","getBaseId","scrollTop","populate","page_scroll_top","document","documentElement","container_offset","getContainerOffset","toolbar_client_rect","button_client_rect","menu_client_rect","total_content_height","scrollHeight","top","bottom","base_max_width","container_max_width","content_max_width","base_max_height","setPopulate","menu_populate_function","setOnclick","highlight","bool","Boolean","setStatus","onmouseover","onmouseout","onclick","getClass","preUpdate","postUpdate","Title","div_selector","title_selector","subtitle","RegionScale","positionIntToString","class","FilterField","_data_layer","data_layers","layer_name","_event_name","custom_event_name","_field","_field_display_html","field_display_html","_operator","operator","_filter_id","_data_type","data_type","_value_selector","filters","result","index","_getTarget","splice","_clearFilter","emit","filter_id","Number","input_size","timer","apply","debounce","_getValue","_setFilter","render","DownloadSVG","_filename","filename","_button_html","button_html","_button_title","button_title","setColor","setHtml","setTitle","setOnMouseover","_getBlobUrl","old","URL","revokeObjectURL","setOnMouseout","root","ancestor_pattern","extractedCSSText","styleSheets","cssRules","rule","selectorText","cssText","styleElement","createElement","setAttribute","innerHTML","refNode","hasChildNodes","children","insertBefore","rescale","copy","cloneNode","selectAll","each","dy","serializer","XMLSerializer","_getDimensions","_appendCSS","_getCSS","serializeToString","_generateSVG","markup","blob","Blob","createObjectURL","DownloadPNG","svg_url","canvas","getContext","reject","image","Image","onload","drawImage","toBlob","png","src","RemovePanel","suppress_confirm","confirm","panel","toolbar","removePanel","MovePanelUp","is_at_top","y_index","disable","moveUp","MovePanelDown","is_at_bottom","panel_ids_by_y_index","moveDown","ShiftRegion","step","applyState","ZoomRegion","can_zoom","current_region_scale","max_region_scale","min_region_scale","new_region_scale","delta","Menu","menu_html","ResizeToData","scaleHeightToData","ToggleLegend","legend","DisplayOptions","allowed_fields","fields_whitelist","dataLayer","dataLayerLayout","defaultConfig","configSlot","_selected_item","uniqueID","random","table","menuLayout","renderRow","display_name","display_options","row_id","row","radioId","field_name","has_option","choice","defaultName","default_config_display_name","options","display","SetState","state_field","show_selected","new_state","choice_name","choice_value","Toolbar","widgets","hide_timeout","dashboard","components","widget","create","error","panel_boundaries","dragging","interaction","orientation","origin","padding","label_size","Legend","background_rect","elements","elements_group","group","line_height","data_layer_ids_by_z_index","reverse","label_x","label_y","shape_factory","path_y","radius","PI","label","bcr","right_x","pad_from_bottom","pad_from_right","min_height","margin","background_click","cliparea","axes","y1","y2","drag_background_to_pan","drag_x_ticks_to_scale","drag_y1_ticks_to_scale","drag_y2_ticks_to_scale","scroll_to_zoom","x_linked","y1_linked","y2_linked","show_loading_indicator","Panel","panels","generateID","initialized","layout_idx","state_id","data_promises","x_scale","y1_scale","y2_scale","x_extent","y1_extent","y2_extent","x_ticks","y1_ticks","y2_ticks","zoom_timeout","event_hooks","initializeLayout","event","hook","theseHooks","hookMatch","eventData","bubble","eventContext","sourceID","target","hookToRun","y_axis","axis","data_layer","z_index","dlid","idx","data_layer_layout","destroyAllTooltips","container","applyDataLayerZIndexesToDataLayerLayouts","setAllElementStatus","clipRect","inner_border","generateExtents","constrain","limit_exponent","neg_min","neg_max","pos_min","pos_max","Infinity","ranges","base_x_range","range","x_shifted","base_y1_range","y1_shifted","base_y2_range","y2_shifted","panel_id","linked_panel_ids","anchor","scalar","zooming","current_extent_size","current_scaled_extent_size","round","invert","zoom_factor","scale","potential_extent_size","new_extent_size","center","offset_ratio","new_x_extent_start","dragged_x","start_x","y_shifted","dragged_y","start_y","domain","renderAxis","zoom_handler","_canInteract","coords","getLinkedPanelIds","data_layer_id","draw","show_immediately","plot_origin","setDimensions","setOrigin","setMargin","x_range","y1_range","y2_range","addDataLayer","base_id","clipPath","addBasicLoader","clearSelections","x_axis","x_axis_label","y1_axis","y1_axis_label","y2_axis","y2_axis_label","mousedown","startDrag","select","applyPanelYIndexesToPanelLayouts","positionPanels","reMap","message","all","decoupled","getAxisExtent","extent","ticks","baseTickConfig","self","nextLayer","getTicks","itemConfig","clip_range","target_tick_count","parseInt","min_n","shrink_sml","high_u_bias","u5_bias","c","base_toFixed","unit","pop","prettyTicks","canRender","axis_params","label_offset","label_rotate","generateTicks","ticksAreAllNumbers","axis_factory","tickPadding","tickValues","tick_format","tickFormat","t","tick_selector","parseFields","tick_mouseover","focus","cursor","target_height","dh","getAbsoluteDataHeight","toggle","verb","adjective","antiverb","min_width","responsive_resize","mouse_guide","Plot","datasource","remap_promises","_base_layout","lzd","_external_listeners","these_hooks","anyEventData","event_name","panel_layout","panelId","mode","panelsList","pid","layer","layer_state","_setDefaultState","clearPanelData","success_callback","opts","error_callback","onerror","listener","new_data","state_changes","mods","attempted_scale","validated_region","attempted_midpoint","temp","_updateStatePosition","loading_data","applyAllElementStatus","some","tracker","registered_events","listeners","removeEventListener","lastElementChild","removeChild","outerHTML","bounding_client_rect","x_offset","scrollLeft","y_offset","offset","offsetParent","offsetTop","offsetLeft","clientRect","resize_listener","rescaleSVG","window","addEventListener","trackExternalListener","load_listener","addPanel","height_scaling_factor","panel_width","panel_height","final_height","x_linked_margins","mouse_guide_svg","mouse_guide_vertical_svg","mouse_guide_horizontal_svg","vertical","horizontal","corner_selector","panel_idx","panel_resize_drag","this_panel","original_panel_height","panel_height_change","loop_panel_id","loop_panel_idx","loop_panel","corner_drag","plot_page_origin","panel_page_origin","mouseout_mouse_guide","mousemove_mouse_guide","mouseup","stopDrag","mousemove","body_node","to_send","active","emitted_by","lz_match_value","client_rect","overrideAxisLayout","axis_number","axis_layout","ceiling","lower_buffer","upper_buffer","min_extent","y_axis_number","suffix","exp_symbols","0","3","6","9","places_exp","min_exp","places","positionStringToInt","suffixre","mult","tokens","condition","variable","branch","close","astify","token","shift","dest","else","ast","cache","render_node","item_value","target_value","if_value","parameters","input","field_value","numerical_bin","breaks","null_value","threshold","prev","curr","categorical_bin","categories","ordinal_cycle","stable_choice","_cache","max_cache_size","clear","hash","String","charCodeAt","interpolate","nullval","upper_idx","brk","normalized_input","isFinite","tooltip","tooltip_positioning","behaviors","BaseDataLayer","_base_id","_filter_func","tooltips","global_statuses","resortDataLayers","getElementId","extra_fields","axis_config","id_key","for","element_id","empty","field_to_match","receive","match_function","broadcast_value","field_resolver","lz_is_match","toHTML","getDataLayer","getPanel","getPlot","deselect","unselectElement","applyCustomDataMethods","option_layout","element_data","data_index","resolveScalableParameter","scale_function","f","getElementAnnotation","dimension","axis_name","data_extent","_getDataExtent","original_extent_span","range_min","range_max","y_scale","y_extent","x_min","x_max","y_min","y_max","plot_layout","layer_layout","tooltip_box","data_layer_height","data_layer_width","x_center","y_center","tooltip_top","tooltip_left","arrow_type","arrow_top","arrow_left","placement","arrow_size","offset_right","offset_left","arrow","filter_rules","array","is_match","test_func","bind","status_flags","Set","updateTooltip","positionTooltip","closable","destroyTooltip","element_or_id","temporary","_getTooltipPosition","_drawTooltip","first_time","resolveStatus","statuses","directive","previousValue","currentValue","sub_status","sub_operator","show_directive","and","hide_directive","antistatus","show_resolved","hide_resolved","has_tooltip","createTooltip","exclusive","get_element_id_error","element_status_node_id","getElementStatusNodeId","added_status","showOrHideTooltip","is_selected","value_to_broadcast","send","setElementStatus","getElementById","event_match","executeBehaviors","requiredKeyStates","datum","behavior","action","current_status_boolean","href","open","location","panel_origin","positionAllTooltips","applyDataMethods","hitarea_width","AnnotationTrack","_hitareas_group","_visible_lines_group","track_data","_applyFilters","hit_areas_selection","_getX","x_left","left_node","left_node_x_center","enter","crds","exit","applyBehaviors","fill_opacity","regions","start_field","end_field","merge_field","HighlightRegions","cur_item","prev_item","new_start","new_end","_mergeNodes","fill","Arcs","_make_line","x1","field1","x2","field2","xmid","curve","line","hitareas","stroke","label_font_size","label_exon_spacing","exon_height","bounding_box_padding","track_vertical_spacing","Genes","transcript_idx","tracks","gene_track_index","1","_getLabelWidth","font_size","temp_text","label_width","getBBox","gene_id","gene_version","transcript_id","transcripts","display_range","text_anchor","centered_margin","display_domain","track","potential_track","collision_on_potential_track","placed_gene","min_start","exons","assignTracks","bboxes","getTrackHeight","boundaries","labels","strand","exon_id","clickareas","gene_bbox_id","gene_bbox","Line","x_field","y_field","y0","path_class","global_status","default_orthogonal_layout","OrthogonalLine","default_y","point_size","point_shape","coalesce","max_points","x_gap","y_gap","Scatter","spacing","handle_lines","lines","min_x","max_x","flip","dn","dnl","dnx","text_swing","dnlx2","line_swing","label_texts","da","dal","label_lines","nodes","dax","abound","bbound","seperate_iterations","again","db","adjust","new_a_y","new_b_y","min_y","max_y","label_elements","separate_labels","xcs","ycs","final_data","x_start","y_start","current_group","_combine","_start_run","in_combine_region","coalesce_scatter_points","label_data","label_groups","style_class","groups_enter","flip_labels","item_data","CategoryScatter","_categories","xField","category_field","sourceData","ak","bk","av","toLowerCase","bv","uniqueCategories","category","bounds","categoryNames","_setDynamicColorScheme","from_source","color_params","colorParams","_getColorScale","baseParams","parameters_categories_hash","colors","categoryBounds","knownCategories","knownColors","xPos","_prepareData","_generateCategoryBounds","LZ_SIG_THRESHOLD_LOGP","standard_association_tooltip","or","standard_association_tooltip_with_label","standard_genes_tooltip","catalog_variant_tooltip","coaccessibility_tooltip","significance_layer","recomb_rate_layer","association_pvalues_layer","coaccessibility_layer","association_pvalues_catalog_layer","catalog","phewas_pvalues_layer","genes_layer","genes_layer_filtered","annotation_catalog_layer","ldlz2_pop_selector_menu","gene_selector_menu","standard_panel_toolbar","standard_plot_toolbar","standard_association_toolbar","region_nav_plot_toolbar","association_panel","coaccessibility_panel","association_catalog_panel","genes_panel","phewas_panel","annotation_catalog_panel","standard_association_plot","association_catalog_plot","standard_phewas_plot","coaccessibility_plot","color_config","standard_association","standard_association_with_label","standard_genes","catalog_variant","coaccessibility","toolbar_widgets","ldlz2_pop_selector","standard_panel","standard_plot","region_nav_plot","significance","recomb_rate","association_pvalues","association_pvalues_catalog","phewas_pvalues","genes","genes_filtered","annotation_catalog","association","association_catalog","phewas","plot","standard_phewas","unnamespaced","contents","list","LocusZoom","version","iterator","dataset","region","parsed_state","chrpos","parsePositionQuery","refresh","DataSources","_registry","Adapters","DataLayers","Layouts","MatchFunctions","ScaleFunctions","TransformationFunctions","Widgets","INSTALLED_PLUGINS","use","plugin","install"],"mappings":";iCACA,IAAIA,EAAsB,CCA1B,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3E,EAAwB,CAACM,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClF,EAAyBT,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,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pBP,OCpBXmzC,SAAQ,EACRC,WAAU,GACVC,QAAO,GACPC,eAAc,GACdC,eAAc,GACdC,wBAAuB,EACvBC,QAAO,GAEP,uBAEI,OADAvyC,QAAQC,KAAK,wEACN,IAYTuyC,GAAoB,GAQ1BlB,GAAUmB,IAAM,SAASC,KAAW9yC,GAEhC,IAAI4yC,GAAkB5xC,SAAS8xC,GAA/B,CAMA,GADA9yC,EAAK2F,QAAQ+rC,IACiB,mBAAnBoB,EAAOC,QACdD,EAAOC,QAAQ51B,MAAM21B,EAAQ9yC,OAC1B,IAAsB,mBAAX8yC,EAGd,MAAM,IAAIvzC,MAAM,mFAFhBuzC,EAAO31B,MAAM,KAAMnd,GAIvB4yC,GAAkBnvC,KAAKqvC,KAI3B,a","file":"locuszoom.app.min.js","sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export default '0.13.3';\n","/**\n * @module\n * @private\n */\n\n/**\n * Base class for all registries.\n *\n * LocusZoom is plugin-extensible, and layouts are JSON-serializable objects that refer to desired features by name (not by class).\n * This is achieved through the use of a central registry that holds a reference to each possible feature.\n *\n * Each registry has some syntactical sugar to make it easier to, eg, modify layouts or create classes.\n * This class is documented solely so that those helper methods can be referenced.\n */\nclass RegistryBase {\n constructor() {\n this._items = new Map();\n }\n\n /**\n * Return the registry member. If the registry stores classes, this returns the class, not the instance.\n * @param {String} name\n * @returns {Function}\n */\n get(name) {\n if (!this._items.has(name)) {\n throw new Error(`Item not found: ${name}`);\n }\n return this._items.get(name);\n }\n\n /**\n * Add a new item to the registry\n * @param {String} name The name of the item to add to the registry\n * @param {*} item The item to be added (constructor, value, etc)\n * @param {boolean} [override=false] Allow redefining an existing item?\n * @return {*} The actual object as added to the registry\n */\n add(name, item, override = false) {\n if (!override && this._items.has(name)) {\n throw new Error(`Item ${name} is already defined`);\n }\n this._items.set(name, item);\n return item;\n }\n\n /**\n * Remove a datasource from the registry (if present)\n * @param {String} name\n * @returns {boolean} True if item removed, false if item was never present\n */\n remove(name) {\n return this._items.delete(name);\n }\n\n /**\n * Check whether the specified item is registered\n * @param {String} name\n * @returns {boolean}\n */\n has(name) {\n return this._items.has(name);\n }\n\n /**\n * Names of each allowed\n * @returns {String[]}\n */\n list() {\n return Array.from(this._items.keys());\n }\n}\n\n/**\n * A specialized registry whose members are class constructors. Contains helper methods for creating instances\n * and subclasses.\n * @ignore\n */\nclass ClassRegistry extends RegistryBase {\n /**\n * Create an instance of the specified class from the registry\n * @param {String} name\n * @param {*} args Any additional arguments to be passed to the constructor\n * @returns {*}\n */\n create(name, ...args) {\n const base = this.get(name);\n return new base(...args);\n }\n\n /**\n * Create a new child class for an item in the registry.\n *\n * This is (almost, but not quite) a compatibility layer for old sites that used locuszoom\n *\n * This is primarily aimed at low-tooling environments. It is syntactic sugar, roughly equivalent to:\n * `registry.get(base); registry.add(name, class A extends base {});`\n *\n * Because this bypasses es6 class mechanics, certain things, esp super calls, may not work as well as using the\n * \"real\" class expression. This method is provided solely for convenience.\n *\n * This method is a compatibility layer for old versions. Born to be deprecated!\n * @deprecated\n * @param {string} parent_name The name of the desired parent class as represented in the registry\n * @param {string} source_name The desired name of the class to be created, as it will be named in the registry\n * @param {object} overrides An object\n * @return {*}\n */\n extend(parent_name, source_name, overrides) {\n console.warn('Deprecation warning: .extend method will be removed in future versions, in favor of explicit ES6 subclasses');\n if (arguments.length !== 3) {\n throw new Error('Invalid arguments to .extend');\n }\n\n const base = this.get(parent_name);\n class sub extends base {}\n Object.assign(sub.prototype, overrides, base);\n this.add(source_name, sub);\n return sub;\n }\n}\n\n\nexport default RegistryBase;\nexport {RegistryBase, ClassRegistry};\n","/**\n * Define standard data adapters used to retrieve data (usually from REST APIs)\n *\n * ## Adapters are responsible for retrieving data\n * In LocusZoom, the act of fetching data (from API, JSON file, or Tabix) is separate from the act of rendering data.\n * Adapters are used to handle retrieving from different sources, and can provide various advanced functionality such\n * as caching, data harmonization, and annotating API responses with calculated fields. They can also be used to join\n * two data sources, such as annotating association summary statistics with LD information.\n *\n * Most of LocusZoom's builtin layouts and adapters are written for the field names and data formats of the\n * UMich [PortalDev API](https://portaldev.sph.umich.edu/docs/api/v1/#introduction):\n * if your data is in a different format, an adapter can be used to coerce or rename fields.\n * Although it is possible to change every part of a rendering layout to expect different fields, this is often much\n * more work than providing data in the expected format.\n *\n * ## Creating data adapters\n * The documentation in this section describes the available data types and adapters. Real LocusZoom usage almost never\n * creates these classes directly: rather, they are defined from configuration objects that ask for a source by name.\n *\n * The below example creates an object responsible for fetching two different GWAS summary statistics datasets from two different API endpoints, for any data\n * layer that asks for fields from `trait1:fieldname` or `trait2:fieldname`.\n *\n * ```\n * const data_sources = new LocusZoom.DataSources();\n * data_sources.add(\"trait1\", [\"AssociationLZ\", {url: \"http://server.com/api/single/\", params: {source: 1}}]);\n * data_sources.add(\"trait2\", [\"AssociationLZ\", {url: \"http://server.com/api/single/\", params: {source: 2}}]);\n * ```\n *\n * These data sources are then passed to the plot when data is to be rendered:\n * `const plot = LocusZoom.populate(\"#lz-plot\", data_sources, layout);`\n *\n * @module LocusZoom_Adapters\n */\n\nfunction validateBuildSource(class_name, build, source) {\n // Build OR Source, not both\n if ((build && source) || !(build || source)) {\n throw new Error(`${class_name} must provide a parameter specifying either \"build\" or \"source\". It should not specify both.`);\n }\n // If the build isn't recognized, our APIs can't transparently select a source to match\n if (build && !['GRCh37', 'GRCh38'].includes(build)) {\n throw new Error(`${class_name} must specify a valid genome build number`);\n }\n}\n\n\n// NOTE: Custom adapaters are annotated with `see` instead of `extend` throughout this file, to avoid clutter in the developer API docs.\n// Most people using LZ data sources will never instantiate a class directly and certainly won't be calling internal\n// methods, except when implementing a subclass. For most LZ users, it's usually enough to acknowledge that the\n// private API methods exist in the base class.\n\n/**\n * Base class for LocusZoom data sources (any). See also: BaseApiAdapter for requests from a remote URL.\n * @public\n */\nclass BaseAdapter {\n /**\n * @param {object} config Configuration options\n */\n constructor(config) {\n /**\n * Whether to enable caching (true for most data adapters)\n * @private\n * @member {Boolean}\n */\n this._enableCache = true;\n this._cachedKey = null;\n\n // Almost all LZ sources are \"region based\". Cache the region requested and use it to determine whether\n // the cache would satisfy the request.\n this._cache_pos_start = null;\n this._cache_pos_end = null;\n\n /**\n * Whether this adapter type is dependent on previous requests- for example, the LD source cannot annotate\n * association data if no data was found for that region.\n * @private\n * @member {boolean}\n */\n this.__dependentSource = false;\n\n // Parse configuration options\n this.parseInit(config);\n }\n\n /**\n * Parse configuration used to create the instance. Many custom sources will override this method to suit their\n * needs (eg specific config options, or for sources that do not retrieve data from a URL)\n * @protected\n * @param {String|Object} config Basic configuration- either a url, or a config object\n * @param {String} [config.url] The datasource URL\n * @param {String} [config.params] Initial config params for the datasource\n */\n parseInit(config) {\n /**\n * @private\n * @member {Object}\n */\n this.params = config.params || {};\n }\n\n /**\n * A unique identifier that indicates whether cached data is valid for this request. For most sources using GET\n * requests to a REST API, this is usually the region requested. Some sources will append additional params to define the request.\n *\n * This means that to change caching behavior, both the URL and the cache key may need to be updated. However,\n * it allows most datasources to skip an extra network request when zooming in.\n * @protected\n * @param {Object} state Information available in plot.state (chr, start, end). Sometimes used to inject globally\n * available information that influences the request being made.\n * @param {Object} chain The data chain from previous requests made in a sequence.\n * @param fields\n * @returns {String}\n */\n getCacheKey(state, chain, fields) {\n // Most region sources, by default, will cache the largest region that satisfies the request: zooming in\n // should be satisfied via the cache, but pan or region change operations will cause a network request\n\n // Some adapters rely on values set in chain.header during the getURL call. (eg, the LD source uses\n // this to find the LD refvar) Calling this method is a backwards-compatible way of ensuring that value is set,\n // even on a cache hit in which getURL otherwise wouldn't be called.\n // Some of the adapters that rely on this behavior are user-defined, hence compatibility hack\n this.getURL(state, chain, fields);\n\n const cache_pos_chr = state.chr;\n const {_cache_pos_start, _cache_pos_end} = this;\n if (_cache_pos_start && state.start >= _cache_pos_start && _cache_pos_end && state.end <= _cache_pos_end ) {\n return `${cache_pos_chr}_${_cache_pos_start}_${_cache_pos_end}`;\n } else {\n return `${state.chr}_${state.start}_${state.end}`;\n }\n }\n\n /**\n * Stub: build the URL for any requests made by this source.\n * @protected\n */\n getURL(state, chain, fields) {\n return this.url;\n }\n\n /**\n * Perform a network request to fetch data for this source. This is usually the method that is used to override\n * when defining how to retrieve data.\n * @protected\n * @param {Object} state The state of the parent plot\n * @param chain\n * @param fields\n * @returns {Promise}\n */\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n return fetch(url).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n /**\n * Gets the data for just this source, typically via a network request (but using cache where possible)\n *\n * For most use cases, it is better to override `fetchRequest` instead, to avoid bypassing the cache mechanism\n * by accident.\n * @protected\n * @return {Promise}\n */\n getRequest(state, chain, fields) {\n let req;\n const cacheKey = this.getCacheKey(state, chain, fields);\n\n if (this._enableCache && typeof(cacheKey) !== 'undefined' && cacheKey === this._cachedKey) {\n req = Promise.resolve(this._cachedResponse); // Resolve to the value of the current promise\n } else {\n req = this.fetchRequest(state, chain, fields);\n if (this._enableCache) {\n this._cachedKey = cacheKey;\n this._cache_pos_start = state.start;\n this._cache_pos_end = state.end;\n this._cachedResponse = req;\n }\n }\n return req;\n }\n\n /**\n * Ensure the server response is in a canonical form, an array of one object per record. [ {field: oneval} ].\n * If the server response contains columns, reformats the response from {column1: [], column2: []} to the above.\n *\n * Does not apply namespacing, transformations, or field extraction.\n *\n * May be overridden by data adapters that inherently return more complex payloads, or that exist to annotate other\n * sources (eg, if the payload provides extra data rather than a series of records).\n * @protected\n * @param {Object[]|Object} data The original parsed server response\n */\n normalizeResponse(data) {\n if (Array.isArray(data)) {\n // Already in the desired form\n return data;\n }\n // Otherwise, assume the server response is an object representing columns of data.\n // Each array should have the same length (verify), and a given array index corresponds to a single row.\n const keys = Object.keys(data);\n const N = data[keys[0]].length;\n const sameLength = keys.every(function (key) {\n const item = data[key];\n return item.length === N;\n });\n if (!sameLength) {\n throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);\n }\n\n // Go down the rows, and create an object for each record\n const records = [];\n const fields = Object.keys(data);\n for (let i = 0; i < N; i++) {\n const record = {};\n for (let j = 0; j < fields.length; j++) {\n record[fields[j]] = data[fields[j]][i];\n }\n records.push(record);\n }\n return records;\n }\n\n /**\n * Hook to post-process the data returned by this source with new, additional behavior.\n * (eg cleaning up API values or performing complex calculations on the returned data)\n *\n * @protected\n * @param {Object[]} records The parsed data from the source (eg standardized api response)\n * @param {Object} chain The data chain object. For example, chain.headers may provide useful annotation metadata\n * @returns {Object[]|Promise} The modified set of records\n */\n annotateData(records, chain) {\n // Default behavior: no transformations\n return records;\n }\n\n /**\n * Clean up the server records for use by datalayers: extract only certain fields, with the specified names.\n * Apply per-field transformations as appropriate.\n *\n * This hook can be overridden, eg to create a source that always returns all records and ignores the \"fields\" array.\n * This is particularly common for sources at the end of a chain- many \"dependent\" sources do not allow\n * cherry-picking individual fields, in which case by **convention** the fields array specifies \"last_source_name:all\"\n *\n * @protected\n * @param {Object[]} data One record object per element\n * @param {String[]} fields The names of fields to extract (as named in the source data). Eg \"afield\"\n * @param {String[]} outnames How to represent the source fields in the output. Eg \"namespace:afield|atransform\"\n * @param {function[]} trans An array of transformation functions (if any). One function per data element, or null.\n * @protected\n */\n extractFields (data, fields, outnames, trans) {\n //intended for an array of objects\n // [ {\"id\":1, \"val\":5}, {\"id\":2, \"val\":10}]\n // Since a number of sources exist that do not obey this format, we will provide a convenient pass-through\n if (!Array.isArray(data)) {\n return data;\n }\n\n if (!data.length) {\n // Sometimes there are regions that just don't have data- this should not trigger a missing field error message!\n return data;\n }\n\n const fieldFound = [];\n for (let k = 0; k < fields.length; k++) {\n fieldFound[k] = 0;\n }\n\n const records = data.map(function (item) {\n const output_record = {};\n for (let j = 0; j < fields.length; j++) {\n let val = item[fields[j]];\n if (typeof val != 'undefined') {\n fieldFound[j] = 1;\n }\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n output_record[outnames[j]] = val;\n }\n return output_record;\n });\n fieldFound.forEach(function(v, i) {\n if (!v) {\n throw new Error(`field ${fields[i]} not found in response for ${outnames[i]}`);\n }\n });\n return records;\n }\n\n /**\n * Combine records from this source with others in the chain to yield final chain body.\n * Handles merging this data with other sources (if applicable).\n *\n * @protected\n * @param {Object[]} data The data That would be returned from this source alone\n * @param {Object} chain The data chain built up during previous requests\n * @param {String[]} fields\n * @param {String[]} outnames\n * @param {String[]} trans\n * @return {Promise|Object[]} The new chain body\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n return data;\n }\n\n /**\n * Coordinates the work of parsing a response and returning records. This is broken into 4 steps, which may be\n * overridden separately for fine-grained control. Each step can return either raw data or a promise.\n *\n * @see {module:LocusZoom_Adapters~BaseAdapter#normalizeResponse}\n * @see {module:LocusZoom_Adapters~BaseAdapter#annotateData}\n * @see {module:LocusZoom_Adapters~BaseAdapter#extractFields}\n * @see {module:LocusZoom_Adapters~BaseAdapter#combineChainBody}\n * @protected\n *\n * @param {String|Object} resp The raw data associated with the response\n * @param {Object} chain The combined parsed response data from this and all other requests made in the chain\n * @param {String[]} fields Array of requested field names (as they would appear in the response payload)\n * @param {String[]} outnames Array of field names as they will be represented in the data returned by this source,\n * including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {Promise} A promise that resolves to an object containing\n * request metadata (`headers: {}`), the consolidated data for plotting (`body: []`), and the individual responses that would be\n * returned by each source in the chain in isolation (`discrete: {}`)\n */\n parseResponse (resp, chain, fields, outnames, trans) {\n const source_id = this.source_id || this.constructor.name;\n if (!chain.discrete) {\n chain.discrete = {};\n }\n\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n\n // Perform the 4 steps of parsing the payload and return a combined chain object\n return Promise.resolve(this.normalizeResponse(json.data || json))\n .then((standardized) => {\n // Perform calculations on the data from just this source\n return Promise.resolve(this.annotateData(standardized, chain));\n }).then((data) => {\n return Promise.resolve(this.extractFields(data, fields, outnames, trans));\n }).then((one_source_body) => {\n // Store a copy of the data that would be returned by parsing this source in isolation (and taking the\n // fields array into account). This is useful when we want to re-use the source output in many ways.\n chain.discrete[source_id] = one_source_body;\n return Promise.resolve(this.combineChainBody(one_source_body, chain, fields, outnames, trans));\n }).then((new_body) => {\n return { header: chain.header || {}, discrete: chain.discrete, body: new_body };\n });\n }\n\n /**\n * Fetch the data from the specified data adapter, and apply transformations requested by an external consumer.\n * This is the public-facing datasource method that will most be called by the plot, but custom data adapters will\n * almost never want to override this method directly- more specific hooks are provided to control individual pieces\n * of the request lifecycle.\n *\n * @private\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields Array of field names that the plot has requested from this data adapter. (without the \"namespace\" prefix)\n * @param {String[]} outnames Array describing how the output data should refer to this field. This represents the\n * originally requested field name, including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {function} A callable operation that can be used as part of the data chain\n */\n getData(state, fields, outnames, trans) {\n if (this.preGetData) { // TODO try to remove this method if at all possible\n const pre = this.preGetData(state, fields, outnames, trans);\n if (this.pre) {\n state = pre.state || state;\n fields = pre.fields || fields;\n outnames = pre.outnames || outnames;\n trans = pre.trans || trans;\n }\n }\n\n return (chain) => {\n if (this.__dependentSource && chain && chain.body && !chain.body.length) {\n // A \"dependent\" source should not attempt to fire a request if there is no data for it to act on.\n // Therefore, it should simply return the previous data chain.\n return Promise.resolve(chain);\n }\n\n return this.getRequest(state, chain, fields).then((resp) => {\n return this.parseResponse(resp, chain, fields, outnames, trans);\n });\n };\n }\n}\n\n/**\n * Base class for LocusZoom data adapters that receive their data over the web. Adds default config parameters\n * (and potentially other behavior) that are relevant to URL-based requests.\n * @extends module:LocusZoom_Adapters~BaseAdapter\n * @param {string} config.url The URL for the remote dataset. By default, most adapters perform a GET request.\n * @inheritDoc\n */\nclass BaseApiAdapter extends BaseAdapter {\n parseInit(config) {\n super.parseInit(config);\n\n /**\n * @private\n * @member {String}\n */\n this.url = config.url;\n if (!this.url) {\n throw new Error('Source not initialized with required URL');\n }\n }\n}\n\n/**\n * Retrieve Association Data from the LocusZoom/ Portaldev API (or compatible). Defines how to make a request\n * to a specific REST API.\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data.\n * @param {object} config.params\n * @param [config.params.sort=false] Whether to sort the association data (by an assumed field named \"position\"). This\n * is primarily a site-specific workaround for a particular LZ usage; we encourage apis to sort by position before returning\n * data to the browser.\n * @param [config.params.source] The ID of the GWAS dataset to use for this request, as matching the API backend\n */\nclass AssociationLZ extends BaseApiAdapter {\n preGetData (state, fields, outnames, trans) {\n // TODO: Modify internals to see if we can go without this method\n const id_field = this.params.id_field || 'id';\n [id_field, 'position'].forEach(function(x) {\n if (!fields.includes(x)) {\n fields.unshift(x);\n outnames.unshift(x);\n trans.unshift(null);\n }\n });\n return {fields: fields, outnames:outnames, trans:trans};\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL (state, chain, fields) {\n const analysis = chain.header.analysis || this.params.source || this.params.analysis; // Old usages called this param \"analysis\"\n if (typeof analysis == 'undefined') {\n throw new Error('Association source must specify an analysis ID to plot');\n }\n return `${this.url}results/?filter=analysis in ${analysis} and chromosome in '${state.chr}' and position ge ${state.start} and position le ${state.end}`;\n }\n\n /**\n * Some association sources do not sort their data in a predictable order, which makes it hard to reliably\n * align with other sources (such as LD). For performance reasons, sorting is an opt-in argument.\n * TODO: Consider more fine grained sorting control in the future. This was added as a very specific\n * workaround for the original T2D portal.\n * @protected\n * @param data\n * @return {Object}\n */\n normalizeResponse (data) {\n data = super.normalizeResponse(data);\n if (this.params && this.params.sort && data.length && data[0]['position']) {\n data.sort(function (a, b) {\n return a['position'] - b['position'];\n });\n }\n return data;\n }\n}\n\n/**\n * Fetch linkage disequilibrium information from a UMich LDServer-compatible API, relative to a reference variant.\n * If no `plot.state.ldrefvar` is explicitly provided, this source will attempt to find the most significant GWAS\n * variant (smallest pvalue or largest neg_log_pvalue) and yse that as the LD reference variant.\n *\n * This source is designed to connect its results to association data, and therefore depends on association data having\n * been loaded by a previous request in the data chain. For custom association APIs, some additional options might\n * need to be be specified in order to locate the most significant SNP. Variant IDs of the form `chrom:pos_ref/alt`\n * are preferred, but this source will attempt to harmonize other common data formats into something that the LD\n * server can understand.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass LDServer extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param {object} config.params\n * @param [config.params.build='GRCh37'] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param [config.params.source='1000G'] The name of the reference panel to use, as specified in the LD server instance.\n * May be overridden by a global parameter `plot.state.ld_source` to implement widgets that alter LD display.\n * @param [config.params.population='ALL'] The sample population used to calculate LD for a specified source;\n * population names vary depending on the reference panel and how the server was populated wth data.\n * May be overridden by a global parameter `plot.state.ld_pop` to implement widgets that alter LD display.\n * @param [config.params.method='rsquare'] The metric used to calculate LD\n * @param [config.params.id_field] The association data field that contains variant identifier information. The preferred\n * format of LD server is `chrom:pos_ref/alt` and this source will attempt to normalize other common formats.\n * This source can auto-detect possible matches for field names containing \"variant\" or \"id\"\n * @param [config.params.position_field] The association data field that contains variant position information.\n * This source can auto-detect possible matches for field names containing \"position\" or \"pos\"\n * @param [config.params.pvalue_field] The association data field that contains pvalue information.\n * This source can auto-detect possible matches for field names containing \"pvalue\" or \"log_pvalue\".\n * The suggested LD refvar will be the smallest pvalue, or the largest log_pvalue: this source will auto-detect\n * the word \"log\" in order to determine the sign of the comparison.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n preGetData(state, fields) {\n if (fields.length > 1) {\n if (fields.length !== 2 || !fields.includes('isrefvar')) {\n throw new Error(`LD does not know how to get all fields: ${fields.join(', ')}`);\n }\n }\n }\n\n findMergeFields(chain) {\n // Find the fields (as provided by a previous step in the chain, like an association source) that will be needed to\n // combine LD data with existing information\n\n // Since LD information may be shared across multiple assoc sources with different namespaces,\n // we use regex to find columns to join on, rather than requiring exact matches\n const exactMatch = function (arr) {\n return function () {\n const regexes = arguments;\n for (let i = 0; i < regexes.length; i++) {\n const regex = regexes[i];\n const m = arr.filter(function (x) {\n return x.match(regex);\n });\n if (m.length) {\n return m[0];\n }\n }\n return null;\n };\n };\n let dataFields = {\n id: this.params.id_field,\n position: this.params.position_field,\n pvalue: this.params.pvalue_field,\n _names_:null,\n };\n if (chain && chain.body && chain.body.length > 0) {\n const names = Object.keys(chain.body[0]);\n const nameMatch = exactMatch(names);\n // Internally, fields are generally prefixed with the name of the source they come from.\n // If the user provides an id_field (like `variant`), it should work across data sources (`assoc1:variant`,\n // assoc2:variant), but not match fragments of other field names (assoc1:variant_thing)\n // Note: these lookups hard-code a couple of common fields that will work based on known APIs in the wild\n const id_match = dataFields.id && nameMatch(new RegExp(`${dataFields.id}\\\\b`));\n dataFields.id = id_match || nameMatch(/\\bvariant\\b/) || nameMatch(/\\bid\\b/);\n dataFields.position = dataFields.position || nameMatch(/\\bposition\\b/i, /\\bpos\\b/i);\n dataFields.pvalue = dataFields.pvalue || nameMatch(/\\bpvalue\\b/i, /\\blog_pvalue\\b/i);\n dataFields._names_ = names;\n }\n return dataFields;\n }\n\n findRequestedFields (fields, outnames) {\n // Assumption: all usages of this source will only ever ask for \"isrefvar\" or \"state\". This maps to output names.\n let obj = {};\n for (let i = 0; i < fields.length; i++) {\n if (fields[i] === 'isrefvar') {\n obj.isrefvarin = fields[i];\n obj.isrefvarout = outnames && outnames[i];\n } else {\n obj.ldin = fields[i];\n obj.ldout = outnames && outnames[i];\n }\n }\n return obj;\n }\n\n /**\n * The LD API payload does not obey standard format conventions; do not try to transform it.\n */\n normalizeResponse (data) {\n return data;\n }\n\n /**\n * Get the LD reference variant, which by default will be the most significant hit in the assoc results\n * This will be used in making the original query to the LD server for pairwise LD information.\n *\n * This is meant to join a single LD request to any number of association results, and to work with many kinds of API.\n * To do this, the datasource looks for fields with special known names such as pvalue, log_pvalue, etc.\n * If your API uses different nomenclature, an option must be specified.\n *\n * @protected\n * @returns {String[]} Two strings: 1) the marker id (expected to be in `chr:pos_ref/alt` format) of the reference\n * variant, and 2) the marker ID as it appears in the original dataset that we are joining to, so that the exact\n * refvar can be marked when plotting the data..\n */\n getRefvar(state, chain, fields) {\n let findExtremeValue = function(records, pval_field) {\n // Finds the most significant hit (smallest pvalue, or largest -log10p). Will try to auto-detect the appropriate comparison.\n pval_field = pval_field || 'log_pvalue'; // The official LZ API returns log_pvalue\n const is_log = /log/.test(pval_field);\n let cmp;\n if (is_log) {\n cmp = function(a, b) {\n return a > b;\n };\n } else {\n cmp = function(a, b) {\n return a < b;\n };\n }\n let extremeVal = records[0][pval_field], extremeIdx = 0;\n for (let i = 1; i < records.length; i++) {\n if (cmp(records[i][pval_field], extremeVal)) {\n extremeVal = records[i][pval_field];\n extremeIdx = i;\n }\n }\n return extremeIdx;\n };\n\n let reqFields = this.findRequestedFields(fields);\n let refVar = reqFields.ldin;\n if (refVar === 'state') {\n refVar = state.ldrefvar || chain.header.ldrefvar || 'best';\n }\n if (refVar === 'best') {\n if (!chain.body) {\n throw new Error('No association data found to find best pvalue');\n }\n let keys = this.findMergeFields(chain);\n if (!keys.pvalue || !keys.id) {\n let columns = '';\n if (!keys.id) {\n columns += `${columns.length ? ', ' : ''}id`;\n }\n if (!keys.pvalue) {\n columns += `${columns.length ? ', ' : ''}pvalue`;\n }\n throw new Error(`Unable to find necessary column(s) for merge: ${columns} (available: ${keys._names_})`);\n }\n refVar = chain.body[findExtremeValue(chain.body, keys.pvalue)][keys.id];\n }\n // Some datasets, notably the Portal, use a different marker format.\n // Coerce it into one that will work with the LDServer API. (CHROM:POS_REF/ALT)\n const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n const match = refVar && refVar.match(REGEX_MARKER);\n\n if (!match) {\n throw new Error('Could not request LD for a missing or incomplete marker format');\n }\n const [original, chrom, pos, ref, alt] = match;\n // Currently, the LD server only accepts full variant specs; it won't return LD w/o ref+alt. Allowing\n // a partial match at most leaves room for potential future features.\n let refVar_formatted = `${chrom}:${pos}`;\n if (ref && alt) {\n refVar_formatted += `_${ref}/${alt}`;\n }\n\n return [refVar_formatted, original];\n }\n\n /**\n * Identify (or guess) the LD reference variant, then add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n // The LD source/pop can be overridden from plot.state for dynamic layouts\n const build = state.genome_build || this.params.build || 'GRCh37'; // This isn't expected to change after the data is plotted.\n let source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const method = this.params.method || 'rsquare';\n\n if (source === '1000G' && build === 'GRCh38') {\n // For build 38 (only), there is a newer/improved 1000G LD panel available that uses WGS data. Auto upgrade by default.\n source = '1000G-FRZ09';\n }\n\n validateBuildSource(this.constructor.name, build, null); // LD doesn't need to validate `source` option\n\n const [refVar_formatted, refVar_raw] = this.getRefvar(state, chain, fields);\n\n // Preserve the user-provided variant spec for use when matching to assoc data\n chain.header.ldrefvar = refVar_raw;\n\n return [\n this.url, 'genome_builds/', build, '/references/', source, '/populations/', population, '/variants',\n '?correlation=', method,\n '&variant=', encodeURIComponent(refVar_formatted),\n '&chrom=', encodeURIComponent(state.chr),\n '&start=', encodeURIComponent(state.start),\n '&stop=', encodeURIComponent(state.end),\n ].join('');\n }\n\n /**\n * The LD adapter caches based on region, reference panel, and population name\n * @param state\n * @param chain\n * @param fields\n * @return {string}\n */\n getCacheKey(state, chain, fields) {\n const base = super.getCacheKey(state, chain, fields);\n let source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const [refVar, _] = this.getRefvar(state, chain, fields);\n return `${base}_${refVar}_${source}_${population}`;\n }\n\n /**\n * The LD adapter attempts to intelligently match retrieved LD information to a request for association data earlier in the data chain.\n * Since each layer only asks for the data needed for that layer, one LD call is sufficient to annotate many separate association tracks.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n let keys = this.findMergeFields(chain);\n let reqFields = this.findRequestedFields(fields, outnames);\n if (!keys.position) {\n throw new Error(`Unable to find position field for merge: ${keys._names_}`);\n }\n const leftJoin = function (left, right, lfield, rfield) {\n let i = 0, j = 0;\n while (i < left.length && j < right.position2.length) {\n if (left[i][keys.position] === right.position2[j]) {\n left[i][lfield] = right[rfield][j];\n i++;\n j++;\n } else if (left[i][keys.position] < right.position2[j]) {\n i++;\n } else {\n j++;\n }\n }\n };\n const tagRefVariant = function (data, refvar, idfield, outrefname, outldname) {\n for (let i = 0; i < data.length; i++) {\n if (data[i][idfield] && data[i][idfield] === refvar) {\n data[i][outrefname] = 1;\n data[i][outldname] = 1; // For label/filter purposes, implicitly mark the ref var as LD=1 to itself\n } else {\n data[i][outrefname] = 0;\n }\n }\n };\n\n // LD servers vary slightly. Some report corr as \"rsquare\", others as \"correlation\"\n let corrField = data.rsquare ? 'rsquare' : 'correlation';\n leftJoin(chain.body, data, reqFields.ldout, corrField);\n if (reqFields.isrefvarin && chain.header.ldrefvar) {\n tagRefVariant(chain.body, chain.header.ldrefvar, keys.id, reqFields.isrefvarout, reqFields.ldout);\n }\n return chain.body;\n }\n\n /**\n * The LDServer API is paginated, but we need all of the data to render a plot. Depaginate and combine where appropriate.\n */\n fetchRequest(state, chain, fields) {\n let url = this.getURL(state, chain, fields);\n let combined = { data: {} };\n let chainRequests = function (url) {\n return fetch(url).then().then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function(payload) {\n payload = JSON.parse(payload);\n Object.keys(payload.data).forEach(function (key) {\n combined.data[key] = (combined.data[key] || []).concat(payload.data[key]);\n });\n if (payload.next) {\n return chainRequests(payload.next);\n }\n return combined;\n });\n };\n return chainRequests(url);\n }\n}\n\n/**\n * Fetch GWAS catalog data for a list of known variants, and align the data with previously fetched association data.\n * There can be more than one claim per variant; this adapter is written to support a visualization in which each\n * association variant is labeled with the single most significant hit in the GWAS catalog. (and enough information to link to the external catalog for more information)\n *\n * Sometimes the GWAS catalog uses rsIDs that could refer to more than one variant (eg multiple alt alleles are\n * possible for the same rsID). To avoid missing possible hits due to ambiguous meaning, we connect the assoc\n * and catalog data via the position field, not the full variant specifier. This source will auto-detect the matching\n * field in association data by looking for the field name `position` or `pos`.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass GwasCatalogLZ extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen catalog. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent EBI GWAS catalog, GRCh37.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n // This is intended to be aligned with another source- we will assume they are always ordered by position, asc\n // (regardless of the actual match field)\n const build = state.genome_build || this.params.build;\n const source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and id eq ${source}`;\n return `${this.url }?format=objects&sort=pos&filter=chrom eq '${state.chr}' and pos ge ${state.start} and pos le ${state.end}${source_query}`;\n }\n\n findMergeFields(records) {\n // Data from previous sources is already namespaced. Find the alignment field by matching.\n const knownFields = Object.keys(records);\n // Note: All API endoints involved only give results for 1 chromosome at a time; match is implied\n const posMatch = knownFields.find(function (item) {\n return item.match(/\\b(position|pos)\\b/i);\n });\n\n if (!posMatch) {\n throw new Error('Could not find data to align with GWAS catalog results');\n }\n return { 'pos': posMatch };\n }\n\n extractFields (data, fields, outnames, trans) {\n // Skip the \"individual field extraction\" step; extraction will be handled when building chain body instead\n return data;\n }\n\n /**\n * Intelligently combine the LD data with the association data used for this data layer. See class description\n * for a summary of how this works.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data.length) {\n return chain.body;\n }\n\n // TODO: Better reuse options in the future. This source is very specifically tied to the UM PortalDev API, where\n // the field name is always \"log_pvalue\". Relatively few sites will write their own gwas-catalog endpoint.\n const decider = 'log_pvalue';\n const decider_out = outnames[fields.indexOf(decider)];\n\n function leftJoin(left, right, fields, outnames, trans) { // Add `fields` from `right` to `left`\n // Add a synthetic, un-namespaced field to all matching records\n const n_matches = left['n_catalog_matches'] || 0;\n left['n_catalog_matches'] = n_matches + 1;\n if (decider && left[decider_out] && left[decider_out] > right[decider]) {\n // There may be more than one GWAS catalog entry for the same SNP. This source is intended for a 1:1\n // annotation scenario, so for now it only joins the catalog entry that has the best -log10 pvalue\n return;\n }\n\n for (let j = 0; j < fields.length; j++) {\n const fn = fields[j];\n const outn = outnames[j];\n\n let val = right[fn];\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n left[outn] = val;\n }\n }\n\n const chainNames = this.findMergeFields(chain.body[0]);\n const catNames = this.findMergeFields(data[0]);\n\n var i = 0, j = 0;\n while (i < chain.body.length && j < data.length) {\n var left = chain.body[i];\n var right = data[j];\n\n if (left[chainNames.pos] === right[catNames.pos]) {\n // There may be multiple catalog entries for each matching SNP; evaluate match one at a time\n leftJoin(left, right, fields, outnames, trans);\n j += 1;\n } else if (left[chainNames.pos] < right[catNames.pos]) {\n i += 1;\n } else {\n j += 1;\n }\n }\n return chain.body;\n }\n}\n\n/**\n * Retrieve Gene Data, as fetched from the LocusZoom/Portaldev API server (or compatible format)\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen gene dataset. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent GENCODE data, GRCh37.\n */\nclass GeneLZ extends BaseApiAdapter {\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and source in ${source}`;\n return `${this.url}?filter=chrom eq '${state.chr}' and start le ${state.end} and end ge ${state.start}${source_query}`;\n }\n\n /**\n * The UM genes API has a very complex internal data format. Bypass any record parsing, and provide the data layer with\n * the exact information returned by the API. (ignoring the fields array in the layout)\n * @param data\n * @return {Object[]|Object}\n */\n normalizeResponse(data) {\n return data;\n }\n\n /**\n * Does not attempt to namespace or modify the fields from the API payload; the payload format is very complex and\n * quite coupled with the data rendering implementation.\n * Typically, requests to this adapter specify a single dummy field sufficient to trigger the request: `fields:[ 'gene:all' ]`\n */\n extractFields(data, fields, outnames, trans) {\n return data;\n }\n}\n\n/**\n * Retrieve Gene Constraint Data, as fetched from the gnomAD server (or compatible graphQL api endpoint)\n *\n * This is intended to be the second request in a chain, with special logic that connects it to Genes data\n * already fetched. It assumes that the genes data is returned from the UM API, and thus the logic involves\n * matching on specific assumptions about `gene_name` format.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass GeneConstraintLZ extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n /**\n * GraphQL API: request details are encoded in the body, not the URL\n */\n getURL() {\n return this.url;\n }\n\n /**\n * The gnomAD API has a very complex internal data format. Bypass any record parsing, and provide the data layer with\n * the exact information returned by the API.\n */\n normalizeResponse(data) {\n return data;\n }\n\n fetchRequest(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n if (!build) {\n throw new Error(`Adapter ${this.constructor.name} must specify a 'genome_build' option`);\n }\n\n const unique_gene_names = chain.body.reduce(\n // In rare cases, the same gene symbol may appear at multiple positions. (issue #179) We de-duplicate the\n // gene names to avoid issuing a malformed GraphQL query.\n function (acc, gene) {\n acc[gene.gene_name] = null;\n return acc;\n },\n {}\n );\n let query = Object.keys(unique_gene_names).map(function (gene_name) {\n // GraphQL alias names must match a specific set of allowed characters: https://stackoverflow.com/a/45757065/1422268\n const alias = `_${gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`;\n // Each gene symbol is a separate graphQL query, grouped into one request using aliases\n return `${alias}: gene(gene_symbol: \"${gene_name}\", reference_genome: ${build}) { gnomad_constraint { exp_syn obs_syn syn_z oe_syn oe_syn_lower oe_syn_upper exp_mis obs_mis mis_z oe_mis oe_mis_lower oe_mis_upper exp_lof obs_lof pLI oe_lof oe_lof_lower oe_lof_upper } } `;\n });\n\n if (!query.length || query.length > 25 || build === 'GRCh38') {\n // Skip the API request when it would make no sense:\n // - Build 38 (gnomAD supports build GRCh37 only; don't hit server when invalid. This isn't future proof, but we try to be good neighbors.)\n // - Too many genes (gnomAD appears max cost ~25 genes)\n // - No genes in region (hence no constraint info)\n return Promise.resolve({ data: null });\n }\n\n query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas\n const url = this.getURL(state, chain, fields);\n // See: https://graphql.org/learn/serving-over-http/\n const body = JSON.stringify({ query: query });\n const headers = { 'Content-Type': 'application/json' };\n\n // Note: The gnomAD API sometimes fails randomly.\n // If request blocked, return a fake \"no data\" signal so the genes track can still render w/o constraint info\n return fetch(url, { method: 'POST', body, headers }).then((response) => {\n if (!response.ok) {\n return [];\n }\n return response.text();\n }).catch((err) => []);\n }\n\n /**\n * Annotate GENCODE data (from a previous request to the genes adapter) with additional gene constraint data from\n * the gnomAD API. See class description for a summary of how this works.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data) {\n return chain;\n }\n\n chain.body.forEach(function(gene) {\n // Find payload keys that match gene names in this response\n const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names\n const constraint = data[alias] && data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene\n if (constraint) {\n // Add all fields from constraint data- do not override fields present in the gene source\n Object.keys(constraint).forEach(function (key) {\n let val = constraint[key];\n if (typeof gene[key] === 'undefined') {\n if (typeof val == 'number' && val.toString().includes('.')) {\n val = parseFloat(val.toFixed(2));\n }\n gene[key] = val; // These two sources are both designed to bypass namespacing\n }\n });\n }\n });\n return chain.body;\n }\n}\n\n/**\n * Retrieve Recombination Rate Data, as fetched from the LocusZoom API server (or compatible)\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen dataset. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent HAPMAP recombination rate, GRCh37.\n */\nclass RecombLZ extends BaseApiAdapter {\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.SOURCE_NAME, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and id in ${source}`;\n return `${this.url}?filter=chromosome eq '${state.chr}' and position le ${state.end} and position ge ${state.start}${source_query}`;\n }\n}\n\n/**\n * Retrieve static blobs of data as raw JS objects. This does not perform additional parsing, which is required\n * for some sources (eg it does not know how to join together LD and association data).\n *\n * Therefore it is the responsibility of the user to pass information in a format that can be read and\n * understood by the chosen plot- a StaticJSON source is rarely a drop-in replacement for existing layouts.\n *\n * This source is largely here for legacy reasons. More often, a convenient way to serve static data is as separate\n * JSON files to an existing source (with the JSON url in place of an API).\n *\n * Note: The name is a bit misleading. It receives JS objects, not strings serialized as \"json\".\n * @public\n * @see module:LocusZoom_Adapters~BaseAdapter\n * @param {object} data The data to be returned by this source (subject to namespacing rules)\n */\nclass StaticSource extends BaseAdapter {\n parseInit(data) {\n // Does not receive any config; the only argument is the raw data, embedded when source is created\n this._data = data;\n }\n\n getRequest(state, chain, fields) {\n return Promise.resolve(this._data);\n }\n}\n\n/**\n * Retrieve PheWAS data retrieved from a LocusZoom/PortalDev compatible API\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param {String[]} config.params.build This datasource expects to be provided the name of the genome build that will\n * be used to provide pheWAS results for this position. Note positions may not translate between builds.\n */\nclass PheWASLZ extends BaseApiAdapter {\n getURL(state, chain, fields) {\n const build = (state.genome_build ? [state.genome_build] : null) || this.params.build;\n if (!build || !Array.isArray(build) || !build.length) {\n throw new Error(['Adapter', this.constructor.SOURCE_NAME, 'requires that you specify array of one or more desired genome build names'].join(' '));\n }\n const url = [\n this.url,\n \"?filter=variant eq '\", encodeURIComponent(state.variant), \"'&format=objects&\",\n build.map(function (item) {\n return `build=${encodeURIComponent(item)}`;\n }).join('&'),\n ];\n return url.join('');\n }\n\n getCacheKey(state, chain, fields) {\n // This is not a region-based source; it doesn't make sense to cache by a region\n return this.getURL(state, chain, fields);\n }\n}\n\n/**\n * Base class for \"connectors\"- this is a highly specialized kind of adapter that is rarely used in most LocusZoom\n * deployments. This is meant to be subclassed, rather than used directly.\n *\n * A connector is a data adapter that makes no server requests and caches no data of its own. Instead, it decides how to\n * combine data from other sources in the chain. Connectors are useful when we want to request (or calculate) some\n * useful piece of information once, but apply it to many different kinds of record types.\n *\n * Typically, a subclass will implement the field merging logic in `combineChainBody`.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseAdapter\n */\nclass ConnectorSource extends BaseAdapter {\n /**\n * @param {Object} config.params Additional parameters\n * @param {Object} config.params.sources Specify how the hard-coded logic should find the data it relies on in the chain,\n * as {internal_name: chain_source_id} pairs. This allows writing a reusable connector that does not need to make\n * assumptions about what namespaces a source is using. *\n */\n constructor(config) {\n super(config);\n\n if (!config || !config.sources) {\n throw new Error('Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs');\n }\n\n /**\n * Tells the connector how to find the data it relies on\n *\n * For example, a connector that applies burden test information to the genes layer might specify:\n * {gene_ns: \"gene\", aggregation_ns: \"aggregation\"}\n *\n * @member {Object}\n * @private\n */\n this._source_name_mapping = config.sources;\n\n // Validate that this source has been told how to find the required information\n const specified_ids = Object.keys(config.sources);\n /** @property {String[]} Specifies the sources that must be provided in the original config object */\n\n this._getRequiredSources().forEach((k) => {\n if (!specified_ids.includes(k)) {\n // TODO: Fix constructor.name usage in minified bundles\n throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${k}`);\n }\n });\n }\n\n // Stub- connectors don't have their own url or data, so the defaults don't make sense\n parseInit() {}\n\n getRequest(state, chain, fields) {\n // Connectors do not request their own data by definition, but they *do* depend on other sources having been loaded\n // first. This method performs basic validation, and preserves the accumulated body from the chain so far.\n Object.keys(this._source_name_mapping).forEach((ns) => {\n const chain_source_id = this._source_name_mapping[ns];\n if (chain.discrete && !chain.discrete[chain_source_id]) {\n throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${chain_source_id}`);\n }\n });\n return Promise.resolve(chain.body || []);\n }\n\n parseResponse(data, chain, fields, outnames, trans) {\n // A connector source does not update chain.discrete, but it may use it. It bypasses data formatting\n // and field selection (both are assumed to have been done already, by the previous sources this draws from)\n\n // Because of how the chain works, connectors are not very good at applying new transformations or namespacing.\n // Typically connectors are called with `connector_name:all` in the fields array.\n return Promise.resolve(this.combineChainBody(data, chain, fields, outnames, trans))\n .then(function(new_body) {\n return {header: chain.header || {}, discrete: chain.discrete || {}, body: new_body};\n });\n }\n\n combineChainBody(records, chain) {\n // Stub method: specifies how to combine the data\n throw new Error('This method must be implemented in a subclass');\n }\n\n /**\n * Helper method since ES6 doesn't support class fields\n * @private\n */\n _getRequiredSources() {\n throw new Error('Must specify an array that identifes the kind of data required by this source');\n }\n}\n\nexport { BaseAdapter, BaseApiAdapter };\n\nexport {\n AssociationLZ,\n ConnectorSource,\n GeneConstraintLZ,\n GeneLZ,\n GwasCatalogLZ,\n LDServer,\n PheWASLZ,\n RecombLZ,\n StaticSource,\n};\n","/**\n * A registry of known data adapters. Can be used to find adapters by name. It will search predefined classes\n * as well as those registered by plugins.\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\n\nimport * as adapters from '../data/adapters';\n\n\n// LocusZoom.Adapters is a basic registry with no special behavior.\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data adapters (responsible for\n * controlling the retrieval and harmonization of data).\n * @alias module:LocusZoom~Adapters\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(adapters)) {\n registry.add(name, type);\n}\n\n// Add some hard-coded aliases for backwards compatibility\n\n/**\n * Backwards-compatible alias for StaticSource\n * @public\n * @name module:LocusZoom_Adapters~StaticJSON\n * @see module:LocusZoom_Adapters~StaticSource\n */\nregistry.add('StaticJSON', adapters.StaticSource);\n\n/**\n * Backwards-compatible alias for LDServer\n * @public\n * @name module:LocusZoom_Adapters~LDLZ2\n * @see module:LocusZoom_Adapters~LDServer\n */\nregistry.add('LDLZ2', adapters.LDServer);\n\n\nexport default registry;\n","const __WEBPACK_NAMESPACE_OBJECT__ = d3;","/**\n * Available statuses that individual elements can have. Each status is described by\n * a verb and an adjective. Verbs are used to generate data layer\n * methods for updating the status on one or more elements. Adjectives are used in class\n * names and applied or removed from elements to have a visual representation of the status,\n * as well as used as keys in the state for tracking which elements are in which status(es)\n * @static\n * @type {{verbs: String[], adjectives: String[]}}\n * @private\n */\nexport const STATUSES = {\n verbs: ['highlight', 'select', 'fade', 'hide'],\n adjectives: ['highlighted', 'selected', 'faded', 'hidden'],\n};\n","/**\n * Transformation functions: used to transform a raw data value. For example, a template or axis label\n * can convert from pvalue to -log10pvalue by specifying the following field name (the `|funcname` syntax\n * indicates applying a function):\n *\n * `{{assoc:pvalue|neglog10}}`\n *\n * Transforms can also be chained so that several are used in order from left to right:\n * `{{log_pvalue|logtoscinotation|htmlescape}}`\n *\n * Most parts of LocusZoom that rely on being given a field name (or value) can be used this way: axis labels, position,\n * match/filter logic, tooltip HTML template, etc. If your use case is not working with filters, please file a\n * bug report!\n *\n * NOTE: for best results, don't specify filters in the `fields` array of a data layer- only specify them where the\n * transformed value will be used.\n * @module LocusZoom_TransformationFunctions\n */\n\n/**\n * Return the log10 of a value. Can be applied several times in a row for, eg, loglog plots.\n * @param {number} value\n * @return {null|number}\n */\nexport function log10 (value) {\n if (isNaN(value) || value <= 0) {\n return null;\n }\n return Math.log(value) / Math.LN10;\n}\n\n/**\n * Return the -log (base 10), a common means of representing pvalues in locuszoom plots\n * @param {number} value\n * @return {number}\n */\nexport function neglog10 (value) {\n if (isNaN(value) || value <= 0) {\n return null;\n }\n return -Math.log(value) / Math.LN10;\n}\n\n/**\n * Convert a number from logarithm to scientific notation. Useful for, eg, a datasource that returns -log(p) by default\n * @param {number} value\n * @return {string}\n */\nexport function logtoscinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '1';\n }\n const exp = Math.ceil(value);\n const diff = exp - value;\n const base = Math.pow(10, diff);\n if (exp === 1) {\n return (base / 10).toFixed(4);\n } else if (exp === 2) {\n return (base / 100).toFixed(3);\n } else {\n return `${base.toFixed(2)} × 10^-${exp}`;\n }\n}\n\n/**\n * Represent a number in scientific notation\n * @param {Number} value\n * @returns {String}\n */\nexport function scinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '0';\n }\n\n const abs = Math.abs(value);\n let log;\n if (abs > 1) {\n log = Math.ceil(Math.log(abs) / Math.LN10);\n } else { // 0...1\n log = Math.floor(Math.log(abs) / Math.LN10);\n }\n if (Math.abs(log) <= 3) {\n return value.toFixed(3);\n } else {\n return value.toExponential(2).replace('+', '').replace('e', ' × 10^');\n }\n}\n\n/**\n * HTML-escape user entered values for use in constructed HTML fragments\n *\n * For example, this filter can be used on tooltips with custom HTML display. This protects against some forms of\n * XSS injection when plotting user-provided data, as well as display artifacts from field values with HTML symbols\n * such as `<` or `>`.\n * @param {String} value HTML-escape the provided value\n * @return {string}\n */\nexport function htmlescape (value) {\n if (!value) {\n return '';\n }\n value = `${value}`;\n\n return value.replace(/['\"<>&`]/g, function (s) {\n switch (s) {\n case \"'\":\n return ''';\n case '\"':\n return '"';\n case '<':\n return '<';\n case '>':\n return '>';\n case '&':\n return '&';\n case '`':\n return '`';\n }\n });\n}\n\n/**\n * Return true if the value is numeric (including 0)\n *\n * This is useful in template code, where we might wish to hide a field that is absent, but show numeric values even if they are 0\n * Eg, `{{#if value|is_numeric}}...{{/if}}\n *\n * @param {Number} value\n * @return {boolean}\n */\nexport function is_numeric(value) {\n return typeof value === 'number';\n}\n\n/**\n * URL-encode the provided text, eg for constructing hyperlinks\n * @param {String} value\n * @return {string}\n */\nexport function urlencode (value) {\n return encodeURIComponent(value);\n}\n","import {RegistryBase} from './base';\nimport * as transforms from '../helpers/transforms';\n\n/**\n * Registry of transformation functions that may be applied to template values to control how values are rendered.\n * Provides syntactic sugar atop a standard registry.\n * @public\n * @extends module:registry/base:RegistryBase\n * @inheritDoc\n */\nclass TransformationFunctionsRegistry extends RegistryBase {\n /**\n * Helper function that turns a sequence of function names into a single callable\n * @param template_string\n * @return {function(*=): *}\n * @private\n */\n _collectTransforms(template_string) {\n const funcs = template_string\n .match(/\\|([^|]+)/g)\n .map((item) => super.get(item.substring(1)));\n\n return (value) => {\n return funcs.reduce(\n (acc, func) => func(acc),\n value\n );\n };\n }\n\n /**\n * In templates, we often use a single concatenated string to ask for several transformation functions at once:\n * `value|func1|func2`\n * This class offers syntactical sugar to retrieve the entire sequence of transformations as a single callable\n * @param name\n */\n get(name) {\n if (!name) {\n // This function is sometimes called with no value, and the expected behavior is to return null instead of\n // a callable\n return null;\n }\n if (name.substring(0, 1) === '|') {\n // Legacy artifact of how this function is called- if a pipe is present, this is the template string\n // (`|func1|func2...`), rather than any one single transformation function.\n // A sequence of transformation functions is expected\n return this._collectTransforms(name);\n } else {\n // If not a template string, then user is asking for an item by name directly\n return super.get(name);\n }\n }\n}\n\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided transformation functions, which\n * can be used to modify a value in the input data in a predefined way. For example, these can be used to let APIs\n * that return p_values work with plots that display -log10(p)\n * @alias module:LocusZoom~TransformationFunctions\n * @type {TransformationFunctionsRegistry}\n */\nconst registry = new TransformationFunctionsRegistry();\nfor (let [name, type] of Object.entries(transforms)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n// Export helper class for unit testing\nexport { TransformationFunctionsRegistry as _TransformationFunctions };\n","import transforms from '../registry/transforms';\n\n/**\n * Represents an addressable unit of data from a namespaced datasource, subject to specified value transformations.\n *\n * When used by a data layer, fields will automatically be re-fetched from the appropriate data source whenever the\n * state of a plot fetches, eg pan or zoom operations that would affect what data is displayed.\n *\n * @private\n * @class\n * @param {String} field A string representing the namespace of the datasource, the name of the desired field to fetch\n * from that datasource, and arbitrarily many transformations to apply to the value. The namespace and\n * transformation(s) are optional and information is delimited according to the general syntax\n * `[namespace:]name[|transformation][|transformation]`. For example, `association:pvalue|neglog10`\n */\nclass Field {\n constructor(field) {\n const parts = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/.exec(field);\n /** @member {String} */\n this.full_name = field;\n /** @member {String} */\n this.namespace = parts[1] || null;\n /** @member {String} */\n this.name = parts[2] || null;\n /** @member {Array} */\n this.transformations = [];\n\n if (typeof parts[3] == 'string' && parts[3].length > 1) {\n this.transformations = parts[3].substring(1).split('|');\n this.transformations.forEach((transform, i) => this.transformations[i] = transforms.get(transform));\n }\n }\n\n _applyTransformations(val) {\n this.transformations.forEach(function(transform) {\n val = transform(val);\n });\n return val;\n }\n\n /**\n * Resolve the field for a given data element.\n * First look for a full match with transformations already applied by the data requester.\n * Otherwise prefer a namespace match and fall back to just a name match, applying transformations on the fly.\n * @param {Object} data Returned data/fields into for this element\n * @param {Object} [extra] User-applied annotations for this point (info not provided by the server that we want\n * to preserve across re-renders). Example usage: \"should_show_label\"\n * @returns {*}\n */\n resolve(data, extra) {\n if (typeof data[this.full_name] == 'undefined') { // Check for cached result\n let val = null;\n if (typeof (data[`${this.namespace}:${this.name}`]) != 'undefined') { // Fallback: value sans transforms\n val = data[`${this.namespace}:${this.name}`];\n } else if (typeof data[this.name] != 'undefined') { // Fallback: value present without namespace\n val = data[this.name];\n } else if (extra && typeof extra[this.full_name] != 'undefined') { // Fallback: check annotations\n val = extra[this.full_name];\n } // We should really warn if no value found, but many bad layouts exist and this could break compatibility\n data[this.full_name] = this._applyTransformations(val);\n }\n return data[this.full_name];\n }\n}\n\nexport {Field as default};\n","/**\n * Simplified JSONPath implementation\n *\n * This is designed to make it easier to modify part of a LocusZoom layout, using a syntax based on intent\n * (\"modify association panels\") rather than hard-coded assumptions (\"modify the first button, and gosh I hope the order doesn't change\")\n *\n * This DOES NOT support the full JSONPath specification. Notable limitations:\n * - Arrays can only be indexed by filter expression, not by number (can't ask for \"array item 1\")\n * - Filter expressions support only exact match, `field === value`. There is no support for \"and\" statements or\n * arbitrary JS expressions beyond a single exact comparison. (the parser may be improved in the future if use cases emerge)\n *\n * @module\n * @private\n */\n\nconst ATTR_REGEX = /^(\\*|[\\w]+)/; // attribute names can be wildcard or valid variable names\nconst EXPR_REGEX = /^\\[\\?\\(@((?:\\.[\\w]+)+) *===? *([0-9.eE-]+|\"[^\"]*\"|'[^']*')\\)\\]/; // Arrays can be indexed using filter expressions like `[?(@.id === value)]` where value is a number or a single-or-double quoted string\n\nfunction get_next_token(q) {\n // This just grabs everything that looks good.\n // The caller should check that the remaining query is valid.\n if (q.substr(0, 2) === '..') {\n if (q[2] === '[') {\n return {\n text: '..',\n attr: '*',\n depth: '..',\n };\n }\n const m = ATTR_REGEX.exec(q.substr(2));\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as dotdot_attr.`;\n }\n return {\n text: `..${m[0]}`,\n attr: m[1],\n depth: '..',\n };\n } else if (q[0] === '.') {\n const m = ATTR_REGEX.exec(q.substr(1));\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as dot_attr.`;\n }\n return {\n text: `.${m[0]}`,\n attr: m[1],\n depth: '.',\n };\n } else if (q[0] === '[') {\n const m = EXPR_REGEX.exec(q);\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as expr.`;\n }\n let value;\n try {\n // Parse strings and numbers\n value = JSON.parse(m[2]);\n } catch (e) {\n // Handle single-quoted strings\n value = JSON.parse(m[2].replace(/^'|'$/g, '\"'));\n }\n\n return {\n text: m[0],\n attrs: m[1].substr(1).split('.'),\n value,\n };\n } else {\n throw `The query ${JSON.stringify(q)} doesn't look valid.`;\n }\n}\n\nfunction normalize_query(q) {\n // Normalize the start of the query so that it's just a bunch of selectors one-after-another.\n // Otherwise the first selector is a little different than the others.\n if (!q) {\n return '';\n }\n if (!['$', '['].includes(q[0])) {\n q = `$.${ q}`;\n } // It starts with a dotless attr, so prepend the implied `$.`.\n if (q[0] === '$') {\n q = q.substr(1);\n } // strip the leading $\n return q;\n}\n\nfunction tokenize (q) {\n q = normalize_query(q);\n let selectors = [];\n while (q.length) {\n const selector = get_next_token(q);\n q = q.substr(selector.text.length);\n selectors.push(selector);\n }\n return selectors;\n}\n\n/**\n * Fetch the attribute from a dotted path inside a nested object, eg `extract_path({k:['a','b']}, ['k', 1])` would retrieve `'b'`\n *\n * This function returns a three item array `[parent, key, object]`. This is done to support mutating the value, which requires access to the parent.\n *\n * @param obj\n * @param path\n * @returns {array}\n */\nfunction get_item_at_deep_path(obj, path) {\n let parent;\n for (let key of path) {\n parent = obj;\n obj = obj[key];\n }\n return [parent, path[path.length - 1], obj];\n}\n\nfunction tokens_to_keys(data, selectors) {\n // Resolve the jsonpath query into full path specifier keys in the object, eg\n // `$..data_layers[?(@.tag === 'association)].color\n // would become\n // [\"panels\", 0, \"data_layers\", 1, \"color\"]\n if (!selectors.length) {\n return [[]];\n }\n const sel = selectors[0];\n const remaining_selectors = selectors.slice(1);\n let paths = [];\n\n if (sel.attr && sel.depth === '.' && sel.attr !== '*') { // .attr\n const d = data[sel.attr];\n if (selectors.length === 1) {\n if (d !== undefined) {\n paths.push([sel.attr]);\n }\n } else {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [sel.attr].concat(p)));\n }\n } else if (sel.attr && sel.depth === '.' && sel.attr === '*') { // .*\n for (let [k, d] of Object.entries(data)) {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n } else if (sel.attr && sel.depth === '..') { // ..\n // If `sel.attr` matches, recurse with that match.\n // And also recurse on every value using unchanged selectors.\n // I bet `..*..*` duplicates results, so don't do it please.\n if (typeof data === 'object' && data !== null) {\n if (sel.attr !== '*' && sel.attr in data) { // Exact match!\n paths.push(...tokens_to_keys(data[sel.attr], remaining_selectors).map((p) => [sel.attr].concat(p)));\n }\n for (let [k, d] of Object.entries(data)) {\n paths.push(...tokens_to_keys(d, selectors).map((p) => [k].concat(p))); // No match, just recurse\n if (sel.attr === '*') { // Wildcard match\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n }\n }\n } else if (sel.attrs) { // [?(@.attr===value)]\n for (let [k, d] of Object.entries(data)) {\n const [_, __, subject] = get_item_at_deep_path(d, sel.attrs);\n if (subject === sel.value) {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n }\n }\n\n const uniqPaths = uniqBy(paths, JSON.stringify); // dedup\n uniqPaths.sort((a, b) => b.length - a.length || JSON.stringify(a).localeCompare(JSON.stringify(b))); // sort longest-to-shortest, breaking ties lexicographically\n return uniqPaths;\n}\n\nfunction uniqBy(arr, key) {\n // Sometimes, the process of resolving paths to selectors returns duplicate results. This returns only the unique paths.\n return [...new Map(arr.map((elem) => [key(elem), elem])).values()];\n}\n\nfunction get_items_from_tokens(data, selectors) {\n let items = [];\n for (let path of tokens_to_keys(data, selectors)) {\n items.push(get_item_at_deep_path(data, path));\n }\n return items;\n}\n\n/**\n * Perform a query, and return the item + its parent context\n * @param data\n * @param query\n * @returns {array}\n * @private\n */\nfunction _query(data, query) {\n const tokens = tokenize(query);\n\n const matches = get_items_from_tokens(data, tokens);\n if (!matches.length) {\n console.warn(`No items matched the specified query: '${query}'`);\n }\n return matches;\n}\n\n/**\n * Fetch the value(s) for each possible match for a given query. Returns only the item values.\n * @param {object} data The data object to query\n * @param {string} query A JSONPath-compliant query string\n * @returns {Array}\n */\nfunction query(data, query) {\n return _query(data, query).map((item) => item[2]);\n}\n\n/**\n * Modify the value(s) for each possible match for a given jsonpath query. Returns the new item values.\n * @param {object} data The data object to query\n * @param {string} query A JSONPath-compliant query string\n * @param {function|*} value_or_callback The new value for the specified field. Mutations will only be applied\n * after the keys are resolved; this prevents infinite recursion, but could invalidate some matches\n * (if the mutation removed the expected key).\n */\nfunction mutate(data, query, value_or_callback) {\n const matches_in_context = _query(data, query);\n return matches_in_context.map(([parent, key, old_value]) => {\n const new_value = (typeof value_or_callback === 'function') ? value_or_callback(old_value) : value_or_callback;\n parent[key] = new_value;\n return new_value;\n });\n}\n\nexport {mutate, query};\n","/**\n * Utilities for modifying or working with layout objects\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport {mutate, query} from './jsonpath';\n\nconst sqrt3 = Math.sqrt(3);\n// D3 v5 does not provide a triangle down symbol shape, but it is very useful for showing direction of effect.\n// Modified from https://github.com/d3/d3-shape/blob/master/src/symbol/triangle.js\nconst triangledown = {\n draw(context, size) {\n const y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, -y * 2);\n context.lineTo(-sqrt3 * y, y);\n context.lineTo(sqrt3 * y, y);\n context.closePath();\n },\n};\n\n/**\n * Apply namespaces to layout, recursively\n * @private\n */\nfunction applyNamespaces(element, namespace, default_namespace) {\n if (namespace) {\n if (typeof namespace == 'string') {\n namespace = { default: namespace };\n }\n } else {\n namespace = { default: '' };\n }\n if (typeof element == 'string') {\n const re = /\\{\\{namespace(\\[[A-Za-z_0-9]+\\]|)\\}\\}/g;\n let match, base, key, resolved_namespace;\n const replace = [];\n while ((match = re.exec(element)) !== null) {\n base = match[0];\n key = match[1].length ? match[1].replace(/(\\[|\\])/g, '') : null;\n resolved_namespace = default_namespace;\n if (namespace != null && typeof namespace == 'object' && typeof namespace[key] != 'undefined') {\n resolved_namespace = namespace[key] + (namespace[key].length ? ':' : '');\n }\n replace.push({ base: base, namespace: resolved_namespace });\n }\n for (let r in replace) {\n element = element.replace(replace[r].base, replace[r].namespace);\n }\n } else if (typeof element == 'object' && element != null) {\n if (typeof element.namespace != 'undefined') {\n const merge_namespace = (typeof element.namespace == 'string') ? { default: element.namespace } : element.namespace;\n namespace = merge(namespace, merge_namespace);\n }\n let namespaced_element, namespaced_property;\n for (let property in element) {\n if (property === 'namespace') {\n continue;\n }\n namespaced_element = applyNamespaces(element[property], namespace, default_namespace);\n namespaced_property = applyNamespaces(property, namespace, default_namespace);\n if (property !== namespaced_property) {\n delete element[property];\n }\n element[namespaced_property] = namespaced_element;\n }\n }\n return element;\n}\n\n/**\n * A helper method used for merging two objects. If a key is present in both, takes the value from the first object.\n * Values from `default_layout` will be cleanly copied over, ensuring no references or shared state.\n *\n * Frequently used for preparing custom layouts. Both objects should be JSON-serializable.\n *\n * @alias LayoutRegistry.merge\n * @param {object} custom_layout An object containing configuration parameters that override or add to defaults\n * @param {object} default_layout An object containing default settings.\n * @returns {object} The custom layout is modified in place and also returned from this method.\n */\nfunction merge(custom_layout, default_layout) {\n if (typeof custom_layout !== 'object' || typeof default_layout !== 'object') {\n throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof custom_layout}, ${typeof default_layout} given`);\n }\n for (let property in default_layout) {\n if (!Object.prototype.hasOwnProperty.call(default_layout, property)) {\n continue;\n }\n // Get types for comparison. Treat nulls in the custom layout as undefined for simplicity.\n // (javascript treats nulls as \"object\" when we just want to overwrite them as if they're undefined)\n // Also separate arrays from objects as a discrete type.\n let custom_type = custom_layout[property] === null ? 'undefined' : typeof custom_layout[property];\n let default_type = typeof default_layout[property];\n if (custom_type === 'object' && Array.isArray(custom_layout[property])) {\n custom_type = 'array';\n }\n if (default_type === 'object' && Array.isArray(default_layout[property])) {\n default_type = 'array';\n }\n // Unsupported property types: throw an exception\n if (custom_type === 'function' || default_type === 'function') {\n throw new Error('LocusZoom.Layouts.merge encountered an unsupported property type');\n }\n // Undefined custom value: pull the default value\n if (custom_type === 'undefined') {\n custom_layout[property] = deepCopy(default_layout[property]);\n continue;\n }\n // Both values are objects: merge recursively\n if (custom_type === 'object' && default_type === 'object') {\n custom_layout[property] = merge(custom_layout[property], default_layout[property]);\n continue;\n }\n }\n return custom_layout;\n}\n\nfunction deepCopy(item) {\n return JSON.parse(JSON.stringify(item));\n}\n\n/**\n * Convert name to symbol\n * Layout objects accept symbol names as strings (circle, triangle, etc). Convert to symbol objects.\n * @return {object|null} An object that implements a draw method (eg d3-shape symbols or extra LZ items)\n */\nfunction nameToSymbol(shape) {\n if (!shape) {\n return null;\n }\n if (shape === 'triangledown') {\n // D3 does not provide this symbol natively\n return triangledown;\n }\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const factory_name = `symbol${shape.charAt(0).toUpperCase() + shape.slice(1)}`;\n return d3[factory_name] || null;\n}\n\n/**\n * A utility helper for customizing one part of a pre-made layout. Whenever a primitive value is found (eg string),\n * replaces *exact match*\n *\n * This method works by comparing whether strings are a match. As a result, the \"old\" and \"new\" names must match\n * whatever namespacing is used in the input layout.\n * Note: this utility *can* replace values with filters, but will not do so by default.\n *\n * @alias LayoutRegistry.renameField\n *\n * @param {object} layout The layout object to be transformed.\n * @param {string} old_name The old field name that will be replaced\n * @param {string} new_name The new field name that will be substituted in\n * @param {boolean} [warn_transforms=true] Sometimes, a field name is used with transforms appended, eg `label|htmlescape`.\n * In some cases a rename could change the meaning of the field, and by default this method will print a warning to\n * the console, encouraging the developer to check the relevant usages. This warning can be silenced via an optional function argument.\n */\nfunction renameField(layout, old_name, new_name, warn_transforms = true) {\n const this_type = typeof layout;\n // Handle nested types by recursion (in which case, `layout` may be something other than an object)\n if (Array.isArray(layout)) {\n return layout.map((item) => renameField(item, old_name, new_name, warn_transforms));\n } else if (this_type === 'object' && layout !== null) {\n return Object.keys(layout).reduce(\n (acc, key) => {\n acc[key] = renameField(layout[key], old_name, new_name, warn_transforms);\n return acc;\n }, {}\n );\n } else if (this_type !== 'string') {\n // Field names are always strings. If the value isn't a string, don't even try to change it.\n return layout;\n } else {\n // If we encounter a field we are trying to rename, then do so!\n // Rules:\n // 1. Try to avoid renaming part of a field, by checking token boundaries (field1 should not rename field1_displayvalue)\n // 2. Warn the user if filter functions are being used with the specified field, so they can audit for changes in meaning\n const escaped = old_name.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n if (warn_transforms) {\n // Warn the user that they might be renaming, eg, `pvalue|neg_log` to `log_pvalue|neg_log`. Let them decide\n // whether the new field name has a meaning that is compatible with the specified transforms.\n const filter_regex = new RegExp(`${escaped}\\\\|\\\\w+`, 'g');\n const filter_matches = (layout.match(filter_regex) || []);\n filter_matches.forEach((match_val) => console.warn(`renameFields is renaming a field that uses transform functions: was '${match_val}' . Verify that these transforms are still appropriate.`));\n }\n\n // Find and replace any substring, so long as it is at the end of a valid token\n const regex = new RegExp(`${escaped}(?!\\\\w+)`, 'g');\n return layout.replace(regex, new_name);\n }\n}\n\n/**\n * Modify any and all attributes at the specified path in the object\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which field(s) to change.\n * The callback will be applied to ALL matching selectors\n * (see Interactivity guide for syntax and limitations)\n * @param {*|function} value_or_callable The new value, or a function that receives the old value and returns a new one\n * @alias LayoutRegistry.mutate_attrs\n */\nfunction mutate_attrs(layout, selector, value_or_callable) {\n return mutate(\n layout,\n selector,\n value_or_callable\n );\n}\n\n/**\n * Query any and all attributes at the specified path in the object.\n * This is mostly only useful for debugging, to verify that a particular selector matches the intended field.\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which values to return. (see Interactivity guide for limits)\n * @alias LayoutRegistry.query_attrs\n */\nfunction query_attrs(layout, selector) {\n return query(layout, selector);\n}\n\nexport { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, renameField };\n","import { TRANSFORMS } from '../registry';\n\n/**\n * The Requester manages fetching of data across multiple data sources. It is used internally by LocusZoom data layers.\n * It passes state information and ensures that data is formatted in the manner expected by the plot.\n *\n * This object is not part of the public interface. It should almost **never** be replaced or modified directly.\n *\n * It is also responsible for constructing a \"chain\" of dependent requests, by requesting each datasource\n * sequentially in the order specified in the datalayer `fields` array. Data sources are only chained within a\n * data layer, and only if that layer requests more than one source of data.\n * @param {DataSources} sources A set of data sources used specifically by this plot instance\n * @private\n */\nclass Requester {\n constructor(sources) {\n this._sources = sources;\n }\n\n __split_requests(fields) {\n // Given a fields array, return an object specifying what datasource names the data layer should make requests\n // to, and how to handle the returned data\n var requests = {};\n // Regular expression finds namespace:field|trans\n var re = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/;\n fields.forEach(function(raw) {\n var parts = re.exec(raw);\n var ns = parts[1] || 'base';\n var field = parts[2];\n var trans = TRANSFORMS.get(parts[3]);\n if (typeof requests[ns] == 'undefined') {\n requests[ns] = {outnames:[], fields:[], trans:[]};\n }\n requests[ns].outnames.push(raw);\n requests[ns].fields.push(field);\n requests[ns].trans.push(trans);\n });\n return requests;\n }\n\n /**\n * Fetch data, and create a chain that only connects two data sources if they depend on each other\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields The list of data fields specified in the `layout` for a specific data layer\n * @returns {Promise}\n */\n getData(state, fields) {\n var requests = this.__split_requests(fields);\n // Create an array of functions that, when called, will trigger the request to the specified datasource\n var request_handles = Object.keys(requests).map((key) => {\n if (!this._sources.get(key)) {\n throw new Error(`Datasource for namespace ${key} not found`);\n }\n return this._sources.get(key).getData(\n state,\n requests[key].fields,\n requests[key].outnames,\n requests[key].trans\n );\n });\n //assume the fields are requested in dependent order\n //TODO: better manage dependencies\n var ret = Promise.resolve({header:{}, body: [], discrete: {}});\n for (var i = 0; i < request_handles.length; i++) {\n // If a single datalayer uses multiple sources, perform the next request when the previous one completes\n ret = ret.then(request_handles[i]);\n }\n return ret;\n }\n}\n\n\nexport default Requester;\n","/**\n * @module\n * @private\n */\n// FIXME: A place for code that used to live under the `LocusZoom` namespace\n// Eventually this should be moved into classes or some other mechanism for code sharing. No external uses should\n// depend on any items in this module.\n\nimport * as d3 from 'd3';\n\n/**\n * Generate a curtain object for a plot, panel, or any other subdivision of a layout\n * The panel curtain, like the plot curtain is an HTML overlay that obscures the entire panel. It can be styled\n * arbitrarily and display arbitrary messages. It is useful for reporting error messages visually to an end user\n * when the error renders the panel unusable.\n * TODO: Improve type doc here\n * @returns {object}\n */\nfunction generateCurtain() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n hide_delay: null,\n\n /**\n * Generate the curtain. Any content (string) argument passed will be displayed in the curtain as raw HTML.\n * CSS (object) can be passed which will apply styles to the curtain and its content.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n show: (content, css) => {\n if (!this.curtain.showing) {\n this.curtain.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-curtain')\n .attr('id', `${this.id}.curtain`);\n this.curtain.content_selector = this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-content');\n this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-dismiss').html('Dismiss')\n .on('click', () => this.curtain.hide());\n this.curtain.showing = true;\n }\n return this.curtain.update(content, css);\n },\n\n /**\n * Update the content and css of the curtain that's currently being shown. This method also adjusts the size\n * and positioning of the curtain to ensure it still covers the entire panel with no overlap.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n update: (content, css) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n clearTimeout(this.curtain.hide_delay);\n // Apply CSS if provided\n if (typeof css == 'object') {\n applyStyles(this.curtain.selector, css);\n }\n // Update size and position\n const page_origin = this._getPageOrigin();\n\n // Panel layouts have a height; plot layouts don't\n const height = this.layout.height || this._total_height;\n this.curtain.selector\n .style('top', `${page_origin.y}px`)\n .style('left', `${page_origin.x}px`)\n .style('width', `${this.parent_plot.layout.width}px`)\n .style('height', `${height}px`);\n this.curtain.content_selector\n .style('max-width', `${this.parent_plot.layout.width - 40}px`)\n .style('max-height', `${height - 40}px`);\n // Apply content if provided\n if (typeof content == 'string') {\n this.curtain.content_selector.html(content);\n }\n return this.curtain;\n },\n\n /**\n * Remove the curtain\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.curtain.hide_delay);\n this.curtain.hide_delay = setTimeout(this.curtain.hide, delay);\n return this.curtain;\n }\n // Remove curtain\n this.curtain.selector.remove();\n this.curtain.selector = null;\n this.curtain.content_selector = null;\n this.curtain.showing = false;\n return this.curtain;\n },\n };\n}\n\n/**\n * Generate a loader object for a plot, panel, or any other subdivision of a layout\n *\n * The panel loader is a small HTML overlay that appears in the lower left corner of the panel. It cannot be styled\n * arbitrarily, but can show a custom message and show a minimalist loading bar that can be updated to specific\n * completion percentages or be animated.\n * TODO Improve type documentation\n * @returns {object}\n */\nfunction generateLoader() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n progress_selector: null,\n cancel_selector: null,\n\n /**\n * Show a loading indicator\n * @param {string} [content='Loading...'] Loading message (displayed as raw HTML)\n */\n show: (content) => {\n // Generate loader\n if (!this.loader.showing) {\n this.loader.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-loader')\n .attr('id', `${this.id}.loader`);\n this.loader.content_selector = this.loader.selector.append('div')\n .attr('class', 'lz-loader-content');\n this.loader.progress_selector = this.loader.selector\n .append('div')\n .attr('class', 'lz-loader-progress-container')\n .append('div')\n .attr('class', 'lz-loader-progress');\n\n this.loader.showing = true;\n if (typeof content == 'undefined') {\n content = 'Loading...';\n }\n }\n return this.loader.update(content);\n },\n\n /**\n * Update the currently displayed loader and ensure the new content is positioned correctly.\n * @param {string} content The text to display (as raw HTML). If not a string, will be ignored.\n * @param {number} [percent] A number from 1-100. If a value is specified, it will stop all animations\n * in progress.\n */\n update: (content, percent) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n clearTimeout(this.loader.hide_delay);\n // Apply content if provided\n if (typeof content == 'string') {\n this.loader.content_selector.html(content);\n }\n // Update size and position\n const padding = 6; // is there a better place to store/define this?\n const page_origin = this._getPageOrigin();\n const loader_boundrect = this.loader.selector.node().getBoundingClientRect();\n this.loader.selector\n .style('top', `${page_origin.y + this.layout.height - loader_boundrect.height - padding}px`)\n .style('left', `${page_origin.x + padding }px`);\n\n // Apply percent if provided\n if (typeof percent == 'number') {\n this.loader.progress_selector\n .style('width', `${Math.min(Math.max(percent, 1), 100)}%`);\n }\n return this.loader;\n },\n\n /**\n * Adds a class to the loading bar that makes it loop infinitely in a loading animation. Useful when exact\n * percent progress is not available.\n */\n animate: () => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', true);\n return this.loader;\n },\n\n /**\n * Sets the loading bar in the loader to percentage width equal to the percent (number) value passed. Percents\n * will automatically be limited to a range of 1 to 100. Will stop all animations in progress.\n */\n setPercentCompleted: (percent) => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', false);\n return this.loader.update(null, percent);\n },\n\n /**\n * Remove the loader\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.loader.hide_delay);\n this.loader.hide_delay = setTimeout(this.loader.hide, delay);\n return this.loader;\n }\n // Remove loader\n this.loader.selector.remove();\n this.loader.selector = null;\n this.loader.content_selector = null;\n this.loader.progress_selector = null;\n this.loader.cancel_selector = null;\n this.loader.showing = false;\n return this.loader;\n },\n };\n}\n\n/**\n * Modern d3 removed the ability to set many styles at once (object syntax). This is a helper so that layouts with\n * config-objects can set styles all at once\n * @private\n * @param {d3.selection} selection\n * @param {Object} styles\n */\nfunction applyStyles(selection, styles) {\n styles = styles || {};\n for (let [prop, value] of Object.entries(styles)) {\n selection.style(prop, value);\n }\n}\n\n/**\n * Prevent a UI function from being called more than once in a given interval. This allows, eg, search boxes to delay\n * expensive operations until the user is done typing\n * @param {function} func The function to debounce. Returns a wrapper.\n * @param {number} delay Time to wait after last call (in ms)\n */\nfunction debounce(func, delay = 500) {\n let timer;\n return () => {\n clearTimeout(timer);\n timer = setTimeout(\n () => func.apply(this, arguments),\n delay\n );\n };\n}\n\nexport { applyStyles, debounce, generateCurtain, generateLoader };\n","/**\n * Interactive toolbar widgets that allow users to control the plot. These can be used to modify element display:\n * adding contextual information, rearranging/removing panels, or toggling between sets of rendering options like\n * different LD populations.\n * @module LocusZoom_Widgets\n */\nimport * as d3 from 'd3';\n\nimport {positionIntToString} from '../../helpers/display';\nimport {applyStyles, debounce} from '../../helpers/common';\nimport {deepCopy} from '../../helpers/layouts';\n\n\n/**\n *\n * A widget is an empty div rendered on a toolbar that can display custom\n * html of user interface elements.\n */\nclass BaseWidget {\n /**\n * @param {('left'|'right')} [layout.position='left'] Whether to float the widget left or right.\n * @param {('start'|'middle'|'end')} [layout.group_position] Buttons can optionally be gathered into a visually\n * distinctive group whose elements are closer together. If a button is identified as the start or end of a group,\n * it will be drawn with rounded corners and an extra margin of spacing from any button not part of the group.\n * For example, the region_nav_plot toolbar is a defined as a group.\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} [layout.color='gray'] Color scheme for the\n * widget. Applies to buttons and menus.\n * @param [layout.style] CSS styles that will be applied to the widget\n * @param {Toolbar} parent The toolbar that contains this widget\n */\n constructor(layout, parent) {\n /** @member {Object} */\n this.layout = layout || {};\n if (!this.layout.color) {\n this.layout.color = 'gray';\n }\n\n /** @member {Toolbar|*} */\n this.parent = parent || null;\n /**\n * Some widgets are attached to a panel, rather than directly to a plot\n * @member {Panel|null}\n */\n this.parent_panel = null;\n /** @member {Plot} */\n this.parent_plot = null;\n /**\n * This is a reference to either the panel or the plot, depending on what the toolbar is\n * tied to. Useful when absolutely positioning toolbar widgets relative to their SVG anchor.\n * @member {Plot|Panel}\n */\n this.parent_svg = null;\n if (this.parent) {\n if (this.parent.type === 'panel') {\n this.parent_panel = this.parent.parent;\n this.parent_plot = this.parent.parent.parent;\n this.parent_svg = this.parent_panel;\n } else {\n this.parent_plot = this.parent.parent;\n this.parent_svg = this.parent_plot;\n }\n }\n /** @member {d3.selection} */\n this.selector = null;\n /**\n * If this is an interactive widget, it will contain a button or menu instance that handles the interactivity.\n * There is a 1-to-1 relationship of toolbar widget to button\n * @member {null|Button}\n */\n this.button = null;\n /**\n * If any single widget is marked persistent, it will bubble up to prevent automatic hide behavior on a\n * widget's parent toolbar. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n if (!this.layout.position) {\n this.layout.position = 'left';\n }\n }\n\n /**\n * Perform all rendering of widget, including toggling visibility to true. Will initialize and create SVG element\n * if necessary, as well as updating with new data and performing layout actions.\n */\n show() {\n if (!this.parent || !this.parent.selector) {\n return;\n }\n if (!this.selector) {\n const group_position = (['start', 'middle', 'end'].includes(this.layout.group_position) ? ` lz-toolbar-group-${this.layout.group_position}` : '');\n this.selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-${this.layout.position}${group_position}`);\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n if (typeof this.initialize == 'function') {\n this.initialize();\n }\n }\n if (this.button && this.button.status === 'highlighted') {\n this.button.menu.show();\n }\n this.selector.style('visibility', 'visible');\n this.update();\n return this.position();\n }\n\n /**\n * Update the toolbar widget with any new data or plot state as appropriate. This method performs all\n * necessary rendering steps.\n */\n update() { /* stub */\n }\n\n /**\n * Place the widget correctly in the plot\n * @returns {BaseWidget}\n */\n position() {\n if (this.button) {\n this.button.menu.position();\n }\n return this;\n }\n\n /**\n * Determine whether the widget should persist (will bubble up to parent toolbar)\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n return !!(this.button && this.button.persist);\n }\n\n /**\n * Toggle visibility to hidden, unless marked as persistent\n * @returns {BaseWidget}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n if (this.button) {\n this.button.menu.hide();\n }\n this.selector.style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove widget and button. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n if (this.button && this.button.menu) {\n this.button.menu.destroy();\n }\n this.selector.remove();\n this.selector = null;\n this.button = null;\n return this;\n }\n}\n\n/**\n * Plots and panels may have a \"toolbar\" element suited for showing HTML widgets that may be interactive.\n * When widgets need to incorporate a generic button, or additionally a button that generates a menu, this\n * class provides much of the necessary framework. This widget is rarely used directly; it is usually used as\n * part of the code for other widgets.\n * @alias module:LocusZoom_Widgets~_Button\n * @param {BaseWidget} parent\n */\nclass Button {\n constructor(parent) {\n if (!(parent instanceof BaseWidget)) {\n throw new Error('Unable to create toolbar widget button, invalid parent');\n }\n /** @member {BaseWidget} */\n this.parent = parent;\n /** @member {Panel} */\n this.parent_panel = this.parent.parent_panel;\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n /** @member {Plot|Panel} */\n this.parent_svg = this.parent.parent_svg;\n\n /** @member {Toolbar|null|*} */\n this.parent_toolbar = this.parent.parent;\n /** @member {d3.selection} */\n this.selector = null;\n\n /**\n * Tag to use for the button (default: a)\n * @member {String}\n */\n this.tag = 'a';\n\n /**\n * HTML for the button to show.\n * @protected\n * @member {String}\n */\n this.html = '';\n\n /**\n * Mouseover title text for the button to show\n * @protected\n * @member {String}\n */\n this.title = '';\n\n /**\n * Color of the button\n * @member {String}\n */\n this.color = 'gray';\n\n /**\n * Hash of arbitrary button styles to apply as {name: value} entries\n * @protected\n * @member {Object}\n */\n this.style = {};\n\n // Permanence\n /**\n * Track internal state on whether to keep showing the button/ menu contents at the moment\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n /**\n * Configuration when defining a button: track whether this widget should be allowed to keep open\n * menu/button contents in response to certain events\n * @protected\n * @member {Boolean}\n */\n this.permanent = false;\n\n /**\n * Button status (highlighted / disabled/ etc)\n * @protected\n * @member {String}\n */\n this.status = '';\n\n /**\n * Button Menu Object\n * The menu is an HTML overlay that can appear below a button. It can contain arbitrary HTML and\n * has logic to be automatically positioned and sized to behave more or less like a dropdown menu.\n * @member {Object}\n */\n this.menu = {\n outer_selector: null,\n inner_selector: null,\n scroll_position: 0,\n hidden: true,\n /**\n * Show the button menu, including setting up any DOM elements needed for first rendering\n */\n show: () => {\n if (!this.menu.outer_selector) {\n this.menu.outer_selector = d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', `lz-toolbar-menu lz-toolbar-menu-${this.color}`)\n .attr('id', `${this.parent_svg.getBaseId()}.toolbar.menu`);\n this.menu.inner_selector = this.menu.outer_selector.append('div')\n .attr('class', 'lz-toolbar-menu-content');\n this.menu.inner_selector.on('scroll', () => {\n this.menu.scroll_position = this.menu.inner_selector.node().scrollTop;\n });\n }\n this.menu.outer_selector.style('visibility', 'visible');\n this.menu.hidden = false;\n return this.menu.update();\n },\n /**\n * Update the rendering of the menu\n */\n update: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.populate(); // This function is stubbed for all buttons by default and custom implemented in widget definition\n if (this.menu.inner_selector) {\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n }\n return this.menu.position();\n },\n position: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n // Unset any explicitly defined outer selector height so that menus dynamically shrink if content is removed\n this.menu.outer_selector.style('height', null);\n const padding = 3;\n const scrollbar_padding = 20;\n const menu_height_padding = 14; // 14: 2x 6px padding, 2x 1px border\n const page_origin = this.parent_svg._getPageOrigin();\n const page_scroll_top = document.documentElement.scrollTop || document.body.scrollTop;\n const container_offset = this.parent_plot.getContainerOffset();\n const toolbar_client_rect = this.parent_toolbar.selector.node().getBoundingClientRect();\n const button_client_rect = this.selector.node().getBoundingClientRect();\n const menu_client_rect = this.menu.outer_selector.node().getBoundingClientRect();\n const total_content_height = this.menu.inner_selector.node().scrollHeight;\n let top;\n let left;\n if (this.parent_toolbar.type === 'panel') {\n top = (page_origin.y + toolbar_client_rect.height + (2 * padding));\n left = Math.max(page_origin.x + this.parent_plot.layout.width - menu_client_rect.width - padding, page_origin.x + padding);\n } else {\n top = button_client_rect.bottom + page_scroll_top + padding - container_offset.top;\n left = Math.max(button_client_rect.left + button_client_rect.width - menu_client_rect.width - container_offset.left, page_origin.x + padding);\n }\n const base_max_width = Math.max(this.parent_plot.layout.width - (2 * padding) - scrollbar_padding, scrollbar_padding);\n const container_max_width = base_max_width;\n const content_max_width = (base_max_width - (4 * padding));\n const base_max_height = Math.max(this.parent_svg.layout.height - (10 * padding) - menu_height_padding, menu_height_padding);\n const height = Math.min(total_content_height + menu_height_padding, base_max_height);\n this.menu.outer_selector\n .style('top', `${top}px`)\n .style('left', `${left}px`)\n .style('max-width', `${container_max_width}px`)\n .style('max-height', `${base_max_height}px`)\n .style('height', `${height}px`);\n this.menu.inner_selector\n .style('max-width', `${content_max_width}px`);\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n return this.menu;\n },\n hide: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.outer_selector.style('visibility', 'hidden');\n this.menu.hidden = true;\n return this.menu;\n },\n destroy: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.inner_selector.remove();\n this.menu.outer_selector.remove();\n this.menu.inner_selector = null;\n this.menu.outer_selector = null;\n return this.menu;\n },\n /**\n * Internal method definition\n * By convention populate() does nothing and should be reimplemented with each toolbar button definition\n * Reimplement by way of Toolbar.BaseWidget.Button.menu.setPopulate to define the populate method and hook\n * up standard menu click-toggle behavior prototype.\n * @protected\n */\n populate: () => {\n throw new Error('Method must be implemented');\n },\n /**\n * Define how the menu is populated with items, and set up click and display properties as appropriate\n * @public\n */\n setPopulate: (menu_populate_function) => {\n if (typeof menu_populate_function == 'function') {\n this.menu.populate = menu_populate_function;\n this.setOnclick(() => {\n if (this.menu.hidden) {\n this.menu.show();\n this.highlight().update();\n this.persist = true;\n } else {\n this.menu.hide();\n this.highlight(false).update();\n if (!this.permanent) {\n this.persist = false;\n }\n }\n });\n } else {\n this.setOnclick();\n }\n return this;\n },\n };\n }\n\n /**\n * Set the color associated with this button\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} color Any selection not in the preset list\n * will be replaced with gray.\n * @returns {Button}\n */\n setColor (color) {\n if (typeof color != 'undefined') {\n if (['gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple'].includes(color)) {\n this.color = color;\n } else {\n this.color = 'gray';\n }\n }\n return this;\n }\n\n /**\n * Allow code to change whether the button is allowed to be `permanent`\n * @param {boolean} bool\n * @returns {Button}\n */\n setPermanent (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n this.permanent = bool;\n if (this.permanent) {\n this.persist = true;\n }\n return this;\n }\n\n /**\n * Determine whether the button/menu contents should persist in response to a specific event\n * @returns {Boolean}\n */\n shouldPersist () {\n return this.permanent || this.persist;\n }\n\n /**\n * Set a collection of custom styles to be used by the button\n * @param {Object} style Hash of {name:value} entries\n * @returns {Button}\n */\n setStyle (style) {\n if (typeof style != 'undefined') {\n this.style = style;\n }\n return this;\n }\n\n /**\n * Method to generate a CSS class string\n * @returns {string}\n */\n getClass () {\n const group_position = (['start', 'middle', 'end'].includes(this.parent.layout.group_position) ? ` lz-toolbar-button-group-${this.parent.layout.group_position}` : '');\n return `lz-toolbar-button lz-toolbar-button-${this.color}${this.status ? `-${this.status}` : ''}${group_position}`;\n }\n\n /**\n * Change button state\n * @param {('highlighted'|'disabled'|'')} status\n */\n setStatus (status) {\n if (typeof status != 'undefined' && ['', 'highlighted', 'disabled'].includes(status)) {\n this.status = status;\n }\n return this.update();\n }\n\n /**\n * Toggle whether the button is highlighted\n * @param {boolean} bool If provided, explicitly set highlighted state\n * @returns {Button}\n */\n highlight (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('highlighted');\n } else if (this.status === 'highlighted') {\n return this.setStatus('');\n }\n return this;\n }\n\n /**\n * Toggle whether the button is disabled\n * @param {boolean} bool If provided, explicitly set disabled state\n * @returns {Button}\n */\n disable (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('disabled');\n } else if (this.status === 'disabled') {\n return this.setStatus('');\n }\n return this;\n }\n\n // Mouse events\n /** @member {function} */\n onmouseover () {\n }\n setOnMouseover (onmouseover) {\n if (typeof onmouseover == 'function') {\n this.onmouseover = onmouseover;\n } else {\n this.onmouseover = function () {};\n }\n return this;\n }\n\n /** @member {function} */\n onmouseout () {\n }\n setOnMouseout (onmouseout) {\n if (typeof onmouseout == 'function') {\n this.onmouseout = onmouseout;\n } else {\n this.onmouseout = function () {};\n }\n return this;\n }\n\n /** @member {function} */\n onclick () {\n }\n setOnclick (onclick) {\n if (typeof onclick == 'function') {\n this.onclick = onclick;\n } else {\n this.onclick = function () {};\n }\n return this;\n }\n\n /**\n * Set the mouseover title text for the button (if any)\n * @param {String} title Simple text to display\n * @returns {Button}\n */\n setTitle(title) {\n if (typeof title != 'undefined') {\n this.title = title.toString();\n }\n return this;\n }\n\n /**\n * Specify the HTML content of this button.\n * WARNING: The string provided will be inserted into the document as raw markup; XSS mitigation is the\n * responsibility of each button implementation.\n * @param {String} html\n * @returns {Button}\n */\n setHtml(html) {\n if (typeof html != 'undefined') {\n this.html = html.toString();\n }\n return this;\n }\n\n // Primary behavior functions\n /**\n * Show the button, including creating DOM elements if necessary for first render\n */\n show () {\n if (!this.parent) {\n return;\n }\n if (!this.selector) {\n this.selector = this.parent.selector.append(this.tag)\n .attr('class', this.getClass());\n }\n return this.update();\n }\n\n /**\n * Hook for any actions or state cleanup to be performed before rerendering\n * @returns {Button}\n */\n preUpdate () {\n return this;\n }\n\n /**\n * Update button state and contents, and fully rerender\n * @returns {Button}\n */\n update () {\n if (!this.selector) {\n return this;\n }\n this.preUpdate();\n this.selector\n .attr('class', this.getClass())\n .attr('title', this.title)\n .on('mouseover', (this.status === 'disabled') ? null : this.onmouseover)\n .on('mouseout', (this.status === 'disabled') ? null : this.onmouseout)\n .on('click', (this.status === 'disabled') ? null : this.onclick)\n .html(this.html)\n .call(applyStyles, this.style);\n\n this.menu.update();\n this.postUpdate();\n return this;\n }\n\n /**\n * Hook for any behavior to be added/changed after the button has been re-rendered\n * @returns {Button}\n */\n postUpdate () {\n return this;\n }\n\n /**\n * Hide the button by removing it from the DOM (may be overridden by current persistence setting)\n * @returns {Button}\n */\n hide() {\n if (this.selector && !this.shouldPersist()) {\n this.selector.remove();\n this.selector = null;\n }\n return this;\n }\n\n}\n\n/**\n * Renders arbitrary text with large title formatting\n * @alias module:LocusZoom_Widgets~title\n * @param {string} layout.title Text or HTML to render\n * @param {string} [layout.subtitle] Small text to render next to the title\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass Title extends BaseWidget {\n show() {\n if (!this.div_selector) {\n this.div_selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-title lz-toolbar-${this.layout.position}`);\n this.title_selector = this.div_selector.append('h3');\n }\n return this.update();\n }\n\n update() {\n let title = this.layout.title.toString();\n if (this.layout.subtitle) {\n title += ` ${this.layout.subtitle}`;\n }\n this.title_selector.html(title);\n return this;\n }\n}\n\n/**\n * Display the current scale of the genome region displayed in the plot, as defined by the difference between\n * `state.end` and `state.start`. Few users are interested in seeing coordinates with this level of precision, but\n * it can be useful for debugging.\n * TODO: It would be nice to move this to an extension, but helper functions drag in large dependencies as a side effect.\n * (we'd need to reorganize internals a bit before moving this widget)\n * @alias module:LocusZoom_Widgets~region_scale\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass RegionScale extends BaseWidget {\n update() {\n if (!isNaN(this.parent_plot.state.start) && !isNaN(this.parent_plot.state.end)\n && this.parent_plot.state.start !== null && this.parent_plot.state.end !== null) {\n this.selector.style('display', null);\n this.selector.html(positionIntToString(this.parent_plot.state.end - this.parent_plot.state.start, null, true));\n } else {\n this.selector.style('display', 'none');\n }\n if (this.layout.class) {\n this.selector.attr('class', this.layout.class);\n }\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n return this;\n }\n}\n\n/**\n * The filter field widget has triggered an update to the plot filtering rules\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_filter_field_action\n * @property {Object} data { field, operator, value, filter_id }\n * @see event:any_lz_event\n */\n\n/**\n * @alias module:LocusZoom_Widgets~filter_field\n */\nclass FilterField extends BaseWidget {\n /**\n * @param {string} layout.layer_name The data layer to control with filtering\n * @param {string} [layout.filter_id = null] Sometimes we want to define more than one filter with the same operator\n * (eg != null, != bacon). The `filter_id` option allows us to identify which filter is controlled by this widget.\n * @param {string} layout.field The field to be filtered (eg `assoc:log_pvalue`)\n * @param {string} layout.field_display_html Human-readable label for the field to be filtered (`-log10p`)\n * @param {string} layout.operator The operator to use when filtering. This must be one of the options allowed by data_layer.filter.\n * @param {number} [layout.input_size=4] How wide to make the input textbox (number characters shown at a time)\n * @param {('number'|'string')} [layout.data_type='number'] Convert the text box input to the specified type, and warn the\n * user if the value would be invalid (eg, not numeric)\n * @param {string} [layout.custom_event_name='widget_filter_field_action'] The name of the event that will be emitted when this filter is updated\n */\n constructor(layout, parent) {\n super(layout, parent);\n\n if (!this.parent_panel) {\n throw new Error('Filter widget can only be used in panel toolbars');\n }\n\n this._data_layer = this.parent_panel.data_layers[layout.layer_name];\n if (!this._data_layer) {\n throw new Error(`Filter widget could not locate the specified layer_name: '${layout.layer_name}'`);\n }\n\n this._event_name = layout.custom_event_name || 'widget_filter_field_action';\n this._field = layout.field;\n this._field_display_html = layout.field_display_html;\n this._operator = layout.operator;\n this._filter_id = null;\n this._data_type = layout.data_type || 'number';\n if (!['number', 'string'].includes(this._data_type)) {\n throw new Error('Filter must be either string or number');\n }\n\n this._value_selector = null;\n }\n\n _getTarget() {\n // Find the specific filter in layer.layout.filters, and if not present, add one\n if (!this._data_layer.layout.filters) {\n this._data_layer.layout.filters = [];\n }\n let result = this._data_layer.layout.filters\n .find((item) => item.field === this._field && item.operator === this._operator && (!this._filter_id || item.id === this._filter_id));\n\n if (!result) {\n result = { field: this._field, operator: this._operator, value: null };\n if (this._filter_id) {\n result['id'] = this._filter_id;\n }\n this._data_layer.layout.filters.push(result);\n }\n return result;\n }\n\n /** Clear the filter by removing it from the list */\n _clearFilter() {\n if (this._data_layer.layout.filters) {\n const index = this._data_layer.layout.filters.indexOf(this._getTarget());\n this._data_layer.layout.filters.splice(index, 1);\n }\n }\n\n /**\n * Set the filter based on a provided value\n * @fires event:widget_filter_field_action\n */\n _setFilter(value) {\n if (value === null) {\n // On blank or invalid value, remove the filter & warn\n this._value_selector\n .style('border', '1px solid red')\n .style('color', 'red');\n this._clearFilter();\n } else {\n const filter = this._getTarget();\n filter.value = value;\n }\n this.parent_svg.emit(this._event_name, { field: this._field, operator: this._operator, value, filter_id: this._filter_id }, true);\n }\n\n /** Get the user-entered value, coercing type if necessary. Returns null for invalid or missing values.\n * @return {null|number|string}\n * @private\n */\n _getValue() {\n let value = this._value_selector.property('value');\n if (value === null || value === '') {\n return null;\n }\n if (this._data_type === 'number') {\n value = +value;\n if (Number.isNaN(value)) {\n return null;\n }\n }\n return value;\n }\n\n update() {\n if (this._value_selector) {\n return;\n }\n this.selector.style('padding', '0 6px');\n\n // Label\n this.selector\n .append('span')\n .html(this._field_display_html)\n .style('background', '#fff')\n .style('padding-left', '3px');\n // Operator label\n this.selector.append('span')\n .text(this._operator)\n .style('padding', '0 3px')\n .style('background', '#fff');\n\n this._value_selector = this.selector\n .append('input')\n .attr('size', this.layout.input_size || 4)\n .on('input', debounce(() => {\n // Clear validation state\n this._value_selector\n .style('border', null)\n .style('color', null);\n const value = this._getValue();\n this._setFilter(value);\n this.parent_panel.render();\n }, 750));\n }\n}\n\n/**\n * The user has asked to download the plot as an SVG image\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_save_svg\n * @property {Object} data { filename }\n * @see event:any_lz_event\n */\n\n/**\n * The user has asked to download the plot as a PNG image\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_save_png\n * @property {Object} data { filename }\n * @see event:any_lz_event\n */\n\n/**\n * Button to export current plot to an SVG image\n * @alias module:LocusZoom_Widgets~download_svg\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DownloadSVG extends BaseWidget {\n /**\n * @param {string} [layout.button_html=\"Download SVG\"]\n * @param {string} [layout.button_title=\"Download hi-res image\"]\n * @param {string} [layout.filename=\"locuszoom.svg\"] The default filename to use when saving the image\n * @param {string} [layout.custom_event_name='widget_save_svg'] The name of the event that will be emitted when the button is clicked\n */\n constructor(layout, parent) {\n super(layout, parent);\n this._filename = this.layout.filename || 'locuszoom.svg';\n this._button_html = this.layout.button_html || 'Save SVG';\n this._button_title = this.layout.button_title || 'Download hi-res image';\n this._event_name = layout.custom_event_name || 'widget_save_svg';\n }\n\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this._button_html)\n .setTitle(this._button_title)\n .setOnMouseover(() => {\n this.button.selector\n .classed('lz-toolbar-button-gray-disabled', true)\n .html('Preparing Image');\n this._getBlobUrl().then((url) => {\n const old = this.button.selector.attr('href');\n if (old) {\n // Clean up old url instance to prevent memory leaks\n URL.revokeObjectURL(old);\n }\n this.button.selector\n .attr('href', url)\n .classed('lz-toolbar-button-gray-disabled', false)\n .classed('lz-toolbar-button-gray-highlighted', true)\n .html(this._button_html);\n });\n })\n .setOnMouseout(() => {\n this.button.selector.classed('lz-toolbar-button-gray-highlighted', false);\n });\n this.button.show();\n this.button.selector\n .attr('href-lang', 'image/svg+xml')\n .attr('download', this._filename)\n .on('click', () => this.parent_svg.emit(this._event_name, { filename: this._filename }, true));\n return this;\n }\n\n /**\n * Extract all CSS rules whose selectors directly reference elements under the root node\n * @param {Element} root\n * @return {string}\n * @private\n */\n _getCSS(root) {\n // Hack: this method is based on text matching the rules on a given node; it doesn't handle, eg ancestors.\n // Since all LZ cssRules are written as \"svg .classname\", we need to strip the parent selector prefix in order\n // to extract CSS.\n const ancestor_pattern = /^svg\\.lz-locuszoom\\s*/;\n\n // Extract all relevant CSS Rules by iterating through all available stylesheets\n let extractedCSSText = '';\n for (let i = 0; i < document.styleSheets.length; i++) {\n const s = document.styleSheets[i];\n try {\n if (!s.cssRules) {\n continue;\n }\n } catch ( e ) {\n if (e.name !== 'SecurityError') {\n throw e;\n } // for Firefox\n continue;\n }\n let cssRules = s.cssRules;\n for (let i = 0; i < cssRules.length; i++) {\n // FIXME: We could write smaller SVGs by extracting only the exact CSS rules for this plot. However,\n // extracting rules (including parent selectors) is a finicky process\n // Instead just fetch all LZ plot rules, under a known hardcoded parent selector.\n const rule = cssRules[i];\n const is_match = (rule.selectorText && rule.selectorText.match(ancestor_pattern));\n if (is_match) {\n extractedCSSText += rule.cssText;\n }\n }\n }\n return extractedCSSText;\n }\n\n _appendCSS( cssText, element ) {\n // Append styles to the constructed SVG DOM node\n var styleElement = document.createElement('style');\n styleElement.setAttribute('type', 'text/css');\n styleElement.innerHTML = cssText;\n var refNode = element.hasChildNodes() ? element.children[0] : null;\n element.insertBefore( styleElement, refNode );\n }\n\n /**\n * Get the target dimensions for the rendered image.\n *\n * For non-vector displays, these dimensions will yield ~300 DPI image for an 8\" wide print figure.\n * @return {number[]}\n * @private\n */\n _getDimensions() {\n let { width, height } = this.parent_plot.svg.node().getBoundingClientRect();\n const target_width = 2400;\n const rescale = target_width / width;\n return [rescale * width, rescale * height];\n }\n\n _generateSVG () {\n return new Promise((resolve) => {\n // Copy the DOM node so that we can modify the image for publication\n let copy = this.parent_plot.svg.node().cloneNode(true);\n copy.setAttribute('xlink', 'http://www.w3.org/1999/xlink');\n copy = d3.select(copy);\n\n // Remove unnecessary elements\n copy.selectAll('g.lz-curtain').remove();\n copy.selectAll('g.lz-mouse_guide').remove();\n // Convert units on axis tick dy attributes from ems to pixels\n copy.selectAll('g.tick text').each(function() {\n const dy = +(d3.select(this).attr('dy').substring(-2).slice(0, -2)) * 10;\n d3.select(this).attr('dy', dy);\n });\n // Pull the svg into a string and add the contents of the locuszoom stylesheet\n // Don't add this with d3 because it will escape the CDATA declaration incorrectly\n const serializer = new XMLSerializer();\n\n copy = copy.node();\n\n // Firefox has issues saving the SVG in certain contexts (esp rendering to canvas) unless a width is given.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=700533\n const [width, height] = this._getDimensions();\n copy.setAttribute('width', width);\n copy.setAttribute('height', height);\n\n // Add CSS to the node\n this._appendCSS(this._getCSS(copy), copy);\n let svg_markup = serializer.serializeToString(copy);\n resolve(svg_markup);\n });\n }\n\n /**\n * Converts the SVG string into a downloadable binary object\n * @return {Promise}\n */\n _getBlobUrl() {\n return this._generateSVG().then((markup) => {\n const blob = new Blob([markup], { type: 'image/svg+xml' });\n return URL.createObjectURL(blob);\n });\n }\n}\n\n/**\n * Button to export current plot to a PNG image\n * @alias module:LocusZoom_Widgets~download_png\n * @extends module:LocusZoom_Widgets~download_svg\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DownloadPNG extends DownloadSVG {\n /**\n * @param {string} [layout.button_html=\"Download PNG\"]\n * @param {string} [layout.button_title=\"Download image\"]\n * @param {string} [layout.filename=\"locuszoom.svg\"] The default filename to use when saving the image\n * @param {string} [layout.custom_event_name='widget_save_png'] The name of the event that will be emitted when the button is clicked\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\n constructor(layout, parent) {\n super(...arguments);\n this._filename = this.layout.filename || 'locuszoom.png';\n this._button_html = this.layout.button_html || 'Save PNG';\n this._button_title = this.layout.button_title || 'Download image';\n this._event_name = layout.custom_event_name || 'widget_save_png';\n }\n\n /**\n * @private\n */\n _getBlobUrl() {\n return super._getBlobUrl().then((svg_url) => {\n const canvas = document.createElement('canvas');\n const context = canvas.getContext('2d');\n\n const [width, height] = this._getDimensions();\n\n canvas.width = width;\n canvas.height = height;\n\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => {\n context.drawImage(image, 0, 0, width, height);\n // Once canvas rendered, revoke svg blob to avoid memory leaks, and create new url for the canvas\n URL.revokeObjectURL(svg_url);\n canvas.toBlob((png) => {\n resolve(URL.createObjectURL(png));\n });\n };\n image.src = svg_url;\n });\n });\n }\n}\n\n/**\n * Button to remove panel from plot.\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~remove_panel\n * @param {Boolean} [layout.suppress_confirm=false] If true, removes the panel without prompting user for confirmation\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass RemovePanel extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('×')\n .setTitle('Remove panel')\n .setOnclick(() => {\n if (!this.layout.suppress_confirm && !confirm('Are you sure you want to remove this panel? This cannot be undone.')) {\n return false;\n }\n const panel = this.parent_panel;\n panel.toolbar.hide(true);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseover.${panel.getBaseId()}.toolbar`, null);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseout.${panel.getBaseId()}.toolbar`, null);\n return panel.parent.removePanel(panel.id);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to move panel up relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~move_panel_up\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass MovePanelUp extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_top = (this.parent_panel.layout.y_index === 0);\n this.button.disable(is_at_top);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▴')\n .setTitle('Move panel up')\n .setOnclick(() => {\n this.parent_panel.moveUp();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to move panel down relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~move_panel_down\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass MovePanelDown extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_bottom = (this.parent_panel.layout.y_index === this.parent_plot.panel_ids_by_y_index.length - 1);\n this.button.disable(is_at_bottom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▾')\n .setTitle('Move panel down')\n .setOnclick(() => {\n this.parent_panel.moveDown();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to shift plot region forwards or back by a `step` increment provided in the layout\n * @alias module:LocusZoom_Widgets~shift_region\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ShiftRegion extends BaseWidget {\n /**\n * @param {number} [layout.step=50000] The stepsize to change the region by\n * @param {string} [layout.button_html] Label\n * @param {string} [layout.button_title] Mouseover text\n */\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 50000;\n }\n if (typeof layout.button_html !== 'string') {\n layout.button_html = layout.step > 0 ? '>' : '<';\n }\n\n if (typeof layout.button_title !== 'string') {\n layout.button_title = `Shift region by ${layout.step > 0 ? '+' : '-'}${positionIntToString(Math.abs(layout.step), null, true)}`;\n }\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add shift_region toolbar widget: plot state does not have region bounds');\n }\n\n\n }\n\n update () {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start + this.layout.step, 1),\n end: this.parent_plot.state.end + this.layout.step,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Zoom in or out on the plot, centered on the middle of the plot region, by the specified amount\n * @alias module:LocusZoom_Widgets~zoom_region\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ZoomRegion extends BaseWidget {\n /**\n * @param {number} [layout.step=0.2] The fraction to zoom in by (where 1 indicates 100%)\n * @param {string} [layout.button_html] Label\n * @param {string} [layout.button_title] Mouseover text\n */\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 0.2;\n }\n if (typeof layout.button_html != 'string') {\n layout.button_html = layout.step > 0 ? 'z–' : 'z+';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = `Zoom region ${layout.step > 0 ? 'out' : 'in'} by ${(Math.abs(layout.step) * 100).toFixed(1)}%`;\n }\n\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add zoom_region toolbar widget: plot state does not have region bounds');\n }\n }\n\n update () {\n if (this.button) {\n let can_zoom = true;\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n if (this.layout.step > 0 && !isNaN(this.parent_plot.layout.max_region_scale) && current_region_scale >= this.parent_plot.layout.max_region_scale) {\n can_zoom = false;\n }\n if (this.layout.step < 0 && !isNaN(this.parent_plot.layout.min_region_scale) && current_region_scale <= this.parent_plot.layout.min_region_scale) {\n can_zoom = false;\n }\n this.button.disable(!can_zoom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n const zoom_factor = 1 + this.layout.step;\n let new_region_scale = current_region_scale * zoom_factor;\n if (!isNaN(this.parent_plot.layout.max_region_scale)) {\n new_region_scale = Math.min(new_region_scale, this.parent_plot.layout.max_region_scale);\n }\n if (!isNaN(this.parent_plot.layout.min_region_scale)) {\n new_region_scale = Math.max(new_region_scale, this.parent_plot.layout.min_region_scale);\n }\n const delta = Math.floor((new_region_scale - current_region_scale) / 2);\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start - delta, 1),\n end: this.parent_plot.state.end + delta,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Renders button with arbitrary text that, when clicked, shows a dropdown containing arbitrary HTML. This is usually\n * used as part of coding a custom button, rather than as a standalone widget.\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @alias module:LocusZoom_Widgets~menu\n * @param {string} layout.button_html The HTML to render inside the button\n * @param {string} layout.button_title Text to display as a tooltip when hovering over the button\n * @param {string} layout.menu_html The HTML content of the dropdown menu\n */\nclass Menu extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title);\n this.button.menu.setPopulate(() => {\n this.button.menu.inner_selector.html(this.layout.menu_html);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to resize panel height to fit available data (eg when showing a list of tracks)\n * @alias module:LocusZoom_Widgets~resize_to_data\n */\nclass ResizeToData extends BaseWidget {\n /**\n * @param {string} [layout.button_html=\"Resize to Data\"]\n * @param {string} [layout.button_title]\n */\n constructor(layout) {\n super(...arguments);\n }\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html || 'Resize to Data')\n .setTitle(this.layout.button_title || 'Automatically resize this panel to show all data available')\n .setOnclick(() => {\n this.parent_panel.scaleHeightToData();\n this.update();\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to toggle legend\n * @alias module:LocusZoom_Widgets~toggle_legend\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ToggleLegend extends BaseWidget {\n update() {\n const html = this.parent_panel.legend.layout.hidden ? 'Show Legend' : 'Hide Legend';\n if (this.button) {\n this.button.setHtml(html).show();\n this.parent.position();\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setTitle('Show or hide the legend for this panel')\n .setOnclick(() => {\n this.parent_panel.legend.layout.hidden = !this.parent_panel.legend.layout.hidden;\n this.parent_panel.legend.render();\n this.update();\n });\n return this.update();\n }\n}\n\n\n/**\n * @typedef {object} DisplayOptionsButtonConfigField\n * @property {string} display_name The human-readable label for this set of options\n * @property {object} display An object with layout directives that will be merged into the target layer.\n * The directives should be among those listed in `fields_whitelist` for this widget.\n */\n\n/**\n * The user has chosen a specific display option to show information on the plot\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_display_options_choice\n * @property {Object} data {choice} The display_name of the item chosen from the list\n * @see event:any_lz_event\n */\n\n/**\n * Dropdown menu allowing the user to choose between different display options for a single specific data layer\n * within a panel.\n *\n * This allows controlling how points on a datalayer can be displayed- any display options supported via the layout for the target datalayer. This includes point\n * size/shape, coloring, etc.\n *\n * This button intentionally limits display options it can control to those available on common plot types.\n * Although the list of options it sets can be overridden (to control very special custom plot types), this\n * capability should be used sparingly if at all.\n * @alias module:LocusZoom_Widgets~display_options\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DisplayOptions extends BaseWidget {\n /**\n * @param {string} layout.layer_name Specify the datalayer that this button should affect\n * @param {String} [layout.button_html=\"Display options...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Control how plot items are displayed\"] Hover text for the toolbar button\n * @param {string} [layout.default_config_display_name] Store the default configuration for this datalayer\n * configuration, and show a button to revert to the \"default\" (listing the human-readable display name provided)\n * @param {Array} [layout.fields_whitelist='see code'] The list of presentation fields that this button can control.\n * This can be overridden if this button needs to be used on a custom layer type with special options.\n * The whitelist is chosen to be things that are known to be easily modified with few side effects.\n * When the button is first created, all fields in the whitelist will have their default values saved, so the user can revert to the default view easily.\n * @param {module:LocusZoom_Widgets~DisplayOptionsButtonConfigField[]} layout.options Specify a label and set of layout directives associated\n * with this `display` option. Display field should include all changes that will be merged to datalayer layout options.\n * @param {string} [layout.custom_event_name='widget_display_options_choice'] The name of the event that will be emitted when an option is selected\n */\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Display options...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Control how plot items are displayed';\n }\n super(...arguments);\n this._event_name = layout.custom_event_name || 'widget_display_options_choice';\n\n // List of layout fields that this button is allowed to control. This ensures that we don't override any other\n // information (like plot height etc) while changing point rendering\n const allowed_fields = layout.fields_whitelist || ['color', 'fill_opacity', 'filters', 'label', 'legend',\n 'point_shape', 'point_size', 'tooltip', 'tooltip_positioning'];\n\n const dataLayer = this.parent_panel.data_layers[layout.layer_name];\n if (!dataLayer) {\n throw new Error(`Display options could not locate the specified layer_name: '${layout.layer_name}'`);\n }\n const dataLayerLayout = dataLayer.layout;\n\n // Store default configuration for the layer as a clean deep copy, so we may revert later\n const defaultConfig = {};\n allowed_fields.forEach((name) => {\n const configSlot = dataLayerLayout[name];\n if (configSlot !== undefined) {\n defaultConfig[name] = deepCopy(configSlot);\n }\n });\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n this._selected_item = 'default';\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html)\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const menuLayout = this.layout;\n\n const renderRow = (display_name, display_options, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `display-option-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (row_id === this._selected_item))\n .on('click', () => {\n // If an option is not specified in these display options, use the original defaults\n allowed_fields.forEach((field_name) => {\n const has_option = typeof display_options[field_name] !== 'undefined';\n dataLayer.layout[field_name] = has_option ? display_options[field_name] : defaultConfig[field_name];\n });\n\n this.parent_svg.emit(this._event_name, { choice: display_name }, true);\n this._selected_item = row_id;\n this.parent_panel.render();\n const legend = this.parent_panel.legend;\n if (legend) {\n legend.render();\n }\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n // Render the \"display options\" menu: default and special custom options\n const defaultName = menuLayout.default_config_display_name || 'Default style';\n renderRow(defaultName, defaultConfig, 'default');\n menuLayout.options.forEach((item, index) => renderRow(item.display_name, item.display, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n/**\n * @typedef {object} SetStateOptionsConfigField\n * @property {string} display_name Human readable name for option label (eg \"European\")\n * @property value Value to set in plot.state (eg \"EUR\")\n */\n\n/**\n * An option has been chosen from the set_state dropdown menu\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_set_state_choice\n * @property {Object} data { choice_name, choice_value, state_field }\n * @see event:any_lz_event\n */\n\n/**\n * Dropdown menu allowing the user to set the value of a specific `state_field` in plot.state\n * This is useful for things (like datasources) that allow dynamic configuration based on global information in state\n *\n * For example, the LDServer data adapter can use it to change LD reference population (for all panels) after render\n *\n * @alias module:LocusZoom_Widgets~set_state\n * @param {String} [layout.button_html=\"Set option...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Choose an option to customize the plot\"] Hover text for the toolbar button\n * @param {bool} [layout.show_selected=false] Whether to append the selected value to the button label (\"LD Population: ALL\")\n * @param {string} [layout.state_field] The name of the field in plot.state that will be set by this button\n * @param {module:LocusZoom_Widgets~SetStateOptionsConfigField[]} layout.options Specify human labels and associated values for the dropdown menu\n * @param {string} [layout.custom_event_name='widget_set_state_choice'] The name of the event that will be emitted when an option is selected\n */\nclass SetState extends BaseWidget {\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Set option...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Choose an option to customize the plot';\n }\n\n super(layout, parent);\n\n if (this.parent_panel) {\n throw new Error('This widget is designed to set global options, so it can only be used at the top (plot) level');\n }\n if (!layout.state_field) {\n throw new Error('Must specify the `state_field` that this widget controls');\n }\n\n this._event_name = layout.custom_event_name || 'widget_set_state_choice';\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n // The first option listed is automatically assumed to be the default, unless a value exists in plot.state\n this._selected_item = this.parent_plot.state[layout.state_field] || layout.options[0].value;\n if (!layout.options.find((item) => {\n return item.value === this._selected_item;\n })) {\n // Check only gets run at widget creation, but generally this widget is assumed to be an exclusive list of options\n throw new Error('There is an existing state value that does not match the known values in this widget');\n }\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''))\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const renderRow = (display_name, value, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `set-state-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (value === this._selected_item))\n .on('click', () => {\n const new_state = {};\n new_state[layout.state_field] = value;\n this._selected_item = value;\n this.parent_plot.applyState(new_state);\n this.button.setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''));\n\n this.parent_svg.emit(this._event_name, { choice_name: display_name, choice_value: value, state_field: layout.state_field }, true);\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n layout.options.forEach((item, index) => renderRow(item.display_name, item.value, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n\nexport {\n BaseWidget, // This is used to create subclasses\n Button as _Button, // This is used to create Widgets that contain a button. It actually shouldn't be in the registry because it's not usable directly..\n DisplayOptions as display_options,\n DownloadSVG as download,\n DownloadPNG as download_png,\n FilterField as filter_field,\n Menu as menu,\n MovePanelDown as move_panel_down,\n MovePanelUp as move_panel_up,\n RegionScale as region_scale,\n ResizeToData as resize_to_data,\n SetState as set_state,\n ShiftRegion as shift_region,\n RemovePanel as remove_panel,\n Title as title,\n ToggleLegend as toggle_legend,\n ZoomRegion as zoom_region,\n};\n","import {ClassRegistry} from './base';\nimport * as widgets from '../components/toolbar/widgets';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided toolbar widgets: interactive buttons\n * and menus that control plot display, modify data, or show additional information as context.\n * @alias module:LocusZoom~Widgets\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(widgets)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","import widgets from '../../registry/widgets';\nimport * as d3 from 'd3';\n\n/**\n * A Toolbar is an HTML element used for presenting arbitrary user interface widgets. Toolbars are anchored\n * to either the entire Plot or to individual Panels.\n *\n * Each toolbar is an HTML-based (read: not SVG) collection of widgets used to display information or provide\n * user interface. Toolbars can exist on entire plots, where their visibility is permanent and vertically adjacent\n * to the plot, or on individual panels, where their visibility is tied to a behavior (e.g. a mouseover) and is as\n * an overlay.\n *\n * This class is used internally for rendering, and is not part of the public interface\n * @private\n */\nclass Toolbar {\n constructor(parent) {\n // parent must be a locuszoom plot or panel\n // if (!(parent instanceof LocusZoom.Plot) && !(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create toolbar, parent must be a locuszoom plot or panel');\n // }\n /** @member {Plot|Panel} */\n this.parent = parent;\n\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.toolbar`;\n\n /** @member {('plot'|'panel')} */\n this.type = (this.parent.parent) ? 'panel' : 'plot';\n\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n\n /** @member {d3.selection} */\n this.selector = null;\n\n /** @member {BaseWidget[]} */\n this.widgets = [];\n\n /**\n * The timer identifier as returned by setTimeout\n * @member {Number}\n */\n this.hide_timeout = null;\n\n /**\n * Whether to hide the toolbar. Can be overridden by a child widget. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n\n this.initialize();\n }\n\n /**\n * Prepare the toolbar for first use: generate all widget instances for this toolbar, based on the provided\n * layout of the parent. Connects event listeners and shows/hides as appropriate.\n * @returns {Toolbar}\n */\n initialize() {\n // Parse layout to generate widget instances\n // In LZ 0.12, `dashboard.components` was renamed to `toolbar.widgets`. Preserve a backwards-compatible alias.\n const options = (this.parent.layout.dashboard && this.parent.layout.dashboard.components) || this.parent.layout.toolbar.widgets;\n if (Array.isArray(options)) {\n options.forEach((layout) => {\n try {\n const widget = widgets.create(layout.type, layout, this);\n this.widgets.push(widget);\n } catch (e) {\n console.warn('Failed to create widget');\n console.error(e);\n }\n });\n }\n\n // Add mouseover event handlers to show/hide panel toolbar\n if (this.type === 'panel') {\n d3.select(this.parent.parent.svg.node().parentNode)\n .on(`mouseover.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n if (!this.selector || this.selector.style('visibility') === 'hidden') {\n this.show();\n }\n }).on(`mouseout.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n this.hide_timeout = setTimeout(() => {\n this.hide();\n }, 300);\n });\n }\n\n return this;\n }\n\n /**\n * Whether to persist the toolbar. Returns true if at least one widget should persist, or if the panel is engaged\n * in an active drag event.\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n let persist = false;\n // Persist if at least one widget should also persist\n this.widgets.forEach((widget) => {\n persist = persist || widget.shouldPersist();\n });\n // Persist if in a parent drag event\n persist = persist || (this.parent_plot.panel_boundaries.dragging || this.parent_plot.interaction.dragging);\n return !!persist;\n }\n\n /**\n * Make the toolbar appear. If it doesn't exist yet create it, including creating/positioning all widgets within,\n * and make sure it is set to be visible.\n */\n show() {\n if (!this.selector) {\n switch (this.type) {\n case 'plot':\n this.selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', ':first-child');\n break;\n case 'panel':\n this.selector = d3.select(this.parent.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip, .lz-toolbar-menu, .lz-curtain').classed('lz-panel-toolbar', true);\n break;\n default:\n throw new Error(`Toolbar cannot be a child of ${this.type}`);\n }\n\n this.selector\n .classed('lz-toolbar', true)\n .classed(`lz-${this.type}-toolbar`, true)\n .attr('id', this.id);\n }\n this.widgets.forEach((widget) => widget.show());\n this.selector.style('visibility', 'visible');\n return this.update();\n }\n\n\n /**\n * Update the toolbar and rerender all child widgets. This can be called whenever plot state changes.\n * @returns {Toolbar}\n */\n update() {\n if (!this.selector) {\n return this;\n }\n this.widgets.forEach((widget) => widget.update());\n return this.position();\n }\n\n\n /**\n * Position the toolbar (and child widgets) within the panel\n * @returns {Toolbar}\n */\n position() {\n if (!this.selector) {\n return this;\n }\n // Position the toolbar itself (panel only)\n if (this.type === 'panel') {\n const page_origin = this.parent._getPageOrigin();\n const top = `${(page_origin.y + 3.5).toString()}px`;\n const left = `${page_origin.x.toString()}px`;\n const width = `${(this.parent_plot.layout.width - 4).toString()}px`;\n this.selector\n .style('position', 'absolute')\n .style('top', top)\n .style('left', left)\n .style('width', width);\n }\n // Recursively position widgets\n this.widgets.forEach((widget) => widget.position());\n return this;\n }\n\n /**\n * Hide the toolbar (make invisible but do not destroy). Will do nothing if `shouldPersist` returns true.\n *\n * @returns {Toolbar}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n this.widgets.forEach((widget) => widget.hide());\n this.selector\n .style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove toolbar and all child widgets. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n this.widgets.forEach((widget) => widget.destroy(true));\n this.widgets = [];\n this.selector.remove();\n this.selector = null;\n return this;\n }\n}\n\n\nexport {Toolbar as default};\n","/**\n * @module\n * @private\n */\nimport * as d3 from 'd3';\nimport {applyStyles} from '../helpers/common';\nimport {merge, nameToSymbol} from '../helpers/layouts';\n\n// FIXME: Document legend options\n/**\n * The default layout used by legends (used internally)\n * @protected\n * @member {Object}\n */\nconst default_layout = {\n orientation: 'vertical',\n origin: { x: 0, y: 0 },\n width: 10,\n height: 10,\n padding: 5,\n label_size: 12,\n hidden: false,\n};\n\n/**\n * An SVG object used to display contextual information about a panel.\n * Panel layouts determine basic features of a legend - its position in the panel, orientation, title, etc.\n * Layouts of child data layers of the panel determine the actual content of the legend.\n *\n * @param {Panel} parent\n*/\nclass Legend {\n constructor(parent) {\n // if (!(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create legend, parent must be a locuszoom panel');\n // }\n /** @member {Panel} */\n this.parent = parent;\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.legend`;\n\n this.parent.layout.legend = merge(this.parent.layout.legend || {}, default_layout);\n /** @member {Object} */\n this.layout = this.parent.layout.legend;\n\n /** @member {d3.selection} */\n this.selector = null;\n /** @member {d3.selection} */\n this.background_rect = null;\n /** @member {d3.selection[]} */\n this.elements = [];\n /**\n * SVG selector for the group containing all elements in the legend\n * @protected\n * @member {d3.selection|null}\n */\n this.elements_group = null;\n\n /**\n * TODO: Not sure if this property is used; the external-facing methods are setting `layout.hidden` instead. Tentatively mark deprecated.\n * @deprecated\n * @protected\n * @member {Boolean}\n */\n this.hidden = false;\n\n return this.render();\n }\n\n /**\n * Render the legend in the parent panel\n */\n render() {\n // Get a legend group selector if not yet defined\n if (!this.selector) {\n this.selector = this.parent.svg.group.append('g')\n .attr('id', `${this.parent.getBaseId()}.legend`).attr('class', 'lz-legend');\n }\n\n // Get a legend background rect selector if not yet defined\n if (!this.background_rect) {\n this.background_rect = this.selector.append('rect')\n .attr('width', 100)\n .attr('height', 100)\n .attr('class', 'lz-legend-background');\n }\n\n // Get a legend elements group selector if not yet defined\n if (!this.elements_group) {\n this.elements_group = this.selector.append('g');\n }\n\n // Remove all elements from the document and re-render from scratch\n this.elements.forEach((element) => element.remove());\n this.elements = [];\n\n // Gather all elements from data layers in order (top to bottom) and render them\n const padding = +this.layout.padding || 1;\n let x = padding;\n let y = padding;\n let line_height = 0;\n this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((id) => {\n if (Array.isArray(this.parent.data_layers[id].layout.legend)) {\n this.parent.data_layers[id].layout.legend.forEach((element) => {\n const selector = this.elements_group.append('g')\n .attr('transform', `translate(${x}, ${y})`);\n const label_size = +element.label_size || +this.layout.label_size || 12;\n let label_x = 0;\n let label_y = (label_size / 2) + (padding / 2);\n line_height = Math.max(line_height, label_size + padding);\n // Draw the legend element symbol (line, rect, shape, etc)\n const shape = element.shape || '';\n const shape_factory = nameToSymbol(shape);\n if (shape === 'line') {\n // Line symbol\n const length = +element.length || 16;\n const path_y = (label_size / 4) + (padding / 2);\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', `M0,${path_y}L${length},${path_y}`)\n .call(applyStyles, element.style || {});\n label_x = length + padding;\n } else if (shape === 'rect') {\n // Rect symbol\n const width = +element.width || 16;\n const height = +element.height || width;\n selector\n .append('rect')\n .attr('class', element.class || '')\n .attr('width', width)\n .attr('height', height)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = width + padding;\n line_height = Math.max(line_height, height + padding);\n } else if (shape_factory) {\n // Shape symbol is a recognized d3 type, so we can draw it in the legend (circle, diamond, etc.)\n const size = +element.size || 40;\n const radius = Math.ceil(Math.sqrt(size / Math.PI));\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', d3.symbol().size(size).type(shape_factory))\n .attr('transform', `translate(${radius}, ${radius + (padding / 2)})`)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = (2 * radius) + padding;\n label_y = Math.max((2 * radius) + (padding / 2), label_y);\n line_height = Math.max(line_height, (2 * radius) + padding);\n }\n // Draw the legend element label\n selector\n .append('text')\n .attr('text-anchor', 'left')\n .attr('class', 'lz-label')\n .attr('x', label_x)\n .attr('y', label_y)\n .style('font-size', label_size)\n .text(element.label);\n\n // Position the legend element group based on legend layout orientation\n const bcr = selector.node().getBoundingClientRect();\n if (this.layout.orientation === 'vertical') {\n y += bcr.height + padding;\n line_height = 0;\n } else {\n // Ensure this element does not exceed the panel width\n // (E.g. drop to the next line if it does, but only if it's not the only element on this line)\n const right_x = this.layout.origin.x + x + bcr.width;\n if (x > padding && right_x > this.parent.parent.layout.width) {\n y += line_height;\n x = padding;\n selector.attr('transform', `translate(${x}, ${y})`);\n }\n x += bcr.width + (3 * padding);\n }\n // Store the element\n this.elements.push(selector);\n });\n }\n });\n\n // Scale the background rect to the elements in the legend\n const bcr = this.elements_group.node().getBoundingClientRect();\n this.layout.width = bcr.width + (2 * this.layout.padding);\n this.layout.height = bcr.height + (2 * this.layout.padding);\n this.background_rect\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n\n // Set the visibility on the legend from the \"hidden\" flag\n // TODO: `show()` and `hide()` call a full rerender; might be able to make this more lightweight?\n this.selector\n .style('visibility', this.layout.hidden ? 'hidden' : 'visible');\n\n return this.position();\n }\n\n /**\n * Place the legend in position relative to the panel, as specified in the layout configuration\n * @returns {Legend | null}\n * TODO: should this always be chainable?\n */\n position() {\n if (!this.selector) {\n return this;\n }\n const bcr = this.selector.node().getBoundingClientRect();\n if (!isNaN(+this.layout.pad_from_bottom)) {\n this.layout.origin.y = this.parent.layout.height - bcr.height - +this.layout.pad_from_bottom;\n }\n if (!isNaN(+this.layout.pad_from_right)) {\n this.layout.origin.x = this.parent.parent.layout.width - bcr.width - +this.layout.pad_from_right;\n }\n this.selector.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n }\n\n /**\n * Hide the legend (triggers a re-render)\n * @public\n */\n hide() {\n this.layout.hidden = true;\n this.render();\n }\n\n /**\n * Show the legend (triggers a re-render)\n * @public\n */\n show() {\n this.layout.hidden = false;\n this.render();\n }\n}\n\nexport {Legend as default};\n","import * as d3 from 'd3';\n\nimport {STATUSES} from './constants';\nimport Toolbar from './toolbar';\nimport {applyStyles, generateCurtain, generateLoader} from '../helpers/common';\nimport {parseFields, positionIntToString, prettyTicks} from '../helpers/display';\nimport {merge} from '../helpers/layouts';\nimport Legend from './legend';\nimport data_layers from '../registry/data_layers';\n\n\n/**\n * Default panel layout\n * @memberof Panel\n * @static\n * @type {Object}\n */\nconst default_layout = {\n id: '',\n tag: 'custom_data_type',\n title: { text: '', style: {}, x: 10, y: 22 },\n y_index: null,\n min_height: 1,\n height: 1,\n origin: { x: 0, y: null },\n margin: { top: 0, right: 0, bottom: 0, left: 0 },\n background_click: 'clear_selections',\n toolbar: {\n widgets: [],\n },\n cliparea: {\n height: 0,\n width: 0,\n origin: { x: 0, y: 0 },\n },\n axes: { // These are the only axes supported!!\n x: {},\n y1: {},\n y2: {},\n },\n legend: null,\n interaction: {\n drag_background_to_pan: false,\n drag_x_ticks_to_scale: false,\n drag_y1_ticks_to_scale: false,\n drag_y2_ticks_to_scale: false,\n scroll_to_zoom: false,\n x_linked: false,\n y1_linked: false,\n y2_linked: false,\n },\n show_loading_indicator: true,\n data_layers: [],\n};\n\n/**\n * A panel is an abstract class representing a subdivision of the LocusZoom stage\n * to display a distinct data representation as a collection of data layers.\n */\nclass Panel {\n /**\n * @param {string} [layout.id=''] An identifier string that must be unique across all panels in the plot\n * @param {string} [layout.tag='custom_data_type'] Tags have no functional purpose, but they can be used\n * as a semantic label for what is being displayed in this element. This makes it easy to write custom code like \"find every panel\n * that shows association scatter plots, anywhere\": even if the IDs are different, the tag can be the same.\n * Most built-in panels will contain a tag that describes, in human-readable terms, what kind of data is being shown.\n * (see: {@link LayoutRegistry.mutate_attrs})\n * @param {boolean} [layout.show_loading_indicator=true] Whether to show a \"loading indicator\" while data is being fetched\n * @param {module:LocusZoom_DataLayers[]} [layout.data_layers] Data layer layout objects\n * @param {module:LocusZoom_Widgets[]} [layout.toolbar.widgets] Configuration options for each toolbar widget; {@link module:LocusZoom_Widgets}\n * @param {number} [layout.title.text] Text to show in panel title\n * @param {number} [layout.title.style] CSS options to apply to the title\n * @param {number} [layout.title.x=10] x-offset for title position\n * @param {number} [layout.title.y=22] y-offset for title position\n * @param {'vertical'|'horizontal'} [layout.legend.orientation='vertical'] Orientation with which elements in the legend should be arranged.\n * Presently only \"vertical\" and \"horizontal\" are supported values. When using the horizontal orientation\n * elements will automatically drop to a new line if the width of the legend would exceed the right edge of the\n * containing panel. Defaults to \"vertical\".\n * @param {number} [layout.legend.origin.x=0] X-offset, in pixels, for the top-left corner of the legend (relative to the top left corner of the panel).\n * @param {number} [layout.legend.origin.y=0] Y-offset, in pixels, for the top-left corner of the legend (relative to the top left corner of the panel).\n * NOTE: SVG y values go from the top down, so the SVG origin of (0,0) is in the top left corner.\n * @param {number} [layout.legend.padding=5] Value in pixels to pad between the legend's outer border and the\n * elements within the legend. This value is also used for spacing between elements in the legend on different\n * lines (e.g. in a vertical orientation) and spacing between element shapes and labels, as well as between\n * elements in a horizontal orientation, are defined as a function of this value. Defaults to 5.\n * @param {number} [layout.legend.label_size=12] Font size for element labels in the legend (loosely analogous to the height of full-height letters, in pixels). Defaults to 12.\n * @param {boolean} [layout.legend.hidden=false] Whether to hide the legend by default\n * @param {number} [layout.y_index] The position of the panel (above or below other panels). This is usually set\n * automatically when the panel is added, and rarely controlled directly.\n * @param {number} [layout.min_height=1] When resizing, do not allow height to go below this value\n * @param {number} [layout.height=1] The actual height allocated to the panel (>= min_height)\n * @param {number} [layout.margin.top=0] The margin (space between top of panel and edge of viewing area)\n * @param {number} [layout.margin.right=0] The margin (space between right side of panel and edge of viewing area)\n * @param {number} [layout.margin.bottom=0] The margin (space between bottom of panel and edge of viewing area)\n * @param {number} [layout.margin.left=0] The margin (space between left side of panel and edge of viewing area)\n * @param {'clear_selections'|null} [layout.background_click='clear_selections'] What happens when the background of the panel is clicked\n * @param {'state'|null} [layout.axes.x.extent] If 'state', the x extent will be determined from plot.state (a\n * shared region). Otherwise it will be determined based on data later ranges.\n * @param {string} [layout.axes.x.label] Label text for the provided axis\n * @param {number} [layout.axes.x.label_offset]\n * @param {boolean} [layout.axes.x.render] Whether to render this axis\n * @param {'region'|null} [layout.axes.x.tick_format] If 'region', format ticks in a concise way suitable for\n * genomic coordinates, eg 23423456 => 23.42 (Mb)\n * @param {Array} [layout.axes.x.ticks] An array of custom ticks that will override any automatically generated)\n * @param {string} [layout.axes.y1.label] Label text for the provided axis\n * @param {number} [layout.axes.y1.label_offset]\n * @param {boolean} [layout.axes.y1.render=false] Whether to render this axis\n * @param {Array} [layout.axes.y1.ticks] An array of custom ticks that will override any automatically generated)\n * @param {string} [layout.axes.y2.label] Label text for the provided axis\n * @param {number} [layout.axes.y2.label_offset]\n * @param {boolean} [layout.axes.y2.render=false] Whether to render this axis\n * @param {Array} [layout.axes.y2.ticks] An array of custom ticks that will override any automatically generated)\n * @param {boolean} [layout.interaction.drag_background_to_pan=false] Allow the user to drag the panel background to pan\n * the plot to another genomic region.\n * @param {boolean} [layout.interaction.drag_x_ticks_to_scale=false] Allow the user to rescale the x axis by dragging x ticks\n * @param {boolean} [layout.interaction.drag_y1_ticks_to_scale=false] Allow the user to rescale the y1 axis by dragging y1 ticks\n * @param {boolean} [layout.interaction.drag_y2_ticks_to_scale=false] Allow the user to rescale the y2 axis by dragging y2 ticks\n * @param {boolean} [layout.interaction.scroll_to_zoom=false] Allow the user to rescale the plot by mousewheel-scrolling\n * @param {boolean} [layout.interaction.x_linked=false] Whether this panel should change regions to match all other linked panels\n * @param {boolean} [layout.interaction.y1_linked=false] Whether this panel should rescale to match all other linked panels\n * @param {boolean} [layout.interaction.y2_linked=false] Whether this panel should rescale to match all other linked panels\n * @param {Plot|null} parent\n */\n constructor(layout, parent) {\n if (typeof layout !== 'object') {\n throw new Error('Unable to create panel, invalid layout');\n }\n\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent = parent || null;\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent_plot = parent;\n\n // Ensure a valid ID is present. If there is no valid ID then generate one\n if (typeof layout.id !== 'string' || !layout.id.length) {\n if (!this.parent) {\n layout.id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n } else {\n const generateID = () => {\n let id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n if (id === null || typeof this.parent.panels[id] != 'undefined') {\n id = generateID();\n }\n return id;\n };\n layout.id = generateID();\n }\n } else if (this.parent) {\n if (typeof this.parent.panels[layout.id] !== 'undefined') {\n throw new Error(`Cannot create panel with id [${layout.id}]; panel with that id already exists`);\n }\n }\n /**\n * @public\n * @member {String}\n */\n this.id = layout.id;\n\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * The index of this panel in the parent plot's `layout.panels`\n * @private\n * @member {number}\n * */\n this.layout_idx = null;\n /**\n * @private\n * @member {Object}\n */\n this.svg = {};\n\n /**\n * A JSON-serializable object used to describe the composition of the Panel\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n\n // Define state parameters specific to this panel\n if (this.parent) {\n /**\n * @private\n * @member {Object}\n */\n this.state = this.parent.state;\n\n /**\n * @private\n * @member {String}\n */\n this.state_id = this.id;\n this.state[this.state_id] = this.state[this.state_id] || {};\n } else {\n this.state = null;\n this.state_id = null;\n }\n\n /**\n * Direct access to data layer instances, keyed by data layer ID. Used primarily for introspection/ development.\n * @public\n * @member {Object.}\n */\n this.data_layers = {};\n /**\n * @private\n * @member {String[]}\n */\n this.data_layer_ids_by_z_index = [];\n\n /**\n * Track data requests in progress\n * @member {Promise[]}\n * @private\n */\n this.data_promises = [];\n\n /**\n * @private\n * @member {d3.scale}\n */\n this.x_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y1_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y2_scale = null;\n\n /**\n * @private\n * @member {d3.extent}\n */\n this.x_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y1_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y2_extent = null;\n\n /**\n * @private\n * @member {Number[]}\n */\n this.x_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y1_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y2_ticks = [];\n\n /**\n * A timeout ID as returned by setTimeout\n * @private\n * @member {number}\n */\n this.zoom_timeout = null;\n\n /**\n * Known event hooks that the panel can respond to\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @protected\n * @member {Object}\n */\n this.event_hooks = {};\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* Public methods: intended for direct external manipulation of panel internals */\n\n /**\n * There are several events that a LocusZoom panel can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * To register a hook for any of these events use `panel.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered.\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of the event. Consult documentation for the names of built-in events.\n * @param {function} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n // TODO: Dry plot and panel event code into a shared mixin\n if (typeof event !== 'string') {\n throw new Error(`Unable to register event hook. Event name must be a string: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n if (!this.event_hooks[event]) {\n // We do not validate on known event names, because LZ is allowed to track and emit custom events like \"widget button clicked\".\n this.event_hooks[event] = [];\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Panel}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof event != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n *\n * There is a shorter overloaded form of this method: if the event does not have any data, the second\n * argument can be a boolean to control bubbling\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {string} event A known event name\n * @param {*} [eventData] Data or event description that will be passed to the event listener\n * @param {boolean} [bubble=false] Whether to bubble the event to the parent\n * @returns {Panel}\n */\n emit(event, eventData, bubble) {\n bubble = bubble || false;\n\n // TODO: DRY this with the parent plot implementation. Ensure interfaces remain compatible.\n // TODO: Improve documentation for overloaded method signature (JSDoc may have trouble here)\n if (typeof event != 'string') {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n }\n if (typeof eventData === 'boolean' && arguments.length === 2) {\n // Overloaded method signature: emit(event, bubble)\n bubble = eventData;\n eventData = null;\n }\n const sourceID = this.getBaseId();\n const eventContext = { sourceID: sourceID, target: this, data: eventData || null };\n\n if (this.event_hooks[event]) {\n // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound?\n this.event_hooks[event].forEach((hookToRun) => {\n // By default, any handlers fired here will see the panel as the value of `this`. If a bound function is\n // registered as a handler, the previously bound `this` will override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n }\n\n if (bubble && this.parent) {\n // Even if this event has no listeners locally, it might still have listeners on the parent\n this.parent.emit(event, eventContext);\n }\n return this;\n }\n\n /**\n * Set the title for the panel. If passed an object, will merge the object with the existing layout configuration, so\n * that all or only some of the title layout object's parameters can be customized. If passed null, false, or an empty\n * string, the title DOM element will be set to display: none.\n *\n * @public\n * @param {string|object|null} title The title text, or an object with additional configuration\n * @param {string} title.text Text to display. Since titles are rendered as SVG text, HTML and newlines will not be rendered.\n * @param {number} title.x X-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n * @param {number} title.y Y-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n NOTE: SVG y values go from the top down, so the SVG origin of (0,0) is in the top left corner.\n * @param {object} title.style CSS styles object to be applied to the title's DOM element.\n * @returns {Panel}\n */\n setTitle(title) {\n if (typeof this.layout.title == 'string') {\n const text = this.layout.title;\n this.layout.title = { text: text, x: 0, y: 0, style: {} };\n }\n if (typeof title == 'string') {\n this.layout.title.text = title;\n } else if (typeof title == 'object' && title !== null) {\n this.layout.title = merge(title, this.layout.title);\n }\n if (this.layout.title.text.length) {\n this.title\n .attr('display', null)\n .attr('x', parseFloat(this.layout.title.x))\n .attr('y', parseFloat(this.layout.title.y))\n .text(this.layout.title.text)\n .call(applyStyles, this.layout.title.style);\n\n } else {\n this.title.attr('display', 'none');\n }\n return this;\n }\n\n /**\n * Create a new data layer from a provided layout object. Should have the keys specified in `DefaultLayout`\n * Will automatically add at the top (depth/z-index) of the panel unless explicitly directed differently\n * in the layout provided.\n *\n * **NOTE**: It is very rare that new data layers are added after a panel is rendered.\n * @public\n * @param {object} layout\n * @returns {BaseDataLayer}\n */\n addDataLayer(layout) {\n\n // Sanity checks\n if (typeof layout !== 'object' || typeof layout.id !== 'string' || !layout.id.length) {\n throw new Error('Invalid data layer layout');\n }\n if (typeof this.data_layers[layout.id] !== 'undefined') {\n throw new Error(`Cannot create data_layer with id [${layout.id}]; data layer with that id already exists in the panel`);\n }\n if (typeof layout.type !== 'string') {\n throw new Error('Invalid data layer type');\n }\n\n // If the layout defines a y axis make sure the axis number is set and is 1 or 2 (default to 1)\n if (typeof layout.y_axis == 'object' && (typeof layout.y_axis.axis == 'undefined' || ![1, 2].includes(layout.y_axis.axis))) {\n layout.y_axis.axis = 1;\n }\n\n // Create the Data Layer\n const data_layer = data_layers.create(layout.type, layout, this);\n\n // Store the Data Layer on the Panel\n this.data_layers[data_layer.id] = data_layer;\n\n // If a discrete z_index was set in the layout then adjust other data layer z_index values to accommodate this one\n if (data_layer.layout.z_index !== null && !isNaN(data_layer.layout.z_index)\n && this.data_layer_ids_by_z_index.length > 0) {\n // Negative z_index values should count backwards from the end, so convert negatives to appropriate values here\n if (data_layer.layout.z_index < 0) {\n data_layer.layout.z_index = Math.max(this.data_layer_ids_by_z_index.length + data_layer.layout.z_index, 0);\n }\n this.data_layer_ids_by_z_index.splice(data_layer.layout.z_index, 0, data_layer.id);\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n } else {\n const length = this.data_layer_ids_by_z_index.push(data_layer.id);\n this.data_layers[data_layer.id].layout.z_index = length - 1;\n }\n\n // Determine if this data layer was already in the layout.data_layers array.\n // If it wasn't, add it. Either way store the layout.data_layers array index on the data_layer.\n let layout_idx = null;\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n if (data_layer_layout.id === data_layer.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.data_layers.push(this.data_layers[data_layer.id].layout) - 1;\n }\n this.data_layers[data_layer.id].layout_idx = layout_idx;\n\n return this.data_layers[data_layer.id];\n }\n\n /**\n * Remove a data layer by id\n * @public\n * @param {string} id\n * @returns {Panel}\n */\n removeDataLayer(id) {\n if (!this.data_layers[id]) {\n throw new Error(`Unable to remove data layer, ID not found: ${id}`);\n }\n\n // Destroy all tooltips for the data layer\n this.data_layers[id].destroyAllTooltips();\n\n // Remove the svg container for the data layer if it exists\n if (this.data_layers[id].svg.container) {\n this.data_layers[id].svg.container.remove();\n }\n\n // Delete the data layer and its presence in the panel layout and state\n this.layout.data_layers.splice(this.data_layers[id].layout_idx, 1);\n delete this.state[this.data_layers[id].state_id];\n delete this.data_layers[id];\n\n // Remove the data_layer id from the z_index array\n this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(id), 1);\n\n // Update layout_idx and layout.z_index values for all remaining data_layers\n this.applyDataLayerZIndexesToDataLayerLayouts();\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n this.data_layers[data_layer_layout.id].layout_idx = idx;\n });\n\n return this;\n }\n\n /**\n * Clear all selections on all data layers\n * @public\n * @returns {Panel}\n */\n clearSelections() {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus('selected', false);\n });\n return this;\n }\n\n /**\n * Update rendering of this panel whenever an event triggers a redraw. Assumes that the panel has already been\n * prepared the first time via `initialize`\n * @public\n * @returns {Panel}\n */\n render() {\n\n // Position the panel container\n this.svg.container.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n\n // Set size on the clip rect\n this.svg.clipRect\n .attr('width', this.parent_plot.layout.width)\n .attr('height', this.layout.height);\n\n // Set and position the inner border, style if necessary\n this.inner_border\n .attr('x', this.layout.margin.left)\n .attr('y', this.layout.margin.top)\n .attr('width', this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right))\n .attr('height', this.layout.height - (this.layout.margin.top + this.layout.margin.bottom));\n if (this.layout.inner_border) {\n this.inner_border\n .style('stroke-width', 1)\n .style('stroke', this.layout.inner_border);\n }\n\n // Set/update panel title if necessary\n this.setTitle();\n\n // Regenerate all extents\n this.generateExtents();\n\n // Helper function to constrain any procedurally generated vectors (e.g. ranges, extents)\n // Constraints applied here keep vectors from going to infinity or beyond a definable power of ten\n const constrain = function (value, limit_exponent) {\n const neg_min = Math.pow(-10, limit_exponent);\n const neg_max = Math.pow(-10, -limit_exponent);\n const pos_min = Math.pow(10, -limit_exponent);\n const pos_max = Math.pow(10, limit_exponent);\n if (value === Infinity) {\n value = pos_max;\n }\n if (value === -Infinity) {\n value = neg_min;\n }\n if (value === 0) {\n value = pos_min;\n }\n if (value > 0) {\n value = Math.max(Math.min(value, pos_max), pos_min);\n }\n if (value < 0) {\n value = Math.max(Math.min(value, neg_max), neg_min);\n }\n return value;\n };\n\n // Define default and shifted ranges for all axes\n const ranges = {};\n if (this.x_extent) {\n const base_x_range = { start: 0, end: this.layout.cliparea.width };\n if (this.layout.axes.x.range) {\n base_x_range.start = this.layout.axes.x.range.start || base_x_range.start;\n base_x_range.end = this.layout.axes.x.range.end || base_x_range.end;\n }\n ranges.x = [base_x_range.start, base_x_range.end];\n ranges.x_shifted = [base_x_range.start, base_x_range.end];\n }\n if (this.y1_extent) {\n const base_y1_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y1.range) {\n base_y1_range.start = this.layout.axes.y1.range.start || base_y1_range.start;\n base_y1_range.end = this.layout.axes.y1.range.end || base_y1_range.end;\n }\n ranges.y1 = [base_y1_range.start, base_y1_range.end];\n ranges.y1_shifted = [base_y1_range.start, base_y1_range.end];\n }\n if (this.y2_extent) {\n const base_y2_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y2.range) {\n base_y2_range.start = this.layout.axes.y2.range.start || base_y2_range.start;\n base_y2_range.end = this.layout.axes.y2.range.end || base_y2_range.end;\n }\n ranges.y2 = [base_y2_range.start, base_y2_range.end];\n ranges.y2_shifted = [base_y2_range.start, base_y2_range.end];\n }\n\n // Shift ranges based on any drag or zoom interactions currently underway\n if (this.parent.interaction.panel_id && (this.parent.interaction.panel_id === this.id || this.parent.interaction.linked_panel_ids.includes(this.id))) {\n let anchor, scalar = null;\n if (this.parent.interaction.zooming && typeof this.x_scale == 'function') {\n const current_extent_size = Math.abs(this.x_extent[1] - this.x_extent[0]);\n const current_scaled_extent_size = Math.round(this.x_scale.invert(ranges.x_shifted[1])) - Math.round(this.x_scale.invert(ranges.x_shifted[0]));\n let zoom_factor = this.parent.interaction.zooming.scale;\n const potential_extent_size = Math.floor(current_scaled_extent_size * (1 / zoom_factor));\n if (zoom_factor < 1 && !isNaN(this.parent.layout.max_region_scale)) {\n zoom_factor = 1 / (Math.min(potential_extent_size, this.parent.layout.max_region_scale) / current_scaled_extent_size);\n } else if (zoom_factor > 1 && !isNaN(this.parent.layout.min_region_scale)) {\n zoom_factor = 1 / (Math.max(potential_extent_size, this.parent.layout.min_region_scale) / current_scaled_extent_size);\n }\n const new_extent_size = Math.floor(current_extent_size * zoom_factor);\n anchor = this.parent.interaction.zooming.center - this.layout.margin.left - this.layout.origin.x;\n const offset_ratio = anchor / this.layout.cliparea.width;\n const new_x_extent_start = Math.max(Math.floor(this.x_scale.invert(ranges.x_shifted[0]) - ((new_extent_size - current_scaled_extent_size) * offset_ratio)), 1);\n ranges.x_shifted = [ this.x_scale(new_x_extent_start), this.x_scale(new_x_extent_start + new_extent_size) ];\n } else if (this.parent.interaction.dragging) {\n switch (this.parent.interaction.dragging.method) {\n case 'background':\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n break;\n case 'x_tick':\n if (d3.event && d3.event.shiftKey) {\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n } else {\n anchor = this.parent.interaction.dragging.start_x - this.layout.margin.left - this.layout.origin.x;\n scalar = constrain(anchor / (anchor + this.parent.interaction.dragging.dragged_x), 3);\n ranges.x_shifted[0] = 0;\n ranges.x_shifted[1] = Math.max(this.layout.cliparea.width * (1 / scalar), 1);\n }\n break;\n case 'y1_tick':\n case 'y2_tick': {\n const y_shifted = `y${this.parent.interaction.dragging.method[1]}_shifted`;\n if (d3.event && d3.event.shiftKey) {\n ranges[y_shifted][0] = this.layout.cliparea.height + this.parent.interaction.dragging.dragged_y;\n ranges[y_shifted][1] = +this.parent.interaction.dragging.dragged_y;\n } else {\n anchor = this.layout.cliparea.height - (this.parent.interaction.dragging.start_y - this.layout.margin.top - this.layout.origin.y);\n scalar = constrain(anchor / (anchor - this.parent.interaction.dragging.dragged_y), 3);\n ranges[y_shifted][0] = this.layout.cliparea.height;\n ranges[y_shifted][1] = this.layout.cliparea.height - (this.layout.cliparea.height * (1 / scalar));\n }\n }\n }\n }\n }\n\n // Generate scales and ticks for all axes, then render them\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!this[`${axis}_extent`]) {\n return;\n }\n\n // Base Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`])\n .range(ranges[`${axis}_shifted`]);\n\n // Shift the extent\n this[`${axis}_extent`] = [\n this[`${axis}_scale`].invert(ranges[axis][0]),\n this[`${axis}_scale`].invert(ranges[axis][1]),\n ];\n\n // Finalize Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`]).range(ranges[axis]);\n\n // Render axis (and generate ticks as needed)\n this.renderAxis(axis);\n });\n\n // Establish mousewheel zoom event handers on the panel (namespacing not passed through by d3, so not used here)\n if (this.layout.interaction.scroll_to_zoom) {\n const zoom_handler = () => {\n // Look for a shift key press while scrolling to execute.\n // If not present, gracefully raise a notification and allow conventional scrolling\n if (!(d3.event.shiftKey || d3.event.altKey)) {\n if (this.parent._canInteract(this.id)) {\n this.loader.show('Press [SHIFT] or [ALT] while scrolling to zoom').hide(1000);\n }\n return;\n }\n d3.event.preventDefault();\n if (!this.parent._canInteract(this.id)) {\n return;\n }\n const coords = d3.mouse(this.svg.container.node());\n const delta = Math.max(-1, Math.min(1, (d3.event.wheelDelta || -d3.event.detail || -d3.event.deltaY)));\n if (delta === 0) {\n return;\n }\n this.parent.interaction = {\n panel_id: this.id,\n linked_panel_ids: this.getLinkedPanelIds('x'),\n zooming: {\n scale: (delta < 1) ? 0.9 : 1.1,\n center: coords[0],\n },\n };\n this.render();\n this.parent.interaction.linked_panel_ids.forEach((panel_id) => {\n this.parent.panels[panel_id].render();\n });\n if (this.zoom_timeout !== null) {\n clearTimeout(this.zoom_timeout);\n }\n this.zoom_timeout = setTimeout(() => {\n this.parent.interaction = {};\n this.parent.applyState({ start: this.x_extent[0], end: this.x_extent[1] });\n }, 500);\n };\n // FIXME: Consider moving back to d3.zoom and rewriting drag + zoom to use behaviors.\n this.svg.container\n .on('wheel.zoom', zoom_handler)\n .on('mousewheel.zoom', zoom_handler)\n .on('DOMMouseScroll.zoom', zoom_handler);\n }\n\n // Render data layers in order by z-index\n this.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n this.data_layers[data_layer_id].draw().render();\n });\n\n // Rerender legend last (on top of data). A legend must have been defined at the start in order for this to work.\n if (this.legend) {\n this.legend.render();\n }\n return this;\n }\n\n /**\n * Add a \"basic\" loader to a panel. This is rarely used directly: the `show_loading_indicator` panel layout\n * directive is the preferred way to trigger this function. The imperative form is useful if for some reason a\n * loading indicator needs to be added only after first render.\n * This method is just a shortcut for adding the most commonly used type of loading indicator, which appears when\n * data is requested, animates (e.g. shows an infinitely cycling progress bar as opposed to one that loads from\n * 0-100% based on actual load progress), and disappears when new data is loaded and rendered.\n *\n * @protected\n * @listens event:data_requested\n * @listens event:data_rendered\n * @param {Boolean} show_immediately\n * @returns {Panel}\n */\n addBasicLoader(show_immediately = true) {\n if (this.layout.show_loading_indicator && this.initialized) {\n // Prior to LZ 0.13, this function was called only after the plot was first rendered. Now, it is run by default.\n // Some older pages could thus end up adding a loader twice: to avoid duplicate render events,\n // short-circuit if a loader is already present after the first render has finished.\n return this;\n }\n if (show_immediately) {\n this.loader.show('Loading...').animate();\n }\n this.on('data_requested', () => {\n this.loader.show('Loading...').animate();\n });\n this.on('data_rendered', () => {\n this.loader.hide();\n });\n\n // Update layout to reflect new option\n this.layout.show_loading_indicator = true;\n return this;\n }\n\n /************* Private interface: only used internally */\n /** @private */\n applyDataLayerZIndexesToDataLayerLayouts () {\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n }\n\n /**\n * @private\n * @returns {string}\n */\n getBaseId () {\n return `${this.parent.id}.${this.id}`;\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const plot_origin = this.parent._getPageOrigin();\n return {\n x: plot_origin.x + this.layout.origin.x,\n y: plot_origin.y + this.layout.origin.y,\n };\n }\n\n /**\n * Prepare the panel for first use by performing parameter validation, creating axes, setting default dimensions,\n * and preparing / positioning data layers as appropriate.\n * @private\n * @returns {Panel}\n */\n initializeLayout() {\n // Set panel dimensions, origin, and margin\n this.setDimensions();\n this.setOrigin();\n this.setMargin();\n\n // Set ranges\n // TODO: Define stub values in constructor\n this.x_range = [0, this.layout.cliparea.width];\n this.y1_range = [this.layout.cliparea.height, 0];\n this.y2_range = [this.layout.cliparea.height, 0];\n\n // Initialize panel axes\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!Object.keys(this.layout.axes[axis]).length || this.layout.axes[axis].render === false) {\n // The default layout sets the axis to an empty object, so set its render boolean here\n this.layout.axes[axis].render = false;\n } else {\n this.layout.axes[axis].render = true;\n this.layout.axes[axis].label = this.layout.axes[axis].label || null;\n }\n });\n\n // Add data layers (which define x and y extents)\n this.layout.data_layers.forEach((data_layer_layout) => {\n this.addDataLayer(data_layer_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for the panel. If passed with no arguments will calculate optimal size based on layout\n * directives and the available area within the plot. If passed discrete width (number) and height (number) will\n * attempt to resize the panel to them, but may be limited by minimum dimensions defined on the plot or panel.\n *\n * @private\n * @param {number} [width]\n * @param {number} [height]\n * @returns {Panel}\n */\n setDimensions(width, height) {\n if (typeof width != 'undefined' && typeof height != 'undefined') {\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n this.parent.layout.width = Math.round(+width);\n // Ensure that the requested height satisfies all minimum values\n this.layout.height = Math.max(Math.round(+height), this.layout.min_height);\n }\n }\n this.layout.cliparea.width = Math.max(this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n if (this.svg.clipRect) {\n this.svg.clipRect\n .attr('width', this.parent.layout.width)\n .attr('height', this.layout.height);\n }\n if (this.initialized) {\n this.render();\n this.curtain.update();\n this.loader.update();\n this.toolbar.update();\n if (this.legend) {\n this.legend.position();\n }\n }\n return this;\n }\n\n /**\n * Set panel origin on the plot, and re-render as appropriate\n *\n * @private\n * @param {number} x\n * @param {number} y\n * @returns {Panel}\n */\n setOrigin(x, y) {\n if (!isNaN(x) && x >= 0) {\n this.layout.origin.x = Math.max(Math.round(+x), 0);\n }\n if (!isNaN(y) && y >= 0) {\n this.layout.origin.y = Math.max(Math.round(+y), 0);\n }\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Set margins around this panel\n * @private\n * @param {number} top\n * @param {number} right\n * @param {number} bottom\n * @param {number} left\n * @returns {Panel}\n */\n setMargin(top, right, bottom, left) {\n let extra;\n if (!isNaN(top) && top >= 0) {\n this.layout.margin.top = Math.max(Math.round(+top), 0);\n }\n if (!isNaN(right) && right >= 0) {\n this.layout.margin.right = Math.max(Math.round(+right), 0);\n }\n if (!isNaN(bottom) && bottom >= 0) {\n this.layout.margin.bottom = Math.max(Math.round(+bottom), 0);\n }\n if (!isNaN(left) && left >= 0) {\n this.layout.margin.left = Math.max(Math.round(+left), 0);\n }\n // If the specified margins are greater than the available width, then shrink the margins.\n if (this.layout.margin.top + this.layout.margin.bottom > this.layout.height) {\n extra = Math.floor(((this.layout.margin.top + this.layout.margin.bottom) - this.layout.height) / 2);\n this.layout.margin.top -= extra;\n this.layout.margin.bottom -= extra;\n }\n if (this.layout.margin.left + this.layout.margin.right > this.parent_plot.layout.width) {\n extra = Math.floor(((this.layout.margin.left + this.layout.margin.right) - this.parent_plot.layout.width) / 2);\n this.layout.margin.left -= extra;\n this.layout.margin.right -= extra;\n }\n ['top', 'right', 'bottom', 'left'].forEach((m) => {\n this.layout.margin[m] = Math.max(this.layout.margin[m], 0);\n });\n this.layout.cliparea.width = Math.max(this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n this.layout.cliparea.origin.x = this.layout.margin.left;\n this.layout.cliparea.origin.y = this.layout.margin.top;\n\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Prepare the first rendering of the panel. This includes drawing the individual data layers, but also creates shared\n * elements such as axes, title, and loader/curtain.\n * @private\n * @returns {Panel}\n */\n initialize() {\n\n // Append a container group element to house the main panel group element and the clip path\n // Position with initial layout parameters\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.append('g')\n .attr('id', `${base_id}.panel_container`)\n .attr('transform', `translate(${this.layout.origin.x || 0}, ${this.layout.origin.y || 0})`);\n\n // Append clip path to the parent svg element, size with initial layout parameters\n const clipPath = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`);\n this.svg.clipRect = clipPath.append('rect')\n .attr('width', this.parent_plot.layout.width)\n .attr('height', this.layout.height);\n\n // Append svg group for rendering all panel child elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.panel`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n // Add curtain and loader to the panel\n /**\n * @protected\n * @member {Object}\n */\n this.curtain = generateCurtain.call(this);\n /**\n * @protected\n * @member {Object}\n */\n this.loader = generateLoader.call(this);\n\n if (this.layout.show_loading_indicator) {\n // Activate the loading indicator prior to first render, and only show when data is loading\n this.addBasicLoader(false);\n }\n\n /**\n * Create the toolbar object and hang widgets on it as defined by panel layout\n * @protected\n * @member {Toolbar}\n */\n this.toolbar = new Toolbar(this);\n\n // Inner border\n this.inner_border = this.svg.group.append('rect')\n .attr('class', 'lz-panel-background')\n .on('click', () => {\n if (this.layout.background_click === 'clear_selections') {\n this.clearSelections();\n }\n });\n\n // Add the title\n /**\n * @private\n * @member {Element}\n */\n this.title = this.svg.group.append('text').attr('class', 'lz-panel-title');\n if (typeof this.layout.title != 'undefined') {\n this.setTitle();\n }\n\n // Initialize Axes\n this.svg.x_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.x_axis`)\n .attr('class', 'lz-x lz-axis');\n if (this.layout.axes.x.render) {\n this.svg.x_axis_label = this.svg.x_axis.append('text')\n .attr('class', 'lz-x lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y1_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y1_axis`).attr('class', 'lz-y lz-y1 lz-axis');\n if (this.layout.axes.y1.render) {\n this.svg.y1_axis_label = this.svg.y1_axis.append('text')\n .attr('class', 'lz-y1 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y2_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y2_axis`)\n .attr('class', 'lz-y lz-y2 lz-axis');\n if (this.layout.axes.y2.render) {\n this.svg.y2_axis_label = this.svg.y2_axis.append('text')\n .attr('class', 'lz-y2 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n\n // Initialize child Data Layers\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].initialize();\n });\n\n /**\n * Legend object, as defined by panel layout and child data layer layouts\n * @protected\n * @member {Legend}\n * */\n this.legend = null;\n if (this.layout.legend) {\n this.legend = new Legend(this);\n }\n\n // Establish panel background drag interaction mousedown event handler (on the panel background)\n if (this.layout.interaction.drag_background_to_pan) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const mousedown = () => this.parent.startDrag(this, 'background');\n this.svg.container.select('.lz-panel-background')\n .on(`mousedown${namespace}.background`, mousedown)\n .on(`touchstart${namespace}.background`, mousedown);\n }\n\n return this;\n }\n\n /**\n * Refresh the sort order of all data layers (called by data layer moveForward and moveBack methods)\n * @private\n */\n resortDataLayers() {\n const sort = [];\n this.data_layer_ids_by_z_index.forEach((id) => {\n sort.push(this.data_layers[id].layout.z_index);\n });\n this.svg.group\n .selectAll('g.lz-data_layer-container')\n .data(sort)\n .sort(d3.ascending);\n this.applyDataLayerZIndexesToDataLayerLayouts();\n }\n\n /**\n * Get an array of panel IDs that are axis-linked to this panel\n * @private\n * @param {('x'|'y1'|'y2')} axis\n * @returns {Array}\n */\n getLinkedPanelIds(axis) {\n axis = axis || null;\n const linked_panel_ids = [];\n if (!['x', 'y1', 'y2'].includes(axis)) {\n return linked_panel_ids;\n }\n if (!this.layout.interaction[`${axis}_linked`]) {\n return linked_panel_ids;\n }\n this.parent.panel_ids_by_y_index.forEach((panel_id) => {\n if (panel_id !== this.id && this.parent.panels[panel_id].layout.interaction[`${axis}_linked`]) {\n linked_panel_ids.push(panel_id);\n }\n });\n return linked_panel_ids;\n }\n\n /**\n * Move a panel up relative to others by y-index\n * @private\n * @returns {Panel}\n */\n moveUp() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index - 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index - 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index - 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * Move a panel down (y-axis) relative to others in the plot\n * @private\n * @returns {Panel}\n */\n moveDown() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index + 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index + 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index + 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * When the parent plot changes state, adjust the panel accordingly. For example, this may include fetching new data\n * from the API as the viewing region changes\n * @private\n * @fires event:data_requested\n * @fires event:layout_changed\n * @fires event:data_rendered\n * @returns {Promise}\n */\n reMap() {\n this.emit('data_requested');\n this.data_promises = [];\n\n // Remove any previous error messages before attempting to load new data\n this.curtain.hide();\n // Trigger reMap on each Data Layer\n for (let id in this.data_layers) {\n try {\n this.data_promises.push(this.data_layers[id].reMap());\n } catch (error) {\n console.error(error);\n this.curtain.show(error.message || error);\n }\n }\n // When all finished trigger a render\n return Promise.all(this.data_promises)\n .then(() => {\n this.initialized = true;\n this.render();\n this.emit('layout_changed', true);\n this.emit('data_rendered');\n })\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n });\n }\n\n /**\n * Iterate over data layers to generate panel axis extents\n * @private\n * @returns {Panel}\n */\n generateExtents() {\n\n // Reset extents\n ['x', 'y1', 'y2'].forEach((axis) => {\n this[`${axis}_extent`] = null;\n });\n\n // Loop through the data layers\n for (let id in this.data_layers) {\n\n const data_layer = this.data_layers[id];\n\n // If defined and not decoupled, merge the x extent of the data layer with the panel's x extent\n if (data_layer.layout.x_axis && !data_layer.layout.x_axis.decoupled) {\n this.x_extent = d3.extent((this.x_extent || []).concat(data_layer.getAxisExtent('x')));\n }\n\n // If defined and not decoupled, merge the y extent of the data layer with the panel's appropriate y extent\n if (data_layer.layout.y_axis && !data_layer.layout.y_axis.decoupled) {\n const y_axis = `y${data_layer.layout.y_axis.axis}`;\n this[`${y_axis}_extent`] = d3.extent((this[`${y_axis}_extent`] || []).concat(data_layer.getAxisExtent('y')));\n }\n\n }\n\n // Override x_extent from state if explicitly defined to do so\n if (this.layout.axes.x && this.layout.axes.x.extent === 'state') {\n this.x_extent = [ this.state.start, this.state.end ];\n }\n return this;\n }\n\n /**\n * Generate an array of ticks for an axis. These ticks are generated in one of three ways (highest wins):\n * 1. An array of specific tick marks\n * 2. Query each data layer for what ticks are appropriate, and allow a panel-level tick configuration parameter\n * object to override the layer's default presentation settings\n * 3. Generate generic tick marks based on the extent of the data\n *\n * @private\n * @param {('x'|'y1'|'y2')} axis The string identifier of the axis\n * @returns {Number[]|Object[]} TODO: number format?\n * An array of numbers: interpreted as an array of axis value offsets for positioning.\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n generateTicks(axis) {\n\n // Parse an explicit 'ticks' attribute in the axis layout\n if (this.layout.axes[axis].ticks) {\n const layout = this.layout.axes[axis];\n\n const baseTickConfig = layout.ticks;\n if (Array.isArray(baseTickConfig)) {\n // Array of specific ticks hard-coded into a panel will override any ticks that an individual layer might specify\n return baseTickConfig;\n }\n\n if (typeof baseTickConfig === 'object') {\n // If the layout specifies base configuration for ticks- but without specific positions- then ask each\n // data layer to report the tick marks that it thinks it needs\n // TODO: Few layers currently need to specify custom ticks (which is ok!). But if it becomes common, consider adding mechanisms to deduplicate ticks across layers\n const self = this;\n\n // Pass any layer-specific customizations for how ticks are calculated. (styles are overridden separately)\n const config = { position: baseTickConfig.position };\n\n const combinedTicks = this.data_layer_ids_by_z_index.reduce((acc, data_layer_id) => {\n const nextLayer = self.data_layers[data_layer_id];\n return acc.concat(nextLayer.getTicks(axis, config));\n }, []);\n\n return combinedTicks.map((item) => {\n // The layer makes suggestions, but tick configuration params specified on the panel take precedence\n let itemConfig = {};\n itemConfig = merge(itemConfig, baseTickConfig);\n return merge(itemConfig, item);\n });\n }\n }\n\n // If no other configuration is provided, attempt to generate ticks from the extent\n if (this[`${axis}_extent`]) {\n return prettyTicks(this[`${axis}_extent`], 'both');\n }\n return [];\n }\n\n /**\n * Render ticks for a particular axis\n * @private\n * @param {('x'|'y1'|'y2')} axis The identifier of the axes\n * @returns {Panel}\n */\n renderAxis(axis) {\n\n if (!['x', 'y1', 'y2'].includes(axis)) {\n throw new Error(`Unable to render axis; invalid axis identifier: ${axis}`);\n }\n\n const canRender = this.layout.axes[axis].render\n && typeof this[`${axis}_scale`] == 'function'\n && !isNaN(this[`${axis}_scale`](0));\n\n // If the axis has already been rendered then check if we can/can't render it\n // Make sure the axis element is shown/hidden to suit\n if (this[`${axis}_axis`]) {\n this.svg.container.select(`g.lz-axis.lz-${axis}`)\n .style('display', canRender ? null : 'none');\n }\n\n if (!canRender) {\n return this;\n }\n\n // Axis-specific values to plug in where needed\n const axis_params = {\n x: {\n position: `translate(${this.layout.margin.left}, ${this.layout.height - this.layout.margin.bottom})`,\n orientation: 'bottom',\n label_x: this.layout.cliparea.width / 2,\n label_y: (this.layout.axes[axis].label_offset || 0),\n label_rotate: null,\n },\n y1: {\n position: `translate(${this.layout.margin.left}, ${this.layout.margin.top})`,\n orientation: 'left',\n label_x: -1 * (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n y2: {\n position: `translate(${this.parent_plot.layout.width - this.layout.margin.right}, ${this.layout.margin.top})`,\n orientation: 'right',\n label_x: (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n };\n\n // Generate Ticks\n this[`${axis}_ticks`] = this.generateTicks(axis);\n\n // Determine if the ticks are all numbers (d3-automated tick rendering) or not (manual tick rendering)\n const ticksAreAllNumbers = ((ticks) => {\n for (let i = 0; i < ticks.length; i++) {\n if (isNaN(ticks[i])) {\n return false;\n }\n }\n return true;\n })(this[`${axis}_ticks`]);\n\n // Initialize the axis; set scale and orientation\n let axis_factory;\n switch (axis_params[axis].orientation) {\n case 'right':\n axis_factory = d3.axisRight;\n break;\n case 'left':\n axis_factory = d3.axisLeft;\n break;\n case 'bottom':\n axis_factory = d3.axisBottom;\n break;\n default:\n throw new Error('Unrecognized axis orientation');\n }\n\n this[`${axis}_axis`] = axis_factory(this[`${axis}_scale`])\n .tickPadding(3);\n\n // Set tick values and format\n if (ticksAreAllNumbers) {\n this[`${axis}_axis`].tickValues(this[`${axis}_ticks`]);\n if (this.layout.axes[axis].tick_format === 'region') {\n this[`${axis}_axis`].tickFormat((d) => positionIntToString(d, 6));\n }\n } else {\n let ticks = this[`${axis}_ticks`].map((t) => {\n return (t[axis.substr(0, 1)]);\n });\n this[`${axis}_axis`].tickValues(ticks)\n .tickFormat((t, i) => {\n return this[`${axis}_ticks`][i].text;\n });\n }\n\n // Position the axis in the SVG and apply the axis construct\n this.svg[`${axis}_axis`]\n .attr('transform', axis_params[axis].position)\n .call(this[`${axis}_axis`]);\n\n // If necessary manually apply styles and transforms to ticks as specified by the layout\n if (!ticksAreAllNumbers) {\n const tick_selector = d3.selectAll(`g#${this.getBaseId().replace('.', '\\\\.')}\\\\.${axis}_axis g.tick`);\n const panel = this;\n tick_selector.each(function (d, i) {\n const selector = d3.select(this).select('text');\n if (panel[`${axis}_ticks`][i].style) {\n applyStyles(selector, panel[`${axis}_ticks`][i].style);\n }\n if (panel[`${axis}_ticks`][i].transform) {\n selector.attr('transform', panel[`${axis}_ticks`][i].transform);\n }\n });\n }\n\n // Render the axis label if necessary\n const label = this.layout.axes[axis].label || null;\n if (label !== null) {\n this.svg[`${axis}_axis_label`]\n .attr('x', axis_params[axis].label_x)\n .attr('y', axis_params[axis].label_y)\n .text(parseFields(label, this.state))\n .attr('fill', 'currentColor');\n if (axis_params[axis].label_rotate !== null) {\n this.svg[`${axis}_axis_label`]\n .attr('transform', `rotate(${axis_params[axis].label_rotate} ${axis_params[axis].label_x}, ${axis_params[axis].label_y})`);\n }\n }\n\n // Attach interactive handlers to ticks as needed\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (this.layout.interaction[`drag_${axis}_ticks_to_scale`]) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const tick_mouseover = function() {\n if (typeof d3.select(this).node().focus == 'function') {\n d3.select(this).node().focus();\n }\n let cursor = (axis === 'x') ? 'ew-resize' : 'ns-resize';\n if (d3.event && d3.event.shiftKey) {\n cursor = 'move';\n }\n d3.select(this)\n .style('font-weight', 'bold')\n .style('cursor', cursor )\n .on(`keydown${namespace}`, tick_mouseover)\n .on(`keyup${namespace}`, tick_mouseover);\n };\n this.svg.container.selectAll(`.lz-axis.lz-${axis} .tick text`)\n .attr('tabindex', 0) // necessary to make the tick focusable so keypress events can be captured\n .on(`mouseover${namespace}`, tick_mouseover)\n .on(`mouseout${namespace}`, function() {\n d3.select(this)\n .style('font-weight', 'normal')\n .on(`keydown${namespace}`, null)\n .on(`keyup${namespace}`, null);\n })\n .on(`mousedown${namespace}`, () => {\n this.parent.startDrag(this, `${axis}_tick`);\n });\n }\n });\n\n return this;\n }\n\n /**\n * Force the height of this panel to the largest absolute height of the data in\n * all child data layers (if not null for any child data layers)\n * @private\n * @param {number|null} [target_height] A target height, which will be used in situations when the expected height can be\n * pre-calculated (eg when the layers are transitioning)\n */\n scaleHeightToData(target_height) {\n target_height = +target_height || null;\n if (target_height === null) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n const dh = this.data_layers[id].getAbsoluteDataHeight();\n if (+dh) {\n if (target_height === null) {\n target_height = +dh;\n } else {\n target_height = Math.max(target_height, +dh);\n }\n }\n });\n }\n if (+target_height) {\n target_height += +this.layout.margin.top + +this.layout.margin.bottom;\n // FIXME: plot.setDimensions calls panel.setDimensions (though without arguments)\n this.setDimensions(this.parent_plot.layout.width, target_height);\n this.parent.setDimensions();\n this.parent.positionPanels();\n }\n }\n\n /**\n * Set/unset element statuses across all data layers\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n */\n setAllElementStatus(status, toggle) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus(status, toggle);\n });\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n\n // Set/unset status for all elements\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n Panel.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n */\n /**\n * @private\n * @function unhideAllElements\n */\n Panel.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {Panel as default};\n","/**\n * Helpers that control the display of individual points and field values\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport Field from '../data/field';\nimport Plot from '../components/plot';\nimport {applyStyles} from './common';\n\n\n/**\n * Convert an integer chromosome position to an SI string representation (e.g. 23423456 => \"23.42\" (Mb))\n * @param {Number} pos Position\n * @param {Number} [exp] Exponent to use for the returned string, eg 6=> MB. If not specified, will attempt to guess\n * the most appropriate SI prefix based on the number provided.\n * @param {Boolean} [suffix=false] Whether or not to append a suffix (e.g. \"Mb\") to the end of the returned string\n * @returns {string}\n */\nfunction positionIntToString(pos, exp, suffix) {\n const exp_symbols = { 0: '', 3: 'K', 6: 'M', 9: 'G' };\n suffix = suffix || false;\n if (isNaN(exp) || exp === null) {\n const log = Math.log(pos) / Math.LN10;\n exp = Math.min(Math.max(log - (log % 3), 0), 9);\n }\n const places_exp = exp - Math.floor((Math.log(pos) / Math.LN10).toFixed(exp + 3));\n const min_exp = Math.min(Math.max(exp, 0), 2);\n const places = Math.min(Math.max(places_exp, min_exp), 12);\n let ret = `${(pos / Math.pow(10, exp)).toFixed(places)}`;\n if (suffix && typeof exp_symbols[exp] !== 'undefined') {\n ret += ` ${exp_symbols[exp]}b`;\n }\n return ret;\n}\n\n/**\n * Convert an SI string chromosome position to an integer representation (e.g. \"5.8 Mb\" => 58000000)\n * @param {String} p The chromosome position\n * @returns {Number}\n */\nfunction positionStringToInt(p) {\n let val = p.toUpperCase();\n val = val.replace(/,/g, '');\n const suffixre = /([KMG])[B]*$/;\n const suffix = suffixre.exec(val);\n let mult = 1;\n if (suffix) {\n if (suffix[1] === 'M') {\n mult = 1e6;\n } else if (suffix[1] === 'G') {\n mult = 1e9;\n } else {\n mult = 1e3; //K\n }\n val = val.replace(suffixre, '');\n }\n val = Number(val) * mult;\n return val;\n}\n\n/**\n * Generate a \"pretty\" set of ticks (multiples of 1, 2, or 5 on the same order of magnitude for the range)\n * Based on R's \"pretty\" function: https://github.com/wch/r-source/blob/b156e3a711967f58131e23c1b1dc1ea90e2f0c43/src/appl/pretty.c\n * @param {Number[]} range A two-item array specifying [low, high] values for the axis range\n * @param {('low'|'high'|'both'|'neither')} [clip_range='neither'] What to do if first and last generated ticks extend\n * beyond the range. Set this to \"low\", \"high\", \"both\", or \"neither\" to clip the first (low) or last (high) tick to\n * be inside the range or allow them to extend beyond.\n * e.g. \"low\" will clip the first (low) tick if it extends beyond the low end of the range but allow the\n * last (high) tick to extend beyond the range. \"both\" clips both ends, \"neither\" allows both to extend beyond.\n * @param {Number} [target_tick_count=5] The approximate number of ticks you would like to be returned; may not be exact\n * @returns {Number[]}\n */\nfunction prettyTicks(range, clip_range, target_tick_count) {\n if (typeof target_tick_count == 'undefined' || isNaN(parseInt(target_tick_count))) {\n target_tick_count = 5;\n }\n target_tick_count = +target_tick_count;\n\n const min_n = target_tick_count / 3;\n const shrink_sml = 0.75;\n const high_u_bias = 1.5;\n const u5_bias = 0.5 + 1.5 * high_u_bias;\n\n const d = Math.abs(range[0] - range[1]);\n let c = d / target_tick_count;\n if ((Math.log(d) / Math.LN10) < -2) {\n c = (Math.max(Math.abs(d)) * shrink_sml) / min_n;\n }\n\n const base = Math.pow(10, Math.floor(Math.log(c) / Math.LN10));\n let base_toFixed = 0;\n if (base < 1 && base !== 0) {\n base_toFixed = Math.abs(Math.round(Math.log(base) / Math.LN10));\n }\n\n let unit = base;\n if ( ((2 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 2 * base;\n if ( ((5 * base) - c) < (u5_bias * (c - unit)) ) {\n unit = 5 * base;\n if ( ((10 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 10 * base;\n }\n }\n }\n\n let ticks = [];\n let i = parseFloat((Math.floor(range[0] / unit) * unit).toFixed(base_toFixed));\n while (i < range[1]) {\n ticks.push(i);\n i += unit;\n if (base_toFixed > 0) {\n i = parseFloat(i.toFixed(base_toFixed));\n }\n }\n ticks.push(i);\n\n if (typeof clip_range == 'undefined' || ['low', 'high', 'both', 'neither'].indexOf(clip_range) === -1) {\n clip_range = 'neither';\n }\n if (clip_range === 'low' || clip_range === 'both') {\n if (ticks[0] < range[0]) {\n ticks = ticks.slice(1);\n }\n }\n if (clip_range === 'high' || clip_range === 'both') {\n if (ticks[ticks.length - 1] > range[1]) {\n ticks.pop();\n }\n }\n\n return ticks;\n}\n\n/**\n * Replace placeholders in an html string with field values defined in a data object\n * Only works on scalar values in data! Will ignore non-scalars. This is useful in, eg, tooltip templates.\n *\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @param {String} html A placeholder string in which to substitute fields. Supports several template options:\n * `{{field_name}}` is a variable placeholder for the value of `field_name` from the provided data\n * `{{#if field_name}} Conditional text {{/if}}` will insert the contents of the tag only if the value exists.\n * This can be used with namespaced values, `{{#if assoc:field}}`; any dynamic namespacing will be applied when the\n * layout is first retrieved. For numbers, transforms like `{{#if field|is_numeric}}` can help to ensure that 0\n * values are displayed when expected.\n * Can optionally take an else block, useful for things like toggle buttons: {{#if field}} ... {{#else}} ... {{/if}}\n * @param {Object} data The data associated with a particular element. Eg, tooltips often appear over a specific point.\n * @param {Object|null} extra Any additional fields (eg element annotations) associated with the specified datum\n * @returns {string}\n */\nfunction parseFields(html, data, extra) {\n if (typeof data != 'object') {\n throw new Error('invalid arguments: data is not an object');\n }\n if (typeof html != 'string') {\n throw new Error('invalid arguments: html is not a string');\n }\n // `tokens` is like [token,...]\n // `token` is like {text: '...'} or {variable: 'foo|bar'} or {condition: 'foo|bar'} or {close: 'if'}\n const tokens = [];\n const regex = /{{(?:(#if )?([A-Za-z0-9_:|]+)|(#else)|(\\/if))}}/;\n while (html.length > 0) {\n const m = regex.exec(html);\n if (!m) {\n tokens.push({text: html});\n html = '';\n } else if (m.index !== 0) {\n tokens.push({text: html.slice(0, m.index)});\n html = html.slice(m.index);\n } else if (m[1] === '#if ') {\n tokens.push({condition: m[2]});\n html = html.slice(m[0].length);\n } else if (m[2]) {\n tokens.push({variable: m[2]});\n html = html.slice(m[0].length);\n } else if (m[3] === '#else') {\n tokens.push({branch: 'else'});\n html = html.slice(m[0].length);\n } else if (m[4] === '/if') {\n tokens.push({close: 'if'});\n html = html.slice(m[0].length);\n } else {\n console.error(`Error tokenizing tooltip when remaining template is ${JSON.stringify(html)} and previous tokens are ${JSON.stringify(tokens)} and current regex match is ${JSON.stringify([m[1], m[2], m[3]])}`);\n html = html.slice(m[0].length);\n }\n }\n const astify = function () {\n const token = tokens.shift();\n if (typeof token.text !== 'undefined' || token.variable) {\n return token;\n } else if (token.condition) {\n let dest = token.then = [];\n token.else = [];\n // Inside an if block, consume all tokens related to text and/or else block\n while (tokens.length > 0) {\n if (tokens[0].close === 'if') {\n tokens.shift();\n break;\n }\n if (tokens[0].branch === 'else') {\n tokens.shift();\n dest = token.else;\n }\n dest.push(astify());\n }\n return token;\n } else {\n console.error(`Error making tooltip AST due to unknown token ${JSON.stringify(token)}`);\n return { text: '' };\n }\n };\n // `ast` is like [thing,...]\n // `thing` is like {text: \"...\"} or {variable:\"foo|bar\"} or {condition: \"foo|bar\", then:[thing,...]}\n const ast = [];\n while (tokens.length > 0) {\n ast.push(astify());\n }\n\n const resolve = function (variable) {\n if (!Object.prototype.hasOwnProperty.call(resolve.cache, variable)) {\n resolve.cache[variable] = (new Field(variable)).resolve(data, extra);\n }\n return resolve.cache[variable];\n };\n resolve.cache = {};\n const render_node = function (node) {\n if (typeof node.text !== 'undefined') {\n return node.text;\n } else if (node.variable) {\n try {\n const value = resolve(node.variable);\n if (['string', 'number', 'boolean'].indexOf(typeof value) !== -1) {\n return value;\n }\n if (value === null) {\n return '';\n }\n } catch (error) {\n console.error(`Error while processing variable ${JSON.stringify(node.variable)}`);\n }\n return `{{${node.variable}}}`;\n } else if (node.condition) {\n try {\n const condition = resolve(node.condition);\n if (condition) {\n return node.then.map(render_node).join('');\n } else if (node.else) {\n return node.else.map(render_node).join('');\n }\n } catch (error) {\n console.error(`Error while processing condition ${JSON.stringify(node.variable)}`);\n }\n return '';\n } else {\n console.error(`Error rendering tooltip due to unknown AST node ${JSON.stringify(node)}`);\n }\n };\n return ast.map(render_node).join('');\n}\n\n/**\n * Populate a single element with a LocusZoom plot. This is the primary means of generating a new plot, and is part\n * of the public interface for LocusZoom.\n * @alias module:LocusZoom~populate\n * @public\n * @param {String|d3.selection} selector CSS selector for the container element where the plot will be mounted. Any pre-existing\n * content in the container will be completely replaced.\n * @param {module:LocusZoom~DataSources} datasource Ensemble of data providers used by the plot\n * @param {Object} layout A JSON-serializable object of layout configuration parameters\n * @returns {Plot} The newly created plot instance\n */\nfunction populate(selector, datasource, layout) {\n if (typeof selector == 'undefined') {\n throw new Error('LocusZoom.populate selector not defined');\n }\n // Empty the selector of any existing content\n d3.select(selector).html('');\n let plot;\n d3.select(selector).call(function(target) {\n // Require each containing element have an ID. If one isn't present, create one.\n if (typeof target.node().id == 'undefined') {\n let iterator = 0;\n while (!d3.select(`#lz-${iterator}`).empty()) {\n iterator++;\n }\n target.attr('id', `#lz-${iterator}`);\n }\n // Create the plot\n plot = new Plot(target.node().id, datasource, layout);\n plot.container = target.node();\n // Detect HTML `data-region` attribute, and use it to fill in state values if present\n if (typeof target.node().dataset !== 'undefined' && typeof target.node().dataset.region !== 'undefined') {\n const parsed_state = parsePositionQuery(target.node().dataset.region);\n Object.keys(parsed_state).forEach(function(key) {\n plot.state[key] = parsed_state[key];\n });\n }\n // Add an SVG to the div and set its dimensions\n plot.svg = d3.select(`div#${plot.id}`)\n .append('svg')\n .attr('version', '1.1')\n .attr('xmlns', 'http://www.w3.org/2000/svg')\n .attr('id', `${plot.id}_svg`)\n .attr('class', 'lz-locuszoom')\n .call(applyStyles, plot.layout.style);\n\n plot.setDimensions();\n plot.positionPanels();\n // Initialize the plot\n plot.initialize();\n // If the plot has defined data sources then trigger its first mapping based on state values\n if (datasource) {\n plot.refresh();\n }\n });\n return plot;\n}\n\n/**\n * Parse region queries into their constituent parts\n * @param {String} x A chromosome position query. May be any of the forms `chr:start-end`, `chr:center+offset`,\n * or `chr:pos`\n * @returns {{chr:*, start: *, end:*} | {chr:*, position:*}}\n */\nfunction parsePositionQuery(x) {\n const chrposoff = /^(\\w+):([\\d,.]+[kmgbKMGB]*)([-+])([\\d,.]+[kmgbKMGB]*)$/;\n const chrpos = /^(\\w+):([\\d,.]+[kmgbKMGB]*)$/;\n let match = chrposoff.exec(x);\n if (match) {\n if (match[3] === '+') {\n const center = positionStringToInt(match[2]);\n const offset = positionStringToInt(match[4]);\n return {\n chr:match[1],\n start: center - offset,\n end: center + offset,\n };\n } else {\n return {\n chr: match[1],\n start: positionStringToInt(match[2]),\n end: positionStringToInt(match[4]),\n };\n }\n }\n match = chrpos.exec(x);\n if (match) {\n return {\n chr:match[1],\n position: positionStringToInt(match[2]),\n };\n }\n return null;\n}\n\nexport { parseFields, parsePositionQuery, populate, positionIntToString, positionStringToInt, prettyTicks };\n","import * as d3 from 'd3';\n\nimport {deepCopy, merge} from '../helpers/layouts';\nimport Requester from '../data/requester';\nimport Toolbar from './toolbar';\nimport Panel from './panel';\nimport {generateCurtain, generateLoader} from '../helpers/common';\n\n/**\n * Default/ expected configuration parameters for basic plotting; most plots will override\n *\n * @memberof Plot\n * @protected\n * @static\n * @type {Object}\n */\nconst default_layout = {\n state: {},\n width: 800,\n min_width: 400,\n min_region_scale: null,\n max_region_scale: null,\n responsive_resize: false,\n panels: [],\n toolbar: {\n widgets: [],\n },\n panel_boundaries: true,\n mouse_guide: true,\n};\n\n\n/**\n * Fields common to every event emitted by LocusZoom. This is not an actual event that should ever be used directly;\n * see list below.\n *\n * Note: plot-level listeners *can* be defined for this event, but you should almost never do this.\n * Use the most specific event name to describe the thing you are interested in.\n *\n * Listening to 'any_lz_event' is only for advanced usages, such as proxying (repeating) LZ behavior to a piece of\n * wrapper code. One example is converting all LocusZoom events to vue.js events.\n *\n * @event any_lz_event\n * @type {object}\n * @property {string} sourceID The fully qualified ID of the entity that originated the event, eg `lz-plot.association`\n * @property {Plot|Panel} target A reference to the plot or panel instance that originated the event.\n * @property {object|null} data Additional data provided. (see event-specific documentation)\n */\n\n/**\n * A panel was removed from the plot. Commonly initiated by the \"remove panel\" toolbar widget.\n * @event panel_removed\n * @property {string} data The id of the panel that was removed (eg 'genes')\n * @see event:any_lz_event\n */\n\n/**\n * A request for new or cached data was initiated. This can be used for, eg, showing data loading indicators.\n * @event data_requested\n * @see event:any_lz_event\n */\n\n/**\n * A request for new data has completed, and all data has been rendered in the plot.\n * @event data_rendered\n * @see event:any_lz_event\n */\n\n/**\n * An action occurred that changed, or could change, the layout.\n * Many rerendering operations can fire this event and it is somewhat generic: it includes resize, highlight,\n * and rerender on new data.\n * Caution: Direct layout mutations might not be captured by this event. It is deprecated due to its limited utility.\n * @event layout_changed\n * @deprecated\n * @see event:any_lz_event\n */\n\n/**\n * The user has requested any state changes, eg via `plot.applyState`. This reports the original requested values even\n * if they are overridden by plot logic. Only triggered when a state change causes a re-render.\n * @event state_changed\n * @property {object} data The set of all state changes requested\n * @see event:any_lz_event\n * @see {@link event:region_changed} for a related event that provides more accurate information in some cases\n */\n\n/**\n * The plot region has changed. Reports the actual coordinates of the plot after the zoom event. If plot.applyState is\n * called with an invalid region (eg zooming in or out too far), this reports the actual final coordinates, not what was requested.\n * The actual coordinates are subject to region min/max, etc.\n * @event region_changed\n * @property {object} data The {chr, start, end} coordinates of the requested region.\n * @see event:any_lz_event\n */\n\n/**\n * Indicate whether the element was selected (or unselected)\n * @event element_selection\n * @property {object} data An object with keys { element, active }, representing the datum bound to the element and the\n * selection status (boolean)\n * @see {@link event:element_clicked} if you are interested in tracking clicks that result in other behaviors, like links\n * @see event:any_lz_event\n */\n\n/**\n * Indicates whether an element was clicked. (regardless of the behavior associated with clicking)\n * @event element_clicked\n * @see {@link event:element_selection} for a more specific and more frequently useful event\n * @see event:any_lz_event\n */\n\n/**\n * Indicate whether a match was requested from within a data layer.\n * @event match_requested\n * @property {object} data An object of `{value, active}` representing the scalar value to be matched and whether a match is\n * being initiated or canceled\n * @see event:any_lz_event\n */\n\n/**\n * Check that position fields (chr, start, end) are provided where appropriate, and ensure that the plot fits within\n * any constraints specified by the layout\n *\n * This function has side effects; it mutates the proposed state in order to meet certain bounds checks etc.\n * @private\n * @param {Object} new_state\n * @param {Number} new_state.chr\n * @param {Number} new_state.start\n * @param {Number} new_state.end\n * @param {Object} layout\n * @returns {*|{}}\n */\nfunction _updateStatePosition(new_state, layout) {\n\n new_state = new_state || {};\n layout = layout || {};\n\n // If a \"chr\", \"start\", and \"end\" are present then resolve start and end\n // to numeric values that are not decimal, negative, or flipped\n let validated_region = false;\n let attempted_midpoint = null;\n let attempted_scale;\n if (typeof new_state.chr != 'undefined' && typeof new_state.start != 'undefined' && typeof new_state.end != 'undefined') {\n // Determine a numeric scale and midpoint for the attempted region,\n new_state.start = Math.max(parseInt(new_state.start), 1);\n new_state.end = Math.max(parseInt(new_state.end), 1);\n if (isNaN(new_state.start) && isNaN(new_state.end)) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_midpoint = 0.5;\n attempted_scale = 0;\n } else if (isNaN(new_state.start) || isNaN(new_state.end)) {\n attempted_midpoint = new_state.start || new_state.end;\n attempted_scale = 0;\n new_state.start = (isNaN(new_state.start) ? new_state.end : new_state.start);\n new_state.end = (isNaN(new_state.end) ? new_state.start : new_state.end);\n } else {\n attempted_midpoint = Math.round((new_state.start + new_state.end) / 2);\n attempted_scale = new_state.end - new_state.start;\n if (attempted_scale < 0) {\n const temp = new_state.start;\n new_state.end = new_state.start;\n new_state.start = temp;\n attempted_scale = new_state.end - new_state.start;\n }\n if (attempted_midpoint < 0) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_scale = 0;\n }\n }\n validated_region = true;\n }\n\n // Constrain w/r/t layout-defined minimum region scale\n if (layout.min_region_scale && validated_region && attempted_scale < layout.min_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.min_region_scale / 2), 1);\n new_state.end = new_state.start + layout.min_region_scale;\n }\n\n // Constrain w/r/t layout-defined maximum region scale\n if (layout.max_region_scale && validated_region && attempted_scale > layout.max_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.max_region_scale / 2), 1);\n new_state.end = new_state.start + layout.max_region_scale;\n }\n\n return new_state;\n}\n\n\nclass Plot {\n /**\n * An independent LocusZoom object that renders a unique set of data and subpanels.\n * Many such LocusZoom objects can exist simultaneously on a single page, each having its own layout.\n *\n * This creates a new plot instance, but does not immediately render it. For practical use, it may be more convenient\n * to use the `LocusZoom.populate` helper method.\n *\n * @param {String} id The ID of the plot. Often corresponds to the ID of the container element on the page\n * where the plot is rendered..\n * @param {DataSources} datasource Ensemble of data providers used by the plot\n * @param {object} [layout.state] Initial state parameters; the most common options are 'chr', 'start', and 'end'\n * to specify initial region view\n * @param {number} [layout.width=800] The width of the plot and all child panels\n * @param {number} [layout.min_width=400] Do not allow the panel to be resized below this width\n * @param {number} [layout.min_region_scale] The minimum region width (do not allow the user to zoom smaller than this region size)\n * @param {number} [layout.max_region_scale] The maximum region width (do not allow the user to zoom wider than this region size)\n * @param {boolean} [layout.responsive_resize=false] Whether to resize plot width as the screen is resized\n * @param {Object[]} [layout.panels] Configuration options for each panel to be added\n * @param {module:LocusZoom_Widgets[]} [layout.toolbar.widgets] Configuration options for each widget to place on the\n * plot-level toolbar\n * @param {boolean} [layout.panel_boundaries=true] Whether to show interactive resize handles to change panel dimensions\n * @param {boolean} [layout.mouse_guide=true] Whether to always show horizontal and vertical dotted lines that intersect at the current location of the mouse pointer.\n * This line spans the entire plot area and is especially useful for plots with multiple panels.\n */\n constructor(id, datasource, layout) {\n /**\n * @private\n * @member Boolean}\n */\n this.initialized = false;\n\n /**\n * @private\n * @member {Plot}\n */\n this.parent_plot = this;\n\n /**\n * @public\n * @member {String}\n */\n this.id = id;\n\n /**\n * @private\n * @member {Element}\n */\n this.container = null;\n /**\n * Selector for a node that will contain the plot. (set externally by populate methods)\n * @private\n * @member {d3.selection}\n */\n this.svg = null;\n\n /**\n * Direct access to panel instances, keyed by panel ID. Used primarily for introspection/ development.\n * @public\n * @member {Object.}\n */\n this.panels = {};\n /**\n * TODO: This is currently used by external classes that manipulate the parent and may indicate room for a helper method in the api to coordinate boilerplate\n * @private\n * @member {String[]}\n */\n this.panel_ids_by_y_index = [];\n\n /**\n * Track update operations (reMap) performed on all child panels, and notify the parent plot when complete\n * TODO: Reconsider whether we need to be tracking this as global state outside of context of specific operations\n * @ignore\n * @protected\n * @member {Promise[]}\n */\n this.remap_promises = [];\n\n\n /**\n * The current layout options for the plot, including the effect of any resizing events or dynamically\n * generated config produced during rendering options.\n * @public\n * @type {Object}\n */\n this.layout = layout;\n merge(this.layout, default_layout); // TODO: evaluate how the default layout is applied\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original plot options.\n * This is useful for, eg, dynamically generated color schemes that need to start from scratch when new data is\n * loaded: it contains the \"defaults\", not just the result of a calculated value.\n * @ignore\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * Create a shortcut to the state in the layout on the Plot. Tracking in the layout allows the plot to be created\n * with initial state/setup.\n *\n * Tracks state of the plot, eg start and end position\n * @public\n * @member {Object}\n */\n this.state = this.layout.state;\n\n /**\n * @private\n * @member {Requester}\n */\n this.lzd = new Requester(datasource);\n\n /**\n * Track global event listeners that are used by LZ. This allows cleanup of listeners when plot is destroyed.\n * @private\n * @member {Map} A nested hash of entries: { parent: {event_name: [listeners] } }\n */\n this._external_listeners = new Map();\n\n /**\n * Known event hooks that the panel can respond to\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @protected\n * @member {Object}\n */\n this.event_hooks = {};\n\n /**\n * @callback eventCallback\n * @param {object} eventData A description of the event\n * @param {String|null} eventData.sourceID The unique identifier (eg plot or parent name) of the element that\n * triggered the event. Will be automatically filled in if not explicitly provided.\n * @param {Object|null} eventData.context Any additional information to be passed to the callback, eg the data\n * associated with a clicked plot element\n */\n\n /**\n * Event information describing interaction (e.g. panning and zooming) is stored on the plot\n * TODO: Add/ document details of interaction structure as we expand\n * @private\n * @member {{panel_id: String, linked_panel_ids: Array, x_linked: *, dragging: *, zooming: *}}\n * @returns {Plot}\n */\n this.interaction = {};\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* User-facing methods that allow manipulation of the plot instance: the public interface */\n\n /**\n * There are several events that a LocusZoom plot can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * To register a hook for any of these events use `plot.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered.\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of an event. Consult documentation for the names of built-in events.\n * @param {eventCallback} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n if (typeof event !== 'string') {\n throw new Error(`Unable to register event hook. Event name must be a string: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n if (!this.event_hooks[event]) {\n // We do not validate on known event names, because LZ is allowed to track and emit custom events like \"widget button clicked\".\n this.event_hooks[event] = [];\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Plot}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof event != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {string} event A known event name\n * @param {*} eventData Data or event description that will be passed to the event listener\n * @returns {Plot}\n */\n emit(event, eventData) {\n // TODO: there are small differences between the emit implementation between plots and panels. In the future,\n // DRY this code via mixins, and make sure to keep the interfaces compatible when refactoring.\n const these_hooks = this.event_hooks[event];\n if (typeof event != 'string') {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n } else if (!these_hooks && !this.event_hooks['any_lz_event']) {\n // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound?\n return this;\n }\n const sourceID = this.getBaseId();\n let eventContext;\n if (eventData && eventData.sourceID) {\n // If we detect that an event originated elsewhere (via bubbling or externally), preserve the context\n // when re-emitting the event to plot-level listeners\n eventContext = eventData;\n } else {\n eventContext = {sourceID: sourceID, target: this, data: eventData || null};\n }\n if (these_hooks) {\n // This event may have no hooks, but we could be passing by on our way to any_lz_event (below)\n these_hooks.forEach((hookToRun) => {\n // By default, any handlers fired here (either directly, or bubbled) will see the plot as the\n // value of `this`. If a bound function is registered as a handler, the previously bound `this` will\n // override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n }\n\n // At the plot level (only), all events will be re-emitted under the special name \"any_lz_event\"- a single place to\n // globally listen to every possible event.\n // This is not intended for direct use. It is for UI frameworks like Vue.js, which may need to wrap LZ\n // instances and proxy all events to their own declarative event system\n if (event !== 'any_lz_event') {\n const anyEventData = Object.assign({ event_name: event }, eventContext);\n this.emit('any_lz_event', anyEventData);\n }\n return this;\n }\n\n /**\n * Create a new panel from a layout, and handle the work of initializing and placing the panel on the plot\n * @public\n * @param {Object} layout\n * @returns {Panel}\n */\n addPanel(layout) {\n // Sanity checks\n if (typeof layout !== 'object') {\n throw new Error('Invalid panel layout');\n }\n\n // Create the Panel and set its parent\n const panel = new Panel(layout, this);\n\n // Store the Panel on the Plot\n this.panels[panel.id] = panel;\n\n // If a discrete y_index was set in the layout then adjust other panel y_index values to accommodate this one\n if (panel.layout.y_index !== null && !isNaN(panel.layout.y_index)\n && this.panel_ids_by_y_index.length > 0) {\n // Negative y_index values should count backwards from the end, so convert negatives to appropriate values here\n if (panel.layout.y_index < 0) {\n panel.layout.y_index = Math.max(this.panel_ids_by_y_index.length + panel.layout.y_index, 0);\n }\n this.panel_ids_by_y_index.splice(panel.layout.y_index, 0, panel.id);\n this.applyPanelYIndexesToPanelLayouts();\n } else {\n const length = this.panel_ids_by_y_index.push(panel.id);\n this.panels[panel.id].layout.y_index = length - 1;\n }\n\n // Determine if this panel was already in the layout.panels array.\n // If it wasn't, add it. Either way store the layout.panels array index on the panel.\n let layout_idx = null;\n this.layout.panels.forEach((panel_layout, idx) => {\n if (panel_layout.id === panel.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.panels.push(this.panels[panel.id].layout) - 1;\n }\n this.panels[panel.id].layout_idx = layout_idx;\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n this.positionPanels();\n // Initialize and load data into the new panel\n this.panels[panel.id].initialize();\n this.panels[panel.id].reMap();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this._total_height);\n }\n return this.panels[panel.id];\n }\n\n /**\n * Clear all state, tooltips, and other persisted data associated with one (or all) panel(s) in the plot\n *\n * This is useful when reloading an existing plot with new data, eg \"click for genome region\" links.\n * This is a utility method for custom usage. It is not fired automatically during normal rerender of existing panels\n * TODO: Is this method still necessary in modern usage? Hide from docs for now.\n * @public\n * @ignore\n * @param {String} [panelId] If provided, clear state for only this panel. Otherwise, clear state for all panels.\n * @param {('wipe'|'reset')} [mode='wipe'] Optionally specify how state should be cleared. `wipe` deletes all data\n * and is useful for when the panel is being removed; `reset` is best when the panel will be reused in place.\n * @returns {Plot}\n */\n clearPanelData(panelId, mode) {\n mode = mode || 'wipe';\n\n // TODO: Add unit tests for this method\n let panelsList;\n if (panelId) {\n panelsList = [panelId];\n } else {\n panelsList = Object.keys(this.panels);\n }\n\n panelsList.forEach((pid) => {\n this.panels[pid].data_layer_ids_by_z_index.forEach((dlid) => {\n const layer = this.panels[pid].data_layers[dlid];\n layer.destroyAllTooltips();\n\n delete layer.layer_state;\n delete this.layout.state[layer.state_id];\n if (mode === 'reset') {\n layer._setDefaultState();\n }\n });\n });\n return this;\n }\n\n /**\n * Remove the panel from the plot, and clear any state, tooltips, or other visual elements belonging to nested content\n * @public\n * @fires event:panel_removed\n * @param {String} id\n * @returns {Plot}\n */\n removePanel(id) {\n if (!this.panels[id]) {\n throw new Error(`Unable to remove panel, ID not found: ${id}`);\n }\n\n // Hide all panel boundaries\n this.panel_boundaries.hide();\n\n // Destroy all tooltips and state vars for all data layers on the panel\n this.clearPanelData(id);\n\n // Remove all panel-level HTML overlay elements\n this.panels[id].loader.hide();\n this.panels[id].toolbar.destroy(true);\n this.panels[id].curtain.hide();\n\n // Remove the svg container for the panel if it exists\n if (this.panels[id].svg.container) {\n this.panels[id].svg.container.remove();\n }\n\n // Delete the panel and its presence in the plot layout and state\n this.layout.panels.splice(this.panels[id].layout_idx, 1);\n delete this.panels[id];\n delete this.layout.state[id];\n\n // Update layout_idx values for all remaining panels\n this.layout.panels.forEach((panel_layout, idx) => {\n this.panels[panel_layout.id].layout_idx = idx;\n });\n\n // Remove the panel id from the y_index array\n this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(id), 1);\n this.applyPanelYIndexesToPanelLayouts();\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n this.positionPanels();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this._total_height);\n }\n\n this.emit('panel_removed', id);\n\n return this;\n }\n\n /**\n * Refresh (or fetch) a plot's data from sources, regardless of whether position or state has changed\n * @public\n * @returns {Promise}\n */\n refresh() {\n return this.applyState();\n }\n\n /**\n * A user-defined callback function that can receive (and potentially act on) new plot data.\n * @callback externalDataCallback\n * @param {Object} new_data The body resulting from a data request. This represents the same information that would be passed to\n * a data layer making an equivalent request.\n */\n\n /**\n * A user-defined callback function that can respond to errors received during a previous operation\n * @callback externalErrorCallback\n * @param err A representation of the error that occurred\n */\n\n /**\n * Allow newly fetched data to be made available outside the LocusZoom plot. For example, a callback could be\n * registered to draw an HTML table of top GWAS hits, and update that table whenever the plot region changes.\n *\n * This is a convenience method for external hooks. It registers an event listener and returns parsed data,\n * using the same fields syntax and underlying methods as data layers.\n *\n * @public\n * @listens event:data_rendered\n * @param {String[]} fields An array of field names and transforms, in the same syntax used by a data layer.\n * Different data sources should be prefixed by the namespace name.\n * @param {externalDataCallback} success_callback Used defined function that is automatically called any time that\n * new data is received by the plot. Receives two arguments: (data, plot).\n * @param {Object} [opts] Options\n * @param {externalErrorCallback} [opts.onerror] User defined function that is automatically called if a problem\n * occurs during the data request or subsequent callback operations\n * @param {boolean} [opts.discrete=false] Normally the callback will subscribe to the combined body from the chain,\n * which may not be in a format that matches what the external callback wants to do. If discrete=true, returns the\n * uncombined record info\n * @return {function} The newly created event listener, to allow for later cleanup/removal\n */\n subscribeToData(fields, success_callback, opts) {\n opts = opts || {};\n\n // Register an event listener that is notified whenever new data has been rendered\n const error_callback = opts.onerror || function (err) {\n console.log('An error occurred while acting on an external callback', err);\n };\n\n const listener = () => {\n try {\n this.lzd.getData(this.state, fields)\n .then((new_data) => success_callback(opts.discrete ? new_data.discrete : new_data.body, this))\n .catch(error_callback);\n } catch (error) {\n // In certain cases, errors are thrown before a promise can be generated, and LZ error display seems to rely on these errors bubbling up\n error_callback(error);\n }\n };\n this.on('data_rendered', listener);\n return listener;\n }\n\n /**\n * Update state values and trigger a pull for fresh data on all data sources for all data layers\n * @public\n * @param {Object} state_changes\n * @returns {Promise} A promise that resolves when all data fetch and update operations are complete\n * @listens event:match_requested\n * @fires event:data_requested\n * @fires event:layout_changed\n * @fires event:data_rendered\n * @fires event:state_changed\n * @fires event:region_changed\n */\n applyState(state_changes) {\n state_changes = state_changes || {};\n if (typeof state_changes != 'object') {\n throw new Error(`applyState only accepts an object; ${typeof state_changes} given`);\n }\n\n // Track what parameters will be modified. For bounds checking, we must take some preset values into account.\n let mods = { chr: this.state.chr, start: this.state.start, end: this.state.end };\n for (let property in state_changes) {\n mods[property] = state_changes[property];\n }\n mods = _updateStatePosition(mods, this.layout);\n\n // Apply new state to the actual state\n for (let property in mods) {\n this.state[property] = mods[property];\n }\n\n // Generate requests for all panels given new state\n this.emit('data_requested');\n this.remap_promises = [];\n this.loading_data = true;\n for (let id in this.panels) {\n this.remap_promises.push(this.panels[id].reMap());\n }\n\n return Promise.all(this.remap_promises)\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n this.loading_data = false;\n })\n .then(() => {\n // Update toolbar / widgets\n this.toolbar.update();\n\n // Apply panel-level state values\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.toolbar.update();\n // Apply data-layer-level state values\n panel.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n panel.data_layers[data_layer_id].applyAllElementStatus();\n });\n });\n\n // Emit events\n this.emit('layout_changed');\n this.emit('data_rendered');\n this.emit('state_changed', state_changes);\n\n // An interesting quirk of region changing in LZ: the final region is not always the same as the requested region\n // (example: zoom out beyond max, or request non-integer position)\n // Echo the actual plot region as the final source of truth\n const { chr, start, end } = this.state;\n const position_changed = Object.keys(state_changes)\n .some((key) => ['chr', 'start', 'end'].includes(key));\n\n if (position_changed) {\n this.emit('region_changed', { chr, start, end });\n }\n\n this.loading_data = false;\n });\n }\n\n /**\n * Keep a record of event listeners that are defined outside of the LocusZoom boundary (and therefore would not\n * get cleaned up when the plot was removed from the DOM). For example, window resize or mouse events.\n * This allows safe cleanup of the plot on removal from the page. This method is useful for authors of LocusZoom plugins.\n * @param {Node} target The node on which the listener has been defined\n * @param {String} event_name\n * @param {function} listener The handle for the event listener to be cleaned up\n */\n trackExternalListener(target, event_name, listener) {\n if (!this._external_listeners.has(target)) {\n this._external_listeners.set(target, new Map());\n }\n const container = this._external_listeners.get(target);\n\n const tracker = container.get(event_name) || [];\n if (!tracker.includes(listener)) {\n tracker.push(listener);\n }\n container.set(event_name, tracker);\n }\n\n /**\n * Remove the plot from the page, and clean up any globally registered event listeners\n *\n * Internally, the plot retains references to some nodes via selectors; it may be useful to delete the plot\n * instance after calling this method\n */\n destroy() {\n for (let [target, registered_events] of this._external_listeners.entries()) {\n for (let [event_name, listeners] of registered_events) {\n for (let listener of listeners) {\n target.removeEventListener(event_name, listener);\n }\n }\n }\n\n // Clear the SVG, plus other HTML nodes (like toolbar) that live under the same parent\n const parent = this.svg.node().parentNode;\n if (!parent) {\n throw new Error('Plot has already been removed');\n }\n while (parent.lastElementChild) {\n parent.removeChild(parent.lastElementChild);\n }\n // Clear toolbar event listeners defined on the parent lz-container. As of 2020 this appears to be the\n // state of the art cross-browser DOM API for this task.\n // eslint-disable-next-line no-self-assign\n parent.outerHTML = parent.outerHTML;\n\n this.initialized = false;\n\n this.svg = null;\n this.panels = null;\n }\n\n /******* The private interface: methods only used by LocusZoom internals */\n /**\n * Track whether the target panel can respond to mouse interaction events\n * @private\n * @param {String} panel_id\n * @returns {boolean}\n */\n _canInteract(panel_id) {\n panel_id = panel_id || null;\n if (panel_id) {\n return ((typeof this.interaction.panel_id == 'undefined' || this.interaction.panel_id === panel_id) && !this.loading_data);\n } else {\n return !(this.interaction.dragging || this.interaction.zooming || this.loading_data);\n }\n }\n\n /**\n * Get an object with the x and y coordinates of the plot's origin in terms of the entire page\n * This returns a result with absolute position relative to the page, regardless of current scrolling\n * Necessary for positioning any HTML elements over the plot\n * @private\n * @returns {{x: Number, y: Number, width: Number, height: Number}}\n */\n _getPageOrigin() {\n const bounding_client_rect = this.svg.node().getBoundingClientRect();\n let x_offset = document.documentElement.scrollLeft || document.body.scrollLeft;\n let y_offset = document.documentElement.scrollTop || document.body.scrollTop;\n let container = this.svg.node();\n while (container.parentNode !== null) {\n // TODO: Recursively seeks offsets for highest non-static parent node. This can lead to incorrect\n // calculations of, for example, x coordinate relative to the page. Revisit this logic.\n container = container.parentNode;\n if (container !== document && d3.select(container).style('position') !== 'static') {\n x_offset = -1 * container.getBoundingClientRect().left;\n y_offset = -1 * container.getBoundingClientRect().top;\n break;\n }\n }\n return {\n x: x_offset + bounding_client_rect.left,\n y: y_offset + bounding_client_rect.top,\n width: bounding_client_rect.width,\n height: bounding_client_rect.height,\n };\n }\n\n /**\n * Get the top and left offset values for the plot's container element (the div that was populated)\n * @private\n * @returns {{top: number, left: number}}\n */\n getContainerOffset() {\n const offset = { top: 0, left: 0 };\n let container = this.container.offsetParent || null;\n while (container !== null) {\n offset.top += container.offsetTop;\n offset.left += container.offsetLeft;\n container = container.offsetParent || null;\n }\n return offset;\n }\n\n /**\n * Notify each child panel of the plot of changes in panel ordering/ arrangement\n * @private\n */\n applyPanelYIndexesToPanelLayouts () {\n this.panel_ids_by_y_index.forEach((pid, idx) => {\n this.panels[pid].layout.y_index = idx;\n });\n }\n\n /**\n * Get the qualified ID pathname for the plot\n * @private\n * @returns {String}\n */\n getBaseId () {\n return this.id;\n }\n\n /**\n * Resize the plot to fit the bounding container\n * @private\n * @returns {Plot}\n */\n rescaleSVG() {\n const clientRect = this.svg.node().getBoundingClientRect();\n this.setDimensions(clientRect.width, clientRect.height);\n return this;\n }\n\n /**\n * Prepare the plot for first use by performing parameter validation, setting up panels, and calculating dimensions\n * @private\n * @returns {Plot}\n */\n initializeLayout() {\n\n // Sanity check layout values\n if (isNaN(this.layout.width) || this.layout.width <= 0) {\n throw new Error('Plot layout parameter `width` must be a positive number');\n }\n\n // Backwards compatible check: there was previously a third option. Anything truthy should thus act as \"responsive_resize: true\"\n this.layout.responsive_resize = !!this.layout.responsive_resize;\n\n // If this is a responsive layout then set a namespaced/unique onresize event listener on the window\n if (this.layout.responsive_resize) {\n const resize_listener = () => this.rescaleSVG();\n window.addEventListener('resize', resize_listener);\n this.trackExternalListener(window, 'resize', resize_listener);\n\n // Forcing one additional setDimensions() call after the page is loaded clears up\n // any disagreements between the initial layout and the loaded responsive container's size\n const load_listener = () => this.setDimensions();\n window.addEventListener('load', load_listener);\n this.trackExternalListener(window, 'load', load_listener);\n }\n\n // Add panels\n this.layout.panels.forEach((panel_layout) => {\n this.addPanel(panel_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for a plot, and ensure that panels are sized and positioned correctly.\n *\n * If dimensions are provided, resizes each panel proportionally to match the new plot dimensions. Otherwise,\n * calculates the appropriate plot dimensions based on all panels, and ensures that panels are placed and\n * rendered in the correct relative positions.\n * @private\n * @param {Number} [width] If provided and larger than minimum allowed size, set plot to this width\n * @param {Number} [height] If provided and larger than minimum allowed size, set plot to this height\n * @returns {Plot}\n * @fires event:layout_changed\n */\n setDimensions(width, height) {\n // If width and height arguments were passed, then adjust plot dimensions to fit all panels\n // Then resize the plot and proportionally resize panels to fit inside the new plot dimensions.\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n // Resize operations may ask for a different amount of space than that used by panels.\n const height_scaling_factor = height / this._total_height;\n\n this.layout.width = Math.max(Math.round(+width), this.layout.min_width);\n // Override discrete values if resizing responsively\n if (this.layout.responsive_resize) {\n // All resize modes will affect width\n if (this.svg) {\n this.layout.width = Math.max(this.svg.node().parentNode.getBoundingClientRect().width, this.layout.min_width);\n }\n }\n // Resize/reposition panels to fit, update proportional origins if necessary\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n const panel_width = this.layout.width;\n // In this block, we are passing explicit dimensions that might require rescaling all panels at once\n const panel_height = panel.layout.height * height_scaling_factor;\n panel.setDimensions(panel_width, panel_height);\n panel.setOrigin(0, y_offset);\n y_offset += panel_height;\n panel.toolbar.update();\n });\n }\n\n // Set the plot height to the sum of all panels (using the \"real\" height values accounting for panel.min_height)\n const final_height = this._total_height;\n\n // Apply layout width and height as discrete values or viewbox values\n if (this.svg !== null) {\n // The viewBox must always be specified in order for \"save as image\" button to work\n this.svg.attr('viewBox', `0 0 ${this.layout.width} ${final_height}`);\n\n this.svg\n .attr('width', this.layout.width)\n .attr('height', final_height);\n }\n\n // If the plot has been initialized then trigger some necessary render functions\n if (this.initialized) {\n this.panel_boundaries.position();\n this.toolbar.update();\n this.curtain.update();\n this.loader.update();\n }\n\n return this.emit('layout_changed');\n }\n\n /**\n * Automatically position panels based on panel positioning rules and values.\n * Keep panels from overlapping vertically by adjusting origins, and keep the sum of proportional heights at 1.\n *\n * LocusZoom panels can only be stacked vertically (not horizontally)\n * @private\n */\n positionPanels() {\n // We want to enforce that all x-linked panels have consistent horizontal margins\n // (to ensure that aligned items stay aligned despite inconsistent initial layout parameters)\n // NOTE: This assumes panels have consistent widths already. That should probably be enforced too!\n const x_linked_margins = { left: 0, right: 0 };\n\n // Proportional heights for newly added panels default to null unless explicitly set, so determine appropriate\n // proportional heights for all panels with a null value from discretely set dimensions.\n // Likewise handle default nulls for proportional widths, but instead just force a value of 1 (full width)\n for (let id in this.panels) {\n if (this.panels[id].layout.interaction.x_linked) {\n x_linked_margins.left = Math.max(x_linked_margins.left, this.panels[id].layout.margin.left);\n x_linked_margins.right = Math.max(x_linked_margins.right, this.panels[id].layout.margin.right);\n }\n }\n\n // Update origins on all panels without changing plot-level dimensions yet\n // Also apply x-linked margins to x-linked panels, updating widths as needed\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.setOrigin(0, y_offset);\n y_offset += this.panels[panel_id].layout.height;\n if (panel.layout.interaction.x_linked) {\n const delta = Math.max(x_linked_margins.left - panel.layout.margin.left, 0)\n + Math.max(x_linked_margins.right - panel.layout.margin.right, 0);\n panel.layout.width += delta;\n panel.layout.margin.left = x_linked_margins.left;\n panel.layout.margin.right = x_linked_margins.right;\n panel.layout.cliparea.origin.x = x_linked_margins.left;\n }\n });\n\n // Update dimensions on the plot to accommodate repositioned panels (eg when resizing one panel,\n // also must update the plot dimensions)\n this.setDimensions();\n\n // Set dimensions on all panels using newly set plot-level dimensions and panel-level proportional dimensions\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.setDimensions(\n this.layout.width,\n panel.layout.height\n );\n });\n\n return this;\n }\n\n /**\n * Prepare the first rendering of the plot. This includes initializing the individual panels, but also creates shared\n * elements such as mouse events, panel guides/boundaries, and loader/curtain.\n * @private\n * @returns {Plot}\n */\n initialize() {\n\n // Ensure proper responsive class is present on the containing node if called for\n if (this.layout.responsive_resize) {\n d3.select(this.container).classed('lz-container-responsive', true);\n }\n\n // Create an element/layer for containing mouse guides\n if (this.layout.mouse_guide) {\n const mouse_guide_svg = this.svg.append('g')\n .attr('class', 'lz-mouse_guide')\n .attr('id', `${this.id}.mouse_guide`);\n const mouse_guide_vertical_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-vertical')\n .attr('x', -1);\n const mouse_guide_horizontal_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-horizontal')\n .attr('y', -1);\n this.mouse_guide = {\n svg: mouse_guide_svg,\n vertical: mouse_guide_vertical_svg,\n horizontal: mouse_guide_horizontal_svg,\n };\n }\n\n // Add curtain and loader prototpyes to the plot\n this.curtain = generateCurtain.call(this);\n this.loader = generateLoader.call(this);\n\n // Create the panel_boundaries object with show/position/hide methods\n this.panel_boundaries = {\n parent: this,\n hide_timeout: null,\n showing: false,\n dragging: false,\n selectors: [],\n corner_selector: null,\n show: function() {\n // Generate panel boundaries\n if (!this.showing && !this.parent.curtain.showing) {\n this.showing = true;\n // Loop through all panels to create a horizontal boundary for each\n this.parent.panel_ids_by_y_index.forEach((panel_id, panel_idx) => {\n const selector = d3.select(this.parent.svg.node().parentNode).insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-boundary')\n .attr('title', 'Resize panel');\n selector.append('span');\n const panel_resize_drag = d3.drag();\n panel_resize_drag.on('start', () => {\n this.dragging = true;\n });\n panel_resize_drag.on('end', () => {\n this.dragging = false;\n });\n panel_resize_drag.on('drag', () => {\n // First set the dimensions on the panel we're resizing\n const this_panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]];\n const original_panel_height = this_panel.layout.height;\n this_panel.setDimensions(this.parent.layout.width, this_panel.layout.height + d3.event.dy);\n const panel_height_change = this_panel.layout.height - original_panel_height;\n // Next loop through all panels.\n // Update proportional dimensions for all panels including the one we've resized using discrete heights.\n // Reposition panels with a greater y-index than this panel to their appropriate new origin.\n this.parent.panel_ids_by_y_index.forEach((loop_panel_id, loop_panel_idx) => {\n const loop_panel = this.parent.panels[this.parent.panel_ids_by_y_index[loop_panel_idx]];\n if (loop_panel_idx > panel_idx) {\n loop_panel.setOrigin(loop_panel.layout.origin.x, loop_panel.layout.origin.y + panel_height_change);\n loop_panel.toolbar.position();\n }\n });\n // Reset dimensions on the entire plot and reposition panel boundaries\n this.parent.positionPanels();\n this.position();\n });\n selector.call(panel_resize_drag);\n this.parent.panel_boundaries.selectors.push(selector);\n });\n // Create a corner boundary / resize element on the bottom-most panel that resizes the entire plot\n const corner_selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-corner-boundary')\n .attr('title', 'Resize plot');\n\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-outer');\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-inner');\n\n const corner_drag = d3.drag();\n corner_drag.on('start', () => {\n this.dragging = true;\n });\n corner_drag.on('end', () => {\n this.dragging = false;\n });\n corner_drag.on('drag', () => {\n this.parent.setDimensions(this.parent.layout.width + d3.event.dx, this.parent._total_height + d3.event.dy);\n });\n corner_selector.call(corner_drag);\n this.parent.panel_boundaries.corner_selector = corner_selector;\n }\n return this.position();\n },\n position: function() {\n if (!this.showing) {\n return this;\n }\n // Position panel boundaries\n const plot_page_origin = this.parent._getPageOrigin();\n this.selectors.forEach((selector, panel_idx) => {\n const panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]];\n const panel_page_origin = panel._getPageOrigin();\n const left = plot_page_origin.x;\n const top = panel_page_origin.y + panel.layout.height - 12;\n const width = this.parent.layout.width - 1;\n selector\n .style('top', `${top}px`)\n .style('left', `${left}px`)\n .style('width', `${width}px`);\n selector.select('span')\n .style('width', `${width}px`);\n });\n // Position corner selector\n const corner_padding = 10;\n const corner_size = 16;\n this.corner_selector\n .style('top', `${plot_page_origin.y + this.parent._total_height - corner_padding - corner_size}px`)\n .style('left', `${plot_page_origin.x + this.parent.layout.width - corner_padding - corner_size}px`);\n return this;\n },\n hide: function() {\n if (!this.showing) {\n return this;\n }\n this.showing = false;\n // Remove panel boundaries\n this.selectors.forEach((selector) => {\n selector.remove();\n });\n this.selectors = [];\n // Remove corner boundary\n this.corner_selector.remove();\n this.corner_selector = null;\n return this;\n },\n };\n\n // Show panel boundaries stipulated by the layout (basic toggle, only show on mouse over plot)\n if (this.layout.panel_boundaries) {\n d3.select(this.svg.node().parentNode)\n .on(`mouseover.${this.id}.panel_boundaries`, () => {\n clearTimeout(this.panel_boundaries.hide_timeout);\n this.panel_boundaries.show();\n })\n .on(`mouseout.${this.id}.panel_boundaries`, () => {\n this.panel_boundaries.hide_timeout = setTimeout(() => {\n this.panel_boundaries.hide();\n }, 300);\n });\n }\n\n // Create the toolbar object and immediately show it\n this.toolbar = new Toolbar(this).show();\n\n // Initialize all panels\n for (let id in this.panels) {\n this.panels[id].initialize();\n }\n\n // Define plot-level mouse events\n const namespace = `.${this.id}`;\n if (this.layout.mouse_guide) {\n const mouseout_mouse_guide = () => {\n this.mouse_guide.vertical.attr('x', -1);\n this.mouse_guide.horizontal.attr('y', -1);\n };\n const mousemove_mouse_guide = () => {\n const coords = d3.mouse(this.svg.node());\n this.mouse_guide.vertical.attr('x', coords[0]);\n this.mouse_guide.horizontal.attr('y', coords[1]);\n };\n this.svg\n .on(`mouseout${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`touchleave${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`mousemove${namespace}-mouse_guide`, mousemove_mouse_guide);\n }\n const mouseup = () => {\n this.stopDrag();\n };\n const mousemove = () => {\n if (this.interaction.dragging) {\n const coords = d3.mouse(this.svg.node());\n if (d3.event) {\n d3.event.preventDefault();\n }\n this.interaction.dragging.dragged_x = coords[0] - this.interaction.dragging.start_x;\n this.interaction.dragging.dragged_y = coords[1] - this.interaction.dragging.start_y;\n this.panels[this.interaction.panel_id].render();\n this.interaction.linked_panel_ids.forEach((panel_id) => {\n this.panels[panel_id].render();\n });\n }\n };\n this.svg\n .on(`mouseup${namespace}`, mouseup)\n .on(`touchend${namespace}`, mouseup)\n .on(`mousemove${namespace}`, mousemove)\n .on(`touchmove${namespace}`, mousemove);\n\n // Add an extra namespaced mouseup handler to the containing body, if there is one\n // This helps to stop interaction events gracefully when dragging outside of the plot element\n const body_selector = d3.select('body');\n const body_node = body_selector.node();\n if (body_node) {\n body_node.addEventListener('mouseup', mouseup);\n body_node.addEventListener('touchend', mouseup);\n\n this.trackExternalListener(body_node, 'mouseup', mouseup);\n this.trackExternalListener(body_node, 'touchend', mouseup);\n }\n\n this.on('match_requested', (eventData) => {\n // Layers can broadcast that a specific point has been selected, and the plot will tell every other layer\n // to look for that value. Whenever a point is de-selected, it clears the match.\n const data = eventData.data;\n const to_send = (data.active ? data.value : null);\n const emitted_by = eventData.target.id;\n // When a match is initiated, hide all tooltips from other panels (prevents zombie tooltips from reopening)\n // TODO: This is a bit hacky. Right now, selection and matching are tightly coupled, and hence tooltips\n // reappear somewhat aggressively. A better solution depends on designing alternative behavior, and\n // applying tooltips post (instead of pre) render.\n Object.values(this.panels).forEach((panel) => {\n if (panel.id !== emitted_by) {\n Object.values(panel.data_layers).forEach((layer) => layer.destroyAllTooltips(false));\n }\n });\n\n this.applyState({ lz_match_value: to_send });\n });\n\n this.initialized = true;\n\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n const client_rect = this.svg.node().getBoundingClientRect();\n const width = client_rect.width ? client_rect.width : this.layout.width;\n const height = client_rect.height ? client_rect.height : this._total_height;\n this.setDimensions(width, height);\n\n return this;\n }\n\n /**\n * Register interactions along the specified axis, provided that the target panel allows interaction.\n * @private\n * @param {Panel} panel\n * @param {('background'|'x_tick'|'y1_tick'|'y2_tick')} method The direction (axis) along which dragging is being performed.\n * @returns {Plot}\n */\n startDrag(panel, method) {\n panel = panel || null;\n method = method || null;\n\n let axis = null;\n switch (method) {\n case 'background':\n case 'x_tick':\n axis = 'x';\n break;\n case 'y1_tick':\n axis = 'y1';\n break;\n case 'y2_tick':\n axis = 'y2';\n break;\n }\n\n if (!(panel instanceof Panel) || !axis || !this._canInteract()) {\n return this.stopDrag();\n }\n\n const coords = d3.mouse(this.svg.node());\n this.interaction = {\n panel_id: panel.id,\n linked_panel_ids: panel.getLinkedPanelIds(axis),\n dragging: {\n method: method,\n start_x: coords[0],\n start_y: coords[1],\n dragged_x: 0,\n dragged_y: 0,\n axis: axis,\n },\n };\n\n this.svg.style('cursor', 'all-scroll');\n\n return this;\n }\n\n /**\n * Process drag interactions across the target panel and synchronize plot state across other panels in sync;\n * clear the event when complete\n * @private\n * @returns {Plot}\n */\n stopDrag() {\n\n if (!this.interaction.dragging) {\n return this;\n }\n\n if (typeof this.panels[this.interaction.panel_id] != 'object') {\n this.interaction = {};\n return this;\n }\n const panel = this.panels[this.interaction.panel_id];\n\n // Helper function to find the appropriate axis layouts on child data layers\n // Once found, apply the extent as floor/ceiling and remove all other directives\n // This forces all associated axes to conform to the extent generated by a drag action\n const overrideAxisLayout = (axis, axis_number, extent) => {\n panel.data_layer_ids_by_z_index.forEach((id) => {\n const axis_layout = panel.data_layers[id].layout[`${axis}_axis`];\n if (axis_layout.axis === axis_number) {\n axis_layout.floor = extent[0];\n axis_layout.ceiling = extent[1];\n delete axis_layout.lower_buffer;\n delete axis_layout.upper_buffer;\n delete axis_layout.min_extent;\n delete axis_layout.ticks;\n }\n });\n };\n\n switch (this.interaction.dragging.method) {\n case 'background':\n case 'x_tick':\n if (this.interaction.dragging.dragged_x !== 0) {\n overrideAxisLayout('x', 1, panel.x_extent);\n this.applyState({ start: panel.x_extent[0], end: panel.x_extent[1] });\n }\n break;\n case 'y1_tick':\n case 'y2_tick':\n if (this.interaction.dragging.dragged_y !== 0) {\n const y_axis_number = parseInt(this.interaction.dragging.method[1]);\n overrideAxisLayout('y', y_axis_number, panel[`y${y_axis_number}_extent`]);\n }\n break;\n }\n\n this.interaction = {};\n this.svg.style('cursor', null);\n\n return this;\n\n }\n\n get _total_height() {\n // The plot height is a calculated property, derived from the sum of its panel layout objects\n return this.layout.panels.reduce((acc, item) => item.height + acc, 0);\n }\n}\n\nexport {Plot as default};\n\n// Only for testing\nexport { _updateStatePosition };\n","/**\n * \"Match\" test functions used to compare two values for filtering (what to render) and matching\n * (comparison and finding related points across data layers)\n *\n * ### How do matching and filtering work?\n * See the Interactivity Tutorial for details.\n *\n * ## Adding a new function\n * LocusZoom allows users to write their own plugins, so that \"does this point match\" logic can incorporate\n * user-defined code. (via `LocusZoom.MatchFunctions.add('my_function', my_function);`)\n *\n * All \"matcher\" functions have the call signature (item_value, target_value) => {boolean}\n *\n * Both filtering and matching depend on asking \"is this field interesting to me\", which is inherently a problem of\n * making comparisons. The registry allows any arbitrary function (with a field value as the first argument), but that\n * function doesn't have to use either argument.\n *\n * @module LocusZoom_MatchFunctions\n */\nimport {RegistryBase} from './base';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided \"match\" functions, used by filtering and matching behavior.\n * @alias module:LocusZoom~MatchFunctions\n * @type {module:registry/base~RegistryBase}\n */\nconst registry = new RegistryBase();\n\n// Most of the filter syntax uses things that are JS reserved operators. Instead of exporting symbols from another\n// module, just define and register them here.\n\n/**\n * Check if two values are (strictly) equal\n * @function\n * @name '='\n * @param item_value\n * @param target_value\n */\nregistry.add('=', (item_value, target_value) => item_value === target_value);\n\n/**\n * Check if two values are not equal. This allows weak comparisons (eg undefined/null), so it can also be used to test for the absence of a value\n * @function\n * @name '!='\n * @param item_value\n * @param target_value\n */\n// eslint-disable-next-line eqeqeq\nregistry.add('!=', (a, b) => a != b); // For absence of a value, deliberately allow weak comparisons (eg undefined/null)\n\n/**\n * Less-than comparison\n * @function\n * @name '<'\n * @param item_value\n * @param target_value\n */\nregistry.add('<', (a, b) => a < b);\n\n/**\n * Less than or equals to comparison\n * @function\n * @name '<='\n * @param item_value\n * @param target_value\n */\nregistry.add('<=', (a, b) => a <= b);\n\n/**\n * Greater-than comparison\n * @function\n * @name '>'\n * @param item_value\n * @param target_value\n */\nregistry.add('>', (a, b) => a > b);\n\n/**\n * Greater than or equals to comparison\n * @function\n * @name '>='\n * @param item_value\n * @param target_value\n */\nregistry.add('>=', (a, b) => a >= b);\n\n/**\n * Modulo: tests for whether the remainder a % b is nonzero\n * @function\n * @name '%'\n * @param item_value\n * @param target_value\n */\nregistry.add('%', (a, b) => a % b);\n\n/**\n * Check whether the provided value (a) is in the string or array of values (b)\n *\n * This can be used to check if a field value is one of a set of predefined choices\n * Eg, `gene_type` is one of the allowed types of interest\n * @function\n * @name 'in'\n * @param item_value A scalar value\n * @param {String|Array} target_value A container that implements the `includes` method\n */\nregistry.add('in', (a, b) => b && b.includes(a));\n\n/**\n * Partial-match function. Can be used for free text search (\"find all gene names that contain the user-entered string 'TCF'\")\n * @function\n * @name 'match'\n * @param {String|Array} item_value A container (like a string) that implements the `includes` method\n * @param target_value A scalar value, like a string\n */\nregistry.add('match', (a, b) => a && a.includes(b)); // useful for text search: \"find all gene names that contain the user-entered value HLA\"\n\n\nexport default registry;\n","/**\n * Plugin registry of available functions that can be used in scalable layout directives.\n *\n * These \"scale functions\" are used during rendering to return output (eg color) based on input value\n *\n * @module LocusZoom_ScaleFunctions\n * @see {@link module:LocusZoom_DataLayers~ScalableParameter} for details on how scale functions are used by datalayers\n */\n\nimport * as d3 from 'd3';\n\n/**\n * Basic conditional function to evaluate the value of the input field and return based on equality.\n * @alias module:LocusZoom_ScaleFunctions~if\n * @param {Object} parameters\n * @param {*} parameters.field_value The value against which to test the input value.\n * @param {*} parameters.then The value to return if the input value matches the field value\n * @param {*} parameters.else The value to return if the input value does not match the field value. Optional. If not\n * defined this scale function will return null (or value of null_value parameter, if defined) when input value fails\n * to match field_value.\n * @param {*} input value\n */\nconst if_value = (parameters, input) => {\n if (typeof input == 'undefined' || parameters.field_value !== input) {\n if (typeof parameters.else != 'undefined') {\n return parameters.else;\n } else {\n return null;\n }\n } else {\n return parameters.then;\n }\n};\n\n/**\n * Function to sort numerical values into bins based on numerical break points. Will only operate on numbers and\n * return null (or value of null_value parameter, if defined) if provided a non-numeric input value. Parameters:\n * @function numerical_bin\n * @param {Object} parameters\n * @param {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter. If the input value is greater than or equal to break n and less than\n * or equal to break n+1 (or break n+1 doesn't exist) then returned value is the nth entry in the values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against break points. Must be of\n * equal length to breaks parameter. Each entry n represents the value to return if the input value is greater than\n * or equal to break n and less than or equal to break n+1 (or break n+1 doesn't exist).\n * @param {*} parameters.null_value\n * @param {*} input value\n * @returns {*}\n */\nconst numerical_bin = (parameters, input) => {\n const breaks = parameters.breaks || [];\n const values = parameters.values || [];\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return (parameters.null_value ? parameters.null_value : null);\n }\n const threshold = breaks.reduce(function (prev, curr) {\n if (+input < prev || (+input >= prev && +input < curr)) {\n return prev;\n } else {\n return curr;\n }\n });\n return values[breaks.indexOf(threshold)];\n};\n\n/**\n * Function to sort values of any type into bins based on direct equality testing with a list of categories.\n * Will return null if provided an input value that does not match to a listed category.\n * @function categorical_bin\n * @param {Object} parameters\n * @param {Array} parameters.categories Array of values against which to evaluate the input value. Must be of equal\n * length to values parameter. If the input value is equal to category n then returned value is the nth entry in the\n * values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against categories. Must be of equal\n * length to categories parameter. Each entry n represents the value to return if the input value is equal to the nth\n * value in the categories parameter.\n * @param {*} parameters.null_value Value to return if the input value fails to match to any categories. Optional.\n */\nconst categorical_bin = (parameters, value) => {\n if (typeof value == 'undefined' || !parameters.categories.includes(value)) {\n return (parameters.null_value ? parameters.null_value : null);\n } else {\n return parameters.values[parameters.categories.indexOf(value)];\n }\n};\n\n/**\n * Cycle through a set of options, so that the each element in a set of data receives a value different than the\n * element before it. For example: \"use this palette of 10 colors to visually distinguish 100 adjacent items\"\n * This is useful when ADJACENT items must be guaranteed to yield a different result, but it leads to unstable color\n * choices if the user pans to a region with a different number/order of items. (the same item is assigned a different color)\n *\n * See also: stable_choice.\n * @param {Object} parameters\n * @param {Array} parameters.values A list of option values\n * @return {*}\n */\nconst ordinal_cycle = (parameters, value, index) => {\n const options = parameters.values;\n return options[index % options.length];\n};\n\n/**\n * A scale function that auto-chooses something (like color) from a preset scheme, and makes the same choice every\n * time given the same value, regardless of ordering or what other data is in the region\n *\n * This is useful when categories must be stable (same color, every time). But sometimes it will assign adjacent values\n * the same color due to hash collisions.\n *\n * For performance reasons, this is memoized once per instance. Eg, each scalable color parameter has its own cache.\n * This function is therefore slightly less amenable to layout mutations like \"changing the options after scaling\n * function is used\", but this is not expected to be a common use case.\n *\n * CAVEAT: Some datasets do not return true datum ids, but instead append synthetic ID fields (\"item 1, item2\"...)\n * just to appease D3. This hash function only works if there is a meaningful, stable identifier in the data,\n * like a category or gene name.\n * @param parameters\n * @param {Array} [parameters.values] A list of options to choose from\n * @param {Number} [parameters.max_cache_size=500] The maximum number of values to cache. This option is mostly used\n * for unit testing, because stable choice is intended for datasets with a relatively limited number of\n * discrete categories.\n * @param value\n * @param index\n */\nlet stable_choice = (parameters, value, index) => {\n // Each place the function gets used has its own parameters object. This function thus memoizes per usage\n // (\"association - point color - directive 1\") rather than globally (\"all properties/panels\")\n const cache = parameters._cache = parameters._cache || new Map();\n const max_cache_size = parameters.max_cache_size || 500;\n\n if (cache.size >= max_cache_size) {\n // Prevent cache from growing out of control (eg as user moves between regions a lot)\n cache.clear();\n }\n if (cache.has(value)) {\n return cache.get(value);\n }\n\n // Simple JS hashcode implementation, from:\n // https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript\n let hash = 0;\n value = String(value);\n for (let i = 0; i < value.length; i++) {\n let chr = value.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n // Convert signed 32 bit integer to be within the range of options allowed\n const options = parameters.values;\n const result = options[Math.abs(hash) % options.length];\n cache.set(value, result);\n return result;\n};\n\n/**\n * Function for continuous interpolation of numerical values along a gradient with arbitrarily many break points.\n * @function interpolate\n * @parameters {Object} parameters\n * @parameters {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter and contain at least two elements. Input value will be evaluated for\n * relative position between two break points n and n+1 and the returned value will be interpolated at a relative\n * position between values n and n+1.\n * @parameters {*[]} parameters.values Array of values to interpolate and return given evaluations against break\n * points. Must be of equal length to breaks parameter and contain at least two elements. Each entry n represents\n * the value to return if the input value matches the nth entry in breaks exactly. Note that this scale function\n * uses d3.interpolate to provide for effective interpolation of many different value types, including numbers,\n * colors, shapes, etc.\n * @parameters {*} parameters.null_value\n */\nconst interpolate = (parameters, input) => {\n var breaks = parameters.breaks || [];\n var values = parameters.values || [];\n var nullval = (parameters.null_value ? parameters.null_value : null);\n if (breaks.length < 2 || breaks.length !== values.length) {\n return nullval;\n }\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return nullval;\n }\n if (+input <= parameters.breaks[0]) {\n return values[0];\n } else if (+input >= parameters.breaks[parameters.breaks.length - 1]) {\n return values[breaks.length - 1];\n } else {\n var upper_idx = null;\n breaks.forEach(function (brk, idx) {\n if (!idx) {\n return;\n }\n if (breaks[idx - 1] <= +input && breaks[idx] >= +input) {\n upper_idx = idx;\n }\n });\n if (upper_idx === null) {\n return nullval;\n }\n const normalized_input = (+input - breaks[upper_idx - 1]) / (breaks[upper_idx] - breaks[upper_idx - 1]);\n if (!isFinite(normalized_input)) {\n return nullval;\n }\n return d3.interpolate(values[upper_idx - 1], values[upper_idx])(normalized_input);\n }\n};\n\n\nexport { categorical_bin, stable_choice, if_value, interpolate, numerical_bin, ordinal_cycle };\n","/**\n * Functions that control \"scalable\" layout directives: given a value (like a number) return another value\n * (like a color, size, or shape) that governs how something is displayed\n *\n * All scale functions have the call signature `(layout_parameters, input) => result|null`\n * @module\n * @private\n */\nimport {RegistryBase} from './base';\nimport * as scalable from '../helpers/scalable';\n\n\nconst registry = new RegistryBase();\nfor (let [name, type] of Object.entries(scalable)) {\n registry.add(name, type);\n}\n\n// Alias for the \"if_value\" function (can't export reserved language keywords directly)\nregistry.add('if', scalable.if_value);\n\n\nexport default registry;\n","/**\n * Data layers represent instructions for how to render common types of information.\n * (GWAS scatter plot, nearby genes, straight lines and filled curves, etc)\n *\n * Each rendering type also provides helpful functionality such as filtering, matching, and interactive tooltip\n * display. Predefined layers can be extended or customized, with many configurable options.\n *\n * @module LocusZoom_DataLayers\n */\n\nimport * as d3 from 'd3';\n\nimport {STATUSES} from '../constants';\nimport Field from '../../data/field';\nimport {parseFields} from '../../helpers/display';\nimport {deepCopy, merge} from '../../helpers/layouts';\nimport MATCHERS from '../../registry/matchers';\nimport SCALABLE from '../../registry/scalable';\n\n\n/**\n * \"Scalable\" parameters indicate that a datum can be rendered in custom ways based on its value. (color, size, shape, etc)\n *\n * This means that if the value of this property is a scalar, it is used directly (`color: '#FF0000'`). But if the\n * value is an array of options, each will be evaluated in turn until the first non-null result is found. The syntax\n * below describes how each member of the array should specify the field and scale function to be used.\n * Often, the last item in the list is a string, providing a \"default\" value if all scale functions evaluate to null.\n *\n * @typedef {object[]|string} ScalableParameter\n * @property {string} [field] The name of the field to use in the scale function. If omitted, all fields for the given\n * datum element will be passed to the scale function.\n * @property {module:LocusZoom_ScaleFunctions} scale_function The name of a scale function that will be run on each individual datum\n * @property {object} parameters A set of parameters that configure the desired scale function (options vary by function)\n */\n\n\n/**\n * @typedef {Object} module:LocusZoom_DataLayers~behavior\n * @property {'set'|'unset'|'toggle'|'link'} action\n * @property {'highlighted'|'selected'|'faded'|'hidden'} status An element display status to set/unset/toggle\n * @property {boolean} exclusive Whether an element status should be exclusive (eg only allow one point to be selected at a time)\n * @property {string} href For links, the URL to visit when clicking\n * @property {string} target For links, the `target` attribute (eg, name of a window or tab in which to open this link)\n */\n\n\n/**\n * @typedef {object} FilterOption\n * @property {string} field The name of a field found within each datapoint datum\n * @property {module:LocusZoom_MatchFunctions} operator The name of a comparison function to use when deciding if the\n * field satisfies this filter\n * @property value The target value to compare to\n */\n\n\n/**\n * @typedef {object} LegendItem\n * @property [shape] This is optional (e.g. a legend element could just be a textual label).\n * Supported values are the standard d3 3.x symbol types (i.e. \"circle\", \"cross\", \"diamond\", \"square\",\n * \"triangle-down\", and \"triangle-up\"), as well as \"rect\" for an arbitrary square/rectangle or line for a path.\n * @property {string} color The point color (hexadecimal, rgb, etc)\n * @property {string} label The human-readable label of the legend item\n * @property {string} [class] The name of a CSS class used to style the point in the legend\n * @property {number} [size] The point area for each element (if the shape is a d3 symbol). Eg, for a 40 px area,\n * a circle would be ~7..14 px in diameter.\n * @property {number} [length] Length (in pixels) for the path rendered as the graphical portion of the legend element\n * if the value of the shape parameter is \"line\".\n * @property {number} [width] Width (in pixels) for the rect rendered as the graphical portion of the legend element if\n * the value of the shape parameter is \"rect\".\n * @property {number} [height] Height (in pixels) for the rect rendered as the graphical portion of the legend element if\n * the value of the shape parameter is \"rect\".\n * @property {object} style CSS styles object to be applied to the DOM element representing the graphical portion of\n * the legend element.\n */\n\n\n/**\n * A basic description of keys expected in all data layer layouts. Not intended to be directly used or modified by an end user.\n * @memberof module:LocusZoom_DataLayers~BaseDataLayer\n * @protected\n * @type {{type: string, fields: Array, x_axis: {}, y_axis: {}}}\n */\nconst default_layout = {\n id: '',\n type: '',\n tag: 'custom_data_type',\n fields: [],\n id_field: 'id',\n filters: null,\n match: {},\n x_axis: {},\n y_axis: {}, // Axis options vary based on data layer type\n legend: null,\n tooltip: {},\n tooltip_positioning: 'horizontal', // Where to draw tooltips relative to the point. Can be \"vertical\" or \"horizontal\"\n behaviors: {},\n};\n\n/**\n * A data layer is an abstract class representing a data set and its graphical representation within a panel\n * @public\n*/\nclass BaseDataLayer {\n /**\n * @param {string} [layout.id=''] An identifier string that must be unique across all layers within the same panel\n * @param {string} [layout.type=''] The type of data layer. This parameter is used in layouts to specify which class\n * (from the registry) is created; it is also used in CSS class names.\n * @param {string} [layout.tag='custom_data_type'] Tags have no functional purpose, but they can be used\n * as a semantic label for what is being displayed in this element. This makes it easy to write custom code like \"find every data\n * layer that shows association scatter plots, anywhere\": even if the IDs are different, the tag can be the same.\n * Most built-in data layers will contain a tag that describes, in human-readable terms, what kind of data is being shown.\n * (see: {@link LayoutRegistry.mutate_attrs})\n * @param {String[]} layout.fields A list of (namespaced) fields specifying what data is used by the layer. Only\n * these fields will be made available to the data layer, and only data sources (namespaces) referred to in\n * this array will be fetched. This represents the \"contract\" between what data is returned and what data is rendered.\n * This fields array works in concert with the data retrieval method BaseAdapter.extractFields.\n * @param {string} [layout.id_field] The datum field used for unique element IDs when addressing DOM elements, mouse\n * events, etc. This should be unique to the specified datum.\n * @param {module:LocusZoom_DataLayers~FilterOption[]} [layout.filters] If present, restricts the list of data elements to be displayed. Typically, filters\n * hide elements, but arrange the layer so as to leave the space those elements would have occupied. The exact\n * details vary from one layer to the next. See the Interactivity Tutorial for details.\n * @param {object} [layout.match] An object describing how to connect this data layer to other data layers in the\n * same plot. Specifies keys `send` and `receive` containing the names of fields with data to be matched;\n * `operator` specifies the name of a MatchFunction to use. If a datum matches the broadcast value, it will be\n * marked with the special field `lz_is_match=true`, which can be used in any scalable layout directive to control how the item is rendered.\n * @param {boolean} [layout.x_axis.decoupled=false] If true, the data in this layer will not influence the x-extent of the panel.\n * @param {'state'|null} [layout.x_axis.extent] If provided, the region plot x-extent will be determined from\n * `plot.state` rather than from the range of the data. This is the most common way of setting x-extent,\n * as it is useful for drawing a set of panels to reflect a particular genomic region.\n * @param {number} [layout.x_axis.floor] The low end of the x-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {number} [layout.x_axis.ceiling] The high end of the x-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {Number[]} [layout.x_axis.min_extent] The smallest possible range [min, max] of the x-axis. If the actual values lie outside the extent, the actual data takes precedence.\n * @param {number} [layout.x_axis.field] The datum field to look at when determining data extent along the x-axis.\n * @param {number} [layout.x_axis.lower_buffer] Amount to expand (pad) the lower end of an axis as a proportion of the extent of the data.\n * @param {number} [layout.x_axis.upper_buffer] Amount to expand (pad) the higher end of an axis as a proportion of the extent of the data.\n * @param {boolean} [layout.y_axis.decoupled=false] If true, the data in this layer will not influence the y-extent of the panel.\n * @param {object} [layout.y_axis.axis=1] Which y axis to use for this data layer (left=1, right=2)\n * @param {number} [layout.y_axis.floor] The low end of the y-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {number} [layout.y_axis.ceiling] The high end of the y-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {Number[]} [layout.y_axis.min_extent] The smallest possible range [min, max] of the y-axis. Actual lower or higher data values will take precedence.\n * @param {number} [layout.y_axis.field] The datum field to look at when determining data extent along the y-axis.\n * @param {number} [layout.y_axis.lower_buffer] Amount to expand (pad) the lower end of an axis as a proportion of the extent of the data.\n * @param {number} [layout.y_axis.upper_buffer] Amount to expand (pad) the higher end of an axis as a proportion of the extent of the data.\n * @param {object} [layout.tooltip.show] Define when to show a tooltip in terms of interaction states, eg, `{ or: ['highlighted', 'selected'] }`\n * @param {object} [layout.tooltip.hide] Define when to hide a tooltip in terms of interaction states, eg, `{ and: ['unhighlighted', 'unselected'] }`\n * @param {boolean} [layout.tooltip.closable] Whether a tool tip should render a \"close\" button in the upper right corner.\n * @param {string} [layout.tooltip.html] HTML template to render inside the tool tip. The template syntax uses curly braces to allow simple expressions:\n * eg `{{sourcename:fieldname}} to insert a field value from the datum associated with\n * the tooltip/element. Conditional tags are supported using the format:\n * `{{#if sourcename:fieldname|transforms_can_be_used_too}}render text here{{#else}}Optional else branch{{/if}}`.\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='horizontal'] Where to draw the tooltip relative to the datum.\n * Typically tooltip positions are centered around the midpoint of the data element, subject to overflow off the edge of the plot.\n * @param {object} [layout.behaviors] LocusZoom data layers support the binding of mouse events to one or more\n * layout-definable behaviors. Some examples of behaviors include highlighting an element on mouseover, or\n * linking to a dynamic URL on click, etc.\n * @param {module:LocusZoom_DataLayers~LegendItem[]} [layout.legend] Tick marks found in the panel legend\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onctrlclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onctrlshiftclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onshiftclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onmouseover]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onmouseout]\n * @param {Panel|null} parent Where this layout is used\n */\n constructor(layout, parent) {\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * @private\n * @member {Number}\n */\n this.layout_idx = null;\n\n /**\n * The unique identifier for this layer. Should be unique within this panel.\n * @public\n * @member {String}\n */\n this.id = null;\n\n /**\n * The fully qualified identifier for the data layer, prefixed by any parent or container elements.\n * @type {string}\n * @private\n */\n this._base_id = null;\n\n /**\n * @protected\n * @member {Panel}\n */\n this.parent = parent || null;\n /**\n * @private\n * @member {{group: d3.selection, container: d3.selection, clipRect: d3.selection}}\n */\n this.svg = {};\n\n /**\n * @protected\n * @member {Plot}\n */\n this.parent_plot = null;\n if (parent) {\n this.parent_plot = parent.parent;\n }\n\n /**\n * The current layout configuration for this data layer. This reflects any resizing or dynamically generated\n * config options produced during rendering. Direct layout mutations are a powerful way to dynamically\n * modify the plot in response to user interactions, but require a deep knowledge of LZ internals to use\n * effectively.\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n if (this.layout.id) {\n this.id = this.layout.id;\n }\n\n /**\n * A user-provided function used to filter data for display. If provided, this will override any declarative\n * options in `layout.filters`\n * @private\n * @deprecated\n */\n this._filter_func = null;\n\n // Ensure any axes defined in the layout have an explicit axis number (default: 1)\n if (this.layout.x_axis !== {} && typeof this.layout.x_axis.axis !== 'number') {\n // TODO: Example of x2? if none remove\n this.layout.x_axis.axis = 1;\n }\n if (this.layout.y_axis !== {} && typeof this.layout.y_axis.axis !== 'number') {\n this.layout.y_axis.axis = 1;\n }\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original data layer state.\n * This is useful for, eg, dynamically generated color schemes that need to start from scratch when new data is\n * loaded: it contains the \"defaults\", not just the result of a calculated value.\n * @ignore\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * @private\n * @member {Object}\n */\n this.state = {};\n /**\n * @private\n * @member {String}\n */\n this.state_id = null;\n\n /**\n * @private\n * @member {Object}\n * */\n this.layer_state = null;\n // Create a default state (and set any references to the parent as appropriate)\n this._setDefaultState();\n\n // Initialize parameters for storing data and tool tips\n /**\n * The data retrieved from a region request. This field is useful for debugging, but will be overridden on\n * re-render; do not modify it directly. The point annotation cache can be used to preserve markings\n * after re-render.\n * @protected\n * @member {Array}\n */\n this.data = [];\n if (this.layout.tooltip) {\n /**\n * @private\n * @member {Object}\n */\n this.tooltips = {};\n }\n\n // Initialize flags for tracking global statuses\n this.global_statuses = {\n 'highlighted': false,\n 'selected': false,\n 'faded': false,\n 'hidden': false,\n };\n }\n\n /****** Public interface: methods for external manipulation */\n\n /**\n * @public\n */\n render() {\n throw new Error('Method must be implemented');\n }\n\n /**\n * Move a data layer forward relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveForward() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Move a data layer back relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveBack() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Set an \"annotation\": a piece of additional information about a point that is preserved across re-render,\n * or as the user pans and zooms near this region.\n *\n * Annotations can be referenced as a named pseudo-field in any filters and scalable parameters. (template support\n * may be added in the future)\n * Sample use case: user clicks a tooltip to \"label this specific point\". (or change any other display property)\n *\n * @public\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} key The name of the annotation to track\n * @param {*} value The value of the marked field\n */\n setElementAnnotation (element, key, value) {\n const id = this.getElementId(element);\n if (!this.layer_state.extra_fields[id]) {\n this.layer_state.extra_fields[id] = {};\n }\n this.layer_state.extra_fields[id][key] = value;\n return this;\n }\n\n /**\n * Select a filter function to be applied to the data. DEPRECATED: Please use the LocusZoom.MatchFunctions registry\n * and reference via declarative filters.\n * @param func\n * @deprecated\n */\n setFilter(func) {\n console.warn('The setFilter method is deprecated and will be removed in the future; please use the layout API with a custom filter function instead');\n this._filter_func = func;\n }\n\n /********** Protected methods: useful in subclasses to manipulate data layer behaviors */\n /**\n * Implementation hook for fetching the min and max values of available data. Used to determine axis range, if no other\n * explicit axis settings override. Useful for data layers where the data extent depends on more than one field.\n * (eg confidence intervals in a forest plot)\n *\n * @protected\n * @param data\n * @param axis_config The configuration object for the specified axis.\n * @returns {Array} [min, max] without any padding applied\n */\n _getDataExtent (data, axis_config) {\n data = data || this.data;\n // By default this depends only on a single field.\n return d3.extent(data, (d) => {\n const f = new Field(axis_config.field);\n return +f.resolve(d);\n });\n }\n\n /**\n * Fetch the fully qualified ID to be associated with a specific visual element, based on the data to which that\n * element is bound. In general this element ID will be unique, allowing it to be addressed directly via selectors.\n * @protected\n * @param {Object} element\n * @returns {String}\n */\n getElementId (element) {\n // Use a cached value if possible\n const id_key = Symbol.for('lzID');\n if (element[id_key]) {\n return element[id_key];\n }\n\n const id_field = this.layout.id_field || 'id';\n if (typeof element[id_field] == 'undefined') {\n throw new Error('Unable to generate element ID');\n }\n const element_id = element[id_field].toString().replace(/\\W/g, '');\n\n // Cache ID value for future calls\n const key = (`${this.getBaseId()}-${element_id}`).replace(/([:.[\\],])/g, '_');\n element[id_key] = key;\n return key;\n }\n\n /**\n * Fetch an ID that may bind a data element to a separate visual node for displaying status\n * Examples of this might be separate visual nodes to show select/highlight statuses, or\n * even a common/shared node to show status across many elements in a set.\n * Abstract method. It should be overridden by data layers that implement seperate status\n * nodes specifically to the use case of the data layer type.\n * @private\n * @param {String|Object} element\n * @returns {String|null}\n */\n getElementStatusNodeId (element) {\n return null;\n }\n\n /**\n * Returns a reference to the underlying data associated with a single visual element in the data layer, as\n * referenced by the unique identifier for the element\n *\n * @ignore\n * @protected\n * @param {String} id The unique identifier for the element, as defined by `getElementId`\n * @returns {Object|null} The data bound to that element\n */\n getElementById(id) {\n const selector = d3.select(`#${id.replace(/([:.[\\],])/g, '\\\\$1')}`); // escape special characters\n if (!selector.empty() && selector.data() && selector.data().length) {\n return selector.data()[0];\n } else {\n return null;\n }\n }\n\n /**\n * Basic method to apply arbitrary methods and properties to data elements.\n * This is called on all data immediately after being fetched. (requires reMap, not just re-render)\n *\n * Allowing a data element to access its parent enables interactive functionality, such as tooltips that modify\n * the parent plot. This is also used for system-derived fields like \"matching\" behavior\".\n *\n * @protected\n * @returns {BaseDataLayer}\n */\n applyDataMethods() {\n const field_to_match = (this.layout.match && this.layout.match.receive);\n const match_function = MATCHERS.get(this.layout.match && this.layout.match.operator || '=');\n const broadcast_value = this.parent_plot.state.lz_match_value;\n // Match functions are allowed to use transform syntax on field values, but not (yet) UI \"annotations\"\n const field_resolver = field_to_match ? new Field(field_to_match) : null;\n this.data.forEach((item, i) => {\n // Basic toHTML() method - return the stringified value in the id_field, if defined.\n\n // When this layer receives data, mark whether points match (via a synthetic boolean field)\n // Any field-based layout directives (color, size, shape) can then be used to control display\n if (field_to_match && broadcast_value !== null && broadcast_value !== undefined) {\n item.lz_is_match = (match_function(field_resolver.resolve(item), broadcast_value));\n }\n\n item.toHTML = () => {\n const id_field = this.layout.id_field || 'id';\n let html = '';\n if (item[id_field]) {\n html = item[id_field].toString();\n }\n return html;\n };\n // Helper methods - return a reference to various plot levels. Useful for interactive tooltips.\n item.getDataLayer = () => this;\n item.getPanel = () => this.parent || null;\n item.getPlot = () => {\n // For unit testing etc, this layer may be created without a parent.\n const panel = this.parent;\n return panel ? panel.parent : null;\n };\n // deselect() method - shortcut method to deselect the element\n item.deselect = () => {\n const data_layer = this.getDataLayer();\n data_layer.unselectElement(this); // dynamically generated method name. It exists, honest.\n };\n });\n this.applyCustomDataMethods();\n return this;\n }\n\n /**\n * Hook that allows custom datalayers to apply additional methods and properties to data elements as needed.\n * Most data layers will never need to use this.\n * @protected\n * @returns {BaseDataLayer}\n */\n applyCustomDataMethods() {\n return this;\n }\n\n /**\n * Apply scaling functions to an element as needed, based on the layout rules governing display + the element's data\n * If the layout parameter is already a primitive type, simply return the value as given\n *\n * In the future this may be further expanded, so that scaling functions can operate similar to mappers\n * (item, index, array). Additional arguments would be added as the need arose.\n *\n * @private\n * @param {Array|Number|String|Object} option_layout Either a scalar (\"color is red\") or a configuration object\n * (\"rules for how to choose color based on item value\")\n * @param {*} element_data The value to be used with the filter. May be a primitive value, or a data object for a single item\n * @param {Number} data_index The array index for the data element\n * @returns {*} The transformed value\n */\n resolveScalableParameter (option_layout, element_data, data_index) {\n let ret = null;\n if (Array.isArray(option_layout)) {\n let idx = 0;\n while (ret === null && idx < option_layout.length) {\n ret = this.resolveScalableParameter(option_layout[idx], element_data, data_index);\n idx++;\n }\n } else {\n switch (typeof option_layout) {\n case 'number':\n case 'string':\n ret = option_layout;\n break;\n case 'object':\n if (option_layout.scale_function) {\n const func = SCALABLE.get(option_layout.scale_function);\n if (option_layout.field) {\n const f = new Field(option_layout.field);\n let extra;\n try {\n extra = this.getElementAnnotation(element_data);\n } catch (e) {\n extra = null;\n }\n ret = func(option_layout.parameters || {}, f.resolve(element_data, extra), data_index);\n } else {\n ret = func(option_layout.parameters || {}, element_data, data_index);\n }\n }\n break;\n }\n }\n return ret;\n }\n\n /**\n * Generate dimension extent function based on layout parameters\n * @ignore\n * @protected\n * @param {('x'|'y')} dimension\n */\n getAxisExtent (dimension) {\n\n if (!['x', 'y'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n\n const axis_name = `${dimension}_axis`;\n const axis_layout = this.layout[axis_name];\n\n // If a floor AND a ceiling are explicitly defined then just return that extent and be done\n if (!isNaN(axis_layout.floor) && !isNaN(axis_layout.ceiling)) {\n return [+axis_layout.floor, +axis_layout.ceiling];\n }\n\n // If a field is defined for the axis and the data layer has data then generate the extent from the data set\n let data_extent = [];\n if (axis_layout.field && this.data) {\n if (!this.data.length) {\n // If data has been fetched (but no points in region), enforce the min_extent (with no buffers,\n // because we don't need padding around an empty screen)\n data_extent = axis_layout.min_extent || [];\n return data_extent;\n } else {\n data_extent = this._getDataExtent(this.data, axis_layout);\n\n // Apply upper/lower buffers, if applicable\n const original_extent_span = data_extent[1] - data_extent[0];\n if (!isNaN(axis_layout.lower_buffer)) {\n data_extent[0] -= original_extent_span * axis_layout.lower_buffer;\n }\n if (!isNaN(axis_layout.upper_buffer)) {\n data_extent[1] += original_extent_span * axis_layout.upper_buffer;\n }\n\n if (typeof axis_layout.min_extent == 'object') {\n // The data should span at least the range specified by min_extent, an array with [low, high]\n const range_min = axis_layout.min_extent[0];\n const range_max = axis_layout.min_extent[1];\n if (!isNaN(range_min) && !isNaN(range_max)) {\n data_extent[0] = Math.min(data_extent[0], range_min);\n }\n if (!isNaN(range_max)) {\n data_extent[1] = Math.max(data_extent[1], range_max);\n }\n }\n // If specified, floor and ceiling will override the actual data range\n return [\n isNaN(axis_layout.floor) ? data_extent[0] : axis_layout.floor,\n isNaN(axis_layout.ceiling) ? data_extent[1] : axis_layout.ceiling,\n ];\n }\n }\n\n // If this is for the x axis and no extent could be generated yet but state has a defined start and end\n // then default to using the state-defined region as the extent\n if (dimension === 'x' && !isNaN(this.state.start) && !isNaN(this.state.end)) {\n return [this.state.start, this.state.end];\n }\n\n // No conditions met for generating a valid extent, return an empty array\n return [];\n\n }\n\n /**\n * Allow this data layer to tell the panel what axis ticks it thinks it will require. The panel may choose whether\n * to use some, all, or none of these when rendering, either alone or in conjunction with other data layers.\n *\n * This method is a stub and should be overridden in data layers that need to specify custom behavior.\n *\n * @protected\n * @param {('x'|'y1'|'y2')} dimension\n * @param {Object} [config] Additional parameters for the panel to specify how it wants ticks to be drawn. The names\n * and meanings of these parameters may vary between different data layers.\n * @returns {Object[]}\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n getTicks (dimension, config) {\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n return [];\n }\n\n /**\n * Determine the coordinates for where to point the tooltip at. Typically, this is the center of a datum element (eg,\n * the middle of a scatter plot point). Also provide an offset if the tooltip should not be at that center (most\n * elements are not single points, eg a scatter plot point has a radius and a gene is a rectangle).\n * The default implementation is quite naive: it places the tooltip at the origin for that layer. Individual layers\n * should override this method to position relative to the chosen data element or mouse event.\n * @protected\n * @param {Object} tooltip A tooltip object (including attribute tooltip.data)\n * @returns {Object} as {x_min, x_max, y_min, y_max} in px, representing bounding box of a rectangle around the data pt\n * Note that these pixels are in the SVG coordinate system\n */\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n const y_extent = panel[`y${this.layout.y_axis.axis}_extent`];\n\n const x = panel.x_scale(panel.x_extent[0]);\n const y = y_scale(y_extent[0]);\n\n return { x_min: x, x_max: x, y_min: y, y_max: y };\n }\n\n /**\n * Draw a tooltip on the data layer pointed at the specified coordinates, in the specified orientation.\n * Tooltip will be drawn on the edge of the major axis, and centered along the minor axis- see diagram.\n * v\n * > o <\n * ^\n *\n * @protected\n * @param tooltip {Object} The object representing all data for the tooltip to be drawn\n * @param {'vertical'|'horizontal'|'top'|'bottom'|'left'|'right'} position Where to draw the tooltip relative to\n * the data\n * @param {Number} x_min The min x-coordinate for the bounding box of the data element\n * @param {Number} x_max The max x-coordinate for the bounding box of the data element\n * @param {Number} y_min The min y-coordinate for the bounding box of the data element\n * @param {Number} y_max The max y-coordinate for the bounding box of the data element\n */\n _drawTooltip(tooltip, position, x_min, x_max, y_min, y_max) {\n const panel_layout = this.parent.layout;\n const plot_layout = this.parent_plot.layout;\n const layer_layout = this.layout;\n\n // Tooltip position params: as defined in the default stylesheet, used in calculations\n const arrow_size = 7;\n const stroke_width = 1;\n const arrow_total = arrow_size + stroke_width; // Tooltip pos should account for how much space the arrow takes up\n\n const tooltip_padding = 6; // bbox size must account for any internal padding applied between data and border\n\n const page_origin = this._getPageOrigin();\n const tooltip_box = tooltip.selector.node().getBoundingClientRect();\n const data_layer_height = panel_layout.height - (panel_layout.margin.top + panel_layout.margin.bottom);\n const data_layer_width = plot_layout.width - (panel_layout.margin.left + panel_layout.margin.right);\n\n // Clip the edges of the datum to the available plot area\n x_min = Math.max(x_min, 0);\n x_max = Math.min(x_max, data_layer_width);\n y_min = Math.max(y_min, 0);\n y_max = Math.min(y_max, data_layer_height);\n\n const x_center = (x_min + x_max) / 2;\n const y_center = (y_min + y_max) / 2;\n // Default offsets are the far edge of the datum bounding box\n let x_offset = x_max - x_center;\n let y_offset = y_max - y_center;\n let placement = layer_layout.tooltip_positioning;\n\n // Coordinate system note: the tooltip is positioned relative to the plot/page; the arrow is positioned relative to\n // the tooltip boundaries\n let tooltip_top, tooltip_left, arrow_type, arrow_top, arrow_left;\n\n // The user can specify a generic orientation, and LocusZoom will autoselect whether to place the tooltip above or below\n if (placement === 'vertical') {\n // Auto-select whether to position above the item, or below\n x_offset = 0;\n if (tooltip_box.height + arrow_total > data_layer_height - (y_center + y_offset)) {\n placement = 'top';\n } else {\n placement = 'bottom';\n }\n } else if (placement === 'horizontal') {\n // Auto select whether to position to the left of the item, or to the right\n y_offset = 0;\n if (x_center <= plot_layout.width / 2) {\n placement = 'left';\n } else {\n placement = 'right';\n }\n }\n\n if (placement === 'top' || placement === 'bottom') {\n // Position horizontally centered above the point\n const offset_right = Math.max((tooltip_box.width / 2) - x_center, 0);\n const offset_left = Math.max((tooltip_box.width / 2) + x_center - data_layer_width, 0);\n tooltip_left = page_origin.x + x_center - (tooltip_box.width / 2) - offset_left + offset_right;\n arrow_left = page_origin.x + x_center - tooltip_left - arrow_size; // Arrow should be centered over the data\n // Position vertically above the point unless there's insufficient space, then go below\n if (placement === 'top') {\n tooltip_top = page_origin.y + y_center - (y_offset + tooltip_box.height + arrow_total);\n arrow_type = 'down';\n arrow_top = tooltip_box.height - stroke_width;\n } else {\n tooltip_top = page_origin.y + y_center + y_offset + arrow_total;\n arrow_type = 'up';\n arrow_top = 0 - arrow_total;\n }\n } else if (placement === 'left' || placement === 'right') {\n // Position tooltip horizontally on the left or the right depending on which side of the plot the point is on\n if (placement === 'left') {\n tooltip_left = page_origin.x + x_center + x_offset + arrow_total;\n arrow_type = 'left';\n arrow_left = -1 * (arrow_size + stroke_width);\n } else {\n tooltip_left = page_origin.x + x_center - tooltip_box.width - x_offset - arrow_total;\n arrow_type = 'right';\n arrow_left = tooltip_box.width - stroke_width;\n }\n // Position with arrow vertically centered along tooltip edge unless we're at the top or bottom of the plot\n if (y_center - (tooltip_box.height / 2) <= 0) { // Too close to the top, push it down\n tooltip_top = page_origin.y + y_center - (1.5 * arrow_size) - tooltip_padding;\n arrow_top = tooltip_padding;\n } else if (y_center + (tooltip_box.height / 2) >= data_layer_height) { // Too close to the bottom, pull it up\n tooltip_top = page_origin.y + y_center + arrow_size + tooltip_padding - tooltip_box.height;\n arrow_top = tooltip_box.height - (2 * arrow_size) - tooltip_padding;\n } else { // vertically centered\n tooltip_top = page_origin.y + y_center - (tooltip_box.height / 2);\n arrow_top = (tooltip_box.height / 2) - arrow_size;\n }\n } else {\n throw new Error('Unrecognized placement value');\n }\n\n // Position the div itself, relative to the layer origin\n tooltip.selector\n .style('left', `${tooltip_left}px`)\n .style('top', `${tooltip_top}px`);\n // Create / update position on arrow connecting tooltip to data\n if (!tooltip.arrow) {\n tooltip.arrow = tooltip.selector.append('div')\n .style('position', 'absolute');\n }\n tooltip.arrow\n .attr('class', `lz-data_layer-tooltip-arrow_${arrow_type}`)\n .style('left', `${arrow_left}px`)\n .style('top', `${arrow_top}px`);\n return this;\n }\n\n /**\n * Determine whether a given data element matches all predefined filter criteria, usually as specified in a layout directive.\n *\n * Typically this is used with array.filter (the first argument is curried, `this.filter.bind(this, options)`\n * @private\n * @param {Object[]} filter_rules A list of rule entries: {field, value, operator} describing each filter.\n * Operator must be from a list of built-in operators. If the field is omitted, the entire datum object will be\n * passed to the filter, rather than a single scalar value. (this is only useful with custom `MatchFunctions` as operator)\n * @param {Object} item\n * @param {Number} index\n * @param {Array} array\n * @returns {Boolean} Whether the specified item is a match\n */\n filter(filter_rules, item, index, array) {\n let is_match = true;\n filter_rules.forEach((filter) => { // Try each filter on this item, in sequence\n const {field, operator, value: target} = filter;\n const test_func = MATCHERS.get(operator);\n\n // Return the field value or annotation. If no `field` is specified, the filter function will operate on\n // the entire data object. This behavior is only really useful with custom functions, because the\n // builtin ones expect to receive a scalar value\n const extra = this.getElementAnnotation(item);\n const field_value = field ? (new Field(field)).resolve(item, extra) : item;\n if (!test_func(field_value, target)) {\n is_match = false;\n }\n });\n return is_match;\n }\n\n /**\n * Get \"annotation\" metadata associated with a particular point.\n *\n * @protected\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} [key] The name of the annotation to track. If omitted, returns all annotations for this element as an object.\n * @return {*}\n */\n getElementAnnotation (element, key) {\n const id = this.getElementId(element);\n const extra = this.layer_state.extra_fields[id];\n return key ? (extra && extra[key]) : extra;\n }\n\n /****** Private methods: rarely overridden or modified by external usages */\n\n /**\n * Apply filtering options to determine the set of data to render\n *\n * This must be applied on rendering, not fetch, so that the axis limits reflect the true range of the dataset\n * Otherwise, two stacked panels (same dataset filtered in different ways) might not line up on the x-axis when\n * filters are applied.\n * @param data\n * @return {*}\n * @private\n */\n _applyFilters(data) {\n data = data || this.data;\n\n if (this._filter_func) {\n data = data.filter(this._filter_func);\n } else if (this.layout.filters) {\n data = data.filter(this.filter.bind(this, this.layout.filters));\n }\n return data;\n }\n\n /**\n * Define default state that should get tracked during the lifetime of this layer.\n *\n * In some special custom usages, it may be useful to completely reset a panel (eg \"click for\n * genome region\" links), plotting new data that invalidates any previously tracked state. This hook makes it\n * possible to reset without destroying the panel entirely. It is used by `Plot.clearPanelData`.\n * @private\n */\n _setDefaultState() {\n // Each datalayer tracks two kinds of status: flags for internal state (highlighted, selected, tooltip),\n // and \"extra fields\" (annotations like \"show a tooltip\" that are not determined by the server, but need to\n // persist across re-render)\n const layer_state = { status_flags: {}, extra_fields: {} };\n const status_flags = layer_state.status_flags;\n STATUSES.adjectives.forEach((status) => {\n status_flags[status] = status_flags[status] || new Set();\n });\n // Also initialize \"internal-only\" state fields (things that are tracked, but not set directly by external events)\n status_flags['has_tooltip'] = status_flags['has_tooltip'] || new Set();\n\n if (this.parent) {\n // If layer has a parent, store a reference in the overarching plot.state object\n this.state_id = `${this.parent.id}.${this.id}`;\n this.state = this.parent.state;\n this.state[this.state_id] = layer_state;\n }\n this.layer_state = layer_state;\n }\n\n /**\n * Get the fully qualified identifier for the data layer, prefixed by any parent or container elements\n *\n * @private\n * @returns {string} A dot-delimited string of the format ..\n */\n getBaseId () {\n if (this._base_id) {\n return this._base_id;\n }\n\n if (this.parent) {\n return `${this.parent_plot.id}.${this.parent.id}.${this.id}`;\n } else {\n return (this.id || '').toString();\n }\n }\n\n /**\n * Determine the pixel height of data-bound objects represented inside this data layer. (excluding elements such as axes)\n *\n * May be used by operations that resize the data layer to fit available data\n *\n * @private\n * @returns {number}\n */\n getAbsoluteDataHeight() {\n const dataBCR = this.svg.group.node().getBoundingClientRect();\n return dataBCR.height;\n }\n\n /**\n * Initialize a data layer\n * @private\n * @returns {BaseDataLayer}\n */\n initialize() {\n this._base_id = this.getBaseId();\n\n // Append a container group element to house the main data layer group element and the clip path\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.group.append('g')\n .attr('class', 'lz-data_layer-container')\n .attr('id', `${base_id}.data_layer_container`);\n\n // Append clip path to the container element\n this.svg.clipRect = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`)\n .append('rect');\n\n // Append svg group for rendering all data layer elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.data_layer`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n return this;\n\n }\n\n /**\n * Generate a tool tip for a given element\n * @private\n * @param {String|Object} data Data for the element associated with the tooltip\n */\n createTooltip (data) {\n if (typeof this.layout.tooltip != 'object') {\n throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`);\n }\n const id = this.getElementId(data);\n if (this.tooltips[id]) {\n this.positionTooltip(id);\n return;\n }\n this.tooltips[id] = {\n data: data,\n arrow: null,\n selector: d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', 'lz-data_layer-tooltip')\n .attr('id', `${id}-tooltip`),\n };\n this.layer_state.status_flags['has_tooltip'].add(id);\n this.updateTooltip(data);\n return this;\n }\n\n /**\n * Update a tool tip (generate its inner HTML)\n *\n * @private\n * @param {String|Object} d The element associated with the tooltip\n * @param {String} [id] An identifier to the tooltip\n */\n updateTooltip(d, id) {\n if (typeof id == 'undefined') {\n id = this.getElementId(d);\n }\n // Empty the tooltip of all HTML (including its arrow!)\n this.tooltips[id].selector.html('');\n this.tooltips[id].arrow = null;\n // Set the new HTML\n if (this.layout.tooltip.html) {\n this.tooltips[id].selector.html(parseFields(this.layout.tooltip.html, d, this.getElementAnnotation(d)));\n }\n // If the layout allows tool tips on this data layer to be closable then add the close button\n // and add padding to the tooltip to accommodate it\n if (this.layout.tooltip.closable) {\n this.tooltips[id].selector.insert('button', ':first-child')\n .attr('class', 'lz-tooltip-close-button')\n .attr('title', 'Close')\n .text('×')\n .on('click', () => {\n this.destroyTooltip(id);\n });\n }\n // Apply data directly to the tool tip for easier retrieval by custom UI elements inside the tool tip\n this.tooltips[id].selector.data([d]);\n // Reposition and draw a new arrow\n this.positionTooltip(id);\n return this;\n }\n\n /**\n * Destroy tool tip - remove the tool tip element from the DOM and delete the tool tip's record on the data layer\n *\n * @private\n * @param {String|Object} element_or_id The element (or id) associated with the tooltip\n * @param {boolean} [temporary=false] Whether this is temporary (not to be tracked in state). Differentiates\n * \"recreate tooltips on re-render\" (which is temporary) from \"user has closed this tooltip\" (permanent)\n * @returns {BaseDataLayer}\n */\n destroyTooltip(element_or_id, temporary) {\n let id;\n if (typeof element_or_id == 'string') {\n id = element_or_id;\n } else {\n id = this.getElementId(element_or_id);\n }\n if (this.tooltips[id]) {\n if (typeof this.tooltips[id].selector == 'object') {\n this.tooltips[id].selector.remove();\n }\n delete this.tooltips[id];\n }\n // When a tooltip is removed, also remove the reference from the state\n if (!temporary) {\n const tooltip_state = this.layer_state.status_flags['has_tooltip'];\n tooltip_state.delete(id);\n }\n return this;\n }\n\n /**\n * Loop through and destroy all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n destroyAllTooltips(temporary = true) {\n for (let id in this.tooltips) {\n this.destroyTooltip(id, temporary);\n }\n return this;\n }\n\n /**\n * Position and then redraw tool tip - naïve function to place a tool tip in the data layer. By default, positions wrt\n * the top-left corner of the data layer.\n *\n * Each layer type may have more specific logic. Consider overriding the provided hooks `_getTooltipPosition` or\n * `_drawTooltip` as appropriate\n *\n * @private\n * @param {String} id The identifier of the tooltip to position\n * @returns {BaseDataLayer}\n */\n positionTooltip(id) {\n if (typeof id != 'string') {\n throw new Error('Unable to position tooltip: id is not a string');\n }\n if (!this.tooltips[id]) {\n throw new Error('Unable to position tooltip: id does not point to a valid tooltip');\n }\n const tooltip = this.tooltips[id];\n const coords = this._getTooltipPosition(tooltip);\n\n if (!coords) {\n // Special cutout: normally, tooltips are positioned based on the datum element. Some, like lines/curves,\n // work better if based on a mouse event. Since not every redraw contains a mouse event, we can just skip\n // calculating position when no position information is available.\n return null;\n }\n this._drawTooltip(tooltip, this.layout.tooltip_positioning, coords.x_min, coords.x_max, coords.y_min, coords.y_max);\n }\n\n /**\n * Loop through and position all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n positionAllTooltips() {\n for (let id in this.tooltips) {\n this.positionTooltip(id);\n }\n return this;\n }\n\n /**\n * Show or hide a tool tip by ID depending on directives in the layout and state values relative to the ID\n *\n * @private\n * @param {String|Object} element The element associated with the tooltip\n * @param {boolean} first_time Because panels can re-render, the rules for showing a tooltip\n * depend on whether this is the first time a status change affecting display has been applied.\n * @returns {BaseDataLayer}\n */\n showOrHideTooltip(element, first_time) {\n if (typeof this.layout.tooltip != 'object') {\n return this;\n }\n const id = this.getElementId(element);\n\n /**\n * Apply rules and decide whether to show or hide the tooltip\n * @param {Object} statuses All statuses that apply to an element\n * @param {String[]|object} directive A layout directive object\n * @param operator\n * @returns {null|bool}\n */\n const resolveStatus = (statuses, directive, operator) => {\n let status = null;\n if (typeof statuses != 'object' || statuses === null) {\n return null;\n }\n if (Array.isArray(directive)) {\n // This happens when the function is called on the inner part of the directive\n operator = operator || 'and';\n if (directive.length === 1) {\n status = statuses[directive[0]];\n } else {\n status = directive.reduce((previousValue, currentValue) => {\n if (operator === 'and') {\n return statuses[previousValue] && statuses[currentValue];\n } else if (operator === 'or') {\n return statuses[previousValue] || statuses[currentValue];\n }\n return null;\n });\n }\n } else if (typeof directive == 'object') {\n let sub_status;\n for (let sub_operator in directive) {\n sub_status = resolveStatus(statuses, directive[sub_operator], sub_operator);\n if (status === null) {\n status = sub_status;\n } else if (operator === 'and') {\n status = status && sub_status;\n } else if (operator === 'or') {\n status = status || sub_status;\n }\n }\n } else {\n return false;\n }\n return status;\n };\n\n let show_directive = {};\n if (typeof this.layout.tooltip.show == 'string') {\n show_directive = { and: [ this.layout.tooltip.show ] };\n } else if (typeof this.layout.tooltip.show == 'object') {\n show_directive = this.layout.tooltip.show;\n }\n\n let hide_directive = {};\n if (typeof this.layout.tooltip.hide == 'string') {\n hide_directive = { and: [ this.layout.tooltip.hide ] };\n } else if (typeof this.layout.tooltip.hide == 'object') {\n hide_directive = this.layout.tooltip.hide;\n }\n\n // Find all the statuses that apply to just this single element\n const layer_state = this.layer_state;\n var status_flags = {}; // {status_name: bool}\n STATUSES.adjectives.forEach((status) => {\n const antistatus = `un${status}`;\n status_flags[status] = (layer_state.status_flags[status].has(id));\n status_flags[antistatus] = !status_flags[status];\n });\n\n // Decide whether to show/hide the tooltip based solely on the underlying element\n const show_resolved = resolveStatus(status_flags, show_directive);\n const hide_resolved = resolveStatus(status_flags, hide_directive);\n\n // Most of the tooltip display logic depends on behavior layouts: was point (un)selected, (un)highlighted, etc.\n // But sometimes, a point is selected, and the user then closes the tooltip. If the panel is re-rendered for\n // some outside reason (like state change), we must track this in the create/destroy events as tooltip state.\n const has_tooltip = (layer_state.status_flags['has_tooltip'].has(id));\n const tooltip_was_closed = first_time ? false : !has_tooltip;\n if (show_resolved && !tooltip_was_closed && !hide_resolved) {\n this.createTooltip(element);\n } else {\n this.destroyTooltip(element);\n }\n\n return this;\n }\n\n /**\n * Toggle a status (e.g. highlighted, selected, identified) on an element\n *\n * @private\n * @fires event:layout_changed\n * @fires event:element_selection\n * @fires event:match_requested\n * @param {String} status The name of a recognized status to be added/removed on an appropriate element\n * @param {String|Object} element The data bound to the element of interest\n * @param {Boolean} active True to add the status (and associated CSS styles); false to remove it\n * @param {Boolean} exclusive Whether to only allow a state for a single element at a time\n * @returns {BaseDataLayer}\n */\n setElementStatus(status, element, active, exclusive) {\n if (status === 'has_tooltip') {\n // This is a special adjective that exists solely to track tooltip state. It has no CSS and never gets set\n // directly. It is invisible to the official enums.\n return this;\n }\n if (typeof active == 'undefined') {\n active = true;\n }\n\n // Get an ID for the element or return having changed nothing\n let element_id;\n try {\n element_id = this.getElementId(element);\n } catch (get_element_id_error) {\n return this;\n }\n\n // Enforce exclusivity (force all elements to have the opposite of toggle first)\n if (exclusive) {\n this.setAllElementStatus(status, !active);\n }\n\n // Set/unset the proper status class on the appropriate DOM element(s), *and* potentially an additional element\n d3.select(`#${element_id}`).classed(`lz-data_layer-${this.layout.type}-${status}`, active);\n const element_status_node_id = this.getElementStatusNodeId(element);\n if (element_status_node_id !== null) {\n d3.select(`#${element_status_node_id}`).classed(`lz-data_layer-${this.layout.type}-statusnode-${status}`, active);\n }\n\n // Track element ID in the proper status state array\n const added_status = !this.layer_state.status_flags[status].has(element_id); // On a re-render, existing statuses will be reapplied.\n if (active && added_status) {\n this.layer_state.status_flags[status].add(element_id);\n }\n if (!active && !added_status) {\n this.layer_state.status_flags[status].delete(element_id);\n }\n\n // Trigger tool tip show/hide logic\n this.showOrHideTooltip(element, added_status);\n\n // Trigger layout changed event hook\n if (added_status) {\n this.parent.emit('layout_changed', true);\n }\n\n const is_selected = (status === 'selected');\n if (is_selected && (added_status || !active)) {\n // Notify parents that an element has changed selection status (either active, or inactive)\n this.parent.emit('element_selection', { element: element, active: active }, true);\n }\n\n const value_to_broadcast = (this.layout.match && this.layout.match.send);\n if (is_selected && (typeof value_to_broadcast !== 'undefined') && (added_status || !active)) {\n this.parent.emit(\n // The broadcast value can use transforms to \"clean up value before sending broadcasting\"\n 'match_requested',\n { value: new Field(value_to_broadcast).resolve(element), active: active },\n true\n );\n }\n return this;\n }\n\n /**\n * Toggle a status on all elements in the data layer\n *\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n * @returns {BaseDataLayer}\n */\n setAllElementStatus(status, toggle) {\n\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Apply statuses\n if (toggle) {\n this.data.forEach((element) => this.setElementStatus(status, element, true));\n } else {\n const status_ids = new Set(this.layer_state.status_flags[status]); // copy so that we don't mutate while iterating\n status_ids.forEach((id) => {\n const element = this.getElementById(id);\n if (typeof element == 'object' && element !== null) {\n this.setElementStatus(status, element, false);\n }\n });\n this.layer_state.status_flags[status] = new Set();\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n return this;\n }\n\n /**\n * Apply all layout-defined behaviors (DOM event handlers) to a selection of elements\n *\n * @private\n * @param {d3.selection} selection\n */\n applyBehaviors(selection) {\n if (typeof this.layout.behaviors != 'object') {\n return;\n }\n Object.keys(this.layout.behaviors).forEach((directive) => {\n const event_match = /(click|mouseover|mouseout)/.exec(directive);\n if (!event_match) {\n return;\n }\n selection.on(`${event_match[0]}.${directive}`, this.executeBehaviors(directive, this.layout.behaviors[directive]));\n });\n }\n\n /**\n * Generate a function that executes an arbitrary list of behaviors on an element during an event\n *\n * @private\n * @param {String} directive The name of the event, as described in layout.behaviors for this datalayer\n * @param {Object[]} behaviors An object describing the behavior to attach to this single element\n * @param {string} behaviors.action The name of the action that would trigger this behavior (eg click, mouseover, etc)\n * @param {string} behaviors.status What status to apply to the element when this behavior is triggered (highlighted,\n * selected, etc)\n * @param {boolean} [behaviors.exclusive] Whether triggering the event for this element should unset the relevant status\n * for all other elements. Useful for, eg, click events that exclusively highlight one thing.\n * @returns {function(this:BaseDataLayer)} Return a function that handles the event in context with the behavior\n * and the element- can be attached as an event listener\n */\n executeBehaviors(directive, behaviors) {\n\n // Determine the required state of control and shift keys during the event\n const requiredKeyStates = {\n 'ctrl': (directive.includes('ctrl')),\n 'shift': (directive.includes('shift')),\n };\n const self = this;\n return function(element) {\n // This method may be used on two kinds of events: directly attached, or bubbled.\n // D3 doesn't natively support bubbling very well; if no data is bound on the currentTarget, check to see\n // if there is data available at wherever the event was initiated from\n element = element || d3.select(d3.event.target).datum();\n\n // Do nothing if the required control and shift key presses (or lack thereof) doesn't match the event\n if (requiredKeyStates.ctrl !== !!d3.event.ctrlKey || requiredKeyStates.shift !== !!d3.event.shiftKey) {\n return;\n }\n\n // Loop through behaviors making each one go in succession\n behaviors.forEach((behavior) => {\n\n // Route first by the action, if defined\n if (typeof behavior != 'object' || behavior === null) {\n return;\n }\n\n switch (behavior.action) {\n\n // Set a status (set to true regardless of current status, optionally with exclusivity)\n case 'set':\n self.setElementStatus(behavior.status, element, true, behavior.exclusive);\n break;\n\n // Unset a status (set to false regardless of current status, optionally with exclusivity)\n case 'unset':\n self.setElementStatus(behavior.status, element, false, behavior.exclusive);\n break;\n\n // Toggle a status\n case 'toggle':\n var current_status_boolean = (self.layer_state.status_flags[behavior.status].has(self.getElementId(element)));\n var exclusive = behavior.exclusive && !current_status_boolean;\n\n self.setElementStatus(behavior.status, element, !current_status_boolean, exclusive);\n break;\n\n // Link to a dynamic URL\n case 'link':\n if (typeof behavior.href == 'string') {\n const url = parseFields(behavior.href, element, self.getElementAnnotation(element));\n if (typeof behavior.target == 'string') {\n window.open(url, behavior.target);\n } else {\n window.location.href = url;\n }\n }\n break;\n\n // Action not defined, just return\n default:\n break;\n }\n });\n };\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n *\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const panel_origin = this.parent._getPageOrigin();\n return {\n x: panel_origin.x + this.parent.layout.margin.left,\n y: panel_origin.y + this.parent.layout.margin.top,\n };\n }\n\n /**\n * Apply all tracked element statuses. This is primarily intended for re-rendering the plot, in order to preserve\n * behaviors when items are updated.\n * @private\n */\n applyAllElementStatus () {\n const status_flags = this.layer_state.status_flags;\n const self = this;\n for (let property in status_flags) {\n if (!Object.prototype.hasOwnProperty.call(status_flags, property)) {\n continue;\n }\n status_flags[property].forEach((element_id) => {\n try {\n this.setElementStatus(property, this.getElementById(element_id), true);\n } catch (e) {\n console.warn(`Unable to apply state: ${self.state_id}, ${property}`);\n console.error(e);\n }\n });\n\n }\n }\n\n /**\n * Position the datalayer and all tooltips\n * @private\n * @returns {BaseDataLayer}\n */\n draw() {\n this.svg.container\n .attr('transform', `translate(${this.parent.layout.cliparea.origin.x}, ${this.parent.layout.cliparea.origin.y})`);\n this.svg.clipRect\n .attr('width', this.parent.layout.cliparea.width)\n .attr('height', this.parent.layout.cliparea.height);\n this.positionAllTooltips();\n return this;\n }\n\n /**\n * Re-Map a data layer to reflect changes in the state of a plot (such as viewing region/ chromosome range)\n *\n * Whereas .render draws whatever data is available, this method resets the view and fetches new data if necessary.\n *\n * @private\n * @return {Promise}\n */\n reMap() {\n this.destroyAllTooltips(); // hack - only non-visible tooltips should be destroyed\n // and then recreated if returning to visibility\n\n // Fetch new data. Datalayers are only given access to the final consolidated data from the chain (not headers or raw payloads)\n return this.parent_plot.lzd.getData(this.state, this.layout.fields)\n .then((new_data) => {\n this.data = new_data.body; // chain.body from datasources\n this.applyDataMethods();\n this.initialized = true;\n });\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n // Set/unset a single element's status\n\n /**\n * @private\n * @function highlightElement\n */\n /**\n * @private\n * @function selectElement\n */\n /**\n * @private\n * @function fadeElement\n */\n /**\n * @private\n * @function hideElement\n */\n BaseDataLayer.prototype[`${verb}Element`] = function(element, exclusive = false) {\n exclusive = !!exclusive;\n this.setElementStatus(adjective, element, true, exclusive);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightElement\n */\n /**\n * @private\n * @function unselectElement\n */\n /**\n * @private\n * @function unfadeElement\n */\n /**\n * @private\n * @function unhideElement\n */\n BaseDataLayer.prototype[`${antiverb}Element`] = function(element, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n this.setElementStatus(adjective, element, false, exclusive);\n return this;\n };\n\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n // Set/unset status for all elements\n BaseDataLayer.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n * */\n /**\n * @private\n * @function unhideAllElements\n */\n BaseDataLayer.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {BaseDataLayer as default};\n","import BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~annotation_track\n */\nconst default_layout = {\n color: '#000000',\n filters: null,\n tooltip_positioning: 'vertical',\n hitarea_width: 8,\n};\n\n/**\n * Create a single continuous 2D track that provides information about each datapoint\n *\n * For example, this can be used to mark items by membership in a group, alongside information in other panels\n * @alias module:LocusZoom_DataLayers~annotation_track\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass AnnotationTrack extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color] Specify how to choose the fill color for each tick mark\n * @param {number} [layout.hitarea_width=8] The width (in pixels) of hitareas. Annotation marks are typically 1 px wide,\n * so a hit area of 4px on each side can make it much easier to select an item for a tooltip. Hitareas will not interfere\n * with selecting adjacent points.\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='vertical'] Where to draw the tooltip relative to the datum.\n */\n constructor(layout) {\n if (!Array.isArray(layout.filters)) {\n throw new Error('Annotation track must specify array of filters for selecting points to annotate');\n }\n merge(layout, default_layout);\n super(...arguments);\n }\n\n initialize() {\n super.initialize();\n this._hitareas_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-hit_areas`);\n\n this._visible_lines_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-visible_lines`);\n }\n\n render() {\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n const hit_areas_selection = this._hitareas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n\n\n const _getX = (d, i) => {\n // Helper for hitarea position calcs: ensures that a hitarea never overlaps the space allocated\n // for a real data element. Helps to avoid mouse jitter when selecting tooltips in crowded areas.\n const x_center = this.parent['x_scale'](d[this.layout.x_axis.field]);\n let x_left = x_center - this.layout.hitarea_width / 2;\n if (i >= 1) {\n // This assumes that the data are in sorted order.\n const left_node = track_data[i - 1];\n const left_node_x_center = this.parent['x_scale'](left_node[this.layout.x_axis.field]);\n x_left = Math.max(x_left, (x_center + left_node_x_center) / 2);\n }\n return [x_left, x_center];\n };\n\n // Draw hitareas under real data elements, so that real data elements always take precedence\n hit_areas_selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n // Update the set of elements to reflect new data\n .merge(hit_areas_selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('height', this.parent.layout.height)\n .attr('opacity', 0)\n .attr('x', (d, i) => {\n const crds = _getX(d, i);\n return crds[0];\n })\n .attr('width', (d, i) => {\n const crds = _getX(d, i);\n return (crds[1] - crds[0]) + this.layout.hitarea_width / 2;\n });\n\n const width = 1;\n const selection = this._visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n // Draw rectangles (visual and tooltip positioning)\n selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => this.parent['x_scale'](d[this.layout.x_axis.field]) - width / 2)\n .attr('width', width)\n .attr('height', this.parent.layout.height)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i));\n\n // Remove unused elements\n selection.exit()\n .remove();\n\n // Set up tooltips and mouse interaction\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n\n // Remove unused elements\n hit_areas_selection.exit()\n .remove();\n }\n\n /**\n * Render tooltip at the center of each tick mark\n * @param tooltip\n * @return {{y_min: number, x_max: *, y_max: *, x_min: number}}\n * @private\n */\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n const data_layer_height = panel.layout.height - (panel.layout.margin.top + panel.layout.margin.bottom);\n const stroke_width = 1; // as defined in the default stylesheet\n\n const x_center = panel.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_center = data_layer_height / 2;\n return {\n x_min: x_center - stroke_width,\n x_max: x_center + stroke_width,\n y_min: y_center - panel.layout.margin.top,\n y_max: y_center + panel.layout.margin.bottom,\n };\n }\n}\n\nexport {AnnotationTrack as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~highlight_regions\n */\nconst default_layout = {\n color: '#CCCCCC',\n fill_opacity: 0.5,\n // By default, it will draw the regions shown.\n filters: null,\n // Most use cases will show a preset list of regions defined in the layout\n // (if empty, AND layout.fields is not, it could fetch from a data source instead)\n regions: [],\n id_field: 'id',\n start_field: 'start',\n end_field: 'end',\n merge_field: null,\n};\n\n/**\n * \"Highlight regions with rectangle\" data layer.\n * Creates one (or more) continuous 2D rectangles that mark an entire interval, to the full height of the panel.\n *\n * Each individual rectangle can be shown in full, or overlapping ones can be merged (eg, based on same category).\n * The rectangles are generally drawn with partial transparency, and do not respond to mouse events: they are a\n * useful highlight tool to draw attention to intervals that contain interesting variants.\n *\n * This layer has several useful modes:\n * 1. Draw one or more specified rectangles as provided from:\n * A. Hard-coded layout (layout.regions)\n * B. Data fetched from a source (like intervals with start and end coordinates)- as specified in layout.fields\n * 2. Fetch data from an external source, and only render the intervals that match criteria\n *\n * @alias module:LocusZoom_DataLayers~highlight_regions\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass HighlightRegions extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#CCCCCC'] The fill color for each rectangle\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=0.5] The opacity (0-1). We recommend partial transparency so that\n * rectangles do not hide or interfere with adjacent elements.\n * @param {Object[]} [layout.filters] An array of filter entries specifying which intervals to draw annotations for.\n * @param {Object[]} [layout.regions] A hard-coded list of regions. If provided, takes precedence over data fetched from an external source.\n * @param {String} [layout.start_field='start'] The field to use for rectangle start x coordinate\n * @param {String} [layout.end_field='end'] The field to use for rectangle end x coordinate\n * @param {String} [layout.merge_field] If two intervals overlap, they can be \"merged\" based on a field that\n * identifies the category (eg, only rectangles of the same category will be merged).\n * This field must be present in order to trigger merge behavior. This is applied after filters.\n */\n constructor(layout) {\n merge(layout, default_layout);\n if (layout.interaction || layout.behaviors) {\n throw new Error('highlight_regions layer does not support mouse events');\n }\n\n if (layout.regions && layout.regions.length && layout.fields && layout.fields.length) {\n throw new Error('highlight_regions layer can specify \"regions\" in layout, OR external data \"fields\", but not both');\n }\n super(...arguments);\n }\n\n /**\n * Helper method that combines two rectangles if they are the same type of data (category) and occupy the same\n * area of the plot (will automatically sort the data prior to rendering)\n *\n * When two fields conflict, it will fill in the fields for the last of the items that overlap in that range.\n * Thus, it is not recommended to use tooltips with this feature, because the tooltip won't reflect real data.\n * @param {Object[]} data\n * @return {Object[]}\n * @private\n */\n _mergeNodes(data) {\n const { end_field, merge_field, start_field } = this.layout;\n if (!merge_field) {\n return data;\n }\n\n // Ensure data is sorted by start field, with category as a tie breaker\n data.sort((a, b) => {\n // Ensure that data is sorted by category, then start field (ensures overlapping intervals are adjacent)\n return d3.ascending(a[merge_field], b[merge_field]) || d3.ascending(a[start_field], b[start_field]);\n });\n\n let track_data = [];\n data.forEach(function (cur_item, index) {\n const prev_item = track_data[track_data.length - 1] || cur_item;\n if (cur_item[merge_field] === prev_item[merge_field] && cur_item[start_field] <= prev_item[end_field]) {\n // If intervals overlap, merge the current item with the previous, and append only the merged interval\n const new_start = Math.min(prev_item[start_field], cur_item[start_field]);\n const new_end = Math.max(prev_item[end_field], cur_item[end_field]);\n cur_item = Object.assign({}, prev_item, cur_item, { [start_field]: new_start, [end_field]: new_end });\n track_data.pop();\n }\n track_data.push(cur_item);\n });\n return track_data;\n }\n\n render() {\n const { x_scale } = this.parent;\n // Apply filters to only render a specified set of points\n let track_data = this.layout.regions.length ? this.layout.regions : this.data;\n\n // Pseudo identifier for internal use only (regions have no semantic or transition meaning)\n track_data.forEach((d, i) => d.id || (d.id = i));\n track_data = this._applyFilters(track_data);\n track_data = this._mergeNodes(track_data);\n\n const selection = this.svg.group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data);\n\n // Draw rectangles\n selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => x_scale(d[this.layout.start_field]))\n .attr('width', (d) => x_scale(d[this.layout.end_field]) - x_scale(d[this.layout.start_field]))\n .attr('height', this.parent.layout.height)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i));\n\n // Remove unused elements\n selection.exit()\n .remove();\n\n // Note: This layer intentionally does not allow tooltips or mouse behaviors, and doesn't affect pan/zoom\n this.svg.group.style('pointer-events', 'none');\n }\n\n _getTooltipPosition(tooltip) {\n // This layer is for visual highlighting only; it does not allow mouse interaction, drag, or tooltips\n throw new Error('This layer does not support tooltips');\n }\n}\n\nexport {HighlightRegions as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {applyStyles} from '../../helpers/common';\n\n/**\n * @memberof module:LocusZoom_DataLayers~arcs\n */\nconst default_layout = {\n color: 'seagreen',\n hitarea_width: '10px',\n style: {\n fill: 'none',\n 'stroke-width': '1px',\n 'stroke-opacity': '100%',\n },\n tooltip_positioning: 'top',\n};\n\n/**\n * Arc Data Layer\n * Implements a data layer that will render chromatin accessibility tracks.\n * This layer draws arcs (one per datapoint) that connect two endpoints (x.field1 and x.field2) by means of an arc,\n * with a height determined by y.field.\n * @alias module:LocusZoom_DataLayers~arcs\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass Arcs extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='seagreen'] Specify how to choose the stroke color for each arc\n * @param {number} [layout.hitarea_width='10px'] The width (in pixels) of hitareas. Arcs are only as wide as the stroke,\n * so a hit area of 5px on each side can make it much easier to select an item for a tooltip.\n * @param {string} [layout.style.fill='none'] The fill color under the area of the arc\n * @param {string} [layout.style.stroke-width='1px']\n * @param {string} [layout.style.stroke_opacity='100%']\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='top'] Where to draw the tooltip relative to the datum.\n * @param {string} [layout.x_axis.field1] The field to use for one end of the arc; creates a point at (x1, 0)\n * @param {string} [layout.x_axis.field2] The field to use for the other end of the arc; creates a point at (x2, 0)\n * @param {string} [layout.y_axis.field] The height at the midpoint of the arc, (xmid, y)\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n }\n\n // Implement the main render function\n render() {\n const self = this;\n const layout = self.layout;\n const x_scale = self.parent['x_scale'];\n const y_scale = self.parent[`y${layout.y_axis.axis}_scale`];\n\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n // Helper: Each individual data point describes a path composed of 3 points, with a spline to smooth the line\n function _make_line(d) {\n const x1 = d[layout.x_axis.field1];\n const x2 = d[layout.x_axis.field2];\n const xmid = (x1 + x2) / 2;\n const coords = [\n [x_scale(x1), y_scale(0)],\n [x_scale(xmid), y_scale(d[layout.y_axis.field])],\n [x_scale(x2), y_scale(0)],\n ];\n // Smoothing options: https://bl.ocks.org/emmasaunders/f7178ed715a601c5b2c458a2c7093f78\n const line = d3.line()\n .x((d) => d[0])\n .y((d) => d[1])\n .curve(d3.curveNatural);\n return line(coords);\n }\n\n // Draw real lines, and also invisible hitareas for easier mouse events\n const hitareas = this.svg.group\n .selectAll('path.lz-data_layer-arcs-hitarea')\n .data(track_data, (d) => this.getElementId(d));\n\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-arcs')\n .data(track_data, (d) => this.getElementId(d));\n\n this.svg.group\n .call(applyStyles, layout.style);\n\n hitareas\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs-hitarea')\n .merge(hitareas)\n .attr('id', (d) => this.getElementId(d))\n .style('fill', 'none')\n .style('stroke-width', layout.hitarea_width)\n .style('stroke-opacity', 0)\n .style('stroke', 'transparent')\n .attr('d', (d) => _make_line(d));\n\n // Add new points as necessary\n selection\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('stroke', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('d', (d, i) => _make_line(d));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n hitareas.exit()\n .remove();\n\n // Apply mouse behaviors to arcs\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n\n return this;\n }\n\n _getTooltipPosition(tooltip) {\n // Center the tooltip arrow at the apex of the arc. Sometimes, only part of an arc shows on the screen, so we\n // clean up these values to ensure that the tooltip will appear within the window.\n const panel = this.parent;\n const layout = this.layout;\n\n const x1 = tooltip.data[layout.x_axis.field1];\n const x2 = tooltip.data[layout.x_axis.field2];\n\n const y_scale = panel[`y${layout.y_axis.axis}_scale`];\n\n return {\n x_min: panel.x_scale(Math.min(x1, x2)),\n x_max: panel.x_scale(Math.max(x1, x2)),\n y_min: y_scale(tooltip.data[layout.y_axis.field]),\n y_max: y_scale(0),\n };\n }\n\n}\n\nexport {Arcs as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~genes\n * @type {{track_vertical_spacing: number, bounding_box_padding: number, color: string, tooltip_positioning: string, exon_height: number, label_font_size: number, label_exon_spacing: number, stroke: string}}\n */\nconst default_layout = {\n // Optionally specify different fill and stroke properties\n stroke: 'rgb(54, 54, 150)',\n color: '#363696',\n label_font_size: 12,\n label_exon_spacing: 3,\n exon_height: 10,\n bounding_box_padding: 3,\n track_vertical_spacing: 5,\n tooltip_positioning: 'top',\n};\n\n\n/**\n * Genes Data Layer\n * Implements a data layer that will render gene tracks\n * @alias module:LocusZoom_DataLayers~genes\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass Genes extends BaseDataLayer {\n /**\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.stroke='rgb(54, 54, 150)'] The stroke color for each intron and exon\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#363696'] The fill color for each intron and exon\n * @param {number} [layout.label_font_size]\n * @param {number} [layout.label_exon_spacing] The number of px padding between exons and the gene label\n * @param {number} [layout.exon_height=10] The height of each exon (vertical line) when drawing the gene\n * @param {number} [layout.bounding_box_padding=3] Padding around edges of the bounding box, as shown when highlighting a selected gene\n * @param {number} [layout.track_vertical_spacing=5] Vertical spacing between each row of genes\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='top'] Where to draw the tooltip relative to the datum.\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n /**\n * A gene may have arbitrarily many transcripts, but this data layer isn't set up to render them yet.\n * Stash a transcript_idx to point to the first transcript and use that for all transcript refs.\n * @member {number}\n * @type {number}\n */\n this.transcript_idx = 0;\n\n /**\n * An internal counter for the number of tracks in the data layer. Used as an internal counter for looping\n * over positions / assignments\n * @protected\n * @member {number}\n */\n this.tracks = 1;\n\n /**\n * Store information about genes in dataset, in a hash indexed by track number: {track_number: [gene_indices]}\n * @member {Object.}\n */\n this.gene_track_index = { 1: [] };\n }\n\n /**\n * Generate a statusnode ID for a given element\n * @override\n * @returns {String}\n */\n getElementStatusNodeId(element) {\n return `${this.getElementId(element)}-statusnode`;\n }\n\n /**\n * Helper function to sum layout values to derive total height for a single gene track\n * @returns {number}\n */\n getTrackHeight() {\n return 2 * this.layout.bounding_box_padding\n + this.layout.label_font_size\n + this.layout.label_exon_spacing\n + this.layout.exon_height\n + this.layout.track_vertical_spacing;\n }\n\n /**\n * Ensure that genes in overlapping chromosome regions are positioned so that parts of different genes do not\n * overlap in the view. A track is a row used to vertically separate overlapping genes.\n * @returns {Genes}\n */\n assignTracks(data) {\n /**\n * Function to get the width in pixels of a label given the text and layout attributes\n * @param {String} gene_name\n * @param {number|string} font_size\n * @returns {number}\n */\n const _getLabelWidth = (gene_name, font_size) => {\n try {\n const temp_text = this.svg.group.append('text')\n .attr('x', 0)\n .attr('y', 0)\n .attr('class', 'lz-data_layer-genes lz-label')\n .style('font-size', font_size)\n .text(`${gene_name}→`);\n const label_width = temp_text.node().getBBox().width;\n temp_text.remove();\n return label_width;\n } catch (e) {\n return 0;\n }\n };\n\n // Reinitialize some metadata\n this.tracks = 1;\n this.gene_track_index = { 1: [] };\n\n return data\n // Filter out any genes that are fully outside the region of interest. This allows us to use cached data\n // when zooming in, without breaking the layout by allocating space for genes that are not visible.\n .filter((item) => !(item.end < this.state.start) && !(item.start > this.state.end))\n .map((item) => {\n // If necessary, split combined gene id / version fields into discrete fields.\n // NOTE: this may be an issue with CSG's genes data API that may eventually be solved upstream.\n if (item.gene_id && item.gene_id.indexOf('.')) {\n const split = item.gene_id.split('.');\n item.gene_id = split[0];\n item.gene_version = split[1];\n }\n\n // Stash the transcript ID on the parent gene\n item.transcript_id = item.transcripts[this.transcript_idx].transcript_id;\n\n // Determine display range start and end, based on minimum allowable gene display width, bounded by what we can see\n // (range: values in terms of pixels on the screen)\n item.display_range = {\n start: this.parent.x_scale(Math.max(item.start, this.state.start)),\n end: this.parent.x_scale(Math.min(item.end, this.state.end)),\n };\n item.display_range.label_width = _getLabelWidth(item.gene_name, this.layout.label_font_size);\n item.display_range.width = item.display_range.end - item.display_range.start;\n // Determine label text anchor (default to middle)\n item.display_range.text_anchor = 'middle';\n if (item.display_range.width < item.display_range.label_width) {\n if (item.start < this.state.start) {\n item.display_range.end = item.display_range.start\n + item.display_range.label_width\n + this.layout.label_font_size;\n item.display_range.text_anchor = 'start';\n } else if (item.end > this.state.end) {\n item.display_range.start = item.display_range.end\n - item.display_range.label_width\n - this.layout.label_font_size;\n item.display_range.text_anchor = 'end';\n } else {\n const centered_margin = ((item.display_range.label_width - item.display_range.width) / 2)\n + this.layout.label_font_size;\n if ((item.display_range.start - centered_margin) < this.parent.x_scale(this.state.start)) {\n item.display_range.start = this.parent.x_scale(this.state.start);\n item.display_range.end = item.display_range.start + item.display_range.label_width;\n item.display_range.text_anchor = 'start';\n } else if ((item.display_range.end + centered_margin) > this.parent.x_scale(this.state.end)) {\n item.display_range.end = this.parent.x_scale(this.state.end);\n item.display_range.start = item.display_range.end - item.display_range.label_width;\n item.display_range.text_anchor = 'end';\n } else {\n item.display_range.start -= centered_margin;\n item.display_range.end += centered_margin;\n }\n }\n item.display_range.width = item.display_range.end - item.display_range.start;\n }\n // Add bounding box padding to the calculated display range start, end, and width\n item.display_range.start -= this.layout.bounding_box_padding;\n item.display_range.end += this.layout.bounding_box_padding;\n item.display_range.width += 2 * this.layout.bounding_box_padding;\n // Convert and stash display range values into domain values\n // (domain: values in terms of the data set, e.g. megabases)\n item.display_domain = {\n start: this.parent.x_scale.invert(item.display_range.start),\n end: this.parent.x_scale.invert(item.display_range.end),\n };\n item.display_domain.width = item.display_domain.end - item.display_domain.start;\n\n // Using display range/domain data generated above cast each gene to tracks such that none overlap\n item.track = null;\n let potential_track = 1;\n while (item.track === null) {\n let collision_on_potential_track = false;\n this.gene_track_index[potential_track].map((placed_gene) => {\n if (!collision_on_potential_track) {\n const min_start = Math.min(placed_gene.display_range.start, item.display_range.start);\n const max_end = Math.max(placed_gene.display_range.end, item.display_range.end);\n if ((max_end - min_start) < (placed_gene.display_range.width + item.display_range.width)) {\n collision_on_potential_track = true;\n }\n }\n });\n if (!collision_on_potential_track) {\n item.track = potential_track;\n this.gene_track_index[potential_track].push(item);\n } else {\n potential_track++;\n if (potential_track > this.tracks) {\n this.tracks = potential_track;\n this.gene_track_index[potential_track] = [];\n }\n }\n }\n\n // Stash parent references on all genes, transcripts, and exons\n item.parent = this;\n item.transcripts.map((d, t) => {\n item.transcripts[t].parent = item;\n item.transcripts[t].exons.map((d, e) => item.transcripts[t].exons[e].parent = item.transcripts[t]);\n });\n return item;\n });\n }\n\n /**\n * Main render function\n */\n render() {\n const self = this;\n // Apply filters to only render a specified set of points\n let track_data = this._applyFilters();\n track_data = this.assignTracks(track_data);\n let height;\n\n // Render gene groups\n const selection = this.svg.group.selectAll('g.lz-data_layer-genes')\n .data(track_data, (d) => d.gene_name);\n\n selection.enter()\n .append('g')\n .attr('class', 'lz-data_layer-genes')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .each(function(gene) {\n const data_layer = gene.parent;\n\n // Render gene bounding boxes (status nodes to show selected/highlighted)\n const bboxes = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-data_layer-genes-statusnode')\n .data([gene], (d) => data_layer.getElementStatusNodeId(d));\n\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n\n bboxes.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-data_layer-genes-statusnode')\n .merge(bboxes)\n .attr('id', (d) => data_layer.getElementStatusNodeId(d))\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', (d) => d.display_range.width)\n .attr('height', height)\n .attr('x', (d) => d.display_range.start)\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight()));\n\n bboxes.exit()\n .remove();\n\n // Render gene boundaries\n const boundaries = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-boundary')\n .data([gene], (d) => `${d.gene_name}_boundary`);\n\n height = 1;\n boundaries.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-boundary')\n .merge(boundaries)\n .attr('width', (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start))\n .attr('height', height)\n .attr('x', (d) => data_layer.parent.x_scale(d.start))\n .attr('y', (d) => {\n return ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing\n + (Math.max(data_layer.layout.exon_height, 3) / 2);\n })\n .style('fill', (d, i) => self.resolveScalableParameter(self.layout.color, d, i))\n .style('stroke', (d, i) => self.resolveScalableParameter(self.layout.stroke, d, i));\n\n boundaries.exit()\n .remove();\n\n // Render gene labels\n const labels = d3.select(this).selectAll('text.lz-data_layer-genes.lz-label')\n .data([gene], (d) => `${d.gene_name}_label`);\n\n labels.enter()\n .append('text')\n .attr('class', 'lz-data_layer-genes lz-label')\n .merge(labels)\n .attr('text-anchor', (d) => d.display_range.text_anchor)\n .text((d) => (d.strand === '+') ? `${d.gene_name}→` : `←${d.gene_name}`)\n .style('font-size', gene.parent.layout.label_font_size)\n .attr('x', (d) => {\n if (d.display_range.text_anchor === 'middle') {\n return d.display_range.start + (d.display_range.width / 2);\n } else if (d.display_range.text_anchor === 'start') {\n return d.display_range.start + data_layer.layout.bounding_box_padding;\n } else if (d.display_range.text_anchor === 'end') {\n return d.display_range.end - data_layer.layout.bounding_box_padding;\n }\n })\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n );\n\n labels.exit()\n .remove();\n\n // Render exon rects (first transcript only, for now)\n // Exons: by default color on gene properties for consistency with the gene boundary track- hence color uses d.parent.parent\n const exons = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-exon')\n .data(gene.transcripts[gene.parent.transcript_idx].exons, (d) => d.exon_id);\n\n height = data_layer.layout.exon_height;\n\n exons.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-exon')\n .merge(exons)\n .style('fill', (d, i) => self.resolveScalableParameter(self.layout.color, d.parent.parent, i))\n .style('stroke', (d, i) => self.resolveScalableParameter(self.layout.stroke, d.parent.parent, i))\n .attr('width', (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start))\n .attr('height', height)\n .attr('x', (d) => data_layer.parent.x_scale(d.start))\n .attr('y', () => {\n return ((gene.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing;\n });\n\n exons.exit()\n .remove();\n\n // Render gene click area\n const clickareas = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-clickarea')\n .data([gene], (d) => `${d.gene_name}_clickarea`);\n\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n clickareas.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-clickarea')\n .merge(clickareas)\n .attr('id', (d) => `${data_layer.getElementId(d)}_clickarea`)\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', (d) => d.display_range.width)\n .attr('height', height)\n .attr('x', (d) => d.display_range.start)\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight()));\n\n // Remove old clickareas as needed\n clickareas.exit()\n .remove();\n });\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n // Apply mouse behaviors & events to clickareas\n this.svg.group\n .on('click.event_emitter', (element) => this.parent.emit('element_clicked', element, true))\n .call(this.applyBehaviors.bind(this));\n }\n\n _getTooltipPosition(tooltip) {\n const gene_bbox_id = this.getElementStatusNodeId(tooltip.data);\n const gene_bbox = d3.select(`#${gene_bbox_id}`).node().getBBox();\n return {\n x_min: this.parent.x_scale(tooltip.data.start),\n x_max: this.parent.x_scale(tooltip.data.end),\n y_min: gene_bbox.y,\n y_max: gene_bbox.y + gene_bbox.height,\n };\n }\n}\n\nexport {Genes as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {STATUSES} from '../constants';\nimport {applyStyles} from '../../helpers/common';\n\n/**\n * @memberof module:LocusZoom_DataLayers~line\n */\nconst default_layout = {\n style: {\n fill: 'none',\n 'stroke-width': '2px',\n },\n interpolate: 'curveLinear',\n x_axis: { field: 'x' },\n y_axis: { field: 'y', axis: 1 },\n hitarea_width: 5,\n};\n\n/*********************\n * Line Data Layer\n * Implements a standard line plot, representing either a trace or a filled curve. Only one line is drawn per layer used.\n * @alias module:LocusZoom_DataLayers~line\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n*/\nclass Line extends BaseDataLayer {\n /**\n * @param {object} [layout.style] CSS properties to control how the line is drawn\n * @param {string} [layout.style.fill='none'] Fill color for the area under the curve\n * @param {string} [layout.style.stroke]\n * @param {string} [layout.style.stroke-width='2px']\n * @param {string} [layout.interpolate='curveLinear'] The name of the d3 interpolator to use. This determines how to smooth the line in between data points.\n * @param {number} [layout.hitarea_width=5] The size of mouse event hitareas to use. If tooltips are not used, hitareas are not very important.\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n if (layout.tooltip) {\n throw new Error('The line / filled curve layer does not support tooltips');\n }\n super(...arguments);\n }\n\n /**\n * Implement the main render function\n */\n render() {\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_field = this.layout.x_axis.field;\n const y_field = this.layout.y_axis.field;\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line');\n\n // Generate the line\n let line;\n const x_scale = panel['x_scale'];\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n if (this.layout.style.fill && this.layout.style.fill !== 'none') {\n // Filled curve: define the line as a filled boundary\n line = d3.area()\n .x((d) => +x_scale(d[x_field]))\n .y0(+y_scale(0))\n .y1((d) => +y_scale(d[y_field]));\n } else {\n // Basic line\n line = d3.line()\n .x((d) => +x_scale(d[x_field]))\n .y((d) => +y_scale(d[y_field]))\n .curve(d3[this.layout.interpolate]);\n }\n\n // Apply line and style\n selection.merge(this.path)\n .attr('d', line)\n .call(applyStyles, this.layout.style);\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n }\n\n /**\n * Redefine setElementStatus family of methods as line data layers will only ever have a single path element\n * @param {String} status A member of `LocusZoom.DataLayer.Statuses.adjectives`\n * @param {String|Object} element\n * @param {Boolean} toggle\n */\n setElementStatus(status, element, toggle) {\n return this.setAllElementStatus(status, toggle);\n }\n\n setAllElementStatus(status, toggle) {\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n // Apply class to path based on global status flags\n let path_class = 'lz-data_layer-line';\n Object.keys(this.global_statuses).forEach((global_status) => {\n if (this.global_statuses[global_status]) {\n path_class += ` lz-data_layer-line-${global_status}`;\n }\n });\n this.path.attr('class', path_class);\n\n // Trigger layout changed event hook\n this.parent.emit('layout_changed', true);\n return this;\n }\n}\n\n/**\n * @memberof module:LocusZoom_DataLayers~orthogonal_line\n */\nconst default_orthogonal_layout = {\n style: {\n 'stroke': '#D3D3D3',\n 'stroke-width': '3px',\n 'stroke-dasharray': '10px 10px',\n },\n orientation: 'horizontal',\n x_axis: {\n axis: 1,\n decoupled: true,\n },\n y_axis: {\n axis: 1,\n decoupled: true,\n },\n tooltip_positioning: 'vertical',\n offset: 0,\n};\n\n\n/**\n * Orthogonal Line Data Layer\n * Draw a horizontal or vertical line given an orientation and an offset in the layout\n * Does not require a data source or fields.\n * @alias module:LocusZoom_DataLayers~orthogonal_line\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass OrthogonalLine extends BaseDataLayer {\n /**\n * @param {string} [layout.style.stroke='#D3D3D3']\n * @param {string} [layout.style.stroke-width='3px']\n * @param {string} [layout.style.stroke-dasharray='10px 10px']\n * @param {'horizontal'|'vertical'} [layout.orientation] The orientation of the horizontal line\n * @param {boolean} [layout.x_axis.decoupled=true] If true, the data in this layer will not influence the x-extent of the panel.\n * @param {boolean} [layout.y_axis.decoupled=true] If true, the data in this layer will not influence the y-extent of the panel.\n * @param {'horizontal'|'vertical'} [layout.tooltip_positioning='vertical'] Where to draw the tooltip relative to the mouse pointer.\n * @param {number} [layout.offset=0] Where the line intercepts the orthogonal axis (eg, the y coordinate for a horizontal line, or x for a vertical line)\n */\n constructor(layout) {\n layout = merge(layout, default_orthogonal_layout);\n // Require that orientation be \"horizontal\" or \"vertical\" only\n if (!['horizontal', 'vertical'].includes(layout.orientation)) {\n layout.orientation = 'horizontal';\n }\n super(...arguments);\n\n // Vars for storing the data generated line\n /** @member {Array} */\n this.data = [];\n }\n\n getElementId(element) {\n // There is only one line per datalayer, so this is sufficient.\n return this.getBaseId();\n }\n\n /**\n * Implement the main render function\n */\n render() {\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const x_extent = 'x_extent';\n const y_extent = `y${this.layout.y_axis.axis}_extent`;\n const x_range = 'x_range';\n\n // Generate data using extents depending on orientation\n if (this.layout.orientation === 'horizontal') {\n this.data = [\n { x: panel[x_extent][0], y: this.layout.offset },\n { x: panel[x_extent][1], y: this.layout.offset },\n ];\n } else if (this.layout.orientation === 'vertical') {\n this.data = [\n { x: this.layout.offset, y: panel[y_extent][0] },\n { x: this.layout.offset, y: panel[y_extent][1] },\n ];\n } else {\n throw new Error('Unrecognized vertical line type. Must be \"vertical\" or \"horizontal\"');\n }\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // In some cases, a vertical line may overlay a track that has no inherent y-values (extent)\n // When that happens, provide a default height based on the current panel dimensions (accounting\n // for any resizing that happened after the panel was created)\n const default_y = [panel.layout.cliparea.height, 0];\n\n // Generate the line\n const line = d3.line()\n .x((d, i) => {\n const x = +panel[x_scale](d['x']);\n return isNaN(x) ? panel[x_range][i] : x;\n })\n .y((d, i) => {\n const y = +panel[y_scale](d['y']);\n return isNaN(y) ? default_y[i] : y;\n });\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line')\n .merge(selection)\n .attr('d', line)\n .call(applyStyles, this.layout.style)\n // Allow the layer to respond to mouseover events and show a tooltip.\n .call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n }\n\n _getTooltipPosition(tooltip) {\n try {\n const coords = d3.mouse(this.svg.container.node());\n const x = coords[0];\n const y = coords[1];\n return { x_min: x - 1, x_max: x + 1, y_min: y - 1, y_max: y + 1 };\n } catch (e) {\n // On redraw, there won't be a mouse event, so skip tooltip repositioning.\n return null;\n }\n }\n\n}\n\n\nexport { Line as line, OrthogonalLine as orthogonal_line };\n","import * as d3 from 'd3';\nimport BaseDataLayer from './base';\nimport {applyStyles} from '../../helpers/common';\nimport {parseFields} from '../../helpers/display';\nimport {merge, nameToSymbol} from '../../helpers/layouts';\nimport {coalesce_scatter_points} from '../../helpers/render';\n\n/**\n * @memberof module:LocusZoom_DataLayers~scatter\n */\nconst default_layout = {\n point_size: 40,\n point_shape: 'circle',\n tooltip_positioning: 'horizontal',\n color: '#888888',\n coalesce: {\n active: false,\n max_points: 800, // Many plots are 800-2400 px wide, so, more than 1 datum per pixel of average region width\n // Define the \"region of interest\", like \"bottom half of plot\"; any points outside this region are taken as is\n // Values are expressed in terms of data value and will be converted to pixels internally.\n x_min: '-Infinity', // JSON doesn't handle some valid JS numbers. Kids, don't get a career in computers.\n x_max: 'Infinity',\n y_min: 0,\n y_max: 3.0,\n x_gap: 7,\n y_gap: 7,\n },\n fill_opacity: 1,\n y_axis: {\n axis: 1,\n },\n id_field: 'id',\n};\n\n/**\n * Options that control point-coalescing in scatter plots\n * @typedef {object} module:LocusZoom_DataLayers~scatter~coalesce_options\n * @property {boolean} [active=false] Whether to use this feature. Typically used for GWAS plots, but\n * not other scatter plots such as PheWAS.\n * @property {number} [max_points=800] Only attempt to reduce DOM size if there are at least this many\n * points. Many plots are 800-2400 px wide, so, more than 1 datum per pixel of average region width. For more\n * sparse datasets, all points will be faithfully rendered even if coalesce.active=true.\n * @property {number} [x_min='-Infinity'] Min x coordinate of the region where points will be coalesced\n * @property {number} [x_max='Infinity'] Max x coordinate of the region where points will be coalesced\n * @property {number} [y_min=0] Min y coordinate of the region where points will be coalesced.\n * @property {number} [y_max=3.0] Max y coordinate of the region where points will be coalesced\n * @property {number} [x_gap=7] Max number of pixels between the center of two points that can be\n * coalesced. For circles, area 40 = radius ~3.5; aim for ~1 diameter distance.\n * @property {number} [y_gap=7]\n */\n\n/**\n * Scatter Data Layer\n * Implements a standard scatter plot\n * @alias module:LocusZoom_DataLayers~scatter\n */\nclass Scatter extends BaseDataLayer {\n /**\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.point_size=40] The size (area) of the point for each datum\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.point_shape='circle'] Shape of the point for each datum. Supported values map to the d3 SVG Symbol Types (i.e.: \"circle\", \"cross\", \"diamond\", \"square\", \"triangle\", \"star\", and \"wye\"), plus \"triangledown\".\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#888888'] The color of the point for each datum\n * @param {module:LocusZoom_DataLayers~scatter~coalesce_options} [layout.coalesce] Options to control whether and how to combine adjacent insignificant (\"within region of interest\") points\n * to improve rendering performance. These options are primarily aimed at GWAS region plots. Within a specified\n * rectangle area (eg \"insignificant point cutoff\"), we choose only points far enough part to be seen.\n * The defaults are specifically tuned for GWAS plots with -log(p) on the y-axis.\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1] Opacity (0..1) for each datum point\n * @param {string} [layout.label.text] Similar to tooltips: a template string that can reference datum fields for label text.\n * @param {number} [layout.label.spacing] Distance (in px) between the label and the center of the datum.\n * @param {object} [layout.label.lines.style] CSS style options for how the line is rendered\n * @param {number} [layout.label.filters] Filters that describe which points to label. For performance reasons,\n * we recommend labeling only a small subset of most interesting points.\n * @param {object} [layout.label.style] CSS style options for label text\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n\n // Extra default for layout spacing\n // Not in default layout since that would make the label attribute always present\n if (layout.label && isNaN(layout.label.spacing)) {\n layout.label.spacing = 4;\n }\n super(...arguments);\n }\n\n // Implement tooltip position to be layer-specific\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n\n return {\n x_min: x_center - offset, x_max: x_center + offset,\n y_min: y_center - offset, y_max: y_center + offset,\n };\n }\n\n // Function to flip labels from being anchored at the start of the text to the end\n // Both to keep labels from running outside the data layer and also as a first\n // pass on recursive separation\n flip_labels() {\n const data_layer = this;\n // Base positions on the default point size (which is what resolve scalable param returns if no data provided)\n const point_size = data_layer.resolveScalableParameter(data_layer.layout.point_size, {});\n const spacing = data_layer.layout.label.spacing;\n const handle_lines = Boolean(data_layer.layout.label.lines);\n const min_x = 2 * spacing;\n const max_x = this.parent_plot.layout.width - this.parent.layout.margin.left - this.parent.layout.margin.right - (2 * spacing);\n\n const flip = (dn, dnl) => {\n const dnx = +dn.attr('x');\n const text_swing = (2 * spacing) + (2 * Math.sqrt(point_size));\n let dnlx2;\n let line_swing;\n if (handle_lines) {\n dnlx2 = +dnl.attr('x2');\n line_swing = spacing + (2 * Math.sqrt(point_size));\n }\n if (dn.style('text-anchor') === 'start') {\n dn.style('text-anchor', 'end');\n dn.attr('x', dnx - text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 - line_swing);\n }\n } else {\n dn.style('text-anchor', 'start');\n dn.attr('x', dnx + text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 + line_swing);\n }\n }\n };\n // Flip any going over the right edge from the right side to the left side\n // (all labels start on the right side)\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n const dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n if (dax + abound.width + spacing > max_x) {\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n flip(da, dal);\n }\n });\n // Second pass to flip any others that haven't flipped yet if they collide with another label\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n if (da.style('text-anchor') === 'end') {\n return;\n }\n let dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n data_layer.label_texts.each(function () {\n const b = this;\n const db = d3.select(b);\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (collision) {\n flip(da, dal);\n // Double check that this flip didn't push the label past min_x. If it did, immediately flip back.\n dax = +da.attr('x');\n if (dax - abound.width - spacing < min_x) {\n flip(da, dal);\n }\n }\n });\n });\n }\n\n // Recursive function to space labels apart immediately after initial render\n // Adapted from thudfactor's fiddle here: https://jsfiddle.net/thudfactor/HdwTH/\n // TODO: Make labels also aware of data elements\n separate_labels() {\n this.seperate_iterations++;\n const data_layer = this;\n const alpha = 0.5;\n if (!this.layout.label) {\n // Guard against layout changing in the midst of iterative rerender\n return;\n }\n const spacing = this.layout.label.spacing;\n let again = false;\n data_layer.label_texts.each(function () {\n // TODO: O(n2) algorithm; revisit performance?\n const a = this;\n const da = d3.select(a);\n const y1 = da.attr('y');\n data_layer.label_texts.each(function () {\n const b = this;\n // a & b are the same element and don't collide.\n if (a === b) {\n return;\n }\n const db = d3.select(b);\n // a & b are on opposite sides of the chart and\n // don't collide\n if (da.attr('text-anchor') !== db.attr('text-anchor')) {\n return;\n }\n // Determine if the bounding rects for the two text elements collide\n const abound = da.node().getBoundingClientRect();\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (!collision) {\n return;\n }\n again = true;\n // If the labels collide, we'll push each\n // of the two labels up and down a little bit.\n const y2 = db.attr('y');\n const sign = abound.top < bbound.top ? 1 : -1;\n const adjust = sign * alpha;\n let new_a_y = +y1 - adjust;\n let new_b_y = +y2 + adjust;\n // Keep new values from extending outside the data layer\n const min_y = 2 * spacing;\n const max_y = data_layer.parent.layout.height - data_layer.parent.layout.margin.top - data_layer.parent.layout.margin.bottom - (2 * spacing);\n let delta;\n if (new_a_y - (abound.height / 2) < min_y) {\n delta = +y1 - new_a_y;\n new_a_y = +y1;\n new_b_y += delta;\n } else if (new_b_y - (bbound.height / 2) < min_y) {\n delta = +y2 - new_b_y;\n new_b_y = +y2;\n new_a_y += delta;\n }\n if (new_a_y + (abound.height / 2) > max_y) {\n delta = new_a_y - +y1;\n new_a_y = +y1;\n new_b_y -= delta;\n } else if (new_b_y + (bbound.height / 2) > max_y) {\n delta = new_b_y - +y2;\n new_b_y = +y2;\n new_a_y -= delta;\n }\n da.attr('y', new_a_y);\n db.attr('y', new_b_y);\n });\n });\n if (again) {\n // Adjust lines to follow the labels\n if (data_layer.layout.label.lines) {\n const label_elements = data_layer.label_texts.nodes();\n data_layer.label_lines.attr('y2', (d, i) => {\n const label_line = d3.select(label_elements[i]);\n return label_line.attr('y');\n });\n }\n // After ~150 iterations we're probably beyond diminising returns, so stop recursing\n if (this.seperate_iterations < 150) {\n setTimeout(() => {\n this.separate_labels();\n }, 1);\n }\n }\n }\n\n // Implement the main render function\n render() {\n const data_layer = this;\n const x_scale = this.parent['x_scale'];\n const y_scale = this.parent[`y${this.layout.y_axis.axis}_scale`];\n\n const xcs = Symbol.for('lzX');\n const ycs = Symbol.for('lzY');\n\n // Apply filters to only render a specified set of points\n let track_data = this._applyFilters();\n\n // Add coordinates before rendering, so we can coalesce\n track_data.forEach((item) => {\n let x = x_scale(item[this.layout.x_axis.field]);\n let y = y_scale(item[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n item[xcs] = x;\n item[ycs] = y;\n });\n\n if (this.layout.coalesce.active && track_data.length > this.layout.coalesce.max_points) {\n let { x_min, x_max, y_min, y_max, x_gap, y_gap } = this.layout.coalesce;\n // Convert x and y \"significant region\" range from data values to pixels\n const x_min_px = isFinite(x_min) ? x_scale(+x_min) : -Infinity;\n const x_max_px = isFinite(x_max) ? x_scale(+x_max) : Infinity;\n // For y px, we flip the data min/max b/c in SVG coord system +y is down: smaller data y = larger px y\n const y_min_px = isFinite(y_max) ? y_scale(+y_max) : -Infinity;\n const y_max_px = isFinite(y_min) ? y_scale(+y_min) : Infinity;\n track_data = coalesce_scatter_points(track_data, x_min_px, x_max_px, x_gap, y_min_px, y_max_px, y_gap);\n }\n\n if (this.layout.label) {\n let label_data;\n const filters = data_layer.layout.label.filters || [];\n if (!filters.length) {\n label_data = track_data;\n } else {\n const func = this.filter.bind(this, filters);\n label_data = track_data.filter(func);\n }\n\n // Render label groups\n this.label_groups = this.svg.group\n .selectAll(`g.lz-data_layer-${this.layout.type}-label`)\n .data(label_data, (d) => `${d[this.layout.id_field]}_label`);\n\n const style_class = `lz-data_layer-${this.layout.type}-label`;\n const groups_enter = this.label_groups.enter()\n .append('g')\n .attr('class', style_class);\n\n if (this.label_texts) {\n this.label_texts.remove();\n }\n\n this.label_texts = this.label_groups.merge(groups_enter)\n .append('text')\n .text((d) => parseFields(data_layer.layout.label.text || '', d, this.getElementAnnotation(d)))\n .attr('x', (d) => {\n return d[xcs]\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + data_layer.layout.label.spacing;\n })\n .attr('y', (d) => d[ycs])\n .attr('text-anchor', 'start')\n .call(applyStyles, data_layer.layout.label.style || {});\n\n // Render label lines\n if (data_layer.layout.label.lines) {\n if (this.label_lines) {\n this.label_lines.remove();\n }\n this.label_lines = this.label_groups.merge(groups_enter)\n .append('line')\n .attr('x1', (d) => d[xcs])\n .attr('y1', (d) => d[ycs])\n .attr('x2', (d) => {\n return d[xcs]\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + (data_layer.layout.label.spacing / 2);\n })\n .attr('y2', (d) => d[ycs])\n .call(applyStyles, data_layer.layout.label.lines.style || {});\n }\n // Remove labels when they're no longer in the filtered data set\n this.label_groups.exit()\n .remove();\n } else {\n // If the layout definition has changed (& no longer specifies labels), strip any previously rendered\n if (this.label_texts) {\n this.label_texts.remove();\n }\n if (this.label_lines) {\n this.label_lines.remove();\n }\n if (this.label_groups) {\n this.label_groups.remove();\n }\n }\n\n // Generate main scatter data elements\n const selection = this.svg.group\n .selectAll(`path.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n\n // Create elements, apply class, ID, and initial position\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => `translate(${d[xcs]}, ${d[ycs]})`;\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => nameToSymbol(this.resolveScalableParameter(this.layout.point_shape, d, i)));\n\n const style_class = `lz-data_layer-${this.layout.type}`;\n selection.enter()\n .append('path')\n .attr('class', style_class)\n .attr('id', (d) => this.getElementId(d))\n .merge(selection)\n .attr('transform', transform)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i))\n .attr('d', shape);\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n // Apply method to keep labels from overlapping each other\n if (this.layout.label) {\n this.flip_labels();\n this.seperate_iterations = 0;\n this.separate_labels();\n }\n\n // Apply default event emitters & mouse behaviors. Apply to the container, not per element,\n // to reduce number of event listeners. These events will apply to both scatter points and labels.\n this.svg.group\n .on('click.event_emitter', () => {\n // D3 doesn't natively support bubbling very well; we need to find the data for the bubbled event\n const item_data = d3.select(d3.event.target).datum();\n this.parent.emit('element_clicked', item_data, true);\n })\n .call(this.applyBehaviors.bind(this));\n }\n\n /**\n * A new LD reference variant has been selected (usually by clicking within a GWAS scatter plot)\n * This event only fires for manually selected variants. It does not fire if the LD reference variant is\n * automatically selected (eg by choosing the most significant hit in the region)\n * @event set_ldrefvar\n * @property {object} data { ldrefvar } The variant identifier of the LD reference variant\n * @see event:any_lz_event\n */\n\n /**\n * Method to set a passed element as the LD reference variant in the plot-level state. Triggers a re-render\n * so that the plot will update with the new LD information.\n * This is useful in tooltips, eg the \"make LD reference\" action link for GWAS scatter plots.\n * @param {object} element The data associated with a particular plot element\n * @fires event:set_ldrefvar\n * @return {Promise}\n */\n makeLDReference(element) {\n let ref = null;\n if (typeof element == 'undefined') {\n throw new Error('makeLDReference requires one argument of any type');\n } else if (typeof element == 'object') {\n if (this.layout.id_field && typeof element[this.layout.id_field] != 'undefined') {\n ref = element[this.layout.id_field].toString();\n } else if (typeof element['id'] != 'undefined') {\n ref = element['id'].toString();\n } else {\n ref = element.toString();\n }\n } else {\n ref = element.toString();\n }\n this.parent.emit('set_ldrefvar', { ldrefvar: ref }, true);\n return this.parent_plot.applyState({ ldrefvar: ref });\n }\n}\n\n/**\n * A scatter plot in which the x-axis represents categories, rather than individual positions.\n * For example, this can be used by PheWAS plots to show related groups. This plot allows the categories and color options to be\n * determined dynamically when data is first loaded.\n * @alias module:LocusZoom_DataLayers~category_scatter\n */\nclass CategoryScatter extends Scatter {\n /**\n * @param {string} layout.x_axis.category_field The datum field to use in auto-generating tick marks, color scheme, and point ordering.\n */\n constructor(layout) {\n super(...arguments);\n /**\n * Define category names and extents (boundaries) for plotting.\n * In the form {category_name: [min_x, max_x]}\n * @private\n * @member {Object.}\n */\n this._categories = {};\n }\n\n /**\n * This plot layer makes certain assumptions about the data passed in. Transform the raw array of records from\n * the datasource to prepare it for plotting, as follows:\n * 1. The scatter plot assumes that all records are given in sequence (pre-grouped by `category_field`)\n * 2. It assumes that all records have an x coordinate for individual plotting\n * @private\n */\n _prepareData() {\n const xField = this.layout.x_axis.field || 'x';\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n // Sort the data so that things in the same category are adjacent (case-insensitive by specified field)\n const sourceData = this.data\n .sort((a, b) => {\n const ak = a[category_field];\n const bk = b[category_field];\n const av = (typeof ak === 'string') ? ak.toLowerCase() : ak;\n const bv = (typeof bk === 'string') ? bk.toLowerCase() : bk;\n return (av === bv) ? 0 : (av < bv ? -1 : 1);\n });\n sourceData.forEach((d, i) => {\n // Implementation detail: Scatter plot requires specifying an x-axis value, and most datasources do not\n // specify plotting positions. If a point is missing this field, fill in a synthetic value.\n d[xField] = d[xField] || i;\n });\n return sourceData;\n }\n\n /**\n * Identify the unique categories on the plot, and update the layout with an appropriate color scheme.\n * Also identify the min and max x value associated with the category, which will be used to generate ticks\n * @private\n * @returns {Object.} Series of entries used to build category name ticks {category_name: [min_x, max_x]}\n */\n _generateCategoryBounds() {\n // TODO: API may return null values in category_field; should we add placeholder category label?\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n const xField = this.layout.x_axis.field || 'x';\n const uniqueCategories = {};\n this.data.forEach((item) => {\n const category = item[category_field];\n const x = item[xField];\n const bounds = uniqueCategories[category] || [x, x];\n uniqueCategories[category] = [Math.min(bounds[0], x), Math.max(bounds[1], x)];\n });\n\n const categoryNames = Object.keys(uniqueCategories);\n this._setDynamicColorScheme(categoryNames);\n\n return uniqueCategories;\n }\n\n /**\n * This layer relies on defining its own category-based color scheme. Find the correct color config object to\n * be modified.\n * @param [from_source]\n * @returns {Object} A mutable reference to the layout configuration object\n * @private\n */\n _getColorScale(from_source) {\n from_source = from_source || this.layout;\n // If the layout does not use a supported coloring scheme, or is already complete, this method should do nothing\n\n // For legacy reasons, layouts can specify color as an object (only one way to set color), as opposed to the\n // preferred mechanism of array (multiple coloring options)\n let color_params = from_source.color || []; // Object or scalar, no other options allowed\n if (Array.isArray(color_params)) {\n color_params = color_params.find((item) => item.scale_function === 'categorical_bin');\n }\n if (!color_params || color_params.scale_function !== 'categorical_bin') {\n throw new Error('This layer requires that color options be provided as a `categorical_bin`');\n }\n return color_params;\n }\n\n /**\n * Automatically define a color scheme for the layer based on data returned from the server.\n * If part of the color scheme has been specified, it will fill in remaining missing information.\n *\n * There are three scenarios:\n * 1. The layout does not specify either category names or (color) values. Dynamically build both based on\n * the data and update the layout.\n * 2. The layout specifies colors, but not categories. Use that exact color information provided, and dynamically\n * determine what categories are present in the data. (cycle through the available colors, reusing if there\n * are a lot of categories)\n * 3. The layout specifies exactly what colors and categories to use (and they match the data!). This is useful to\n * specify an explicit mapping between color scheme and category names, when you want to be sure that the\n * plot matches a standard color scheme.\n * (If the layout specifies categories that do not match the data, the user specified categories will be ignored)\n *\n * This method will only act if the layout defines a `categorical_bin` scale function for coloring. It may be\n * overridden in a subclass to suit other types of coloring methods.\n *\n * @param {String[]} categoryNames\n * @private\n */\n _setDynamicColorScheme(categoryNames) {\n const colorParams = this._getColorScale(this.layout).parameters;\n const baseParams = this._getColorScale(this._base_layout).parameters;\n\n if (baseParams.categories.length && baseParams.values.length) {\n // If there are preset category/color combos, make sure that they apply to the actual dataset\n const parameters_categories_hash = {};\n baseParams.categories.forEach((category) => {\n parameters_categories_hash[category] = 1;\n });\n if (categoryNames.every((name) => Object.prototype.hasOwnProperty.call(parameters_categories_hash, name))) {\n // The layout doesn't have to specify categories in order, but make sure they are all there\n colorParams.categories = baseParams.categories;\n } else {\n colorParams.categories = categoryNames;\n }\n } else {\n colorParams.categories = categoryNames;\n }\n // Prefer user-specified colors if provided. Make sure that there are enough colors for all the categories.\n let colors;\n if (baseParams.values.length) {\n colors = baseParams.values;\n } else {\n // Originally from d3v3 category20\n colors = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'];\n }\n while (colors.length < categoryNames.length) {\n colors = colors.concat(colors);\n }\n colors = colors.slice(0, categoryNames.length); // List of hex values, should be of same length as categories array\n colorParams.values = colors;\n }\n\n /**\n *\n * @param dimension\n * @param {Object} [config] Parameters that customize how ticks are calculated (not style)\n * @param {('left'|'center'|'right')} [config.position='left'] Align ticks with the center or edge of category\n * @returns {Array}\n */\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n const position = config.position || 'left';\n if (!['left', 'center', 'right'].includes(position)) {\n throw new Error('Invalid tick position');\n }\n\n const categoryBounds = this._categories;\n if (!categoryBounds || !Object.keys(categoryBounds).length) {\n return [];\n }\n\n if (dimension === 'y') {\n return [];\n }\n\n if (dimension === 'x') {\n // If colors have been defined by this layer, use them to make tick colors match scatterplot point colors\n const colors = this._getColorScale(this.layout);\n const knownCategories = colors.parameters.categories || [];\n const knownColors = colors.parameters.values || [];\n\n return Object.keys(categoryBounds).map((category, index) => {\n const bounds = categoryBounds[category];\n let xPos;\n\n switch (position) {\n case 'left':\n xPos = bounds[0];\n break;\n case 'center':\n // Center tick under one or many elements as appropriate\n // eslint-disable-next-line no-case-declarations\n const diff = bounds[1] - bounds[0];\n xPos = bounds[0] + (diff !== 0 ? diff : bounds[0]) / 2;\n break;\n case 'right':\n xPos = bounds[1];\n break;\n }\n return {\n x: xPos,\n text: category,\n style: {\n 'fill': knownColors[knownCategories.indexOf(category)] || '#000000',\n },\n };\n });\n }\n }\n\n applyCustomDataMethods() {\n this.data = this._prepareData();\n this._categories = this._generateCategoryBounds();\n return this;\n }\n}\n\n\nexport { Scatter as scatter, CategoryScatter as category_scatter };\n","/**\n * Helper functions targeted at rendering operations\n * @module\n * @private\n*/\n\n\n/**\n * A very simple function aimed at scatter plots: attempts to coalesce \"low-significance\" SNPs that are too close to\n * visually distinguish, thus creating a dataset with fewer points that can be rendered more quickly.\n *\n * This depends on the strong and explicit assumption that points are ordered (typically in x position), so that\n * nearby points can be grouped by iterating over the data in sequence.\n *\n * @param {Object[]} data Plot data, annotated with calculated `xc` and `yc` symbols for x and y coordinates (in px).\n * @param {Number} x_min The smallest x value of an \"insignificant region\" rectangle\n * @param {Number} x_max The largest x value of an \"insignificant region\" rectangle\n * @param {Number} x_gap Max px distance, in x direction, from the first point in a set, to qualify for grouping\n * @param {Number} y_min The smallest y value of an \"insignificant region\" rectangle\n * @param {Number} y_max The largest y value of an \"insignificant region\" rectangle\n * @param {Number} y_gap Max px distance, in y direction, from the first point in a set, to qualify for grouping\n * @return {Object[]} The simplified dataset with fewer points\n */\nfunction coalesce_scatter_points (data, x_min, x_max, x_gap, y_min, y_max, y_gap) {\n let final_data = [];\n\n const xcs = Symbol.for('lzX');\n const ycs = Symbol.for('lzY');\n\n let x_start = null;\n let y_start = null;\n let current_group = [];\n\n function _combine () {\n if (current_group.length) {\n // If there are points near each other, return the middle item to represent the group\n // We use a real point (rather than a synthetic average point) to best handle extra fields\n const item = current_group[Math.floor((current_group.length - 1) / 2)];\n final_data.push(item);\n }\n x_start = y_start = null;\n current_group = [];\n }\n\n function _start_run(x, y, item) {\n x_start = x;\n y_start = y;\n current_group.push(item);\n }\n\n data.forEach((item) => {\n const x = item[xcs];\n const y = item[ycs];\n\n const in_combine_region = (x >= x_min && x <= x_max && y >= y_min && y <= y_max);\n if (item.lz_is_match || !in_combine_region) {\n // If an item is marked as interesting in some way, always render it explicitly\n // (and coalesce the preceding points if a run was in progress, to preserve ordering)\n _combine();\n final_data.push(item);\n } else if (x_start === null) {\n // If not tracking a group, start tracking\n _start_run(x, y, item);\n } else {\n // Otherwise, the decision to render the point depends on whether it is close to a run of other\n // insignificant points\n const near_prior = Math.abs(x - x_start) <= x_gap && Math.abs(y - y_start) <= y_gap;\n\n if (near_prior) {\n current_group.push(item);\n } else {\n // \"if in combine region, and not near a prior point, coalesce all prior items, then track this point\n // as part of the next run that could be grouped\"\n _combine();\n _start_run(x, y, item);\n }\n }\n });\n // At the end of the dataset, check whether any runs of adjacent points were in progress, and coalesce if so\n _combine();\n\n return final_data;\n}\n\nexport { coalesce_scatter_points };\n","/**\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\nimport * as layers from '../components/data_layer';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data rendering types (data layers).\n * @alias module:LocusZoom~DataLayers\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\nfor (let [name, type] of Object.entries(layers)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","/**\n * Predefined layouts that describe how to draw common types of data, as well as what interactive features to use.\n * Each plot contains multiple panels (rows), and each row can stack several kinds of data in layers\n * (eg scatter plot and line of significance). Layouts provide the building blocks to provide interactive experiences\n * and user-friendly tooltips for common kinds of genetic data.\n *\n * Many of these layouts (like the standard association plot) assume that field names are the same as those provided\n * in the UMich [portaldev API](https://portaldev.sph.umich.edu/docs/api/v1/). Although layouts can be used on many\n * kinds of data, it is often less work to write an adapter that uses the same field names, rather than to modify\n * every single reference to a field anywhere in the layout.\n *\n * See the Layouts Tutorial for details on how to customize nested layouts.\n *\n * @module LocusZoom_Layouts\n */\n\nimport version from '../version';\nimport {deepCopy, merge} from '../helpers/layouts';\n\nconst LZ_SIG_THRESHOLD_LOGP = 7.301; // -log10(.05/1e6)\n\n/*\n * Tooltip Layouts\n */\nconst standard_association_tooltip = {\n namespace: { 'assoc': 'assoc' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: `{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n {{#if {{namespace[ld]}}isrefvar}}LD Reference Variant{{#else}}\n Make LD Reference{{/if}}
`,\n};\n\nconst standard_association_tooltip_with_label = function() {\n // Add a special \"toggle label\" button to the base tooltip. This must be used in tandem with a custom layout\n // directive (label.filters should check a boolean annotation field called \"lz_show_label\").\n const base = deepCopy(standard_association_tooltip);\n base.html += `{{#if lz_show_label}}Hide{{#else}}Show{{/if}} label`;\n return base;\n}();\n\nconst standard_genes_tooltip = {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '

{{gene_name|htmlescape}}

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

{{/if}}'\n + 'More data on gnomAD',\n};\n\nconst catalog_variant_tooltip = {\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[catalog]}}variant|htmlescape}}
'\n + 'Catalog entries: {{n_catalog_matches|htmlescape}}
'\n + 'Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
'\n + 'Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
'\n // User note: if a different catalog is used, the tooltip will need to be replaced with a different link URL\n + 'More: GWAS catalog / dbSNP',\n};\n\nconst coaccessibility_tooltip = {\n namespace: { 'access': 'access' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n // TODO: Is there a more generic terminology? (eg not every technique is in terms of cis-regulatory element)\n html: 'Regulatory element
' +\n '{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
' +\n 'Promoter
' +\n '{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
' +\n '{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}' +\n 'Score: {{{{namespace[access]}}score|htmlescape}}',\n};\n\n/*\n * Data Layer Layouts: represent specific information given provided data.\n */\n\n/**\n * A horizontal line of GWAS significance at the standard threshold of p=5e-8\n * @name significance\n * @type data_layer\n */\nconst significance_layer = {\n id: 'significance',\n type: 'orthogonal_line',\n tag: 'significance',\n orientation: 'horizontal',\n offset: LZ_SIG_THRESHOLD_LOGP,\n};\n\n/**\n * A simple curve representing the genetic recombination rate, drawn from the UM API\n * @name recomb_rate\n * @type data_layer\n */\nconst recomb_rate_layer = {\n namespace: { 'recomb': 'recomb' },\n id: 'recombrate',\n type: 'line',\n tag: 'recombination',\n fields: ['{{namespace[recomb]}}position', '{{namespace[recomb]}}recomb_rate'],\n z_index: 1,\n style: {\n 'stroke': '#0000FF',\n 'stroke-width': '1.5px',\n },\n x_axis: {\n field: '{{namespace[recomb]}}position',\n },\n y_axis: {\n axis: 2,\n field: '{{namespace[recomb]}}recomb_rate',\n floor: 0,\n ceiling: 100,\n },\n};\n\n/**\n * A scatter plot of GWAS association summary statistics, with preset field names matching the UM portaldev api\n * @name association_pvalues\n * @type data_layer\n */\nconst association_pvalues_layer = {\n namespace: { 'assoc': 'assoc', 'ld': 'ld' },\n id: 'associationpvalues',\n type: 'scatter',\n tag: 'association',\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation', '{{namespace[assoc]}}ref_allele', '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar'],\n id_field: '{{namespace[assoc]}}variant',\n coalesce: {\n active: true,\n },\n point_shape: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 'diamond',\n else: 'circle',\n },\n },\n point_size: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 80,\n else: 40,\n },\n },\n color: [\n {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: '#9632b8',\n },\n },\n {\n scale_function: 'numerical_bin',\n field: '{{namespace[ld]}}state',\n parameters: {\n breaks: [0, 0.2, 0.4, 0.6, 0.8],\n values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'],\n },\n },\n '#B8B8B8',\n ],\n legend: [\n { shape: 'diamond', color: '#9632b8', size: 40, label: 'LD Ref Var', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#d43f3a', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#eea236', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#5cb85c', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#46b8da', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#357ebd', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#B8B8B8', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' },\n ],\n label: null,\n z_index: 2,\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[assoc]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.10,\n min_extent: [0, 10],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(standard_association_tooltip),\n};\n\n/**\n * An arc track that shows arcs representing chromatic coaccessibility\n * @name coaccessibility\n * @type data_layer\n */\nconst coaccessibility_layer = {\n namespace: { 'access': 'access' },\n id: 'coaccessibility',\n type: 'arcs',\n tag: 'coaccessibility',\n fields: ['{{namespace[access]}}start1', '{{namespace[access]}}end1', '{{namespace[access]}}start2', '{{namespace[access]}}end2', '{{namespace[access]}}id', '{{namespace[access]}}target', '{{namespace[access]}}score'],\n match: { send: '{{namespace[access]}}target', receive: '{{namespace[access]}}target' },\n id_field: '{{namespace[access]}}id',\n filters: [\n { field: '{{namespace[access]}}score', operator: '!=', value: null },\n ],\n color: [\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#4285f4',\n },\n },\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n {\n scale_function: 'ordinal_cycle',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'], // Drawn from d3v3 \"category20\"\n },\n },\n ],\n x_axis: {\n field1: '{{namespace[access]}}start1',\n field2: '{{namespace[access]}}start2',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[access]}}score',\n upper_buffer: 0.1,\n min_extent: [0, 1],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(coaccessibility_tooltip),\n};\n\n/**\n * A scatter plot of GWAS summary statistics, with additional tooltip fields showing GWAS catalog annotations\n * @name association_pvalues_catalog\n * @type data_layer\n */\nconst association_pvalues_catalog_layer = function () {\n // Slightly modify an existing layout\n let base = deepCopy(association_pvalues_layer);\n base = merge({ id: 'associationpvaluescatalog', fill_opacity: 0.7 }, base);\n base.tooltip.html += '{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}';\n base.namespace.catalog = 'catalog';\n base.fields.push('{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait', '{{namespace[catalog]}}log_pvalue');\n return base;\n}();\n\n/**\n * A scatter plot of PheWAS pvalues, with preset field names matching the UM Portaldev API\n * @name phewas_pvalues\n * @type data_layer\n */\nconst phewas_pvalues_layer = {\n namespace: { 'phewas': 'phewas' },\n id: 'phewaspvalues',\n type: 'category_scatter',\n tag: 'phewas',\n point_shape: 'circle',\n point_size: 70,\n tooltip_positioning: 'vertical',\n id_field: '{{namespace[phewas]}}id',\n fields: ['{{namespace[phewas]}}id', '{{namespace[phewas]}}log_pvalue', '{{namespace[phewas]}}trait_group', '{{namespace[phewas]}}trait_label'],\n x_axis: {\n field: '{{namespace[phewas]}}x', // Synthetic/derived field added by `category_scatter` layer\n category_field: '{{namespace[phewas]}}trait_group',\n lower_buffer: 0.025,\n upper_buffer: 0.025,\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[phewas]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.15,\n },\n color: [{\n field: '{{namespace[phewas]}}trait_group',\n scale_function: 'categorical_bin',\n parameters: {\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n }],\n fill_opacity: 0.7,\n tooltip: {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: [\n 'Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
',\n 'Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
',\n 'P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
',\n ].join(''),\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n label: {\n text: '{{{{namespace[phewas]}}trait_label}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n {\n field: '{{namespace[phewas]}}log_pvalue',\n operator: '>=',\n value: 20,\n },\n ],\n style: {\n 'font-size': '14px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n};\n\n/**\n * Shows genes in the specified region, with names and formats drawn from the UM Portaldev API and GENCODE datasource\n * @type data_layer\n */\nconst genes_layer = {\n namespace: { 'gene': 'gene', 'constraint': 'constraint' },\n id: 'genes',\n type: 'genes',\n tag: 'genes',\n fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'],\n id_field: 'gene_id',\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(standard_genes_tooltip),\n};\n\n/**\n * A genes data layer that uses filters to limit what information is shown by default. This layer hides a curated\n * list of GENCODE gene_types that are of less interest to most analysts.\n * Often used in tandem with a panel-level toolbar \"show all\" button so that the user can toggle to a full view.\n * @name genes_filtered\n * @type data_layer\n */\nconst genes_layer_filtered = merge({\n filters: [\n {\n field: 'gene_type',\n operator: 'in',\n // A manually curated subset of Gencode biotypes, based on user suggestions\n // See full list: https://www.gencodegenes.org/human/stats.html\n // This is approximately intended to cover elements of generally known function, and exclude things\n // like pseudogenes.\n value: [\n 'protein_coding',\n 'IG_C_gene', 'IG_D_gene', 'IG_J_gene', 'IG_V_gene',\n 'TR_C_gene', 'TR_D_gene', 'TR_J_gene', 'TR_V_gene',\n 'rRNA',\n 'Mt_rRNA', 'Mt_tRNA',\n ],\n },\n ],\n}, deepCopy(genes_layer));\n\n/**\n * An annotation / rug track that shows tick marks for each position in which a variant is present in the provided\n * association data, *and* has a significant claim in the EBI GWAS catalog.\n * @type data_layer\n */\nconst annotation_catalog_layer = {\n // Identify GWAS hits that are present in the GWAS catalog\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n id: 'annotation_catalog',\n type: 'annotation_track',\n tag: 'gwascatalog',\n id_field: '{{namespace[assoc]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: '#0000CC',\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}chromosome', '{{namespace[assoc]}}position',\n '{{namespace[catalog]}}variant', '{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait',\n '{{namespace[catalog]}}log_pvalue', '{{namespace[catalog]}}pos',\n ],\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: '{{namespace[catalog]}}rsid', operator: '!=', value: null },\n { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(catalog_variant_tooltip),\n tooltip_positioning: 'top',\n};\n\n/*\n * Individual toolbar buttons\n */\n\n/**\n * A dropdown menu that can be used to control the LD population used with the LDServer Adapter. Population\n * names are provided for the 1000G dataset that is used by the offical UM LD Server.\n * @name ldlz2_pop_selector\n * @type toolbar_widgets\n */\nconst ldlz2_pop_selector_menu = {\n // **Note**: this widget is aimed at the LDServer datasource, and the UM 1000G LDServer\n type: 'set_state',\n tag: 'ld_population',\n position: 'right',\n color: 'blue',\n button_html: 'LD Population: ',\n show_selected: true,\n button_title: 'Select LD Population: ',\n custom_event_name: 'widget_set_ldpop',\n state_field: 'ld_pop',\n // This list below is hardcoded to work with the UMich LDServer, default 1000G populations\n // It can be customized to work with other LD servers that specify population differently\n // https://portaldev.sph.umich.edu/ld/genome_builds/GRCh37/references/1000G/populations\n options: [\n { display_name: 'ALL (default)', value: 'ALL' },\n { display_name: 'AFR', value: 'AFR' },\n { display_name: 'AMR', value: 'AMR' },\n { display_name: 'EAS', value: 'EAS' },\n { display_name: 'EUR', value: 'EUR' },\n { display_name: 'SAS', value: 'SAS' },\n ],\n};\n\n/**\n * A dropdown menu that selects which types of genes to show in the plot. The provided options are curated sets of\n * interesting gene types based on the GENCODE dataset.\n * @type toolbar_widgets\n */\nconst gene_selector_menu = {\n type: 'display_options',\n tag: 'gene_filter',\n custom_event_name: 'widget_gene_filter_choice',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Filter...',\n button_title: 'Choose which genes to show',\n layer_name: 'genes',\n default_config_display_name: 'Coding genes & rRNA',\n options: [\n {\n display_name: 'All features',\n display: {\n filters: null,\n },\n },\n ],\n};\n\n/*\n * Toolbar Layouts: Collections of toolbar buttons etc\n */\n\n/**\n * Basic options to remove and reorder panels\n * @name standard_panel\n * @type toolbar\n */\nconst standard_panel_toolbar = {\n widgets: [\n {\n type: 'remove_panel',\n position: 'right',\n color: 'red',\n group_position: 'end',\n },\n {\n type: 'move_panel_up',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'move_panel_down',\n position: 'right',\n group_position: 'start',\n style: { 'margin-left': '0.75em' },\n },\n ],\n};\n\n/**\n * A simple plot toolbar with buttons to download as image\n * @name standard_plot\n * @type toolbar\n */\nconst standard_plot_toolbar = {\n // Suitable for most any type of plot drawn with LZ. Title and download buttons.\n widgets: [\n {\n type: 'title',\n title: 'LocusZoom',\n subtitle: `v${version}`,\n position: 'left',\n },\n {\n type: 'download',\n position: 'right',\n group_position: 'end',\n },\n {\n type: 'download_png',\n position: 'right',\n group_position: 'start',\n },\n ],\n};\n\n/**\n * A plot toolbar that adds a button for controlling LD population. This is useful for plots intended to show\n * GWAS summary stats, which is one of the most common usages of LocusZoom.\n * @type toolbar\n */\nconst standard_association_toolbar = function () {\n // Suitable for association plots (adds a button for LD data)\n const base = deepCopy(standard_plot_toolbar);\n base.widgets.push(deepCopy(ldlz2_pop_selector_menu));\n return base;\n}();\n\n/**\n * A basic plot toolbar with buttons to scroll sideways or zoom in. Useful for all region-based plots.\n * @name region_nav_plot\n * @type toolbar\n */\nconst region_nav_plot_toolbar = function () {\n // Generic region nav buttons\n const base = deepCopy(standard_plot_toolbar);\n base.widgets.push(\n {\n type: 'shift_region',\n step: 500000,\n button_html: '>>',\n position: 'right',\n group_position: 'end',\n }, {\n type: 'shift_region',\n step: 50000,\n button_html: '>',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: 0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: -0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -50000,\n button_html: '<',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -500000,\n button_html: '<<',\n position: 'right',\n group_position: 'start',\n }\n );\n return base;\n}();\n\n/*\n * Panel Layouts\n */\n\n\n/**\n * A panel that describes the most common kind of LocusZoom plot, with line of GWAS significance, recombination rate,\n * and a scatter plot superimposed.\n * @name association\n * @type panel\n */\nconst association_panel = {\n id: 'association',\n tag: 'association',\n min_height: 200,\n height: 225,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push({\n type: 'toggle_legend',\n position: 'right',\n });\n return base;\n })(),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n y2: {\n label: 'Recombination Rate (cM/Mb)',\n label_offset: 40,\n },\n },\n legend: {\n orientation: 'vertical',\n origin: { x: 55, y: 40 },\n hidden: true,\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n drag_y2_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_layer),\n ],\n};\n\n/**\n * A panel showing chromatin coaccessibility arcs with some common display options\n * @type panel\n */\nconst coaccessibility_panel = {\n id: 'coaccessibility',\n tag: 'coaccessibility',\n min_height: 150,\n height: 180,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: 'Score',\n label_offset: 28,\n render: false, // We are mainly concerned with the relative magnitudes: hide y axis to avoid clutter.\n },\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(coaccessibility_layer),\n ],\n};\n\n/**\n * A panel showing GWAS summary statistics, plus annotations for connecting it to the EBI GWAS catalog\n * @type panel\n */\nconst association_catalog_panel = function () {\n let base = deepCopy(association_panel);\n base = merge({\n id: 'associationcatalog',\n namespace: { 'assoc': 'assoc', 'ld': 'ld', 'catalog': 'catalog' }, // Required to resolve display options\n }, base);\n\n base.toolbar.widgets.push({\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n\n layer_name: 'associationpvaluescatalog',\n default_config_display_name: 'No catalog labels (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: 'Label catalog traits', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n label: {\n text: '{{{{namespace[catalog]}}trait}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n // Only label points if they are significant for some trait in the catalog, AND in high LD\n // with the top hit of interest\n { field: '{{namespace[catalog]}}trait', operator: '!=', value: null },\n { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP },\n { field: '{{namespace[ld]}}state', operator: '>', value: 0.4 },\n ],\n style: {\n 'font-size': '10px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n },\n },\n ],\n });\n base.data_layers = [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_catalog_layer),\n ];\n return base;\n}();\n\n/**\n * A panel showing genes in the specified region. This panel lets the user choose which genes are shown.\n * @type panel\n */\nconst genes_panel = {\n id: 'genes',\n tag: 'genes',\n min_height: 150,\n height: 225,\n margin: { top: 20, right: 50, bottom: 20, left: 50 },\n axes: {},\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push(\n {\n type: 'resize_to_data',\n position: 'right',\n button_html: 'Resize',\n },\n deepCopy(gene_selector_menu)\n );\n return base;\n })(),\n data_layers: [\n deepCopy(genes_layer_filtered),\n ],\n};\n\n/**\n * A pael that displays PheWAS scatter plots and automatically generates a color scheme\n * @type panel\n */\nconst phewas_panel = {\n id: 'phewas',\n tag: 'phewas',\n min_height: 300,\n height: 300,\n margin: { top: 20, right: 50, bottom: 120, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n axes: {\n x: {\n ticks: { // Object based config (shared defaults; allow layers to specify ticks)\n style: {\n 'font-weight': 'bold',\n 'font-size': '11px',\n 'text-anchor': 'start',\n },\n transform: 'rotate(50)',\n position: 'left', // Special param recognized by `category_scatter` layers\n },\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(phewas_pvalues_layer),\n ],\n};\n\n/**\n * A panel that shows a simple annotation track connecting GWAS results\n * @name annotation_catalog\n * @type panel\n */\nconst annotation_catalog_panel = {\n id: 'annotationcatalog',\n tag: 'gwascatalog',\n min_height: 50,\n height: 50,\n margin: { top: 25, right: 50, bottom: 10, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n axes: {\n x: { extent: 'state', render: false },\n },\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(annotation_catalog_layer),\n ],\n};\n\n/*\n * Plot Layouts\n */\n\n/**\n * Describes how to fetch and draw each part of the most common LocusZoom plot (with field names that reference the portaldev API)\n * @name standard_association\n * @type plot\n */\nconst standard_association_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: standard_association_toolbar,\n panels: [\n deepCopy(association_panel),\n deepCopy(genes_panel),\n ],\n};\n\n/**\n * A modified version of the standard LocusZoom plot, which adds a track that shows which SNPs in the plot also have claims in the EBI GWAS catalog.\n * @name association_catalog\n * @type plot\n */\nconst association_catalog_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: standard_association_toolbar,\n panels: [\n annotation_catalog_panel,\n association_catalog_panel,\n genes_panel,\n ],\n};\n\n/**\n * A PheWAS scatter plot with an additional track showing nearby genes, to put the region in biological context.\n * @name standard_phewas\n * @type plot\n */\nconst standard_phewas_plot = {\n width: 800,\n responsive_resize: true,\n toolbar: standard_plot_toolbar,\n panels: [\n deepCopy(phewas_panel),\n merge({\n height: 300,\n margin: { bottom: 40 },\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n },\n }, deepCopy(genes_panel)),\n ],\n mouse_guide: false,\n};\n\n/**\n * Show chromatin coaccessibility arcs, with additional features that connect these arcs to nearby genes to show regulatory interactions.\n * @name coaccessibility\n * @type plot\n */\nconst coaccessibility_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: deepCopy(standard_plot_toolbar),\n panels: [\n deepCopy(coaccessibility_panel),\n function () {\n // Take the default genes panel, and add a custom feature to highlight gene tracks based on short name\n // This is a companion to the \"match\" directive in the coaccessibility panel\n const base = Object.assign(\n { height: 270 },\n deepCopy(genes_panel)\n );\n const layer = base.data_layers[0];\n layer.match = { send: 'gene_name', receive: 'gene_name' };\n const color_config = [\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#4285f4',\n },\n },\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n '#363696',\n ];\n layer.color = color_config;\n layer.stroke = color_config;\n return base;\n }(),\n ],\n};\n\n\nexport const tooltip = {\n standard_association: standard_association_tooltip,\n standard_association_with_label: standard_association_tooltip_with_label,\n standard_genes: standard_genes_tooltip,\n catalog_variant: catalog_variant_tooltip,\n coaccessibility: coaccessibility_tooltip,\n};\n\nexport const toolbar_widgets = {\n ldlz2_pop_selector: ldlz2_pop_selector_menu,\n gene_selector_menu,\n};\n\nexport const toolbar = {\n standard_panel: standard_panel_toolbar,\n standard_plot: standard_plot_toolbar,\n standard_association: standard_association_toolbar,\n region_nav_plot: region_nav_plot_toolbar,\n};\n\nexport const data_layer = {\n significance: significance_layer,\n recomb_rate: recomb_rate_layer,\n association_pvalues: association_pvalues_layer,\n coaccessibility: coaccessibility_layer,\n association_pvalues_catalog: association_pvalues_catalog_layer,\n phewas_pvalues: phewas_pvalues_layer,\n genes: genes_layer,\n genes_filtered: genes_layer_filtered,\n annotation_catalog: annotation_catalog_layer,\n};\n\nexport const panel = {\n association: association_panel,\n coaccessibility: coaccessibility_panel,\n association_catalog: association_catalog_panel,\n genes: genes_panel,\n phewas: phewas_panel,\n annotation_catalog: annotation_catalog_panel,\n};\n\nexport const plot = {\n standard_association: standard_association_plot,\n association_catalog: association_catalog_plot,\n standard_phewas: standard_phewas_plot,\n coaccessibility: coaccessibility_plot,\n};\n","import {RegistryBase} from './base';\nimport {applyNamespaces, deepCopy, mutate_attrs, merge, query_attrs, renameField} from '../helpers/layouts';\nimport * as layouts from '../layouts';\n\n/**\n * Helper for working with predefined layouts\n *\n * This is part of the public interface with LocusZoom and a major way that users interact to configure plots.\n *\n * Each layout object that is added or retrieved here is a deep copy and totally independent from any other object\n * @public\n * @extends module:registry/base:RegistryBase\n * @inheritDoc\n */\nclass LayoutRegistry extends RegistryBase {\n // Implemented as a \"registry of registries\"- one lookup each for panels, plots, etc...\n get(type, name, overrides = {}) {\n if (!(type && name)) {\n throw new Error('Must specify both the type and name for the layout desired. See .list() for available options');\n }\n // This is a registry of registries. Fetching an item may apply additional custom behaviors, such as\n // applying overrides or using namespaces to convert an abstract layout into a concrete one.\n let base = super.get(type).get(name);\n base = merge(overrides, base);\n if (base.unnamespaced) {\n delete base.unnamespaced;\n return deepCopy(base);\n }\n let default_namespace = '';\n if (typeof base.namespace == 'string') {\n default_namespace = base.namespace;\n } else if (typeof base.namespace == 'object' && Object.keys(base.namespace).length) {\n if (typeof base.namespace.default != 'undefined') {\n default_namespace = base.namespace.default;\n } else {\n default_namespace = base.namespace[Object.keys(base.namespace)[0]].toString();\n }\n }\n default_namespace += default_namespace.length ? ':' : '';\n const result = applyNamespaces(base, base.namespace, default_namespace);\n\n return deepCopy(result);\n }\n\n /**\n * Add a type of layout to the registry\n * @param {String} type The type of layout to add (plot, panel, data_layer, toolbar, toolbar_widgets, or tooltip)\n * @param {String} name The name of the layout object to add\n * @param {Object} item The layout object describing parameters\n * @param {boolean} override Whether to replace an existing item by that name\n * @return {*}\n */\n add(type, name, item, override = false) {\n if (!(type && name && item)) {\n throw new Error('To add a layout, type, name, and item must all be specified');\n }\n if (!(typeof item === 'object')) {\n throw new Error('The configuration to be added must be an object');\n }\n\n if (!this.has(type)) {\n super.add(type, new RegistryBase());\n }\n // Ensure that each use of a layout can be modified, by returning a copy is independent\n const copy = deepCopy(item);\n return super.get(type).add(name, copy, override);\n }\n\n /**\n * List all available types of layout (eg toolbar, panel, etc). If a specific type name is provided, list the\n * layouts for that type of element (\"just predefined panels\").\n * @param {String} [type] The type of layout (eg toolbar, panel, etc)\n * @return {String[]|Object}\n */\n list(type) {\n if (!type) {\n let result = {};\n for (let [type, contents] of this._items) {\n result[type] = contents.list();\n }\n return result;\n }\n return super.get(type).list();\n }\n\n /**\n * Static alias to a helper method. Preserved for backwards compatibility, so that UMD users can access this method.\n * @static\n * @private\n */\n merge(custom_layout, default_layout) {\n return merge(custom_layout, default_layout);\n }\n\n /**\n * Static alias to a helper method. Allows renaming fields\n * @static\n * @private\n */\n renameField() {\n return renameField(...arguments);\n }\n\n /**\n * Static alias to a helper method. Allows mutating nested layout attributes\n * @static\n * @private\n */\n mutate_attrs() {\n return mutate_attrs(...arguments);\n }\n\n /**\n * Static alias to a helper method. Allows mutating nested layout attributes\n * @static\n * @private\n */\n query_attrs() {\n return query_attrs(...arguments);\n }\n}\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data adapters.\n * @alias module:LocusZoom~Layouts\n * @type {LayoutRegistry}\n */\nconst registry = new LayoutRegistry();\n\nfor (let [type, entries] of Object.entries(layouts)) {\n for (let [name, config] of Object.entries(entries)) {\n registry.add(type, name, config);\n }\n}\n\n\nexport default registry;\n\n// Export base class for unit testing\nexport {LayoutRegistry as _LayoutRegistry};\n","import {RegistryBase} from '../registry/base';\nimport { ADAPTERS } from '../registry';\n\n/**\n * Create and coordinate an ensemble of (namespaced) data adapter instances.\n * This is the mechanism by which users tell a plot how to retrieve data for a specific plot: adapters are created\n * through this object rather than instantiating directly.\n *\n * @public\n * @alias module:LocusZoom~DataSources\n * @extends module:registry/base~RegistryBase\n * @inheritDoc\n */\nclass DataSources extends RegistryBase {\n /**\n * @param {RegistryBase} [registry] Primarily used for unit testing. When creating sources by name, specify where to\n * find the registry of known sources.\n */\n constructor(registry) {\n super();\n // This both acts as a registry (of the instantiated sources for this plot), and references a registry\n // (to locate adapter classes by name, when creating from config)\n this._registry = registry || ADAPTERS;\n }\n\n /**\n * For data sources, there is a special behavior of \"create item from config, then add\"\n * @param {String} namespace Uniquely identify this datasource\n * @param {BaseAdapter|Array} item An instantiated datasource, or an array of arguments that can be used to\n * create a known datasource type.\n * @param [override=false] Whether to allow existing sources to be redefined\n * @return {DataSources} Most registries return the created instance, but this registry returns a reference to\n * itself (to support chaining)\n */\n add(namespace, item, override = false) {\n if (this._registry.has(namespace)) {\n throw new Error(`The namespace ${namespace} is already in use by another source`);\n }\n\n if (namespace.match(/[^A-Za-z0-9_]/)) {\n throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores. Invalid name: ${namespace}`);\n }\n if (Array.isArray(item)) {\n const [type, options] = item;\n item = this._registry.create(type, options);\n }\n // Each datasource in the chain should be aware of its assigned namespace\n item.source_id = namespace;\n\n super.add(namespace, item, override);\n return this;\n }\n}\n\n\nexport default DataSources;\n","/**\n * Whether imported (ES6 modules) or loaded via script tag (UMD), this module represents\n * the \"public interface\" via which core LocusZoom features and plugins are exposed for programmatic usage.\n *\n * A library using this file will need to load `locuszoom.css` separately in order for styles to appear.\n *\n * @module LocusZoom\n */\nimport version from './version';\n\nimport {default as DataSources} from './data';\nimport { populate } from './helpers/display';\n\nimport {\n ADAPTERS as Adapters,\n DATA_LAYERS as DataLayers,\n WIDGETS as Widgets,\n LAYOUTS as Layouts,\n MATCHERS as MatchFunctions,\n SCALABLE as ScaleFunctions,\n TRANSFORMS as TransformationFunctions,\n} from './registry';\n\n\nconst LocusZoom = {\n version,\n // Helpers for creating plots- the main public interface for most use cases\n populate,\n DataSources,\n // Registries for plugin system\n Adapters,\n DataLayers,\n Layouts,\n MatchFunctions,\n ScaleFunctions,\n TransformationFunctions,\n Widgets,\n\n get KnownDataSources() { // Backwards- compatibility alias\n console.warn('Deprecation warning: KnownDataSources has been renamed to \"Adapters\"');\n return Adapters;\n },\n};\n\n\n/**\n * @callback pluginCallback\n * @param {Object} LocusZoom The global LocusZoom object\n * @param args Any additional arguments passed to LocusZoom.use will be passed to the function when the plugin is loaded\n */\n\n\nconst INSTALLED_PLUGINS = [];\n\n/**\n * @alias module:LocusZoom.use\n * @param {pluginCallback} plugin The plugin should be a module that exports the function as either the default export,\n * or as a member named \"install\"\n * @param args Additional options to be passed when creating the plugin\n */\nLocusZoom.use = function(plugin, ...args) {\n // Deliberately similar implementation to Vue.js .use() plugin system\n if (INSTALLED_PLUGINS.includes(plugin)) {\n // Avoid double-installation of a plugin\n return;\n }\n\n args.unshift(LocusZoom); // All plugins are passed a reference to LocusZoom object\n if (typeof plugin.install === 'function') {\n plugin.install.apply(plugin, args);\n } else if (typeof plugin === 'function') {\n plugin.apply(null, args);\n } else {\n throw new Error('Plugin must export a function that receives the LocusZoom object as an argument');\n }\n INSTALLED_PLUGINS.push(plugin);\n};\n\n\nexport default LocusZoom;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/webpack/runtime/make namespace object","webpack://[name]/./esm/version.js","webpack://[name]/./esm/registry/base.js","webpack://[name]/./esm/data/adapters.js","webpack://[name]/./esm/registry/adapters.js","webpack://[name]/external \"d3\"","webpack://[name]/./esm/components/constants.js","webpack://[name]/./esm/helpers/transforms.js","webpack://[name]/./esm/registry/transforms.js","webpack://[name]/./esm/data/field.js","webpack://[name]/./esm/helpers/jsonpath.js","webpack://[name]/./esm/helpers/layouts.js","webpack://[name]/./esm/data/requester.js","webpack://[name]/./esm/helpers/common.js","webpack://[name]/./esm/components/toolbar/widgets.js","webpack://[name]/./esm/registry/widgets.js","webpack://[name]/./esm/components/toolbar/index.js","webpack://[name]/./esm/components/legend.js","webpack://[name]/./esm/components/panel.js","webpack://[name]/./esm/helpers/display.js","webpack://[name]/./esm/components/plot.js","webpack://[name]/./esm/registry/matchers.js","webpack://[name]/./esm/helpers/scalable.js","webpack://[name]/./esm/registry/scalable.js","webpack://[name]/./esm/components/data_layer/base.js","webpack://[name]/./esm/components/data_layer/annotation_track.js","webpack://[name]/./esm/components/data_layer/highlight_regions.js","webpack://[name]/./esm/components/data_layer/arcs.js","webpack://[name]/./esm/components/data_layer/genes.js","webpack://[name]/./esm/components/data_layer/line.js","webpack://[name]/./esm/components/data_layer/scatter.js","webpack://[name]/./esm/helpers/render.js","webpack://[name]/./esm/registry/data_layers.js","webpack://[name]/./esm/layouts/index.js","webpack://[name]/./esm/registry/layouts.js","webpack://[name]/./esm/data/sources.js","webpack://[name]/./esm/index.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","RegistryBase","this","_items","Map","name","has","Error","item","override","set","delete","Array","from","keys","ClassRegistry","args","parent_name","source_name","overrides","console","warn","arguments","length","base","sub","assign","add","validateBuildSource","class_name","build","source","includes","BaseAdapter","config","_enableCache","_cachedKey","_cache_pos_start","_cache_pos_end","__dependentSource","parseInit","params","state","chain","fields","getURL","cache_pos_chr","chr","start","end","url","fetch","then","response","ok","statusText","text","req","cacheKey","getCacheKey","Promise","resolve","_cachedResponse","fetchRequest","data","isArray","N","every","constructor","records","i","record","j","push","outnames","trans","fieldFound","k","map","output_record","val","forEach","v","resp","source_id","discrete","json","JSON","parse","normalizeResponse","standardized","annotateData","extractFields","one_source_body","combineChainBody","new_body","header","body","preGetData","pre","getRequest","parseResponse","BaseApiAdapter","super","AssociationLZ","id_field","x","unshift","analysis","sort","a","b","LDServer","join","dataFields","id","position","position_field","pvalue","pvalue_field","_names_","names","nameMatch","arr","regexes","regex","m","filter","match","id_match","RegExp","isrefvarin","isrefvarout","ldin","ldout","refVar","findRequestedFields","ldrefvar","findMergeFields","columns","pval_field","cmp","test","extremeVal","extremeIdx","findExtremeValue","original","chrom","pos","ref","alt","refVar_formatted","genome_build","ld_source","population","ld_pop","method","refVar_raw","getRefvar","encodeURIComponent","_","reqFields","corrField","rsquare","left","right","lfield","rfield","position2","leftJoin","refvar","idfield","outrefname","outldname","tagRefVariant","combined","chainRequests","payload","concat","next","GwasCatalogLZ","source_query","posMatch","find","decider","decider_out","indexOf","n_matches","fn","outn","chainNames","catNames","GeneLZ","GeneConstraintLZ","unique_gene_names","reduce","acc","gene","gene_name","query","replace","stringify","headers","catch","err","alias","constraint","toString","parseFloat","toFixed","RecombLZ","SOURCE_NAME","StaticSource","_data","PheWASLZ","variant","ConnectorSource","sources","_source_name_mapping","specified_ids","_getRequiredSources","ns","chain_source_id","registry","type","entries","d3","STATUSES","verbs","adjectives","log10","isNaN","Math","log","LN10","neglog10","logtoscinotation","exp","ceil","diff","pow","scinotation","abs","floor","toExponential","htmlescape","s","is_numeric","urlencode","template_string","funcs","substring","func","_collectTransforms","Field","field","parts","exec","full_name","namespace","transformations","split","transform","transforms","extra","_applyTransformations","ATTR_REGEX","EXPR_REGEX","get_next_token","q","substr","attr","depth","e","attrs","get_item_at_deep_path","path","parent","tokens_to_keys","selectors","sel","remaining_selectors","slice","paths","d","undefined","p","__","subject","uniqPaths","elem","values","localeCompare","_query","matches","items","get_items_from_tokens","normalize_query","selector","tokenize","sqrt3","sqrt","triangledown","context","size","y","moveTo","lineTo","closePath","applyNamespaces","element","default_namespace","default","re","resolved_namespace","r","merge","namespaced_element","namespaced_property","property","custom_layout","default_layout","custom_type","default_type","deepCopy","nameToSymbol","shape","factory_name","charAt","toUpperCase","renameField","layout","old_name","new_name","warn_transforms","this_type","escaped","filter_regex","match_val","mutate_attrs","value_or_callable","value_or_callback","old_value","new_value","mutate","query_attrs","_sources","requests","raw","__split_requests","request_handles","getData","ret","generateCurtain","showing","content_selector","hide_delay","show","content","css","curtain","parent_plot","svg","node","parentNode","insert","append","html","on","hide","update","clearTimeout","applyStyles","page_origin","_getPageOrigin","height","_total_height","style","width","delay","setTimeout","remove","generateLoader","progress_selector","cancel_selector","loader","percent","loader_boundrect","getBoundingClientRect","min","max","animate","classed","setPercentCompleted","selection","styles","BaseWidget","color","parent_panel","parent_svg","button","persist","group_position","initialize","status","menu","shouldPersist","force","destroy","Button","parent_toolbar","tag","title","permanent","outer_selector","inner_selector","scroll_position","hidden","getBaseId","scrollTop","populate","page_scroll_top","document","documentElement","container_offset","getContainerOffset","toolbar_client_rect","button_client_rect","menu_client_rect","total_content_height","scrollHeight","top","bottom","base_max_width","container_max_width","content_max_width","base_max_height","setPopulate","menu_populate_function","setOnclick","highlight","bool","Boolean","setStatus","onmouseover","onmouseout","onclick","getClass","preUpdate","postUpdate","Title","div_selector","title_selector","subtitle","RegionScale","positionIntToString","class","FilterField","_data_layer","data_layers","layer_name","_event_name","custom_event_name","_field","_field_display_html","field_display_html","_operator","operator","_filter_id","_data_type","data_type","_value_selector","filters","result","index","_getTarget","splice","_clearFilter","emit","filter_id","Number","input_size","timer","apply","debounce","_getValue","_setFilter","render","DownloadSVG","_filename","filename","_button_html","button_html","_button_title","button_title","setColor","setHtml","setTitle","setOnMouseover","_getBlobUrl","old","URL","revokeObjectURL","setOnMouseout","root","ancestor_pattern","extractedCSSText","styleSheets","cssRules","rule","selectorText","cssText","styleElement","createElement","setAttribute","innerHTML","refNode","hasChildNodes","children","insertBefore","rescale","copy","cloneNode","selectAll","each","dy","serializer","XMLSerializer","_getDimensions","_appendCSS","_getCSS","serializeToString","_generateSVG","markup","blob","Blob","createObjectURL","DownloadPNG","svg_url","canvas","getContext","reject","image","Image","onload","drawImage","toBlob","png","src","RemovePanel","suppress_confirm","confirm","panel","toolbar","removePanel","MovePanelUp","is_at_top","y_index","disable","moveUp","MovePanelDown","is_at_bottom","panel_ids_by_y_index","moveDown","ShiftRegion","step","applyState","ZoomRegion","can_zoom","current_region_scale","max_region_scale","min_region_scale","new_region_scale","delta","Menu","menu_html","ResizeToData","scaleHeightToData","ToggleLegend","legend","DisplayOptions","allowed_fields","fields_whitelist","dataLayer","dataLayerLayout","defaultConfig","configSlot","_selected_item","uniqueID","random","table","menuLayout","renderRow","display_name","display_options","row_id","row","radioId","field_name","has_option","choice","defaultName","default_config_display_name","options","display","SetState","state_field","show_selected","new_state","choice_name","choice_value","Toolbar","widgets","hide_timeout","dashboard","components","widget","create","error","panel_boundaries","dragging","interaction","orientation","origin","padding","label_size","Legend","background_rect","elements","elements_group","group","line_height","data_layer_ids_by_z_index","reverse","label_x","label_y","shape_factory","path_y","radius","PI","label","bcr","right_x","pad_from_bottom","pad_from_right","min_height","margin","background_click","cliparea","axes","y1","y2","drag_background_to_pan","drag_x_ticks_to_scale","drag_y1_ticks_to_scale","drag_y2_ticks_to_scale","scroll_to_zoom","x_linked","y1_linked","y2_linked","show_loading_indicator","Panel","panels","generateID","initialized","layout_idx","state_id","data_promises","x_scale","y1_scale","y2_scale","x_extent","y1_extent","y2_extent","x_ticks","y1_ticks","y2_ticks","zoom_timeout","event_hooks","initializeLayout","event","hook","theseHooks","hookMatch","eventData","bubble","eventContext","sourceID","target","hookToRun","y_axis","axis","data_layer","z_index","dlid","idx","data_layer_layout","destroyAllTooltips","container","applyDataLayerZIndexesToDataLayerLayouts","setAllElementStatus","clipRect","inner_border","generateExtents","constrain","limit_exponent","neg_min","neg_max","pos_min","pos_max","Infinity","ranges","base_x_range","range","x_shifted","base_y1_range","y1_shifted","base_y2_range","y2_shifted","panel_id","linked_panel_ids","anchor","scalar","zooming","current_extent_size","current_scaled_extent_size","round","invert","zoom_factor","scale","potential_extent_size","new_extent_size","center","offset_ratio","new_x_extent_start","dragged_x","start_x","y_shifted","dragged_y","start_y","domain","renderAxis","zoom_handler","_canInteract","coords","getLinkedPanelIds","data_layer_id","draw","show_immediately","plot_origin","setDimensions","setOrigin","setMargin","x_range","y1_range","y2_range","addDataLayer","base_id","clipPath","addBasicLoader","clearSelections","x_axis","x_axis_label","y1_axis","y1_axis_label","y2_axis","y2_axis_label","mousedown","startDrag","select","applyPanelYIndexesToPanelLayouts","positionPanels","reMap","message","all","decoupled","getAxisExtent","extent","ticks","baseTickConfig","self","nextLayer","getTicks","itemConfig","clip_range","target_tick_count","parseInt","min_n","shrink_sml","high_u_bias","u5_bias","c","base_toFixed","unit","pop","prettyTicks","canRender","axis_params","label_offset","label_rotate","generateTicks","ticksAreAllNumbers","axis_factory","tickPadding","tickValues","tick_format","tickFormat","t","tick_selector","parseFields","tick_mouseover","focus","cursor","target_height","dh","getAbsoluteDataHeight","toggle","verb","adjective","antiverb","min_width","responsive_resize","mouse_guide","Plot","datasource","remap_promises","_base_layout","lzd","_external_listeners","these_hooks","anyEventData","event_name","panel_layout","panelId","mode","panelsList","pid","layer","layer_state","_setDefaultState","clearPanelData","success_callback","opts","error_callback","onerror","listener","new_data","state_changes","mods","attempted_scale","validated_region","attempted_midpoint","temp","_updateStatePosition","loading_data","applyAllElementStatus","some","tracker","registered_events","listeners","removeEventListener","lastElementChild","removeChild","outerHTML","bounding_client_rect","x_offset","scrollLeft","y_offset","offset","offsetParent","offsetTop","offsetLeft","clientRect","resize_listener","rescaleSVG","window","addEventListener","trackExternalListener","load_listener","addPanel","height_scaling_factor","panel_width","panel_height","final_height","x_linked_margins","mouse_guide_svg","mouse_guide_vertical_svg","mouse_guide_horizontal_svg","vertical","horizontal","corner_selector","panel_idx","panel_resize_drag","this_panel","original_panel_height","panel_height_change","loop_panel_id","loop_panel_idx","loop_panel","corner_drag","plot_page_origin","panel_page_origin","mouseout_mouse_guide","mousemove_mouse_guide","mouseup","stopDrag","mousemove","body_node","to_send","active","emitted_by","lz_match_value","client_rect","overrideAxisLayout","axis_number","axis_layout","ceiling","lower_buffer","upper_buffer","min_extent","y_axis_number","suffix","exp_symbols","0","3","6","9","places_exp","min_exp","places","positionStringToInt","suffixre","mult","tokens","condition","variable","branch","close","astify","token","shift","dest","else","ast","cache","render_node","item_value","target_value","if_value","parameters","input","field_value","numerical_bin","breaks","null_value","threshold","prev","curr","categorical_bin","categories","ordinal_cycle","stable_choice","_cache","max_cache_size","clear","hash","String","charCodeAt","interpolate","nullval","upper_idx","brk","normalized_input","isFinite","tooltip","tooltip_positioning","behaviors","BaseDataLayer","_base_id","_filter_func","tooltips","global_statuses","resortDataLayers","getElementId","extra_fields","axis_config","id_key","for","element_id","empty","field_to_match","receive","match_function","broadcast_value","field_resolver","lz_is_match","toHTML","getDataLayer","getPanel","getPlot","deselect","unselectElement","applyCustomDataMethods","option_layout","element_data","data_index","resolveScalableParameter","scale_function","f","getElementAnnotation","dimension","axis_name","data_extent","_getDataExtent","original_extent_span","range_min","range_max","y_scale","y_extent","x_min","x_max","y_min","y_max","plot_layout","layer_layout","tooltip_box","data_layer_height","data_layer_width","x_center","y_center","tooltip_top","tooltip_left","arrow_type","arrow_top","arrow_left","placement","arrow_size","offset_right","offset_left","arrow","filter_rules","array","is_match","test_func","bind","status_flags","Set","updateTooltip","positionTooltip","closable","destroyTooltip","element_or_id","temporary","_getTooltipPosition","_drawTooltip","first_time","resolveStatus","statuses","directive","previousValue","currentValue","sub_status","sub_operator","show_directive","and","hide_directive","antistatus","show_resolved","hide_resolved","has_tooltip","createTooltip","exclusive","get_element_id_error","element_status_node_id","getElementStatusNodeId","added_status","showOrHideTooltip","is_selected","value_to_broadcast","send","setElementStatus","getElementById","event_match","executeBehaviors","requiredKeyStates","datum","behavior","action","current_status_boolean","href","open","location","panel_origin","positionAllTooltips","applyDataMethods","hitarea_width","AnnotationTrack","_hitareas_group","_visible_lines_group","track_data","_applyFilters","hit_areas_selection","_getX","x_left","left_node","left_node_x_center","enter","crds","exit","applyBehaviors","fill_opacity","regions","start_field","end_field","merge_field","HighlightRegions","cur_item","prev_item","new_start","new_end","_mergeNodes","fill","Arcs","_make_line","x1","field1","x2","field2","xmid","curve","line","hitareas","stroke","label_font_size","label_exon_spacing","exon_height","bounding_box_padding","track_vertical_spacing","Genes","transcript_idx","tracks","gene_track_index","1","_getLabelWidth","font_size","temp_text","label_width","getBBox","gene_id","gene_version","transcript_id","transcripts","display_range","text_anchor","centered_margin","display_domain","track","potential_track","collision_on_potential_track","placed_gene","min_start","exons","assignTracks","bboxes","getTrackHeight","boundaries","labels","strand","exon_id","clickareas","gene_bbox_id","gene_bbox","Line","x_field","y_field","y0","path_class","global_status","default_orthogonal_layout","OrthogonalLine","default_y","point_size","point_shape","coalesce","max_points","x_gap","y_gap","Scatter","spacing","handle_lines","lines","min_x","max_x","flip","dn","dnl","dnx","text_swing","dnlx2","line_swing","label_texts","da","dal","label_lines","nodes","dax","abound","bbound","seperate_iterations","again","db","adjust","new_a_y","new_b_y","min_y","max_y","label_elements","separate_labels","xcs","ycs","final_data","x_start","y_start","current_group","_combine","_start_run","in_combine_region","coalesce_scatter_points","label_data","label_groups","style_class","groups_enter","flip_labels","item_data","CategoryScatter","_categories","xField","category_field","sourceData","ak","bk","av","toLowerCase","bv","uniqueCategories","category","bounds","categoryNames","_setDynamicColorScheme","from_source","color_params","colorParams","_getColorScale","baseParams","parameters_categories_hash","colors","categoryBounds","knownCategories","knownColors","xPos","_prepareData","_generateCategoryBounds","LZ_SIG_THRESHOLD_LOGP","standard_association_tooltip","or","standard_association_tooltip_with_label","standard_genes_tooltip","catalog_variant_tooltip","coaccessibility_tooltip","significance_layer","recomb_rate_layer","association_pvalues_layer","coaccessibility_layer","association_pvalues_catalog_layer","catalog","phewas_pvalues_layer","genes_layer","genes_layer_filtered","annotation_catalog_layer","ldlz2_pop_selector_menu","gene_selector_menu","standard_panel_toolbar","standard_plot_toolbar","standard_association_toolbar","region_nav_plot_toolbar","association_panel","coaccessibility_panel","association_catalog_panel","genes_panel","phewas_panel","annotation_catalog_panel","standard_association_plot","association_catalog_plot","standard_phewas_plot","coaccessibility_plot","color_config","standard_association","standard_association_with_label","standard_genes","catalog_variant","coaccessibility","toolbar_widgets","ldlz2_pop_selector","standard_panel","standard_plot","region_nav_plot","significance","recomb_rate","association_pvalues","association_pvalues_catalog","phewas_pvalues","genes","genes_filtered","annotation_catalog","association","association_catalog","phewas","plot","standard_phewas","unnamespaced","contents","list","LocusZoom","version","iterator","dataset","region","parsed_state","chrpos","parsePositionQuery","refresh","DataSources","_registry","Adapters","DataLayers","Layouts","MatchFunctions","ScaleFunctions","TransformationFunctions","Widgets","INSTALLED_PLUGINS","use","plugin","install"],"mappings":";iCACA,IAAIA,EAAsB,CCA1B,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3E,EAAwB,CAACM,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClF,EAAyBT,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,0rCCLvD,iBCcA,MAAMC,EACF,cACIC,KAAKC,OAAS,IAAIC,IAQtB,IAAIC,GACA,IAAKH,KAAKC,OAAOG,IAAID,GACjB,MAAM,IAAIE,MAAM,mBAAmBF,KAEvC,OAAOH,KAAKC,OAAOX,IAAIa,GAU3B,IAAIA,EAAMG,EAAMC,GAAW,GACvB,IAAKA,GAAYP,KAAKC,OAAOG,IAAID,GAC7B,MAAM,IAAIE,MAAM,QAAQF,wBAG5B,OADAH,KAAKC,OAAOO,IAAIL,EAAMG,GACfA,EAQX,OAAOH,GACH,OAAOH,KAAKC,OAAOQ,OAAON,GAQ9B,IAAIA,GACA,OAAOH,KAAKC,OAAOG,IAAID,GAO3B,OACI,OAAOO,MAAMC,KAAKX,KAAKC,OAAOW,SAStC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/F,KAAK,UAAW,OAChBA,KAAK,QAAS,8BACdA,KAAK,KAAM,GAAGshC,EAAKlrC,UACnB4J,KAAK,QAAS,gBACdlR,KAAKuX,GAAai7B,EAAK19B,OAAO8C,OAEnC46B,EAAKvjB,gBACLujB,EAAKliB,iBAELkiB,EAAKl5B,aAEDqa,GACA6e,EAAKa,aAGNb,GiBjSPc,YDfJ,cAA0BlzC,EAKtB,YAAY8N,GACRxH,QAGArG,KAAKkzC,UAAYrlC,GAAY,EAYjC,IAAIoC,EAAW3P,EAAMC,GAAW,GAC5B,GAAIP,KAAKkzC,UAAU9yC,IAAI6P,GACnB,MAAM,IAAI5P,MAAM,iBAAiB4P,yCAGrC,GAAIA,EAAUnI,MAAM,iBAChB,MAAM,IAAIzH,MAAM,sGAAsG4P,KAE1H,GAAIvP,MAAMqD,QAAQzD,GAAO,CACrB,MAAOwN,EAAM2X,GAAWnlB,EACxBA,EAAON,KAAKkzC,UAAU3sB,OAAOzY,EAAM2X,GAMvC,OAHAnlB,EAAK4E,UAAY+K,EAEjB5J,MAAM5E,IAAIwO,EAAW3P,EAAMC,GACpBP,OCpBXmzC,SAAQ,EACRC,WAAU,GACVC,QAAO,GACPC,eAAc,GACdC,eAAc,GACdC,wBAAuB,EACvBC,QAAO,GAEP,uBAEI,OADAvyC,QAAQC,KAAK,wEACN,IAYTuyC,GAAoB,GAQ1BlB,GAAUmB,IAAM,SAASC,KAAW9yC,GAEhC,IAAI4yC,GAAkB5xC,SAAS8xC,GAA/B,CAMA,GADA9yC,EAAK2F,QAAQ+rC,IACiB,mBAAnBoB,EAAOC,QACdD,EAAOC,QAAQ51B,MAAM21B,EAAQ9yC,OAC1B,IAAsB,mBAAX8yC,EAGd,MAAM,IAAIvzC,MAAM,mFAFhBuzC,EAAO31B,MAAM,KAAMnd,GAIvB4yC,GAAkBnvC,KAAKqvC,KAI3B,a","file":"locuszoom.app.min.js","sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export default '0.13.4';\n","/**\n * @module\n * @private\n */\n\n/**\n * Base class for all registries.\n *\n * LocusZoom is plugin-extensible, and layouts are JSON-serializable objects that refer to desired features by name (not by class).\n * This is achieved through the use of a central registry that holds a reference to each possible feature.\n *\n * Each registry has some syntactical sugar to make it easier to, eg, modify layouts or create classes.\n * This class is documented solely so that those helper methods can be referenced.\n */\nclass RegistryBase {\n constructor() {\n this._items = new Map();\n }\n\n /**\n * Return the registry member. If the registry stores classes, this returns the class, not the instance.\n * @param {String} name\n * @returns {Function}\n */\n get(name) {\n if (!this._items.has(name)) {\n throw new Error(`Item not found: ${name}`);\n }\n return this._items.get(name);\n }\n\n /**\n * Add a new item to the registry\n * @param {String} name The name of the item to add to the registry\n * @param {*} item The item to be added (constructor, value, etc)\n * @param {boolean} [override=false] Allow redefining an existing item?\n * @return {*} The actual object as added to the registry\n */\n add(name, item, override = false) {\n if (!override && this._items.has(name)) {\n throw new Error(`Item ${name} is already defined`);\n }\n this._items.set(name, item);\n return item;\n }\n\n /**\n * Remove a datasource from the registry (if present)\n * @param {String} name\n * @returns {boolean} True if item removed, false if item was never present\n */\n remove(name) {\n return this._items.delete(name);\n }\n\n /**\n * Check whether the specified item is registered\n * @param {String} name\n * @returns {boolean}\n */\n has(name) {\n return this._items.has(name);\n }\n\n /**\n * Names of each allowed\n * @returns {String[]}\n */\n list() {\n return Array.from(this._items.keys());\n }\n}\n\n/**\n * A specialized registry whose members are class constructors. Contains helper methods for creating instances\n * and subclasses.\n * @ignore\n */\nclass ClassRegistry extends RegistryBase {\n /**\n * Create an instance of the specified class from the registry\n * @param {String} name\n * @param {*} args Any additional arguments to be passed to the constructor\n * @returns {*}\n */\n create(name, ...args) {\n const base = this.get(name);\n return new base(...args);\n }\n\n /**\n * Create a new child class for an item in the registry.\n *\n * This is (almost, but not quite) a compatibility layer for old sites that used locuszoom\n *\n * This is primarily aimed at low-tooling environments. It is syntactic sugar, roughly equivalent to:\n * `registry.get(base); registry.add(name, class A extends base {});`\n *\n * Because this bypasses es6 class mechanics, certain things, esp super calls, may not work as well as using the\n * \"real\" class expression. This method is provided solely for convenience.\n *\n * This method is a compatibility layer for old versions. Born to be deprecated!\n * @deprecated\n * @param {string} parent_name The name of the desired parent class as represented in the registry\n * @param {string} source_name The desired name of the class to be created, as it will be named in the registry\n * @param {object} overrides An object\n * @return {*}\n */\n extend(parent_name, source_name, overrides) {\n console.warn('Deprecation warning: .extend method will be removed in future versions, in favor of explicit ES6 subclasses');\n if (arguments.length !== 3) {\n throw new Error('Invalid arguments to .extend');\n }\n\n const base = this.get(parent_name);\n class sub extends base {}\n Object.assign(sub.prototype, overrides, base);\n this.add(source_name, sub);\n return sub;\n }\n}\n\n\nexport default RegistryBase;\nexport {RegistryBase, ClassRegistry};\n","/**\n * Define standard data adapters used to retrieve data (usually from REST APIs)\n *\n * ## Adapters are responsible for retrieving data\n * In LocusZoom, the act of fetching data (from API, JSON file, or Tabix) is separate from the act of rendering data.\n * Adapters are used to handle retrieving from different sources, and can provide various advanced functionality such\n * as caching, data harmonization, and annotating API responses with calculated fields. They can also be used to join\n * two data sources, such as annotating association summary statistics with LD information.\n *\n * Most of LocusZoom's builtin layouts and adapters are written for the field names and data formats of the\n * UMich [PortalDev API](https://portaldev.sph.umich.edu/docs/api/v1/#introduction):\n * if your data is in a different format, an adapter can be used to coerce or rename fields.\n * Although it is possible to change every part of a rendering layout to expect different fields, this is often much\n * more work than providing data in the expected format.\n *\n * ## Creating data adapters\n * The documentation in this section describes the available data types and adapters. Real LocusZoom usage almost never\n * creates these classes directly: rather, they are defined from configuration objects that ask for a source by name.\n *\n * The below example creates an object responsible for fetching two different GWAS summary statistics datasets from two different API endpoints, for any data\n * layer that asks for fields from `trait1:fieldname` or `trait2:fieldname`.\n *\n * ```\n * const data_sources = new LocusZoom.DataSources();\n * data_sources.add(\"trait1\", [\"AssociationLZ\", {url: \"http://server.com/api/single/\", params: {source: 1}}]);\n * data_sources.add(\"trait2\", [\"AssociationLZ\", {url: \"http://server.com/api/single/\", params: {source: 2}}]);\n * ```\n *\n * These data sources are then passed to the plot when data is to be rendered:\n * `const plot = LocusZoom.populate(\"#lz-plot\", data_sources, layout);`\n *\n * @module LocusZoom_Adapters\n */\n\nfunction validateBuildSource(class_name, build, source) {\n // Build OR Source, not both\n if ((build && source) || !(build || source)) {\n throw new Error(`${class_name} must provide a parameter specifying either \"build\" or \"source\". It should not specify both.`);\n }\n // If the build isn't recognized, our APIs can't transparently select a source to match\n if (build && !['GRCh37', 'GRCh38'].includes(build)) {\n throw new Error(`${class_name} must specify a valid genome build number`);\n }\n}\n\n\n// NOTE: Custom adapaters are annotated with `see` instead of `extend` throughout this file, to avoid clutter in the developer API docs.\n// Most people using LZ data sources will never instantiate a class directly and certainly won't be calling internal\n// methods, except when implementing a subclass. For most LZ users, it's usually enough to acknowledge that the\n// private API methods exist in the base class.\n\n/**\n * Base class for LocusZoom data sources (any). See also: BaseApiAdapter for requests from a remote URL.\n * @public\n */\nclass BaseAdapter {\n /**\n * @param {object} config Configuration options\n */\n constructor(config) {\n /**\n * Whether to enable caching (true for most data adapters)\n * @private\n * @member {Boolean}\n */\n this._enableCache = true;\n this._cachedKey = null;\n\n // Almost all LZ sources are \"region based\". Cache the region requested and use it to determine whether\n // the cache would satisfy the request.\n this._cache_pos_start = null;\n this._cache_pos_end = null;\n\n /**\n * Whether this adapter type is dependent on previous requests- for example, the LD source cannot annotate\n * association data if no data was found for that region.\n * @private\n * @member {boolean}\n */\n this.__dependentSource = false;\n\n // Parse configuration options\n this.parseInit(config);\n }\n\n /**\n * Parse configuration used to create the instance. Many custom sources will override this method to suit their\n * needs (eg specific config options, or for sources that do not retrieve data from a URL)\n * @protected\n * @param {String|Object} config Basic configuration- either a url, or a config object\n * @param {String} [config.url] The datasource URL\n * @param {String} [config.params] Initial config params for the datasource\n */\n parseInit(config) {\n /**\n * @private\n * @member {Object}\n */\n this.params = config.params || {};\n }\n\n /**\n * A unique identifier that indicates whether cached data is valid for this request. For most sources using GET\n * requests to a REST API, this is usually the region requested. Some sources will append additional params to define the request.\n *\n * This means that to change caching behavior, both the URL and the cache key may need to be updated. However,\n * it allows most datasources to skip an extra network request when zooming in.\n * @protected\n * @param {Object} state Information available in plot.state (chr, start, end). Sometimes used to inject globally\n * available information that influences the request being made.\n * @param {Object} chain The data chain from previous requests made in a sequence.\n * @param fields\n * @returns {String}\n */\n getCacheKey(state, chain, fields) {\n // Most region sources, by default, will cache the largest region that satisfies the request: zooming in\n // should be satisfied via the cache, but pan or region change operations will cause a network request\n\n // Some adapters rely on values set in chain.header during the getURL call. (eg, the LD source uses\n // this to find the LD refvar) Calling this method is a backwards-compatible way of ensuring that value is set,\n // even on a cache hit in which getURL otherwise wouldn't be called.\n // Some of the adapters that rely on this behavior are user-defined, hence compatibility hack\n this.getURL(state, chain, fields);\n\n const cache_pos_chr = state.chr;\n const {_cache_pos_start, _cache_pos_end} = this;\n if (_cache_pos_start && state.start >= _cache_pos_start && _cache_pos_end && state.end <= _cache_pos_end ) {\n return `${cache_pos_chr}_${_cache_pos_start}_${_cache_pos_end}`;\n } else {\n return `${state.chr}_${state.start}_${state.end}`;\n }\n }\n\n /**\n * Stub: build the URL for any requests made by this source.\n * @protected\n */\n getURL(state, chain, fields) {\n return this.url;\n }\n\n /**\n * Perform a network request to fetch data for this source. This is usually the method that is used to override\n * when defining how to retrieve data.\n * @protected\n * @param {Object} state The state of the parent plot\n * @param chain\n * @param fields\n * @returns {Promise}\n */\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n return fetch(url).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n });\n }\n\n /**\n * Gets the data for just this source, typically via a network request (but using cache where possible)\n *\n * For most use cases, it is better to override `fetchRequest` instead, to avoid bypassing the cache mechanism\n * by accident.\n * @protected\n * @return {Promise}\n */\n getRequest(state, chain, fields) {\n let req;\n const cacheKey = this.getCacheKey(state, chain, fields);\n\n if (this._enableCache && typeof(cacheKey) !== 'undefined' && cacheKey === this._cachedKey) {\n req = Promise.resolve(this._cachedResponse); // Resolve to the value of the current promise\n } else {\n req = this.fetchRequest(state, chain, fields);\n if (this._enableCache) {\n this._cachedKey = cacheKey;\n this._cache_pos_start = state.start;\n this._cache_pos_end = state.end;\n this._cachedResponse = req;\n }\n }\n return req;\n }\n\n /**\n * Ensure the server response is in a canonical form, an array of one object per record. [ {field: oneval} ].\n * If the server response contains columns, reformats the response from {column1: [], column2: []} to the above.\n *\n * Does not apply namespacing, transformations, or field extraction.\n *\n * May be overridden by data adapters that inherently return more complex payloads, or that exist to annotate other\n * sources (eg, if the payload provides extra data rather than a series of records).\n * @protected\n * @param {Object[]|Object} data The original parsed server response\n */\n normalizeResponse(data) {\n if (Array.isArray(data)) {\n // Already in the desired form\n return data;\n }\n // Otherwise, assume the server response is an object representing columns of data.\n // Each array should have the same length (verify), and a given array index corresponds to a single row.\n const keys = Object.keys(data);\n const N = data[keys[0]].length;\n const sameLength = keys.every(function (key) {\n const item = data[key];\n return item.length === N;\n });\n if (!sameLength) {\n throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);\n }\n\n // Go down the rows, and create an object for each record\n const records = [];\n const fields = Object.keys(data);\n for (let i = 0; i < N; i++) {\n const record = {};\n for (let j = 0; j < fields.length; j++) {\n record[fields[j]] = data[fields[j]][i];\n }\n records.push(record);\n }\n return records;\n }\n\n /**\n * Hook to post-process the data returned by this source with new, additional behavior.\n * (eg cleaning up API values or performing complex calculations on the returned data)\n *\n * @protected\n * @param {Object[]} records The parsed data from the source (eg standardized api response)\n * @param {Object} chain The data chain object. For example, chain.headers may provide useful annotation metadata\n * @returns {Object[]|Promise} The modified set of records\n */\n annotateData(records, chain) {\n // Default behavior: no transformations\n return records;\n }\n\n /**\n * Clean up the server records for use by datalayers: extract only certain fields, with the specified names.\n * Apply per-field transformations as appropriate.\n *\n * This hook can be overridden, eg to create a source that always returns all records and ignores the \"fields\" array.\n * This is particularly common for sources at the end of a chain- many \"dependent\" sources do not allow\n * cherry-picking individual fields, in which case by **convention** the fields array specifies \"last_source_name:all\"\n *\n * @protected\n * @param {Object[]} data One record object per element\n * @param {String[]} fields The names of fields to extract (as named in the source data). Eg \"afield\"\n * @param {String[]} outnames How to represent the source fields in the output. Eg \"namespace:afield|atransform\"\n * @param {function[]} trans An array of transformation functions (if any). One function per data element, or null.\n * @protected\n */\n extractFields (data, fields, outnames, trans) {\n //intended for an array of objects\n // [ {\"id\":1, \"val\":5}, {\"id\":2, \"val\":10}]\n // Since a number of sources exist that do not obey this format, we will provide a convenient pass-through\n if (!Array.isArray(data)) {\n return data;\n }\n\n if (!data.length) {\n // Sometimes there are regions that just don't have data- this should not trigger a missing field error message!\n return data;\n }\n\n const fieldFound = [];\n for (let k = 0; k < fields.length; k++) {\n fieldFound[k] = 0;\n }\n\n const records = data.map(function (item) {\n const output_record = {};\n for (let j = 0; j < fields.length; j++) {\n let val = item[fields[j]];\n if (typeof val != 'undefined') {\n fieldFound[j] = 1;\n }\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n output_record[outnames[j]] = val;\n }\n return output_record;\n });\n fieldFound.forEach(function(v, i) {\n if (!v) {\n throw new Error(`field ${fields[i]} not found in response for ${outnames[i]}`);\n }\n });\n return records;\n }\n\n /**\n * Combine records from this source with others in the chain to yield final chain body.\n * Handles merging this data with other sources (if applicable).\n *\n * @protected\n * @param {Object[]} data The data That would be returned from this source alone\n * @param {Object} chain The data chain built up during previous requests\n * @param {String[]} fields\n * @param {String[]} outnames\n * @param {String[]} trans\n * @return {Promise|Object[]} The new chain body\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n return data;\n }\n\n /**\n * Coordinates the work of parsing a response and returning records. This is broken into 4 steps, which may be\n * overridden separately for fine-grained control. Each step can return either raw data or a promise.\n *\n * @see {module:LocusZoom_Adapters~BaseAdapter#normalizeResponse}\n * @see {module:LocusZoom_Adapters~BaseAdapter#annotateData}\n * @see {module:LocusZoom_Adapters~BaseAdapter#extractFields}\n * @see {module:LocusZoom_Adapters~BaseAdapter#combineChainBody}\n * @protected\n *\n * @param {String|Object} resp The raw data associated with the response\n * @param {Object} chain The combined parsed response data from this and all other requests made in the chain\n * @param {String[]} fields Array of requested field names (as they would appear in the response payload)\n * @param {String[]} outnames Array of field names as they will be represented in the data returned by this source,\n * including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {Promise} A promise that resolves to an object containing\n * request metadata (`headers: {}`), the consolidated data for plotting (`body: []`), and the individual responses that would be\n * returned by each source in the chain in isolation (`discrete: {}`)\n */\n parseResponse (resp, chain, fields, outnames, trans) {\n const source_id = this.source_id || this.constructor.name;\n if (!chain.discrete) {\n chain.discrete = {};\n }\n\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n\n // Perform the 4 steps of parsing the payload and return a combined chain object\n return Promise.resolve(this.normalizeResponse(json.data || json))\n .then((standardized) => {\n // Perform calculations on the data from just this source\n return Promise.resolve(this.annotateData(standardized, chain));\n }).then((data) => {\n return Promise.resolve(this.extractFields(data, fields, outnames, trans));\n }).then((one_source_body) => {\n // Store a copy of the data that would be returned by parsing this source in isolation (and taking the\n // fields array into account). This is useful when we want to re-use the source output in many ways.\n chain.discrete[source_id] = one_source_body;\n return Promise.resolve(this.combineChainBody(one_source_body, chain, fields, outnames, trans));\n }).then((new_body) => {\n return { header: chain.header || {}, discrete: chain.discrete, body: new_body };\n });\n }\n\n /**\n * Fetch the data from the specified data adapter, and apply transformations requested by an external consumer.\n * This is the public-facing datasource method that will most be called by the plot, but custom data adapters will\n * almost never want to override this method directly- more specific hooks are provided to control individual pieces\n * of the request lifecycle.\n *\n * @private\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields Array of field names that the plot has requested from this data adapter. (without the \"namespace\" prefix)\n * @param {String[]} outnames Array describing how the output data should refer to this field. This represents the\n * originally requested field name, including the namespace. This must be an array with the same length as `fields`\n * @param {Function[]} trans The collection of transformation functions to be run on selected fields.\n * This must be an array with the same length as `fields`\n * @returns {function} A callable operation that can be used as part of the data chain\n */\n getData(state, fields, outnames, trans) {\n if (this.preGetData) { // TODO try to remove this method if at all possible\n const pre = this.preGetData(state, fields, outnames, trans);\n if (this.pre) {\n state = pre.state || state;\n fields = pre.fields || fields;\n outnames = pre.outnames || outnames;\n trans = pre.trans || trans;\n }\n }\n\n return (chain) => {\n if (this.__dependentSource && chain && chain.body && !chain.body.length) {\n // A \"dependent\" source should not attempt to fire a request if there is no data for it to act on.\n // Therefore, it should simply return the previous data chain.\n return Promise.resolve(chain);\n }\n\n return this.getRequest(state, chain, fields).then((resp) => {\n return this.parseResponse(resp, chain, fields, outnames, trans);\n });\n };\n }\n}\n\n/**\n * Base class for LocusZoom data adapters that receive their data over the web. Adds default config parameters\n * (and potentially other behavior) that are relevant to URL-based requests.\n * @extends module:LocusZoom_Adapters~BaseAdapter\n * @param {string} config.url The URL for the remote dataset. By default, most adapters perform a GET request.\n * @inheritDoc\n */\nclass BaseApiAdapter extends BaseAdapter {\n parseInit(config) {\n super.parseInit(config);\n\n /**\n * @private\n * @member {String}\n */\n this.url = config.url;\n if (!this.url) {\n throw new Error('Source not initialized with required URL');\n }\n }\n}\n\n/**\n * Retrieve Association Data from the LocusZoom/ Portaldev API (or compatible). Defines how to make a request\n * to a specific REST API.\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data.\n * @param {object} config.params\n * @param [config.params.sort=false] Whether to sort the association data (by an assumed field named \"position\"). This\n * is primarily a site-specific workaround for a particular LZ usage; we encourage apis to sort by position before returning\n * data to the browser.\n * @param [config.params.source] The ID of the GWAS dataset to use for this request, as matching the API backend\n */\nclass AssociationLZ extends BaseApiAdapter {\n preGetData (state, fields, outnames, trans) {\n // TODO: Modify internals to see if we can go without this method\n const id_field = this.params.id_field || 'id';\n [id_field, 'position'].forEach(function(x) {\n if (!fields.includes(x)) {\n fields.unshift(x);\n outnames.unshift(x);\n trans.unshift(null);\n }\n });\n return {fields: fields, outnames:outnames, trans:trans};\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL (state, chain, fields) {\n const analysis = chain.header.analysis || this.params.source || this.params.analysis; // Old usages called this param \"analysis\"\n if (typeof analysis == 'undefined') {\n throw new Error('Association source must specify an analysis ID to plot');\n }\n return `${this.url}results/?filter=analysis in ${analysis} and chromosome in '${state.chr}' and position ge ${state.start} and position le ${state.end}`;\n }\n\n /**\n * Some association sources do not sort their data in a predictable order, which makes it hard to reliably\n * align with other sources (such as LD). For performance reasons, sorting is an opt-in argument.\n * TODO: Consider more fine grained sorting control in the future. This was added as a very specific\n * workaround for the original T2D portal.\n * @protected\n * @param data\n * @return {Object}\n */\n normalizeResponse (data) {\n data = super.normalizeResponse(data);\n if (this.params && this.params.sort && data.length && data[0]['position']) {\n data.sort(function (a, b) {\n return a['position'] - b['position'];\n });\n }\n return data;\n }\n}\n\n/**\n * Fetch linkage disequilibrium information from a UMich LDServer-compatible API, relative to a reference variant.\n * If no `plot.state.ldrefvar` is explicitly provided, this source will attempt to find the most significant GWAS\n * variant (smallest pvalue or largest neg_log_pvalue) and yse that as the LD reference variant.\n *\n * This source is designed to connect its results to association data, and therefore depends on association data having\n * been loaded by a previous request in the data chain. For custom association APIs, some additional options might\n * need to be be specified in order to locate the most significant SNP. Variant IDs of the form `chrom:pos_ref/alt`\n * are preferred, but this source will attempt to harmonize other common data formats into something that the LD\n * server can understand.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass LDServer extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param {object} config.params\n * @param [config.params.build='GRCh37'] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param [config.params.source='1000G'] The name of the reference panel to use, as specified in the LD server instance.\n * May be overridden by a global parameter `plot.state.ld_source` to implement widgets that alter LD display.\n * @param [config.params.population='ALL'] The sample population used to calculate LD for a specified source;\n * population names vary depending on the reference panel and how the server was populated wth data.\n * May be overridden by a global parameter `plot.state.ld_pop` to implement widgets that alter LD display.\n * @param [config.params.method='rsquare'] The metric used to calculate LD\n * @param [config.params.id_field] The association data field that contains variant identifier information. The preferred\n * format of LD server is `chrom:pos_ref/alt` and this source will attempt to normalize other common formats.\n * This source can auto-detect possible matches for field names containing \"variant\" or \"id\"\n * @param [config.params.position_field] The association data field that contains variant position information.\n * This source can auto-detect possible matches for field names containing \"position\" or \"pos\"\n * @param [config.params.pvalue_field] The association data field that contains pvalue information.\n * This source can auto-detect possible matches for field names containing \"pvalue\" or \"log_pvalue\".\n * The suggested LD refvar will be the smallest pvalue, or the largest log_pvalue: this source will auto-detect\n * the word \"log\" in order to determine the sign of the comparison.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n preGetData(state, fields) {\n if (fields.length > 1) {\n if (fields.length !== 2 || !fields.includes('isrefvar')) {\n throw new Error(`LD does not know how to get all fields: ${fields.join(', ')}`);\n }\n }\n }\n\n findMergeFields(chain) {\n // Find the fields (as provided by a previous step in the chain, like an association source) that will be needed to\n // combine LD data with existing information\n\n // Since LD information may be shared across multiple assoc sources with different namespaces,\n // we use regex to find columns to join on, rather than requiring exact matches\n const exactMatch = function (arr) {\n return function () {\n const regexes = arguments;\n for (let i = 0; i < regexes.length; i++) {\n const regex = regexes[i];\n const m = arr.filter(function (x) {\n return x.match(regex);\n });\n if (m.length) {\n return m[0];\n }\n }\n return null;\n };\n };\n let dataFields = {\n id: this.params.id_field,\n position: this.params.position_field,\n pvalue: this.params.pvalue_field,\n _names_:null,\n };\n if (chain && chain.body && chain.body.length > 0) {\n const names = Object.keys(chain.body[0]);\n const nameMatch = exactMatch(names);\n // Internally, fields are generally prefixed with the name of the source they come from.\n // If the user provides an id_field (like `variant`), it should work across data sources (`assoc1:variant`,\n // assoc2:variant), but not match fragments of other field names (assoc1:variant_thing)\n // Note: these lookups hard-code a couple of common fields that will work based on known APIs in the wild\n const id_match = dataFields.id && nameMatch(new RegExp(`${dataFields.id}\\\\b`));\n dataFields.id = id_match || nameMatch(/\\bvariant\\b/) || nameMatch(/\\bid\\b/);\n dataFields.position = dataFields.position || nameMatch(/\\bposition\\b/i, /\\bpos\\b/i);\n dataFields.pvalue = dataFields.pvalue || nameMatch(/\\bpvalue\\b/i, /\\blog_pvalue\\b/i);\n dataFields._names_ = names;\n }\n return dataFields;\n }\n\n findRequestedFields (fields, outnames) {\n // Assumption: all usages of this source will only ever ask for \"isrefvar\" or \"state\". This maps to output names.\n let obj = {};\n for (let i = 0; i < fields.length; i++) {\n if (fields[i] === 'isrefvar') {\n obj.isrefvarin = fields[i];\n obj.isrefvarout = outnames && outnames[i];\n } else {\n obj.ldin = fields[i];\n obj.ldout = outnames && outnames[i];\n }\n }\n return obj;\n }\n\n /**\n * The LD API payload does not obey standard format conventions; do not try to transform it.\n */\n normalizeResponse (data) {\n return data;\n }\n\n /**\n * Get the LD reference variant, which by default will be the most significant hit in the assoc results\n * This will be used in making the original query to the LD server for pairwise LD information.\n *\n * This is meant to join a single LD request to any number of association results, and to work with many kinds of API.\n * To do this, the datasource looks for fields with special known names such as pvalue, log_pvalue, etc.\n * If your API uses different nomenclature, an option must be specified.\n *\n * @protected\n * @returns {String[]} Two strings: 1) the marker id (expected to be in `chr:pos_ref/alt` format) of the reference\n * variant, and 2) the marker ID as it appears in the original dataset that we are joining to, so that the exact\n * refvar can be marked when plotting the data..\n */\n getRefvar(state, chain, fields) {\n let findExtremeValue = function(records, pval_field) {\n // Finds the most significant hit (smallest pvalue, or largest -log10p). Will try to auto-detect the appropriate comparison.\n pval_field = pval_field || 'log_pvalue'; // The official LZ API returns log_pvalue\n const is_log = /log/.test(pval_field);\n let cmp;\n if (is_log) {\n cmp = function(a, b) {\n return a > b;\n };\n } else {\n cmp = function(a, b) {\n return a < b;\n };\n }\n let extremeVal = records[0][pval_field], extremeIdx = 0;\n for (let i = 1; i < records.length; i++) {\n if (cmp(records[i][pval_field], extremeVal)) {\n extremeVal = records[i][pval_field];\n extremeIdx = i;\n }\n }\n return extremeIdx;\n };\n\n let reqFields = this.findRequestedFields(fields);\n let refVar = reqFields.ldin;\n if (refVar === 'state') {\n refVar = state.ldrefvar || chain.header.ldrefvar || 'best';\n }\n if (refVar === 'best') {\n if (!chain.body) {\n throw new Error('No association data found to find best pvalue');\n }\n let keys = this.findMergeFields(chain);\n if (!keys.pvalue || !keys.id) {\n let columns = '';\n if (!keys.id) {\n columns += `${columns.length ? ', ' : ''}id`;\n }\n if (!keys.pvalue) {\n columns += `${columns.length ? ', ' : ''}pvalue`;\n }\n throw new Error(`Unable to find necessary column(s) for merge: ${columns} (available: ${keys._names_})`);\n }\n refVar = chain.body[findExtremeValue(chain.body, keys.pvalue)][keys.id];\n }\n // Some datasets, notably the Portal, use a different marker format.\n // Coerce it into one that will work with the LDServer API. (CHROM:POS_REF/ALT)\n const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n const match = refVar && refVar.match(REGEX_MARKER);\n\n if (!match) {\n throw new Error('Could not request LD for a missing or incomplete marker format');\n }\n const [original, chrom, pos, ref, alt] = match;\n // Currently, the LD server only accepts full variant specs; it won't return LD w/o ref+alt. Allowing\n // a partial match at most leaves room for potential future features.\n let refVar_formatted = `${chrom}:${pos}`;\n if (ref && alt) {\n refVar_formatted += `_${ref}/${alt}`;\n }\n\n return [refVar_formatted, original];\n }\n\n /**\n * Identify (or guess) the LD reference variant, then add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n // The LD source/pop can be overridden from plot.state for dynamic layouts\n const build = state.genome_build || this.params.build || 'GRCh37'; // This isn't expected to change after the data is plotted.\n let source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const method = this.params.method || 'rsquare';\n\n if (source === '1000G' && build === 'GRCh38') {\n // For build 38 (only), there is a newer/improved 1000G LD panel available that uses WGS data. Auto upgrade by default.\n source = '1000G-FRZ09';\n }\n\n validateBuildSource(this.constructor.name, build, null); // LD doesn't need to validate `source` option\n\n const [refVar_formatted, refVar_raw] = this.getRefvar(state, chain, fields);\n\n // Preserve the user-provided variant spec for use when matching to assoc data\n chain.header.ldrefvar = refVar_raw;\n\n return [\n this.url, 'genome_builds/', build, '/references/', source, '/populations/', population, '/variants',\n '?correlation=', method,\n '&variant=', encodeURIComponent(refVar_formatted),\n '&chrom=', encodeURIComponent(state.chr),\n '&start=', encodeURIComponent(state.start),\n '&stop=', encodeURIComponent(state.end),\n ].join('');\n }\n\n /**\n * The LD adapter caches based on region, reference panel, and population name\n * @param state\n * @param chain\n * @param fields\n * @return {string}\n */\n getCacheKey(state, chain, fields) {\n const base = super.getCacheKey(state, chain, fields);\n let source = state.ld_source || this.params.source || '1000G';\n const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL\n const [refVar, _] = this.getRefvar(state, chain, fields);\n return `${base}_${refVar}_${source}_${population}`;\n }\n\n /**\n * The LD adapter attempts to intelligently match retrieved LD information to a request for association data earlier in the data chain.\n * Since each layer only asks for the data needed for that layer, one LD call is sufficient to annotate many separate association tracks.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n let keys = this.findMergeFields(chain);\n let reqFields = this.findRequestedFields(fields, outnames);\n if (!keys.position) {\n throw new Error(`Unable to find position field for merge: ${keys._names_}`);\n }\n const leftJoin = function (left, right, lfield, rfield) {\n let i = 0, j = 0;\n while (i < left.length && j < right.position2.length) {\n if (left[i][keys.position] === right.position2[j]) {\n left[i][lfield] = right[rfield][j];\n i++;\n j++;\n } else if (left[i][keys.position] < right.position2[j]) {\n i++;\n } else {\n j++;\n }\n }\n };\n const tagRefVariant = function (data, refvar, idfield, outrefname, outldname) {\n for (let i = 0; i < data.length; i++) {\n if (data[i][idfield] && data[i][idfield] === refvar) {\n data[i][outrefname] = 1;\n data[i][outldname] = 1; // For label/filter purposes, implicitly mark the ref var as LD=1 to itself\n } else {\n data[i][outrefname] = 0;\n }\n }\n };\n\n // LD servers vary slightly. Some report corr as \"rsquare\", others as \"correlation\"\n let corrField = data.rsquare ? 'rsquare' : 'correlation';\n leftJoin(chain.body, data, reqFields.ldout, corrField);\n if (reqFields.isrefvarin && chain.header.ldrefvar) {\n tagRefVariant(chain.body, chain.header.ldrefvar, keys.id, reqFields.isrefvarout, reqFields.ldout);\n }\n return chain.body;\n }\n\n /**\n * The LDServer API is paginated, but we need all of the data to render a plot. Depaginate and combine where appropriate.\n */\n fetchRequest(state, chain, fields) {\n let url = this.getURL(state, chain, fields);\n let combined = { data: {} };\n let chainRequests = function (url) {\n return fetch(url).then().then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function(payload) {\n payload = JSON.parse(payload);\n Object.keys(payload.data).forEach(function (key) {\n combined.data[key] = (combined.data[key] || []).concat(payload.data[key]);\n });\n if (payload.next) {\n return chainRequests(payload.next);\n }\n return combined;\n });\n };\n return chainRequests(url);\n }\n}\n\n/**\n * Fetch GWAS catalog data for a list of known variants, and align the data with previously fetched association data.\n * There can be more than one claim per variant; this adapter is written to support a visualization in which each\n * association variant is labeled with the single most significant hit in the GWAS catalog. (and enough information to link to the external catalog for more information)\n *\n * Sometimes the GWAS catalog uses rsIDs that could refer to more than one variant (eg multiple alt alleles are\n * possible for the same rsID). To avoid missing possible hits due to ambiguous meaning, we connect the assoc\n * and catalog data via the position field, not the full variant specifier. This source will auto-detect the matching\n * field in association data by looking for the field name `position` or `pos`.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass GwasCatalogLZ extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen catalog. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent EBI GWAS catalog, GRCh37.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n // This is intended to be aligned with another source- we will assume they are always ordered by position, asc\n // (regardless of the actual match field)\n const build = state.genome_build || this.params.build;\n const source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and id eq ${source}`;\n return `${this.url }?format=objects&sort=pos&filter=chrom eq '${state.chr}' and pos ge ${state.start} and pos le ${state.end}${source_query}`;\n }\n\n findMergeFields(records) {\n // Data from previous sources is already namespaced. Find the alignment field by matching.\n const knownFields = Object.keys(records);\n // Note: All API endoints involved only give results for 1 chromosome at a time; match is implied\n const posMatch = knownFields.find(function (item) {\n return item.match(/\\b(position|pos)\\b/i);\n });\n\n if (!posMatch) {\n throw new Error('Could not find data to align with GWAS catalog results');\n }\n return { 'pos': posMatch };\n }\n\n extractFields (data, fields, outnames, trans) {\n // Skip the \"individual field extraction\" step; extraction will be handled when building chain body instead\n return data;\n }\n\n /**\n * Intelligently combine the LD data with the association data used for this data layer. See class description\n * for a summary of how this works.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data.length) {\n return chain.body;\n }\n\n // TODO: Better reuse options in the future. This source is very specifically tied to the UM PortalDev API, where\n // the field name is always \"log_pvalue\". Relatively few sites will write their own gwas-catalog endpoint.\n const decider = 'log_pvalue';\n const decider_out = outnames[fields.indexOf(decider)];\n\n function leftJoin(left, right, fields, outnames, trans) { // Add `fields` from `right` to `left`\n // Add a synthetic, un-namespaced field to all matching records\n const n_matches = left['n_catalog_matches'] || 0;\n left['n_catalog_matches'] = n_matches + 1;\n if (decider && left[decider_out] && left[decider_out] > right[decider]) {\n // There may be more than one GWAS catalog entry for the same SNP. This source is intended for a 1:1\n // annotation scenario, so for now it only joins the catalog entry that has the best -log10 pvalue\n return;\n }\n\n for (let j = 0; j < fields.length; j++) {\n const fn = fields[j];\n const outn = outnames[j];\n\n let val = right[fn];\n if (trans && trans[j]) {\n val = trans[j](val);\n }\n left[outn] = val;\n }\n }\n\n const chainNames = this.findMergeFields(chain.body[0]);\n const catNames = this.findMergeFields(data[0]);\n\n var i = 0, j = 0;\n while (i < chain.body.length && j < data.length) {\n var left = chain.body[i];\n var right = data[j];\n\n if (left[chainNames.pos] === right[catNames.pos]) {\n // There may be multiple catalog entries for each matching SNP; evaluate match one at a time\n leftJoin(left, right, fields, outnames, trans);\n j += 1;\n } else if (left[chainNames.pos] < right[catNames.pos]) {\n i += 1;\n } else {\n j += 1;\n }\n }\n return chain.body;\n }\n}\n\n/**\n * Retrieve Gene Data, as fetched from the LocusZoom/Portaldev API server (or compatible format)\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen gene dataset. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent GENCODE data, GRCh37.\n */\nclass GeneLZ extends BaseApiAdapter {\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.name, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and source in ${source}`;\n return `${this.url}?filter=chrom eq '${state.chr}' and start le ${state.end} and end ge ${state.start}${source_query}`;\n }\n\n /**\n * The UM genes API has a very complex internal data format. Bypass any record parsing, and provide the data layer with\n * the exact information returned by the API. (ignoring the fields array in the layout)\n * @param data\n * @return {Object[]|Object}\n */\n normalizeResponse(data) {\n return data;\n }\n\n /**\n * Does not attempt to namespace or modify the fields from the API payload; the payload format is very complex and\n * quite coupled with the data rendering implementation.\n * Typically, requests to this adapter specify a single dummy field sufficient to trigger the request: `fields:[ 'gene:all' ]`\n */\n extractFields(data, fields, outnames, trans) {\n return data;\n }\n}\n\n/**\n * Retrieve Gene Constraint Data, as fetched from the gnomAD server (or compatible graphQL api endpoint)\n *\n * This is intended to be the second request in a chain, with special logic that connects it to Genes data\n * already fetched. It assumes that the genes data is returned from the UM API, and thus the logic involves\n * matching on specific assumptions about `gene_name` format.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n */\nclass GeneConstraintLZ extends BaseApiAdapter {\n /**\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n */\n constructor(config) {\n super(config);\n this.__dependentSource = true;\n }\n\n /**\n * GraphQL API: request details are encoded in the body, not the URL\n */\n getURL() {\n return this.url;\n }\n\n /**\n * The gnomAD API has a very complex internal data format. Bypass any record parsing, and provide the data layer with\n * the exact information returned by the API.\n */\n normalizeResponse(data) {\n return data;\n }\n\n fetchRequest(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n if (!build) {\n throw new Error(`Adapter ${this.constructor.name} must specify a 'genome_build' option`);\n }\n\n const unique_gene_names = chain.body.reduce(\n // In rare cases, the same gene symbol may appear at multiple positions. (issue #179) We de-duplicate the\n // gene names to avoid issuing a malformed GraphQL query.\n function (acc, gene) {\n acc[gene.gene_name] = null;\n return acc;\n },\n {}\n );\n let query = Object.keys(unique_gene_names).map(function (gene_name) {\n // GraphQL alias names must match a specific set of allowed characters: https://stackoverflow.com/a/45757065/1422268\n const alias = `_${gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`;\n // Each gene symbol is a separate graphQL query, grouped into one request using aliases\n return `${alias}: gene(gene_symbol: \"${gene_name}\", reference_genome: ${build}) { gnomad_constraint { exp_syn obs_syn syn_z oe_syn oe_syn_lower oe_syn_upper exp_mis obs_mis mis_z oe_mis oe_mis_lower oe_mis_upper exp_lof obs_lof pLI oe_lof oe_lof_lower oe_lof_upper } } `;\n });\n\n if (!query.length || query.length > 25 || build === 'GRCh38') {\n // Skip the API request when it would make no sense:\n // - Build 38 (gnomAD supports build GRCh37 only; don't hit server when invalid. This isn't future proof, but we try to be good neighbors.)\n // - Too many genes (gnomAD appears max cost ~25 genes)\n // - No genes in region (hence no constraint info)\n return Promise.resolve({ data: null });\n }\n\n query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas\n const url = this.getURL(state, chain, fields);\n // See: https://graphql.org/learn/serving-over-http/\n const body = JSON.stringify({ query: query });\n const headers = { 'Content-Type': 'application/json' };\n\n // Note: The gnomAD API sometimes fails randomly.\n // If request blocked, return a fake \"no data\" signal so the genes track can still render w/o constraint info\n return fetch(url, { method: 'POST', body, headers }).then((response) => {\n if (!response.ok) {\n return [];\n }\n return response.text();\n }).catch((err) => []);\n }\n\n /**\n * Annotate GENCODE data (from a previous request to the genes adapter) with additional gene constraint data from\n * the gnomAD API. See class description for a summary of how this works.\n */\n combineChainBody(data, chain, fields, outnames, trans) {\n if (!data) {\n return chain;\n }\n\n chain.body.forEach(function(gene) {\n // Find payload keys that match gene names in this response\n const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names\n const constraint = data[alias] && data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene\n if (constraint) {\n // Add all fields from constraint data- do not override fields present in the gene source\n Object.keys(constraint).forEach(function (key) {\n let val = constraint[key];\n if (typeof gene[key] === 'undefined') {\n if (typeof val == 'number' && val.toString().includes('.')) {\n val = parseFloat(val.toFixed(2));\n }\n gene[key] = val; // These two sources are both designed to bypass namespacing\n }\n });\n }\n });\n return chain.body;\n }\n}\n\n/**\n * Retrieve Recombination Rate Data, as fetched from the LocusZoom API server (or compatible)\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant.\n * May be overridden by a global parameter `plot.state.genome_build` so that all datasets can be fetched for the appropriate build in a consistent way.\n * @param {Number} [config.params.source] The ID of the chosen dataset. Most usages should omit this parameter and\n * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent HAPMAP recombination rate, GRCh37.\n */\nclass RecombLZ extends BaseApiAdapter {\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n getURL(state, chain, fields) {\n const build = state.genome_build || this.params.build;\n let source = this.params.source;\n validateBuildSource(this.constructor.SOURCE_NAME, build, source);\n\n // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build).\n // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date\n const source_query = build ? `&build=${build}` : ` and id in ${source}`;\n return `${this.url}?filter=chromosome eq '${state.chr}' and position le ${state.end} and position ge ${state.start}${source_query}`;\n }\n}\n\n/**\n * Retrieve static blobs of data as raw JS objects. This does not perform additional parsing, which is required\n * for some sources (eg it does not know how to join together LD and association data).\n *\n * Therefore it is the responsibility of the user to pass information in a format that can be read and\n * understood by the chosen plot- a StaticJSON source is rarely a drop-in replacement for existing layouts.\n *\n * This source is largely here for legacy reasons. More often, a convenient way to serve static data is as separate\n * JSON files to an existing source (with the JSON url in place of an API).\n *\n * Note: The name is a bit misleading. It receives JS objects, not strings serialized as \"json\".\n * @public\n * @see module:LocusZoom_Adapters~BaseAdapter\n * @param {object} data The data to be returned by this source (subject to namespacing rules)\n */\nclass StaticSource extends BaseAdapter {\n parseInit(data) {\n // Does not receive any config; the only argument is the raw data, embedded when source is created\n this._data = data;\n }\n\n getRequest(state, chain, fields) {\n return Promise.resolve(this._data);\n }\n}\n\n/**\n * Retrieve PheWAS data retrieved from a LocusZoom/PortalDev compatible API\n * @public\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {Object} config.params\n * @param {String[]} config.params.build This datasource expects to be provided the name of the genome build that will\n * be used to provide pheWAS results for this position. Note positions may not translate between builds.\n */\nclass PheWASLZ extends BaseApiAdapter {\n getURL(state, chain, fields) {\n const build = (state.genome_build ? [state.genome_build] : null) || this.params.build;\n if (!build || !Array.isArray(build) || !build.length) {\n throw new Error(['Adapter', this.constructor.SOURCE_NAME, 'requires that you specify array of one or more desired genome build names'].join(' '));\n }\n const url = [\n this.url,\n \"?filter=variant eq '\", encodeURIComponent(state.variant), \"'&format=objects&\",\n build.map(function (item) {\n return `build=${encodeURIComponent(item)}`;\n }).join('&'),\n ];\n return url.join('');\n }\n\n getCacheKey(state, chain, fields) {\n // This is not a region-based source; it doesn't make sense to cache by a region\n return this.getURL(state, chain, fields);\n }\n}\n\n/**\n * Base class for \"connectors\"- this is a highly specialized kind of adapter that is rarely used in most LocusZoom\n * deployments. This is meant to be subclassed, rather than used directly.\n *\n * A connector is a data adapter that makes no server requests and caches no data of its own. Instead, it decides how to\n * combine data from other sources in the chain. Connectors are useful when we want to request (or calculate) some\n * useful piece of information once, but apply it to many different kinds of record types.\n *\n * Typically, a subclass will implement the field merging logic in `combineChainBody`.\n *\n * @public\n * @see module:LocusZoom_Adapters~BaseAdapter\n */\nclass ConnectorSource extends BaseAdapter {\n /**\n * @param {Object} config.params Additional parameters\n * @param {Object} config.params.sources Specify how the hard-coded logic should find the data it relies on in the chain,\n * as {internal_name: chain_source_id} pairs. This allows writing a reusable connector that does not need to make\n * assumptions about what namespaces a source is using. *\n */\n constructor(config) {\n super(config);\n\n if (!config || !config.sources) {\n throw new Error('Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs');\n }\n\n /**\n * Tells the connector how to find the data it relies on\n *\n * For example, a connector that applies burden test information to the genes layer might specify:\n * {gene_ns: \"gene\", aggregation_ns: \"aggregation\"}\n *\n * @member {Object}\n * @private\n */\n this._source_name_mapping = config.sources;\n\n // Validate that this source has been told how to find the required information\n const specified_ids = Object.keys(config.sources);\n /** @property {String[]} Specifies the sources that must be provided in the original config object */\n\n this._getRequiredSources().forEach((k) => {\n if (!specified_ids.includes(k)) {\n // TODO: Fix constructor.name usage in minified bundles\n throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${k}`);\n }\n });\n }\n\n // Stub- connectors don't have their own url or data, so the defaults don't make sense\n parseInit() {}\n\n getRequest(state, chain, fields) {\n // Connectors do not request their own data by definition, but they *do* depend on other sources having been loaded\n // first. This method performs basic validation, and preserves the accumulated body from the chain so far.\n Object.keys(this._source_name_mapping).forEach((ns) => {\n const chain_source_id = this._source_name_mapping[ns];\n if (chain.discrete && !chain.discrete[chain_source_id]) {\n throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${chain_source_id}`);\n }\n });\n return Promise.resolve(chain.body || []);\n }\n\n parseResponse(data, chain, fields, outnames, trans) {\n // A connector source does not update chain.discrete, but it may use it. It bypasses data formatting\n // and field selection (both are assumed to have been done already, by the previous sources this draws from)\n\n // Because of how the chain works, connectors are not very good at applying new transformations or namespacing.\n // Typically connectors are called with `connector_name:all` in the fields array.\n return Promise.resolve(this.combineChainBody(data, chain, fields, outnames, trans))\n .then(function(new_body) {\n return {header: chain.header || {}, discrete: chain.discrete || {}, body: new_body};\n });\n }\n\n combineChainBody(records, chain) {\n // Stub method: specifies how to combine the data\n throw new Error('This method must be implemented in a subclass');\n }\n\n /**\n * Helper method since ES6 doesn't support class fields\n * @private\n */\n _getRequiredSources() {\n throw new Error('Must specify an array that identifes the kind of data required by this source');\n }\n}\n\nexport { BaseAdapter, BaseApiAdapter };\n\nexport {\n AssociationLZ,\n ConnectorSource,\n GeneConstraintLZ,\n GeneLZ,\n GwasCatalogLZ,\n LDServer,\n PheWASLZ,\n RecombLZ,\n StaticSource,\n};\n","/**\n * A registry of known data adapters. Can be used to find adapters by name. It will search predefined classes\n * as well as those registered by plugins.\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\n\nimport * as adapters from '../data/adapters';\n\n\n// LocusZoom.Adapters is a basic registry with no special behavior.\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data adapters (responsible for\n * controlling the retrieval and harmonization of data).\n * @alias module:LocusZoom~Adapters\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(adapters)) {\n registry.add(name, type);\n}\n\n// Add some hard-coded aliases for backwards compatibility\n\n/**\n * Backwards-compatible alias for StaticSource\n * @public\n * @name module:LocusZoom_Adapters~StaticJSON\n * @see module:LocusZoom_Adapters~StaticSource\n */\nregistry.add('StaticJSON', adapters.StaticSource);\n\n/**\n * Backwards-compatible alias for LDServer\n * @public\n * @name module:LocusZoom_Adapters~LDLZ2\n * @see module:LocusZoom_Adapters~LDServer\n */\nregistry.add('LDLZ2', adapters.LDServer);\n\n\nexport default registry;\n","const __WEBPACK_NAMESPACE_OBJECT__ = d3;","/**\n * Available statuses that individual elements can have. Each status is described by\n * a verb and an adjective. Verbs are used to generate data layer\n * methods for updating the status on one or more elements. Adjectives are used in class\n * names and applied or removed from elements to have a visual representation of the status,\n * as well as used as keys in the state for tracking which elements are in which status(es)\n * @static\n * @type {{verbs: String[], adjectives: String[]}}\n * @private\n */\nexport const STATUSES = {\n verbs: ['highlight', 'select', 'fade', 'hide'],\n adjectives: ['highlighted', 'selected', 'faded', 'hidden'],\n};\n","/**\n * Transformation functions: used to transform a raw data value. For example, a template or axis label\n * can convert from pvalue to -log10pvalue by specifying the following field name (the `|funcname` syntax\n * indicates applying a function):\n *\n * `{{assoc:pvalue|neglog10}}`\n *\n * Transforms can also be chained so that several are used in order from left to right:\n * `{{log_pvalue|logtoscinotation|htmlescape}}`\n *\n * Most parts of LocusZoom that rely on being given a field name (or value) can be used this way: axis labels, position,\n * match/filter logic, tooltip HTML template, etc. If your use case is not working with filters, please file a\n * bug report!\n *\n * NOTE: for best results, don't specify filters in the `fields` array of a data layer- only specify them where the\n * transformed value will be used.\n * @module LocusZoom_TransformationFunctions\n */\n\n/**\n * Return the log10 of a value. Can be applied several times in a row for, eg, loglog plots.\n * @param {number} value\n * @return {null|number}\n */\nexport function log10 (value) {\n if (isNaN(value) || value <= 0) {\n return null;\n }\n return Math.log(value) / Math.LN10;\n}\n\n/**\n * Return the -log (base 10), a common means of representing pvalues in locuszoom plots\n * @param {number} value\n * @return {number}\n */\nexport function neglog10 (value) {\n if (isNaN(value) || value <= 0) {\n return null;\n }\n return -Math.log(value) / Math.LN10;\n}\n\n/**\n * Convert a number from logarithm to scientific notation. Useful for, eg, a datasource that returns -log(p) by default\n * @param {number} value\n * @return {string}\n */\nexport function logtoscinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '1';\n }\n const exp = Math.ceil(value);\n const diff = exp - value;\n const base = Math.pow(10, diff);\n if (exp === 1) {\n return (base / 10).toFixed(4);\n } else if (exp === 2) {\n return (base / 100).toFixed(3);\n } else {\n return `${base.toFixed(2)} × 10^-${exp}`;\n }\n}\n\n/**\n * Represent a number in scientific notation\n * @param {Number} value\n * @returns {String}\n */\nexport function scinotation (value) {\n if (isNaN(value)) {\n return 'NaN';\n }\n if (value === 0) {\n return '0';\n }\n\n const abs = Math.abs(value);\n let log;\n if (abs > 1) {\n log = Math.ceil(Math.log(abs) / Math.LN10);\n } else { // 0...1\n log = Math.floor(Math.log(abs) / Math.LN10);\n }\n if (Math.abs(log) <= 3) {\n return value.toFixed(3);\n } else {\n return value.toExponential(2).replace('+', '').replace('e', ' × 10^');\n }\n}\n\n/**\n * HTML-escape user entered values for use in constructed HTML fragments\n *\n * For example, this filter can be used on tooltips with custom HTML display. This protects against some forms of\n * XSS injection when plotting user-provided data, as well as display artifacts from field values with HTML symbols\n * such as `<` or `>`.\n * @param {String} value HTML-escape the provided value\n * @return {string}\n */\nexport function htmlescape (value) {\n if (!value) {\n return '';\n }\n value = `${value}`;\n\n return value.replace(/['\"<>&`]/g, function (s) {\n switch (s) {\n case \"'\":\n return ''';\n case '\"':\n return '"';\n case '<':\n return '<';\n case '>':\n return '>';\n case '&':\n return '&';\n case '`':\n return '`';\n }\n });\n}\n\n/**\n * Return true if the value is numeric (including 0)\n *\n * This is useful in template code, where we might wish to hide a field that is absent, but show numeric values even if they are 0\n * Eg, `{{#if value|is_numeric}}...{{/if}}\n *\n * @param {Number} value\n * @return {boolean}\n */\nexport function is_numeric(value) {\n return typeof value === 'number';\n}\n\n/**\n * URL-encode the provided text, eg for constructing hyperlinks\n * @param {String} value\n * @return {string}\n */\nexport function urlencode (value) {\n return encodeURIComponent(value);\n}\n","import {RegistryBase} from './base';\nimport * as transforms from '../helpers/transforms';\n\n/**\n * Registry of transformation functions that may be applied to template values to control how values are rendered.\n * Provides syntactic sugar atop a standard registry.\n * @public\n * @extends module:registry/base:RegistryBase\n * @inheritDoc\n */\nclass TransformationFunctionsRegistry extends RegistryBase {\n /**\n * Helper function that turns a sequence of function names into a single callable\n * @param template_string\n * @return {function(*=): *}\n * @private\n */\n _collectTransforms(template_string) {\n const funcs = template_string\n .match(/\\|([^|]+)/g)\n .map((item) => super.get(item.substring(1)));\n\n return (value) => {\n return funcs.reduce(\n (acc, func) => func(acc),\n value\n );\n };\n }\n\n /**\n * In templates, we often use a single concatenated string to ask for several transformation functions at once:\n * `value|func1|func2`\n * This class offers syntactical sugar to retrieve the entire sequence of transformations as a single callable\n * @param name\n */\n get(name) {\n if (!name) {\n // This function is sometimes called with no value, and the expected behavior is to return null instead of\n // a callable\n return null;\n }\n if (name.substring(0, 1) === '|') {\n // Legacy artifact of how this function is called- if a pipe is present, this is the template string\n // (`|func1|func2...`), rather than any one single transformation function.\n // A sequence of transformation functions is expected\n return this._collectTransforms(name);\n } else {\n // If not a template string, then user is asking for an item by name directly\n return super.get(name);\n }\n }\n}\n\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided transformation functions, which\n * can be used to modify a value in the input data in a predefined way. For example, these can be used to let APIs\n * that return p_values work with plots that display -log10(p)\n * @alias module:LocusZoom~TransformationFunctions\n * @type {TransformationFunctionsRegistry}\n */\nconst registry = new TransformationFunctionsRegistry();\nfor (let [name, type] of Object.entries(transforms)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n// Export helper class for unit testing\nexport { TransformationFunctionsRegistry as _TransformationFunctions };\n","import transforms from '../registry/transforms';\n\n/**\n * Represents an addressable unit of data from a namespaced datasource, subject to specified value transformations.\n *\n * When used by a data layer, fields will automatically be re-fetched from the appropriate data source whenever the\n * state of a plot fetches, eg pan or zoom operations that would affect what data is displayed.\n *\n * @private\n * @class\n * @param {String} field A string representing the namespace of the datasource, the name of the desired field to fetch\n * from that datasource, and arbitrarily many transformations to apply to the value. The namespace and\n * transformation(s) are optional and information is delimited according to the general syntax\n * `[namespace:]name[|transformation][|transformation]`. For example, `association:pvalue|neglog10`\n */\nclass Field {\n constructor(field) {\n const parts = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/.exec(field);\n /** @member {String} */\n this.full_name = field;\n /** @member {String} */\n this.namespace = parts[1] || null;\n /** @member {String} */\n this.name = parts[2] || null;\n /** @member {Array} */\n this.transformations = [];\n\n if (typeof parts[3] == 'string' && parts[3].length > 1) {\n this.transformations = parts[3].substring(1).split('|');\n this.transformations.forEach((transform, i) => this.transformations[i] = transforms.get(transform));\n }\n }\n\n _applyTransformations(val) {\n this.transformations.forEach(function(transform) {\n val = transform(val);\n });\n return val;\n }\n\n /**\n * Resolve the field for a given data element.\n * First look for a full match with transformations already applied by the data requester.\n * Otherwise prefer a namespace match and fall back to just a name match, applying transformations on the fly.\n * @param {Object} data Returned data/fields into for this element\n * @param {Object} [extra] User-applied annotations for this point (info not provided by the server that we want\n * to preserve across re-renders). Example usage: \"should_show_label\"\n * @returns {*}\n */\n resolve(data, extra) {\n if (typeof data[this.full_name] == 'undefined') { // Check for cached result\n let val = null;\n if (typeof (data[`${this.namespace}:${this.name}`]) != 'undefined') { // Fallback: value sans transforms\n val = data[`${this.namespace}:${this.name}`];\n } else if (typeof data[this.name] != 'undefined') { // Fallback: value present without namespace\n val = data[this.name];\n } else if (extra && typeof extra[this.full_name] != 'undefined') { // Fallback: check annotations\n val = extra[this.full_name];\n } // We should really warn if no value found, but many bad layouts exist and this could break compatibility\n data[this.full_name] = this._applyTransformations(val);\n }\n return data[this.full_name];\n }\n}\n\nexport {Field as default};\n","/**\n * Simplified JSONPath implementation\n *\n * This is designed to make it easier to modify part of a LocusZoom layout, using a syntax based on intent\n * (\"modify association panels\") rather than hard-coded assumptions (\"modify the first button, and gosh I hope the order doesn't change\")\n *\n * This DOES NOT support the full JSONPath specification. Notable limitations:\n * - Arrays can only be indexed by filter expression, not by number (can't ask for \"array item 1\")\n * - Filter expressions support only exact match, `field === value`. There is no support for \"and\" statements or\n * arbitrary JS expressions beyond a single exact comparison. (the parser may be improved in the future if use cases emerge)\n *\n * @module\n * @private\n */\n\nconst ATTR_REGEX = /^(\\*|[\\w]+)/; // attribute names can be wildcard or valid variable names\nconst EXPR_REGEX = /^\\[\\?\\(@((?:\\.[\\w]+)+) *===? *([0-9.eE-]+|\"[^\"]*\"|'[^']*')\\)\\]/; // Arrays can be indexed using filter expressions like `[?(@.id === value)]` where value is a number or a single-or-double quoted string\n\nfunction get_next_token(q) {\n // This just grabs everything that looks good.\n // The caller should check that the remaining query is valid.\n if (q.substr(0, 2) === '..') {\n if (q[2] === '[') {\n return {\n text: '..',\n attr: '*',\n depth: '..',\n };\n }\n const m = ATTR_REGEX.exec(q.substr(2));\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as dotdot_attr.`;\n }\n return {\n text: `..${m[0]}`,\n attr: m[1],\n depth: '..',\n };\n } else if (q[0] === '.') {\n const m = ATTR_REGEX.exec(q.substr(1));\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as dot_attr.`;\n }\n return {\n text: `.${m[0]}`,\n attr: m[1],\n depth: '.',\n };\n } else if (q[0] === '[') {\n const m = EXPR_REGEX.exec(q);\n if (!m) {\n throw `Cannot parse ${JSON.stringify(q)} as expr.`;\n }\n let value;\n try {\n // Parse strings and numbers\n value = JSON.parse(m[2]);\n } catch (e) {\n // Handle single-quoted strings\n value = JSON.parse(m[2].replace(/^'|'$/g, '\"'));\n }\n\n return {\n text: m[0],\n attrs: m[1].substr(1).split('.'),\n value,\n };\n } else {\n throw `The query ${JSON.stringify(q)} doesn't look valid.`;\n }\n}\n\nfunction normalize_query(q) {\n // Normalize the start of the query so that it's just a bunch of selectors one-after-another.\n // Otherwise the first selector is a little different than the others.\n if (!q) {\n return '';\n }\n if (!['$', '['].includes(q[0])) {\n q = `$.${ q}`;\n } // It starts with a dotless attr, so prepend the implied `$.`.\n if (q[0] === '$') {\n q = q.substr(1);\n } // strip the leading $\n return q;\n}\n\nfunction tokenize (q) {\n q = normalize_query(q);\n let selectors = [];\n while (q.length) {\n const selector = get_next_token(q);\n q = q.substr(selector.text.length);\n selectors.push(selector);\n }\n return selectors;\n}\n\n/**\n * Fetch the attribute from a dotted path inside a nested object, eg `extract_path({k:['a','b']}, ['k', 1])` would retrieve `'b'`\n *\n * This function returns a three item array `[parent, key, object]`. This is done to support mutating the value, which requires access to the parent.\n *\n * @param obj\n * @param path\n * @returns {Array}\n */\nfunction get_item_at_deep_path(obj, path) {\n let parent;\n for (let key of path) {\n parent = obj;\n obj = obj[key];\n }\n return [parent, path[path.length - 1], obj];\n}\n\nfunction tokens_to_keys(data, selectors) {\n // Resolve the jsonpath query into full path specifier keys in the object, eg\n // `$..data_layers[?(@.tag === 'association)].color\n // would become\n // [\"panels\", 0, \"data_layers\", 1, \"color\"]\n if (!selectors.length) {\n return [[]];\n }\n const sel = selectors[0];\n const remaining_selectors = selectors.slice(1);\n let paths = [];\n\n if (sel.attr && sel.depth === '.' && sel.attr !== '*') { // .attr\n const d = data[sel.attr];\n if (selectors.length === 1) {\n if (d !== undefined) {\n paths.push([sel.attr]);\n }\n } else {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [sel.attr].concat(p)));\n }\n } else if (sel.attr && sel.depth === '.' && sel.attr === '*') { // .*\n for (let [k, d] of Object.entries(data)) {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n } else if (sel.attr && sel.depth === '..') { // ..\n // If `sel.attr` matches, recurse with that match.\n // And also recurse on every value using unchanged selectors.\n // I bet `..*..*` duplicates results, so don't do it please.\n if (typeof data === 'object' && data !== null) {\n if (sel.attr !== '*' && sel.attr in data) { // Exact match!\n paths.push(...tokens_to_keys(data[sel.attr], remaining_selectors).map((p) => [sel.attr].concat(p)));\n }\n for (let [k, d] of Object.entries(data)) {\n paths.push(...tokens_to_keys(d, selectors).map((p) => [k].concat(p))); // No match, just recurse\n if (sel.attr === '*') { // Wildcard match\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n }\n }\n } else if (sel.attrs) { // [?(@.attr===value)]\n for (let [k, d] of Object.entries(data)) {\n const [_, __, subject] = get_item_at_deep_path(d, sel.attrs);\n if (subject === sel.value) {\n paths.push(...tokens_to_keys(d, remaining_selectors).map((p) => [k].concat(p)));\n }\n }\n }\n\n const uniqPaths = uniqBy(paths, JSON.stringify); // dedup\n uniqPaths.sort((a, b) => b.length - a.length || JSON.stringify(a).localeCompare(JSON.stringify(b))); // sort longest-to-shortest, breaking ties lexicographically\n return uniqPaths;\n}\n\nfunction uniqBy(arr, key) {\n // Sometimes, the process of resolving paths to selectors returns duplicate results. This returns only the unique paths.\n return [...new Map(arr.map((elem) => [key(elem), elem])).values()];\n}\n\nfunction get_items_from_tokens(data, selectors) {\n let items = [];\n for (let path of tokens_to_keys(data, selectors)) {\n items.push(get_item_at_deep_path(data, path));\n }\n return items;\n}\n\n/**\n * Perform a query, and return the item + its parent context\n * @param data\n * @param query\n * @returns {Array}\n * @private\n */\nfunction _query(data, query) {\n const tokens = tokenize(query);\n\n const matches = get_items_from_tokens(data, tokens);\n if (!matches.length) {\n console.warn(`No items matched the specified query: '${query}'`);\n }\n return matches;\n}\n\n/**\n * Fetch the value(s) for each possible match for a given query. Returns only the item values.\n * @param {object} data The data object to query\n * @param {string} query A JSONPath-compliant query string\n * @returns {Array}\n */\nfunction query(data, query) {\n return _query(data, query).map((item) => item[2]);\n}\n\n/**\n * Modify the value(s) for each possible match for a given jsonpath query. Returns the new item values.\n * @param {object} data The data object to query\n * @param {string} query A JSONPath-compliant query string\n * @param {function|*} value_or_callback The new value for the specified field. Mutations will only be applied\n * after the keys are resolved; this prevents infinite recursion, but could invalidate some matches\n * (if the mutation removed the expected key).\n */\nfunction mutate(data, query, value_or_callback) {\n const matches_in_context = _query(data, query);\n return matches_in_context.map(([parent, key, old_value]) => {\n const new_value = (typeof value_or_callback === 'function') ? value_or_callback(old_value) : value_or_callback;\n parent[key] = new_value;\n return new_value;\n });\n}\n\nexport {mutate, query};\n","/**\n * Utilities for modifying or working with layout objects\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport {mutate, query} from './jsonpath';\n\nconst sqrt3 = Math.sqrt(3);\n// D3 v5 does not provide a triangle down symbol shape, but it is very useful for showing direction of effect.\n// Modified from https://github.com/d3/d3-shape/blob/master/src/symbol/triangle.js\nconst triangledown = {\n draw(context, size) {\n const y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, -y * 2);\n context.lineTo(-sqrt3 * y, y);\n context.lineTo(sqrt3 * y, y);\n context.closePath();\n },\n};\n\n/**\n * Apply namespaces to layout, recursively\n * @private\n */\nfunction applyNamespaces(element, namespace, default_namespace) {\n if (namespace) {\n if (typeof namespace == 'string') {\n namespace = { default: namespace };\n }\n } else {\n namespace = { default: '' };\n }\n if (typeof element == 'string') {\n const re = /\\{\\{namespace(\\[[A-Za-z_0-9]+\\]|)\\}\\}/g;\n let match, base, key, resolved_namespace;\n const replace = [];\n while ((match = re.exec(element)) !== null) {\n base = match[0];\n key = match[1].length ? match[1].replace(/(\\[|\\])/g, '') : null;\n resolved_namespace = default_namespace;\n if (namespace != null && typeof namespace == 'object' && typeof namespace[key] != 'undefined') {\n resolved_namespace = namespace[key] + (namespace[key].length ? ':' : '');\n }\n replace.push({ base: base, namespace: resolved_namespace });\n }\n for (let r in replace) {\n element = element.replace(replace[r].base, replace[r].namespace);\n }\n } else if (typeof element == 'object' && element != null) {\n if (typeof element.namespace != 'undefined') {\n const merge_namespace = (typeof element.namespace == 'string') ? { default: element.namespace } : element.namespace;\n namespace = merge(namespace, merge_namespace);\n }\n let namespaced_element, namespaced_property;\n for (let property in element) {\n if (property === 'namespace') {\n continue;\n }\n namespaced_element = applyNamespaces(element[property], namespace, default_namespace);\n namespaced_property = applyNamespaces(property, namespace, default_namespace);\n if (property !== namespaced_property) {\n delete element[property];\n }\n element[namespaced_property] = namespaced_element;\n }\n }\n return element;\n}\n\n/**\n * A helper method used for merging two objects. If a key is present in both, takes the value from the first object.\n * Values from `default_layout` will be cleanly copied over, ensuring no references or shared state.\n *\n * Frequently used for preparing custom layouts. Both objects should be JSON-serializable.\n *\n * @alias LayoutRegistry.merge\n * @param {object} custom_layout An object containing configuration parameters that override or add to defaults\n * @param {object} default_layout An object containing default settings.\n * @returns {object} The custom layout is modified in place and also returned from this method.\n */\nfunction merge(custom_layout, default_layout) {\n if (typeof custom_layout !== 'object' || typeof default_layout !== 'object') {\n throw new Error(`LocusZoom.Layouts.merge only accepts two layout objects; ${typeof custom_layout}, ${typeof default_layout} given`);\n }\n for (let property in default_layout) {\n if (!Object.prototype.hasOwnProperty.call(default_layout, property)) {\n continue;\n }\n // Get types for comparison. Treat nulls in the custom layout as undefined for simplicity.\n // (javascript treats nulls as \"object\" when we just want to overwrite them as if they're undefined)\n // Also separate arrays from objects as a discrete type.\n let custom_type = custom_layout[property] === null ? 'undefined' : typeof custom_layout[property];\n let default_type = typeof default_layout[property];\n if (custom_type === 'object' && Array.isArray(custom_layout[property])) {\n custom_type = 'array';\n }\n if (default_type === 'object' && Array.isArray(default_layout[property])) {\n default_type = 'array';\n }\n // Unsupported property types: throw an exception\n if (custom_type === 'function' || default_type === 'function') {\n throw new Error('LocusZoom.Layouts.merge encountered an unsupported property type');\n }\n // Undefined custom value: pull the default value\n if (custom_type === 'undefined') {\n custom_layout[property] = deepCopy(default_layout[property]);\n continue;\n }\n // Both values are objects: merge recursively\n if (custom_type === 'object' && default_type === 'object') {\n custom_layout[property] = merge(custom_layout[property], default_layout[property]);\n continue;\n }\n }\n return custom_layout;\n}\n\nfunction deepCopy(item) {\n return JSON.parse(JSON.stringify(item));\n}\n\n/**\n * Convert name to symbol\n * Layout objects accept symbol names as strings (circle, triangle, etc). Convert to symbol objects.\n * @return {object|null} An object that implements a draw method (eg d3-shape symbols or extra LZ items)\n */\nfunction nameToSymbol(shape) {\n if (!shape) {\n return null;\n }\n if (shape === 'triangledown') {\n // D3 does not provide this symbol natively\n return triangledown;\n }\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const factory_name = `symbol${shape.charAt(0).toUpperCase() + shape.slice(1)}`;\n return d3[factory_name] || null;\n}\n\n/**\n * A utility helper for customizing one part of a pre-made layout. Whenever a primitive value is found (eg string),\n * replaces *exact match*\n *\n * This method works by comparing whether strings are a match. As a result, the \"old\" and \"new\" names must match\n * whatever namespacing is used in the input layout.\n * Note: this utility *can* replace values with filters, but will not do so by default.\n *\n * @alias LayoutRegistry.renameField\n *\n * @param {object} layout The layout object to be transformed.\n * @param {string} old_name The old field name that will be replaced\n * @param {string} new_name The new field name that will be substituted in\n * @param {boolean} [warn_transforms=true] Sometimes, a field name is used with transforms appended, eg `label|htmlescape`.\n * In some cases a rename could change the meaning of the field, and by default this method will print a warning to\n * the console, encouraging the developer to check the relevant usages. This warning can be silenced via an optional function argument.\n */\nfunction renameField(layout, old_name, new_name, warn_transforms = true) {\n const this_type = typeof layout;\n // Handle nested types by recursion (in which case, `layout` may be something other than an object)\n if (Array.isArray(layout)) {\n return layout.map((item) => renameField(item, old_name, new_name, warn_transforms));\n } else if (this_type === 'object' && layout !== null) {\n return Object.keys(layout).reduce(\n (acc, key) => {\n acc[key] = renameField(layout[key], old_name, new_name, warn_transforms);\n return acc;\n }, {}\n );\n } else if (this_type !== 'string') {\n // Field names are always strings. If the value isn't a string, don't even try to change it.\n return layout;\n } else {\n // If we encounter a field we are trying to rename, then do so!\n // Rules:\n // 1. Try to avoid renaming part of a field, by checking token boundaries (field1 should not rename field1_displayvalue)\n // 2. Warn the user if filter functions are being used with the specified field, so they can audit for changes in meaning\n const escaped = old_name.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n if (warn_transforms) {\n // Warn the user that they might be renaming, eg, `pvalue|neg_log` to `log_pvalue|neg_log`. Let them decide\n // whether the new field name has a meaning that is compatible with the specified transforms.\n const filter_regex = new RegExp(`${escaped}\\\\|\\\\w+`, 'g');\n const filter_matches = (layout.match(filter_regex) || []);\n filter_matches.forEach((match_val) => console.warn(`renameFields is renaming a field that uses transform functions: was '${match_val}' . Verify that these transforms are still appropriate.`));\n }\n\n // Find and replace any substring, so long as it is at the end of a valid token\n const regex = new RegExp(`${escaped}(?!\\\\w+)`, 'g');\n return layout.replace(regex, new_name);\n }\n}\n\n/**\n * Modify any and all attributes at the specified path in the object\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which field(s) to change.\n * The callback will be applied to ALL matching selectors\n * (see Interactivity guide for syntax and limitations)\n * @param {*|function} value_or_callable The new value, or a function that receives the old value and returns a new one\n * @returns {Array}\n * @alias LayoutRegistry.mutate_attrs\n */\nfunction mutate_attrs(layout, selector, value_or_callable) {\n return mutate(\n layout,\n selector,\n value_or_callable\n );\n}\n\n/**\n * Query any and all attributes at the specified path in the object.\n * This is mostly only useful for debugging, to verify that a particular selector matches the intended field.\n * @param {object} layout The layout object to be mutated\n * @param {string} selector The JSONPath-compliant selector string specifying which values to return. (see Interactivity guide for limits)\n * @returns {Array}\n * @alias LayoutRegistry.query_attrs\n */\nfunction query_attrs(layout, selector) {\n return query(layout, selector);\n}\n\nexport { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, renameField };\n","import { TRANSFORMS } from '../registry';\n\n/**\n * The Requester manages fetching of data across multiple data sources. It is used internally by LocusZoom data layers.\n * It passes state information and ensures that data is formatted in the manner expected by the plot.\n *\n * This object is not part of the public interface. It should almost **never** be replaced or modified directly.\n *\n * It is also responsible for constructing a \"chain\" of dependent requests, by requesting each datasource\n * sequentially in the order specified in the datalayer `fields` array. Data sources are only chained within a\n * data layer, and only if that layer requests more than one source of data.\n * @param {DataSources} sources A set of data sources used specifically by this plot instance\n * @private\n */\nclass Requester {\n constructor(sources) {\n this._sources = sources;\n }\n\n __split_requests(fields) {\n // Given a fields array, return an object specifying what datasource names the data layer should make requests\n // to, and how to handle the returned data\n var requests = {};\n // Regular expression finds namespace:field|trans\n var re = /^(?:([^:]+):)?([^:|]*)(\\|.+)*$/;\n fields.forEach(function(raw) {\n var parts = re.exec(raw);\n var ns = parts[1] || 'base';\n var field = parts[2];\n var trans = TRANSFORMS.get(parts[3]);\n if (typeof requests[ns] == 'undefined') {\n requests[ns] = {outnames:[], fields:[], trans:[]};\n }\n requests[ns].outnames.push(raw);\n requests[ns].fields.push(field);\n requests[ns].trans.push(trans);\n });\n return requests;\n }\n\n /**\n * Fetch data, and create a chain that only connects two data sources if they depend on each other\n * @param {Object} state The current \"state\" of the plot, such as chromosome and start/end positions\n * @param {String[]} fields The list of data fields specified in the `layout` for a specific data layer\n * @returns {Promise}\n */\n getData(state, fields) {\n var requests = this.__split_requests(fields);\n // Create an array of functions that, when called, will trigger the request to the specified datasource\n var request_handles = Object.keys(requests).map((key) => {\n if (!this._sources.get(key)) {\n throw new Error(`Datasource for namespace ${key} not found`);\n }\n return this._sources.get(key).getData(\n state,\n requests[key].fields,\n requests[key].outnames,\n requests[key].trans\n );\n });\n //assume the fields are requested in dependent order\n //TODO: better manage dependencies\n var ret = Promise.resolve({header:{}, body: [], discrete: {}});\n for (var i = 0; i < request_handles.length; i++) {\n // If a single datalayer uses multiple sources, perform the next request when the previous one completes\n ret = ret.then(request_handles[i]);\n }\n return ret;\n }\n}\n\n\nexport default Requester;\n","/**\n * @module\n * @private\n */\n// FIXME: A place for code that used to live under the `LocusZoom` namespace\n// Eventually this should be moved into classes or some other mechanism for code sharing. No external uses should\n// depend on any items in this module.\n\nimport * as d3 from 'd3';\n\n/**\n * Generate a curtain object for a plot, panel, or any other subdivision of a layout\n * The panel curtain, like the plot curtain is an HTML overlay that obscures the entire panel. It can be styled\n * arbitrarily and display arbitrary messages. It is useful for reporting error messages visually to an end user\n * when the error renders the panel unusable.\n * TODO: Improve type doc here\n * @returns {object}\n */\nfunction generateCurtain() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n hide_delay: null,\n\n /**\n * Generate the curtain. Any content (string) argument passed will be displayed in the curtain as raw HTML.\n * CSS (object) can be passed which will apply styles to the curtain and its content.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n show: (content, css) => {\n if (!this.curtain.showing) {\n this.curtain.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-curtain')\n .attr('id', `${this.id}.curtain`);\n this.curtain.content_selector = this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-content');\n this.curtain.selector.append('div')\n .attr('class', 'lz-curtain-dismiss').html('Dismiss')\n .on('click', () => this.curtain.hide());\n this.curtain.showing = true;\n }\n return this.curtain.update(content, css);\n },\n\n /**\n * Update the content and css of the curtain that's currently being shown. This method also adjusts the size\n * and positioning of the curtain to ensure it still covers the entire panel with no overlap.\n * @param {string} content Content to be displayed on the curtain (as raw HTML)\n * @param {object} css Apply the specified styles to the curtain and its contents\n */\n update: (content, css) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n clearTimeout(this.curtain.hide_delay);\n // Apply CSS if provided\n if (typeof css == 'object') {\n applyStyles(this.curtain.selector, css);\n }\n // Update size and position\n const page_origin = this._getPageOrigin();\n\n // Panel layouts have a height; plot layouts don't\n const height = this.layout.height || this._total_height;\n this.curtain.selector\n .style('top', `${page_origin.y}px`)\n .style('left', `${page_origin.x}px`)\n .style('width', `${this.parent_plot.layout.width}px`)\n .style('height', `${height}px`);\n this.curtain.content_selector\n .style('max-width', `${this.parent_plot.layout.width - 40}px`)\n .style('max-height', `${height - 40}px`);\n // Apply content if provided\n if (typeof content == 'string') {\n this.curtain.content_selector.html(content);\n }\n return this.curtain;\n },\n\n /**\n * Remove the curtain\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.curtain.showing) {\n return this.curtain;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.curtain.hide_delay);\n this.curtain.hide_delay = setTimeout(this.curtain.hide, delay);\n return this.curtain;\n }\n // Remove curtain\n this.curtain.selector.remove();\n this.curtain.selector = null;\n this.curtain.content_selector = null;\n this.curtain.showing = false;\n return this.curtain;\n },\n };\n}\n\n/**\n * Generate a loader object for a plot, panel, or any other subdivision of a layout\n *\n * The panel loader is a small HTML overlay that appears in the lower left corner of the panel. It cannot be styled\n * arbitrarily, but can show a custom message and show a minimalist loading bar that can be updated to specific\n * completion percentages or be animated.\n * TODO Improve type documentation\n * @returns {object}\n */\nfunction generateLoader() {\n return {\n showing: false,\n selector: null,\n content_selector: null,\n progress_selector: null,\n cancel_selector: null,\n\n /**\n * Show a loading indicator\n * @param {string} [content='Loading...'] Loading message (displayed as raw HTML)\n */\n show: (content) => {\n // Generate loader\n if (!this.loader.showing) {\n this.loader.selector = d3.select(this.parent_plot.svg.node().parentNode).insert('div')\n .attr('class', 'lz-loader')\n .attr('id', `${this.id}.loader`);\n this.loader.content_selector = this.loader.selector.append('div')\n .attr('class', 'lz-loader-content');\n this.loader.progress_selector = this.loader.selector\n .append('div')\n .attr('class', 'lz-loader-progress-container')\n .append('div')\n .attr('class', 'lz-loader-progress');\n\n this.loader.showing = true;\n if (typeof content == 'undefined') {\n content = 'Loading...';\n }\n }\n return this.loader.update(content);\n },\n\n /**\n * Update the currently displayed loader and ensure the new content is positioned correctly.\n * @param {string} content The text to display (as raw HTML). If not a string, will be ignored.\n * @param {number} [percent] A number from 1-100. If a value is specified, it will stop all animations\n * in progress.\n */\n update: (content, percent) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n clearTimeout(this.loader.hide_delay);\n // Apply content if provided\n if (typeof content == 'string') {\n this.loader.content_selector.html(content);\n }\n // Update size and position\n const padding = 6; // is there a better place to store/define this?\n const page_origin = this._getPageOrigin();\n const loader_boundrect = this.loader.selector.node().getBoundingClientRect();\n this.loader.selector\n .style('top', `${page_origin.y + this.layout.height - loader_boundrect.height - padding}px`)\n .style('left', `${page_origin.x + padding }px`);\n\n // Apply percent if provided\n if (typeof percent == 'number') {\n this.loader.progress_selector\n .style('width', `${Math.min(Math.max(percent, 1), 100)}%`);\n }\n return this.loader;\n },\n\n /**\n * Adds a class to the loading bar that makes it loop infinitely in a loading animation. Useful when exact\n * percent progress is not available.\n */\n animate: () => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', true);\n return this.loader;\n },\n\n /**\n * Sets the loading bar in the loader to percentage width equal to the percent (number) value passed. Percents\n * will automatically be limited to a range of 1 to 100. Will stop all animations in progress.\n */\n setPercentCompleted: (percent) => {\n this.loader.progress_selector.classed('lz-loader-progress-animated', false);\n return this.loader.update(null, percent);\n },\n\n /**\n * Remove the loader\n * @param {number} delay Time to wait (in ms)\n */\n hide: (delay) => {\n if (!this.loader.showing) {\n return this.loader;\n }\n // If a delay was passed then defer to a timeout\n if (typeof delay == 'number') {\n clearTimeout(this.loader.hide_delay);\n this.loader.hide_delay = setTimeout(this.loader.hide, delay);\n return this.loader;\n }\n // Remove loader\n this.loader.selector.remove();\n this.loader.selector = null;\n this.loader.content_selector = null;\n this.loader.progress_selector = null;\n this.loader.cancel_selector = null;\n this.loader.showing = false;\n return this.loader;\n },\n };\n}\n\n/**\n * Modern d3 removed the ability to set many styles at once (object syntax). This is a helper so that layouts with\n * config-objects can set styles all at once\n * @private\n * @param {d3.selection} selection\n * @param {Object} styles\n */\nfunction applyStyles(selection, styles) {\n styles = styles || {};\n for (let [prop, value] of Object.entries(styles)) {\n selection.style(prop, value);\n }\n}\n\n/**\n * Prevent a UI function from being called more than once in a given interval. This allows, eg, search boxes to delay\n * expensive operations until the user is done typing\n * @param {function} func The function to debounce. Returns a wrapper.\n * @param {number} delay Time to wait after last call (in ms)\n */\nfunction debounce(func, delay = 500) {\n let timer;\n return () => {\n clearTimeout(timer);\n timer = setTimeout(\n () => func.apply(this, arguments),\n delay\n );\n };\n}\n\nexport { applyStyles, debounce, generateCurtain, generateLoader };\n","/**\n * Interactive toolbar widgets that allow users to control the plot. These can be used to modify element display:\n * adding contextual information, rearranging/removing panels, or toggling between sets of rendering options like\n * different LD populations.\n * @module LocusZoom_Widgets\n */\nimport * as d3 from 'd3';\n\nimport {positionIntToString} from '../../helpers/display';\nimport {applyStyles, debounce} from '../../helpers/common';\nimport {deepCopy} from '../../helpers/layouts';\n\n\n/**\n *\n * A widget is an empty div rendered on a toolbar that can display custom\n * html of user interface elements.\n */\nclass BaseWidget {\n /**\n * @param {('left'|'right')} [layout.position='left'] Whether to float the widget left or right.\n * @param {('start'|'middle'|'end')} [layout.group_position] Buttons can optionally be gathered into a visually\n * distinctive group whose elements are closer together. If a button is identified as the start or end of a group,\n * it will be drawn with rounded corners and an extra margin of spacing from any button not part of the group.\n * For example, the region_nav_plot toolbar is a defined as a group.\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} [layout.color='gray'] Color scheme for the\n * widget. Applies to buttons and menus.\n * @param [layout.style] CSS styles that will be applied to the widget\n * @param {Toolbar} parent The toolbar that contains this widget\n */\n constructor(layout, parent) {\n /** @member {Object} */\n this.layout = layout || {};\n if (!this.layout.color) {\n this.layout.color = 'gray';\n }\n\n /** @member {Toolbar|*} */\n this.parent = parent || null;\n /**\n * Some widgets are attached to a panel, rather than directly to a plot\n * @member {Panel|null}\n */\n this.parent_panel = null;\n /** @member {Plot} */\n this.parent_plot = null;\n /**\n * This is a reference to either the panel or the plot, depending on what the toolbar is\n * tied to. Useful when absolutely positioning toolbar widgets relative to their SVG anchor.\n * @member {Plot|Panel}\n */\n this.parent_svg = null;\n if (this.parent) {\n if (this.parent.type === 'panel') {\n this.parent_panel = this.parent.parent;\n this.parent_plot = this.parent.parent.parent;\n this.parent_svg = this.parent_panel;\n } else {\n this.parent_plot = this.parent.parent;\n this.parent_svg = this.parent_plot;\n }\n }\n /** @member {d3.selection} */\n this.selector = null;\n /**\n * If this is an interactive widget, it will contain a button or menu instance that handles the interactivity.\n * There is a 1-to-1 relationship of toolbar widget to button\n * @member {null|Button}\n */\n this.button = null;\n /**\n * If any single widget is marked persistent, it will bubble up to prevent automatic hide behavior on a\n * widget's parent toolbar. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n if (!this.layout.position) {\n this.layout.position = 'left';\n }\n }\n\n /**\n * Perform all rendering of widget, including toggling visibility to true. Will initialize and create SVG element\n * if necessary, as well as updating with new data and performing layout actions.\n */\n show() {\n if (!this.parent || !this.parent.selector) {\n return;\n }\n if (!this.selector) {\n const group_position = (['start', 'middle', 'end'].includes(this.layout.group_position) ? ` lz-toolbar-group-${this.layout.group_position}` : '');\n this.selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-${this.layout.position}${group_position}`);\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n if (typeof this.initialize == 'function') {\n this.initialize();\n }\n }\n if (this.button && this.button.status === 'highlighted') {\n this.button.menu.show();\n }\n this.selector.style('visibility', 'visible');\n this.update();\n return this.position();\n }\n\n /**\n * Update the toolbar widget with any new data or plot state as appropriate. This method performs all\n * necessary rendering steps.\n */\n update() { /* stub */\n }\n\n /**\n * Place the widget correctly in the plot\n * @returns {BaseWidget}\n */\n position() {\n if (this.button) {\n this.button.menu.position();\n }\n return this;\n }\n\n /**\n * Determine whether the widget should persist (will bubble up to parent toolbar)\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n return !!(this.button && this.button.persist);\n }\n\n /**\n * Toggle visibility to hidden, unless marked as persistent\n * @returns {BaseWidget}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n if (this.button) {\n this.button.menu.hide();\n }\n this.selector.style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove widget and button. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n if (this.button && this.button.menu) {\n this.button.menu.destroy();\n }\n this.selector.remove();\n this.selector = null;\n this.button = null;\n return this;\n }\n}\n\n/**\n * Plots and panels may have a \"toolbar\" element suited for showing HTML widgets that may be interactive.\n * When widgets need to incorporate a generic button, or additionally a button that generates a menu, this\n * class provides much of the necessary framework. This widget is rarely used directly; it is usually used as\n * part of the code for other widgets.\n * @alias module:LocusZoom_Widgets~_Button\n * @param {BaseWidget} parent\n */\nclass Button {\n constructor(parent) {\n if (!(parent instanceof BaseWidget)) {\n throw new Error('Unable to create toolbar widget button, invalid parent');\n }\n /** @member {BaseWidget} */\n this.parent = parent;\n /** @member {Panel} */\n this.parent_panel = this.parent.parent_panel;\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n /** @member {Plot|Panel} */\n this.parent_svg = this.parent.parent_svg;\n\n /** @member {Toolbar|null|*} */\n this.parent_toolbar = this.parent.parent;\n /** @member {d3.selection} */\n this.selector = null;\n\n /**\n * Tag to use for the button (default: a)\n * @member {String}\n */\n this.tag = 'a';\n\n /**\n * HTML for the button to show.\n * @protected\n * @member {String}\n */\n this.html = '';\n\n /**\n * Mouseover title text for the button to show\n * @protected\n * @member {String}\n */\n this.title = '';\n\n /**\n * Color of the button\n * @member {String}\n */\n this.color = 'gray';\n\n /**\n * Hash of arbitrary button styles to apply as {name: value} entries\n * @protected\n * @member {Object}\n */\n this.style = {};\n\n // Permanence\n /**\n * Track internal state on whether to keep showing the button/ menu contents at the moment\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n /**\n * Configuration when defining a button: track whether this widget should be allowed to keep open\n * menu/button contents in response to certain events\n * @protected\n * @member {Boolean}\n */\n this.permanent = false;\n\n /**\n * Button status (highlighted / disabled/ etc)\n * @protected\n * @member {String}\n */\n this.status = '';\n\n /**\n * Button Menu Object\n * The menu is an HTML overlay that can appear below a button. It can contain arbitrary HTML and\n * has logic to be automatically positioned and sized to behave more or less like a dropdown menu.\n * @member {Object}\n */\n this.menu = {\n outer_selector: null,\n inner_selector: null,\n scroll_position: 0,\n hidden: true,\n /**\n * Show the button menu, including setting up any DOM elements needed for first rendering\n */\n show: () => {\n if (!this.menu.outer_selector) {\n this.menu.outer_selector = d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', `lz-toolbar-menu lz-toolbar-menu-${this.color}`)\n .attr('id', `${this.parent_svg.getBaseId()}.toolbar.menu`);\n this.menu.inner_selector = this.menu.outer_selector.append('div')\n .attr('class', 'lz-toolbar-menu-content');\n this.menu.inner_selector.on('scroll', () => {\n this.menu.scroll_position = this.menu.inner_selector.node().scrollTop;\n });\n }\n this.menu.outer_selector.style('visibility', 'visible');\n this.menu.hidden = false;\n return this.menu.update();\n },\n /**\n * Update the rendering of the menu\n */\n update: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.populate(); // This function is stubbed for all buttons by default and custom implemented in widget definition\n if (this.menu.inner_selector) {\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n }\n return this.menu.position();\n },\n position: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n // Unset any explicitly defined outer selector height so that menus dynamically shrink if content is removed\n this.menu.outer_selector.style('height', null);\n const padding = 3;\n const scrollbar_padding = 20;\n const menu_height_padding = 14; // 14: 2x 6px padding, 2x 1px border\n const page_origin = this.parent_svg._getPageOrigin();\n const page_scroll_top = document.documentElement.scrollTop || document.body.scrollTop;\n const container_offset = this.parent_plot.getContainerOffset();\n const toolbar_client_rect = this.parent_toolbar.selector.node().getBoundingClientRect();\n const button_client_rect = this.selector.node().getBoundingClientRect();\n const menu_client_rect = this.menu.outer_selector.node().getBoundingClientRect();\n const total_content_height = this.menu.inner_selector.node().scrollHeight;\n let top;\n let left;\n if (this.parent_toolbar.type === 'panel') {\n top = (page_origin.y + toolbar_client_rect.height + (2 * padding));\n left = Math.max(page_origin.x + this.parent_plot.layout.width - menu_client_rect.width - padding, page_origin.x + padding);\n } else {\n top = button_client_rect.bottom + page_scroll_top + padding - container_offset.top;\n left = Math.max(button_client_rect.left + button_client_rect.width - menu_client_rect.width - container_offset.left, page_origin.x + padding);\n }\n const base_max_width = Math.max(this.parent_plot.layout.width - (2 * padding) - scrollbar_padding, scrollbar_padding);\n const container_max_width = base_max_width;\n const content_max_width = (base_max_width - (4 * padding));\n const base_max_height = Math.max(this.parent_svg.layout.height - (10 * padding) - menu_height_padding, menu_height_padding);\n const height = Math.min(total_content_height + menu_height_padding, base_max_height);\n this.menu.outer_selector\n .style('top', `${top}px`)\n .style('left', `${left}px`)\n .style('max-width', `${container_max_width}px`)\n .style('max-height', `${base_max_height}px`)\n .style('height', `${height}px`);\n this.menu.inner_selector\n .style('max-width', `${content_max_width}px`);\n this.menu.inner_selector.node().scrollTop = this.menu.scroll_position;\n return this.menu;\n },\n hide: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.outer_selector.style('visibility', 'hidden');\n this.menu.hidden = true;\n return this.menu;\n },\n destroy: () => {\n if (!this.menu.outer_selector) {\n return this.menu;\n }\n this.menu.inner_selector.remove();\n this.menu.outer_selector.remove();\n this.menu.inner_selector = null;\n this.menu.outer_selector = null;\n return this.menu;\n },\n /**\n * Internal method definition\n * By convention populate() does nothing and should be reimplemented with each toolbar button definition\n * Reimplement by way of Toolbar.BaseWidget.Button.menu.setPopulate to define the populate method and hook\n * up standard menu click-toggle behavior prototype.\n * @protected\n */\n populate: () => {\n throw new Error('Method must be implemented');\n },\n /**\n * Define how the menu is populated with items, and set up click and display properties as appropriate\n * @public\n */\n setPopulate: (menu_populate_function) => {\n if (typeof menu_populate_function == 'function') {\n this.menu.populate = menu_populate_function;\n this.setOnclick(() => {\n if (this.menu.hidden) {\n this.menu.show();\n this.highlight().update();\n this.persist = true;\n } else {\n this.menu.hide();\n this.highlight(false).update();\n if (!this.permanent) {\n this.persist = false;\n }\n }\n });\n } else {\n this.setOnclick();\n }\n return this;\n },\n };\n }\n\n /**\n * Set the color associated with this button\n * @param {('gray'|'red'|'orange'|'yellow'|'green'|'blue'|'purple')} color Any selection not in the preset list\n * will be replaced with gray.\n * @returns {Button}\n */\n setColor (color) {\n if (typeof color != 'undefined') {\n if (['gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple'].includes(color)) {\n this.color = color;\n } else {\n this.color = 'gray';\n }\n }\n return this;\n }\n\n /**\n * Allow code to change whether the button is allowed to be `permanent`\n * @param {boolean} bool\n * @returns {Button}\n */\n setPermanent (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n this.permanent = bool;\n if (this.permanent) {\n this.persist = true;\n }\n return this;\n }\n\n /**\n * Determine whether the button/menu contents should persist in response to a specific event\n * @returns {Boolean}\n */\n shouldPersist () {\n return this.permanent || this.persist;\n }\n\n /**\n * Set a collection of custom styles to be used by the button\n * @param {Object} style Hash of {name:value} entries\n * @returns {Button}\n */\n setStyle (style) {\n if (typeof style != 'undefined') {\n this.style = style;\n }\n return this;\n }\n\n /**\n * Method to generate a CSS class string\n * @returns {string}\n */\n getClass () {\n const group_position = (['start', 'middle', 'end'].includes(this.parent.layout.group_position) ? ` lz-toolbar-button-group-${this.parent.layout.group_position}` : '');\n return `lz-toolbar-button lz-toolbar-button-${this.color}${this.status ? `-${this.status}` : ''}${group_position}`;\n }\n\n /**\n * Change button state\n * @param {('highlighted'|'disabled'|'')} status\n */\n setStatus (status) {\n if (typeof status != 'undefined' && ['', 'highlighted', 'disabled'].includes(status)) {\n this.status = status;\n }\n return this.update();\n }\n\n /**\n * Toggle whether the button is highlighted\n * @param {boolean} bool If provided, explicitly set highlighted state\n * @returns {Button}\n */\n highlight (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('highlighted');\n } else if (this.status === 'highlighted') {\n return this.setStatus('');\n }\n return this;\n }\n\n /**\n * Toggle whether the button is disabled\n * @param {boolean} bool If provided, explicitly set disabled state\n * @returns {Button}\n */\n disable (bool) {\n if (typeof bool == 'undefined') {\n bool = true;\n } else {\n bool = Boolean(bool);\n }\n if (bool) {\n return this.setStatus('disabled');\n } else if (this.status === 'disabled') {\n return this.setStatus('');\n }\n return this;\n }\n\n // Mouse events\n /** @member {function} */\n onmouseover () {\n }\n setOnMouseover (onmouseover) {\n if (typeof onmouseover == 'function') {\n this.onmouseover = onmouseover;\n } else {\n this.onmouseover = function () {};\n }\n return this;\n }\n\n /** @member {function} */\n onmouseout () {\n }\n setOnMouseout (onmouseout) {\n if (typeof onmouseout == 'function') {\n this.onmouseout = onmouseout;\n } else {\n this.onmouseout = function () {};\n }\n return this;\n }\n\n /** @member {function} */\n onclick () {\n }\n setOnclick (onclick) {\n if (typeof onclick == 'function') {\n this.onclick = onclick;\n } else {\n this.onclick = function () {};\n }\n return this;\n }\n\n /**\n * Set the mouseover title text for the button (if any)\n * @param {String} title Simple text to display\n * @returns {Button}\n */\n setTitle(title) {\n if (typeof title != 'undefined') {\n this.title = title.toString();\n }\n return this;\n }\n\n /**\n * Specify the HTML content of this button.\n * WARNING: The string provided will be inserted into the document as raw markup; XSS mitigation is the\n * responsibility of each button implementation.\n * @param {String} html\n * @returns {Button}\n */\n setHtml(html) {\n if (typeof html != 'undefined') {\n this.html = html.toString();\n }\n return this;\n }\n\n // Primary behavior functions\n /**\n * Show the button, including creating DOM elements if necessary for first render\n */\n show () {\n if (!this.parent) {\n return;\n }\n if (!this.selector) {\n this.selector = this.parent.selector.append(this.tag)\n .attr('class', this.getClass());\n }\n return this.update();\n }\n\n /**\n * Hook for any actions or state cleanup to be performed before rerendering\n * @returns {Button}\n */\n preUpdate () {\n return this;\n }\n\n /**\n * Update button state and contents, and fully rerender\n * @returns {Button}\n */\n update () {\n if (!this.selector) {\n return this;\n }\n this.preUpdate();\n this.selector\n .attr('class', this.getClass())\n .attr('title', this.title)\n .on('mouseover', (this.status === 'disabled') ? null : this.onmouseover)\n .on('mouseout', (this.status === 'disabled') ? null : this.onmouseout)\n .on('click', (this.status === 'disabled') ? null : this.onclick)\n .html(this.html)\n .call(applyStyles, this.style);\n\n this.menu.update();\n this.postUpdate();\n return this;\n }\n\n /**\n * Hook for any behavior to be added/changed after the button has been re-rendered\n * @returns {Button}\n */\n postUpdate () {\n return this;\n }\n\n /**\n * Hide the button by removing it from the DOM (may be overridden by current persistence setting)\n * @returns {Button}\n */\n hide() {\n if (this.selector && !this.shouldPersist()) {\n this.selector.remove();\n this.selector = null;\n }\n return this;\n }\n\n}\n\n/**\n * Renders arbitrary text with large title formatting\n * @alias module:LocusZoom_Widgets~title\n * @param {string} layout.title Text or HTML to render\n * @param {string} [layout.subtitle] Small text to render next to the title\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass Title extends BaseWidget {\n show() {\n if (!this.div_selector) {\n this.div_selector = this.parent.selector.append('div')\n .attr('class', `lz-toolbar-title lz-toolbar-${this.layout.position}`);\n this.title_selector = this.div_selector.append('h3');\n }\n return this.update();\n }\n\n update() {\n let title = this.layout.title.toString();\n if (this.layout.subtitle) {\n title += ` ${this.layout.subtitle}`;\n }\n this.title_selector.html(title);\n return this;\n }\n}\n\n/**\n * Display the current scale of the genome region displayed in the plot, as defined by the difference between\n * `state.end` and `state.start`. Few users are interested in seeing coordinates with this level of precision, but\n * it can be useful for debugging.\n * TODO: It would be nice to move this to an extension, but helper functions drag in large dependencies as a side effect.\n * (we'd need to reorganize internals a bit before moving this widget)\n * @alias module:LocusZoom_Widgets~region_scale\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass RegionScale extends BaseWidget {\n update() {\n if (!isNaN(this.parent_plot.state.start) && !isNaN(this.parent_plot.state.end)\n && this.parent_plot.state.start !== null && this.parent_plot.state.end !== null) {\n this.selector.style('display', null);\n this.selector.html(positionIntToString(this.parent_plot.state.end - this.parent_plot.state.start, null, true));\n } else {\n this.selector.style('display', 'none');\n }\n if (this.layout.class) {\n this.selector.attr('class', this.layout.class);\n }\n if (this.layout.style) {\n applyStyles(this.selector, this.layout.style);\n }\n return this;\n }\n}\n\n/**\n * The filter field widget has triggered an update to the plot filtering rules\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_filter_field_action\n * @property {Object} data { field, operator, value, filter_id }\n * @see event:any_lz_event\n */\n\n/**\n * @alias module:LocusZoom_Widgets~filter_field\n */\nclass FilterField extends BaseWidget {\n /**\n * @param {string} layout.layer_name The data layer to control with filtering\n * @param {string} [layout.filter_id = null] Sometimes we want to define more than one filter with the same operator\n * (eg != null, != bacon). The `filter_id` option allows us to identify which filter is controlled by this widget.\n * @param {string} layout.field The field to be filtered (eg `assoc:log_pvalue`)\n * @param {string} layout.field_display_html Human-readable label for the field to be filtered (`-log10p`)\n * @param {string} layout.operator The operator to use when filtering. This must be one of the options allowed by data_layer.filter.\n * @param {number} [layout.input_size=4] How wide to make the input textbox (number characters shown at a time)\n * @param {('number'|'string')} [layout.data_type='number'] Convert the text box input to the specified type, and warn the\n * user if the value would be invalid (eg, not numeric)\n * @param {string} [layout.custom_event_name='widget_filter_field_action'] The name of the event that will be emitted when this filter is updated\n */\n constructor(layout, parent) {\n super(layout, parent);\n\n if (!this.parent_panel) {\n throw new Error('Filter widget can only be used in panel toolbars');\n }\n\n this._data_layer = this.parent_panel.data_layers[layout.layer_name];\n if (!this._data_layer) {\n throw new Error(`Filter widget could not locate the specified layer_name: '${layout.layer_name}'`);\n }\n\n this._event_name = layout.custom_event_name || 'widget_filter_field_action';\n this._field = layout.field;\n this._field_display_html = layout.field_display_html;\n this._operator = layout.operator;\n this._filter_id = null;\n this._data_type = layout.data_type || 'number';\n if (!['number', 'string'].includes(this._data_type)) {\n throw new Error('Filter must be either string or number');\n }\n\n this._value_selector = null;\n }\n\n _getTarget() {\n // Find the specific filter in layer.layout.filters, and if not present, add one\n if (!this._data_layer.layout.filters) {\n this._data_layer.layout.filters = [];\n }\n let result = this._data_layer.layout.filters\n .find((item) => item.field === this._field && item.operator === this._operator && (!this._filter_id || item.id === this._filter_id));\n\n if (!result) {\n result = { field: this._field, operator: this._operator, value: null };\n if (this._filter_id) {\n result['id'] = this._filter_id;\n }\n this._data_layer.layout.filters.push(result);\n }\n return result;\n }\n\n /** Clear the filter by removing it from the list */\n _clearFilter() {\n if (this._data_layer.layout.filters) {\n const index = this._data_layer.layout.filters.indexOf(this._getTarget());\n this._data_layer.layout.filters.splice(index, 1);\n }\n }\n\n /**\n * Set the filter based on a provided value\n * @fires event:widget_filter_field_action\n */\n _setFilter(value) {\n if (value === null) {\n // On blank or invalid value, remove the filter & warn\n this._value_selector\n .style('border', '1px solid red')\n .style('color', 'red');\n this._clearFilter();\n } else {\n const filter = this._getTarget();\n filter.value = value;\n }\n this.parent_svg.emit(this._event_name, { field: this._field, operator: this._operator, value, filter_id: this._filter_id }, true);\n }\n\n /** Get the user-entered value, coercing type if necessary. Returns null for invalid or missing values.\n * @return {null|number|string}\n * @private\n */\n _getValue() {\n let value = this._value_selector.property('value');\n if (value === null || value === '') {\n return null;\n }\n if (this._data_type === 'number') {\n value = +value;\n if (Number.isNaN(value)) {\n return null;\n }\n }\n return value;\n }\n\n update() {\n if (this._value_selector) {\n return;\n }\n this.selector.style('padding', '0 6px');\n\n // Label\n this.selector\n .append('span')\n .html(this._field_display_html)\n .style('background', '#fff')\n .style('padding-left', '3px');\n // Operator label\n this.selector.append('span')\n .text(this._operator)\n .style('padding', '0 3px')\n .style('background', '#fff');\n\n this._value_selector = this.selector\n .append('input')\n .attr('size', this.layout.input_size || 4)\n .on('input', debounce(() => {\n // Clear validation state\n this._value_selector\n .style('border', null)\n .style('color', null);\n const value = this._getValue();\n this._setFilter(value);\n this.parent_panel.render();\n }, 750));\n }\n}\n\n/**\n * The user has asked to download the plot as an SVG image\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_save_svg\n * @property {Object} data { filename }\n * @see event:any_lz_event\n */\n\n/**\n * The user has asked to download the plot as a PNG image\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_save_png\n * @property {Object} data { filename }\n * @see event:any_lz_event\n */\n\n/**\n * Button to export current plot to an SVG image\n * @alias module:LocusZoom_Widgets~download_svg\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DownloadSVG extends BaseWidget {\n /**\n * @param {string} [layout.button_html=\"Download SVG\"]\n * @param {string} [layout.button_title=\"Download hi-res image\"]\n * @param {string} [layout.filename=\"locuszoom.svg\"] The default filename to use when saving the image\n * @param {string} [layout.custom_event_name='widget_save_svg'] The name of the event that will be emitted when the button is clicked\n */\n constructor(layout, parent) {\n super(layout, parent);\n this._filename = this.layout.filename || 'locuszoom.svg';\n this._button_html = this.layout.button_html || 'Save SVG';\n this._button_title = this.layout.button_title || 'Download hi-res image';\n this._event_name = layout.custom_event_name || 'widget_save_svg';\n }\n\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this._button_html)\n .setTitle(this._button_title)\n .setOnMouseover(() => {\n this.button.selector\n .classed('lz-toolbar-button-gray-disabled', true)\n .html('Preparing Image');\n this._getBlobUrl().then((url) => {\n const old = this.button.selector.attr('href');\n if (old) {\n // Clean up old url instance to prevent memory leaks\n URL.revokeObjectURL(old);\n }\n this.button.selector\n .attr('href', url)\n .classed('lz-toolbar-button-gray-disabled', false)\n .classed('lz-toolbar-button-gray-highlighted', true)\n .html(this._button_html);\n });\n })\n .setOnMouseout(() => {\n this.button.selector.classed('lz-toolbar-button-gray-highlighted', false);\n });\n this.button.show();\n this.button.selector\n .attr('href-lang', 'image/svg+xml')\n .attr('download', this._filename)\n .on('click', () => this.parent_svg.emit(this._event_name, { filename: this._filename }, true));\n return this;\n }\n\n /**\n * Extract all CSS rules whose selectors directly reference elements under the root node\n * @param {Element} root\n * @return {string}\n * @private\n */\n _getCSS(root) {\n // Hack: this method is based on text matching the rules on a given node; it doesn't handle, eg ancestors.\n // Since all LZ cssRules are written as \"svg .classname\", we need to strip the parent selector prefix in order\n // to extract CSS.\n const ancestor_pattern = /^svg\\.lz-locuszoom\\s*/;\n\n // Extract all relevant CSS Rules by iterating through all available stylesheets\n let extractedCSSText = '';\n for (let i = 0; i < document.styleSheets.length; i++) {\n const s = document.styleSheets[i];\n try {\n if (!s.cssRules) {\n continue;\n }\n } catch ( e ) {\n if (e.name !== 'SecurityError') {\n throw e;\n } // for Firefox\n continue;\n }\n let cssRules = s.cssRules;\n for (let i = 0; i < cssRules.length; i++) {\n // FIXME: We could write smaller SVGs by extracting only the exact CSS rules for this plot. However,\n // extracting rules (including parent selectors) is a finicky process\n // Instead just fetch all LZ plot rules, under a known hardcoded parent selector.\n const rule = cssRules[i];\n const is_match = (rule.selectorText && rule.selectorText.match(ancestor_pattern));\n if (is_match) {\n extractedCSSText += rule.cssText;\n }\n }\n }\n return extractedCSSText;\n }\n\n _appendCSS( cssText, element ) {\n // Append styles to the constructed SVG DOM node\n var styleElement = document.createElement('style');\n styleElement.setAttribute('type', 'text/css');\n styleElement.innerHTML = cssText;\n var refNode = element.hasChildNodes() ? element.children[0] : null;\n element.insertBefore( styleElement, refNode );\n }\n\n /**\n * Get the target dimensions for the rendered image.\n *\n * For non-vector displays, these dimensions will yield ~300 DPI image for an 8\" wide print figure.\n * @return {number[]}\n * @private\n */\n _getDimensions() {\n let { width, height } = this.parent_plot.svg.node().getBoundingClientRect();\n const target_width = 2400;\n const rescale = target_width / width;\n return [rescale * width, rescale * height];\n }\n\n _generateSVG () {\n return new Promise((resolve) => {\n // Copy the DOM node so that we can modify the image for publication\n let copy = this.parent_plot.svg.node().cloneNode(true);\n copy.setAttribute('xlink', 'http://www.w3.org/1999/xlink');\n copy = d3.select(copy);\n\n // Remove unnecessary elements\n copy.selectAll('g.lz-curtain').remove();\n copy.selectAll('g.lz-mouse_guide').remove();\n // Convert units on axis tick dy attributes from ems to pixels\n copy.selectAll('g.tick text').each(function() {\n const dy = +(d3.select(this).attr('dy').substring(-2).slice(0, -2)) * 10;\n d3.select(this).attr('dy', dy);\n });\n // Pull the svg into a string and add the contents of the locuszoom stylesheet\n // Don't add this with d3 because it will escape the CDATA declaration incorrectly\n const serializer = new XMLSerializer();\n\n copy = copy.node();\n\n // Firefox has issues saving the SVG in certain contexts (esp rendering to canvas) unless a width is given.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=700533\n const [width, height] = this._getDimensions();\n copy.setAttribute('width', width);\n copy.setAttribute('height', height);\n\n // Add CSS to the node\n this._appendCSS(this._getCSS(copy), copy);\n let svg_markup = serializer.serializeToString(copy);\n resolve(svg_markup);\n });\n }\n\n /**\n * Converts the SVG string into a downloadable binary object\n * @return {Promise}\n */\n _getBlobUrl() {\n return this._generateSVG().then((markup) => {\n const blob = new Blob([markup], { type: 'image/svg+xml' });\n return URL.createObjectURL(blob);\n });\n }\n}\n\n/**\n * Button to export current plot to a PNG image\n * @alias module:LocusZoom_Widgets~download_png\n * @extends module:LocusZoom_Widgets~download_svg\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DownloadPNG extends DownloadSVG {\n /**\n * @param {string} [layout.button_html=\"Download PNG\"]\n * @param {string} [layout.button_title=\"Download image\"]\n * @param {string} [layout.filename=\"locuszoom.svg\"] The default filename to use when saving the image\n * @param {string} [layout.custom_event_name='widget_save_png'] The name of the event that will be emitted when the button is clicked\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\n constructor(layout, parent) {\n super(...arguments);\n this._filename = this.layout.filename || 'locuszoom.png';\n this._button_html = this.layout.button_html || 'Save PNG';\n this._button_title = this.layout.button_title || 'Download image';\n this._event_name = layout.custom_event_name || 'widget_save_png';\n }\n\n /**\n * @private\n */\n _getBlobUrl() {\n return super._getBlobUrl().then((svg_url) => {\n const canvas = document.createElement('canvas');\n const context = canvas.getContext('2d');\n\n const [width, height] = this._getDimensions();\n\n canvas.width = width;\n canvas.height = height;\n\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => {\n context.drawImage(image, 0, 0, width, height);\n // Once canvas rendered, revoke svg blob to avoid memory leaks, and create new url for the canvas\n URL.revokeObjectURL(svg_url);\n canvas.toBlob((png) => {\n resolve(URL.createObjectURL(png));\n });\n };\n image.src = svg_url;\n });\n });\n }\n}\n\n/**\n * Button to remove panel from plot.\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~remove_panel\n * @param {Boolean} [layout.suppress_confirm=false] If true, removes the panel without prompting user for confirmation\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass RemovePanel extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('×')\n .setTitle('Remove panel')\n .setOnclick(() => {\n if (!this.layout.suppress_confirm && !confirm('Are you sure you want to remove this panel? This cannot be undone.')) {\n return false;\n }\n const panel = this.parent_panel;\n panel.toolbar.hide(true);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseover.${panel.getBaseId()}.toolbar`, null);\n d3.select(panel.parent.svg.node().parentNode).on(`mouseout.${panel.getBaseId()}.toolbar`, null);\n return panel.parent.removePanel(panel.id);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to move panel up relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~move_panel_up\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass MovePanelUp extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_top = (this.parent_panel.layout.y_index === 0);\n this.button.disable(is_at_top);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▴')\n .setTitle('Move panel up')\n .setOnclick(() => {\n this.parent_panel.moveUp();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to move panel down relative to other panels (in terms of y-index on the page)\n * NOTE: Will only work on panel widgets.\n * @alias module:LocusZoom_Widgets~move_panel_down\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass MovePanelDown extends BaseWidget {\n update () {\n if (this.button) {\n const is_at_bottom = (this.parent_panel.layout.y_index === this.parent_plot.panel_ids_by_y_index.length - 1);\n this.button.disable(is_at_bottom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml('▾')\n .setTitle('Move panel down')\n .setOnclick(() => {\n this.parent_panel.moveDown();\n this.update();\n });\n this.button.show();\n return this.update();\n }\n}\n\n/**\n * Button to shift plot region forwards or back by a `step` increment provided in the layout\n * @alias module:LocusZoom_Widgets~shift_region\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ShiftRegion extends BaseWidget {\n /**\n * @param {number} [layout.step=50000] The stepsize to change the region by\n * @param {string} [layout.button_html] Label\n * @param {string} [layout.button_title] Mouseover text\n */\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 50000;\n }\n if (typeof layout.button_html !== 'string') {\n layout.button_html = layout.step > 0 ? '>' : '<';\n }\n\n if (typeof layout.button_title !== 'string') {\n layout.button_title = `Shift region by ${layout.step > 0 ? '+' : '-'}${positionIntToString(Math.abs(layout.step), null, true)}`;\n }\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add shift_region toolbar widget: plot state does not have region bounds');\n }\n\n\n }\n\n update () {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start + this.layout.step, 1),\n end: this.parent_plot.state.end + this.layout.step,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Zoom in or out on the plot, centered on the middle of the plot region, by the specified amount\n * @alias module:LocusZoom_Widgets~zoom_region\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ZoomRegion extends BaseWidget {\n /**\n * @param {number} [layout.step=0.2] The fraction to zoom in by (where 1 indicates 100%)\n * @param {string} [layout.button_html] Label\n * @param {string} [layout.button_title] Mouseover text\n */\n constructor(layout, parent) {\n if (isNaN(layout.step) || layout.step === 0) {\n layout.step = 0.2;\n }\n if (typeof layout.button_html != 'string') {\n layout.button_html = layout.step > 0 ? 'z–' : 'z+';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = `Zoom region ${layout.step > 0 ? 'out' : 'in'} by ${(Math.abs(layout.step) * 100).toFixed(1)}%`;\n }\n\n super(layout, parent);\n if (isNaN(this.parent_plot.state.start) || isNaN(this.parent_plot.state.end)) {\n throw new Error('Unable to add zoom_region toolbar widget: plot state does not have region bounds');\n }\n }\n\n update () {\n if (this.button) {\n let can_zoom = true;\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n if (this.layout.step > 0 && !isNaN(this.parent_plot.layout.max_region_scale) && current_region_scale >= this.parent_plot.layout.max_region_scale) {\n can_zoom = false;\n }\n if (this.layout.step < 0 && !isNaN(this.parent_plot.layout.min_region_scale) && current_region_scale <= this.parent_plot.layout.min_region_scale) {\n can_zoom = false;\n }\n this.button.disable(!can_zoom);\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title)\n .setOnclick(() => {\n const current_region_scale = this.parent_plot.state.end - this.parent_plot.state.start;\n const zoom_factor = 1 + this.layout.step;\n let new_region_scale = current_region_scale * zoom_factor;\n if (!isNaN(this.parent_plot.layout.max_region_scale)) {\n new_region_scale = Math.min(new_region_scale, this.parent_plot.layout.max_region_scale);\n }\n if (!isNaN(this.parent_plot.layout.min_region_scale)) {\n new_region_scale = Math.max(new_region_scale, this.parent_plot.layout.min_region_scale);\n }\n const delta = Math.floor((new_region_scale - current_region_scale) / 2);\n this.parent_plot.applyState({\n start: Math.max(this.parent_plot.state.start - delta, 1),\n end: this.parent_plot.state.end + delta,\n });\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Renders button with arbitrary text that, when clicked, shows a dropdown containing arbitrary HTML. This is usually\n * used as part of coding a custom button, rather than as a standalone widget.\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @alias module:LocusZoom_Widgets~menu\n * @param {string} layout.button_html The HTML to render inside the button\n * @param {string} layout.button_title Text to display as a tooltip when hovering over the button\n * @param {string} layout.menu_html The HTML content of the dropdown menu\n */\nclass Menu extends BaseWidget {\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html)\n .setTitle(this.layout.button_title);\n this.button.menu.setPopulate(() => {\n this.button.menu.inner_selector.html(this.layout.menu_html);\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to resize panel height to fit available data (eg when showing a list of tracks)\n * @alias module:LocusZoom_Widgets~resize_to_data\n */\nclass ResizeToData extends BaseWidget {\n /**\n * @param {string} [layout.button_html=\"Resize to Data\"]\n * @param {string} [layout.button_title]\n */\n constructor(layout) {\n super(...arguments);\n }\n update() {\n if (this.button) {\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setHtml(this.layout.button_html || 'Resize to Data')\n .setTitle(this.layout.button_title || 'Automatically resize this panel to show all data available')\n .setOnclick(() => {\n this.parent_panel.scaleHeightToData();\n this.update();\n });\n this.button.show();\n return this;\n }\n}\n\n/**\n * Button to toggle legend\n * @alias module:LocusZoom_Widgets~toggle_legend\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass ToggleLegend extends BaseWidget {\n update() {\n const html = this.parent_panel.legend.layout.hidden ? 'Show Legend' : 'Hide Legend';\n if (this.button) {\n this.button.setHtml(html).show();\n this.parent.position();\n return this;\n }\n this.button = new Button(this)\n .setColor(this.layout.color)\n .setTitle('Show or hide the legend for this panel')\n .setOnclick(() => {\n this.parent_panel.legend.layout.hidden = !this.parent_panel.legend.layout.hidden;\n this.parent_panel.legend.render();\n this.update();\n });\n return this.update();\n }\n}\n\n\n/**\n * @typedef {object} DisplayOptionsButtonConfigField\n * @property {string} display_name The human-readable label for this set of options\n * @property {object} display An object with layout directives that will be merged into the target layer.\n * The directives should be among those listed in `fields_whitelist` for this widget.\n */\n\n/**\n * The user has chosen a specific display option to show information on the plot\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_display_options_choice\n * @property {Object} data {choice} The display_name of the item chosen from the list\n * @see event:any_lz_event\n */\n\n/**\n * Dropdown menu allowing the user to choose between different display options for a single specific data layer\n * within a panel.\n *\n * This allows controlling how points on a datalayer can be displayed- any display options supported via the layout for the target datalayer. This includes point\n * size/shape, coloring, etc.\n *\n * This button intentionally limits display options it can control to those available on common plot types.\n * Although the list of options it sets can be overridden (to control very special custom plot types), this\n * capability should be used sparingly if at all.\n * @alias module:LocusZoom_Widgets~display_options\n * @see {@link module:LocusZoom_Widgets~BaseWidget} for additional options\n */\nclass DisplayOptions extends BaseWidget {\n /**\n * @param {string} layout.layer_name Specify the datalayer that this button should affect\n * @param {String} [layout.button_html=\"Display options...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Control how plot items are displayed\"] Hover text for the toolbar button\n * @param {string} [layout.default_config_display_name] Store the default configuration for this datalayer\n * configuration, and show a button to revert to the \"default\" (listing the human-readable display name provided)\n * @param {Array} [layout.fields_whitelist='see code'] The list of presentation fields that this button can control.\n * This can be overridden if this button needs to be used on a custom layer type with special options.\n * The whitelist is chosen to be things that are known to be easily modified with few side effects.\n * When the button is first created, all fields in the whitelist will have their default values saved, so the user can revert to the default view easily.\n * @param {module:LocusZoom_Widgets~DisplayOptionsButtonConfigField[]} layout.options Specify a label and set of layout directives associated\n * with this `display` option. Display field should include all changes that will be merged to datalayer layout options.\n * @param {string} [layout.custom_event_name='widget_display_options_choice'] The name of the event that will be emitted when an option is selected\n */\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Display options...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Control how plot items are displayed';\n }\n super(...arguments);\n this._event_name = layout.custom_event_name || 'widget_display_options_choice';\n\n // List of layout fields that this button is allowed to control. This ensures that we don't override any other\n // information (like plot height etc) while changing point rendering\n const allowed_fields = layout.fields_whitelist || ['color', 'fill_opacity', 'filters', 'label', 'legend',\n 'point_shape', 'point_size', 'tooltip', 'tooltip_positioning'];\n\n const dataLayer = this.parent_panel.data_layers[layout.layer_name];\n if (!dataLayer) {\n throw new Error(`Display options could not locate the specified layer_name: '${layout.layer_name}'`);\n }\n const dataLayerLayout = dataLayer.layout;\n\n // Store default configuration for the layer as a clean deep copy, so we may revert later\n const defaultConfig = {};\n allowed_fields.forEach((name) => {\n const configSlot = dataLayerLayout[name];\n if (configSlot !== undefined) {\n defaultConfig[name] = deepCopy(configSlot);\n }\n });\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n this._selected_item = 'default';\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html)\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const menuLayout = this.layout;\n\n const renderRow = (display_name, display_options, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `display-option-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (row_id === this._selected_item))\n .on('click', () => {\n // If an option is not specified in these display options, use the original defaults\n allowed_fields.forEach((field_name) => {\n const has_option = typeof display_options[field_name] !== 'undefined';\n dataLayer.layout[field_name] = has_option ? display_options[field_name] : defaultConfig[field_name];\n });\n\n this.parent_svg.emit(this._event_name, { choice: display_name }, true);\n this._selected_item = row_id;\n this.parent_panel.render();\n const legend = this.parent_panel.legend;\n if (legend) {\n legend.render();\n }\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n // Render the \"display options\" menu: default and special custom options\n const defaultName = menuLayout.default_config_display_name || 'Default style';\n renderRow(defaultName, defaultConfig, 'default');\n menuLayout.options.forEach((item, index) => renderRow(item.display_name, item.display, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n/**\n * @typedef {object} SetStateOptionsConfigField\n * @property {string} display_name Human readable name for option label (eg \"European\")\n * @property value Value to set in plot.state (eg \"EUR\")\n */\n\n/**\n * An option has been chosen from the set_state dropdown menu\n * Note: The widget can optionally be configured to broadcast this event under an alias (layout.custom_event_name)\n *\n * @event widget_set_state_choice\n * @property {Object} data { choice_name, choice_value, state_field }\n * @see event:any_lz_event\n */\n\n/**\n * Dropdown menu allowing the user to set the value of a specific `state_field` in plot.state\n * This is useful for things (like datasources) that allow dynamic configuration based on global information in state\n *\n * For example, the LDServer data adapter can use it to change LD reference population (for all panels) after render\n *\n * @alias module:LocusZoom_Widgets~set_state\n * @param {String} [layout.button_html=\"Set option...\"] Text to display on the toolbar button\n * @param {String} [layout.button_title=\"Choose an option to customize the plot\"] Hover text for the toolbar button\n * @param {bool} [layout.show_selected=false] Whether to append the selected value to the button label (\"LD Population: ALL\")\n * @param {string} [layout.state_field] The name of the field in plot.state that will be set by this button\n * @param {module:LocusZoom_Widgets~SetStateOptionsConfigField[]} layout.options Specify human labels and associated values for the dropdown menu\n * @param {string} [layout.custom_event_name='widget_set_state_choice'] The name of the event that will be emitted when an option is selected\n */\nclass SetState extends BaseWidget {\n constructor(layout, parent) {\n if (typeof layout.button_html != 'string') {\n layout.button_html = 'Set option...';\n }\n if (typeof layout.button_title != 'string') {\n layout.button_title = 'Choose an option to customize the plot';\n }\n\n super(layout, parent);\n\n if (this.parent_panel) {\n throw new Error('This widget is designed to set global options, so it can only be used at the top (plot) level');\n }\n if (!layout.state_field) {\n throw new Error('Must specify the `state_field` that this widget controls');\n }\n\n this._event_name = layout.custom_event_name || 'widget_set_state_choice';\n\n /**\n * Which item in the menu is currently selected. (track for rerendering menu)\n * @member {String}\n * @private\n */\n // The first option listed is automatically assumed to be the default, unless a value exists in plot.state\n this._selected_item = this.parent_plot.state[layout.state_field] || layout.options[0].value;\n if (!layout.options.find((item) => {\n return item.value === this._selected_item;\n })) {\n // Check only gets run at widget creation, but generally this widget is assumed to be an exclusive list of options\n throw new Error('There is an existing state value that does not match the known values in this widget');\n }\n\n // Define the button + menu that provides the real functionality for this toolbar widget\n this.button = new Button(this)\n .setColor(layout.color)\n .setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''))\n .setTitle(layout.button_title)\n .setOnclick(() => {\n this.button.menu.populate();\n });\n this.button.menu.setPopulate(() => {\n // Multiple copies of this button might be used on a single LZ page; append unique IDs where needed\n const uniqueID = Math.floor(Math.random() * 1e4).toString();\n\n this.button.menu.inner_selector.html('');\n const table = this.button.menu.inner_selector.append('table');\n\n const renderRow = (display_name, value, row_id) => { // Helper method\n const row = table.append('tr');\n const radioId = `${uniqueID}${row_id}`;\n row.append('td')\n .append('input')\n .attr('id', radioId)\n .attr('type', 'radio')\n .attr('name', `set-state-${uniqueID}`)\n .attr('value', row_id)\n .style('margin', 0) // Override css libraries (eg skeleton) that style form inputs\n .property('checked', (value === this._selected_item))\n .on('click', () => {\n const new_state = {};\n new_state[layout.state_field] = value;\n this._selected_item = value;\n this.parent_plot.applyState(new_state);\n this.button.setHtml(layout.button_html + (layout.show_selected ? this._selected_item : ''));\n\n this.parent_svg.emit(this._event_name, { choice_name: display_name, choice_value: value, state_field: layout.state_field }, true);\n });\n row.append('td').append('label')\n .style('font-weight', 'normal')\n .attr('for', radioId)\n .text(display_name);\n };\n layout.options.forEach((item, index) => renderRow(item.display_name, item.value, index));\n return this;\n });\n }\n\n update() {\n this.button.show();\n return this;\n }\n}\n\n\nexport {\n BaseWidget, // This is used to create subclasses\n Button as _Button, // This is used to create Widgets that contain a button. It actually shouldn't be in the registry because it's not usable directly..\n DisplayOptions as display_options,\n DownloadSVG as download,\n DownloadPNG as download_png,\n FilterField as filter_field,\n Menu as menu,\n MovePanelDown as move_panel_down,\n MovePanelUp as move_panel_up,\n RegionScale as region_scale,\n ResizeToData as resize_to_data,\n SetState as set_state,\n ShiftRegion as shift_region,\n RemovePanel as remove_panel,\n Title as title,\n ToggleLegend as toggle_legend,\n ZoomRegion as zoom_region,\n};\n","import {ClassRegistry} from './base';\nimport * as widgets from '../components/toolbar/widgets';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided toolbar widgets: interactive buttons\n * and menus that control plot display, modify data, or show additional information as context.\n * @alias module:LocusZoom~Widgets\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\n\nfor (let [name, type] of Object.entries(widgets)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","import widgets from '../../registry/widgets';\nimport * as d3 from 'd3';\n\n/**\n * A Toolbar is an HTML element used for presenting arbitrary user interface widgets. Toolbars are anchored\n * to either the entire Plot or to individual Panels.\n *\n * Each toolbar is an HTML-based (read: not SVG) collection of widgets used to display information or provide\n * user interface. Toolbars can exist on entire plots, where their visibility is permanent and vertically adjacent\n * to the plot, or on individual panels, where their visibility is tied to a behavior (e.g. a mouseover) and is as\n * an overlay.\n *\n * This class is used internally for rendering, and is not part of the public interface\n * @private\n */\nclass Toolbar {\n constructor(parent) {\n // parent must be a locuszoom plot or panel\n // if (!(parent instanceof LocusZoom.Plot) && !(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create toolbar, parent must be a locuszoom plot or panel');\n // }\n /** @member {Plot|Panel} */\n this.parent = parent;\n\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.toolbar`;\n\n /** @member {('plot'|'panel')} */\n this.type = (this.parent.parent) ? 'panel' : 'plot';\n\n /** @member {Plot} */\n this.parent_plot = this.parent.parent_plot;\n\n /** @member {d3.selection} */\n this.selector = null;\n\n /** @member {BaseWidget[]} */\n this.widgets = [];\n\n /**\n * The timer identifier as returned by setTimeout\n * @member {Number}\n */\n this.hide_timeout = null;\n\n /**\n * Whether to hide the toolbar. Can be overridden by a child widget. Check via `shouldPersist`\n * @protected\n * @member {Boolean}\n */\n this.persist = false;\n\n this.initialize();\n }\n\n /**\n * Prepare the toolbar for first use: generate all widget instances for this toolbar, based on the provided\n * layout of the parent. Connects event listeners and shows/hides as appropriate.\n * @returns {Toolbar}\n */\n initialize() {\n // Parse layout to generate widget instances\n // In LZ 0.12, `dashboard.components` was renamed to `toolbar.widgets`. Preserve a backwards-compatible alias.\n const options = (this.parent.layout.dashboard && this.parent.layout.dashboard.components) || this.parent.layout.toolbar.widgets;\n if (Array.isArray(options)) {\n options.forEach((layout) => {\n try {\n const widget = widgets.create(layout.type, layout, this);\n this.widgets.push(widget);\n } catch (e) {\n console.warn('Failed to create widget');\n console.error(e);\n }\n });\n }\n\n // Add mouseover event handlers to show/hide panel toolbar\n if (this.type === 'panel') {\n d3.select(this.parent.parent.svg.node().parentNode)\n .on(`mouseover.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n if (!this.selector || this.selector.style('visibility') === 'hidden') {\n this.show();\n }\n }).on(`mouseout.${this.id}`, () => {\n clearTimeout(this.hide_timeout);\n this.hide_timeout = setTimeout(() => {\n this.hide();\n }, 300);\n });\n }\n\n return this;\n }\n\n /**\n * Whether to persist the toolbar. Returns true if at least one widget should persist, or if the panel is engaged\n * in an active drag event.\n * @returns {boolean}\n */\n shouldPersist() {\n if (this.persist) {\n return true;\n }\n let persist = false;\n // Persist if at least one widget should also persist\n this.widgets.forEach((widget) => {\n persist = persist || widget.shouldPersist();\n });\n // Persist if in a parent drag event\n persist = persist || (this.parent_plot.panel_boundaries.dragging || this.parent_plot.interaction.dragging);\n return !!persist;\n }\n\n /**\n * Make the toolbar appear. If it doesn't exist yet create it, including creating/positioning all widgets within,\n * and make sure it is set to be visible.\n */\n show() {\n if (!this.selector) {\n switch (this.type) {\n case 'plot':\n this.selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', ':first-child');\n break;\n case 'panel':\n this.selector = d3.select(this.parent.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip, .lz-toolbar-menu, .lz-curtain').classed('lz-panel-toolbar', true);\n break;\n default:\n throw new Error(`Toolbar cannot be a child of ${this.type}`);\n }\n\n this.selector\n .classed('lz-toolbar', true)\n .classed(`lz-${this.type}-toolbar`, true)\n .attr('id', this.id);\n }\n this.widgets.forEach((widget) => widget.show());\n this.selector.style('visibility', 'visible');\n return this.update();\n }\n\n\n /**\n * Update the toolbar and rerender all child widgets. This can be called whenever plot state changes.\n * @returns {Toolbar}\n */\n update() {\n if (!this.selector) {\n return this;\n }\n this.widgets.forEach((widget) => widget.update());\n return this.position();\n }\n\n\n /**\n * Position the toolbar (and child widgets) within the panel\n * @returns {Toolbar}\n */\n position() {\n if (!this.selector) {\n return this;\n }\n // Position the toolbar itself (panel only)\n if (this.type === 'panel') {\n const page_origin = this.parent._getPageOrigin();\n const top = `${(page_origin.y + 3.5).toString()}px`;\n const left = `${page_origin.x.toString()}px`;\n const width = `${(this.parent_plot.layout.width - 4).toString()}px`;\n this.selector\n .style('position', 'absolute')\n .style('top', top)\n .style('left', left)\n .style('width', width);\n }\n // Recursively position widgets\n this.widgets.forEach((widget) => widget.position());\n return this;\n }\n\n /**\n * Hide the toolbar (make invisible but do not destroy). Will do nothing if `shouldPersist` returns true.\n *\n * @returns {Toolbar}\n */\n hide() {\n if (!this.selector || this.shouldPersist()) {\n return this;\n }\n this.widgets.forEach((widget) => widget.hide());\n this.selector\n .style('visibility', 'hidden');\n return this;\n }\n\n /**\n * Completely remove toolbar and all child widgets. (may be overridden by persistence settings)\n * @param {Boolean} [force=false] If true, will ignore persistence settings and always destroy the toolbar\n * @returns {Toolbar}\n */\n destroy(force) {\n if (typeof force == 'undefined') {\n force = false;\n }\n if (!this.selector) {\n return this;\n }\n if (this.shouldPersist() && !force) {\n return this;\n }\n this.widgets.forEach((widget) => widget.destroy(true));\n this.widgets = [];\n this.selector.remove();\n this.selector = null;\n return this;\n }\n}\n\n\nexport {Toolbar as default};\n","/**\n * @module\n * @private\n */\nimport * as d3 from 'd3';\nimport {applyStyles} from '../helpers/common';\nimport {merge, nameToSymbol} from '../helpers/layouts';\n\n// FIXME: Document legend options\n/**\n * The default layout used by legends (used internally)\n * @protected\n * @member {Object}\n */\nconst default_layout = {\n orientation: 'vertical',\n origin: { x: 0, y: 0 },\n width: 10,\n height: 10,\n padding: 5,\n label_size: 12,\n hidden: false,\n};\n\n/**\n * An SVG object used to display contextual information about a panel.\n * Panel layouts determine basic features of a legend - its position in the panel, orientation, title, etc.\n * Layouts of child data layers of the panel determine the actual content of the legend.\n *\n * @param {Panel} parent\n*/\nclass Legend {\n constructor(parent) {\n // if (!(parent instanceof LocusZoom.Panel)) {\n // throw new Error('Unable to create legend, parent must be a locuszoom panel');\n // }\n /** @member {Panel} */\n this.parent = parent;\n /** @member {String} */\n this.id = `${this.parent.getBaseId()}.legend`;\n\n this.parent.layout.legend = merge(this.parent.layout.legend || {}, default_layout);\n /** @member {Object} */\n this.layout = this.parent.layout.legend;\n\n /** @member {d3.selection} */\n this.selector = null;\n /** @member {d3.selection} */\n this.background_rect = null;\n /** @member {d3.selection[]} */\n this.elements = [];\n /**\n * SVG selector for the group containing all elements in the legend\n * @protected\n * @member {d3.selection|null}\n */\n this.elements_group = null;\n\n /**\n * TODO: Not sure if this property is used; the external-facing methods are setting `layout.hidden` instead. Tentatively mark deprecated.\n * @deprecated\n * @protected\n * @member {Boolean}\n */\n this.hidden = false;\n\n return this.render();\n }\n\n /**\n * Render the legend in the parent panel\n */\n render() {\n // Get a legend group selector if not yet defined\n if (!this.selector) {\n this.selector = this.parent.svg.group.append('g')\n .attr('id', `${this.parent.getBaseId()}.legend`).attr('class', 'lz-legend');\n }\n\n // Get a legend background rect selector if not yet defined\n if (!this.background_rect) {\n this.background_rect = this.selector.append('rect')\n .attr('width', 100)\n .attr('height', 100)\n .attr('class', 'lz-legend-background');\n }\n\n // Get a legend elements group selector if not yet defined\n if (!this.elements_group) {\n this.elements_group = this.selector.append('g');\n }\n\n // Remove all elements from the document and re-render from scratch\n this.elements.forEach((element) => element.remove());\n this.elements = [];\n\n // Gather all elements from data layers in order (top to bottom) and render them\n const padding = +this.layout.padding || 1;\n let x = padding;\n let y = padding;\n let line_height = 0;\n this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((id) => {\n if (Array.isArray(this.parent.data_layers[id].layout.legend)) {\n this.parent.data_layers[id].layout.legend.forEach((element) => {\n const selector = this.elements_group.append('g')\n .attr('transform', `translate(${x}, ${y})`);\n const label_size = +element.label_size || +this.layout.label_size || 12;\n let label_x = 0;\n let label_y = (label_size / 2) + (padding / 2);\n line_height = Math.max(line_height, label_size + padding);\n // Draw the legend element symbol (line, rect, shape, etc)\n const shape = element.shape || '';\n const shape_factory = nameToSymbol(shape);\n if (shape === 'line') {\n // Line symbol\n const length = +element.length || 16;\n const path_y = (label_size / 4) + (padding / 2);\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', `M0,${path_y}L${length},${path_y}`)\n .call(applyStyles, element.style || {});\n label_x = length + padding;\n } else if (shape === 'rect') {\n // Rect symbol\n const width = +element.width || 16;\n const height = +element.height || width;\n selector\n .append('rect')\n .attr('class', element.class || '')\n .attr('width', width)\n .attr('height', height)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = width + padding;\n line_height = Math.max(line_height, height + padding);\n } else if (shape_factory) {\n // Shape symbol is a recognized d3 type, so we can draw it in the legend (circle, diamond, etc.)\n const size = +element.size || 40;\n const radius = Math.ceil(Math.sqrt(size / Math.PI));\n selector\n .append('path')\n .attr('class', element.class || '')\n .attr('d', d3.symbol().size(size).type(shape_factory))\n .attr('transform', `translate(${radius}, ${radius + (padding / 2)})`)\n .attr('fill', element.color || {})\n .call(applyStyles, element.style || {});\n\n label_x = (2 * radius) + padding;\n label_y = Math.max((2 * radius) + (padding / 2), label_y);\n line_height = Math.max(line_height, (2 * radius) + padding);\n }\n // Draw the legend element label\n selector\n .append('text')\n .attr('text-anchor', 'left')\n .attr('class', 'lz-label')\n .attr('x', label_x)\n .attr('y', label_y)\n .style('font-size', label_size)\n .text(element.label);\n\n // Position the legend element group based on legend layout orientation\n const bcr = selector.node().getBoundingClientRect();\n if (this.layout.orientation === 'vertical') {\n y += bcr.height + padding;\n line_height = 0;\n } else {\n // Ensure this element does not exceed the panel width\n // (E.g. drop to the next line if it does, but only if it's not the only element on this line)\n const right_x = this.layout.origin.x + x + bcr.width;\n if (x > padding && right_x > this.parent.parent.layout.width) {\n y += line_height;\n x = padding;\n selector.attr('transform', `translate(${x}, ${y})`);\n }\n x += bcr.width + (3 * padding);\n }\n // Store the element\n this.elements.push(selector);\n });\n }\n });\n\n // Scale the background rect to the elements in the legend\n const bcr = this.elements_group.node().getBoundingClientRect();\n this.layout.width = bcr.width + (2 * this.layout.padding);\n this.layout.height = bcr.height + (2 * this.layout.padding);\n this.background_rect\n .attr('width', this.layout.width)\n .attr('height', this.layout.height);\n\n // Set the visibility on the legend from the \"hidden\" flag\n // TODO: `show()` and `hide()` call a full rerender; might be able to make this more lightweight?\n this.selector\n .style('visibility', this.layout.hidden ? 'hidden' : 'visible');\n\n return this.position();\n }\n\n /**\n * Place the legend in position relative to the panel, as specified in the layout configuration\n * @returns {Legend | null}\n * TODO: should this always be chainable?\n */\n position() {\n if (!this.selector) {\n return this;\n }\n const bcr = this.selector.node().getBoundingClientRect();\n if (!isNaN(+this.layout.pad_from_bottom)) {\n this.layout.origin.y = this.parent.layout.height - bcr.height - +this.layout.pad_from_bottom;\n }\n if (!isNaN(+this.layout.pad_from_right)) {\n this.layout.origin.x = this.parent.parent.layout.width - bcr.width - +this.layout.pad_from_right;\n }\n this.selector.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n }\n\n /**\n * Hide the legend (triggers a re-render)\n * @public\n */\n hide() {\n this.layout.hidden = true;\n this.render();\n }\n\n /**\n * Show the legend (triggers a re-render)\n * @public\n */\n show() {\n this.layout.hidden = false;\n this.render();\n }\n}\n\nexport {Legend as default};\n","import * as d3 from 'd3';\n\nimport {STATUSES} from './constants';\nimport Toolbar from './toolbar';\nimport {applyStyles, generateCurtain, generateLoader} from '../helpers/common';\nimport {parseFields, positionIntToString, prettyTicks} from '../helpers/display';\nimport {merge} from '../helpers/layouts';\nimport Legend from './legend';\nimport data_layers from '../registry/data_layers';\n\n\n/**\n * Default panel layout\n * @memberof Panel\n * @static\n * @type {Object}\n */\nconst default_layout = {\n id: '',\n tag: 'custom_data_type',\n title: { text: '', style: {}, x: 10, y: 22 },\n y_index: null,\n min_height: 1,\n height: 1,\n origin: { x: 0, y: null },\n margin: { top: 0, right: 0, bottom: 0, left: 0 },\n background_click: 'clear_selections',\n toolbar: {\n widgets: [],\n },\n cliparea: {\n height: 0,\n width: 0,\n origin: { x: 0, y: 0 },\n },\n axes: { // These are the only axes supported!!\n x: {},\n y1: {},\n y2: {},\n },\n legend: null,\n interaction: {\n drag_background_to_pan: false,\n drag_x_ticks_to_scale: false,\n drag_y1_ticks_to_scale: false,\n drag_y2_ticks_to_scale: false,\n scroll_to_zoom: false,\n x_linked: false,\n y1_linked: false,\n y2_linked: false,\n },\n show_loading_indicator: true,\n data_layers: [],\n};\n\n/**\n * A panel is an abstract class representing a subdivision of the LocusZoom stage\n * to display a distinct data representation as a collection of data layers.\n */\nclass Panel {\n /**\n * @param {string} [layout.id=''] An identifier string that must be unique across all panels in the plot\n * @param {string} [layout.tag='custom_data_type'] Tags have no functional purpose, but they can be used\n * as a semantic label for what is being displayed in this element. This makes it easy to write custom code like \"find every panel\n * that shows association scatter plots, anywhere\": even if the IDs are different, the tag can be the same.\n * Most built-in panels will contain a tag that describes, in human-readable terms, what kind of data is being shown.\n * (see: {@link LayoutRegistry.mutate_attrs})\n * @param {boolean} [layout.show_loading_indicator=true] Whether to show a \"loading indicator\" while data is being fetched\n * @param {module:LocusZoom_DataLayers[]} [layout.data_layers] Data layer layout objects\n * @param {module:LocusZoom_Widgets[]} [layout.toolbar.widgets] Configuration options for each toolbar widget; {@link module:LocusZoom_Widgets}\n * @param {number} [layout.title.text] Text to show in panel title\n * @param {number} [layout.title.style] CSS options to apply to the title\n * @param {number} [layout.title.x=10] x-offset for title position\n * @param {number} [layout.title.y=22] y-offset for title position\n * @param {'vertical'|'horizontal'} [layout.legend.orientation='vertical'] Orientation with which elements in the legend should be arranged.\n * Presently only \"vertical\" and \"horizontal\" are supported values. When using the horizontal orientation\n * elements will automatically drop to a new line if the width of the legend would exceed the right edge of the\n * containing panel. Defaults to \"vertical\".\n * @param {number} [layout.legend.origin.x=0] X-offset, in pixels, for the top-left corner of the legend (relative to the top left corner of the panel).\n * @param {number} [layout.legend.origin.y=0] Y-offset, in pixels, for the top-left corner of the legend (relative to the top left corner of the panel).\n * NOTE: SVG y values go from the top down, so the SVG origin of (0,0) is in the top left corner.\n * @param {number} [layout.legend.padding=5] Value in pixels to pad between the legend's outer border and the\n * elements within the legend. This value is also used for spacing between elements in the legend on different\n * lines (e.g. in a vertical orientation) and spacing between element shapes and labels, as well as between\n * elements in a horizontal orientation, are defined as a function of this value. Defaults to 5.\n * @param {number} [layout.legend.label_size=12] Font size for element labels in the legend (loosely analogous to the height of full-height letters, in pixels). Defaults to 12.\n * @param {boolean} [layout.legend.hidden=false] Whether to hide the legend by default\n * @param {number} [layout.y_index] The position of the panel (above or below other panels). This is usually set\n * automatically when the panel is added, and rarely controlled directly.\n * @param {number} [layout.min_height=1] When resizing, do not allow height to go below this value\n * @param {number} [layout.height=1] The actual height allocated to the panel (>= min_height)\n * @param {number} [layout.margin.top=0] The margin (space between top of panel and edge of viewing area)\n * @param {number} [layout.margin.right=0] The margin (space between right side of panel and edge of viewing area)\n * @param {number} [layout.margin.bottom=0] The margin (space between bottom of panel and edge of viewing area)\n * @param {number} [layout.margin.left=0] The margin (space between left side of panel and edge of viewing area)\n * @param {'clear_selections'|null} [layout.background_click='clear_selections'] What happens when the background of the panel is clicked\n * @param {'state'|null} [layout.axes.x.extent] If 'state', the x extent will be determined from plot.state (a\n * shared region). Otherwise it will be determined based on data later ranges.\n * @param {string} [layout.axes.x.label] Label text for the provided axis\n * @param {number} [layout.axes.x.label_offset]\n * @param {boolean} [layout.axes.x.render] Whether to render this axis\n * @param {'region'|null} [layout.axes.x.tick_format] If 'region', format ticks in a concise way suitable for\n * genomic coordinates, eg 23423456 => 23.42 (Mb)\n * @param {Array} [layout.axes.x.ticks] An array of custom ticks that will override any automatically generated)\n * @param {string} [layout.axes.y1.label] Label text for the provided axis\n * @param {number} [layout.axes.y1.label_offset]\n * @param {boolean} [layout.axes.y1.render=false] Whether to render this axis\n * @param {Array} [layout.axes.y1.ticks] An array of custom ticks that will override any automatically generated)\n * @param {string} [layout.axes.y2.label] Label text for the provided axis\n * @param {number} [layout.axes.y2.label_offset]\n * @param {boolean} [layout.axes.y2.render=false] Whether to render this axis\n * @param {Array} [layout.axes.y2.ticks] An array of custom ticks that will override any automatically generated)\n * @param {boolean} [layout.interaction.drag_background_to_pan=false] Allow the user to drag the panel background to pan\n * the plot to another genomic region.\n * @param {boolean} [layout.interaction.drag_x_ticks_to_scale=false] Allow the user to rescale the x axis by dragging x ticks\n * @param {boolean} [layout.interaction.drag_y1_ticks_to_scale=false] Allow the user to rescale the y1 axis by dragging y1 ticks\n * @param {boolean} [layout.interaction.drag_y2_ticks_to_scale=false] Allow the user to rescale the y2 axis by dragging y2 ticks\n * @param {boolean} [layout.interaction.scroll_to_zoom=false] Allow the user to rescale the plot by mousewheel-scrolling\n * @param {boolean} [layout.interaction.x_linked=false] Whether this panel should change regions to match all other linked panels\n * @param {boolean} [layout.interaction.y1_linked=false] Whether this panel should rescale to match all other linked panels\n * @param {boolean} [layout.interaction.y2_linked=false] Whether this panel should rescale to match all other linked panels\n * @param {Plot|null} parent\n */\n constructor(layout, parent) {\n if (typeof layout !== 'object') {\n throw new Error('Unable to create panel, invalid layout');\n }\n\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent = parent || null;\n /**\n * @protected\n * @member {Plot|null}\n */\n this.parent_plot = parent;\n\n // Ensure a valid ID is present. If there is no valid ID then generate one\n if (typeof layout.id !== 'string' || !layout.id.length) {\n if (!this.parent) {\n layout.id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n } else {\n const generateID = () => {\n let id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`;\n if (id === null || typeof this.parent.panels[id] != 'undefined') {\n id = generateID();\n }\n return id;\n };\n layout.id = generateID();\n }\n } else if (this.parent) {\n if (typeof this.parent.panels[layout.id] !== 'undefined') {\n throw new Error(`Cannot create panel with id [${layout.id}]; panel with that id already exists`);\n }\n }\n /**\n * @public\n * @member {String}\n */\n this.id = layout.id;\n\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * The index of this panel in the parent plot's `layout.panels`\n * @private\n * @member {number}\n * */\n this.layout_idx = null;\n /**\n * @private\n * @member {Object}\n */\n this.svg = {};\n\n /**\n * A JSON-serializable object used to describe the composition of the Panel\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n\n // Define state parameters specific to this panel\n if (this.parent) {\n /**\n * @private\n * @member {Object}\n */\n this.state = this.parent.state;\n\n /**\n * @private\n * @member {String}\n */\n this.state_id = this.id;\n this.state[this.state_id] = this.state[this.state_id] || {};\n } else {\n this.state = null;\n this.state_id = null;\n }\n\n /**\n * Direct access to data layer instances, keyed by data layer ID. Used primarily for introspection/ development.\n * @public\n * @member {Object.}\n */\n this.data_layers = {};\n /**\n * @private\n * @member {String[]}\n */\n this.data_layer_ids_by_z_index = [];\n\n /**\n * Track data requests in progress\n * @member {Promise[]}\n * @private\n */\n this.data_promises = [];\n\n /**\n * @private\n * @member {d3.scale}\n */\n this.x_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y1_scale = null;\n /**\n * @private\n * @member {d3.scale}\n */\n this.y2_scale = null;\n\n /**\n * @private\n * @member {d3.extent}\n */\n this.x_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y1_extent = null;\n /**\n * @private\n * @member {d3.extent}\n */\n this.y2_extent = null;\n\n /**\n * @private\n * @member {Number[]}\n */\n this.x_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y1_ticks = [];\n /**\n * @private\n * @member {Number[]}\n */\n this.y2_ticks = [];\n\n /**\n * A timeout ID as returned by setTimeout\n * @private\n * @member {number}\n */\n this.zoom_timeout = null;\n\n /**\n * Known event hooks that the panel can respond to\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @protected\n * @member {Object}\n */\n this.event_hooks = {};\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* Public methods: intended for direct external manipulation of panel internals */\n\n /**\n * There are several events that a LocusZoom panel can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * To register a hook for any of these events use `panel.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered.\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of the event. Consult documentation for the names of built-in events.\n * @param {function} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n // TODO: Dry plot and panel event code into a shared mixin\n if (typeof event !== 'string') {\n throw new Error(`Unable to register event hook. Event name must be a string: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n if (!this.event_hooks[event]) {\n // We do not validate on known event names, because LZ is allowed to track and emit custom events like \"widget button clicked\".\n this.event_hooks[event] = [];\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Panel}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof event != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n *\n * There is a shorter overloaded form of this method: if the event does not have any data, the second\n * argument can be a boolean to control bubbling\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {string} event A known event name\n * @param {*} [eventData] Data or event description that will be passed to the event listener\n * @param {boolean} [bubble=false] Whether to bubble the event to the parent\n * @returns {Panel}\n */\n emit(event, eventData, bubble) {\n bubble = bubble || false;\n\n // TODO: DRY this with the parent plot implementation. Ensure interfaces remain compatible.\n // TODO: Improve documentation for overloaded method signature (JSDoc may have trouble here)\n if (typeof event != 'string') {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n }\n if (typeof eventData === 'boolean' && arguments.length === 2) {\n // Overloaded method signature: emit(event, bubble)\n bubble = eventData;\n eventData = null;\n }\n const sourceID = this.getBaseId();\n const eventContext = { sourceID: sourceID, target: this, data: eventData || null };\n\n if (this.event_hooks[event]) {\n // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound?\n this.event_hooks[event].forEach((hookToRun) => {\n // By default, any handlers fired here will see the panel as the value of `this`. If a bound function is\n // registered as a handler, the previously bound `this` will override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n }\n\n if (bubble && this.parent) {\n // Even if this event has no listeners locally, it might still have listeners on the parent\n this.parent.emit(event, eventContext);\n }\n return this;\n }\n\n /**\n * Set the title for the panel. If passed an object, will merge the object with the existing layout configuration, so\n * that all or only some of the title layout object's parameters can be customized. If passed null, false, or an empty\n * string, the title DOM element will be set to display: none.\n *\n * @public\n * @param {string|object|null} title The title text, or an object with additional configuration\n * @param {string} title.text Text to display. Since titles are rendered as SVG text, HTML and newlines will not be rendered.\n * @param {number} title.x X-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n * @param {number} title.y Y-offset, in pixels, for the title's text anchor (default left) relative to the top-left corner of the panel.\n NOTE: SVG y values go from the top down, so the SVG origin of (0,0) is in the top left corner.\n * @param {object} title.style CSS styles object to be applied to the title's DOM element.\n * @returns {Panel}\n */\n setTitle(title) {\n if (typeof this.layout.title == 'string') {\n const text = this.layout.title;\n this.layout.title = { text: text, x: 0, y: 0, style: {} };\n }\n if (typeof title == 'string') {\n this.layout.title.text = title;\n } else if (typeof title == 'object' && title !== null) {\n this.layout.title = merge(title, this.layout.title);\n }\n if (this.layout.title.text.length) {\n this.title\n .attr('display', null)\n .attr('x', parseFloat(this.layout.title.x))\n .attr('y', parseFloat(this.layout.title.y))\n .text(this.layout.title.text)\n .call(applyStyles, this.layout.title.style);\n\n } else {\n this.title.attr('display', 'none');\n }\n return this;\n }\n\n /**\n * Create a new data layer from a provided layout object. Should have the keys specified in `DefaultLayout`\n * Will automatically add at the top (depth/z-index) of the panel unless explicitly directed differently\n * in the layout provided.\n *\n * **NOTE**: It is very rare that new data layers are added after a panel is rendered.\n * @public\n * @param {object} layout\n * @returns {BaseDataLayer}\n */\n addDataLayer(layout) {\n\n // Sanity checks\n if (typeof layout !== 'object' || typeof layout.id !== 'string' || !layout.id.length) {\n throw new Error('Invalid data layer layout');\n }\n if (typeof this.data_layers[layout.id] !== 'undefined') {\n throw new Error(`Cannot create data_layer with id [${layout.id}]; data layer with that id already exists in the panel`);\n }\n if (typeof layout.type !== 'string') {\n throw new Error('Invalid data layer type');\n }\n\n // If the layout defines a y axis make sure the axis number is set and is 1 or 2 (default to 1)\n if (typeof layout.y_axis == 'object' && (typeof layout.y_axis.axis == 'undefined' || ![1, 2].includes(layout.y_axis.axis))) {\n layout.y_axis.axis = 1;\n }\n\n // Create the Data Layer\n const data_layer = data_layers.create(layout.type, layout, this);\n\n // Store the Data Layer on the Panel\n this.data_layers[data_layer.id] = data_layer;\n\n // If a discrete z_index was set in the layout then adjust other data layer z_index values to accommodate this one\n if (data_layer.layout.z_index !== null && !isNaN(data_layer.layout.z_index)\n && this.data_layer_ids_by_z_index.length > 0) {\n // Negative z_index values should count backwards from the end, so convert negatives to appropriate values here\n if (data_layer.layout.z_index < 0) {\n data_layer.layout.z_index = Math.max(this.data_layer_ids_by_z_index.length + data_layer.layout.z_index, 0);\n }\n this.data_layer_ids_by_z_index.splice(data_layer.layout.z_index, 0, data_layer.id);\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n } else {\n const length = this.data_layer_ids_by_z_index.push(data_layer.id);\n this.data_layers[data_layer.id].layout.z_index = length - 1;\n }\n\n // Determine if this data layer was already in the layout.data_layers array.\n // If it wasn't, add it. Either way store the layout.data_layers array index on the data_layer.\n let layout_idx = null;\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n if (data_layer_layout.id === data_layer.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.data_layers.push(this.data_layers[data_layer.id].layout) - 1;\n }\n this.data_layers[data_layer.id].layout_idx = layout_idx;\n\n return this.data_layers[data_layer.id];\n }\n\n /**\n * Remove a data layer by id\n * @public\n * @param {string} id\n * @returns {Panel}\n */\n removeDataLayer(id) {\n if (!this.data_layers[id]) {\n throw new Error(`Unable to remove data layer, ID not found: ${id}`);\n }\n\n // Destroy all tooltips for the data layer\n this.data_layers[id].destroyAllTooltips();\n\n // Remove the svg container for the data layer if it exists\n if (this.data_layers[id].svg.container) {\n this.data_layers[id].svg.container.remove();\n }\n\n // Delete the data layer and its presence in the panel layout and state\n this.layout.data_layers.splice(this.data_layers[id].layout_idx, 1);\n delete this.state[this.data_layers[id].state_id];\n delete this.data_layers[id];\n\n // Remove the data_layer id from the z_index array\n this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(id), 1);\n\n // Update layout_idx and layout.z_index values for all remaining data_layers\n this.applyDataLayerZIndexesToDataLayerLayouts();\n this.layout.data_layers.forEach((data_layer_layout, idx) => {\n this.data_layers[data_layer_layout.id].layout_idx = idx;\n });\n\n return this;\n }\n\n /**\n * Clear all selections on all data layers\n * @public\n * @returns {Panel}\n */\n clearSelections() {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus('selected', false);\n });\n return this;\n }\n\n /**\n * Update rendering of this panel whenever an event triggers a redraw. Assumes that the panel has already been\n * prepared the first time via `initialize`\n * @public\n * @returns {Panel}\n */\n render() {\n\n // Position the panel container\n this.svg.container.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`);\n\n // Set size on the clip rect\n this.svg.clipRect\n .attr('width', this.parent_plot.layout.width)\n .attr('height', this.layout.height);\n\n // Set and position the inner border, style if necessary\n this.inner_border\n .attr('x', this.layout.margin.left)\n .attr('y', this.layout.margin.top)\n .attr('width', this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right))\n .attr('height', this.layout.height - (this.layout.margin.top + this.layout.margin.bottom));\n if (this.layout.inner_border) {\n this.inner_border\n .style('stroke-width', 1)\n .style('stroke', this.layout.inner_border);\n }\n\n // Set/update panel title if necessary\n this.setTitle();\n\n // Regenerate all extents\n this.generateExtents();\n\n // Helper function to constrain any procedurally generated vectors (e.g. ranges, extents)\n // Constraints applied here keep vectors from going to infinity or beyond a definable power of ten\n const constrain = function (value, limit_exponent) {\n const neg_min = Math.pow(-10, limit_exponent);\n const neg_max = Math.pow(-10, -limit_exponent);\n const pos_min = Math.pow(10, -limit_exponent);\n const pos_max = Math.pow(10, limit_exponent);\n if (value === Infinity) {\n value = pos_max;\n }\n if (value === -Infinity) {\n value = neg_min;\n }\n if (value === 0) {\n value = pos_min;\n }\n if (value > 0) {\n value = Math.max(Math.min(value, pos_max), pos_min);\n }\n if (value < 0) {\n value = Math.max(Math.min(value, neg_max), neg_min);\n }\n return value;\n };\n\n // Define default and shifted ranges for all axes\n const ranges = {};\n if (this.x_extent) {\n const base_x_range = { start: 0, end: this.layout.cliparea.width };\n if (this.layout.axes.x.range) {\n base_x_range.start = this.layout.axes.x.range.start || base_x_range.start;\n base_x_range.end = this.layout.axes.x.range.end || base_x_range.end;\n }\n ranges.x = [base_x_range.start, base_x_range.end];\n ranges.x_shifted = [base_x_range.start, base_x_range.end];\n }\n if (this.y1_extent) {\n const base_y1_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y1.range) {\n base_y1_range.start = this.layout.axes.y1.range.start || base_y1_range.start;\n base_y1_range.end = this.layout.axes.y1.range.end || base_y1_range.end;\n }\n ranges.y1 = [base_y1_range.start, base_y1_range.end];\n ranges.y1_shifted = [base_y1_range.start, base_y1_range.end];\n }\n if (this.y2_extent) {\n const base_y2_range = { start: this.layout.cliparea.height, end: 0 };\n if (this.layout.axes.y2.range) {\n base_y2_range.start = this.layout.axes.y2.range.start || base_y2_range.start;\n base_y2_range.end = this.layout.axes.y2.range.end || base_y2_range.end;\n }\n ranges.y2 = [base_y2_range.start, base_y2_range.end];\n ranges.y2_shifted = [base_y2_range.start, base_y2_range.end];\n }\n\n // Shift ranges based on any drag or zoom interactions currently underway\n if (this.parent.interaction.panel_id && (this.parent.interaction.panel_id === this.id || this.parent.interaction.linked_panel_ids.includes(this.id))) {\n let anchor, scalar = null;\n if (this.parent.interaction.zooming && typeof this.x_scale == 'function') {\n const current_extent_size = Math.abs(this.x_extent[1] - this.x_extent[0]);\n const current_scaled_extent_size = Math.round(this.x_scale.invert(ranges.x_shifted[1])) - Math.round(this.x_scale.invert(ranges.x_shifted[0]));\n let zoom_factor = this.parent.interaction.zooming.scale;\n const potential_extent_size = Math.floor(current_scaled_extent_size * (1 / zoom_factor));\n if (zoom_factor < 1 && !isNaN(this.parent.layout.max_region_scale)) {\n zoom_factor = 1 / (Math.min(potential_extent_size, this.parent.layout.max_region_scale) / current_scaled_extent_size);\n } else if (zoom_factor > 1 && !isNaN(this.parent.layout.min_region_scale)) {\n zoom_factor = 1 / (Math.max(potential_extent_size, this.parent.layout.min_region_scale) / current_scaled_extent_size);\n }\n const new_extent_size = Math.floor(current_extent_size * zoom_factor);\n anchor = this.parent.interaction.zooming.center - this.layout.margin.left - this.layout.origin.x;\n const offset_ratio = anchor / this.layout.cliparea.width;\n const new_x_extent_start = Math.max(Math.floor(this.x_scale.invert(ranges.x_shifted[0]) - ((new_extent_size - current_scaled_extent_size) * offset_ratio)), 1);\n ranges.x_shifted = [ this.x_scale(new_x_extent_start), this.x_scale(new_x_extent_start + new_extent_size) ];\n } else if (this.parent.interaction.dragging) {\n switch (this.parent.interaction.dragging.method) {\n case 'background':\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n break;\n case 'x_tick':\n if (d3.event && d3.event.shiftKey) {\n ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x;\n ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x;\n } else {\n anchor = this.parent.interaction.dragging.start_x - this.layout.margin.left - this.layout.origin.x;\n scalar = constrain(anchor / (anchor + this.parent.interaction.dragging.dragged_x), 3);\n ranges.x_shifted[0] = 0;\n ranges.x_shifted[1] = Math.max(this.layout.cliparea.width * (1 / scalar), 1);\n }\n break;\n case 'y1_tick':\n case 'y2_tick': {\n const y_shifted = `y${this.parent.interaction.dragging.method[1]}_shifted`;\n if (d3.event && d3.event.shiftKey) {\n ranges[y_shifted][0] = this.layout.cliparea.height + this.parent.interaction.dragging.dragged_y;\n ranges[y_shifted][1] = +this.parent.interaction.dragging.dragged_y;\n } else {\n anchor = this.layout.cliparea.height - (this.parent.interaction.dragging.start_y - this.layout.margin.top - this.layout.origin.y);\n scalar = constrain(anchor / (anchor - this.parent.interaction.dragging.dragged_y), 3);\n ranges[y_shifted][0] = this.layout.cliparea.height;\n ranges[y_shifted][1] = this.layout.cliparea.height - (this.layout.cliparea.height * (1 / scalar));\n }\n }\n }\n }\n }\n\n // Generate scales and ticks for all axes, then render them\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!this[`${axis}_extent`]) {\n return;\n }\n\n // Base Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`])\n .range(ranges[`${axis}_shifted`]);\n\n // Shift the extent\n this[`${axis}_extent`] = [\n this[`${axis}_scale`].invert(ranges[axis][0]),\n this[`${axis}_scale`].invert(ranges[axis][1]),\n ];\n\n // Finalize Scale\n this[`${axis}_scale`] = d3.scaleLinear()\n .domain(this[`${axis}_extent`]).range(ranges[axis]);\n\n // Render axis (and generate ticks as needed)\n this.renderAxis(axis);\n });\n\n // Establish mousewheel zoom event handers on the panel (namespacing not passed through by d3, so not used here)\n if (this.layout.interaction.scroll_to_zoom) {\n const zoom_handler = () => {\n // Look for a shift key press while scrolling to execute.\n // If not present, gracefully raise a notification and allow conventional scrolling\n if (!(d3.event.shiftKey || d3.event.altKey)) {\n if (this.parent._canInteract(this.id)) {\n this.loader.show('Press [SHIFT] or [ALT] while scrolling to zoom').hide(1000);\n }\n return;\n }\n d3.event.preventDefault();\n if (!this.parent._canInteract(this.id)) {\n return;\n }\n const coords = d3.mouse(this.svg.container.node());\n const delta = Math.max(-1, Math.min(1, (d3.event.wheelDelta || -d3.event.detail || -d3.event.deltaY)));\n if (delta === 0) {\n return;\n }\n this.parent.interaction = {\n panel_id: this.id,\n linked_panel_ids: this.getLinkedPanelIds('x'),\n zooming: {\n scale: (delta < 1) ? 0.9 : 1.1,\n center: coords[0],\n },\n };\n this.render();\n this.parent.interaction.linked_panel_ids.forEach((panel_id) => {\n this.parent.panels[panel_id].render();\n });\n if (this.zoom_timeout !== null) {\n clearTimeout(this.zoom_timeout);\n }\n this.zoom_timeout = setTimeout(() => {\n this.parent.interaction = {};\n this.parent.applyState({ start: this.x_extent[0], end: this.x_extent[1] });\n }, 500);\n };\n // FIXME: Consider moving back to d3.zoom and rewriting drag + zoom to use behaviors.\n this.svg.container\n .on('wheel.zoom', zoom_handler)\n .on('mousewheel.zoom', zoom_handler)\n .on('DOMMouseScroll.zoom', zoom_handler);\n }\n\n // Render data layers in order by z-index\n this.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n this.data_layers[data_layer_id].draw().render();\n });\n\n // Rerender legend last (on top of data). A legend must have been defined at the start in order for this to work.\n if (this.legend) {\n this.legend.render();\n }\n return this;\n }\n\n /**\n * Add a \"basic\" loader to a panel. This is rarely used directly: the `show_loading_indicator` panel layout\n * directive is the preferred way to trigger this function. The imperative form is useful if for some reason a\n * loading indicator needs to be added only after first render.\n * This method is just a shortcut for adding the most commonly used type of loading indicator, which appears when\n * data is requested, animates (e.g. shows an infinitely cycling progress bar as opposed to one that loads from\n * 0-100% based on actual load progress), and disappears when new data is loaded and rendered.\n *\n * @protected\n * @listens event:data_requested\n * @listens event:data_rendered\n * @param {Boolean} show_immediately\n * @returns {Panel}\n */\n addBasicLoader(show_immediately = true) {\n if (this.layout.show_loading_indicator && this.initialized) {\n // Prior to LZ 0.13, this function was called only after the plot was first rendered. Now, it is run by default.\n // Some older pages could thus end up adding a loader twice: to avoid duplicate render events,\n // short-circuit if a loader is already present after the first render has finished.\n return this;\n }\n if (show_immediately) {\n this.loader.show('Loading...').animate();\n }\n this.on('data_requested', () => {\n this.loader.show('Loading...').animate();\n });\n this.on('data_rendered', () => {\n this.loader.hide();\n });\n\n // Update layout to reflect new option\n this.layout.show_loading_indicator = true;\n return this;\n }\n\n /************* Private interface: only used internally */\n /** @private */\n applyDataLayerZIndexesToDataLayerLayouts () {\n this.data_layer_ids_by_z_index.forEach((dlid, idx) => {\n this.data_layers[dlid].layout.z_index = idx;\n });\n }\n\n /**\n * @private\n * @returns {string}\n */\n getBaseId () {\n return `${this.parent.id}.${this.id}`;\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const plot_origin = this.parent._getPageOrigin();\n return {\n x: plot_origin.x + this.layout.origin.x,\n y: plot_origin.y + this.layout.origin.y,\n };\n }\n\n /**\n * Prepare the panel for first use by performing parameter validation, creating axes, setting default dimensions,\n * and preparing / positioning data layers as appropriate.\n * @private\n * @returns {Panel}\n */\n initializeLayout() {\n // Set panel dimensions, origin, and margin\n this.setDimensions();\n this.setOrigin();\n this.setMargin();\n\n // Set ranges\n // TODO: Define stub values in constructor\n this.x_range = [0, this.layout.cliparea.width];\n this.y1_range = [this.layout.cliparea.height, 0];\n this.y2_range = [this.layout.cliparea.height, 0];\n\n // Initialize panel axes\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (!Object.keys(this.layout.axes[axis]).length || this.layout.axes[axis].render === false) {\n // The default layout sets the axis to an empty object, so set its render boolean here\n this.layout.axes[axis].render = false;\n } else {\n this.layout.axes[axis].render = true;\n this.layout.axes[axis].label = this.layout.axes[axis].label || null;\n }\n });\n\n // Add data layers (which define x and y extents)\n this.layout.data_layers.forEach((data_layer_layout) => {\n this.addDataLayer(data_layer_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for the panel. If passed with no arguments will calculate optimal size based on layout\n * directives and the available area within the plot. If passed discrete width (number) and height (number) will\n * attempt to resize the panel to them, but may be limited by minimum dimensions defined on the plot or panel.\n *\n * @private\n * @param {number} [width]\n * @param {number} [height]\n * @returns {Panel}\n */\n setDimensions(width, height) {\n if (typeof width != 'undefined' && typeof height != 'undefined') {\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n this.parent.layout.width = Math.round(+width);\n // Ensure that the requested height satisfies all minimum values\n this.layout.height = Math.max(Math.round(+height), this.layout.min_height);\n }\n }\n this.layout.cliparea.width = Math.max(this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n if (this.svg.clipRect) {\n this.svg.clipRect\n .attr('width', this.parent.layout.width)\n .attr('height', this.layout.height);\n }\n if (this.initialized) {\n this.render();\n this.curtain.update();\n this.loader.update();\n this.toolbar.update();\n if (this.legend) {\n this.legend.position();\n }\n }\n return this;\n }\n\n /**\n * Set panel origin on the plot, and re-render as appropriate\n *\n * @private\n * @param {number} x\n * @param {number} y\n * @returns {Panel}\n */\n setOrigin(x, y) {\n if (!isNaN(x) && x >= 0) {\n this.layout.origin.x = Math.max(Math.round(+x), 0);\n }\n if (!isNaN(y) && y >= 0) {\n this.layout.origin.y = Math.max(Math.round(+y), 0);\n }\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Set margins around this panel\n * @private\n * @param {number} top\n * @param {number} right\n * @param {number} bottom\n * @param {number} left\n * @returns {Panel}\n */\n setMargin(top, right, bottom, left) {\n let extra;\n if (!isNaN(top) && top >= 0) {\n this.layout.margin.top = Math.max(Math.round(+top), 0);\n }\n if (!isNaN(right) && right >= 0) {\n this.layout.margin.right = Math.max(Math.round(+right), 0);\n }\n if (!isNaN(bottom) && bottom >= 0) {\n this.layout.margin.bottom = Math.max(Math.round(+bottom), 0);\n }\n if (!isNaN(left) && left >= 0) {\n this.layout.margin.left = Math.max(Math.round(+left), 0);\n }\n // If the specified margins are greater than the available width, then shrink the margins.\n if (this.layout.margin.top + this.layout.margin.bottom > this.layout.height) {\n extra = Math.floor(((this.layout.margin.top + this.layout.margin.bottom) - this.layout.height) / 2);\n this.layout.margin.top -= extra;\n this.layout.margin.bottom -= extra;\n }\n if (this.layout.margin.left + this.layout.margin.right > this.parent_plot.layout.width) {\n extra = Math.floor(((this.layout.margin.left + this.layout.margin.right) - this.parent_plot.layout.width) / 2);\n this.layout.margin.left -= extra;\n this.layout.margin.right -= extra;\n }\n ['top', 'right', 'bottom', 'left'].forEach((m) => {\n this.layout.margin[m] = Math.max(this.layout.margin[m], 0);\n });\n this.layout.cliparea.width = Math.max(this.parent_plot.layout.width - (this.layout.margin.left + this.layout.margin.right), 0);\n this.layout.cliparea.height = Math.max(this.layout.height - (this.layout.margin.top + this.layout.margin.bottom), 0);\n this.layout.cliparea.origin.x = this.layout.margin.left;\n this.layout.cliparea.origin.y = this.layout.margin.top;\n\n if (this.initialized) {\n this.render();\n }\n return this;\n }\n\n /**\n * Prepare the first rendering of the panel. This includes drawing the individual data layers, but also creates shared\n * elements such as axes, title, and loader/curtain.\n * @private\n * @returns {Panel}\n */\n initialize() {\n\n // Append a container group element to house the main panel group element and the clip path\n // Position with initial layout parameters\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.append('g')\n .attr('id', `${base_id}.panel_container`)\n .attr('transform', `translate(${this.layout.origin.x || 0}, ${this.layout.origin.y || 0})`);\n\n // Append clip path to the parent svg element, size with initial layout parameters\n const clipPath = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`);\n this.svg.clipRect = clipPath.append('rect')\n .attr('width', this.parent_plot.layout.width)\n .attr('height', this.layout.height);\n\n // Append svg group for rendering all panel child elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.panel`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n // Add curtain and loader to the panel\n /**\n * @protected\n * @member {Object}\n */\n this.curtain = generateCurtain.call(this);\n /**\n * @protected\n * @member {Object}\n */\n this.loader = generateLoader.call(this);\n\n if (this.layout.show_loading_indicator) {\n // Activate the loading indicator prior to first render, and only show when data is loading\n this.addBasicLoader(false);\n }\n\n /**\n * Create the toolbar object and hang widgets on it as defined by panel layout\n * @protected\n * @member {Toolbar}\n */\n this.toolbar = new Toolbar(this);\n\n // Inner border\n this.inner_border = this.svg.group.append('rect')\n .attr('class', 'lz-panel-background')\n .on('click', () => {\n if (this.layout.background_click === 'clear_selections') {\n this.clearSelections();\n }\n });\n\n // Add the title\n /**\n * @private\n * @member {Element}\n */\n this.title = this.svg.group.append('text').attr('class', 'lz-panel-title');\n if (typeof this.layout.title != 'undefined') {\n this.setTitle();\n }\n\n // Initialize Axes\n this.svg.x_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.x_axis`)\n .attr('class', 'lz-x lz-axis');\n if (this.layout.axes.x.render) {\n this.svg.x_axis_label = this.svg.x_axis.append('text')\n .attr('class', 'lz-x lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y1_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y1_axis`).attr('class', 'lz-y lz-y1 lz-axis');\n if (this.layout.axes.y1.render) {\n this.svg.y1_axis_label = this.svg.y1_axis.append('text')\n .attr('class', 'lz-y1 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n this.svg.y2_axis = this.svg.group.append('g')\n .attr('id', `${base_id}.y2_axis`)\n .attr('class', 'lz-y lz-y2 lz-axis');\n if (this.layout.axes.y2.render) {\n this.svg.y2_axis_label = this.svg.y2_axis.append('text')\n .attr('class', 'lz-y2 lz-axis lz-label')\n .attr('text-anchor', 'middle');\n }\n\n // Initialize child Data Layers\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].initialize();\n });\n\n /**\n * Legend object, as defined by panel layout and child data layer layouts\n * @protected\n * @member {Legend}\n * */\n this.legend = null;\n if (this.layout.legend) {\n this.legend = new Legend(this);\n }\n\n // Establish panel background drag interaction mousedown event handler (on the panel background)\n if (this.layout.interaction.drag_background_to_pan) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const mousedown = () => this.parent.startDrag(this, 'background');\n this.svg.container.select('.lz-panel-background')\n .on(`mousedown${namespace}.background`, mousedown)\n .on(`touchstart${namespace}.background`, mousedown);\n }\n\n return this;\n }\n\n /**\n * Refresh the sort order of all data layers (called by data layer moveForward and moveBack methods)\n * @private\n */\n resortDataLayers() {\n const sort = [];\n this.data_layer_ids_by_z_index.forEach((id) => {\n sort.push(this.data_layers[id].layout.z_index);\n });\n this.svg.group\n .selectAll('g.lz-data_layer-container')\n .data(sort)\n .sort(d3.ascending);\n this.applyDataLayerZIndexesToDataLayerLayouts();\n }\n\n /**\n * Get an array of panel IDs that are axis-linked to this panel\n * @private\n * @param {('x'|'y1'|'y2')} axis\n * @returns {Array}\n */\n getLinkedPanelIds(axis) {\n axis = axis || null;\n const linked_panel_ids = [];\n if (!['x', 'y1', 'y2'].includes(axis)) {\n return linked_panel_ids;\n }\n if (!this.layout.interaction[`${axis}_linked`]) {\n return linked_panel_ids;\n }\n this.parent.panel_ids_by_y_index.forEach((panel_id) => {\n if (panel_id !== this.id && this.parent.panels[panel_id].layout.interaction[`${axis}_linked`]) {\n linked_panel_ids.push(panel_id);\n }\n });\n return linked_panel_ids;\n }\n\n /**\n * Move a panel up relative to others by y-index\n * @private\n * @returns {Panel}\n */\n moveUp() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index - 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index - 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index - 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * Move a panel down (y-axis) relative to others in the plot\n * @private\n * @returns {Panel}\n */\n moveDown() {\n if (this.parent.panel_ids_by_y_index[this.layout.y_index + 1]) {\n this.parent.panel_ids_by_y_index[this.layout.y_index] = this.parent.panel_ids_by_y_index[this.layout.y_index + 1];\n this.parent.panel_ids_by_y_index[this.layout.y_index + 1] = this.id;\n this.parent.applyPanelYIndexesToPanelLayouts();\n this.parent.positionPanels();\n }\n return this;\n }\n\n /**\n * When the parent plot changes state, adjust the panel accordingly. For example, this may include fetching new data\n * from the API as the viewing region changes\n * @private\n * @fires event:data_requested\n * @fires event:layout_changed\n * @fires event:data_rendered\n * @returns {Promise}\n */\n reMap() {\n this.emit('data_requested');\n this.data_promises = [];\n\n // Remove any previous error messages before attempting to load new data\n this.curtain.hide();\n // Trigger reMap on each Data Layer\n for (let id in this.data_layers) {\n try {\n this.data_promises.push(this.data_layers[id].reMap());\n } catch (error) {\n console.error(error);\n this.curtain.show(error.message || error);\n }\n }\n // When all finished trigger a render\n return Promise.all(this.data_promises)\n .then(() => {\n this.initialized = true;\n this.render();\n this.emit('layout_changed', true);\n this.emit('data_rendered');\n })\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n });\n }\n\n /**\n * Iterate over data layers to generate panel axis extents\n * @private\n * @returns {Panel}\n */\n generateExtents() {\n\n // Reset extents\n ['x', 'y1', 'y2'].forEach((axis) => {\n this[`${axis}_extent`] = null;\n });\n\n // Loop through the data layers\n for (let id in this.data_layers) {\n\n const data_layer = this.data_layers[id];\n\n // If defined and not decoupled, merge the x extent of the data layer with the panel's x extent\n if (data_layer.layout.x_axis && !data_layer.layout.x_axis.decoupled) {\n this.x_extent = d3.extent((this.x_extent || []).concat(data_layer.getAxisExtent('x')));\n }\n\n // If defined and not decoupled, merge the y extent of the data layer with the panel's appropriate y extent\n if (data_layer.layout.y_axis && !data_layer.layout.y_axis.decoupled) {\n const y_axis = `y${data_layer.layout.y_axis.axis}`;\n this[`${y_axis}_extent`] = d3.extent((this[`${y_axis}_extent`] || []).concat(data_layer.getAxisExtent('y')));\n }\n\n }\n\n // Override x_extent from state if explicitly defined to do so\n if (this.layout.axes.x && this.layout.axes.x.extent === 'state') {\n this.x_extent = [ this.state.start, this.state.end ];\n }\n return this;\n }\n\n /**\n * Generate an array of ticks for an axis. These ticks are generated in one of three ways (highest wins):\n * 1. An array of specific tick marks\n * 2. Query each data layer for what ticks are appropriate, and allow a panel-level tick configuration parameter\n * object to override the layer's default presentation settings\n * 3. Generate generic tick marks based on the extent of the data\n *\n * @private\n * @param {('x'|'y1'|'y2')} axis The string identifier of the axis\n * @returns {Number[]|Object[]} TODO: number format?\n * An array of numbers: interpreted as an array of axis value offsets for positioning.\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n generateTicks(axis) {\n\n // Parse an explicit 'ticks' attribute in the axis layout\n if (this.layout.axes[axis].ticks) {\n const layout = this.layout.axes[axis];\n\n const baseTickConfig = layout.ticks;\n if (Array.isArray(baseTickConfig)) {\n // Array of specific ticks hard-coded into a panel will override any ticks that an individual layer might specify\n return baseTickConfig;\n }\n\n if (typeof baseTickConfig === 'object') {\n // If the layout specifies base configuration for ticks- but without specific positions- then ask each\n // data layer to report the tick marks that it thinks it needs\n // TODO: Few layers currently need to specify custom ticks (which is ok!). But if it becomes common, consider adding mechanisms to deduplicate ticks across layers\n const self = this;\n\n // Pass any layer-specific customizations for how ticks are calculated. (styles are overridden separately)\n const config = { position: baseTickConfig.position };\n\n const combinedTicks = this.data_layer_ids_by_z_index.reduce((acc, data_layer_id) => {\n const nextLayer = self.data_layers[data_layer_id];\n return acc.concat(nextLayer.getTicks(axis, config));\n }, []);\n\n return combinedTicks.map((item) => {\n // The layer makes suggestions, but tick configuration params specified on the panel take precedence\n let itemConfig = {};\n itemConfig = merge(itemConfig, baseTickConfig);\n return merge(itemConfig, item);\n });\n }\n }\n\n // If no other configuration is provided, attempt to generate ticks from the extent\n if (this[`${axis}_extent`]) {\n return prettyTicks(this[`${axis}_extent`], 'both');\n }\n return [];\n }\n\n /**\n * Render ticks for a particular axis\n * @private\n * @param {('x'|'y1'|'y2')} axis The identifier of the axes\n * @returns {Panel}\n */\n renderAxis(axis) {\n\n if (!['x', 'y1', 'y2'].includes(axis)) {\n throw new Error(`Unable to render axis; invalid axis identifier: ${axis}`);\n }\n\n const canRender = this.layout.axes[axis].render\n && typeof this[`${axis}_scale`] == 'function'\n && !isNaN(this[`${axis}_scale`](0));\n\n // If the axis has already been rendered then check if we can/can't render it\n // Make sure the axis element is shown/hidden to suit\n if (this[`${axis}_axis`]) {\n this.svg.container.select(`g.lz-axis.lz-${axis}`)\n .style('display', canRender ? null : 'none');\n }\n\n if (!canRender) {\n return this;\n }\n\n // Axis-specific values to plug in where needed\n const axis_params = {\n x: {\n position: `translate(${this.layout.margin.left}, ${this.layout.height - this.layout.margin.bottom})`,\n orientation: 'bottom',\n label_x: this.layout.cliparea.width / 2,\n label_y: (this.layout.axes[axis].label_offset || 0),\n label_rotate: null,\n },\n y1: {\n position: `translate(${this.layout.margin.left}, ${this.layout.margin.top})`,\n orientation: 'left',\n label_x: -1 * (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n y2: {\n position: `translate(${this.parent_plot.layout.width - this.layout.margin.right}, ${this.layout.margin.top})`,\n orientation: 'right',\n label_x: (this.layout.axes[axis].label_offset || 0),\n label_y: this.layout.cliparea.height / 2,\n label_rotate: -90,\n },\n };\n\n // Generate Ticks\n this[`${axis}_ticks`] = this.generateTicks(axis);\n\n // Determine if the ticks are all numbers (d3-automated tick rendering) or not (manual tick rendering)\n const ticksAreAllNumbers = ((ticks) => {\n for (let i = 0; i < ticks.length; i++) {\n if (isNaN(ticks[i])) {\n return false;\n }\n }\n return true;\n })(this[`${axis}_ticks`]);\n\n // Initialize the axis; set scale and orientation\n let axis_factory;\n switch (axis_params[axis].orientation) {\n case 'right':\n axis_factory = d3.axisRight;\n break;\n case 'left':\n axis_factory = d3.axisLeft;\n break;\n case 'bottom':\n axis_factory = d3.axisBottom;\n break;\n default:\n throw new Error('Unrecognized axis orientation');\n }\n\n this[`${axis}_axis`] = axis_factory(this[`${axis}_scale`])\n .tickPadding(3);\n\n // Set tick values and format\n if (ticksAreAllNumbers) {\n this[`${axis}_axis`].tickValues(this[`${axis}_ticks`]);\n if (this.layout.axes[axis].tick_format === 'region') {\n this[`${axis}_axis`].tickFormat((d) => positionIntToString(d, 6));\n }\n } else {\n let ticks = this[`${axis}_ticks`].map((t) => {\n return (t[axis.substr(0, 1)]);\n });\n this[`${axis}_axis`].tickValues(ticks)\n .tickFormat((t, i) => {\n return this[`${axis}_ticks`][i].text;\n });\n }\n\n // Position the axis in the SVG and apply the axis construct\n this.svg[`${axis}_axis`]\n .attr('transform', axis_params[axis].position)\n .call(this[`${axis}_axis`]);\n\n // If necessary manually apply styles and transforms to ticks as specified by the layout\n if (!ticksAreAllNumbers) {\n const tick_selector = d3.selectAll(`g#${this.getBaseId().replace('.', '\\\\.')}\\\\.${axis}_axis g.tick`);\n const panel = this;\n tick_selector.each(function (d, i) {\n const selector = d3.select(this).select('text');\n if (panel[`${axis}_ticks`][i].style) {\n applyStyles(selector, panel[`${axis}_ticks`][i].style);\n }\n if (panel[`${axis}_ticks`][i].transform) {\n selector.attr('transform', panel[`${axis}_ticks`][i].transform);\n }\n });\n }\n\n // Render the axis label if necessary\n const label = this.layout.axes[axis].label || null;\n if (label !== null) {\n this.svg[`${axis}_axis_label`]\n .attr('x', axis_params[axis].label_x)\n .attr('y', axis_params[axis].label_y)\n .text(parseFields(label, this.state))\n .attr('fill', 'currentColor');\n if (axis_params[axis].label_rotate !== null) {\n this.svg[`${axis}_axis_label`]\n .attr('transform', `rotate(${axis_params[axis].label_rotate} ${axis_params[axis].label_x}, ${axis_params[axis].label_y})`);\n }\n }\n\n // Attach interactive handlers to ticks as needed\n ['x', 'y1', 'y2'].forEach((axis) => {\n if (this.layout.interaction[`drag_${axis}_ticks_to_scale`]) {\n const namespace = `.${this.parent.id}.${this.id}.interaction.drag`;\n const tick_mouseover = function() {\n if (typeof d3.select(this).node().focus == 'function') {\n d3.select(this).node().focus();\n }\n let cursor = (axis === 'x') ? 'ew-resize' : 'ns-resize';\n if (d3.event && d3.event.shiftKey) {\n cursor = 'move';\n }\n d3.select(this)\n .style('font-weight', 'bold')\n .style('cursor', cursor )\n .on(`keydown${namespace}`, tick_mouseover)\n .on(`keyup${namespace}`, tick_mouseover);\n };\n this.svg.container.selectAll(`.lz-axis.lz-${axis} .tick text`)\n .attr('tabindex', 0) // necessary to make the tick focusable so keypress events can be captured\n .on(`mouseover${namespace}`, tick_mouseover)\n .on(`mouseout${namespace}`, function() {\n d3.select(this)\n .style('font-weight', 'normal')\n .on(`keydown${namespace}`, null)\n .on(`keyup${namespace}`, null);\n })\n .on(`mousedown${namespace}`, () => {\n this.parent.startDrag(this, `${axis}_tick`);\n });\n }\n });\n\n return this;\n }\n\n /**\n * Force the height of this panel to the largest absolute height of the data in\n * all child data layers (if not null for any child data layers)\n * @private\n * @param {number|null} [target_height] A target height, which will be used in situations when the expected height can be\n * pre-calculated (eg when the layers are transitioning)\n */\n scaleHeightToData(target_height) {\n target_height = +target_height || null;\n if (target_height === null) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n const dh = this.data_layers[id].getAbsoluteDataHeight();\n if (+dh) {\n if (target_height === null) {\n target_height = +dh;\n } else {\n target_height = Math.max(target_height, +dh);\n }\n }\n });\n }\n if (+target_height) {\n target_height += +this.layout.margin.top + +this.layout.margin.bottom;\n // FIXME: plot.setDimensions calls panel.setDimensions (though without arguments)\n this.setDimensions(this.parent_plot.layout.width, target_height);\n this.parent.setDimensions();\n this.parent.positionPanels();\n }\n }\n\n /**\n * Set/unset element statuses across all data layers\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n */\n setAllElementStatus(status, toggle) {\n this.data_layer_ids_by_z_index.forEach((id) => {\n this.data_layers[id].setAllElementStatus(status, toggle);\n });\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n\n // Set/unset status for all elements\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n Panel.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n */\n /**\n * @private\n * @function unhideAllElements\n */\n Panel.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {Panel as default};\n","/**\n * Helpers that control the display of individual points and field values\n * @module\n * @private\n */\nimport * as d3 from 'd3';\n\nimport Field from '../data/field';\nimport Plot from '../components/plot';\nimport {applyStyles} from './common';\n\n\n/**\n * Convert an integer chromosome position to an SI string representation (e.g. 23423456 => \"23.42\" (Mb))\n * @param {Number} pos Position\n * @param {Number} [exp] Exponent to use for the returned string, eg 6=> MB. If not specified, will attempt to guess\n * the most appropriate SI prefix based on the number provided.\n * @param {Boolean} [suffix=false] Whether or not to append a suffix (e.g. \"Mb\") to the end of the returned string\n * @returns {string}\n */\nfunction positionIntToString(pos, exp, suffix) {\n const exp_symbols = { 0: '', 3: 'K', 6: 'M', 9: 'G' };\n suffix = suffix || false;\n if (isNaN(exp) || exp === null) {\n const log = Math.log(pos) / Math.LN10;\n exp = Math.min(Math.max(log - (log % 3), 0), 9);\n }\n const places_exp = exp - Math.floor((Math.log(pos) / Math.LN10).toFixed(exp + 3));\n const min_exp = Math.min(Math.max(exp, 0), 2);\n const places = Math.min(Math.max(places_exp, min_exp), 12);\n let ret = `${(pos / Math.pow(10, exp)).toFixed(places)}`;\n if (suffix && typeof exp_symbols[exp] !== 'undefined') {\n ret += ` ${exp_symbols[exp]}b`;\n }\n return ret;\n}\n\n/**\n * Convert an SI string chromosome position to an integer representation (e.g. \"5.8 Mb\" => 58000000)\n * @param {String} p The chromosome position\n * @returns {Number}\n */\nfunction positionStringToInt(p) {\n let val = p.toUpperCase();\n val = val.replace(/,/g, '');\n const suffixre = /([KMG])[B]*$/;\n const suffix = suffixre.exec(val);\n let mult = 1;\n if (suffix) {\n if (suffix[1] === 'M') {\n mult = 1e6;\n } else if (suffix[1] === 'G') {\n mult = 1e9;\n } else {\n mult = 1e3; //K\n }\n val = val.replace(suffixre, '');\n }\n val = Number(val) * mult;\n return val;\n}\n\n/**\n * Generate a \"pretty\" set of ticks (multiples of 1, 2, or 5 on the same order of magnitude for the range)\n * Based on R's \"pretty\" function: https://github.com/wch/r-source/blob/b156e3a711967f58131e23c1b1dc1ea90e2f0c43/src/appl/pretty.c\n * @param {Number[]} range A two-item array specifying [low, high] values for the axis range\n * @param {('low'|'high'|'both'|'neither')} [clip_range='neither'] What to do if first and last generated ticks extend\n * beyond the range. Set this to \"low\", \"high\", \"both\", or \"neither\" to clip the first (low) or last (high) tick to\n * be inside the range or allow them to extend beyond.\n * e.g. \"low\" will clip the first (low) tick if it extends beyond the low end of the range but allow the\n * last (high) tick to extend beyond the range. \"both\" clips both ends, \"neither\" allows both to extend beyond.\n * @param {Number} [target_tick_count=5] The approximate number of ticks you would like to be returned; may not be exact\n * @returns {Number[]}\n */\nfunction prettyTicks(range, clip_range, target_tick_count) {\n if (typeof target_tick_count == 'undefined' || isNaN(parseInt(target_tick_count))) {\n target_tick_count = 5;\n }\n target_tick_count = +target_tick_count;\n\n const min_n = target_tick_count / 3;\n const shrink_sml = 0.75;\n const high_u_bias = 1.5;\n const u5_bias = 0.5 + 1.5 * high_u_bias;\n\n const d = Math.abs(range[0] - range[1]);\n let c = d / target_tick_count;\n if ((Math.log(d) / Math.LN10) < -2) {\n c = (Math.max(Math.abs(d)) * shrink_sml) / min_n;\n }\n\n const base = Math.pow(10, Math.floor(Math.log(c) / Math.LN10));\n let base_toFixed = 0;\n if (base < 1 && base !== 0) {\n base_toFixed = Math.abs(Math.round(Math.log(base) / Math.LN10));\n }\n\n let unit = base;\n if ( ((2 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 2 * base;\n if ( ((5 * base) - c) < (u5_bias * (c - unit)) ) {\n unit = 5 * base;\n if ( ((10 * base) - c) < (high_u_bias * (c - unit)) ) {\n unit = 10 * base;\n }\n }\n }\n\n let ticks = [];\n let i = parseFloat((Math.floor(range[0] / unit) * unit).toFixed(base_toFixed));\n while (i < range[1]) {\n ticks.push(i);\n i += unit;\n if (base_toFixed > 0) {\n i = parseFloat(i.toFixed(base_toFixed));\n }\n }\n ticks.push(i);\n\n if (typeof clip_range == 'undefined' || ['low', 'high', 'both', 'neither'].indexOf(clip_range) === -1) {\n clip_range = 'neither';\n }\n if (clip_range === 'low' || clip_range === 'both') {\n if (ticks[0] < range[0]) {\n ticks = ticks.slice(1);\n }\n }\n if (clip_range === 'high' || clip_range === 'both') {\n if (ticks[ticks.length - 1] > range[1]) {\n ticks.pop();\n }\n }\n\n return ticks;\n}\n\n/**\n * Replace placeholders in an html string with field values defined in a data object\n * Only works on scalar values in data! Will ignore non-scalars. This is useful in, eg, tooltip templates.\n *\n * NOTE: Trusts content exactly as given. XSS prevention is the responsibility of the implementer.\n * @param {String} html A placeholder string in which to substitute fields. Supports several template options:\n * `{{field_name}}` is a variable placeholder for the value of `field_name` from the provided data\n * `{{#if field_name}} Conditional text {{/if}}` will insert the contents of the tag only if the value exists.\n * This can be used with namespaced values, `{{#if assoc:field}}`; any dynamic namespacing will be applied when the\n * layout is first retrieved. For numbers, transforms like `{{#if field|is_numeric}}` can help to ensure that 0\n * values are displayed when expected.\n * Can optionally take an else block, useful for things like toggle buttons: {{#if field}} ... {{#else}} ... {{/if}}\n * @param {Object} data The data associated with a particular element. Eg, tooltips often appear over a specific point.\n * @param {Object|null} extra Any additional fields (eg element annotations) associated with the specified datum\n * @returns {string}\n */\nfunction parseFields(html, data, extra) {\n if (typeof data != 'object') {\n throw new Error('invalid arguments: data is not an object');\n }\n if (typeof html != 'string') {\n throw new Error('invalid arguments: html is not a string');\n }\n // `tokens` is like [token,...]\n // `token` is like {text: '...'} or {variable: 'foo|bar'} or {condition: 'foo|bar'} or {close: 'if'}\n const tokens = [];\n const regex = /{{(?:(#if )?([A-Za-z0-9_:|]+)|(#else)|(\\/if))}}/;\n while (html.length > 0) {\n const m = regex.exec(html);\n if (!m) {\n tokens.push({text: html});\n html = '';\n } else if (m.index !== 0) {\n tokens.push({text: html.slice(0, m.index)});\n html = html.slice(m.index);\n } else if (m[1] === '#if ') {\n tokens.push({condition: m[2]});\n html = html.slice(m[0].length);\n } else if (m[2]) {\n tokens.push({variable: m[2]});\n html = html.slice(m[0].length);\n } else if (m[3] === '#else') {\n tokens.push({branch: 'else'});\n html = html.slice(m[0].length);\n } else if (m[4] === '/if') {\n tokens.push({close: 'if'});\n html = html.slice(m[0].length);\n } else {\n console.error(`Error tokenizing tooltip when remaining template is ${JSON.stringify(html)} and previous tokens are ${JSON.stringify(tokens)} and current regex match is ${JSON.stringify([m[1], m[2], m[3]])}`);\n html = html.slice(m[0].length);\n }\n }\n const astify = function () {\n const token = tokens.shift();\n if (typeof token.text !== 'undefined' || token.variable) {\n return token;\n } else if (token.condition) {\n let dest = token.then = [];\n token.else = [];\n // Inside an if block, consume all tokens related to text and/or else block\n while (tokens.length > 0) {\n if (tokens[0].close === 'if') {\n tokens.shift();\n break;\n }\n if (tokens[0].branch === 'else') {\n tokens.shift();\n dest = token.else;\n }\n dest.push(astify());\n }\n return token;\n } else {\n console.error(`Error making tooltip AST due to unknown token ${JSON.stringify(token)}`);\n return { text: '' };\n }\n };\n // `ast` is like [thing,...]\n // `thing` is like {text: \"...\"} or {variable:\"foo|bar\"} or {condition: \"foo|bar\", then:[thing,...]}\n const ast = [];\n while (tokens.length > 0) {\n ast.push(astify());\n }\n\n const resolve = function (variable) {\n if (!Object.prototype.hasOwnProperty.call(resolve.cache, variable)) {\n resolve.cache[variable] = (new Field(variable)).resolve(data, extra);\n }\n return resolve.cache[variable];\n };\n resolve.cache = {};\n const render_node = function (node) {\n if (typeof node.text !== 'undefined') {\n return node.text;\n } else if (node.variable) {\n try {\n const value = resolve(node.variable);\n if (['string', 'number', 'boolean'].indexOf(typeof value) !== -1) {\n return value;\n }\n if (value === null) {\n return '';\n }\n } catch (error) {\n console.error(`Error while processing variable ${JSON.stringify(node.variable)}`);\n }\n return `{{${node.variable}}}`;\n } else if (node.condition) {\n try {\n const condition = resolve(node.condition);\n if (condition) {\n return node.then.map(render_node).join('');\n } else if (node.else) {\n return node.else.map(render_node).join('');\n }\n } catch (error) {\n console.error(`Error while processing condition ${JSON.stringify(node.variable)}`);\n }\n return '';\n } else {\n console.error(`Error rendering tooltip due to unknown AST node ${JSON.stringify(node)}`);\n }\n };\n return ast.map(render_node).join('');\n}\n\n/**\n * Populate a single element with a LocusZoom plot. This is the primary means of generating a new plot, and is part\n * of the public interface for LocusZoom.\n * @alias module:LocusZoom~populate\n * @public\n * @param {String|d3.selection} selector CSS selector for the container element where the plot will be mounted. Any pre-existing\n * content in the container will be completely replaced.\n * @param {module:LocusZoom~DataSources} datasource Ensemble of data providers used by the plot\n * @param {Object} layout A JSON-serializable object of layout configuration parameters\n * @returns {Plot} The newly created plot instance\n */\nfunction populate(selector, datasource, layout) {\n if (typeof selector == 'undefined') {\n throw new Error('LocusZoom.populate selector not defined');\n }\n // Empty the selector of any existing content\n d3.select(selector).html('');\n let plot;\n d3.select(selector).call(function(target) {\n // Require each containing element have an ID. If one isn't present, create one.\n if (typeof target.node().id == 'undefined') {\n let iterator = 0;\n while (!d3.select(`#lz-${iterator}`).empty()) {\n iterator++;\n }\n target.attr('id', `#lz-${iterator}`);\n }\n // Create the plot\n plot = new Plot(target.node().id, datasource, layout);\n plot.container = target.node();\n // Detect HTML `data-region` attribute, and use it to fill in state values if present\n if (typeof target.node().dataset !== 'undefined' && typeof target.node().dataset.region !== 'undefined') {\n const parsed_state = parsePositionQuery(target.node().dataset.region);\n Object.keys(parsed_state).forEach(function(key) {\n plot.state[key] = parsed_state[key];\n });\n }\n // Add an SVG to the div and set its dimensions\n plot.svg = d3.select(`div#${plot.id}`)\n .append('svg')\n .attr('version', '1.1')\n .attr('xmlns', 'http://www.w3.org/2000/svg')\n .attr('id', `${plot.id}_svg`)\n .attr('class', 'lz-locuszoom')\n .call(applyStyles, plot.layout.style);\n\n plot.setDimensions();\n plot.positionPanels();\n // Initialize the plot\n plot.initialize();\n // If the plot has defined data sources then trigger its first mapping based on state values\n if (datasource) {\n plot.refresh();\n }\n });\n return plot;\n}\n\n/**\n * Parse region queries into their constituent parts\n * @param {String} x A chromosome position query. May be any of the forms `chr:start-end`, `chr:center+offset`,\n * or `chr:pos`\n * @returns {{chr:*, start: *, end:*} | {chr:*, position:*}}\n */\nfunction parsePositionQuery(x) {\n const chrposoff = /^(\\w+):([\\d,.]+[kmgbKMGB]*)([-+])([\\d,.]+[kmgbKMGB]*)$/;\n const chrpos = /^(\\w+):([\\d,.]+[kmgbKMGB]*)$/;\n let match = chrposoff.exec(x);\n if (match) {\n if (match[3] === '+') {\n const center = positionStringToInt(match[2]);\n const offset = positionStringToInt(match[4]);\n return {\n chr:match[1],\n start: center - offset,\n end: center + offset,\n };\n } else {\n return {\n chr: match[1],\n start: positionStringToInt(match[2]),\n end: positionStringToInt(match[4]),\n };\n }\n }\n match = chrpos.exec(x);\n if (match) {\n return {\n chr:match[1],\n position: positionStringToInt(match[2]),\n };\n }\n return null;\n}\n\nexport { parseFields, parsePositionQuery, populate, positionIntToString, positionStringToInt, prettyTicks };\n","import * as d3 from 'd3';\n\nimport {deepCopy, merge} from '../helpers/layouts';\nimport Requester from '../data/requester';\nimport Toolbar from './toolbar';\nimport Panel from './panel';\nimport {generateCurtain, generateLoader} from '../helpers/common';\n\n/**\n * Default/ expected configuration parameters for basic plotting; most plots will override\n *\n * @memberof Plot\n * @protected\n * @static\n * @type {Object}\n */\nconst default_layout = {\n state: {},\n width: 800,\n min_width: 400,\n min_region_scale: null,\n max_region_scale: null,\n responsive_resize: false,\n panels: [],\n toolbar: {\n widgets: [],\n },\n panel_boundaries: true,\n mouse_guide: true,\n};\n\n\n/**\n * Fields common to every event emitted by LocusZoom. This is not an actual event that should ever be used directly;\n * see list below.\n *\n * Note: plot-level listeners *can* be defined for this event, but you should almost never do this.\n * Use the most specific event name to describe the thing you are interested in.\n *\n * Listening to 'any_lz_event' is only for advanced usages, such as proxying (repeating) LZ behavior to a piece of\n * wrapper code. One example is converting all LocusZoom events to vue.js events.\n *\n * @event any_lz_event\n * @type {object}\n * @property {string} sourceID The fully qualified ID of the entity that originated the event, eg `lz-plot.association`\n * @property {Plot|Panel} target A reference to the plot or panel instance that originated the event.\n * @property {object|null} data Additional data provided. (see event-specific documentation)\n */\n\n/**\n * A panel was removed from the plot. Commonly initiated by the \"remove panel\" toolbar widget.\n * @event panel_removed\n * @property {string} data The id of the panel that was removed (eg 'genes')\n * @see event:any_lz_event\n */\n\n/**\n * A request for new or cached data was initiated. This can be used for, eg, showing data loading indicators.\n * @event data_requested\n * @see event:any_lz_event\n */\n\n/**\n * A request for new data has completed, and all data has been rendered in the plot.\n * @event data_rendered\n * @see event:any_lz_event\n */\n\n/**\n * An action occurred that changed, or could change, the layout.\n * Many rerendering operations can fire this event and it is somewhat generic: it includes resize, highlight,\n * and rerender on new data.\n * Caution: Direct layout mutations might not be captured by this event. It is deprecated due to its limited utility.\n * @event layout_changed\n * @deprecated\n * @see event:any_lz_event\n */\n\n/**\n * The user has requested any state changes, eg via `plot.applyState`. This reports the original requested values even\n * if they are overridden by plot logic. Only triggered when a state change causes a re-render.\n * @event state_changed\n * @property {object} data The set of all state changes requested\n * @see event:any_lz_event\n * @see {@link event:region_changed} for a related event that provides more accurate information in some cases\n */\n\n/**\n * The plot region has changed. Reports the actual coordinates of the plot after the zoom event. If plot.applyState is\n * called with an invalid region (eg zooming in or out too far), this reports the actual final coordinates, not what was requested.\n * The actual coordinates are subject to region min/max, etc.\n * @event region_changed\n * @property {object} data The {chr, start, end} coordinates of the requested region.\n * @see event:any_lz_event\n */\n\n/**\n * Indicate whether the element was selected (or unselected)\n * @event element_selection\n * @property {object} data An object with keys { element, active }, representing the datum bound to the element and the\n * selection status (boolean)\n * @see {@link event:element_clicked} if you are interested in tracking clicks that result in other behaviors, like links\n * @see event:any_lz_event\n */\n\n/**\n * Indicates whether an element was clicked. (regardless of the behavior associated with clicking)\n * @event element_clicked\n * @see {@link event:element_selection} for a more specific and more frequently useful event\n * @see event:any_lz_event\n */\n\n/**\n * Indicate whether a match was requested from within a data layer.\n * @event match_requested\n * @property {object} data An object of `{value, active}` representing the scalar value to be matched and whether a match is\n * being initiated or canceled\n * @see event:any_lz_event\n */\n\n/**\n * Check that position fields (chr, start, end) are provided where appropriate, and ensure that the plot fits within\n * any constraints specified by the layout\n *\n * This function has side effects; it mutates the proposed state in order to meet certain bounds checks etc.\n * @private\n * @param {Object} new_state\n * @param {Number} new_state.chr\n * @param {Number} new_state.start\n * @param {Number} new_state.end\n * @param {Object} layout\n * @returns {*|{}}\n */\nfunction _updateStatePosition(new_state, layout) {\n\n new_state = new_state || {};\n layout = layout || {};\n\n // If a \"chr\", \"start\", and \"end\" are present then resolve start and end\n // to numeric values that are not decimal, negative, or flipped\n let validated_region = false;\n let attempted_midpoint = null;\n let attempted_scale;\n if (typeof new_state.chr != 'undefined' && typeof new_state.start != 'undefined' && typeof new_state.end != 'undefined') {\n // Determine a numeric scale and midpoint for the attempted region,\n new_state.start = Math.max(parseInt(new_state.start), 1);\n new_state.end = Math.max(parseInt(new_state.end), 1);\n if (isNaN(new_state.start) && isNaN(new_state.end)) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_midpoint = 0.5;\n attempted_scale = 0;\n } else if (isNaN(new_state.start) || isNaN(new_state.end)) {\n attempted_midpoint = new_state.start || new_state.end;\n attempted_scale = 0;\n new_state.start = (isNaN(new_state.start) ? new_state.end : new_state.start);\n new_state.end = (isNaN(new_state.end) ? new_state.start : new_state.end);\n } else {\n attempted_midpoint = Math.round((new_state.start + new_state.end) / 2);\n attempted_scale = new_state.end - new_state.start;\n if (attempted_scale < 0) {\n const temp = new_state.start;\n new_state.end = new_state.start;\n new_state.start = temp;\n attempted_scale = new_state.end - new_state.start;\n }\n if (attempted_midpoint < 0) {\n new_state.start = 1;\n new_state.end = 1;\n attempted_scale = 0;\n }\n }\n validated_region = true;\n }\n\n // Constrain w/r/t layout-defined minimum region scale\n if (layout.min_region_scale && validated_region && attempted_scale < layout.min_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.min_region_scale / 2), 1);\n new_state.end = new_state.start + layout.min_region_scale;\n }\n\n // Constrain w/r/t layout-defined maximum region scale\n if (layout.max_region_scale && validated_region && attempted_scale > layout.max_region_scale) {\n new_state.start = Math.max(attempted_midpoint - Math.floor(layout.max_region_scale / 2), 1);\n new_state.end = new_state.start + layout.max_region_scale;\n }\n\n return new_state;\n}\n\n\nclass Plot {\n /**\n * An independent LocusZoom object that renders a unique set of data and subpanels.\n * Many such LocusZoom objects can exist simultaneously on a single page, each having its own layout.\n *\n * This creates a new plot instance, but does not immediately render it. For practical use, it may be more convenient\n * to use the `LocusZoom.populate` helper method.\n *\n * @param {String} id The ID of the plot. Often corresponds to the ID of the container element on the page\n * where the plot is rendered..\n * @param {DataSources} datasource Ensemble of data providers used by the plot\n * @param {object} [layout.state] Initial state parameters; the most common options are 'chr', 'start', and 'end'\n * to specify initial region view\n * @param {number} [layout.width=800] The width of the plot and all child panels\n * @param {number} [layout.min_width=400] Do not allow the panel to be resized below this width\n * @param {number} [layout.min_region_scale] The minimum region width (do not allow the user to zoom smaller than this region size)\n * @param {number} [layout.max_region_scale] The maximum region width (do not allow the user to zoom wider than this region size)\n * @param {boolean} [layout.responsive_resize=false] Whether to resize plot width as the screen is resized\n * @param {Object[]} [layout.panels] Configuration options for each panel to be added\n * @param {module:LocusZoom_Widgets[]} [layout.toolbar.widgets] Configuration options for each widget to place on the\n * plot-level toolbar\n * @param {boolean} [layout.panel_boundaries=true] Whether to show interactive resize handles to change panel dimensions\n * @param {boolean} [layout.mouse_guide=true] Whether to always show horizontal and vertical dotted lines that intersect at the current location of the mouse pointer.\n * This line spans the entire plot area and is especially useful for plots with multiple panels.\n */\n constructor(id, datasource, layout) {\n /**\n * @private\n * @member Boolean}\n */\n this.initialized = false;\n\n /**\n * @private\n * @member {Plot}\n */\n this.parent_plot = this;\n\n /**\n * @public\n * @member {String}\n */\n this.id = id;\n\n /**\n * @private\n * @member {Element}\n */\n this.container = null;\n /**\n * Selector for a node that will contain the plot. (set externally by populate methods)\n * @private\n * @member {d3.selection}\n */\n this.svg = null;\n\n /**\n * Direct access to panel instances, keyed by panel ID. Used primarily for introspection/ development.\n * @public\n * @member {Object.}\n */\n this.panels = {};\n /**\n * TODO: This is currently used by external classes that manipulate the parent and may indicate room for a helper method in the api to coordinate boilerplate\n * @private\n * @member {String[]}\n */\n this.panel_ids_by_y_index = [];\n\n /**\n * Track update operations (reMap) performed on all child panels, and notify the parent plot when complete\n * TODO: Reconsider whether we need to be tracking this as global state outside of context of specific operations\n * @ignore\n * @protected\n * @member {Promise[]}\n */\n this.remap_promises = [];\n\n\n /**\n * The current layout options for the plot, including the effect of any resizing events or dynamically\n * generated config produced during rendering options.\n * @public\n * @type {Object}\n */\n this.layout = layout;\n merge(this.layout, default_layout); // TODO: evaluate how the default layout is applied\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original plot options.\n * This is useful for, eg, dynamically generated color schemes that need to start from scratch when new data is\n * loaded: it contains the \"defaults\", not just the result of a calculated value.\n * @ignore\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * Create a shortcut to the state in the layout on the Plot. Tracking in the layout allows the plot to be created\n * with initial state/setup.\n *\n * Tracks state of the plot, eg start and end position\n * @public\n * @member {Object}\n */\n this.state = this.layout.state;\n\n /**\n * @private\n * @member {Requester}\n */\n this.lzd = new Requester(datasource);\n\n /**\n * Track global event listeners that are used by LZ. This allows cleanup of listeners when plot is destroyed.\n * @private\n * @member {Map} A nested hash of entries: { parent: {event_name: [listeners] } }\n */\n this._external_listeners = new Map();\n\n /**\n * Known event hooks that the panel can respond to\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @protected\n * @member {Object}\n */\n this.event_hooks = {};\n\n /**\n * @callback eventCallback\n * @param {object} eventData A description of the event\n * @param {String|null} eventData.sourceID The unique identifier (eg plot or parent name) of the element that\n * triggered the event. Will be automatically filled in if not explicitly provided.\n * @param {Object|null} eventData.context Any additional information to be passed to the callback, eg the data\n * associated with a clicked plot element\n */\n\n /**\n * Event information describing interaction (e.g. panning and zooming) is stored on the plot\n * TODO: Add/ document details of interaction structure as we expand\n * @private\n * @member {{panel_id: String, linked_panel_ids: Array, x_linked: *, dragging: *, zooming: *}}\n * @returns {Plot}\n */\n this.interaction = {};\n\n // Initialize the layout\n this.initializeLayout();\n }\n\n /******* User-facing methods that allow manipulation of the plot instance: the public interface */\n\n /**\n * There are several events that a LocusZoom plot can \"emit\" when appropriate, and LocusZoom supports registering\n * \"hooks\" for these events which are essentially custom functions intended to fire at certain times.\n *\n * To register a hook for any of these events use `plot.on('event_name', function() {})`.\n *\n * There can be arbitrarily many functions registered to the same event. They will be executed in the order they\n * were registered.\n *\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of an event. Consult documentation for the names of built-in events.\n * @param {eventCallback} hook\n * @returns {function} The registered event listener\n */\n on(event, hook) {\n if (typeof event !== 'string') {\n throw new Error(`Unable to register event hook. Event name must be a string: ${event.toString()}`);\n }\n if (typeof hook != 'function') {\n throw new Error('Unable to register event hook, invalid hook function passed');\n }\n if (!this.event_hooks[event]) {\n // We do not validate on known event names, because LZ is allowed to track and emit custom events like \"widget button clicked\".\n this.event_hooks[event] = [];\n }\n this.event_hooks[event].push(hook);\n return hook;\n }\n\n /**\n * Remove one or more previously defined event listeners\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {String} event The name of an event (as defined in `event_hooks`)\n * @param {eventCallback} [hook] The callback to deregister\n * @returns {Plot}\n */\n off(event, hook) {\n const theseHooks = this.event_hooks[event];\n if (typeof event != 'string' || !Array.isArray(theseHooks)) {\n throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`);\n }\n if (hook === undefined) {\n // Deregistering all hooks for this event may break basic functionality, and should only be used during\n // cleanup operations (eg to prevent memory leaks)\n this.event_hooks[event] = [];\n } else {\n const hookMatch = theseHooks.indexOf(hook);\n if (hookMatch !== -1) {\n theseHooks.splice(hookMatch, 1);\n } else {\n throw new Error('The specified event listener is not registered and therefore cannot be removed');\n }\n }\n return this;\n }\n\n /**\n * Handle running of event hooks when an event is emitted\n * @public\n * @see {@link event:any_lz_event} for a list of pre-defined events commonly used by LocusZoom\n * @param {string} event A known event name\n * @param {*} eventData Data or event description that will be passed to the event listener\n * @returns {Plot}\n */\n emit(event, eventData) {\n // TODO: there are small differences between the emit implementation between plots and panels. In the future,\n // DRY this code via mixins, and make sure to keep the interfaces compatible when refactoring.\n const these_hooks = this.event_hooks[event];\n if (typeof event != 'string') {\n throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`);\n } else if (!these_hooks && !this.event_hooks['any_lz_event']) {\n // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound?\n return this;\n }\n const sourceID = this.getBaseId();\n let eventContext;\n if (eventData && eventData.sourceID) {\n // If we detect that an event originated elsewhere (via bubbling or externally), preserve the context\n // when re-emitting the event to plot-level listeners\n eventContext = eventData;\n } else {\n eventContext = {sourceID: sourceID, target: this, data: eventData || null};\n }\n if (these_hooks) {\n // This event may have no hooks, but we could be passing by on our way to any_lz_event (below)\n these_hooks.forEach((hookToRun) => {\n // By default, any handlers fired here (either directly, or bubbled) will see the plot as the\n // value of `this`. If a bound function is registered as a handler, the previously bound `this` will\n // override anything provided to `call` below.\n hookToRun.call(this, eventContext);\n });\n }\n\n // At the plot level (only), all events will be re-emitted under the special name \"any_lz_event\"- a single place to\n // globally listen to every possible event.\n // This is not intended for direct use. It is for UI frameworks like Vue.js, which may need to wrap LZ\n // instances and proxy all events to their own declarative event system\n if (event !== 'any_lz_event') {\n const anyEventData = Object.assign({ event_name: event }, eventContext);\n this.emit('any_lz_event', anyEventData);\n }\n return this;\n }\n\n /**\n * Create a new panel from a layout, and handle the work of initializing and placing the panel on the plot\n * @public\n * @param {Object} layout\n * @returns {Panel}\n */\n addPanel(layout) {\n // Sanity checks\n if (typeof layout !== 'object') {\n throw new Error('Invalid panel layout');\n }\n\n // Create the Panel and set its parent\n const panel = new Panel(layout, this);\n\n // Store the Panel on the Plot\n this.panels[panel.id] = panel;\n\n // If a discrete y_index was set in the layout then adjust other panel y_index values to accommodate this one\n if (panel.layout.y_index !== null && !isNaN(panel.layout.y_index)\n && this.panel_ids_by_y_index.length > 0) {\n // Negative y_index values should count backwards from the end, so convert negatives to appropriate values here\n if (panel.layout.y_index < 0) {\n panel.layout.y_index = Math.max(this.panel_ids_by_y_index.length + panel.layout.y_index, 0);\n }\n this.panel_ids_by_y_index.splice(panel.layout.y_index, 0, panel.id);\n this.applyPanelYIndexesToPanelLayouts();\n } else {\n const length = this.panel_ids_by_y_index.push(panel.id);\n this.panels[panel.id].layout.y_index = length - 1;\n }\n\n // Determine if this panel was already in the layout.panels array.\n // If it wasn't, add it. Either way store the layout.panels array index on the panel.\n let layout_idx = null;\n this.layout.panels.forEach((panel_layout, idx) => {\n if (panel_layout.id === panel.id) {\n layout_idx = idx;\n }\n });\n if (layout_idx === null) {\n layout_idx = this.layout.panels.push(this.panels[panel.id].layout) - 1;\n }\n this.panels[panel.id].layout_idx = layout_idx;\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n this.positionPanels();\n // Initialize and load data into the new panel\n this.panels[panel.id].initialize();\n this.panels[panel.id].reMap();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this._total_height);\n }\n return this.panels[panel.id];\n }\n\n /**\n * Clear all state, tooltips, and other persisted data associated with one (or all) panel(s) in the plot\n *\n * This is useful when reloading an existing plot with new data, eg \"click for genome region\" links.\n * This is a utility method for custom usage. It is not fired automatically during normal rerender of existing panels\n * TODO: Is this method still necessary in modern usage? Hide from docs for now.\n * @public\n * @ignore\n * @param {String} [panelId] If provided, clear state for only this panel. Otherwise, clear state for all panels.\n * @param {('wipe'|'reset')} [mode='wipe'] Optionally specify how state should be cleared. `wipe` deletes all data\n * and is useful for when the panel is being removed; `reset` is best when the panel will be reused in place.\n * @returns {Plot}\n */\n clearPanelData(panelId, mode) {\n mode = mode || 'wipe';\n\n // TODO: Add unit tests for this method\n let panelsList;\n if (panelId) {\n panelsList = [panelId];\n } else {\n panelsList = Object.keys(this.panels);\n }\n\n panelsList.forEach((pid) => {\n this.panels[pid].data_layer_ids_by_z_index.forEach((dlid) => {\n const layer = this.panels[pid].data_layers[dlid];\n layer.destroyAllTooltips();\n\n delete layer.layer_state;\n delete this.layout.state[layer.state_id];\n if (mode === 'reset') {\n layer._setDefaultState();\n }\n });\n });\n return this;\n }\n\n /**\n * Remove the panel from the plot, and clear any state, tooltips, or other visual elements belonging to nested content\n * @public\n * @fires event:panel_removed\n * @param {String} id\n * @returns {Plot}\n */\n removePanel(id) {\n if (!this.panels[id]) {\n throw new Error(`Unable to remove panel, ID not found: ${id}`);\n }\n\n // Hide all panel boundaries\n this.panel_boundaries.hide();\n\n // Destroy all tooltips and state vars for all data layers on the panel\n this.clearPanelData(id);\n\n // Remove all panel-level HTML overlay elements\n this.panels[id].loader.hide();\n this.panels[id].toolbar.destroy(true);\n this.panels[id].curtain.hide();\n\n // Remove the svg container for the panel if it exists\n if (this.panels[id].svg.container) {\n this.panels[id].svg.container.remove();\n }\n\n // Delete the panel and its presence in the plot layout and state\n this.layout.panels.splice(this.panels[id].layout_idx, 1);\n delete this.panels[id];\n delete this.layout.state[id];\n\n // Update layout_idx values for all remaining panels\n this.layout.panels.forEach((panel_layout, idx) => {\n this.panels[panel_layout.id].layout_idx = idx;\n });\n\n // Remove the panel id from the y_index array\n this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(id), 1);\n this.applyPanelYIndexesToPanelLayouts();\n\n // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space\n if (this.initialized) {\n this.positionPanels();\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n this.setDimensions(this.layout.width, this._total_height);\n }\n\n this.emit('panel_removed', id);\n\n return this;\n }\n\n /**\n * Refresh (or fetch) a plot's data from sources, regardless of whether position or state has changed\n * @public\n * @returns {Promise}\n */\n refresh() {\n return this.applyState();\n }\n\n /**\n * A user-defined callback function that can receive (and potentially act on) new plot data.\n * @callback externalDataCallback\n * @param {Object} new_data The body resulting from a data request. This represents the same information that would be passed to\n * a data layer making an equivalent request.\n */\n\n /**\n * A user-defined callback function that can respond to errors received during a previous operation\n * @callback externalErrorCallback\n * @param err A representation of the error that occurred\n */\n\n /**\n * Allow newly fetched data to be made available outside the LocusZoom plot. For example, a callback could be\n * registered to draw an HTML table of top GWAS hits, and update that table whenever the plot region changes.\n *\n * This is a convenience method for external hooks. It registers an event listener and returns parsed data,\n * using the same fields syntax and underlying methods as data layers.\n *\n * @public\n * @listens event:data_rendered\n * @param {String[]} fields An array of field names and transforms, in the same syntax used by a data layer.\n * Different data sources should be prefixed by the namespace name.\n * @param {externalDataCallback} success_callback Used defined function that is automatically called any time that\n * new data is received by the plot. Receives two arguments: (data, plot).\n * @param {Object} [opts] Options\n * @param {externalErrorCallback} [opts.onerror] User defined function that is automatically called if a problem\n * occurs during the data request or subsequent callback operations\n * @param {boolean} [opts.discrete=false] Normally the callback will subscribe to the combined body from the chain,\n * which may not be in a format that matches what the external callback wants to do. If discrete=true, returns the\n * uncombined record info\n * @return {function} The newly created event listener, to allow for later cleanup/removal\n */\n subscribeToData(fields, success_callback, opts) {\n opts = opts || {};\n\n // Register an event listener that is notified whenever new data has been rendered\n const error_callback = opts.onerror || function (err) {\n console.log('An error occurred while acting on an external callback', err);\n };\n\n const listener = () => {\n try {\n this.lzd.getData(this.state, fields)\n .then((new_data) => success_callback(opts.discrete ? new_data.discrete : new_data.body, this))\n .catch(error_callback);\n } catch (error) {\n // In certain cases, errors are thrown before a promise can be generated, and LZ error display seems to rely on these errors bubbling up\n error_callback(error);\n }\n };\n this.on('data_rendered', listener);\n return listener;\n }\n\n /**\n * Update state values and trigger a pull for fresh data on all data sources for all data layers\n * @public\n * @param {Object} state_changes\n * @returns {Promise} A promise that resolves when all data fetch and update operations are complete\n * @listens event:match_requested\n * @fires event:data_requested\n * @fires event:layout_changed\n * @fires event:data_rendered\n * @fires event:state_changed\n * @fires event:region_changed\n */\n applyState(state_changes) {\n state_changes = state_changes || {};\n if (typeof state_changes != 'object') {\n throw new Error(`applyState only accepts an object; ${typeof state_changes} given`);\n }\n\n // Track what parameters will be modified. For bounds checking, we must take some preset values into account.\n let mods = { chr: this.state.chr, start: this.state.start, end: this.state.end };\n for (let property in state_changes) {\n mods[property] = state_changes[property];\n }\n mods = _updateStatePosition(mods, this.layout);\n\n // Apply new state to the actual state\n for (let property in mods) {\n this.state[property] = mods[property];\n }\n\n // Generate requests for all panels given new state\n this.emit('data_requested');\n this.remap_promises = [];\n this.loading_data = true;\n for (let id in this.panels) {\n this.remap_promises.push(this.panels[id].reMap());\n }\n\n return Promise.all(this.remap_promises)\n .catch((error) => {\n console.error(error);\n this.curtain.show(error.message || error);\n this.loading_data = false;\n })\n .then(() => {\n // Update toolbar / widgets\n this.toolbar.update();\n\n // Apply panel-level state values\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.toolbar.update();\n // Apply data-layer-level state values\n panel.data_layer_ids_by_z_index.forEach((data_layer_id) => {\n panel.data_layers[data_layer_id].applyAllElementStatus();\n });\n });\n\n // Emit events\n this.emit('layout_changed');\n this.emit('data_rendered');\n this.emit('state_changed', state_changes);\n\n // An interesting quirk of region changing in LZ: the final region is not always the same as the requested region\n // (example: zoom out beyond max, or request non-integer position)\n // Echo the actual plot region as the final source of truth\n const { chr, start, end } = this.state;\n const position_changed = Object.keys(state_changes)\n .some((key) => ['chr', 'start', 'end'].includes(key));\n\n if (position_changed) {\n this.emit('region_changed', { chr, start, end });\n }\n\n this.loading_data = false;\n });\n }\n\n /**\n * Keep a record of event listeners that are defined outside of the LocusZoom boundary (and therefore would not\n * get cleaned up when the plot was removed from the DOM). For example, window resize or mouse events.\n * This allows safe cleanup of the plot on removal from the page. This method is useful for authors of LocusZoom plugins.\n * @param {Node} target The node on which the listener has been defined\n * @param {String} event_name\n * @param {function} listener The handle for the event listener to be cleaned up\n */\n trackExternalListener(target, event_name, listener) {\n if (!this._external_listeners.has(target)) {\n this._external_listeners.set(target, new Map());\n }\n const container = this._external_listeners.get(target);\n\n const tracker = container.get(event_name) || [];\n if (!tracker.includes(listener)) {\n tracker.push(listener);\n }\n container.set(event_name, tracker);\n }\n\n /**\n * Remove the plot from the page, and clean up any globally registered event listeners\n *\n * Internally, the plot retains references to some nodes via selectors; it may be useful to delete the plot\n * instance after calling this method\n */\n destroy() {\n for (let [target, registered_events] of this._external_listeners.entries()) {\n for (let [event_name, listeners] of registered_events) {\n for (let listener of listeners) {\n target.removeEventListener(event_name, listener);\n }\n }\n }\n\n // Clear the SVG, plus other HTML nodes (like toolbar) that live under the same parent\n const parent = this.svg.node().parentNode;\n if (!parent) {\n throw new Error('Plot has already been removed');\n }\n while (parent.lastElementChild) {\n parent.removeChild(parent.lastElementChild);\n }\n // Clear toolbar event listeners defined on the parent lz-container. As of 2020 this appears to be the\n // state of the art cross-browser DOM API for this task.\n // eslint-disable-next-line no-self-assign\n parent.outerHTML = parent.outerHTML;\n\n this.initialized = false;\n\n this.svg = null;\n this.panels = null;\n }\n\n /******* The private interface: methods only used by LocusZoom internals */\n /**\n * Track whether the target panel can respond to mouse interaction events\n * @private\n * @param {String} panel_id\n * @returns {boolean}\n */\n _canInteract(panel_id) {\n panel_id = panel_id || null;\n if (panel_id) {\n return ((typeof this.interaction.panel_id == 'undefined' || this.interaction.panel_id === panel_id) && !this.loading_data);\n } else {\n return !(this.interaction.dragging || this.interaction.zooming || this.loading_data);\n }\n }\n\n /**\n * Get an object with the x and y coordinates of the plot's origin in terms of the entire page\n * This returns a result with absolute position relative to the page, regardless of current scrolling\n * Necessary for positioning any HTML elements over the plot\n * @private\n * @returns {{x: Number, y: Number, width: Number, height: Number}}\n */\n _getPageOrigin() {\n const bounding_client_rect = this.svg.node().getBoundingClientRect();\n let x_offset = document.documentElement.scrollLeft || document.body.scrollLeft;\n let y_offset = document.documentElement.scrollTop || document.body.scrollTop;\n let container = this.svg.node();\n while (container.parentNode !== null) {\n // TODO: Recursively seeks offsets for highest non-static parent node. This can lead to incorrect\n // calculations of, for example, x coordinate relative to the page. Revisit this logic.\n container = container.parentNode;\n if (container !== document && d3.select(container).style('position') !== 'static') {\n x_offset = -1 * container.getBoundingClientRect().left;\n y_offset = -1 * container.getBoundingClientRect().top;\n break;\n }\n }\n return {\n x: x_offset + bounding_client_rect.left,\n y: y_offset + bounding_client_rect.top,\n width: bounding_client_rect.width,\n height: bounding_client_rect.height,\n };\n }\n\n /**\n * Get the top and left offset values for the plot's container element (the div that was populated)\n * @private\n * @returns {{top: number, left: number}}\n */\n getContainerOffset() {\n const offset = { top: 0, left: 0 };\n let container = this.container.offsetParent || null;\n while (container !== null) {\n offset.top += container.offsetTop;\n offset.left += container.offsetLeft;\n container = container.offsetParent || null;\n }\n return offset;\n }\n\n /**\n * Notify each child panel of the plot of changes in panel ordering/ arrangement\n * @private\n */\n applyPanelYIndexesToPanelLayouts () {\n this.panel_ids_by_y_index.forEach((pid, idx) => {\n this.panels[pid].layout.y_index = idx;\n });\n }\n\n /**\n * Get the qualified ID pathname for the plot\n * @private\n * @returns {String}\n */\n getBaseId () {\n return this.id;\n }\n\n /**\n * Resize the plot to fit the bounding container\n * @private\n * @returns {Plot}\n */\n rescaleSVG() {\n const clientRect = this.svg.node().getBoundingClientRect();\n this.setDimensions(clientRect.width, clientRect.height);\n return this;\n }\n\n /**\n * Prepare the plot for first use by performing parameter validation, setting up panels, and calculating dimensions\n * @private\n * @returns {Plot}\n */\n initializeLayout() {\n\n // Sanity check layout values\n if (isNaN(this.layout.width) || this.layout.width <= 0) {\n throw new Error('Plot layout parameter `width` must be a positive number');\n }\n\n // Backwards compatible check: there was previously a third option. Anything truthy should thus act as \"responsive_resize: true\"\n this.layout.responsive_resize = !!this.layout.responsive_resize;\n\n // If this is a responsive layout then set a namespaced/unique onresize event listener on the window\n if (this.layout.responsive_resize) {\n const resize_listener = () => this.rescaleSVG();\n window.addEventListener('resize', resize_listener);\n this.trackExternalListener(window, 'resize', resize_listener);\n\n // Forcing one additional setDimensions() call after the page is loaded clears up\n // any disagreements between the initial layout and the loaded responsive container's size\n const load_listener = () => this.setDimensions();\n window.addEventListener('load', load_listener);\n this.trackExternalListener(window, 'load', load_listener);\n }\n\n // Add panels\n this.layout.panels.forEach((panel_layout) => {\n this.addPanel(panel_layout);\n });\n\n return this;\n }\n\n /**\n * Set the dimensions for a plot, and ensure that panels are sized and positioned correctly.\n *\n * If dimensions are provided, resizes each panel proportionally to match the new plot dimensions. Otherwise,\n * calculates the appropriate plot dimensions based on all panels, and ensures that panels are placed and\n * rendered in the correct relative positions.\n * @private\n * @param {Number} [width] If provided and larger than minimum allowed size, set plot to this width\n * @param {Number} [height] If provided and larger than minimum allowed size, set plot to this height\n * @returns {Plot}\n * @fires event:layout_changed\n */\n setDimensions(width, height) {\n // If width and height arguments were passed, then adjust plot dimensions to fit all panels\n // Then resize the plot and proportionally resize panels to fit inside the new plot dimensions.\n if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) {\n // Resize operations may ask for a different amount of space than that used by panels.\n const height_scaling_factor = height / this._total_height;\n\n this.layout.width = Math.max(Math.round(+width), this.layout.min_width);\n // Override discrete values if resizing responsively\n if (this.layout.responsive_resize) {\n // All resize modes will affect width\n if (this.svg) {\n this.layout.width = Math.max(this.svg.node().parentNode.getBoundingClientRect().width, this.layout.min_width);\n }\n }\n // Resize/reposition panels to fit, update proportional origins if necessary\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n const panel_width = this.layout.width;\n // In this block, we are passing explicit dimensions that might require rescaling all panels at once\n const panel_height = panel.layout.height * height_scaling_factor;\n panel.setDimensions(panel_width, panel_height);\n panel.setOrigin(0, y_offset);\n y_offset += panel_height;\n panel.toolbar.update();\n });\n }\n\n // Set the plot height to the sum of all panels (using the \"real\" height values accounting for panel.min_height)\n const final_height = this._total_height;\n\n // Apply layout width and height as discrete values or viewbox values\n if (this.svg !== null) {\n // The viewBox must always be specified in order for \"save as image\" button to work\n this.svg.attr('viewBox', `0 0 ${this.layout.width} ${final_height}`);\n\n this.svg\n .attr('width', this.layout.width)\n .attr('height', final_height);\n }\n\n // If the plot has been initialized then trigger some necessary render functions\n if (this.initialized) {\n this.panel_boundaries.position();\n this.toolbar.update();\n this.curtain.update();\n this.loader.update();\n }\n\n return this.emit('layout_changed');\n }\n\n /**\n * Automatically position panels based on panel positioning rules and values.\n * Keep panels from overlapping vertically by adjusting origins, and keep the sum of proportional heights at 1.\n *\n * LocusZoom panels can only be stacked vertically (not horizontally)\n * @private\n */\n positionPanels() {\n // We want to enforce that all x-linked panels have consistent horizontal margins\n // (to ensure that aligned items stay aligned despite inconsistent initial layout parameters)\n // NOTE: This assumes panels have consistent widths already. That should probably be enforced too!\n const x_linked_margins = { left: 0, right: 0 };\n\n // Proportional heights for newly added panels default to null unless explicitly set, so determine appropriate\n // proportional heights for all panels with a null value from discretely set dimensions.\n // Likewise handle default nulls for proportional widths, but instead just force a value of 1 (full width)\n for (let id in this.panels) {\n if (this.panels[id].layout.interaction.x_linked) {\n x_linked_margins.left = Math.max(x_linked_margins.left, this.panels[id].layout.margin.left);\n x_linked_margins.right = Math.max(x_linked_margins.right, this.panels[id].layout.margin.right);\n }\n }\n\n // Update origins on all panels without changing plot-level dimensions yet\n // Also apply x-linked margins to x-linked panels, updating widths as needed\n let y_offset = 0;\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.setOrigin(0, y_offset);\n y_offset += this.panels[panel_id].layout.height;\n if (panel.layout.interaction.x_linked) {\n const delta = Math.max(x_linked_margins.left - panel.layout.margin.left, 0)\n + Math.max(x_linked_margins.right - panel.layout.margin.right, 0);\n panel.layout.width += delta;\n panel.layout.margin.left = x_linked_margins.left;\n panel.layout.margin.right = x_linked_margins.right;\n panel.layout.cliparea.origin.x = x_linked_margins.left;\n }\n });\n\n // Update dimensions on the plot to accommodate repositioned panels (eg when resizing one panel,\n // also must update the plot dimensions)\n this.setDimensions();\n\n // Set dimensions on all panels using newly set plot-level dimensions and panel-level proportional dimensions\n this.panel_ids_by_y_index.forEach((panel_id) => {\n const panel = this.panels[panel_id];\n panel.setDimensions(\n this.layout.width,\n panel.layout.height\n );\n });\n\n return this;\n }\n\n /**\n * Prepare the first rendering of the plot. This includes initializing the individual panels, but also creates shared\n * elements such as mouse events, panel guides/boundaries, and loader/curtain.\n * @private\n * @returns {Plot}\n */\n initialize() {\n\n // Ensure proper responsive class is present on the containing node if called for\n if (this.layout.responsive_resize) {\n d3.select(this.container).classed('lz-container-responsive', true);\n }\n\n // Create an element/layer for containing mouse guides\n if (this.layout.mouse_guide) {\n const mouse_guide_svg = this.svg.append('g')\n .attr('class', 'lz-mouse_guide')\n .attr('id', `${this.id}.mouse_guide`);\n const mouse_guide_vertical_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-vertical')\n .attr('x', -1);\n const mouse_guide_horizontal_svg = mouse_guide_svg.append('rect')\n .attr('class', 'lz-mouse_guide-horizontal')\n .attr('y', -1);\n this.mouse_guide = {\n svg: mouse_guide_svg,\n vertical: mouse_guide_vertical_svg,\n horizontal: mouse_guide_horizontal_svg,\n };\n }\n\n // Add curtain and loader prototpyes to the plot\n this.curtain = generateCurtain.call(this);\n this.loader = generateLoader.call(this);\n\n // Create the panel_boundaries object with show/position/hide methods\n this.panel_boundaries = {\n parent: this,\n hide_timeout: null,\n showing: false,\n dragging: false,\n selectors: [],\n corner_selector: null,\n show: function() {\n // Generate panel boundaries\n if (!this.showing && !this.parent.curtain.showing) {\n this.showing = true;\n // Loop through all panels to create a horizontal boundary for each\n this.parent.panel_ids_by_y_index.forEach((panel_id, panel_idx) => {\n const selector = d3.select(this.parent.svg.node().parentNode).insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-boundary')\n .attr('title', 'Resize panel');\n selector.append('span');\n const panel_resize_drag = d3.drag();\n panel_resize_drag.on('start', () => {\n this.dragging = true;\n });\n panel_resize_drag.on('end', () => {\n this.dragging = false;\n });\n panel_resize_drag.on('drag', () => {\n // First set the dimensions on the panel we're resizing\n const this_panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]];\n const original_panel_height = this_panel.layout.height;\n this_panel.setDimensions(this.parent.layout.width, this_panel.layout.height + d3.event.dy);\n const panel_height_change = this_panel.layout.height - original_panel_height;\n // Next loop through all panels.\n // Update proportional dimensions for all panels including the one we've resized using discrete heights.\n // Reposition panels with a greater y-index than this panel to their appropriate new origin.\n this.parent.panel_ids_by_y_index.forEach((loop_panel_id, loop_panel_idx) => {\n const loop_panel = this.parent.panels[this.parent.panel_ids_by_y_index[loop_panel_idx]];\n if (loop_panel_idx > panel_idx) {\n loop_panel.setOrigin(loop_panel.layout.origin.x, loop_panel.layout.origin.y + panel_height_change);\n loop_panel.toolbar.position();\n }\n });\n // Reset dimensions on the entire plot and reposition panel boundaries\n this.parent.positionPanels();\n this.position();\n });\n selector.call(panel_resize_drag);\n this.parent.panel_boundaries.selectors.push(selector);\n });\n // Create a corner boundary / resize element on the bottom-most panel that resizes the entire plot\n const corner_selector = d3.select(this.parent.svg.node().parentNode)\n .insert('div', '.lz-data_layer-tooltip')\n .attr('class', 'lz-panel-corner-boundary')\n .attr('title', 'Resize plot');\n\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-outer');\n corner_selector\n .append('span')\n .attr('class', 'lz-panel-corner-boundary-inner');\n\n const corner_drag = d3.drag();\n corner_drag.on('start', () => {\n this.dragging = true;\n });\n corner_drag.on('end', () => {\n this.dragging = false;\n });\n corner_drag.on('drag', () => {\n this.parent.setDimensions(this.parent.layout.width + d3.event.dx, this.parent._total_height + d3.event.dy);\n });\n corner_selector.call(corner_drag);\n this.parent.panel_boundaries.corner_selector = corner_selector;\n }\n return this.position();\n },\n position: function() {\n if (!this.showing) {\n return this;\n }\n // Position panel boundaries\n const plot_page_origin = this.parent._getPageOrigin();\n this.selectors.forEach((selector, panel_idx) => {\n const panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]];\n const panel_page_origin = panel._getPageOrigin();\n const left = plot_page_origin.x;\n const top = panel_page_origin.y + panel.layout.height - 12;\n const width = this.parent.layout.width - 1;\n selector\n .style('top', `${top}px`)\n .style('left', `${left}px`)\n .style('width', `${width}px`);\n selector.select('span')\n .style('width', `${width}px`);\n });\n // Position corner selector\n const corner_padding = 10;\n const corner_size = 16;\n this.corner_selector\n .style('top', `${plot_page_origin.y + this.parent._total_height - corner_padding - corner_size}px`)\n .style('left', `${plot_page_origin.x + this.parent.layout.width - corner_padding - corner_size}px`);\n return this;\n },\n hide: function() {\n if (!this.showing) {\n return this;\n }\n this.showing = false;\n // Remove panel boundaries\n this.selectors.forEach((selector) => {\n selector.remove();\n });\n this.selectors = [];\n // Remove corner boundary\n this.corner_selector.remove();\n this.corner_selector = null;\n return this;\n },\n };\n\n // Show panel boundaries stipulated by the layout (basic toggle, only show on mouse over plot)\n if (this.layout.panel_boundaries) {\n d3.select(this.svg.node().parentNode)\n .on(`mouseover.${this.id}.panel_boundaries`, () => {\n clearTimeout(this.panel_boundaries.hide_timeout);\n this.panel_boundaries.show();\n })\n .on(`mouseout.${this.id}.panel_boundaries`, () => {\n this.panel_boundaries.hide_timeout = setTimeout(() => {\n this.panel_boundaries.hide();\n }, 300);\n });\n }\n\n // Create the toolbar object and immediately show it\n this.toolbar = new Toolbar(this).show();\n\n // Initialize all panels\n for (let id in this.panels) {\n this.panels[id].initialize();\n }\n\n // Define plot-level mouse events\n const namespace = `.${this.id}`;\n if (this.layout.mouse_guide) {\n const mouseout_mouse_guide = () => {\n this.mouse_guide.vertical.attr('x', -1);\n this.mouse_guide.horizontal.attr('y', -1);\n };\n const mousemove_mouse_guide = () => {\n const coords = d3.mouse(this.svg.node());\n this.mouse_guide.vertical.attr('x', coords[0]);\n this.mouse_guide.horizontal.attr('y', coords[1]);\n };\n this.svg\n .on(`mouseout${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`touchleave${namespace}-mouse_guide`, mouseout_mouse_guide)\n .on(`mousemove${namespace}-mouse_guide`, mousemove_mouse_guide);\n }\n const mouseup = () => {\n this.stopDrag();\n };\n const mousemove = () => {\n if (this.interaction.dragging) {\n const coords = d3.mouse(this.svg.node());\n if (d3.event) {\n d3.event.preventDefault();\n }\n this.interaction.dragging.dragged_x = coords[0] - this.interaction.dragging.start_x;\n this.interaction.dragging.dragged_y = coords[1] - this.interaction.dragging.start_y;\n this.panels[this.interaction.panel_id].render();\n this.interaction.linked_panel_ids.forEach((panel_id) => {\n this.panels[panel_id].render();\n });\n }\n };\n this.svg\n .on(`mouseup${namespace}`, mouseup)\n .on(`touchend${namespace}`, mouseup)\n .on(`mousemove${namespace}`, mousemove)\n .on(`touchmove${namespace}`, mousemove);\n\n // Add an extra namespaced mouseup handler to the containing body, if there is one\n // This helps to stop interaction events gracefully when dragging outside of the plot element\n const body_selector = d3.select('body');\n const body_node = body_selector.node();\n if (body_node) {\n body_node.addEventListener('mouseup', mouseup);\n body_node.addEventListener('touchend', mouseup);\n\n this.trackExternalListener(body_node, 'mouseup', mouseup);\n this.trackExternalListener(body_node, 'touchend', mouseup);\n }\n\n this.on('match_requested', (eventData) => {\n // Layers can broadcast that a specific point has been selected, and the plot will tell every other layer\n // to look for that value. Whenever a point is de-selected, it clears the match.\n const data = eventData.data;\n const to_send = (data.active ? data.value : null);\n const emitted_by = eventData.target.id;\n // When a match is initiated, hide all tooltips from other panels (prevents zombie tooltips from reopening)\n // TODO: This is a bit hacky. Right now, selection and matching are tightly coupled, and hence tooltips\n // reappear somewhat aggressively. A better solution depends on designing alternative behavior, and\n // applying tooltips post (instead of pre) render.\n Object.values(this.panels).forEach((panel) => {\n if (panel.id !== emitted_by) {\n Object.values(panel.data_layers).forEach((layer) => layer.destroyAllTooltips(false));\n }\n });\n\n this.applyState({ lz_match_value: to_send });\n });\n\n this.initialized = true;\n\n // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip\n // positioning. TODO: make this additional call unnecessary.\n const client_rect = this.svg.node().getBoundingClientRect();\n const width = client_rect.width ? client_rect.width : this.layout.width;\n const height = client_rect.height ? client_rect.height : this._total_height;\n this.setDimensions(width, height);\n\n return this;\n }\n\n /**\n * Register interactions along the specified axis, provided that the target panel allows interaction.\n * @private\n * @param {Panel} panel\n * @param {('background'|'x_tick'|'y1_tick'|'y2_tick')} method The direction (axis) along which dragging is being performed.\n * @returns {Plot}\n */\n startDrag(panel, method) {\n panel = panel || null;\n method = method || null;\n\n let axis = null;\n switch (method) {\n case 'background':\n case 'x_tick':\n axis = 'x';\n break;\n case 'y1_tick':\n axis = 'y1';\n break;\n case 'y2_tick':\n axis = 'y2';\n break;\n }\n\n if (!(panel instanceof Panel) || !axis || !this._canInteract()) {\n return this.stopDrag();\n }\n\n const coords = d3.mouse(this.svg.node());\n this.interaction = {\n panel_id: panel.id,\n linked_panel_ids: panel.getLinkedPanelIds(axis),\n dragging: {\n method: method,\n start_x: coords[0],\n start_y: coords[1],\n dragged_x: 0,\n dragged_y: 0,\n axis: axis,\n },\n };\n\n this.svg.style('cursor', 'all-scroll');\n\n return this;\n }\n\n /**\n * Process drag interactions across the target panel and synchronize plot state across other panels in sync;\n * clear the event when complete\n * @private\n * @returns {Plot}\n */\n stopDrag() {\n\n if (!this.interaction.dragging) {\n return this;\n }\n\n if (typeof this.panels[this.interaction.panel_id] != 'object') {\n this.interaction = {};\n return this;\n }\n const panel = this.panels[this.interaction.panel_id];\n\n // Helper function to find the appropriate axis layouts on child data layers\n // Once found, apply the extent as floor/ceiling and remove all other directives\n // This forces all associated axes to conform to the extent generated by a drag action\n const overrideAxisLayout = (axis, axis_number, extent) => {\n panel.data_layer_ids_by_z_index.forEach((id) => {\n const axis_layout = panel.data_layers[id].layout[`${axis}_axis`];\n if (axis_layout.axis === axis_number) {\n axis_layout.floor = extent[0];\n axis_layout.ceiling = extent[1];\n delete axis_layout.lower_buffer;\n delete axis_layout.upper_buffer;\n delete axis_layout.min_extent;\n delete axis_layout.ticks;\n }\n });\n };\n\n switch (this.interaction.dragging.method) {\n case 'background':\n case 'x_tick':\n if (this.interaction.dragging.dragged_x !== 0) {\n overrideAxisLayout('x', 1, panel.x_extent);\n this.applyState({ start: panel.x_extent[0], end: panel.x_extent[1] });\n }\n break;\n case 'y1_tick':\n case 'y2_tick':\n if (this.interaction.dragging.dragged_y !== 0) {\n const y_axis_number = parseInt(this.interaction.dragging.method[1]);\n overrideAxisLayout('y', y_axis_number, panel[`y${y_axis_number}_extent`]);\n }\n break;\n }\n\n this.interaction = {};\n this.svg.style('cursor', null);\n\n return this;\n\n }\n\n get _total_height() {\n // The plot height is a calculated property, derived from the sum of its panel layout objects\n return this.layout.panels.reduce((acc, item) => item.height + acc, 0);\n }\n}\n\nexport {Plot as default};\n\n// Only for testing\nexport { _updateStatePosition };\n","/**\n * \"Match\" test functions used to compare two values for filtering (what to render) and matching\n * (comparison and finding related points across data layers)\n *\n * ### How do matching and filtering work?\n * See the Interactivity Tutorial for details.\n *\n * ## Adding a new function\n * LocusZoom allows users to write their own plugins, so that \"does this point match\" logic can incorporate\n * user-defined code. (via `LocusZoom.MatchFunctions.add('my_function', my_function);`)\n *\n * All \"matcher\" functions have the call signature (item_value, target_value) => {boolean}\n *\n * Both filtering and matching depend on asking \"is this field interesting to me\", which is inherently a problem of\n * making comparisons. The registry allows any arbitrary function (with a field value as the first argument), but that\n * function doesn't have to use either argument.\n *\n * @module LocusZoom_MatchFunctions\n */\nimport {RegistryBase} from './base';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided \"match\" functions, used by filtering and matching behavior.\n * @alias module:LocusZoom~MatchFunctions\n * @type {module:registry/base~RegistryBase}\n */\nconst registry = new RegistryBase();\n\n// Most of the filter syntax uses things that are JS reserved operators. Instead of exporting symbols from another\n// module, just define and register them here.\n\n/**\n * Check if two values are (strictly) equal\n * @function\n * @name '='\n * @param item_value\n * @param target_value\n */\nregistry.add('=', (item_value, target_value) => item_value === target_value);\n\n/**\n * Check if two values are not equal. This allows weak comparisons (eg undefined/null), so it can also be used to test for the absence of a value\n * @function\n * @name '!='\n * @param item_value\n * @param target_value\n */\n// eslint-disable-next-line eqeqeq\nregistry.add('!=', (a, b) => a != b); // For absence of a value, deliberately allow weak comparisons (eg undefined/null)\n\n/**\n * Less-than comparison\n * @function\n * @name '<'\n * @param item_value\n * @param target_value\n */\nregistry.add('<', (a, b) => a < b);\n\n/**\n * Less than or equals to comparison\n * @function\n * @name '<='\n * @param item_value\n * @param target_value\n */\nregistry.add('<=', (a, b) => a <= b);\n\n/**\n * Greater-than comparison\n * @function\n * @name '>'\n * @param item_value\n * @param target_value\n */\nregistry.add('>', (a, b) => a > b);\n\n/**\n * Greater than or equals to comparison\n * @function\n * @name '>='\n * @param item_value\n * @param target_value\n */\nregistry.add('>=', (a, b) => a >= b);\n\n/**\n * Modulo: tests for whether the remainder a % b is nonzero\n * @function\n * @name '%'\n * @param item_value\n * @param target_value\n */\nregistry.add('%', (a, b) => a % b);\n\n/**\n * Check whether the provided value (a) is in the string or array of values (b)\n *\n * This can be used to check if a field value is one of a set of predefined choices\n * Eg, `gene_type` is one of the allowed types of interest\n * @function\n * @name 'in'\n * @param item_value A scalar value\n * @param {String|Array} target_value A container that implements the `includes` method\n */\nregistry.add('in', (a, b) => b && b.includes(a));\n\n/**\n * Partial-match function. Can be used for free text search (\"find all gene names that contain the user-entered string 'TCF'\")\n * @function\n * @name 'match'\n * @param {String|Array} item_value A container (like a string) that implements the `includes` method\n * @param target_value A scalar value, like a string\n */\nregistry.add('match', (a, b) => a && a.includes(b)); // useful for text search: \"find all gene names that contain the user-entered value HLA\"\n\n\nexport default registry;\n","/**\n * Plugin registry of available functions that can be used in scalable layout directives.\n *\n * These \"scale functions\" are used during rendering to return output (eg color) based on input value\n *\n * @module LocusZoom_ScaleFunctions\n * @see {@link module:LocusZoom_DataLayers~ScalableParameter} for details on how scale functions are used by datalayers\n */\n\nimport * as d3 from 'd3';\n\n/**\n * Basic conditional function to evaluate the value of the input field and return based on equality.\n * @alias module:LocusZoom_ScaleFunctions~if\n * @param {Object} parameters\n * @param {*} parameters.field_value The value against which to test the input value.\n * @param {*} parameters.then The value to return if the input value matches the field value\n * @param {*} parameters.else The value to return if the input value does not match the field value. Optional. If not\n * defined this scale function will return null (or value of null_value parameter, if defined) when input value fails\n * to match field_value.\n * @param {*} input value\n */\nconst if_value = (parameters, input) => {\n if (typeof input == 'undefined' || parameters.field_value !== input) {\n if (typeof parameters.else != 'undefined') {\n return parameters.else;\n } else {\n return null;\n }\n } else {\n return parameters.then;\n }\n};\n\n/**\n * Function to sort numerical values into bins based on numerical break points. Will only operate on numbers and\n * return null (or value of null_value parameter, if defined) if provided a non-numeric input value. Parameters:\n * @function numerical_bin\n * @param {Object} parameters\n * @param {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter. If the input value is greater than or equal to break n and less than\n * or equal to break n+1 (or break n+1 doesn't exist) then returned value is the nth entry in the values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against break points. Must be of\n * equal length to breaks parameter. Each entry n represents the value to return if the input value is greater than\n * or equal to break n and less than or equal to break n+1 (or break n+1 doesn't exist).\n * @param {*} parameters.null_value\n * @param {*} input value\n * @returns {*}\n */\nconst numerical_bin = (parameters, input) => {\n const breaks = parameters.breaks || [];\n const values = parameters.values || [];\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return (parameters.null_value ? parameters.null_value : null);\n }\n const threshold = breaks.reduce(function (prev, curr) {\n if (+input < prev || (+input >= prev && +input < curr)) {\n return prev;\n } else {\n return curr;\n }\n });\n return values[breaks.indexOf(threshold)];\n};\n\n/**\n * Function to sort values of any type into bins based on direct equality testing with a list of categories.\n * Will return null if provided an input value that does not match to a listed category.\n * @function categorical_bin\n * @param {Object} parameters\n * @param {Array} parameters.categories Array of values against which to evaluate the input value. Must be of equal\n * length to values parameter. If the input value is equal to category n then returned value is the nth entry in the\n * values parameter.\n * @param {Array} parameters.values Array of values to return given evaluations against categories. Must be of equal\n * length to categories parameter. Each entry n represents the value to return if the input value is equal to the nth\n * value in the categories parameter.\n * @param {*} parameters.null_value Value to return if the input value fails to match to any categories. Optional.\n */\nconst categorical_bin = (parameters, value) => {\n if (typeof value == 'undefined' || !parameters.categories.includes(value)) {\n return (parameters.null_value ? parameters.null_value : null);\n } else {\n return parameters.values[parameters.categories.indexOf(value)];\n }\n};\n\n/**\n * Cycle through a set of options, so that the each element in a set of data receives a value different than the\n * element before it. For example: \"use this palette of 10 colors to visually distinguish 100 adjacent items\"\n * This is useful when ADJACENT items must be guaranteed to yield a different result, but it leads to unstable color\n * choices if the user pans to a region with a different number/order of items. (the same item is assigned a different color)\n *\n * See also: stable_choice.\n * @param {Object} parameters\n * @param {Array} parameters.values A list of option values\n * @return {*}\n */\nconst ordinal_cycle = (parameters, value, index) => {\n const options = parameters.values;\n return options[index % options.length];\n};\n\n/**\n * A scale function that auto-chooses something (like color) from a preset scheme, and makes the same choice every\n * time given the same value, regardless of ordering or what other data is in the region\n *\n * This is useful when categories must be stable (same color, every time). But sometimes it will assign adjacent values\n * the same color due to hash collisions.\n *\n * For performance reasons, this is memoized once per instance. Eg, each scalable color parameter has its own cache.\n * This function is therefore slightly less amenable to layout mutations like \"changing the options after scaling\n * function is used\", but this is not expected to be a common use case.\n *\n * CAVEAT: Some datasets do not return true datum ids, but instead append synthetic ID fields (\"item 1, item2\"...)\n * just to appease D3. This hash function only works if there is a meaningful, stable identifier in the data,\n * like a category or gene name.\n * @param parameters\n * @param {Array} [parameters.values] A list of options to choose from\n * @param {Number} [parameters.max_cache_size=500] The maximum number of values to cache. This option is mostly used\n * for unit testing, because stable choice is intended for datasets with a relatively limited number of\n * discrete categories.\n * @param value\n * @param index\n */\nlet stable_choice = (parameters, value, index) => {\n // Each place the function gets used has its own parameters object. This function thus memoizes per usage\n // (\"association - point color - directive 1\") rather than globally (\"all properties/panels\")\n const cache = parameters._cache = parameters._cache || new Map();\n const max_cache_size = parameters.max_cache_size || 500;\n\n if (cache.size >= max_cache_size) {\n // Prevent cache from growing out of control (eg as user moves between regions a lot)\n cache.clear();\n }\n if (cache.has(value)) {\n return cache.get(value);\n }\n\n // Simple JS hashcode implementation, from:\n // https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript\n let hash = 0;\n value = String(value);\n for (let i = 0; i < value.length; i++) {\n let chr = value.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n // Convert signed 32 bit integer to be within the range of options allowed\n const options = parameters.values;\n const result = options[Math.abs(hash) % options.length];\n cache.set(value, result);\n return result;\n};\n\n/**\n * Function for continuous interpolation of numerical values along a gradient with arbitrarily many break points.\n * @function interpolate\n * @parameters {Object} parameters\n * @parameters {Number[]} parameters.breaks Array of numerical break points against which to evaluate the input value.\n * Must be of equal length to values parameter and contain at least two elements. Input value will be evaluated for\n * relative position between two break points n and n+1 and the returned value will be interpolated at a relative\n * position between values n and n+1.\n * @parameters {*[]} parameters.values Array of values to interpolate and return given evaluations against break\n * points. Must be of equal length to breaks parameter and contain at least two elements. Each entry n represents\n * the value to return if the input value matches the nth entry in breaks exactly. Note that this scale function\n * uses d3.interpolate to provide for effective interpolation of many different value types, including numbers,\n * colors, shapes, etc.\n * @parameters {*} parameters.null_value\n */\nconst interpolate = (parameters, input) => {\n var breaks = parameters.breaks || [];\n var values = parameters.values || [];\n var nullval = (parameters.null_value ? parameters.null_value : null);\n if (breaks.length < 2 || breaks.length !== values.length) {\n return nullval;\n }\n if (typeof input == 'undefined' || input === null || isNaN(+input)) {\n return nullval;\n }\n if (+input <= parameters.breaks[0]) {\n return values[0];\n } else if (+input >= parameters.breaks[parameters.breaks.length - 1]) {\n return values[breaks.length - 1];\n } else {\n var upper_idx = null;\n breaks.forEach(function (brk, idx) {\n if (!idx) {\n return;\n }\n if (breaks[idx - 1] <= +input && breaks[idx] >= +input) {\n upper_idx = idx;\n }\n });\n if (upper_idx === null) {\n return nullval;\n }\n const normalized_input = (+input - breaks[upper_idx - 1]) / (breaks[upper_idx] - breaks[upper_idx - 1]);\n if (!isFinite(normalized_input)) {\n return nullval;\n }\n return d3.interpolate(values[upper_idx - 1], values[upper_idx])(normalized_input);\n }\n};\n\n\nexport { categorical_bin, stable_choice, if_value, interpolate, numerical_bin, ordinal_cycle };\n","/**\n * Functions that control \"scalable\" layout directives: given a value (like a number) return another value\n * (like a color, size, or shape) that governs how something is displayed\n *\n * All scale functions have the call signature `(layout_parameters, input) => result|null`\n * @module\n * @private\n */\nimport {RegistryBase} from './base';\nimport * as scalable from '../helpers/scalable';\n\n\nconst registry = new RegistryBase();\nfor (let [name, type] of Object.entries(scalable)) {\n registry.add(name, type);\n}\n\n// Alias for the \"if_value\" function (can't export reserved language keywords directly)\nregistry.add('if', scalable.if_value);\n\n\nexport default registry;\n","/**\n * Data layers represent instructions for how to render common types of information.\n * (GWAS scatter plot, nearby genes, straight lines and filled curves, etc)\n *\n * Each rendering type also provides helpful functionality such as filtering, matching, and interactive tooltip\n * display. Predefined layers can be extended or customized, with many configurable options.\n *\n * @module LocusZoom_DataLayers\n */\n\nimport * as d3 from 'd3';\n\nimport {STATUSES} from '../constants';\nimport Field from '../../data/field';\nimport {parseFields} from '../../helpers/display';\nimport {deepCopy, merge} from '../../helpers/layouts';\nimport MATCHERS from '../../registry/matchers';\nimport SCALABLE from '../../registry/scalable';\n\n\n/**\n * \"Scalable\" parameters indicate that a datum can be rendered in custom ways based on its value. (color, size, shape, etc)\n *\n * This means that if the value of this property is a scalar, it is used directly (`color: '#FF0000'`). But if the\n * value is an array of options, each will be evaluated in turn until the first non-null result is found. The syntax\n * below describes how each member of the array should specify the field and scale function to be used.\n * Often, the last item in the list is a string, providing a \"default\" value if all scale functions evaluate to null.\n *\n * @typedef {object[]|string} ScalableParameter\n * @property {string} [field] The name of the field to use in the scale function. If omitted, all fields for the given\n * datum element will be passed to the scale function.\n * @property {module:LocusZoom_ScaleFunctions} scale_function The name of a scale function that will be run on each individual datum\n * @property {object} parameters A set of parameters that configure the desired scale function (options vary by function)\n */\n\n\n/**\n * @typedef {Object} module:LocusZoom_DataLayers~behavior\n * @property {'set'|'unset'|'toggle'|'link'} action\n * @property {'highlighted'|'selected'|'faded'|'hidden'} status An element display status to set/unset/toggle\n * @property {boolean} exclusive Whether an element status should be exclusive (eg only allow one point to be selected at a time)\n * @property {string} href For links, the URL to visit when clicking\n * @property {string} target For links, the `target` attribute (eg, name of a window or tab in which to open this link)\n */\n\n\n/**\n * @typedef {object} FilterOption\n * @property {string} field The name of a field found within each datapoint datum\n * @property {module:LocusZoom_MatchFunctions} operator The name of a comparison function to use when deciding if the\n * field satisfies this filter\n * @property value The target value to compare to\n */\n\n\n/**\n * @typedef {object} LegendItem\n * @property [shape] This is optional (e.g. a legend element could just be a textual label).\n * Supported values are the standard d3 3.x symbol types (i.e. \"circle\", \"cross\", \"diamond\", \"square\",\n * \"triangle-down\", and \"triangle-up\"), as well as \"rect\" for an arbitrary square/rectangle or line for a path.\n * @property {string} color The point color (hexadecimal, rgb, etc)\n * @property {string} label The human-readable label of the legend item\n * @property {string} [class] The name of a CSS class used to style the point in the legend\n * @property {number} [size] The point area for each element (if the shape is a d3 symbol). Eg, for a 40 px area,\n * a circle would be ~7..14 px in diameter.\n * @property {number} [length] Length (in pixels) for the path rendered as the graphical portion of the legend element\n * if the value of the shape parameter is \"line\".\n * @property {number} [width] Width (in pixels) for the rect rendered as the graphical portion of the legend element if\n * the value of the shape parameter is \"rect\".\n * @property {number} [height] Height (in pixels) for the rect rendered as the graphical portion of the legend element if\n * the value of the shape parameter is \"rect\".\n * @property {object} style CSS styles object to be applied to the DOM element representing the graphical portion of\n * the legend element.\n */\n\n\n/**\n * A basic description of keys expected in all data layer layouts. Not intended to be directly used or modified by an end user.\n * @memberof module:LocusZoom_DataLayers~BaseDataLayer\n * @protected\n * @type {{type: string, fields: Array, x_axis: {}, y_axis: {}}}\n */\nconst default_layout = {\n id: '',\n type: '',\n tag: 'custom_data_type',\n fields: [],\n id_field: 'id',\n filters: null,\n match: {},\n x_axis: {},\n y_axis: {}, // Axis options vary based on data layer type\n legend: null,\n tooltip: {},\n tooltip_positioning: 'horizontal', // Where to draw tooltips relative to the point. Can be \"vertical\" or \"horizontal\"\n behaviors: {},\n};\n\n/**\n * A data layer is an abstract class representing a data set and its graphical representation within a panel\n * @public\n*/\nclass BaseDataLayer {\n /**\n * @param {string} [layout.id=''] An identifier string that must be unique across all layers within the same panel\n * @param {string} [layout.type=''] The type of data layer. This parameter is used in layouts to specify which class\n * (from the registry) is created; it is also used in CSS class names.\n * @param {string} [layout.tag='custom_data_type'] Tags have no functional purpose, but they can be used\n * as a semantic label for what is being displayed in this element. This makes it easy to write custom code like \"find every data\n * layer that shows association scatter plots, anywhere\": even if the IDs are different, the tag can be the same.\n * Most built-in data layers will contain a tag that describes, in human-readable terms, what kind of data is being shown.\n * (see: {@link LayoutRegistry.mutate_attrs})\n * @param {String[]} layout.fields A list of (namespaced) fields specifying what data is used by the layer. Only\n * these fields will be made available to the data layer, and only data sources (namespaces) referred to in\n * this array will be fetched. This represents the \"contract\" between what data is returned and what data is rendered.\n * This fields array works in concert with the data retrieval method BaseAdapter.extractFields.\n * @param {string} [layout.id_field] The datum field used for unique element IDs when addressing DOM elements, mouse\n * events, etc. This should be unique to the specified datum.\n * @param {module:LocusZoom_DataLayers~FilterOption[]} [layout.filters] If present, restricts the list of data elements to be displayed. Typically, filters\n * hide elements, but arrange the layer so as to leave the space those elements would have occupied. The exact\n * details vary from one layer to the next. See the Interactivity Tutorial for details.\n * @param {object} [layout.match] An object describing how to connect this data layer to other data layers in the\n * same plot. Specifies keys `send` and `receive` containing the names of fields with data to be matched;\n * `operator` specifies the name of a MatchFunction to use. If a datum matches the broadcast value, it will be\n * marked with the special field `lz_is_match=true`, which can be used in any scalable layout directive to control how the item is rendered.\n * @param {boolean} [layout.x_axis.decoupled=false] If true, the data in this layer will not influence the x-extent of the panel.\n * @param {'state'|null} [layout.x_axis.extent] If provided, the region plot x-extent will be determined from\n * `plot.state` rather than from the range of the data. This is the most common way of setting x-extent,\n * as it is useful for drawing a set of panels to reflect a particular genomic region.\n * @param {number} [layout.x_axis.floor] The low end of the x-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {number} [layout.x_axis.ceiling] The high end of the x-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {Number[]} [layout.x_axis.min_extent] The smallest possible range [min, max] of the x-axis. If the actual values lie outside the extent, the actual data takes precedence.\n * @param {number} [layout.x_axis.field] The datum field to look at when determining data extent along the x-axis.\n * @param {number} [layout.x_axis.lower_buffer] Amount to expand (pad) the lower end of an axis as a proportion of the extent of the data.\n * @param {number} [layout.x_axis.upper_buffer] Amount to expand (pad) the higher end of an axis as a proportion of the extent of the data.\n * @param {boolean} [layout.y_axis.decoupled=false] If true, the data in this layer will not influence the y-extent of the panel.\n * @param {object} [layout.y_axis.axis=1] Which y axis to use for this data layer (left=1, right=2)\n * @param {number} [layout.y_axis.floor] The low end of the y-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {number} [layout.y_axis.ceiling] The high end of the y-extent, which overrides any actual data range, min_extent, or buffer options.\n * @param {Number[]} [layout.y_axis.min_extent] The smallest possible range [min, max] of the y-axis. Actual lower or higher data values will take precedence.\n * @param {number} [layout.y_axis.field] The datum field to look at when determining data extent along the y-axis.\n * @param {number} [layout.y_axis.lower_buffer] Amount to expand (pad) the lower end of an axis as a proportion of the extent of the data.\n * @param {number} [layout.y_axis.upper_buffer] Amount to expand (pad) the higher end of an axis as a proportion of the extent of the data.\n * @param {object} [layout.tooltip.show] Define when to show a tooltip in terms of interaction states, eg, `{ or: ['highlighted', 'selected'] }`\n * @param {object} [layout.tooltip.hide] Define when to hide a tooltip in terms of interaction states, eg, `{ and: ['unhighlighted', 'unselected'] }`\n * @param {boolean} [layout.tooltip.closable] Whether a tool tip should render a \"close\" button in the upper right corner.\n * @param {string} [layout.tooltip.html] HTML template to render inside the tool tip. The template syntax uses curly braces to allow simple expressions:\n * eg `{{sourcename:fieldname}} to insert a field value from the datum associated with\n * the tooltip/element. Conditional tags are supported using the format:\n * `{{#if sourcename:fieldname|transforms_can_be_used_too}}render text here{{#else}}Optional else branch{{/if}}`.\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='horizontal'] Where to draw the tooltip relative to the datum.\n * Typically tooltip positions are centered around the midpoint of the data element, subject to overflow off the edge of the plot.\n * @param {object} [layout.behaviors] LocusZoom data layers support the binding of mouse events to one or more\n * layout-definable behaviors. Some examples of behaviors include highlighting an element on mouseover, or\n * linking to a dynamic URL on click, etc.\n * @param {module:LocusZoom_DataLayers~LegendItem[]} [layout.legend] Tick marks found in the panel legend\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onctrlclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onctrlshiftclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onshiftclick]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onmouseover]\n * @param {module:LocusZoom_DataLayers~behavior[]} [layout.behaviors.onmouseout]\n * @param {Panel|null} parent Where this layout is used\n */\n constructor(layout, parent) {\n /**\n * @private\n * @member {Boolean}\n */\n this.initialized = false;\n /**\n * @private\n * @member {Number}\n */\n this.layout_idx = null;\n\n /**\n * The unique identifier for this layer. Should be unique within this panel.\n * @public\n * @member {String}\n */\n this.id = null;\n\n /**\n * The fully qualified identifier for the data layer, prefixed by any parent or container elements.\n * @type {string}\n * @private\n */\n this._base_id = null;\n\n /**\n * @protected\n * @member {Panel}\n */\n this.parent = parent || null;\n /**\n * @private\n * @member {{group: d3.selection, container: d3.selection, clipRect: d3.selection}}\n */\n this.svg = {};\n\n /**\n * @protected\n * @member {Plot}\n */\n this.parent_plot = null;\n if (parent) {\n this.parent_plot = parent.parent;\n }\n\n /**\n * The current layout configuration for this data layer. This reflects any resizing or dynamically generated\n * config options produced during rendering. Direct layout mutations are a powerful way to dynamically\n * modify the plot in response to user interactions, but require a deep knowledge of LZ internals to use\n * effectively.\n * @public\n * @member {Object}\n */\n this.layout = merge(layout || {}, default_layout);\n if (this.layout.id) {\n this.id = this.layout.id;\n }\n\n /**\n * A user-provided function used to filter data for display. If provided, this will override any declarative\n * options in `layout.filters`\n * @private\n * @deprecated\n */\n this._filter_func = null;\n\n // Ensure any axes defined in the layout have an explicit axis number (default: 1)\n if (this.layout.x_axis !== {} && typeof this.layout.x_axis.axis !== 'number') {\n // TODO: Example of x2? if none remove\n this.layout.x_axis.axis = 1;\n }\n if (this.layout.y_axis !== {} && typeof this.layout.y_axis.axis !== 'number') {\n this.layout.y_axis.axis = 1;\n }\n\n /**\n * Values in the layout object may change during rendering etc. Retain a copy of the original data layer state.\n * This is useful for, eg, dynamically generated color schemes that need to start from scratch when new data is\n * loaded: it contains the \"defaults\", not just the result of a calculated value.\n * @ignore\n * @protected\n * @member {Object}\n */\n this._base_layout = deepCopy(this.layout);\n\n /**\n * @private\n * @member {Object}\n */\n this.state = {};\n /**\n * @private\n * @member {String}\n */\n this.state_id = null;\n\n /**\n * @private\n * @member {Object}\n * */\n this.layer_state = null;\n // Create a default state (and set any references to the parent as appropriate)\n this._setDefaultState();\n\n // Initialize parameters for storing data and tool tips\n /**\n * The data retrieved from a region request. This field is useful for debugging, but will be overridden on\n * re-render; do not modify it directly. The point annotation cache can be used to preserve markings\n * after re-render.\n * @protected\n * @member {Array}\n */\n this.data = [];\n if (this.layout.tooltip) {\n /**\n * @private\n * @member {Object}\n */\n this.tooltips = {};\n }\n\n // Initialize flags for tracking global statuses\n this.global_statuses = {\n 'highlighted': false,\n 'selected': false,\n 'faded': false,\n 'hidden': false,\n };\n }\n\n /****** Public interface: methods for external manipulation */\n\n /**\n * @public\n */\n render() {\n throw new Error('Method must be implemented');\n }\n\n /**\n * Move a data layer forward relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveForward() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index + 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Move a data layer back relative to others by z-index\n * @public\n * @returns {BaseDataLayer}\n */\n moveBack() {\n if (this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1]) {\n this.parent.data_layer_ids_by_z_index[this.layout.z_index] = this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1];\n this.parent.data_layer_ids_by_z_index[this.layout.z_index - 1] = this.id;\n this.parent.resortDataLayers();\n }\n return this;\n }\n\n /**\n * Set an \"annotation\": a piece of additional information about a point that is preserved across re-render,\n * or as the user pans and zooms near this region.\n *\n * Annotations can be referenced as a named pseudo-field in any filters and scalable parameters. (template support\n * may be added in the future)\n * Sample use case: user clicks a tooltip to \"label this specific point\". (or change any other display property)\n *\n * @public\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} key The name of the annotation to track\n * @param {*} value The value of the marked field\n */\n setElementAnnotation (element, key, value) {\n const id = this.getElementId(element);\n if (!this.layer_state.extra_fields[id]) {\n this.layer_state.extra_fields[id] = {};\n }\n this.layer_state.extra_fields[id][key] = value;\n return this;\n }\n\n /**\n * Select a filter function to be applied to the data. DEPRECATED: Please use the LocusZoom.MatchFunctions registry\n * and reference via declarative filters.\n * @param func\n * @deprecated\n */\n setFilter(func) {\n console.warn('The setFilter method is deprecated and will be removed in the future; please use the layout API with a custom filter function instead');\n this._filter_func = func;\n }\n\n /********** Protected methods: useful in subclasses to manipulate data layer behaviors */\n /**\n * Implementation hook for fetching the min and max values of available data. Used to determine axis range, if no other\n * explicit axis settings override. Useful for data layers where the data extent depends on more than one field.\n * (eg confidence intervals in a forest plot)\n *\n * @protected\n * @param data\n * @param axis_config The configuration object for the specified axis.\n * @returns {Array} [min, max] without any padding applied\n */\n _getDataExtent (data, axis_config) {\n data = data || this.data;\n // By default this depends only on a single field.\n return d3.extent(data, (d) => {\n const f = new Field(axis_config.field);\n return +f.resolve(d);\n });\n }\n\n /**\n * Fetch the fully qualified ID to be associated with a specific visual element, based on the data to which that\n * element is bound. In general this element ID will be unique, allowing it to be addressed directly via selectors.\n * @protected\n * @param {Object} element\n * @returns {String}\n */\n getElementId (element) {\n // Use a cached value if possible\n const id_key = Symbol.for('lzID');\n if (element[id_key]) {\n return element[id_key];\n }\n\n const id_field = this.layout.id_field || 'id';\n if (typeof element[id_field] == 'undefined') {\n throw new Error('Unable to generate element ID');\n }\n const element_id = element[id_field].toString().replace(/\\W/g, '');\n\n // Cache ID value for future calls\n const key = (`${this.getBaseId()}-${element_id}`).replace(/([:.[\\],])/g, '_');\n element[id_key] = key;\n return key;\n }\n\n /**\n * Fetch an ID that may bind a data element to a separate visual node for displaying status\n * Examples of this might be separate visual nodes to show select/highlight statuses, or\n * even a common/shared node to show status across many elements in a set.\n * Abstract method. It should be overridden by data layers that implement seperate status\n * nodes specifically to the use case of the data layer type.\n * @private\n * @param {String|Object} element\n * @returns {String|null}\n */\n getElementStatusNodeId (element) {\n return null;\n }\n\n /**\n * Returns a reference to the underlying data associated with a single visual element in the data layer, as\n * referenced by the unique identifier for the element\n *\n * @ignore\n * @protected\n * @param {String} id The unique identifier for the element, as defined by `getElementId`\n * @returns {Object|null} The data bound to that element\n */\n getElementById(id) {\n const selector = d3.select(`#${id.replace(/([:.[\\],])/g, '\\\\$1')}`); // escape special characters\n if (!selector.empty() && selector.data() && selector.data().length) {\n return selector.data()[0];\n } else {\n return null;\n }\n }\n\n /**\n * Basic method to apply arbitrary methods and properties to data elements.\n * This is called on all data immediately after being fetched. (requires reMap, not just re-render)\n *\n * Allowing a data element to access its parent enables interactive functionality, such as tooltips that modify\n * the parent plot. This is also used for system-derived fields like \"matching\" behavior\".\n *\n * @protected\n * @returns {BaseDataLayer}\n */\n applyDataMethods() {\n const field_to_match = (this.layout.match && this.layout.match.receive);\n const match_function = MATCHERS.get(this.layout.match && this.layout.match.operator || '=');\n const broadcast_value = this.parent_plot.state.lz_match_value;\n // Match functions are allowed to use transform syntax on field values, but not (yet) UI \"annotations\"\n const field_resolver = field_to_match ? new Field(field_to_match) : null;\n this.data.forEach((item, i) => {\n // Basic toHTML() method - return the stringified value in the id_field, if defined.\n\n // When this layer receives data, mark whether points match (via a synthetic boolean field)\n // Any field-based layout directives (color, size, shape) can then be used to control display\n if (field_to_match && broadcast_value !== null && broadcast_value !== undefined) {\n item.lz_is_match = (match_function(field_resolver.resolve(item), broadcast_value));\n }\n\n item.toHTML = () => {\n const id_field = this.layout.id_field || 'id';\n let html = '';\n if (item[id_field]) {\n html = item[id_field].toString();\n }\n return html;\n };\n // Helper methods - return a reference to various plot levels. Useful for interactive tooltips.\n item.getDataLayer = () => this;\n item.getPanel = () => this.parent || null;\n item.getPlot = () => {\n // For unit testing etc, this layer may be created without a parent.\n const panel = this.parent;\n return panel ? panel.parent : null;\n };\n // deselect() method - shortcut method to deselect the element\n item.deselect = () => {\n const data_layer = this.getDataLayer();\n data_layer.unselectElement(this); // dynamically generated method name. It exists, honest.\n };\n });\n this.applyCustomDataMethods();\n return this;\n }\n\n /**\n * Hook that allows custom datalayers to apply additional methods and properties to data elements as needed.\n * Most data layers will never need to use this.\n * @protected\n * @returns {BaseDataLayer}\n */\n applyCustomDataMethods() {\n return this;\n }\n\n /**\n * Apply scaling functions to an element as needed, based on the layout rules governing display + the element's data\n * If the layout parameter is already a primitive type, simply return the value as given\n *\n * In the future this may be further expanded, so that scaling functions can operate similar to mappers\n * (item, index, array). Additional arguments would be added as the need arose.\n *\n * @private\n * @param {Array|Number|String|Object} option_layout Either a scalar (\"color is red\") or a configuration object\n * (\"rules for how to choose color based on item value\")\n * @param {*} element_data The value to be used with the filter. May be a primitive value, or a data object for a single item\n * @param {Number} data_index The array index for the data element\n * @returns {*} The transformed value\n */\n resolveScalableParameter (option_layout, element_data, data_index) {\n let ret = null;\n if (Array.isArray(option_layout)) {\n let idx = 0;\n while (ret === null && idx < option_layout.length) {\n ret = this.resolveScalableParameter(option_layout[idx], element_data, data_index);\n idx++;\n }\n } else {\n switch (typeof option_layout) {\n case 'number':\n case 'string':\n ret = option_layout;\n break;\n case 'object':\n if (option_layout.scale_function) {\n const func = SCALABLE.get(option_layout.scale_function);\n if (option_layout.field) {\n const f = new Field(option_layout.field);\n let extra;\n try {\n extra = this.getElementAnnotation(element_data);\n } catch (e) {\n extra = null;\n }\n ret = func(option_layout.parameters || {}, f.resolve(element_data, extra), data_index);\n } else {\n ret = func(option_layout.parameters || {}, element_data, data_index);\n }\n }\n break;\n }\n }\n return ret;\n }\n\n /**\n * Generate dimension extent function based on layout parameters\n * @ignore\n * @protected\n * @param {('x'|'y')} dimension\n */\n getAxisExtent (dimension) {\n\n if (!['x', 'y'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n\n const axis_name = `${dimension}_axis`;\n const axis_layout = this.layout[axis_name];\n\n // If a floor AND a ceiling are explicitly defined then just return that extent and be done\n if (!isNaN(axis_layout.floor) && !isNaN(axis_layout.ceiling)) {\n return [+axis_layout.floor, +axis_layout.ceiling];\n }\n\n // If a field is defined for the axis and the data layer has data then generate the extent from the data set\n let data_extent = [];\n if (axis_layout.field && this.data) {\n if (!this.data.length) {\n // If data has been fetched (but no points in region), enforce the min_extent (with no buffers,\n // because we don't need padding around an empty screen)\n data_extent = axis_layout.min_extent || [];\n return data_extent;\n } else {\n data_extent = this._getDataExtent(this.data, axis_layout);\n\n // Apply upper/lower buffers, if applicable\n const original_extent_span = data_extent[1] - data_extent[0];\n if (!isNaN(axis_layout.lower_buffer)) {\n data_extent[0] -= original_extent_span * axis_layout.lower_buffer;\n }\n if (!isNaN(axis_layout.upper_buffer)) {\n data_extent[1] += original_extent_span * axis_layout.upper_buffer;\n }\n\n if (typeof axis_layout.min_extent == 'object') {\n // The data should span at least the range specified by min_extent, an array with [low, high]\n const range_min = axis_layout.min_extent[0];\n const range_max = axis_layout.min_extent[1];\n if (!isNaN(range_min) && !isNaN(range_max)) {\n data_extent[0] = Math.min(data_extent[0], range_min);\n }\n if (!isNaN(range_max)) {\n data_extent[1] = Math.max(data_extent[1], range_max);\n }\n }\n // If specified, floor and ceiling will override the actual data range\n return [\n isNaN(axis_layout.floor) ? data_extent[0] : axis_layout.floor,\n isNaN(axis_layout.ceiling) ? data_extent[1] : axis_layout.ceiling,\n ];\n }\n }\n\n // If this is for the x axis and no extent could be generated yet but state has a defined start and end\n // then default to using the state-defined region as the extent\n if (dimension === 'x' && !isNaN(this.state.start) && !isNaN(this.state.end)) {\n return [this.state.start, this.state.end];\n }\n\n // No conditions met for generating a valid extent, return an empty array\n return [];\n\n }\n\n /**\n * Allow this data layer to tell the panel what axis ticks it thinks it will require. The panel may choose whether\n * to use some, all, or none of these when rendering, either alone or in conjunction with other data layers.\n *\n * This method is a stub and should be overridden in data layers that need to specify custom behavior.\n *\n * @protected\n * @param {('x'|'y1'|'y2')} dimension\n * @param {Object} [config] Additional parameters for the panel to specify how it wants ticks to be drawn. The names\n * and meanings of these parameters may vary between different data layers.\n * @returns {Object[]}\n * An array of objects: each object must have an 'x' attribute to position the tick.\n * Other supported object keys:\n * * text: string to render for a given tick\n * * style: d3-compatible CSS style object\n * * transform: SVG transform attribute string\n * * color: string or LocusZoom scalable parameter object\n */\n getTicks (dimension, config) {\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n return [];\n }\n\n /**\n * Determine the coordinates for where to point the tooltip at. Typically, this is the center of a datum element (eg,\n * the middle of a scatter plot point). Also provide an offset if the tooltip should not be at that center (most\n * elements are not single points, eg a scatter plot point has a radius and a gene is a rectangle).\n * The default implementation is quite naive: it places the tooltip at the origin for that layer. Individual layers\n * should override this method to position relative to the chosen data element or mouse event.\n * @protected\n * @param {Object} tooltip A tooltip object (including attribute tooltip.data)\n * @returns {Object} as {x_min, x_max, y_min, y_max} in px, representing bounding box of a rectangle around the data pt\n * Note that these pixels are in the SVG coordinate system\n */\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n const y_extent = panel[`y${this.layout.y_axis.axis}_extent`];\n\n const x = panel.x_scale(panel.x_extent[0]);\n const y = y_scale(y_extent[0]);\n\n return { x_min: x, x_max: x, y_min: y, y_max: y };\n }\n\n /**\n * Draw a tooltip on the data layer pointed at the specified coordinates, in the specified orientation.\n * Tooltip will be drawn on the edge of the major axis, and centered along the minor axis- see diagram.\n * v\n * > o <\n * ^\n *\n * @protected\n * @param tooltip {Object} The object representing all data for the tooltip to be drawn\n * @param {'vertical'|'horizontal'|'top'|'bottom'|'left'|'right'} position Where to draw the tooltip relative to\n * the data\n * @param {Number} x_min The min x-coordinate for the bounding box of the data element\n * @param {Number} x_max The max x-coordinate for the bounding box of the data element\n * @param {Number} y_min The min y-coordinate for the bounding box of the data element\n * @param {Number} y_max The max y-coordinate for the bounding box of the data element\n */\n _drawTooltip(tooltip, position, x_min, x_max, y_min, y_max) {\n const panel_layout = this.parent.layout;\n const plot_layout = this.parent_plot.layout;\n const layer_layout = this.layout;\n\n // Tooltip position params: as defined in the default stylesheet, used in calculations\n const arrow_size = 7;\n const stroke_width = 1;\n const arrow_total = arrow_size + stroke_width; // Tooltip pos should account for how much space the arrow takes up\n\n const tooltip_padding = 6; // bbox size must account for any internal padding applied between data and border\n\n const page_origin = this._getPageOrigin();\n const tooltip_box = tooltip.selector.node().getBoundingClientRect();\n const data_layer_height = panel_layout.height - (panel_layout.margin.top + panel_layout.margin.bottom);\n const data_layer_width = plot_layout.width - (panel_layout.margin.left + panel_layout.margin.right);\n\n // Clip the edges of the datum to the available plot area\n x_min = Math.max(x_min, 0);\n x_max = Math.min(x_max, data_layer_width);\n y_min = Math.max(y_min, 0);\n y_max = Math.min(y_max, data_layer_height);\n\n const x_center = (x_min + x_max) / 2;\n const y_center = (y_min + y_max) / 2;\n // Default offsets are the far edge of the datum bounding box\n let x_offset = x_max - x_center;\n let y_offset = y_max - y_center;\n let placement = layer_layout.tooltip_positioning;\n\n // Coordinate system note: the tooltip is positioned relative to the plot/page; the arrow is positioned relative to\n // the tooltip boundaries\n let tooltip_top, tooltip_left, arrow_type, arrow_top, arrow_left;\n\n // The user can specify a generic orientation, and LocusZoom will autoselect whether to place the tooltip above or below\n if (placement === 'vertical') {\n // Auto-select whether to position above the item, or below\n x_offset = 0;\n if (tooltip_box.height + arrow_total > data_layer_height - (y_center + y_offset)) {\n placement = 'top';\n } else {\n placement = 'bottom';\n }\n } else if (placement === 'horizontal') {\n // Auto select whether to position to the left of the item, or to the right\n y_offset = 0;\n if (x_center <= plot_layout.width / 2) {\n placement = 'left';\n } else {\n placement = 'right';\n }\n }\n\n if (placement === 'top' || placement === 'bottom') {\n // Position horizontally centered above the point\n const offset_right = Math.max((tooltip_box.width / 2) - x_center, 0);\n const offset_left = Math.max((tooltip_box.width / 2) + x_center - data_layer_width, 0);\n tooltip_left = page_origin.x + x_center - (tooltip_box.width / 2) - offset_left + offset_right;\n arrow_left = page_origin.x + x_center - tooltip_left - arrow_size; // Arrow should be centered over the data\n // Position vertically above the point unless there's insufficient space, then go below\n if (placement === 'top') {\n tooltip_top = page_origin.y + y_center - (y_offset + tooltip_box.height + arrow_total);\n arrow_type = 'down';\n arrow_top = tooltip_box.height - stroke_width;\n } else {\n tooltip_top = page_origin.y + y_center + y_offset + arrow_total;\n arrow_type = 'up';\n arrow_top = 0 - arrow_total;\n }\n } else if (placement === 'left' || placement === 'right') {\n // Position tooltip horizontally on the left or the right depending on which side of the plot the point is on\n if (placement === 'left') {\n tooltip_left = page_origin.x + x_center + x_offset + arrow_total;\n arrow_type = 'left';\n arrow_left = -1 * (arrow_size + stroke_width);\n } else {\n tooltip_left = page_origin.x + x_center - tooltip_box.width - x_offset - arrow_total;\n arrow_type = 'right';\n arrow_left = tooltip_box.width - stroke_width;\n }\n // Position with arrow vertically centered along tooltip edge unless we're at the top or bottom of the plot\n if (y_center - (tooltip_box.height / 2) <= 0) { // Too close to the top, push it down\n tooltip_top = page_origin.y + y_center - (1.5 * arrow_size) - tooltip_padding;\n arrow_top = tooltip_padding;\n } else if (y_center + (tooltip_box.height / 2) >= data_layer_height) { // Too close to the bottom, pull it up\n tooltip_top = page_origin.y + y_center + arrow_size + tooltip_padding - tooltip_box.height;\n arrow_top = tooltip_box.height - (2 * arrow_size) - tooltip_padding;\n } else { // vertically centered\n tooltip_top = page_origin.y + y_center - (tooltip_box.height / 2);\n arrow_top = (tooltip_box.height / 2) - arrow_size;\n }\n } else {\n throw new Error('Unrecognized placement value');\n }\n\n // Position the div itself, relative to the layer origin\n tooltip.selector\n .style('left', `${tooltip_left}px`)\n .style('top', `${tooltip_top}px`);\n // Create / update position on arrow connecting tooltip to data\n if (!tooltip.arrow) {\n tooltip.arrow = tooltip.selector.append('div')\n .style('position', 'absolute');\n }\n tooltip.arrow\n .attr('class', `lz-data_layer-tooltip-arrow_${arrow_type}`)\n .style('left', `${arrow_left}px`)\n .style('top', `${arrow_top}px`);\n return this;\n }\n\n /**\n * Determine whether a given data element matches all predefined filter criteria, usually as specified in a layout directive.\n *\n * Typically this is used with array.filter (the first argument is curried, `this.filter.bind(this, options)`\n * @private\n * @param {Object[]} filter_rules A list of rule entries: {field, value, operator} describing each filter.\n * Operator must be from a list of built-in operators. If the field is omitted, the entire datum object will be\n * passed to the filter, rather than a single scalar value. (this is only useful with custom `MatchFunctions` as operator)\n * @param {Object} item\n * @param {Number} index\n * @param {Array} array\n * @returns {Boolean} Whether the specified item is a match\n */\n filter(filter_rules, item, index, array) {\n let is_match = true;\n filter_rules.forEach((filter) => { // Try each filter on this item, in sequence\n const {field, operator, value: target} = filter;\n const test_func = MATCHERS.get(operator);\n\n // Return the field value or annotation. If no `field` is specified, the filter function will operate on\n // the entire data object. This behavior is only really useful with custom functions, because the\n // builtin ones expect to receive a scalar value\n const extra = this.getElementAnnotation(item);\n const field_value = field ? (new Field(field)).resolve(item, extra) : item;\n if (!test_func(field_value, target)) {\n is_match = false;\n }\n });\n return is_match;\n }\n\n /**\n * Get \"annotation\" metadata associated with a particular point.\n *\n * @protected\n * @param {String|Object} element The data object or ID string for the element\n * @param {String} [key] The name of the annotation to track. If omitted, returns all annotations for this element as an object.\n * @return {*}\n */\n getElementAnnotation (element, key) {\n const id = this.getElementId(element);\n const extra = this.layer_state.extra_fields[id];\n return key ? (extra && extra[key]) : extra;\n }\n\n /****** Private methods: rarely overridden or modified by external usages */\n\n /**\n * Apply filtering options to determine the set of data to render\n *\n * This must be applied on rendering, not fetch, so that the axis limits reflect the true range of the dataset\n * Otherwise, two stacked panels (same dataset filtered in different ways) might not line up on the x-axis when\n * filters are applied.\n * @param data\n * @return {*}\n * @private\n */\n _applyFilters(data) {\n data = data || this.data;\n\n if (this._filter_func) {\n data = data.filter(this._filter_func);\n } else if (this.layout.filters) {\n data = data.filter(this.filter.bind(this, this.layout.filters));\n }\n return data;\n }\n\n /**\n * Define default state that should get tracked during the lifetime of this layer.\n *\n * In some special custom usages, it may be useful to completely reset a panel (eg \"click for\n * genome region\" links), plotting new data that invalidates any previously tracked state. This hook makes it\n * possible to reset without destroying the panel entirely. It is used by `Plot.clearPanelData`.\n * @private\n */\n _setDefaultState() {\n // Each datalayer tracks two kinds of status: flags for internal state (highlighted, selected, tooltip),\n // and \"extra fields\" (annotations like \"show a tooltip\" that are not determined by the server, but need to\n // persist across re-render)\n const layer_state = { status_flags: {}, extra_fields: {} };\n const status_flags = layer_state.status_flags;\n STATUSES.adjectives.forEach((status) => {\n status_flags[status] = status_flags[status] || new Set();\n });\n // Also initialize \"internal-only\" state fields (things that are tracked, but not set directly by external events)\n status_flags['has_tooltip'] = status_flags['has_tooltip'] || new Set();\n\n if (this.parent) {\n // If layer has a parent, store a reference in the overarching plot.state object\n this.state_id = `${this.parent.id}.${this.id}`;\n this.state = this.parent.state;\n this.state[this.state_id] = layer_state;\n }\n this.layer_state = layer_state;\n }\n\n /**\n * Get the fully qualified identifier for the data layer, prefixed by any parent or container elements\n *\n * @private\n * @returns {string} A dot-delimited string of the format ..\n */\n getBaseId () {\n if (this._base_id) {\n return this._base_id;\n }\n\n if (this.parent) {\n return `${this.parent_plot.id}.${this.parent.id}.${this.id}`;\n } else {\n return (this.id || '').toString();\n }\n }\n\n /**\n * Determine the pixel height of data-bound objects represented inside this data layer. (excluding elements such as axes)\n *\n * May be used by operations that resize the data layer to fit available data\n *\n * @private\n * @returns {number}\n */\n getAbsoluteDataHeight() {\n const dataBCR = this.svg.group.node().getBoundingClientRect();\n return dataBCR.height;\n }\n\n /**\n * Initialize a data layer\n * @private\n * @returns {BaseDataLayer}\n */\n initialize() {\n this._base_id = this.getBaseId();\n\n // Append a container group element to house the main data layer group element and the clip path\n const base_id = this.getBaseId();\n this.svg.container = this.parent.svg.group.append('g')\n .attr('class', 'lz-data_layer-container')\n .attr('id', `${base_id}.data_layer_container`);\n\n // Append clip path to the container element\n this.svg.clipRect = this.svg.container.append('clipPath')\n .attr('id', `${base_id}.clip`)\n .append('rect');\n\n // Append svg group for rendering all data layer elements, clipped by the clip path\n this.svg.group = this.svg.container.append('g')\n .attr('id', `${base_id}.data_layer`)\n .attr('clip-path', `url(#${base_id}.clip)`);\n\n return this;\n\n }\n\n /**\n * Generate a tool tip for a given element\n * @private\n * @param {String|Object} data Data for the element associated with the tooltip\n */\n createTooltip (data) {\n if (typeof this.layout.tooltip != 'object') {\n throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`);\n }\n const id = this.getElementId(data);\n if (this.tooltips[id]) {\n this.positionTooltip(id);\n return;\n }\n this.tooltips[id] = {\n data: data,\n arrow: null,\n selector: d3.select(this.parent_plot.svg.node().parentNode).append('div')\n .attr('class', 'lz-data_layer-tooltip')\n .attr('id', `${id}-tooltip`),\n };\n this.layer_state.status_flags['has_tooltip'].add(id);\n this.updateTooltip(data);\n return this;\n }\n\n /**\n * Update a tool tip (generate its inner HTML)\n *\n * @private\n * @param {String|Object} d The element associated with the tooltip\n * @param {String} [id] An identifier to the tooltip\n */\n updateTooltip(d, id) {\n if (typeof id == 'undefined') {\n id = this.getElementId(d);\n }\n // Empty the tooltip of all HTML (including its arrow!)\n this.tooltips[id].selector.html('');\n this.tooltips[id].arrow = null;\n // Set the new HTML\n if (this.layout.tooltip.html) {\n this.tooltips[id].selector.html(parseFields(this.layout.tooltip.html, d, this.getElementAnnotation(d)));\n }\n // If the layout allows tool tips on this data layer to be closable then add the close button\n // and add padding to the tooltip to accommodate it\n if (this.layout.tooltip.closable) {\n this.tooltips[id].selector.insert('button', ':first-child')\n .attr('class', 'lz-tooltip-close-button')\n .attr('title', 'Close')\n .text('×')\n .on('click', () => {\n this.destroyTooltip(id);\n });\n }\n // Apply data directly to the tool tip for easier retrieval by custom UI elements inside the tool tip\n this.tooltips[id].selector.data([d]);\n // Reposition and draw a new arrow\n this.positionTooltip(id);\n return this;\n }\n\n /**\n * Destroy tool tip - remove the tool tip element from the DOM and delete the tool tip's record on the data layer\n *\n * @private\n * @param {String|Object} element_or_id The element (or id) associated with the tooltip\n * @param {boolean} [temporary=false] Whether this is temporary (not to be tracked in state). Differentiates\n * \"recreate tooltips on re-render\" (which is temporary) from \"user has closed this tooltip\" (permanent)\n * @returns {BaseDataLayer}\n */\n destroyTooltip(element_or_id, temporary) {\n let id;\n if (typeof element_or_id == 'string') {\n id = element_or_id;\n } else {\n id = this.getElementId(element_or_id);\n }\n if (this.tooltips[id]) {\n if (typeof this.tooltips[id].selector == 'object') {\n this.tooltips[id].selector.remove();\n }\n delete this.tooltips[id];\n }\n // When a tooltip is removed, also remove the reference from the state\n if (!temporary) {\n const tooltip_state = this.layer_state.status_flags['has_tooltip'];\n tooltip_state.delete(id);\n }\n return this;\n }\n\n /**\n * Loop through and destroy all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n destroyAllTooltips(temporary = true) {\n for (let id in this.tooltips) {\n this.destroyTooltip(id, temporary);\n }\n return this;\n }\n\n /**\n * Position and then redraw tool tip - naïve function to place a tool tip in the data layer. By default, positions wrt\n * the top-left corner of the data layer.\n *\n * Each layer type may have more specific logic. Consider overriding the provided hooks `_getTooltipPosition` or\n * `_drawTooltip` as appropriate\n *\n * @private\n * @param {String} id The identifier of the tooltip to position\n * @returns {BaseDataLayer}\n */\n positionTooltip(id) {\n if (typeof id != 'string') {\n throw new Error('Unable to position tooltip: id is not a string');\n }\n if (!this.tooltips[id]) {\n throw new Error('Unable to position tooltip: id does not point to a valid tooltip');\n }\n const tooltip = this.tooltips[id];\n const coords = this._getTooltipPosition(tooltip);\n\n if (!coords) {\n // Special cutout: normally, tooltips are positioned based on the datum element. Some, like lines/curves,\n // work better if based on a mouse event. Since not every redraw contains a mouse event, we can just skip\n // calculating position when no position information is available.\n return null;\n }\n this._drawTooltip(tooltip, this.layout.tooltip_positioning, coords.x_min, coords.x_max, coords.y_min, coords.y_max);\n }\n\n /**\n * Loop through and position all tool tips on this data layer\n *\n * @private\n * @returns {BaseDataLayer}\n */\n positionAllTooltips() {\n for (let id in this.tooltips) {\n this.positionTooltip(id);\n }\n return this;\n }\n\n /**\n * Show or hide a tool tip by ID depending on directives in the layout and state values relative to the ID\n *\n * @private\n * @param {String|Object} element The element associated with the tooltip\n * @param {boolean} first_time Because panels can re-render, the rules for showing a tooltip\n * depend on whether this is the first time a status change affecting display has been applied.\n * @returns {BaseDataLayer}\n */\n showOrHideTooltip(element, first_time) {\n if (typeof this.layout.tooltip != 'object') {\n return this;\n }\n const id = this.getElementId(element);\n\n /**\n * Apply rules and decide whether to show or hide the tooltip\n * @param {Object} statuses All statuses that apply to an element\n * @param {String[]|object} directive A layout directive object\n * @param operator\n * @returns {null|bool}\n */\n const resolveStatus = (statuses, directive, operator) => {\n let status = null;\n if (typeof statuses != 'object' || statuses === null) {\n return null;\n }\n if (Array.isArray(directive)) {\n // This happens when the function is called on the inner part of the directive\n operator = operator || 'and';\n if (directive.length === 1) {\n status = statuses[directive[0]];\n } else {\n status = directive.reduce((previousValue, currentValue) => {\n if (operator === 'and') {\n return statuses[previousValue] && statuses[currentValue];\n } else if (operator === 'or') {\n return statuses[previousValue] || statuses[currentValue];\n }\n return null;\n });\n }\n } else if (typeof directive == 'object') {\n let sub_status;\n for (let sub_operator in directive) {\n sub_status = resolveStatus(statuses, directive[sub_operator], sub_operator);\n if (status === null) {\n status = sub_status;\n } else if (operator === 'and') {\n status = status && sub_status;\n } else if (operator === 'or') {\n status = status || sub_status;\n }\n }\n } else {\n return false;\n }\n return status;\n };\n\n let show_directive = {};\n if (typeof this.layout.tooltip.show == 'string') {\n show_directive = { and: [ this.layout.tooltip.show ] };\n } else if (typeof this.layout.tooltip.show == 'object') {\n show_directive = this.layout.tooltip.show;\n }\n\n let hide_directive = {};\n if (typeof this.layout.tooltip.hide == 'string') {\n hide_directive = { and: [ this.layout.tooltip.hide ] };\n } else if (typeof this.layout.tooltip.hide == 'object') {\n hide_directive = this.layout.tooltip.hide;\n }\n\n // Find all the statuses that apply to just this single element\n const layer_state = this.layer_state;\n var status_flags = {}; // {status_name: bool}\n STATUSES.adjectives.forEach((status) => {\n const antistatus = `un${status}`;\n status_flags[status] = (layer_state.status_flags[status].has(id));\n status_flags[antistatus] = !status_flags[status];\n });\n\n // Decide whether to show/hide the tooltip based solely on the underlying element\n const show_resolved = resolveStatus(status_flags, show_directive);\n const hide_resolved = resolveStatus(status_flags, hide_directive);\n\n // Most of the tooltip display logic depends on behavior layouts: was point (un)selected, (un)highlighted, etc.\n // But sometimes, a point is selected, and the user then closes the tooltip. If the panel is re-rendered for\n // some outside reason (like state change), we must track this in the create/destroy events as tooltip state.\n const has_tooltip = (layer_state.status_flags['has_tooltip'].has(id));\n const tooltip_was_closed = first_time ? false : !has_tooltip;\n if (show_resolved && !tooltip_was_closed && !hide_resolved) {\n this.createTooltip(element);\n } else {\n this.destroyTooltip(element);\n }\n\n return this;\n }\n\n /**\n * Toggle a status (e.g. highlighted, selected, identified) on an element\n *\n * @private\n * @fires event:layout_changed\n * @fires event:element_selection\n * @fires event:match_requested\n * @param {String} status The name of a recognized status to be added/removed on an appropriate element\n * @param {String|Object} element The data bound to the element of interest\n * @param {Boolean} active True to add the status (and associated CSS styles); false to remove it\n * @param {Boolean} exclusive Whether to only allow a state for a single element at a time\n * @returns {BaseDataLayer}\n */\n setElementStatus(status, element, active, exclusive) {\n if (status === 'has_tooltip') {\n // This is a special adjective that exists solely to track tooltip state. It has no CSS and never gets set\n // directly. It is invisible to the official enums.\n return this;\n }\n if (typeof active == 'undefined') {\n active = true;\n }\n\n // Get an ID for the element or return having changed nothing\n let element_id;\n try {\n element_id = this.getElementId(element);\n } catch (get_element_id_error) {\n return this;\n }\n\n // Enforce exclusivity (force all elements to have the opposite of toggle first)\n if (exclusive) {\n this.setAllElementStatus(status, !active);\n }\n\n // Set/unset the proper status class on the appropriate DOM element(s), *and* potentially an additional element\n d3.select(`#${element_id}`).classed(`lz-data_layer-${this.layout.type}-${status}`, active);\n const element_status_node_id = this.getElementStatusNodeId(element);\n if (element_status_node_id !== null) {\n d3.select(`#${element_status_node_id}`).classed(`lz-data_layer-${this.layout.type}-statusnode-${status}`, active);\n }\n\n // Track element ID in the proper status state array\n const added_status = !this.layer_state.status_flags[status].has(element_id); // On a re-render, existing statuses will be reapplied.\n if (active && added_status) {\n this.layer_state.status_flags[status].add(element_id);\n }\n if (!active && !added_status) {\n this.layer_state.status_flags[status].delete(element_id);\n }\n\n // Trigger tool tip show/hide logic\n this.showOrHideTooltip(element, added_status);\n\n // Trigger layout changed event hook\n if (added_status) {\n this.parent.emit('layout_changed', true);\n }\n\n const is_selected = (status === 'selected');\n if (is_selected && (added_status || !active)) {\n // Notify parents that an element has changed selection status (either active, or inactive)\n this.parent.emit('element_selection', { element: element, active: active }, true);\n }\n\n const value_to_broadcast = (this.layout.match && this.layout.match.send);\n if (is_selected && (typeof value_to_broadcast !== 'undefined') && (added_status || !active)) {\n this.parent.emit(\n // The broadcast value can use transforms to \"clean up value before sending broadcasting\"\n 'match_requested',\n { value: new Field(value_to_broadcast).resolve(element), active: active },\n true\n );\n }\n return this;\n }\n\n /**\n * Toggle a status on all elements in the data layer\n *\n * @private\n * @param {String} status\n * @param {Boolean} toggle\n * @returns {BaseDataLayer}\n */\n setAllElementStatus(status, toggle) {\n\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Apply statuses\n if (toggle) {\n this.data.forEach((element) => this.setElementStatus(status, element, true));\n } else {\n const status_ids = new Set(this.layer_state.status_flags[status]); // copy so that we don't mutate while iterating\n status_ids.forEach((id) => {\n const element = this.getElementById(id);\n if (typeof element == 'object' && element !== null) {\n this.setElementStatus(status, element, false);\n }\n });\n this.layer_state.status_flags[status] = new Set();\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n return this;\n }\n\n /**\n * Apply all layout-defined behaviors (DOM event handlers) to a selection of elements\n *\n * @private\n * @param {d3.selection} selection\n */\n applyBehaviors(selection) {\n if (typeof this.layout.behaviors != 'object') {\n return;\n }\n Object.keys(this.layout.behaviors).forEach((directive) => {\n const event_match = /(click|mouseover|mouseout)/.exec(directive);\n if (!event_match) {\n return;\n }\n selection.on(`${event_match[0]}.${directive}`, this.executeBehaviors(directive, this.layout.behaviors[directive]));\n });\n }\n\n /**\n * Generate a function that executes an arbitrary list of behaviors on an element during an event\n *\n * @private\n * @param {String} directive The name of the event, as described in layout.behaviors for this datalayer\n * @param {Object[]} behaviors An object describing the behavior to attach to this single element\n * @param {string} behaviors.action The name of the action that would trigger this behavior (eg click, mouseover, etc)\n * @param {string} behaviors.status What status to apply to the element when this behavior is triggered (highlighted,\n * selected, etc)\n * @param {boolean} [behaviors.exclusive] Whether triggering the event for this element should unset the relevant status\n * for all other elements. Useful for, eg, click events that exclusively highlight one thing.\n * @returns {function(this:BaseDataLayer)} Return a function that handles the event in context with the behavior\n * and the element- can be attached as an event listener\n */\n executeBehaviors(directive, behaviors) {\n\n // Determine the required state of control and shift keys during the event\n const requiredKeyStates = {\n 'ctrl': (directive.includes('ctrl')),\n 'shift': (directive.includes('shift')),\n };\n const self = this;\n return function(element) {\n // This method may be used on two kinds of events: directly attached, or bubbled.\n // D3 doesn't natively support bubbling very well; if no data is bound on the currentTarget, check to see\n // if there is data available at wherever the event was initiated from\n element = element || d3.select(d3.event.target).datum();\n\n // Do nothing if the required control and shift key presses (or lack thereof) doesn't match the event\n if (requiredKeyStates.ctrl !== !!d3.event.ctrlKey || requiredKeyStates.shift !== !!d3.event.shiftKey) {\n return;\n }\n\n // Loop through behaviors making each one go in succession\n behaviors.forEach((behavior) => {\n\n // Route first by the action, if defined\n if (typeof behavior != 'object' || behavior === null) {\n return;\n }\n\n switch (behavior.action) {\n\n // Set a status (set to true regardless of current status, optionally with exclusivity)\n case 'set':\n self.setElementStatus(behavior.status, element, true, behavior.exclusive);\n break;\n\n // Unset a status (set to false regardless of current status, optionally with exclusivity)\n case 'unset':\n self.setElementStatus(behavior.status, element, false, behavior.exclusive);\n break;\n\n // Toggle a status\n case 'toggle':\n var current_status_boolean = (self.layer_state.status_flags[behavior.status].has(self.getElementId(element)));\n var exclusive = behavior.exclusive && !current_status_boolean;\n\n self.setElementStatus(behavior.status, element, !current_status_boolean, exclusive);\n break;\n\n // Link to a dynamic URL\n case 'link':\n if (typeof behavior.href == 'string') {\n const url = parseFields(behavior.href, element, self.getElementAnnotation(element));\n if (typeof behavior.target == 'string') {\n window.open(url, behavior.target);\n } else {\n window.location.href = url;\n }\n }\n break;\n\n // Action not defined, just return\n default:\n break;\n }\n });\n };\n }\n\n /**\n * Get an object with the x and y coordinates of the panel's origin in terms of the entire page\n * Necessary for positioning any HTML elements over the panel\n *\n * @private\n * @returns {{x: Number, y: Number}}\n */\n _getPageOrigin() {\n const panel_origin = this.parent._getPageOrigin();\n return {\n x: panel_origin.x + this.parent.layout.margin.left,\n y: panel_origin.y + this.parent.layout.margin.top,\n };\n }\n\n /**\n * Apply all tracked element statuses. This is primarily intended for re-rendering the plot, in order to preserve\n * behaviors when items are updated.\n * @private\n */\n applyAllElementStatus () {\n const status_flags = this.layer_state.status_flags;\n const self = this;\n for (let property in status_flags) {\n if (!Object.prototype.hasOwnProperty.call(status_flags, property)) {\n continue;\n }\n status_flags[property].forEach((element_id) => {\n try {\n this.setElementStatus(property, this.getElementById(element_id), true);\n } catch (e) {\n console.warn(`Unable to apply state: ${self.state_id}, ${property}`);\n console.error(e);\n }\n });\n\n }\n }\n\n /**\n * Position the datalayer and all tooltips\n * @private\n * @returns {BaseDataLayer}\n */\n draw() {\n this.svg.container\n .attr('transform', `translate(${this.parent.layout.cliparea.origin.x}, ${this.parent.layout.cliparea.origin.y})`);\n this.svg.clipRect\n .attr('width', this.parent.layout.cliparea.width)\n .attr('height', this.parent.layout.cliparea.height);\n this.positionAllTooltips();\n return this;\n }\n\n /**\n * Re-Map a data layer to reflect changes in the state of a plot (such as viewing region/ chromosome range)\n *\n * Whereas .render draws whatever data is available, this method resets the view and fetches new data if necessary.\n *\n * @private\n * @return {Promise}\n */\n reMap() {\n this.destroyAllTooltips(); // hack - only non-visible tooltips should be destroyed\n // and then recreated if returning to visibility\n\n // Fetch new data. Datalayers are only given access to the final consolidated data from the chain (not headers or raw payloads)\n return this.parent_plot.lzd.getData(this.state, this.layout.fields)\n .then((new_data) => {\n this.data = new_data.body; // chain.body from datasources\n this.applyDataMethods();\n this.initialized = true;\n });\n }\n}\n\nSTATUSES.verbs.forEach((verb, idx) => {\n const adjective = STATUSES.adjectives[idx];\n const antiverb = `un${verb}`;\n // Set/unset a single element's status\n\n /**\n * @private\n * @function highlightElement\n */\n /**\n * @private\n * @function selectElement\n */\n /**\n * @private\n * @function fadeElement\n */\n /**\n * @private\n * @function hideElement\n */\n BaseDataLayer.prototype[`${verb}Element`] = function(element, exclusive = false) {\n exclusive = !!exclusive;\n this.setElementStatus(adjective, element, true, exclusive);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightElement\n */\n /**\n * @private\n * @function unselectElement\n */\n /**\n * @private\n * @function unfadeElement\n */\n /**\n * @private\n * @function unhideElement\n */\n BaseDataLayer.prototype[`${antiverb}Element`] = function(element, exclusive) {\n if (typeof exclusive == 'undefined') {\n exclusive = false;\n } else {\n exclusive = !!exclusive;\n }\n this.setElementStatus(adjective, element, false, exclusive);\n return this;\n };\n\n /**\n * @private\n * @function highlightAllElements\n */\n /**\n * @private\n * @function selectAllElements\n */\n /**\n * @private\n * @function fadeAllElements\n */\n /**\n * @private\n * @function hideAllElements\n */\n // Set/unset status for all elements\n BaseDataLayer.prototype[`${verb}AllElements`] = function() {\n this.setAllElementStatus(adjective, true);\n return this;\n };\n\n /**\n * @private\n * @function unhighlightAllElements\n */\n /**\n * @private\n * @function unselectAllElements\n */\n /**\n * @private\n * @function unfadeAllElements\n * */\n /**\n * @private\n * @function unhideAllElements\n */\n BaseDataLayer.prototype[`${antiverb}AllElements`] = function() {\n this.setAllElementStatus(adjective, false);\n return this;\n };\n});\n\nexport {BaseDataLayer as default};\n","import BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~annotation_track\n */\nconst default_layout = {\n color: '#000000',\n filters: null,\n tooltip_positioning: 'vertical',\n hitarea_width: 8,\n};\n\n/**\n * Create a single continuous 2D track that provides information about each datapoint\n *\n * For example, this can be used to mark items by membership in a group, alongside information in other panels\n * @alias module:LocusZoom_DataLayers~annotation_track\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass AnnotationTrack extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color] Specify how to choose the fill color for each tick mark\n * @param {number} [layout.hitarea_width=8] The width (in pixels) of hitareas. Annotation marks are typically 1 px wide,\n * so a hit area of 4px on each side can make it much easier to select an item for a tooltip. Hitareas will not interfere\n * with selecting adjacent points.\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='vertical'] Where to draw the tooltip relative to the datum.\n */\n constructor(layout) {\n if (!Array.isArray(layout.filters)) {\n throw new Error('Annotation track must specify array of filters for selecting points to annotate');\n }\n merge(layout, default_layout);\n super(...arguments);\n }\n\n initialize() {\n super.initialize();\n this._hitareas_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-hit_areas`);\n\n this._visible_lines_group = this.svg.group.append('g')\n .attr('class', `lz-data_layer-${this.layout.type}-visible_lines`);\n }\n\n render() {\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n const hit_areas_selection = this._hitareas_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n\n\n const _getX = (d, i) => {\n // Helper for hitarea position calcs: ensures that a hitarea never overlaps the space allocated\n // for a real data element. Helps to avoid mouse jitter when selecting tooltips in crowded areas.\n const x_center = this.parent['x_scale'](d[this.layout.x_axis.field]);\n let x_left = x_center - this.layout.hitarea_width / 2;\n if (i >= 1) {\n // This assumes that the data are in sorted order.\n const left_node = track_data[i - 1];\n const left_node_x_center = this.parent['x_scale'](left_node[this.layout.x_axis.field]);\n x_left = Math.max(x_left, (x_center + left_node_x_center) / 2);\n }\n return [x_left, x_center];\n };\n\n // Draw hitareas under real data elements, so that real data elements always take precedence\n hit_areas_selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n // Update the set of elements to reflect new data\n .merge(hit_areas_selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('height', this.parent.layout.height)\n .attr('opacity', 0)\n .attr('x', (d, i) => {\n const crds = _getX(d, i);\n return crds[0];\n })\n .attr('width', (d, i) => {\n const crds = _getX(d, i);\n return (crds[1] - crds[0]) + this.layout.hitarea_width / 2;\n });\n\n const width = 1;\n const selection = this._visible_lines_group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n // Draw rectangles (visual and tooltip positioning)\n selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => this.parent['x_scale'](d[this.layout.x_axis.field]) - width / 2)\n .attr('width', width)\n .attr('height', this.parent.layout.height)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i));\n\n // Remove unused elements\n selection.exit()\n .remove();\n\n // Set up tooltips and mouse interaction\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n\n // Remove unused elements\n hit_areas_selection.exit()\n .remove();\n }\n\n /**\n * Render tooltip at the center of each tick mark\n * @param tooltip\n * @return {{y_min: number, x_max: *, y_max: *, x_min: number}}\n * @private\n */\n _getTooltipPosition(tooltip) {\n const panel = this.parent;\n const data_layer_height = panel.layout.height - (panel.layout.margin.top + panel.layout.margin.bottom);\n const stroke_width = 1; // as defined in the default stylesheet\n\n const x_center = panel.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_center = data_layer_height / 2;\n return {\n x_min: x_center - stroke_width,\n x_max: x_center + stroke_width,\n y_min: y_center - panel.layout.margin.top,\n y_max: y_center + panel.layout.margin.bottom,\n };\n }\n}\n\nexport {AnnotationTrack as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~highlight_regions\n */\nconst default_layout = {\n color: '#CCCCCC',\n fill_opacity: 0.5,\n // By default, it will draw the regions shown.\n filters: null,\n // Most use cases will show a preset list of regions defined in the layout\n // (if empty, AND layout.fields is not, it could fetch from a data source instead)\n regions: [],\n id_field: 'id',\n start_field: 'start',\n end_field: 'end',\n merge_field: null,\n};\n\n/**\n * \"Highlight regions with rectangle\" data layer.\n * Creates one (or more) continuous 2D rectangles that mark an entire interval, to the full height of the panel.\n *\n * Each individual rectangle can be shown in full, or overlapping ones can be merged (eg, based on same category).\n * The rectangles are generally drawn with partial transparency, and do not respond to mouse events: they are a\n * useful highlight tool to draw attention to intervals that contain interesting variants.\n *\n * This layer has several useful modes:\n * 1. Draw one or more specified rectangles as provided from:\n * A. Hard-coded layout (layout.regions)\n * B. Data fetched from a source (like intervals with start and end coordinates)- as specified in layout.fields\n * 2. Fetch data from an external source, and only render the intervals that match criteria\n *\n * @alias module:LocusZoom_DataLayers~highlight_regions\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass HighlightRegions extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#CCCCCC'] The fill color for each rectangle\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=0.5] The opacity (0-1). We recommend partial transparency so that\n * rectangles do not hide or interfere with adjacent elements.\n * @param {Object[]} [layout.filters] An array of filter entries specifying which intervals to draw annotations for.\n * @param {Object[]} [layout.regions] A hard-coded list of regions. If provided, takes precedence over data fetched from an external source.\n * @param {String} [layout.start_field='start'] The field to use for rectangle start x coordinate\n * @param {String} [layout.end_field='end'] The field to use for rectangle end x coordinate\n * @param {String} [layout.merge_field] If two intervals overlap, they can be \"merged\" based on a field that\n * identifies the category (eg, only rectangles of the same category will be merged).\n * This field must be present in order to trigger merge behavior. This is applied after filters.\n */\n constructor(layout) {\n merge(layout, default_layout);\n if (layout.interaction || layout.behaviors) {\n throw new Error('highlight_regions layer does not support mouse events');\n }\n\n if (layout.regions && layout.regions.length && layout.fields && layout.fields.length) {\n throw new Error('highlight_regions layer can specify \"regions\" in layout, OR external data \"fields\", but not both');\n }\n super(...arguments);\n }\n\n /**\n * Helper method that combines two rectangles if they are the same type of data (category) and occupy the same\n * area of the plot (will automatically sort the data prior to rendering)\n *\n * When two fields conflict, it will fill in the fields for the last of the items that overlap in that range.\n * Thus, it is not recommended to use tooltips with this feature, because the tooltip won't reflect real data.\n * @param {Object[]} data\n * @return {Object[]}\n * @private\n */\n _mergeNodes(data) {\n const { end_field, merge_field, start_field } = this.layout;\n if (!merge_field) {\n return data;\n }\n\n // Ensure data is sorted by start field, with category as a tie breaker\n data.sort((a, b) => {\n // Ensure that data is sorted by category, then start field (ensures overlapping intervals are adjacent)\n return d3.ascending(a[merge_field], b[merge_field]) || d3.ascending(a[start_field], b[start_field]);\n });\n\n let track_data = [];\n data.forEach(function (cur_item, index) {\n const prev_item = track_data[track_data.length - 1] || cur_item;\n if (cur_item[merge_field] === prev_item[merge_field] && cur_item[start_field] <= prev_item[end_field]) {\n // If intervals overlap, merge the current item with the previous, and append only the merged interval\n const new_start = Math.min(prev_item[start_field], cur_item[start_field]);\n const new_end = Math.max(prev_item[end_field], cur_item[end_field]);\n cur_item = Object.assign({}, prev_item, cur_item, { [start_field]: new_start, [end_field]: new_end });\n track_data.pop();\n }\n track_data.push(cur_item);\n });\n return track_data;\n }\n\n render() {\n const { x_scale } = this.parent;\n // Apply filters to only render a specified set of points\n let track_data = this.layout.regions.length ? this.layout.regions : this.data;\n\n // Pseudo identifier for internal use only (regions have no semantic or transition meaning)\n track_data.forEach((d, i) => d.id || (d.id = i));\n track_data = this._applyFilters(track_data);\n track_data = this._mergeNodes(track_data);\n\n const selection = this.svg.group.selectAll(`rect.lz-data_layer-${this.layout.type}`)\n .data(track_data);\n\n // Draw rectangles\n selection.enter()\n .append('rect')\n .attr('class', `lz-data_layer-${this.layout.type}`)\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => x_scale(d[this.layout.start_field]))\n .attr('width', (d) => x_scale(d[this.layout.end_field]) - x_scale(d[this.layout.start_field]))\n .attr('height', this.parent.layout.height)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i));\n\n // Remove unused elements\n selection.exit()\n .remove();\n\n // Note: This layer intentionally does not allow tooltips or mouse behaviors, and doesn't affect pan/zoom\n this.svg.group.style('pointer-events', 'none');\n }\n\n _getTooltipPosition(tooltip) {\n // This layer is for visual highlighting only; it does not allow mouse interaction, drag, or tooltips\n throw new Error('This layer does not support tooltips');\n }\n}\n\nexport {HighlightRegions as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {applyStyles} from '../../helpers/common';\n\n/**\n * @memberof module:LocusZoom_DataLayers~arcs\n */\nconst default_layout = {\n color: 'seagreen',\n hitarea_width: '10px',\n style: {\n fill: 'none',\n 'stroke-width': '1px',\n 'stroke-opacity': '100%',\n },\n tooltip_positioning: 'top',\n};\n\n/**\n * Arc Data Layer\n * Implements a data layer that will render chromatin accessibility tracks.\n * This layer draws arcs (one per datapoint) that connect two endpoints (x.field1 and x.field2) by means of an arc,\n * with a height determined by y.field.\n * @alias module:LocusZoom_DataLayers~arcs\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass Arcs extends BaseDataLayer {\n /**\n * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='seagreen'] Specify how to choose the stroke color for each arc\n * @param {number} [layout.hitarea_width='10px'] The width (in pixels) of hitareas. Arcs are only as wide as the stroke,\n * so a hit area of 5px on each side can make it much easier to select an item for a tooltip.\n * @param {string} [layout.style.fill='none'] The fill color under the area of the arc\n * @param {string} [layout.style.stroke-width='1px']\n * @param {string} [layout.style.stroke_opacity='100%']\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='top'] Where to draw the tooltip relative to the datum.\n * @param {string} [layout.x_axis.field1] The field to use for one end of the arc; creates a point at (x1, 0)\n * @param {string} [layout.x_axis.field2] The field to use for the other end of the arc; creates a point at (x2, 0)\n * @param {string} [layout.y_axis.field] The height at the midpoint of the arc, (xmid, y)\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n }\n\n // Implement the main render function\n render() {\n const self = this;\n const layout = self.layout;\n const x_scale = self.parent['x_scale'];\n const y_scale = self.parent[`y${layout.y_axis.axis}_scale`];\n\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n // Helper: Each individual data point describes a path composed of 3 points, with a spline to smooth the line\n function _make_line(d) {\n const x1 = d[layout.x_axis.field1];\n const x2 = d[layout.x_axis.field2];\n const xmid = (x1 + x2) / 2;\n const coords = [\n [x_scale(x1), y_scale(0)],\n [x_scale(xmid), y_scale(d[layout.y_axis.field])],\n [x_scale(x2), y_scale(0)],\n ];\n // Smoothing options: https://bl.ocks.org/emmasaunders/f7178ed715a601c5b2c458a2c7093f78\n const line = d3.line()\n .x((d) => d[0])\n .y((d) => d[1])\n .curve(d3.curveNatural);\n return line(coords);\n }\n\n // Draw real lines, and also invisible hitareas for easier mouse events\n const hitareas = this.svg.group\n .selectAll('path.lz-data_layer-arcs-hitarea')\n .data(track_data, (d) => this.getElementId(d));\n\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-arcs')\n .data(track_data, (d) => this.getElementId(d));\n\n this.svg.group\n .call(applyStyles, layout.style);\n\n hitareas\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs-hitarea')\n .merge(hitareas)\n .attr('id', (d) => this.getElementId(d))\n .style('fill', 'none')\n .style('stroke-width', layout.hitarea_width)\n .style('stroke-opacity', 0)\n .style('stroke', 'transparent')\n .attr('d', (d) => _make_line(d));\n\n // Add new points as necessary\n selection\n .enter()\n .append('path')\n .attr('class', 'lz-data_layer-arcs')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('stroke', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('d', (d, i) => _make_line(d));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n hitareas.exit()\n .remove();\n\n // Apply mouse behaviors to arcs\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n\n return this;\n }\n\n _getTooltipPosition(tooltip) {\n // Center the tooltip arrow at the apex of the arc. Sometimes, only part of an arc shows on the screen, so we\n // clean up these values to ensure that the tooltip will appear within the window.\n const panel = this.parent;\n const layout = this.layout;\n\n const x1 = tooltip.data[layout.x_axis.field1];\n const x2 = tooltip.data[layout.x_axis.field2];\n\n const y_scale = panel[`y${layout.y_axis.axis}_scale`];\n\n return {\n x_min: panel.x_scale(Math.min(x1, x2)),\n x_max: panel.x_scale(Math.max(x1, x2)),\n y_min: y_scale(tooltip.data[layout.y_axis.field]),\n y_max: y_scale(0),\n };\n }\n\n}\n\nexport {Arcs as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\n\n/**\n * @memberof module:LocusZoom_DataLayers~genes\n * @type {{track_vertical_spacing: number, bounding_box_padding: number, color: string, tooltip_positioning: string, exon_height: number, label_font_size: number, label_exon_spacing: number, stroke: string}}\n */\nconst default_layout = {\n // Optionally specify different fill and stroke properties\n stroke: 'rgb(54, 54, 150)',\n color: '#363696',\n label_font_size: 12,\n label_exon_spacing: 3,\n exon_height: 10,\n bounding_box_padding: 3,\n track_vertical_spacing: 5,\n tooltip_positioning: 'top',\n};\n\n\n/**\n * Genes Data Layer\n * Implements a data layer that will render gene tracks\n * @alias module:LocusZoom_DataLayers~genes\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass Genes extends BaseDataLayer {\n /**\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.stroke='rgb(54, 54, 150)'] The stroke color for each intron and exon\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#363696'] The fill color for each intron and exon\n * @param {number} [layout.label_font_size]\n * @param {number} [layout.label_exon_spacing] The number of px padding between exons and the gene label\n * @param {number} [layout.exon_height=10] The height of each exon (vertical line) when drawing the gene\n * @param {number} [layout.bounding_box_padding=3] Padding around edges of the bounding box, as shown when highlighting a selected gene\n * @param {number} [layout.track_vertical_spacing=5] Vertical spacing between each row of genes\n * @param {'horizontal'|'vertical'|'top'|'bottom'|'left'|'right'} [layout.tooltip_positioning='top'] Where to draw the tooltip relative to the datum.\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n super(...arguments);\n /**\n * A gene may have arbitrarily many transcripts, but this data layer isn't set up to render them yet.\n * Stash a transcript_idx to point to the first transcript and use that for all transcript refs.\n * @member {number}\n * @type {number}\n */\n this.transcript_idx = 0;\n\n /**\n * An internal counter for the number of tracks in the data layer. Used as an internal counter for looping\n * over positions / assignments\n * @protected\n * @member {number}\n */\n this.tracks = 1;\n\n /**\n * Store information about genes in dataset, in a hash indexed by track number: {track_number: [gene_indices]}\n * @member {Object.}\n */\n this.gene_track_index = { 1: [] };\n }\n\n /**\n * Generate a statusnode ID for a given element\n * @override\n * @returns {String}\n */\n getElementStatusNodeId(element) {\n return `${this.getElementId(element)}-statusnode`;\n }\n\n /**\n * Helper function to sum layout values to derive total height for a single gene track\n * @returns {number}\n */\n getTrackHeight() {\n return 2 * this.layout.bounding_box_padding\n + this.layout.label_font_size\n + this.layout.label_exon_spacing\n + this.layout.exon_height\n + this.layout.track_vertical_spacing;\n }\n\n /**\n * Ensure that genes in overlapping chromosome regions are positioned so that parts of different genes do not\n * overlap in the view. A track is a row used to vertically separate overlapping genes.\n * @returns {Genes}\n */\n assignTracks(data) {\n /**\n * Function to get the width in pixels of a label given the text and layout attributes\n * @param {String} gene_name\n * @param {number|string} font_size\n * @returns {number}\n */\n const _getLabelWidth = (gene_name, font_size) => {\n try {\n const temp_text = this.svg.group.append('text')\n .attr('x', 0)\n .attr('y', 0)\n .attr('class', 'lz-data_layer-genes lz-label')\n .style('font-size', font_size)\n .text(`${gene_name}→`);\n const label_width = temp_text.node().getBBox().width;\n temp_text.remove();\n return label_width;\n } catch (e) {\n return 0;\n }\n };\n\n // Reinitialize some metadata\n this.tracks = 1;\n this.gene_track_index = { 1: [] };\n\n return data\n // Filter out any genes that are fully outside the region of interest. This allows us to use cached data\n // when zooming in, without breaking the layout by allocating space for genes that are not visible.\n .filter((item) => !(item.end < this.state.start) && !(item.start > this.state.end))\n .map((item) => {\n // If necessary, split combined gene id / version fields into discrete fields.\n // NOTE: this may be an issue with CSG's genes data API that may eventually be solved upstream.\n if (item.gene_id && item.gene_id.indexOf('.')) {\n const split = item.gene_id.split('.');\n item.gene_id = split[0];\n item.gene_version = split[1];\n }\n\n // Stash the transcript ID on the parent gene\n item.transcript_id = item.transcripts[this.transcript_idx].transcript_id;\n\n // Determine display range start and end, based on minimum allowable gene display width, bounded by what we can see\n // (range: values in terms of pixels on the screen)\n item.display_range = {\n start: this.parent.x_scale(Math.max(item.start, this.state.start)),\n end: this.parent.x_scale(Math.min(item.end, this.state.end)),\n };\n item.display_range.label_width = _getLabelWidth(item.gene_name, this.layout.label_font_size);\n item.display_range.width = item.display_range.end - item.display_range.start;\n // Determine label text anchor (default to middle)\n item.display_range.text_anchor = 'middle';\n if (item.display_range.width < item.display_range.label_width) {\n if (item.start < this.state.start) {\n item.display_range.end = item.display_range.start\n + item.display_range.label_width\n + this.layout.label_font_size;\n item.display_range.text_anchor = 'start';\n } else if (item.end > this.state.end) {\n item.display_range.start = item.display_range.end\n - item.display_range.label_width\n - this.layout.label_font_size;\n item.display_range.text_anchor = 'end';\n } else {\n const centered_margin = ((item.display_range.label_width - item.display_range.width) / 2)\n + this.layout.label_font_size;\n if ((item.display_range.start - centered_margin) < this.parent.x_scale(this.state.start)) {\n item.display_range.start = this.parent.x_scale(this.state.start);\n item.display_range.end = item.display_range.start + item.display_range.label_width;\n item.display_range.text_anchor = 'start';\n } else if ((item.display_range.end + centered_margin) > this.parent.x_scale(this.state.end)) {\n item.display_range.end = this.parent.x_scale(this.state.end);\n item.display_range.start = item.display_range.end - item.display_range.label_width;\n item.display_range.text_anchor = 'end';\n } else {\n item.display_range.start -= centered_margin;\n item.display_range.end += centered_margin;\n }\n }\n item.display_range.width = item.display_range.end - item.display_range.start;\n }\n // Add bounding box padding to the calculated display range start, end, and width\n item.display_range.start -= this.layout.bounding_box_padding;\n item.display_range.end += this.layout.bounding_box_padding;\n item.display_range.width += 2 * this.layout.bounding_box_padding;\n // Convert and stash display range values into domain values\n // (domain: values in terms of the data set, e.g. megabases)\n item.display_domain = {\n start: this.parent.x_scale.invert(item.display_range.start),\n end: this.parent.x_scale.invert(item.display_range.end),\n };\n item.display_domain.width = item.display_domain.end - item.display_domain.start;\n\n // Using display range/domain data generated above cast each gene to tracks such that none overlap\n item.track = null;\n let potential_track = 1;\n while (item.track === null) {\n let collision_on_potential_track = false;\n this.gene_track_index[potential_track].map((placed_gene) => {\n if (!collision_on_potential_track) {\n const min_start = Math.min(placed_gene.display_range.start, item.display_range.start);\n const max_end = Math.max(placed_gene.display_range.end, item.display_range.end);\n if ((max_end - min_start) < (placed_gene.display_range.width + item.display_range.width)) {\n collision_on_potential_track = true;\n }\n }\n });\n if (!collision_on_potential_track) {\n item.track = potential_track;\n this.gene_track_index[potential_track].push(item);\n } else {\n potential_track++;\n if (potential_track > this.tracks) {\n this.tracks = potential_track;\n this.gene_track_index[potential_track] = [];\n }\n }\n }\n\n // Stash parent references on all genes, transcripts, and exons\n item.parent = this;\n item.transcripts.map((d, t) => {\n item.transcripts[t].parent = item;\n item.transcripts[t].exons.map((d, e) => item.transcripts[t].exons[e].parent = item.transcripts[t]);\n });\n return item;\n });\n }\n\n /**\n * Main render function\n */\n render() {\n const self = this;\n // Apply filters to only render a specified set of points\n let track_data = this._applyFilters();\n track_data = this.assignTracks(track_data);\n let height;\n\n // Render gene groups\n const selection = this.svg.group.selectAll('g.lz-data_layer-genes')\n .data(track_data, (d) => d.gene_name);\n\n selection.enter()\n .append('g')\n .attr('class', 'lz-data_layer-genes')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .each(function(gene) {\n const data_layer = gene.parent;\n\n // Render gene bounding boxes (status nodes to show selected/highlighted)\n const bboxes = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-data_layer-genes-statusnode')\n .data([gene], (d) => data_layer.getElementStatusNodeId(d));\n\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n\n bboxes.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-data_layer-genes-statusnode')\n .merge(bboxes)\n .attr('id', (d) => data_layer.getElementStatusNodeId(d))\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', (d) => d.display_range.width)\n .attr('height', height)\n .attr('x', (d) => d.display_range.start)\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight()));\n\n bboxes.exit()\n .remove();\n\n // Render gene boundaries\n const boundaries = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-boundary')\n .data([gene], (d) => `${d.gene_name}_boundary`);\n\n height = 1;\n boundaries.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-boundary')\n .merge(boundaries)\n .attr('width', (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start))\n .attr('height', height)\n .attr('x', (d) => data_layer.parent.x_scale(d.start))\n .attr('y', (d) => {\n return ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing\n + (Math.max(data_layer.layout.exon_height, 3) / 2);\n })\n .style('fill', (d, i) => self.resolveScalableParameter(self.layout.color, d, i))\n .style('stroke', (d, i) => self.resolveScalableParameter(self.layout.stroke, d, i));\n\n boundaries.exit()\n .remove();\n\n // Render gene labels\n const labels = d3.select(this).selectAll('text.lz-data_layer-genes.lz-label')\n .data([gene], (d) => `${d.gene_name}_label`);\n\n labels.enter()\n .append('text')\n .attr('class', 'lz-data_layer-genes lz-label')\n .merge(labels)\n .attr('text-anchor', (d) => d.display_range.text_anchor)\n .text((d) => (d.strand === '+') ? `${d.gene_name}→` : `←${d.gene_name}`)\n .style('font-size', gene.parent.layout.label_font_size)\n .attr('x', (d) => {\n if (d.display_range.text_anchor === 'middle') {\n return d.display_range.start + (d.display_range.width / 2);\n } else if (d.display_range.text_anchor === 'start') {\n return d.display_range.start + data_layer.layout.bounding_box_padding;\n } else if (d.display_range.text_anchor === 'end') {\n return d.display_range.end - data_layer.layout.bounding_box_padding;\n }\n })\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n );\n\n labels.exit()\n .remove();\n\n // Render exon rects (first transcript only, for now)\n // Exons: by default color on gene properties for consistency with the gene boundary track- hence color uses d.parent.parent\n const exons = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-exon')\n .data(gene.transcripts[gene.parent.transcript_idx].exons, (d) => d.exon_id);\n\n height = data_layer.layout.exon_height;\n\n exons.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-exon')\n .merge(exons)\n .style('fill', (d, i) => self.resolveScalableParameter(self.layout.color, d.parent.parent, i))\n .style('stroke', (d, i) => self.resolveScalableParameter(self.layout.stroke, d.parent.parent, i))\n .attr('width', (d) => data_layer.parent.x_scale(d.end) - data_layer.parent.x_scale(d.start))\n .attr('height', height)\n .attr('x', (d) => data_layer.parent.x_scale(d.start))\n .attr('y', () => {\n return ((gene.track - 1) * data_layer.getTrackHeight())\n + data_layer.layout.bounding_box_padding\n + data_layer.layout.label_font_size\n + data_layer.layout.label_exon_spacing;\n });\n\n exons.exit()\n .remove();\n\n // Render gene click area\n const clickareas = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-clickarea')\n .data([gene], (d) => `${d.gene_name}_clickarea`);\n\n height = data_layer.getTrackHeight() - data_layer.layout.track_vertical_spacing;\n clickareas.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-genes lz-clickarea')\n .merge(clickareas)\n .attr('id', (d) => `${data_layer.getElementId(d)}_clickarea`)\n .attr('rx', data_layer.layout.bounding_box_padding)\n .attr('ry', data_layer.layout.bounding_box_padding)\n .attr('width', (d) => d.display_range.width)\n .attr('height', height)\n .attr('x', (d) => d.display_range.start)\n .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight()));\n\n // Remove old clickareas as needed\n clickareas.exit()\n .remove();\n });\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n // Apply mouse behaviors & events to clickareas\n this.svg.group\n .on('click.event_emitter', (element) => this.parent.emit('element_clicked', element, true))\n .call(this.applyBehaviors.bind(this));\n }\n\n _getTooltipPosition(tooltip) {\n const gene_bbox_id = this.getElementStatusNodeId(tooltip.data);\n const gene_bbox = d3.select(`#${gene_bbox_id}`).node().getBBox();\n return {\n x_min: this.parent.x_scale(tooltip.data.start),\n x_max: this.parent.x_scale(tooltip.data.end),\n y_min: gene_bbox.y,\n y_max: gene_bbox.y + gene_bbox.height,\n };\n }\n}\n\nexport {Genes as default};\n","import * as d3 from 'd3';\n\nimport BaseDataLayer from './base';\nimport {merge} from '../../helpers/layouts';\nimport {STATUSES} from '../constants';\nimport {applyStyles} from '../../helpers/common';\n\n/**\n * @memberof module:LocusZoom_DataLayers~line\n */\nconst default_layout = {\n style: {\n fill: 'none',\n 'stroke-width': '2px',\n },\n interpolate: 'curveLinear',\n x_axis: { field: 'x' },\n y_axis: { field: 'y', axis: 1 },\n hitarea_width: 5,\n};\n\n/*********************\n * Line Data Layer\n * Implements a standard line plot, representing either a trace or a filled curve. Only one line is drawn per layer used.\n * @alias module:LocusZoom_DataLayers~line\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n*/\nclass Line extends BaseDataLayer {\n /**\n * @param {object} [layout.style] CSS properties to control how the line is drawn\n * @param {string} [layout.style.fill='none'] Fill color for the area under the curve\n * @param {string} [layout.style.stroke]\n * @param {string} [layout.style.stroke-width='2px']\n * @param {string} [layout.interpolate='curveLinear'] The name of the d3 interpolator to use. This determines how to smooth the line in between data points.\n * @param {number} [layout.hitarea_width=5] The size of mouse event hitareas to use. If tooltips are not used, hitareas are not very important.\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n if (layout.tooltip) {\n throw new Error('The line / filled curve layer does not support tooltips');\n }\n super(...arguments);\n }\n\n /**\n * Implement the main render function\n */\n render() {\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_field = this.layout.x_axis.field;\n const y_field = this.layout.y_axis.field;\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line');\n\n // Generate the line\n let line;\n const x_scale = panel['x_scale'];\n const y_scale = panel[`y${this.layout.y_axis.axis}_scale`];\n if (this.layout.style.fill && this.layout.style.fill !== 'none') {\n // Filled curve: define the line as a filled boundary\n line = d3.area()\n .x((d) => +x_scale(d[x_field]))\n .y0(+y_scale(0))\n .y1((d) => +y_scale(d[y_field]));\n } else {\n // Basic line\n line = d3.line()\n .x((d) => +x_scale(d[x_field]))\n .y((d) => +y_scale(d[y_field]))\n .curve(d3[this.layout.interpolate]);\n }\n\n // Apply line and style\n selection.merge(this.path)\n .attr('d', line)\n .call(applyStyles, this.layout.style);\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n }\n\n /**\n * Redefine setElementStatus family of methods as line data layers will only ever have a single path element\n * @param {String} status A member of `LocusZoom.DataLayer.Statuses.adjectives`\n * @param {String|Object} element\n * @param {Boolean} toggle\n */\n setElementStatus(status, element, toggle) {\n return this.setAllElementStatus(status, toggle);\n }\n\n setAllElementStatus(status, toggle) {\n // Sanity check\n if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) {\n throw new Error('Invalid status');\n }\n if (typeof this.layer_state.status_flags[status] == 'undefined') {\n return this;\n }\n if (typeof toggle == 'undefined') {\n toggle = true;\n }\n\n // Update global status flag\n this.global_statuses[status] = toggle;\n\n // Apply class to path based on global status flags\n let path_class = 'lz-data_layer-line';\n Object.keys(this.global_statuses).forEach((global_status) => {\n if (this.global_statuses[global_status]) {\n path_class += ` lz-data_layer-line-${global_status}`;\n }\n });\n this.path.attr('class', path_class);\n\n // Trigger layout changed event hook\n this.parent.emit('layout_changed', true);\n return this;\n }\n}\n\n/**\n * @memberof module:LocusZoom_DataLayers~orthogonal_line\n */\nconst default_orthogonal_layout = {\n style: {\n 'stroke': '#D3D3D3',\n 'stroke-width': '3px',\n 'stroke-dasharray': '10px 10px',\n },\n orientation: 'horizontal',\n x_axis: {\n axis: 1,\n decoupled: true,\n },\n y_axis: {\n axis: 1,\n decoupled: true,\n },\n tooltip_positioning: 'vertical',\n offset: 0,\n};\n\n\n/**\n * Orthogonal Line Data Layer\n * Draw a horizontal or vertical line given an orientation and an offset in the layout\n * Does not require a data source or fields.\n * @alias module:LocusZoom_DataLayers~orthogonal_line\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\nclass OrthogonalLine extends BaseDataLayer {\n /**\n * @param {string} [layout.style.stroke='#D3D3D3']\n * @param {string} [layout.style.stroke-width='3px']\n * @param {string} [layout.style.stroke-dasharray='10px 10px']\n * @param {'horizontal'|'vertical'} [layout.orientation] The orientation of the horizontal line\n * @param {boolean} [layout.x_axis.decoupled=true] If true, the data in this layer will not influence the x-extent of the panel.\n * @param {boolean} [layout.y_axis.decoupled=true] If true, the data in this layer will not influence the y-extent of the panel.\n * @param {'horizontal'|'vertical'} [layout.tooltip_positioning='vertical'] Where to draw the tooltip relative to the mouse pointer.\n * @param {number} [layout.offset=0] Where the line intercepts the orthogonal axis (eg, the y coordinate for a horizontal line, or x for a vertical line)\n */\n constructor(layout) {\n layout = merge(layout, default_orthogonal_layout);\n // Require that orientation be \"horizontal\" or \"vertical\" only\n if (!['horizontal', 'vertical'].includes(layout.orientation)) {\n layout.orientation = 'horizontal';\n }\n super(...arguments);\n\n // Vars for storing the data generated line\n /** @member {Array} */\n this.data = [];\n }\n\n getElementId(element) {\n // There is only one line per datalayer, so this is sufficient.\n return this.getBaseId();\n }\n\n /**\n * Implement the main render function\n */\n render() {\n // Several vars needed to be in scope\n const panel = this.parent;\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const x_extent = 'x_extent';\n const y_extent = `y${this.layout.y_axis.axis}_extent`;\n const x_range = 'x_range';\n\n // Generate data using extents depending on orientation\n if (this.layout.orientation === 'horizontal') {\n this.data = [\n { x: panel[x_extent][0], y: this.layout.offset },\n { x: panel[x_extent][1], y: this.layout.offset },\n ];\n } else if (this.layout.orientation === 'vertical') {\n this.data = [\n { x: this.layout.offset, y: panel[y_extent][0] },\n { x: this.layout.offset, y: panel[y_extent][1] },\n ];\n } else {\n throw new Error('Unrecognized vertical line type. Must be \"vertical\" or \"horizontal\"');\n }\n\n // Join data to the line selection\n const selection = this.svg.group\n .selectAll('path.lz-data_layer-line')\n .data([this.data]);\n\n // In some cases, a vertical line may overlay a track that has no inherent y-values (extent)\n // When that happens, provide a default height based on the current panel dimensions (accounting\n // for any resizing that happened after the panel was created)\n const default_y = [panel.layout.cliparea.height, 0];\n\n // Generate the line\n const line = d3.line()\n .x((d, i) => {\n const x = +panel[x_scale](d['x']);\n return isNaN(x) ? panel[x_range][i] : x;\n })\n .y((d, i) => {\n const y = +panel[y_scale](d['y']);\n return isNaN(y) ? default_y[i] : y;\n });\n\n // Create path element, apply class\n this.path = selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-line')\n .merge(selection)\n .attr('d', line)\n .call(applyStyles, this.layout.style)\n // Allow the layer to respond to mouseover events and show a tooltip.\n .call(this.applyBehaviors.bind(this));\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n }\n\n _getTooltipPosition(tooltip) {\n try {\n const coords = d3.mouse(this.svg.container.node());\n const x = coords[0];\n const y = coords[1];\n return { x_min: x - 1, x_max: x + 1, y_min: y - 1, y_max: y + 1 };\n } catch (e) {\n // On redraw, there won't be a mouse event, so skip tooltip repositioning.\n return null;\n }\n }\n\n}\n\n\nexport { Line as line, OrthogonalLine as orthogonal_line };\n","import * as d3 from 'd3';\nimport BaseDataLayer from './base';\nimport {applyStyles} from '../../helpers/common';\nimport {parseFields} from '../../helpers/display';\nimport {merge, nameToSymbol} from '../../helpers/layouts';\nimport {coalesce_scatter_points} from '../../helpers/render';\n\n/**\n * @memberof module:LocusZoom_DataLayers~scatter\n */\nconst default_layout = {\n point_size: 40,\n point_shape: 'circle',\n tooltip_positioning: 'horizontal',\n color: '#888888',\n coalesce: {\n active: false,\n max_points: 800, // Many plots are 800-2400 px wide, so, more than 1 datum per pixel of average region width\n // Define the \"region of interest\", like \"bottom half of plot\"; any points outside this region are taken as is\n // Values are expressed in terms of data value and will be converted to pixels internally.\n x_min: '-Infinity', // JSON doesn't handle some valid JS numbers. Kids, don't get a career in computers.\n x_max: 'Infinity',\n y_min: 0,\n y_max: 3.0,\n x_gap: 7,\n y_gap: 7,\n },\n fill_opacity: 1,\n y_axis: {\n axis: 1,\n },\n id_field: 'id',\n};\n\n/**\n * Options that control point-coalescing in scatter plots\n * @typedef {object} module:LocusZoom_DataLayers~scatter~coalesce_options\n * @property {boolean} [active=false] Whether to use this feature. Typically used for GWAS plots, but\n * not other scatter plots such as PheWAS.\n * @property {number} [max_points=800] Only attempt to reduce DOM size if there are at least this many\n * points. Many plots are 800-2400 px wide, so, more than 1 datum per pixel of average region width. For more\n * sparse datasets, all points will be faithfully rendered even if coalesce.active=true.\n * @property {number} [x_min='-Infinity'] Min x coordinate of the region where points will be coalesced\n * @property {number} [x_max='Infinity'] Max x coordinate of the region where points will be coalesced\n * @property {number} [y_min=0] Min y coordinate of the region where points will be coalesced.\n * @property {number} [y_max=3.0] Max y coordinate of the region where points will be coalesced\n * @property {number} [x_gap=7] Max number of pixels between the center of two points that can be\n * coalesced. For circles, area 40 = radius ~3.5; aim for ~1 diameter distance.\n * @property {number} [y_gap=7]\n */\n\n/**\n * Scatter Data Layer\n * Implements a standard scatter plot\n * @alias module:LocusZoom_DataLayers~scatter\n */\nclass Scatter extends BaseDataLayer {\n /**\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.point_size=40] The size (area) of the point for each datum\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.point_shape='circle'] Shape of the point for each datum. Supported values map to the d3 SVG Symbol Types (i.e.: \"circle\", \"cross\", \"diamond\", \"square\", \"triangle\", \"star\", and \"wye\"), plus \"triangledown\".\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#888888'] The color of the point for each datum\n * @param {module:LocusZoom_DataLayers~scatter~coalesce_options} [layout.coalesce] Options to control whether and how to combine adjacent insignificant (\"within region of interest\") points\n * to improve rendering performance. These options are primarily aimed at GWAS region plots. Within a specified\n * rectangle area (eg \"insignificant point cutoff\"), we choose only points far enough part to be seen.\n * The defaults are specifically tuned for GWAS plots with -log(p) on the y-axis.\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1] Opacity (0..1) for each datum point\n * @param {string} [layout.label.text] Similar to tooltips: a template string that can reference datum fields for label text.\n * @param {number} [layout.label.spacing] Distance (in px) between the label and the center of the datum.\n * @param {object} [layout.label.lines.style] CSS style options for how the line is rendered\n * @param {number} [layout.label.filters] Filters that describe which points to label. For performance reasons,\n * we recommend labeling only a small subset of most interesting points.\n * @param {object} [layout.label.style] CSS style options for label text\n */\n constructor(layout) {\n layout = merge(layout, default_layout);\n\n // Extra default for layout spacing\n // Not in default layout since that would make the label attribute always present\n if (layout.label && isNaN(layout.label.spacing)) {\n layout.label.spacing = 4;\n }\n super(...arguments);\n }\n\n // Implement tooltip position to be layer-specific\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n\n return {\n x_min: x_center - offset, x_max: x_center + offset,\n y_min: y_center - offset, y_max: y_center + offset,\n };\n }\n\n // Function to flip labels from being anchored at the start of the text to the end\n // Both to keep labels from running outside the data layer and also as a first\n // pass on recursive separation\n flip_labels() {\n const data_layer = this;\n // Base positions on the default point size (which is what resolve scalable param returns if no data provided)\n const point_size = data_layer.resolveScalableParameter(data_layer.layout.point_size, {});\n const spacing = data_layer.layout.label.spacing;\n const handle_lines = Boolean(data_layer.layout.label.lines);\n const min_x = 2 * spacing;\n const max_x = this.parent_plot.layout.width - this.parent.layout.margin.left - this.parent.layout.margin.right - (2 * spacing);\n\n const flip = (dn, dnl) => {\n const dnx = +dn.attr('x');\n const text_swing = (2 * spacing) + (2 * Math.sqrt(point_size));\n let dnlx2;\n let line_swing;\n if (handle_lines) {\n dnlx2 = +dnl.attr('x2');\n line_swing = spacing + (2 * Math.sqrt(point_size));\n }\n if (dn.style('text-anchor') === 'start') {\n dn.style('text-anchor', 'end');\n dn.attr('x', dnx - text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 - line_swing);\n }\n } else {\n dn.style('text-anchor', 'start');\n dn.attr('x', dnx + text_swing);\n if (handle_lines) {\n dnl.attr('x2', dnlx2 + line_swing);\n }\n }\n };\n // Flip any going over the right edge from the right side to the left side\n // (all labels start on the right side)\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n const dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n if (dax + abound.width + spacing > max_x) {\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n flip(da, dal);\n }\n });\n // Second pass to flip any others that haven't flipped yet if they collide with another label\n data_layer.label_texts.each(function (d, i) {\n const a = this;\n const da = d3.select(a);\n if (da.style('text-anchor') === 'end') {\n return;\n }\n let dax = +da.attr('x');\n const abound = da.node().getBoundingClientRect();\n const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null;\n data_layer.label_texts.each(function () {\n const b = this;\n const db = d3.select(b);\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (collision) {\n flip(da, dal);\n // Double check that this flip didn't push the label past min_x. If it did, immediately flip back.\n dax = +da.attr('x');\n if (dax - abound.width - spacing < min_x) {\n flip(da, dal);\n }\n }\n });\n });\n }\n\n // Recursive function to space labels apart immediately after initial render\n // Adapted from thudfactor's fiddle here: https://jsfiddle.net/thudfactor/HdwTH/\n // TODO: Make labels also aware of data elements\n separate_labels() {\n this.seperate_iterations++;\n const data_layer = this;\n const alpha = 0.5;\n if (!this.layout.label) {\n // Guard against layout changing in the midst of iterative rerender\n return;\n }\n const spacing = this.layout.label.spacing;\n let again = false;\n data_layer.label_texts.each(function () {\n // TODO: O(n2) algorithm; revisit performance?\n const a = this;\n const da = d3.select(a);\n const y1 = da.attr('y');\n data_layer.label_texts.each(function () {\n const b = this;\n // a & b are the same element and don't collide.\n if (a === b) {\n return;\n }\n const db = d3.select(b);\n // a & b are on opposite sides of the chart and\n // don't collide\n if (da.attr('text-anchor') !== db.attr('text-anchor')) {\n return;\n }\n // Determine if the bounding rects for the two text elements collide\n const abound = da.node().getBoundingClientRect();\n const bbound = db.node().getBoundingClientRect();\n const collision = abound.left < bbound.left + bbound.width + (2 * spacing) &&\n abound.left + abound.width + (2 * spacing) > bbound.left &&\n abound.top < bbound.top + bbound.height + (2 * spacing) &&\n abound.height + abound.top + (2 * spacing) > bbound.top;\n if (!collision) {\n return;\n }\n again = true;\n // If the labels collide, we'll push each\n // of the two labels up and down a little bit.\n const y2 = db.attr('y');\n const sign = abound.top < bbound.top ? 1 : -1;\n const adjust = sign * alpha;\n let new_a_y = +y1 - adjust;\n let new_b_y = +y2 + adjust;\n // Keep new values from extending outside the data layer\n const min_y = 2 * spacing;\n const max_y = data_layer.parent.layout.height - data_layer.parent.layout.margin.top - data_layer.parent.layout.margin.bottom - (2 * spacing);\n let delta;\n if (new_a_y - (abound.height / 2) < min_y) {\n delta = +y1 - new_a_y;\n new_a_y = +y1;\n new_b_y += delta;\n } else if (new_b_y - (bbound.height / 2) < min_y) {\n delta = +y2 - new_b_y;\n new_b_y = +y2;\n new_a_y += delta;\n }\n if (new_a_y + (abound.height / 2) > max_y) {\n delta = new_a_y - +y1;\n new_a_y = +y1;\n new_b_y -= delta;\n } else if (new_b_y + (bbound.height / 2) > max_y) {\n delta = new_b_y - +y2;\n new_b_y = +y2;\n new_a_y -= delta;\n }\n da.attr('y', new_a_y);\n db.attr('y', new_b_y);\n });\n });\n if (again) {\n // Adjust lines to follow the labels\n if (data_layer.layout.label.lines) {\n const label_elements = data_layer.label_texts.nodes();\n data_layer.label_lines.attr('y2', (d, i) => {\n const label_line = d3.select(label_elements[i]);\n return label_line.attr('y');\n });\n }\n // After ~150 iterations we're probably beyond diminising returns, so stop recursing\n if (this.seperate_iterations < 150) {\n setTimeout(() => {\n this.separate_labels();\n }, 1);\n }\n }\n }\n\n // Implement the main render function\n render() {\n const data_layer = this;\n const x_scale = this.parent['x_scale'];\n const y_scale = this.parent[`y${this.layout.y_axis.axis}_scale`];\n\n const xcs = Symbol.for('lzX');\n const ycs = Symbol.for('lzY');\n\n // Apply filters to only render a specified set of points\n let track_data = this._applyFilters();\n\n // Add coordinates before rendering, so we can coalesce\n track_data.forEach((item) => {\n let x = x_scale(item[this.layout.x_axis.field]);\n let y = y_scale(item[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n item[xcs] = x;\n item[ycs] = y;\n });\n\n if (this.layout.coalesce.active && track_data.length > this.layout.coalesce.max_points) {\n let { x_min, x_max, y_min, y_max, x_gap, y_gap } = this.layout.coalesce;\n // Convert x and y \"significant region\" range from data values to pixels\n const x_min_px = isFinite(x_min) ? x_scale(+x_min) : -Infinity;\n const x_max_px = isFinite(x_max) ? x_scale(+x_max) : Infinity;\n // For y px, we flip the data min/max b/c in SVG coord system +y is down: smaller data y = larger px y\n const y_min_px = isFinite(y_max) ? y_scale(+y_max) : -Infinity;\n const y_max_px = isFinite(y_min) ? y_scale(+y_min) : Infinity;\n track_data = coalesce_scatter_points(track_data, x_min_px, x_max_px, x_gap, y_min_px, y_max_px, y_gap);\n }\n\n if (this.layout.label) {\n let label_data;\n const filters = data_layer.layout.label.filters || [];\n if (!filters.length) {\n label_data = track_data;\n } else {\n const func = this.filter.bind(this, filters);\n label_data = track_data.filter(func);\n }\n\n // Render label groups\n this.label_groups = this.svg.group\n .selectAll(`g.lz-data_layer-${this.layout.type}-label`)\n .data(label_data, (d) => `${d[this.layout.id_field]}_label`);\n\n const style_class = `lz-data_layer-${this.layout.type}-label`;\n const groups_enter = this.label_groups.enter()\n .append('g')\n .attr('class', style_class);\n\n if (this.label_texts) {\n this.label_texts.remove();\n }\n\n this.label_texts = this.label_groups.merge(groups_enter)\n .append('text')\n .text((d) => parseFields(data_layer.layout.label.text || '', d, this.getElementAnnotation(d)))\n .attr('x', (d) => {\n return d[xcs]\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + data_layer.layout.label.spacing;\n })\n .attr('y', (d) => d[ycs])\n .attr('text-anchor', 'start')\n .call(applyStyles, data_layer.layout.label.style || {});\n\n // Render label lines\n if (data_layer.layout.label.lines) {\n if (this.label_lines) {\n this.label_lines.remove();\n }\n this.label_lines = this.label_groups.merge(groups_enter)\n .append('line')\n .attr('x1', (d) => d[xcs])\n .attr('y1', (d) => d[ycs])\n .attr('x2', (d) => {\n return d[xcs]\n + Math.sqrt(data_layer.resolveScalableParameter(data_layer.layout.point_size, d))\n + (data_layer.layout.label.spacing / 2);\n })\n .attr('y2', (d) => d[ycs])\n .call(applyStyles, data_layer.layout.label.lines.style || {});\n }\n // Remove labels when they're no longer in the filtered data set\n this.label_groups.exit()\n .remove();\n } else {\n // If the layout definition has changed (& no longer specifies labels), strip any previously rendered\n if (this.label_texts) {\n this.label_texts.remove();\n }\n if (this.label_lines) {\n this.label_lines.remove();\n }\n if (this.label_groups) {\n this.label_groups.remove();\n }\n }\n\n // Generate main scatter data elements\n const selection = this.svg.group\n .selectAll(`path.lz-data_layer-${this.layout.type}`)\n .data(track_data, (d) => d[this.layout.id_field]);\n\n // Create elements, apply class, ID, and initial position\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => `translate(${d[xcs]}, ${d[ycs]})`;\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => nameToSymbol(this.resolveScalableParameter(this.layout.point_shape, d, i)));\n\n const style_class = `lz-data_layer-${this.layout.type}`;\n selection.enter()\n .append('path')\n .attr('class', style_class)\n .attr('id', (d) => this.getElementId(d))\n .merge(selection)\n .attr('transform', transform)\n .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))\n .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i))\n .attr('d', shape);\n\n // Remove old elements as needed\n selection.exit()\n .remove();\n\n // Apply method to keep labels from overlapping each other\n if (this.layout.label) {\n this.flip_labels();\n this.seperate_iterations = 0;\n this.separate_labels();\n }\n\n // Apply default event emitters & mouse behaviors. Apply to the container, not per element,\n // to reduce number of event listeners. These events will apply to both scatter points and labels.\n this.svg.group\n .on('click.event_emitter', () => {\n // D3 doesn't natively support bubbling very well; we need to find the data for the bubbled event\n const item_data = d3.select(d3.event.target).datum();\n this.parent.emit('element_clicked', item_data, true);\n })\n .call(this.applyBehaviors.bind(this));\n }\n\n /**\n * A new LD reference variant has been selected (usually by clicking within a GWAS scatter plot)\n * This event only fires for manually selected variants. It does not fire if the LD reference variant is\n * automatically selected (eg by choosing the most significant hit in the region)\n * @event set_ldrefvar\n * @property {object} data { ldrefvar } The variant identifier of the LD reference variant\n * @see event:any_lz_event\n */\n\n /**\n * Method to set a passed element as the LD reference variant in the plot-level state. Triggers a re-render\n * so that the plot will update with the new LD information.\n * This is useful in tooltips, eg the \"make LD reference\" action link for GWAS scatter plots.\n * @param {object} element The data associated with a particular plot element\n * @fires event:set_ldrefvar\n * @return {Promise}\n */\n makeLDReference(element) {\n let ref = null;\n if (typeof element == 'undefined') {\n throw new Error('makeLDReference requires one argument of any type');\n } else if (typeof element == 'object') {\n if (this.layout.id_field && typeof element[this.layout.id_field] != 'undefined') {\n ref = element[this.layout.id_field].toString();\n } else if (typeof element['id'] != 'undefined') {\n ref = element['id'].toString();\n } else {\n ref = element.toString();\n }\n } else {\n ref = element.toString();\n }\n this.parent.emit('set_ldrefvar', { ldrefvar: ref }, true);\n return this.parent_plot.applyState({ ldrefvar: ref });\n }\n}\n\n/**\n * A scatter plot in which the x-axis represents categories, rather than individual positions.\n * For example, this can be used by PheWAS plots to show related groups. This plot allows the categories and color options to be\n * determined dynamically when data is first loaded.\n * @alias module:LocusZoom_DataLayers~category_scatter\n */\nclass CategoryScatter extends Scatter {\n /**\n * @param {string} layout.x_axis.category_field The datum field to use in auto-generating tick marks, color scheme, and point ordering.\n */\n constructor(layout) {\n super(...arguments);\n /**\n * Define category names and extents (boundaries) for plotting.\n * In the form {category_name: [min_x, max_x]}\n * @private\n * @member {Object.}\n */\n this._categories = {};\n }\n\n /**\n * This plot layer makes certain assumptions about the data passed in. Transform the raw array of records from\n * the datasource to prepare it for plotting, as follows:\n * 1. The scatter plot assumes that all records are given in sequence (pre-grouped by `category_field`)\n * 2. It assumes that all records have an x coordinate for individual plotting\n * @private\n */\n _prepareData() {\n const xField = this.layout.x_axis.field || 'x';\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n // Sort the data so that things in the same category are adjacent (case-insensitive by specified field)\n const sourceData = this.data\n .sort((a, b) => {\n const ak = a[category_field];\n const bk = b[category_field];\n const av = (typeof ak === 'string') ? ak.toLowerCase() : ak;\n const bv = (typeof bk === 'string') ? bk.toLowerCase() : bk;\n return (av === bv) ? 0 : (av < bv ? -1 : 1);\n });\n sourceData.forEach((d, i) => {\n // Implementation detail: Scatter plot requires specifying an x-axis value, and most datasources do not\n // specify plotting positions. If a point is missing this field, fill in a synthetic value.\n d[xField] = d[xField] || i;\n });\n return sourceData;\n }\n\n /**\n * Identify the unique categories on the plot, and update the layout with an appropriate color scheme.\n * Also identify the min and max x value associated with the category, which will be used to generate ticks\n * @private\n * @returns {Object.} Series of entries used to build category name ticks {category_name: [min_x, max_x]}\n */\n _generateCategoryBounds() {\n // TODO: API may return null values in category_field; should we add placeholder category label?\n // The (namespaced) field from `this.data` that will be used to assign datapoints to a given category & color\n const category_field = this.layout.x_axis.category_field;\n const xField = this.layout.x_axis.field || 'x';\n const uniqueCategories = {};\n this.data.forEach((item) => {\n const category = item[category_field];\n const x = item[xField];\n const bounds = uniqueCategories[category] || [x, x];\n uniqueCategories[category] = [Math.min(bounds[0], x), Math.max(bounds[1], x)];\n });\n\n const categoryNames = Object.keys(uniqueCategories);\n this._setDynamicColorScheme(categoryNames);\n\n return uniqueCategories;\n }\n\n /**\n * This layer relies on defining its own category-based color scheme. Find the correct color config object to\n * be modified.\n * @param [from_source]\n * @returns {Object} A mutable reference to the layout configuration object\n * @private\n */\n _getColorScale(from_source) {\n from_source = from_source || this.layout;\n // If the layout does not use a supported coloring scheme, or is already complete, this method should do nothing\n\n // For legacy reasons, layouts can specify color as an object (only one way to set color), as opposed to the\n // preferred mechanism of array (multiple coloring options)\n let color_params = from_source.color || []; // Object or scalar, no other options allowed\n if (Array.isArray(color_params)) {\n color_params = color_params.find((item) => item.scale_function === 'categorical_bin');\n }\n if (!color_params || color_params.scale_function !== 'categorical_bin') {\n throw new Error('This layer requires that color options be provided as a `categorical_bin`');\n }\n return color_params;\n }\n\n /**\n * Automatically define a color scheme for the layer based on data returned from the server.\n * If part of the color scheme has been specified, it will fill in remaining missing information.\n *\n * There are three scenarios:\n * 1. The layout does not specify either category names or (color) values. Dynamically build both based on\n * the data and update the layout.\n * 2. The layout specifies colors, but not categories. Use that exact color information provided, and dynamically\n * determine what categories are present in the data. (cycle through the available colors, reusing if there\n * are a lot of categories)\n * 3. The layout specifies exactly what colors and categories to use (and they match the data!). This is useful to\n * specify an explicit mapping between color scheme and category names, when you want to be sure that the\n * plot matches a standard color scheme.\n * (If the layout specifies categories that do not match the data, the user specified categories will be ignored)\n *\n * This method will only act if the layout defines a `categorical_bin` scale function for coloring. It may be\n * overridden in a subclass to suit other types of coloring methods.\n *\n * @param {String[]} categoryNames\n * @private\n */\n _setDynamicColorScheme(categoryNames) {\n const colorParams = this._getColorScale(this.layout).parameters;\n const baseParams = this._getColorScale(this._base_layout).parameters;\n\n if (baseParams.categories.length && baseParams.values.length) {\n // If there are preset category/color combos, make sure that they apply to the actual dataset\n const parameters_categories_hash = {};\n baseParams.categories.forEach((category) => {\n parameters_categories_hash[category] = 1;\n });\n if (categoryNames.every((name) => Object.prototype.hasOwnProperty.call(parameters_categories_hash, name))) {\n // The layout doesn't have to specify categories in order, but make sure they are all there\n colorParams.categories = baseParams.categories;\n } else {\n colorParams.categories = categoryNames;\n }\n } else {\n colorParams.categories = categoryNames;\n }\n // Prefer user-specified colors if provided. Make sure that there are enough colors for all the categories.\n let colors;\n if (baseParams.values.length) {\n colors = baseParams.values;\n } else {\n // Originally from d3v3 category20\n colors = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'];\n }\n while (colors.length < categoryNames.length) {\n colors = colors.concat(colors);\n }\n colors = colors.slice(0, categoryNames.length); // List of hex values, should be of same length as categories array\n colorParams.values = colors;\n }\n\n /**\n *\n * @param dimension\n * @param {Object} [config] Parameters that customize how ticks are calculated (not style)\n * @param {('left'|'center'|'right')} [config.position='left'] Align ticks with the center or edge of category\n * @returns {Array}\n */\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error('Invalid dimension identifier');\n }\n const position = config.position || 'left';\n if (!['left', 'center', 'right'].includes(position)) {\n throw new Error('Invalid tick position');\n }\n\n const categoryBounds = this._categories;\n if (!categoryBounds || !Object.keys(categoryBounds).length) {\n return [];\n }\n\n if (dimension === 'y') {\n return [];\n }\n\n if (dimension === 'x') {\n // If colors have been defined by this layer, use them to make tick colors match scatterplot point colors\n const colors = this._getColorScale(this.layout);\n const knownCategories = colors.parameters.categories || [];\n const knownColors = colors.parameters.values || [];\n\n return Object.keys(categoryBounds).map((category, index) => {\n const bounds = categoryBounds[category];\n let xPos;\n\n switch (position) {\n case 'left':\n xPos = bounds[0];\n break;\n case 'center':\n // Center tick under one or many elements as appropriate\n // eslint-disable-next-line no-case-declarations\n const diff = bounds[1] - bounds[0];\n xPos = bounds[0] + (diff !== 0 ? diff : bounds[0]) / 2;\n break;\n case 'right':\n xPos = bounds[1];\n break;\n }\n return {\n x: xPos,\n text: category,\n style: {\n 'fill': knownColors[knownCategories.indexOf(category)] || '#000000',\n },\n };\n });\n }\n }\n\n applyCustomDataMethods() {\n this.data = this._prepareData();\n this._categories = this._generateCategoryBounds();\n return this;\n }\n}\n\n\nexport { Scatter as scatter, CategoryScatter as category_scatter };\n","/**\n * Helper functions targeted at rendering operations\n * @module\n * @private\n*/\n\n\n/**\n * A very simple function aimed at scatter plots: attempts to coalesce \"low-significance\" SNPs that are too close to\n * visually distinguish, thus creating a dataset with fewer points that can be rendered more quickly.\n *\n * This depends on the strong and explicit assumption that points are ordered (typically in x position), so that\n * nearby points can be grouped by iterating over the data in sequence.\n *\n * @param {Object[]} data Plot data, annotated with calculated `xc` and `yc` symbols for x and y coordinates (in px).\n * @param {Number} x_min The smallest x value of an \"insignificant region\" rectangle\n * @param {Number} x_max The largest x value of an \"insignificant region\" rectangle\n * @param {Number} x_gap Max px distance, in x direction, from the first point in a set, to qualify for grouping\n * @param {Number} y_min The smallest y value of an \"insignificant region\" rectangle\n * @param {Number} y_max The largest y value of an \"insignificant region\" rectangle\n * @param {Number} y_gap Max px distance, in y direction, from the first point in a set, to qualify for grouping\n * @return {Object[]} The simplified dataset with fewer points\n */\nfunction coalesce_scatter_points (data, x_min, x_max, x_gap, y_min, y_max, y_gap) {\n let final_data = [];\n\n const xcs = Symbol.for('lzX');\n const ycs = Symbol.for('lzY');\n\n let x_start = null;\n let y_start = null;\n let current_group = [];\n\n function _combine () {\n if (current_group.length) {\n // If there are points near each other, return the middle item to represent the group\n // We use a real point (rather than a synthetic average point) to best handle extra fields\n const item = current_group[Math.floor((current_group.length - 1) / 2)];\n final_data.push(item);\n }\n x_start = y_start = null;\n current_group = [];\n }\n\n function _start_run(x, y, item) {\n x_start = x;\n y_start = y;\n current_group.push(item);\n }\n\n data.forEach((item) => {\n const x = item[xcs];\n const y = item[ycs];\n\n const in_combine_region = (x >= x_min && x <= x_max && y >= y_min && y <= y_max);\n if (item.lz_is_match || !in_combine_region) {\n // If an item is marked as interesting in some way, always render it explicitly\n // (and coalesce the preceding points if a run was in progress, to preserve ordering)\n _combine();\n final_data.push(item);\n } else if (x_start === null) {\n // If not tracking a group, start tracking\n _start_run(x, y, item);\n } else {\n // Otherwise, the decision to render the point depends on whether it is close to a run of other\n // insignificant points\n const near_prior = Math.abs(x - x_start) <= x_gap && Math.abs(y - y_start) <= y_gap;\n\n if (near_prior) {\n current_group.push(item);\n } else {\n // \"if in combine region, and not near a prior point, coalesce all prior items, then track this point\n // as part of the next run that could be grouped\"\n _combine();\n _start_run(x, y, item);\n }\n }\n });\n // At the end of the dataset, check whether any runs of adjacent points were in progress, and coalesce if so\n _combine();\n\n return final_data;\n}\n\nexport { coalesce_scatter_points };\n","/**\n * @module\n * @private\n */\nimport {ClassRegistry} from './base';\nimport * as layers from '../components/data_layer';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data rendering types (data layers).\n * @alias module:LocusZoom~DataLayers\n * @type {module:registry/base~ClassRegistry}\n */\nconst registry = new ClassRegistry();\nfor (let [name, type] of Object.entries(layers)) {\n registry.add(name, type);\n}\n\n\nexport default registry;\n","/**\n * Predefined layouts that describe how to draw common types of data, as well as what interactive features to use.\n * Each plot contains multiple panels (rows), and each row can stack several kinds of data in layers\n * (eg scatter plot and line of significance). Layouts provide the building blocks to provide interactive experiences\n * and user-friendly tooltips for common kinds of genetic data.\n *\n * Many of these layouts (like the standard association plot) assume that field names are the same as those provided\n * in the UMich [portaldev API](https://portaldev.sph.umich.edu/docs/api/v1/). Although layouts can be used on many\n * kinds of data, it is often less work to write an adapter that uses the same field names, rather than to modify\n * every single reference to a field anywhere in the layout.\n *\n * See the Layouts Tutorial for details on how to customize nested layouts.\n *\n * @module LocusZoom_Layouts\n */\n\nimport version from '../version';\nimport {deepCopy, merge} from '../helpers/layouts';\n\nconst LZ_SIG_THRESHOLD_LOGP = 7.301; // -log10(.05/1e6)\n\n/*\n * Tooltip Layouts\n */\nconst standard_association_tooltip = {\n namespace: { 'assoc': 'assoc' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: `{{{{namespace[assoc]}}variant|htmlescape}}
\n P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
\n {{#if {{namespace[ld]}}isrefvar}}LD Reference Variant{{#else}}\n Make LD Reference{{/if}}
`,\n};\n\nconst standard_association_tooltip_with_label = function() {\n // Add a special \"toggle label\" button to the base tooltip. This must be used in tandem with a custom layout\n // directive (label.filters should check a boolean annotation field called \"lz_show_label\").\n const base = deepCopy(standard_association_tooltip);\n base.html += `{{#if lz_show_label}}Hide{{#else}}Show{{/if}} label`;\n return base;\n}();\n\nconst standard_genes_tooltip = {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '

{{gene_name|htmlescape}}

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

{{/if}}'\n + 'More data on gnomAD',\n};\n\nconst catalog_variant_tooltip = {\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[catalog]}}variant|htmlescape}}
'\n + 'Catalog entries: {{n_catalog_matches|htmlescape}}
'\n + 'Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
'\n + 'Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
'\n // User note: if a different catalog is used, the tooltip will need to be replaced with a different link URL\n + 'More: GWAS catalog / dbSNP',\n};\n\nconst coaccessibility_tooltip = {\n namespace: { 'access': 'access' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n // TODO: Is there a more generic terminology? (eg not every technique is in terms of cis-regulatory element)\n html: 'Regulatory element
' +\n '{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
' +\n 'Promoter
' +\n '{{{{namespace[access]}}start2|htmlescape}}-{{{{namespace[access]}}end2|htmlescape}}
' +\n '{{#if {{namespace[access]}}target}}Target: {{{{namespace[access]}}target|htmlescape}}
{{/if}}' +\n 'Score: {{{{namespace[access]}}score|htmlescape}}',\n};\n\n/*\n * Data Layer Layouts: represent specific information given provided data.\n */\n\n/**\n * A horizontal line of GWAS significance at the standard threshold of p=5e-8\n * @name significance\n * @type data_layer\n */\nconst significance_layer = {\n id: 'significance',\n type: 'orthogonal_line',\n tag: 'significance',\n orientation: 'horizontal',\n offset: LZ_SIG_THRESHOLD_LOGP,\n};\n\n/**\n * A simple curve representing the genetic recombination rate, drawn from the UM API\n * @name recomb_rate\n * @type data_layer\n */\nconst recomb_rate_layer = {\n namespace: { 'recomb': 'recomb' },\n id: 'recombrate',\n type: 'line',\n tag: 'recombination',\n fields: ['{{namespace[recomb]}}position', '{{namespace[recomb]}}recomb_rate'],\n z_index: 1,\n style: {\n 'stroke': '#0000FF',\n 'stroke-width': '1.5px',\n },\n x_axis: {\n field: '{{namespace[recomb]}}position',\n },\n y_axis: {\n axis: 2,\n field: '{{namespace[recomb]}}recomb_rate',\n floor: 0,\n ceiling: 100,\n },\n};\n\n/**\n * A scatter plot of GWAS association summary statistics, with preset field names matching the UM portaldev api\n * @name association_pvalues\n * @type data_layer\n */\nconst association_pvalues_layer = {\n namespace: { 'assoc': 'assoc', 'ld': 'ld' },\n id: 'associationpvalues',\n type: 'scatter',\n tag: 'association',\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation', '{{namespace[assoc]}}ref_allele', '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar'],\n id_field: '{{namespace[assoc]}}variant',\n coalesce: {\n active: true,\n },\n point_shape: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 'diamond',\n else: 'circle',\n },\n },\n point_size: {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: 80,\n else: 40,\n },\n },\n color: [\n {\n scale_function: 'if',\n field: '{{namespace[ld]}}isrefvar',\n parameters: {\n field_value: 1,\n then: '#9632b8',\n },\n },\n {\n scale_function: 'numerical_bin',\n field: '{{namespace[ld]}}state',\n parameters: {\n breaks: [0, 0.2, 0.4, 0.6, 0.8],\n // Derived from Google \"Turbo\" colormap, breakpoints [0.05, 0.25, 0.45, 0.65, 0.85]\n values: ['rgb(70, 54, 153)', 'rgb(38, 188, 225)', 'rgb(110, 254, 104)', 'rgb(248, 195, 42)', 'rgb(219, 61, 17)'],\n },\n },\n '#AAAAAA',\n ],\n legend: [\n { shape: 'diamond', color: '#9632b8', size: 40, label: 'LD Ref Var', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: 'rgb(219, 61, 17)', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: 'rgb(248, 195, 42)', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: 'rgb(110, 254, 104)', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: 'rgb(38, 188, 225)', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: 'rgb(70, 54, 153)', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' },\n { shape: 'circle', color: '#AAAAAA', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' },\n ],\n label: null,\n z_index: 2,\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[assoc]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.10,\n min_extent: [0, 10],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(standard_association_tooltip),\n};\n\n/**\n * An arc track that shows arcs representing chromatic coaccessibility\n * @name coaccessibility\n * @type data_layer\n */\nconst coaccessibility_layer = {\n namespace: { 'access': 'access' },\n id: 'coaccessibility',\n type: 'arcs',\n tag: 'coaccessibility',\n fields: ['{{namespace[access]}}start1', '{{namespace[access]}}end1', '{{namespace[access]}}start2', '{{namespace[access]}}end2', '{{namespace[access]}}id', '{{namespace[access]}}target', '{{namespace[access]}}score'],\n match: { send: '{{namespace[access]}}target', receive: '{{namespace[access]}}target' },\n id_field: '{{namespace[access]}}id',\n filters: [\n { field: '{{namespace[access]}}score', operator: '!=', value: null },\n ],\n color: [\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#4285f4',\n },\n },\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n {\n scale_function: 'ordinal_cycle',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'], // Drawn from d3v3 \"category20\"\n },\n },\n ],\n x_axis: {\n field1: '{{namespace[access]}}start1',\n field2: '{{namespace[access]}}start2',\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[access]}}score',\n upper_buffer: 0.1,\n min_extent: [0, 1],\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(coaccessibility_tooltip),\n};\n\n/**\n * A scatter plot of GWAS summary statistics, with additional tooltip fields showing GWAS catalog annotations\n * @name association_pvalues_catalog\n * @type data_layer\n */\nconst association_pvalues_catalog_layer = function () {\n // Slightly modify an existing layout\n let base = deepCopy(association_pvalues_layer);\n base = merge({ id: 'associationpvaluescatalog', fill_opacity: 0.7 }, base);\n base.tooltip.html += '{{#if {{namespace[catalog]}}rsid}}
See hits in GWAS catalog{{/if}}';\n base.namespace.catalog = 'catalog';\n base.fields.push('{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait', '{{namespace[catalog]}}log_pvalue');\n return base;\n}();\n\n/**\n * A scatter plot of PheWAS pvalues, with preset field names matching the UM Portaldev API\n * @name phewas_pvalues\n * @type data_layer\n */\nconst phewas_pvalues_layer = {\n namespace: { 'phewas': 'phewas' },\n id: 'phewaspvalues',\n type: 'category_scatter',\n tag: 'phewas',\n point_shape: 'circle',\n point_size: 70,\n tooltip_positioning: 'vertical',\n id_field: '{{namespace[phewas]}}id',\n fields: ['{{namespace[phewas]}}id', '{{namespace[phewas]}}log_pvalue', '{{namespace[phewas]}}trait_group', '{{namespace[phewas]}}trait_label'],\n x_axis: {\n field: '{{namespace[phewas]}}x', // Synthetic/derived field added by `category_scatter` layer\n category_field: '{{namespace[phewas]}}trait_group',\n lower_buffer: 0.025,\n upper_buffer: 0.025,\n },\n y_axis: {\n axis: 1,\n field: '{{namespace[phewas]}}log_pvalue',\n floor: 0,\n upper_buffer: 0.15,\n },\n color: [{\n field: '{{namespace[phewas]}}trait_group',\n scale_function: 'categorical_bin',\n parameters: {\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n }],\n fill_opacity: 0.7,\n tooltip: {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: [\n 'Trait: {{{{namespace[phewas]}}trait_label|htmlescape}}
',\n 'Trait Category: {{{{namespace[phewas]}}trait_group|htmlescape}}
',\n 'P-value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
',\n ].join(''),\n },\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n label: {\n text: '{{{{namespace[phewas]}}trait_label}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n {\n field: '{{namespace[phewas]}}log_pvalue',\n operator: '>=',\n value: 20,\n },\n ],\n style: {\n 'font-size': '14px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n};\n\n/**\n * Shows genes in the specified region, with names and formats drawn from the UM Portaldev API and GENCODE datasource\n * @type data_layer\n */\nconst genes_layer = {\n namespace: { 'gene': 'gene', 'constraint': 'constraint' },\n id: 'genes',\n type: 'genes',\n tag: 'genes',\n fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'],\n id_field: 'gene_id',\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(standard_genes_tooltip),\n};\n\n/**\n * A genes data layer that uses filters to limit what information is shown by default. This layer hides a curated\n * list of GENCODE gene_types that are of less interest to most analysts.\n * Often used in tandem with a panel-level toolbar \"show all\" button so that the user can toggle to a full view.\n * @name genes_filtered\n * @type data_layer\n */\nconst genes_layer_filtered = merge({\n filters: [\n {\n field: 'gene_type',\n operator: 'in',\n // A manually curated subset of Gencode biotypes, based on user suggestions\n // See full list: https://www.gencodegenes.org/human/stats.html\n // This is approximately intended to cover elements of generally known function, and exclude things\n // like pseudogenes.\n value: [\n 'protein_coding',\n 'IG_C_gene', 'IG_D_gene', 'IG_J_gene', 'IG_V_gene',\n 'TR_C_gene', 'TR_D_gene', 'TR_J_gene', 'TR_V_gene',\n 'rRNA',\n 'Mt_rRNA', 'Mt_tRNA',\n ],\n },\n ],\n}, deepCopy(genes_layer));\n\n/**\n * An annotation / rug track that shows tick marks for each position in which a variant is present in the provided\n * association data, *and* has a significant claim in the EBI GWAS catalog.\n * @type data_layer\n */\nconst annotation_catalog_layer = {\n // Identify GWAS hits that are present in the GWAS catalog\n namespace: { 'assoc': 'assoc', 'catalog': 'catalog' },\n id: 'annotation_catalog',\n type: 'annotation_track',\n tag: 'gwascatalog',\n id_field: '{{namespace[assoc]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: '#0000CC',\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}chromosome', '{{namespace[assoc]}}position',\n '{{namespace[catalog]}}variant', '{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait',\n '{{namespace[catalog]}}log_pvalue', '{{namespace[catalog]}}pos',\n ],\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: '{{namespace[catalog]}}rsid', operator: '!=', value: null },\n { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n },\n tooltip: deepCopy(catalog_variant_tooltip),\n tooltip_positioning: 'top',\n};\n\n/*\n * Individual toolbar buttons\n */\n\n/**\n * A dropdown menu that can be used to control the LD population used with the LDServer Adapter. Population\n * names are provided for the 1000G dataset that is used by the offical UM LD Server.\n * @name ldlz2_pop_selector\n * @type toolbar_widgets\n */\nconst ldlz2_pop_selector_menu = {\n // **Note**: this widget is aimed at the LDServer datasource, and the UM 1000G LDServer\n type: 'set_state',\n tag: 'ld_population',\n position: 'right',\n color: 'blue',\n button_html: 'LD Population: ',\n show_selected: true,\n button_title: 'Select LD Population: ',\n custom_event_name: 'widget_set_ldpop',\n state_field: 'ld_pop',\n // This list below is hardcoded to work with the UMich LDServer, default 1000G populations\n // It can be customized to work with other LD servers that specify population differently\n // https://portaldev.sph.umich.edu/ld/genome_builds/GRCh37/references/1000G/populations\n options: [\n { display_name: 'ALL (default)', value: 'ALL' },\n { display_name: 'AFR', value: 'AFR' },\n { display_name: 'AMR', value: 'AMR' },\n { display_name: 'EAS', value: 'EAS' },\n { display_name: 'EUR', value: 'EUR' },\n { display_name: 'SAS', value: 'SAS' },\n ],\n};\n\n/**\n * A dropdown menu that selects which types of genes to show in the plot. The provided options are curated sets of\n * interesting gene types based on the GENCODE dataset.\n * @type toolbar_widgets\n */\nconst gene_selector_menu = {\n type: 'display_options',\n tag: 'gene_filter',\n custom_event_name: 'widget_gene_filter_choice',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Filter...',\n button_title: 'Choose which genes to show',\n layer_name: 'genes',\n default_config_display_name: 'Coding genes & rRNA',\n options: [\n {\n display_name: 'All features',\n display: {\n filters: null,\n },\n },\n ],\n};\n\n/*\n * Toolbar Layouts: Collections of toolbar buttons etc\n */\n\n/**\n * Basic options to remove and reorder panels\n * @name standard_panel\n * @type toolbar\n */\nconst standard_panel_toolbar = {\n widgets: [\n {\n type: 'remove_panel',\n position: 'right',\n color: 'red',\n group_position: 'end',\n },\n {\n type: 'move_panel_up',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'move_panel_down',\n position: 'right',\n group_position: 'start',\n style: { 'margin-left': '0.75em' },\n },\n ],\n};\n\n/**\n * A simple plot toolbar with buttons to download as image\n * @name standard_plot\n * @type toolbar\n */\nconst standard_plot_toolbar = {\n // Suitable for most any type of plot drawn with LZ. Title and download buttons.\n widgets: [\n {\n type: 'title',\n title: 'LocusZoom',\n subtitle: `v${version}`,\n position: 'left',\n },\n {\n type: 'download',\n position: 'right',\n group_position: 'end',\n },\n {\n type: 'download_png',\n position: 'right',\n group_position: 'start',\n },\n ],\n};\n\n/**\n * A plot toolbar that adds a button for controlling LD population. This is useful for plots intended to show\n * GWAS summary stats, which is one of the most common usages of LocusZoom.\n * @type toolbar\n */\nconst standard_association_toolbar = function () {\n // Suitable for association plots (adds a button for LD data)\n const base = deepCopy(standard_plot_toolbar);\n base.widgets.push(deepCopy(ldlz2_pop_selector_menu));\n return base;\n}();\n\n/**\n * A basic plot toolbar with buttons to scroll sideways or zoom in. Useful for all region-based plots.\n * @name region_nav_plot\n * @type toolbar\n */\nconst region_nav_plot_toolbar = function () {\n // Generic region nav buttons\n const base = deepCopy(standard_plot_toolbar);\n base.widgets.push(\n {\n type: 'shift_region',\n step: 500000,\n button_html: '>>',\n position: 'right',\n group_position: 'end',\n }, {\n type: 'shift_region',\n step: 50000,\n button_html: '>',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: 0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'zoom_region',\n step: -0.2,\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -50000,\n button_html: '<',\n position: 'right',\n group_position: 'middle',\n },\n {\n type: 'shift_region',\n step: -500000,\n button_html: '<<',\n position: 'right',\n group_position: 'start',\n }\n );\n return base;\n}();\n\n/*\n * Panel Layouts\n */\n\n\n/**\n * A panel that describes the most common kind of LocusZoom plot, with line of GWAS significance, recombination rate,\n * and a scatter plot superimposed.\n * @name association\n * @type panel\n */\nconst association_panel = {\n id: 'association',\n tag: 'association',\n min_height: 200,\n height: 225,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push({\n type: 'toggle_legend',\n position: 'right',\n });\n return base;\n })(),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n y2: {\n label: 'Recombination Rate (cM/Mb)',\n label_offset: 40,\n },\n },\n legend: {\n orientation: 'vertical',\n origin: { x: 55, y: 40 },\n hidden: true,\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n drag_y2_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_layer),\n ],\n};\n\n/**\n * A panel showing chromatin coaccessibility arcs with some common display options\n * @type panel\n */\nconst coaccessibility_panel = {\n id: 'coaccessibility',\n tag: 'coaccessibility',\n min_height: 150,\n height: 180,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: 'Score',\n label_offset: 28,\n render: false, // We are mainly concerned with the relative magnitudes: hide y axis to avoid clutter.\n },\n },\n interaction: {\n drag_background_to_pan: true,\n drag_x_ticks_to_scale: true,\n drag_y1_ticks_to_scale: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(coaccessibility_layer),\n ],\n};\n\n/**\n * A panel showing GWAS summary statistics, plus annotations for connecting it to the EBI GWAS catalog\n * @type panel\n */\nconst association_catalog_panel = function () {\n let base = deepCopy(association_panel);\n base = merge({\n id: 'associationcatalog',\n namespace: { 'assoc': 'assoc', 'ld': 'ld', 'catalog': 'catalog' }, // Required to resolve display options\n }, base);\n\n base.toolbar.widgets.push({\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n\n layer_name: 'associationpvaluescatalog',\n default_config_display_name: 'No catalog labels (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: 'Label catalog traits', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n label: {\n text: '{{{{namespace[catalog]}}trait}}',\n spacing: 6,\n lines: {\n style: {\n 'stroke-width': '2px',\n 'stroke': '#333333',\n 'stroke-dasharray': '2px 2px',\n },\n },\n filters: [\n // Only label points if they are significant for some trait in the catalog, AND in high LD\n // with the top hit of interest\n { field: '{{namespace[catalog]}}trait', operator: '!=', value: null },\n { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP },\n { field: '{{namespace[ld]}}state', operator: '>', value: 0.4 },\n ],\n style: {\n 'font-size': '10px',\n 'font-weight': 'bold',\n 'fill': '#333333',\n },\n },\n },\n },\n ],\n });\n base.data_layers = [\n deepCopy(significance_layer),\n deepCopy(recomb_rate_layer),\n deepCopy(association_pvalues_catalog_layer),\n ];\n return base;\n}();\n\n/**\n * A panel showing genes in the specified region. This panel lets the user choose which genes are shown.\n * @type panel\n */\nconst genes_panel = {\n id: 'genes',\n tag: 'genes',\n min_height: 150,\n height: 225,\n margin: { top: 20, right: 50, bottom: 20, left: 50 },\n axes: {},\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n toolbar: (function () {\n const base = deepCopy(standard_panel_toolbar);\n base.widgets.push(\n {\n type: 'resize_to_data',\n position: 'right',\n button_html: 'Resize',\n },\n deepCopy(gene_selector_menu)\n );\n return base;\n })(),\n data_layers: [\n deepCopy(genes_layer_filtered),\n ],\n};\n\n/**\n * A panel that displays PheWAS scatter plots and automatically generates a color scheme\n * @type panel\n */\nconst phewas_panel = {\n id: 'phewas',\n tag: 'phewas',\n min_height: 300,\n height: 300,\n margin: { top: 20, right: 50, bottom: 120, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n axes: {\n x: {\n ticks: { // Object based config (shared defaults; allow layers to specify ticks)\n style: {\n 'font-weight': 'bold',\n 'font-size': '11px',\n 'text-anchor': 'start',\n },\n transform: 'rotate(50)',\n position: 'left', // Special param recognized by `category_scatter` layers\n },\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 28,\n },\n },\n data_layers: [\n deepCopy(significance_layer),\n deepCopy(phewas_pvalues_layer),\n ],\n};\n\n/**\n * A panel that shows a simple annotation track connecting GWAS results\n * @name annotation_catalog\n * @type panel\n */\nconst annotation_catalog_panel = {\n id: 'annotationcatalog',\n tag: 'gwascatalog',\n min_height: 50,\n height: 50,\n margin: { top: 25, right: 50, bottom: 10, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: deepCopy(standard_panel_toolbar),\n axes: {\n x: { extent: 'state', render: false },\n },\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n data_layers: [\n deepCopy(annotation_catalog_layer),\n ],\n};\n\n/*\n * Plot Layouts\n */\n\n/**\n * Describes how to fetch and draw each part of the most common LocusZoom plot (with field names that reference the portaldev API)\n * @name standard_association\n * @type plot\n */\nconst standard_association_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: standard_association_toolbar,\n panels: [\n deepCopy(association_panel),\n deepCopy(genes_panel),\n ],\n};\n\n/**\n * A modified version of the standard LocusZoom plot, which adds a track that shows which SNPs in the plot also have claims in the EBI GWAS catalog.\n * @name association_catalog\n * @type plot\n */\nconst association_catalog_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: standard_association_toolbar,\n panels: [\n annotation_catalog_panel,\n association_catalog_panel,\n genes_panel,\n ],\n};\n\n/**\n * A PheWAS scatter plot with an additional track showing nearby genes, to put the region in biological context.\n * @name standard_phewas\n * @type plot\n */\nconst standard_phewas_plot = {\n width: 800,\n responsive_resize: true,\n toolbar: standard_plot_toolbar,\n panels: [\n deepCopy(phewas_panel),\n merge({\n height: 300,\n margin: { bottom: 40 },\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 32,\n tick_format: 'region',\n extent: 'state',\n },\n },\n }, deepCopy(genes_panel)),\n ],\n mouse_guide: false,\n};\n\n/**\n * Show chromatin coaccessibility arcs, with additional features that connect these arcs to nearby genes to show regulatory interactions.\n * @name coaccessibility\n * @type plot\n */\nconst coaccessibility_plot = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: deepCopy(standard_plot_toolbar),\n panels: [\n deepCopy(coaccessibility_panel),\n function () {\n // Take the default genes panel, and add a custom feature to highlight gene tracks based on short name\n // This is a companion to the \"match\" directive in the coaccessibility panel\n const base = Object.assign(\n { height: 270 },\n deepCopy(genes_panel)\n );\n const layer = base.data_layers[0];\n layer.match = { send: 'gene_name', receive: 'gene_name' };\n const color_config = [\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#4285f4',\n },\n },\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: false,\n then: '#EAE6E6',\n },\n },\n '#363696',\n ];\n layer.color = color_config;\n layer.stroke = color_config;\n return base;\n }(),\n ],\n};\n\n\nexport const tooltip = {\n standard_association: standard_association_tooltip,\n standard_association_with_label: standard_association_tooltip_with_label,\n standard_genes: standard_genes_tooltip,\n catalog_variant: catalog_variant_tooltip,\n coaccessibility: coaccessibility_tooltip,\n};\n\nexport const toolbar_widgets = {\n ldlz2_pop_selector: ldlz2_pop_selector_menu,\n gene_selector_menu,\n};\n\nexport const toolbar = {\n standard_panel: standard_panel_toolbar,\n standard_plot: standard_plot_toolbar,\n standard_association: standard_association_toolbar,\n region_nav_plot: region_nav_plot_toolbar,\n};\n\nexport const data_layer = {\n significance: significance_layer,\n recomb_rate: recomb_rate_layer,\n association_pvalues: association_pvalues_layer,\n coaccessibility: coaccessibility_layer,\n association_pvalues_catalog: association_pvalues_catalog_layer,\n phewas_pvalues: phewas_pvalues_layer,\n genes: genes_layer,\n genes_filtered: genes_layer_filtered,\n annotation_catalog: annotation_catalog_layer,\n};\n\nexport const panel = {\n association: association_panel,\n coaccessibility: coaccessibility_panel,\n association_catalog: association_catalog_panel,\n genes: genes_panel,\n phewas: phewas_panel,\n annotation_catalog: annotation_catalog_panel,\n};\n\nexport const plot = {\n standard_association: standard_association_plot,\n association_catalog: association_catalog_plot,\n standard_phewas: standard_phewas_plot,\n coaccessibility: coaccessibility_plot,\n};\n","import {RegistryBase} from './base';\nimport {applyNamespaces, deepCopy, mutate_attrs, merge, query_attrs, renameField} from '../helpers/layouts';\nimport * as layouts from '../layouts';\n\n/**\n * Helper for working with predefined layouts\n *\n * This is part of the public interface with LocusZoom and a major way that users interact to configure plots.\n *\n * Each layout object that is added or retrieved here is a deep copy and totally independent from any other object\n * @public\n * @extends module:registry/base:RegistryBase\n * @inheritDoc\n */\nclass LayoutRegistry extends RegistryBase {\n // Implemented as a \"registry of registries\"- one lookup each for panels, plots, etc...\n get(type, name, overrides = {}) {\n if (!(type && name)) {\n throw new Error('Must specify both the type and name for the layout desired. See .list() for available options');\n }\n // This is a registry of registries. Fetching an item may apply additional custom behaviors, such as\n // applying overrides or using namespaces to convert an abstract layout into a concrete one.\n let base = super.get(type).get(name);\n base = merge(overrides, base);\n if (base.unnamespaced) {\n delete base.unnamespaced;\n return deepCopy(base);\n }\n let default_namespace = '';\n if (typeof base.namespace == 'string') {\n default_namespace = base.namespace;\n } else if (typeof base.namespace == 'object' && Object.keys(base.namespace).length) {\n if (typeof base.namespace.default != 'undefined') {\n default_namespace = base.namespace.default;\n } else {\n default_namespace = base.namespace[Object.keys(base.namespace)[0]].toString();\n }\n }\n default_namespace += default_namespace.length ? ':' : '';\n const result = applyNamespaces(base, base.namespace, default_namespace);\n\n return deepCopy(result);\n }\n\n /**\n * Add a type of layout to the registry\n * @param {String} type The type of layout to add (plot, panel, data_layer, toolbar, toolbar_widgets, or tooltip)\n * @param {String} name The name of the layout object to add\n * @param {Object} item The layout object describing parameters\n * @param {boolean} override Whether to replace an existing item by that name\n * @return {*}\n */\n add(type, name, item, override = false) {\n if (!(type && name && item)) {\n throw new Error('To add a layout, type, name, and item must all be specified');\n }\n if (!(typeof item === 'object')) {\n throw new Error('The configuration to be added must be an object');\n }\n\n if (!this.has(type)) {\n super.add(type, new RegistryBase());\n }\n // Ensure that each use of a layout can be modified, by returning a copy is independent\n const copy = deepCopy(item);\n return super.get(type).add(name, copy, override);\n }\n\n /**\n * List all available types of layout (eg toolbar, panel, etc). If a specific type name is provided, list the\n * layouts for that type of element (\"just predefined panels\").\n * @param {String} [type] The type of layout (eg toolbar, panel, etc)\n * @return {String[]|Object}\n */\n list(type) {\n if (!type) {\n let result = {};\n for (let [type, contents] of this._items) {\n result[type] = contents.list();\n }\n return result;\n }\n return super.get(type).list();\n }\n\n /**\n * Static alias to a helper method. Preserved for backwards compatibility, so that UMD users can access this method.\n * @static\n * @private\n */\n merge(custom_layout, default_layout) {\n return merge(custom_layout, default_layout);\n }\n\n /**\n * Static alias to a helper method. Allows renaming fields\n * @static\n * @private\n */\n renameField() {\n return renameField(...arguments);\n }\n\n /**\n * Static alias to a helper method. Allows mutating nested layout attributes\n * @static\n * @private\n */\n mutate_attrs() {\n return mutate_attrs(...arguments);\n }\n\n /**\n * Static alias to a helper method. Allows mutating nested layout attributes\n * @static\n * @private\n */\n query_attrs() {\n return query_attrs(...arguments);\n }\n}\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided data adapters.\n * @alias module:LocusZoom~Layouts\n * @type {LayoutRegistry}\n */\nconst registry = new LayoutRegistry();\n\nfor (let [type, entries] of Object.entries(layouts)) {\n for (let [name, config] of Object.entries(entries)) {\n registry.add(type, name, config);\n }\n}\n\n\nexport default registry;\n\n// Export base class for unit testing\nexport {LayoutRegistry as _LayoutRegistry};\n","import {RegistryBase} from '../registry/base';\nimport { ADAPTERS } from '../registry';\n\n/**\n * Create and coordinate an ensemble of (namespaced) data adapter instances.\n * This is the mechanism by which users tell a plot how to retrieve data for a specific plot: adapters are created\n * through this object rather than instantiating directly.\n *\n * @public\n * @alias module:LocusZoom~DataSources\n * @extends module:registry/base~RegistryBase\n * @inheritDoc\n */\nclass DataSources extends RegistryBase {\n /**\n * @param {RegistryBase} [registry] Primarily used for unit testing. When creating sources by name, specify where to\n * find the registry of known sources.\n */\n constructor(registry) {\n super();\n // This both acts as a registry (of the instantiated sources for this plot), and references a registry\n // (to locate adapter classes by name, when creating from config)\n this._registry = registry || ADAPTERS;\n }\n\n /**\n * For data sources, there is a special behavior of \"create item from config, then add\"\n * @param {String} namespace Uniquely identify this datasource\n * @param {BaseAdapter|Array} item An instantiated datasource, or an array of arguments that can be used to\n * create a known datasource type.\n * @param [override=false] Whether to allow existing sources to be redefined\n * @return {DataSources} Most registries return the created instance, but this registry returns a reference to\n * itself (to support chaining)\n */\n add(namespace, item, override = false) {\n if (this._registry.has(namespace)) {\n throw new Error(`The namespace ${namespace} is already in use by another source`);\n }\n\n if (namespace.match(/[^A-Za-z0-9_]/)) {\n throw new Error(`Data source namespace names can only contain alphanumeric characters or underscores. Invalid name: ${namespace}`);\n }\n if (Array.isArray(item)) {\n const [type, options] = item;\n item = this._registry.create(type, options);\n }\n // Each datasource in the chain should be aware of its assigned namespace\n item.source_id = namespace;\n\n super.add(namespace, item, override);\n return this;\n }\n}\n\n\nexport default DataSources;\n","/**\n * Whether imported (ES6 modules) or loaded via script tag (UMD), this module represents\n * the \"public interface\" via which core LocusZoom features and plugins are exposed for programmatic usage.\n *\n * A library using this file will need to load `locuszoom.css` separately in order for styles to appear.\n *\n * @module LocusZoom\n */\nimport version from './version';\n\nimport {default as DataSources} from './data';\nimport { populate } from './helpers/display';\n\nimport {\n ADAPTERS as Adapters,\n DATA_LAYERS as DataLayers,\n WIDGETS as Widgets,\n LAYOUTS as Layouts,\n MATCHERS as MatchFunctions,\n SCALABLE as ScaleFunctions,\n TRANSFORMS as TransformationFunctions,\n} from './registry';\n\n\nconst LocusZoom = {\n version,\n // Helpers for creating plots- the main public interface for most use cases\n populate,\n DataSources,\n // Registries for plugin system\n Adapters,\n DataLayers,\n Layouts,\n MatchFunctions,\n ScaleFunctions,\n TransformationFunctions,\n Widgets,\n\n get KnownDataSources() { // Backwards- compatibility alias\n console.warn('Deprecation warning: KnownDataSources has been renamed to \"Adapters\"');\n return Adapters;\n },\n};\n\n\n/**\n * @callback pluginCallback\n * @param {Object} LocusZoom The global LocusZoom object\n * @param args Any additional arguments passed to LocusZoom.use will be passed to the function when the plugin is loaded\n */\n\n\nconst INSTALLED_PLUGINS = [];\n\n/**\n * @alias module:LocusZoom.use\n * @param {pluginCallback} plugin The plugin should be a module that exports the function as either the default export,\n * or as a member named \"install\"\n * @param args Additional options to be passed when creating the plugin\n */\nLocusZoom.use = function(plugin, ...args) {\n // Deliberately similar implementation to Vue.js .use() plugin system\n if (INSTALLED_PLUGINS.includes(plugin)) {\n // Avoid double-installation of a plugin\n return;\n }\n\n args.unshift(LocusZoom); // All plugins are passed a reference to LocusZoom object\n if (typeof plugin.install === 'function') {\n plugin.install.apply(plugin, args);\n } else if (typeof plugin === 'function') {\n plugin.apply(null, args);\n } else {\n throw new Error('Plugin must export a function that receives the LocusZoom object as an argument');\n }\n INSTALLED_PLUGINS.push(plugin);\n};\n\n\nexport default LocusZoom;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/docs/api/LayoutRegistry.html b/docs/api/LayoutRegistry.html index 0746edf0..659fb5bc 100644 --- a/docs/api/LayoutRegistry.html +++ b/docs/api/LayoutRegistry.html @@ -1430,7 +1430,7 @@

Home

Modules

  • diff --git a/docs/api/Line.html b/docs/api/Line.html index d8d80fb0..e2e22c07 100644 --- a/docs/api/Line.html +++ b/docs/api/Line.html @@ -725,7 +725,7 @@

    Home

    Modules

    • diff --git a/docs/api/Panel.html b/docs/api/Panel.html index 4c679f94..2178c81f 100644 --- a/docs/api/Panel.html +++ b/docs/api/Panel.html @@ -4401,7 +4401,7 @@

      Home

      Modules

      • diff --git a/docs/api/Plot.html b/docs/api/Plot.html index 47f3510b..00062a08 100644 --- a/docs/api/Plot.html +++ b/docs/api/Plot.html @@ -2902,7 +2902,7 @@

        Home

        Modules

        • diff --git a/docs/api/TransformationFunctionsRegistry.html b/docs/api/TransformationFunctionsRegistry.html index 27c8a96b..b344f6f7 100644 --- a/docs/api/TransformationFunctionsRegistry.html +++ b/docs/api/TransformationFunctionsRegistry.html @@ -311,7 +311,7 @@

          Home

          Modules

          • diff --git a/docs/api/components_data_layer_annotation_track.js.html b/docs/api/components_data_layer_annotation_track.js.html index 31822197..40991901 100644 --- a/docs/api/components_data_layer_annotation_track.js.html +++ b/docs/api/components_data_layer_annotation_track.js.html @@ -177,7 +177,7 @@

            Home

            Modules

            • diff --git a/docs/api/components_data_layer_arcs.js.html b/docs/api/components_data_layer_arcs.js.html index 103236d1..b0036a83 100644 --- a/docs/api/components_data_layer_arcs.js.html +++ b/docs/api/components_data_layer_arcs.js.html @@ -186,7 +186,7 @@

              Home

              Modules

              • diff --git a/docs/api/components_data_layer_base.js.html b/docs/api/components_data_layer_base.js.html index ab306d38..40b2ba9a 100644 --- a/docs/api/components_data_layer_base.js.html +++ b/docs/api/components_data_layer_base.js.html @@ -1639,7 +1639,7 @@

                Home

                Modules

                • diff --git a/docs/api/components_data_layer_genes.js.html b/docs/api/components_data_layer_genes.js.html index 5640db5f..5371cc61 100644 --- a/docs/api/components_data_layer_genes.js.html +++ b/docs/api/components_data_layer_genes.js.html @@ -430,7 +430,7 @@

                  Home

                  Modules

                  • diff --git a/docs/api/components_data_layer_highlight_regions.js.html b/docs/api/components_data_layer_highlight_regions.js.html index 60b24f72..9e52bca8 100644 --- a/docs/api/components_data_layer_highlight_regions.js.html +++ b/docs/api/components_data_layer_highlight_regions.js.html @@ -183,7 +183,7 @@

                    Home

                    Modules

                    • diff --git a/docs/api/components_data_layer_line.js.html b/docs/api/components_data_layer_line.js.html index 436420c2..7fe6d3f2 100644 --- a/docs/api/components_data_layer_line.js.html +++ b/docs/api/components_data_layer_line.js.html @@ -312,7 +312,7 @@

                      Home

                      Modules

                      • diff --git a/docs/api/components_data_layer_scatter.js.html b/docs/api/components_data_layer_scatter.js.html index d1c31463..21b08a7b 100644 --- a/docs/api/components_data_layer_scatter.js.html +++ b/docs/api/components_data_layer_scatter.js.html @@ -722,7 +722,7 @@

                        Home

                        Modules

                        • diff --git a/docs/api/components_legend.js.html b/docs/api/components_legend.js.html index 9b9ab711..c38a31c7 100644 --- a/docs/api/components_legend.js.html +++ b/docs/api/components_legend.js.html @@ -282,7 +282,7 @@

                          Home

                          Modules

                          • diff --git a/docs/api/components_panel.js.html b/docs/api/components_panel.js.html index adfcb4cf..b7850410 100644 --- a/docs/api/components_panel.js.html +++ b/docs/api/components_panel.js.html @@ -1614,7 +1614,7 @@

                            Home

                            Modules

                            • diff --git a/docs/api/components_plot.js.html b/docs/api/components_plot.js.html index 35dbaaee..519f8a75 100644 --- a/docs/api/components_plot.js.html +++ b/docs/api/components_plot.js.html @@ -1468,7 +1468,7 @@

                              Home

                              Modules

                              • diff --git a/docs/api/components_toolbar_index.js.html b/docs/api/components_toolbar_index.js.html index eda853d2..d6f2712e 100644 --- a/docs/api/components_toolbar_index.js.html +++ b/docs/api/components_toolbar_index.js.html @@ -264,7 +264,7 @@

                                Home

                                Modules

                                • diff --git a/docs/api/components_toolbar_widgets.js.html b/docs/api/components_toolbar_widgets.js.html index 8e50c6dc..9e222988 100644 --- a/docs/api/components_toolbar_widgets.js.html +++ b/docs/api/components_toolbar_widgets.js.html @@ -1677,7 +1677,7 @@

                                  Home

                                  Modules

                                  • diff --git a/docs/api/data_adapters.js.html b/docs/api/data_adapters.js.html index 278318d9..487ea043 100644 --- a/docs/api/data_adapters.js.html +++ b/docs/api/data_adapters.js.html @@ -1297,7 +1297,7 @@

                                    Home

                                    Modules

                                    • diff --git a/docs/api/data_field.js.html b/docs/api/data_field.js.html index 5e2e4ab0..2c2f956a 100644 --- a/docs/api/data_field.js.html +++ b/docs/api/data_field.js.html @@ -108,7 +108,7 @@

                                      Home

                                      Modules

                                      • diff --git a/docs/api/data_requester.js.html b/docs/api/data_requester.js.html index 8e871b70..0b27b179 100644 --- a/docs/api/data_requester.js.html +++ b/docs/api/data_requester.js.html @@ -115,7 +115,7 @@

                                        Home

                                        Modules

                                        • diff --git a/docs/api/data_sources.js.html b/docs/api/data_sources.js.html index 4326f561..fa20c2fc 100644 --- a/docs/api/data_sources.js.html +++ b/docs/api/data_sources.js.html @@ -98,7 +98,7 @@

                                          Home

                                          Modules

                                          • diff --git a/docs/api/ext_lz-credible-sets.js.html b/docs/api/ext_lz-credible-sets.js.html index 36101804..aa3fc601 100644 --- a/docs/api/ext_lz-credible-sets.js.html +++ b/docs/api/ext_lz-credible-sets.js.html @@ -482,7 +482,7 @@

                                            Home

                                            Modules

                                            • diff --git a/docs/api/ext_lz-dynamic-urls.js.html b/docs/api/ext_lz-dynamic-urls.js.html index 5ef3564d..dd5bda47 100644 --- a/docs/api/ext_lz-dynamic-urls.js.html +++ b/docs/api/ext_lz-dynamic-urls.js.html @@ -248,7 +248,7 @@

                                              Home

                                              Modules

                                              • diff --git a/docs/api/ext_lz-forest-track.js.html b/docs/api/ext_lz-forest-track.js.html index ee4e3d78..ecc5c180 100644 --- a/docs/api/ext_lz-forest-track.js.html +++ b/docs/api/ext_lz-forest-track.js.html @@ -317,7 +317,7 @@

                                                Home

                                                Modules

                                                • diff --git a/docs/api/ext_lz-intervals-enrichment.js.html b/docs/api/ext_lz-intervals-enrichment.js.html index cfeb10f7..5bcbc09e 100644 --- a/docs/api/ext_lz-intervals-enrichment.js.html +++ b/docs/api/ext_lz-intervals-enrichment.js.html @@ -370,7 +370,7 @@

                                                  Home

                                                  Modules

                                                  • diff --git a/docs/api/ext_lz-intervals-track.js.html b/docs/api/ext_lz-intervals-track.js.html index 504233b5..9e3df01a 100644 --- a/docs/api/ext_lz-intervals-track.js.html +++ b/docs/api/ext_lz-intervals-track.js.html @@ -786,7 +786,7 @@

                                                    Home

                                                    Modules

                                                    • diff --git a/docs/api/ext_lz-tabix-source.js.html b/docs/api/ext_lz-tabix-source.js.html index c64d04ab..f575eebf 100644 --- a/docs/api/ext_lz-tabix-source.js.html +++ b/docs/api/ext_lz-tabix-source.js.html @@ -172,7 +172,7 @@

                                                      Home

                                                      Modules

                                                      • diff --git a/docs/api/ext_lz-widget-addons.js.html b/docs/api/ext_lz-widget-addons.js.html index 9b8c9e71..75ab7163 100644 --- a/docs/api/ext_lz-widget-addons.js.html +++ b/docs/api/ext_lz-widget-addons.js.html @@ -372,7 +372,7 @@

                                                        Home

                                                        Modules

                                                        • diff --git a/docs/api/global.html b/docs/api/global.html index 8d4ddd89..a9d15703 100644 --- a/docs/api/global.html +++ b/docs/api/global.html @@ -2116,7 +2116,7 @@

                                                          Home

                                                          Modules

                                                          • diff --git a/docs/api/helpers_common.js.html b/docs/api/helpers_common.js.html index a7e71cc6..8d2d49be 100644 --- a/docs/api/helpers_common.js.html +++ b/docs/api/helpers_common.js.html @@ -297,7 +297,7 @@

                                                            Home

                                                            Modules

                                                            • diff --git a/docs/api/helpers_display.js.html b/docs/api/helpers_display.js.html index 6a2afc3c..7a4fb411 100644 --- a/docs/api/helpers_display.js.html +++ b/docs/api/helpers_display.js.html @@ -400,7 +400,7 @@

                                                              Home

                                                              Modules

                                                              • diff --git a/docs/api/helpers_jsonpath.js.html b/docs/api/helpers_jsonpath.js.html index c198ac25..77e4ec52 100644 --- a/docs/api/helpers_jsonpath.js.html +++ b/docs/api/helpers_jsonpath.js.html @@ -270,7 +270,7 @@

                                                                Home

                                                                Modules

                                                                • diff --git a/docs/api/helpers_layouts.js.html b/docs/api/helpers_layouts.js.html index 2f3d06c1..6ad78c30 100644 --- a/docs/api/helpers_layouts.js.html +++ b/docs/api/helpers_layouts.js.html @@ -267,7 +267,7 @@

                                                                  Home

                                                                  Modules

                                                                  • diff --git a/docs/api/helpers_render.js.html b/docs/api/helpers_render.js.html index 0898e160..bf7e7448 100644 --- a/docs/api/helpers_render.js.html +++ b/docs/api/helpers_render.js.html @@ -127,7 +127,7 @@

                                                                    Home

                                                                    Modules

                                                                    • diff --git a/docs/api/helpers_scalable.js.html b/docs/api/helpers_scalable.js.html index ab0ab61b..ee25bf7a 100644 --- a/docs/api/helpers_scalable.js.html +++ b/docs/api/helpers_scalable.js.html @@ -248,7 +248,7 @@

                                                                      Home

                                                                      Modules

                                                                      • diff --git a/docs/api/helpers_transforms.js.html b/docs/api/helpers_transforms.js.html index c1d6988b..325a4a67 100644 --- a/docs/api/helpers_transforms.js.html +++ b/docs/api/helpers_transforms.js.html @@ -190,7 +190,7 @@

                                                                        Home

                                                                        Modules

                                                                        • diff --git a/docs/api/index.html b/docs/api/index.html index a84a916d..2a55fee9 100644 --- a/docs/api/index.html +++ b/docs/api/index.html @@ -46,7 +46,7 @@

                                                                          LocusZoom

                                                                          LocusZoom is a Javascript/d3 embeddable plugin for interactively visualizing statistical genetic data from customizable sources.

                                                                          Build Status

                                                                          -

                                                                          See github.com/statgen/locuszoom/wiki for full documentation and API reference.

                                                                          +

                                                                          See https://statgen.github.io/locuszoom/docs/ for full documentation and API reference.

                                                                          To see functional examples of plots generated with LocusZoom.js see statgen.github.io/locuszoom and statgen.github.io/locuszoom/#examples.

                                                                          LocusZoom.js Standard Association Plot

                                                                          Making a LocusZoom Plot

                                                                          @@ -229,7 +229,7 @@

                                                                          Home

                                                                          Modules

                                                                          • diff --git a/docs/api/index.js.html b/docs/api/index.js.html index 51f3c13a..0d0c1466 100644 --- a/docs/api/index.js.html +++ b/docs/api/index.js.html @@ -122,7 +122,7 @@

                                                                            Home

                                                                            Modules

                                                                            • diff --git a/docs/api/layouts_index.js.html b/docs/api/layouts_index.js.html index dc26bd95..8a6f7dcc 100644 --- a/docs/api/layouts_index.js.html +++ b/docs/api/layouts_index.js.html @@ -211,19 +211,20 @@

                                                                              Source: layouts/index.js

                                                                              field: '{{namespace[ld]}}state', parameters: { breaks: [0, 0.2, 0.4, 0.6, 0.8], - values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'], + // Derived from Google "Turbo" colormap, breakpoints [0.05, 0.25, 0.45, 0.65, 0.85] + values: ['rgb(70, 54, 153)', 'rgb(38, 188, 225)', 'rgb(110, 254, 104)', 'rgb(248, 195, 42)', 'rgb(219, 61, 17)'], }, }, - '#B8B8B8', + '#AAAAAA', ], legend: [ { shape: 'diamond', color: '#9632b8', size: 40, label: 'LD Ref Var', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#d43f3a', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#eea236', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#5cb85c', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#46b8da', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#357ebd', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' }, - { shape: 'circle', color: '#B8B8B8', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(219, 61, 17)', size: 40, label: '1.0 > r² ≥ 0.8', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(248, 195, 42)', size: 40, label: '0.8 > r² ≥ 0.6', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(110, 254, 104)', size: 40, label: '0.6 > r² ≥ 0.4', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(38, 188, 225)', size: 40, label: '0.4 > r² ≥ 0.2', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: 'rgb(70, 54, 153)', size: 40, label: '0.2 > r² ≥ 0.0', class: 'lz-data_layer-scatter' }, + { shape: 'circle', color: '#AAAAAA', size: 40, label: 'no r² data', class: 'lz-data_layer-scatter' }, ], label: null, z_index: 2, @@ -883,7 +884,7 @@

                                                                              Source: layouts/index.js

                                                                              }; /** - * A pael that displays PheWAS scatter plots and automatically generates a color scheme + * A panel that displays PheWAS scatter plots and automatically generates a color scheme * @type panel */ const phewas_panel = { @@ -1123,7 +1124,7 @@

                                                                              Home

                                                                              Modules

                                                                              • diff --git a/docs/api/module-LocusZoom-DataSources.html b/docs/api/module-LocusZoom-DataSources.html index 2ef71548..892bd951 100644 --- a/docs/api/module-LocusZoom-DataSources.html +++ b/docs/api/module-LocusZoom-DataSources.html @@ -1100,7 +1100,7 @@

                                                                                Home

                                                                                Modules

                                                                                • diff --git a/docs/api/module-LocusZoom.html b/docs/api/module-LocusZoom.html index d9edfc55..ba54be6d 100644 --- a/docs/api/module-LocusZoom.html +++ b/docs/api/module-LocusZoom.html @@ -1126,7 +1126,7 @@

                                                                                  Home

                                                                                  Modules

                                                                                  • diff --git a/docs/api/module-LocusZoom_Adapters-AssociationLZ.html b/docs/api/module-LocusZoom_Adapters-AssociationLZ.html index ef9bb476..756943cc 100644 --- a/docs/api/module-LocusZoom_Adapters-AssociationLZ.html +++ b/docs/api/module-LocusZoom_Adapters-AssociationLZ.html @@ -585,7 +585,7 @@

                                                                                    Home

                                                                                    Modules

                                                                                    • diff --git a/docs/api/module-LocusZoom_Adapters-BaseAdapter.html b/docs/api/module-LocusZoom_Adapters-BaseAdapter.html index bc206181..259a9940 100644 --- a/docs/api/module-LocusZoom_Adapters-BaseAdapter.html +++ b/docs/api/module-LocusZoom_Adapters-BaseAdapter.html @@ -2105,7 +2105,7 @@

                                                                                      Home

                                                                                      Modules

                                                                                      • diff --git a/docs/api/module-LocusZoom_Adapters-BaseApiAdapter.html b/docs/api/module-LocusZoom_Adapters-BaseApiAdapter.html index 132ec8f0..9437d30d 100644 --- a/docs/api/module-LocusZoom_Adapters-BaseApiAdapter.html +++ b/docs/api/module-LocusZoom_Adapters-BaseApiAdapter.html @@ -2167,7 +2167,7 @@

                                                                                        Home

                                                                                        Modules

                                                                                        • diff --git a/docs/api/module-LocusZoom_Adapters-ConnectorSource.html b/docs/api/module-LocusZoom_Adapters-ConnectorSource.html index dabf9ac7..d0a9371d 100644 --- a/docs/api/module-LocusZoom_Adapters-ConnectorSource.html +++ b/docs/api/module-LocusZoom_Adapters-ConnectorSource.html @@ -274,7 +274,7 @@

                                                                                          Home

                                                                                          Modules

                                                                                          • diff --git a/docs/api/module-LocusZoom_Adapters-CredibleSetLZ.html b/docs/api/module-LocusZoom_Adapters-CredibleSetLZ.html index 0577af2c..398e5f5c 100644 --- a/docs/api/module-LocusZoom_Adapters-CredibleSetLZ.html +++ b/docs/api/module-LocusZoom_Adapters-CredibleSetLZ.html @@ -318,7 +318,7 @@

                                                                                            Home

                                                                                            Modules

                                                                                            • diff --git a/docs/api/module-LocusZoom_Adapters-GeneConstraintLZ.html b/docs/api/module-LocusZoom_Adapters-GeneConstraintLZ.html index 50f3a499..6680d9b6 100644 --- a/docs/api/module-LocusZoom_Adapters-GeneConstraintLZ.html +++ b/docs/api/module-LocusZoom_Adapters-GeneConstraintLZ.html @@ -571,7 +571,7 @@

                                                                                              Home

                                                                                              Modules

                                                                                              • diff --git a/docs/api/module-LocusZoom_Adapters-GeneLZ.html b/docs/api/module-LocusZoom_Adapters-GeneLZ.html index 812527e1..482f4864 100644 --- a/docs/api/module-LocusZoom_Adapters-GeneLZ.html +++ b/docs/api/module-LocusZoom_Adapters-GeneLZ.html @@ -668,7 +668,7 @@

                                                                                                Home

                                                                                                Modules

                                                                                                • diff --git a/docs/api/module-LocusZoom_Adapters-GwasCatalogLZ.html b/docs/api/module-LocusZoom_Adapters-GwasCatalogLZ.html index 91e2367a..f8e6ff2d 100644 --- a/docs/api/module-LocusZoom_Adapters-GwasCatalogLZ.html +++ b/docs/api/module-LocusZoom_Adapters-GwasCatalogLZ.html @@ -519,7 +519,7 @@

                                                                                                  Home

                                                                                                  Modules

                                                                                                  • diff --git a/docs/api/module-LocusZoom_Adapters-IntervalLZ.html b/docs/api/module-LocusZoom_Adapters-IntervalLZ.html index 077120f1..a8673752 100644 --- a/docs/api/module-LocusZoom_Adapters-IntervalLZ.html +++ b/docs/api/module-LocusZoom_Adapters-IntervalLZ.html @@ -220,7 +220,7 @@

                                                                                                    Home

                                                                                                    Modules

                                                                                                    • diff --git a/docs/api/module-LocusZoom_Adapters-LDServer.html b/docs/api/module-LocusZoom_Adapters-LDServer.html index 3bbbb719..0487f8e3 100644 --- a/docs/api/module-LocusZoom_Adapters-LDServer.html +++ b/docs/api/module-LocusZoom_Adapters-LDServer.html @@ -1179,7 +1179,7 @@

                                                                                                      Home

                                                                                                      Modules

                                                                                                      • diff --git a/docs/api/module-LocusZoom_Adapters-PheWASLZ.html b/docs/api/module-LocusZoom_Adapters-PheWASLZ.html index b9da95fe..762c3b24 100644 --- a/docs/api/module-LocusZoom_Adapters-PheWASLZ.html +++ b/docs/api/module-LocusZoom_Adapters-PheWASLZ.html @@ -291,7 +291,7 @@

                                                                                                        Home

                                                                                                        Modules

                                                                                                        • diff --git a/docs/api/module-LocusZoom_Adapters-RecombLZ.html b/docs/api/module-LocusZoom_Adapters-RecombLZ.html index 9c9791ad..1f29c68b 100644 --- a/docs/api/module-LocusZoom_Adapters-RecombLZ.html +++ b/docs/api/module-LocusZoom_Adapters-RecombLZ.html @@ -424,7 +424,7 @@

                                                                                                          Home

                                                                                                          Modules

                                                                                                          • diff --git a/docs/api/module-LocusZoom_Adapters-StaticSource.html b/docs/api/module-LocusZoom_Adapters-StaticSource.html index e79a886e..0b2a9386 100644 --- a/docs/api/module-LocusZoom_Adapters-StaticSource.html +++ b/docs/api/module-LocusZoom_Adapters-StaticSource.html @@ -224,7 +224,7 @@

                                                                                                            Home

                                                                                                            Modules

                                                                                                            • diff --git a/docs/api/module-LocusZoom_Adapters-TabixUrlSource.html b/docs/api/module-LocusZoom_Adapters-TabixUrlSource.html index df30a8f4..4fc2a8dc 100644 --- a/docs/api/module-LocusZoom_Adapters-TabixUrlSource.html +++ b/docs/api/module-LocusZoom_Adapters-TabixUrlSource.html @@ -353,7 +353,7 @@

                                                                                                              Home

                                                                                                              Modules

                                                                                                              • diff --git a/docs/api/module-LocusZoom_Adapters.html b/docs/api/module-LocusZoom_Adapters.html index a4f1df55..75e3f6d0 100644 --- a/docs/api/module-LocusZoom_Adapters.html +++ b/docs/api/module-LocusZoom_Adapters.html @@ -365,7 +365,7 @@

                                                                                                                Home

                                                                                                                Modules

                                                                                                                • diff --git a/docs/api/module-LocusZoom_DataLayers-BaseDataLayer.html b/docs/api/module-LocusZoom_DataLayers-BaseDataLayer.html index 07e16d32..cf404277 100644 --- a/docs/api/module-LocusZoom_DataLayers-BaseDataLayer.html +++ b/docs/api/module-LocusZoom_DataLayers-BaseDataLayer.html @@ -4071,7 +4071,7 @@

                                                                                                                  Home

                                                                                                                  Modules

                                                                                                                  • diff --git a/docs/api/module-LocusZoom_DataLayers-annotation_track.html b/docs/api/module-LocusZoom_DataLayers-annotation_track.html index 9966e003..3bab3354 100644 --- a/docs/api/module-LocusZoom_DataLayers-annotation_track.html +++ b/docs/api/module-LocusZoom_DataLayers-annotation_track.html @@ -397,7 +397,7 @@

                                                                                                                    Home

                                                                                                                    Modules

                                                                                                                    • diff --git a/docs/api/module-LocusZoom_DataLayers-arcs.html b/docs/api/module-LocusZoom_DataLayers-arcs.html index 0a18e721..0d852550 100644 --- a/docs/api/module-LocusZoom_DataLayers-arcs.html +++ b/docs/api/module-LocusZoom_DataLayers-arcs.html @@ -628,7 +628,7 @@

                                                                                                                      Home

                                                                                                                      Modules

                                                                                                                      • diff --git a/docs/api/module-LocusZoom_DataLayers-category_forest.html b/docs/api/module-LocusZoom_DataLayers-category_forest.html index bd1d5bbf..5a827cdd 100644 --- a/docs/api/module-LocusZoom_DataLayers-category_forest.html +++ b/docs/api/module-LocusZoom_DataLayers-category_forest.html @@ -173,7 +173,7 @@

                                                                                                                        Home

                                                                                                                        Modules

                                                                                                                        • diff --git a/docs/api/module-LocusZoom_DataLayers-category_scatter.html b/docs/api/module-LocusZoom_DataLayers-category_scatter.html index 0fee56a0..56c7606f 100644 --- a/docs/api/module-LocusZoom_DataLayers-category_scatter.html +++ b/docs/api/module-LocusZoom_DataLayers-category_scatter.html @@ -481,7 +481,7 @@

                                                                                                                          Home

                                                                                                                          Modules

                                                                                                                          • diff --git a/docs/api/module-LocusZoom_DataLayers-forest.html b/docs/api/module-LocusZoom_DataLayers-forest.html index 8ccd9413..c3e70cd0 100644 --- a/docs/api/module-LocusZoom_DataLayers-forest.html +++ b/docs/api/module-LocusZoom_DataLayers-forest.html @@ -604,7 +604,7 @@

                                                                                                                            Home

                                                                                                                            Modules

                                                                                                                            • diff --git a/docs/api/module-LocusZoom_DataLayers-genes.html b/docs/api/module-LocusZoom_DataLayers-genes.html index daf2c13b..35a2d5b4 100644 --- a/docs/api/module-LocusZoom_DataLayers-genes.html +++ b/docs/api/module-LocusZoom_DataLayers-genes.html @@ -1230,7 +1230,7 @@

                                                                                                                              Home

                                                                                                                              Modules

                                                                                                                              • diff --git a/docs/api/module-LocusZoom_DataLayers-highlight_regions.html b/docs/api/module-LocusZoom_DataLayers-highlight_regions.html index 48d77a7c..6b35ce91 100644 --- a/docs/api/module-LocusZoom_DataLayers-highlight_regions.html +++ b/docs/api/module-LocusZoom_DataLayers-highlight_regions.html @@ -548,7 +548,7 @@

                                                                                                                                Home

                                                                                                                                Modules

                                                                                                                                • diff --git a/docs/api/module-LocusZoom_DataLayers-intervals.html b/docs/api/module-LocusZoom_DataLayers-intervals.html index 4b4c1783..f1924a70 100644 --- a/docs/api/module-LocusZoom_DataLayers-intervals.html +++ b/docs/api/module-LocusZoom_DataLayers-intervals.html @@ -970,7 +970,7 @@

                                                                                                                                  Home

                                                                                                                                  Modules

                                                                                                                                  • diff --git a/docs/api/module-LocusZoom_DataLayers-intervals_enrichment.html b/docs/api/module-LocusZoom_DataLayers-intervals_enrichment.html index 9f8edb76..b81e35b8 100644 --- a/docs/api/module-LocusZoom_DataLayers-intervals_enrichment.html +++ b/docs/api/module-LocusZoom_DataLayers-intervals_enrichment.html @@ -581,7 +581,7 @@

                                                                                                                                    Home

                                                                                                                                    Modules

                                                                                                                                    • diff --git a/docs/api/module-LocusZoom_DataLayers-orthogonal_line.html b/docs/api/module-LocusZoom_DataLayers-orthogonal_line.html index 672effa2..b14b7dd5 100644 --- a/docs/api/module-LocusZoom_DataLayers-orthogonal_line.html +++ b/docs/api/module-LocusZoom_DataLayers-orthogonal_line.html @@ -739,7 +739,7 @@

                                                                                                                                      Home

                                                                                                                                      Modules

                                                                                                                                      • diff --git a/docs/api/module-LocusZoom_DataLayers-scatter.html b/docs/api/module-LocusZoom_DataLayers-scatter.html index 11b72c3b..c31f4665 100644 --- a/docs/api/module-LocusZoom_DataLayers-scatter.html +++ b/docs/api/module-LocusZoom_DataLayers-scatter.html @@ -1224,7 +1224,7 @@

                                                                                                                                        Home

                                                                                                                                        Modules

                                                                                                                                        • diff --git a/docs/api/module-LocusZoom_DataLayers.html b/docs/api/module-LocusZoom_DataLayers.html index be9dc163..1bbe5e84 100644 --- a/docs/api/module-LocusZoom_DataLayers.html +++ b/docs/api/module-LocusZoom_DataLayers.html @@ -1169,7 +1169,7 @@

                                                                                                                                          Home

                                                                                                                                          Modules

                                                                                                                                          • diff --git a/docs/api/module-LocusZoom_Layouts.html b/docs/api/module-LocusZoom_Layouts.html index d6c3cb1f..325b030c 100644 --- a/docs/api/module-LocusZoom_Layouts.html +++ b/docs/api/module-LocusZoom_Layouts.html @@ -200,7 +200,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -273,7 +273,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -583,7 +583,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -655,7 +655,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -727,7 +727,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1187,7 +1187,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1259,7 +1259,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1331,7 +1331,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1403,7 +1403,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1476,7 +1476,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1550,7 +1550,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1622,7 +1622,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -1694,7 +1694,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2326,7 +2326,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2350,7 +2350,7 @@

                                                                                                                                            (inner, constan
                                                                                                                                            -

                                                                                                                                            A pael that displays PheWAS scatter plots and automatically generates a color scheme

                                                                                                                                            +

                                                                                                                                            A panel that displays PheWAS scatter plots and automatically generates a color scheme

                                                                                                                                            @@ -2398,7 +2398,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2470,7 +2470,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2614,7 +2614,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2758,7 +2758,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2831,7 +2831,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -2982,7 +2982,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -3054,7 +3054,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -3126,7 +3126,7 @@
                                                                                                                                            Type:
                                                                                                                                            Source:
                                                                                                                                            @@ -3166,7 +3166,7 @@

                                                                                                                                            Home

                                                                                                                                            Modules

                                                                                                                                            • diff --git a/docs/api/module-LocusZoom_MatchFunctions.html b/docs/api/module-LocusZoom_MatchFunctions.html index 5c88231a..67fbd21b 100644 --- a/docs/api/module-LocusZoom_MatchFunctions.html +++ b/docs/api/module-LocusZoom_MatchFunctions.html @@ -1538,7 +1538,7 @@

                                                                                                                                              Home

                                                                                                                                              Modules

                                                                                                                                              • diff --git a/docs/api/module-LocusZoom_ScaleFunctions.html b/docs/api/module-LocusZoom_ScaleFunctions.html index c21eb5b7..1ab656db 100644 --- a/docs/api/module-LocusZoom_ScaleFunctions.html +++ b/docs/api/module-LocusZoom_ScaleFunctions.html @@ -1692,7 +1692,7 @@

                                                                                                                                                Home

                                                                                                                                                Modules

                                                                                                                                                • diff --git a/docs/api/module-LocusZoom_TransformationFunctions.html b/docs/api/module-LocusZoom_TransformationFunctions.html index 07e67a9d..6bc4a96a 100644 --- a/docs/api/module-LocusZoom_TransformationFunctions.html +++ b/docs/api/module-LocusZoom_TransformationFunctions.html @@ -1263,7 +1263,7 @@

                                                                                                                                                  Home

                                                                                                                                                  Modules

                                                                                                                                                  • diff --git a/docs/api/module-LocusZoom_Widgets-BaseWidget.html b/docs/api/module-LocusZoom_Widgets-BaseWidget.html index 06b5b00c..6c1b59e4 100644 --- a/docs/api/module-LocusZoom_Widgets-BaseWidget.html +++ b/docs/api/module-LocusZoom_Widgets-BaseWidget.html @@ -1660,7 +1660,7 @@

                                                                                                                                                    Home

                                                                                                                                                    Modules

                                                                                                                                                    • diff --git a/docs/api/module-LocusZoom_Widgets-_Button.html b/docs/api/module-LocusZoom_Widgets-_Button.html index 2d91c278..8cbc308f 100644 --- a/docs/api/module-LocusZoom_Widgets-_Button.html +++ b/docs/api/module-LocusZoom_Widgets-_Button.html @@ -3467,7 +3467,7 @@

                                                                                                                                                      Home

                                                                                                                                                      Modules

                                                                                                                                                      • diff --git a/docs/api/module-LocusZoom_Widgets-display_options.html b/docs/api/module-LocusZoom_Widgets-display_options.html index bc813ef8..1e2ec999 100644 --- a/docs/api/module-LocusZoom_Widgets-display_options.html +++ b/docs/api/module-LocusZoom_Widgets-display_options.html @@ -473,7 +473,7 @@

                                                                                                                                                        Home

                                                                                                                                                        Modules

                                                                                                                                                        • diff --git a/docs/api/module-LocusZoom_Widgets-download_png.html b/docs/api/module-LocusZoom_Widgets-download_png.html index ee3b01b3..8d8f947a 100644 --- a/docs/api/module-LocusZoom_Widgets-download_png.html +++ b/docs/api/module-LocusZoom_Widgets-download_png.html @@ -376,7 +376,7 @@

                                                                                                                                                          Home

                                                                                                                                                          Modules

                                                                                                                                                          • diff --git a/docs/api/module-LocusZoom_Widgets-download_svg.html b/docs/api/module-LocusZoom_Widgets-download_svg.html index 2ece976d..ed62c8f3 100644 --- a/docs/api/module-LocusZoom_Widgets-download_svg.html +++ b/docs/api/module-LocusZoom_Widgets-download_svg.html @@ -465,7 +465,7 @@

                                                                                                                                                            Home

                                                                                                                                                            Modules

                                                                                                                                                            • diff --git a/docs/api/module-LocusZoom_Widgets-filter_field.html b/docs/api/module-LocusZoom_Widgets-filter_field.html index 1c9ed4dd..75c08653 100644 --- a/docs/api/module-LocusZoom_Widgets-filter_field.html +++ b/docs/api/module-LocusZoom_Widgets-filter_field.html @@ -674,7 +674,7 @@

                                                                                                                                                              Home

                                                                                                                                                              Modules

                                                                                                                                                              • diff --git a/docs/api/module-LocusZoom_Widgets-menu.html b/docs/api/module-LocusZoom_Widgets-menu.html index b8767986..a3f1b6ad 100644 --- a/docs/api/module-LocusZoom_Widgets-menu.html +++ b/docs/api/module-LocusZoom_Widgets-menu.html @@ -259,7 +259,7 @@

                                                                                                                                                                Home

                                                                                                                                                                Modules

                                                                                                                                                                • diff --git a/docs/api/module-LocusZoom_Widgets-move_panel_down.html b/docs/api/module-LocusZoom_Widgets-move_panel_down.html index 7fa36314..f4b2fa6c 100644 --- a/docs/api/module-LocusZoom_Widgets-move_panel_down.html +++ b/docs/api/module-LocusZoom_Widgets-move_panel_down.html @@ -170,7 +170,7 @@

                                                                                                                                                                  Home

                                                                                                                                                                  Modules

                                                                                                                                                                  • diff --git a/docs/api/module-LocusZoom_Widgets-move_panel_up.html b/docs/api/module-LocusZoom_Widgets-move_panel_up.html index 0bd955e0..d2d91c35 100644 --- a/docs/api/module-LocusZoom_Widgets-move_panel_up.html +++ b/docs/api/module-LocusZoom_Widgets-move_panel_up.html @@ -170,7 +170,7 @@

                                                                                                                                                                    Home

                                                                                                                                                                    Modules

                                                                                                                                                                    • diff --git a/docs/api/module-LocusZoom_Widgets-region_scale.html b/docs/api/module-LocusZoom_Widgets-region_scale.html index 900dfc5e..c9264f29 100644 --- a/docs/api/module-LocusZoom_Widgets-region_scale.html +++ b/docs/api/module-LocusZoom_Widgets-region_scale.html @@ -173,7 +173,7 @@

                                                                                                                                                                      Home

                                                                                                                                                                      Modules

                                                                                                                                                                      • diff --git a/docs/api/module-LocusZoom_Widgets-remove_panel.html b/docs/api/module-LocusZoom_Widgets-remove_panel.html index a804cfce..c10a32eb 100644 --- a/docs/api/module-LocusZoom_Widgets-remove_panel.html +++ b/docs/api/module-LocusZoom_Widgets-remove_panel.html @@ -239,7 +239,7 @@

                                                                                                                                                                        Home

                                                                                                                                                                        Modules

                                                                                                                                                                        • diff --git a/docs/api/module-LocusZoom_Widgets-resize_to_data.html b/docs/api/module-LocusZoom_Widgets-resize_to_data.html index 55f9cfdb..78287773 100644 --- a/docs/api/module-LocusZoom_Widgets-resize_to_data.html +++ b/docs/api/module-LocusZoom_Widgets-resize_to_data.html @@ -268,7 +268,7 @@

                                                                                                                                                                          Home

                                                                                                                                                                          Modules

                                                                                                                                                                          • diff --git a/docs/api/module-LocusZoom_Widgets-set_state.html b/docs/api/module-LocusZoom_Widgets-set_state.html index dac2a253..1f9f17f6 100644 --- a/docs/api/module-LocusZoom_Widgets-set_state.html +++ b/docs/api/module-LocusZoom_Widgets-set_state.html @@ -422,7 +422,7 @@

                                                                                                                                                                            Home

                                                                                                                                                                            Modules

                                                                                                                                                                            • diff --git a/docs/api/module-LocusZoom_Widgets-shift_region.html b/docs/api/module-LocusZoom_Widgets-shift_region.html index 439fd8bd..7758b294 100644 --- a/docs/api/module-LocusZoom_Widgets-shift_region.html +++ b/docs/api/module-LocusZoom_Widgets-shift_region.html @@ -312,7 +312,7 @@

                                                                                                                                                                              Home

                                                                                                                                                                              Modules

                                                                                                                                                                              • diff --git a/docs/api/module-LocusZoom_Widgets-title.html b/docs/api/module-LocusZoom_Widgets-title.html index c81cf1a9..01a6a9b0 100644 --- a/docs/api/module-LocusZoom_Widgets-title.html +++ b/docs/api/module-LocusZoom_Widgets-title.html @@ -261,7 +261,7 @@

                                                                                                                                                                                Home

                                                                                                                                                                                Modules

                                                                                                                                                                                • diff --git a/docs/api/module-LocusZoom_Widgets-toggle_legend.html b/docs/api/module-LocusZoom_Widgets-toggle_legend.html index 65bde958..b496bcfd 100644 --- a/docs/api/module-LocusZoom_Widgets-toggle_legend.html +++ b/docs/api/module-LocusZoom_Widgets-toggle_legend.html @@ -169,7 +169,7 @@

                                                                                                                                                                                  Home

                                                                                                                                                                                  Modules

                                                                                                                                                                                  • diff --git a/docs/api/module-LocusZoom_Widgets-toggle_split_tracks.html b/docs/api/module-LocusZoom_Widgets-toggle_split_tracks.html index 4271becf..578ae799 100644 --- a/docs/api/module-LocusZoom_Widgets-toggle_split_tracks.html +++ b/docs/api/module-LocusZoom_Widgets-toggle_split_tracks.html @@ -221,7 +221,7 @@

                                                                                                                                                                                    Home

                                                                                                                                                                                    Modules

                                                                                                                                                                                    • diff --git a/docs/api/module-LocusZoom_Widgets-zoom_region.html b/docs/api/module-LocusZoom_Widgets-zoom_region.html index 09483514..3fb14c1b 100644 --- a/docs/api/module-LocusZoom_Widgets-zoom_region.html +++ b/docs/api/module-LocusZoom_Widgets-zoom_region.html @@ -312,7 +312,7 @@

                                                                                                                                                                                      Home

                                                                                                                                                                                      Modules

                                                                                                                                                                                      • diff --git a/docs/api/module-LocusZoom_Widgets.html b/docs/api/module-LocusZoom_Widgets.html index 6f15fd54..e67f8452 100644 --- a/docs/api/module-LocusZoom_Widgets.html +++ b/docs/api/module-LocusZoom_Widgets.html @@ -1246,7 +1246,7 @@

                                                                                                                                                                                        Home

                                                                                                                                                                                        Modules

                                                                                                                                                                                        • diff --git a/docs/api/module-components_legend-Legend.html b/docs/api/module-components_legend-Legend.html index 367bc963..d3d94cf6 100644 --- a/docs/api/module-components_legend-Legend.html +++ b/docs/api/module-components_legend-Legend.html @@ -1154,7 +1154,7 @@

                                                                                                                                                                                          Home

                                                                                                                                                                                          Modules

                                                                                                                                                                                          • diff --git a/docs/api/module-ext_lz-credible-sets.html b/docs/api/module-ext_lz-credible-sets.html index 243d320d..e0c69683 100644 --- a/docs/api/module-ext_lz-credible-sets.html +++ b/docs/api/module-ext_lz-credible-sets.html @@ -182,7 +182,7 @@

                                                                                                                                                                                            Home

                                                                                                                                                                                            Modules

                                                                                                                                                                                            • diff --git a/docs/api/module-ext_lz-dynamic-urls.html b/docs/api/module-ext_lz-dynamic-urls.html index 2572538f..b7304c25 100644 --- a/docs/api/module-ext_lz-dynamic-urls.html +++ b/docs/api/module-ext_lz-dynamic-urls.html @@ -883,7 +883,7 @@

                                                                                                                                                                                              Home

                                                                                                                                                                                              Modules

                                                                                                                                                                                              • diff --git a/docs/api/module-ext_lz-forest-track.html b/docs/api/module-ext_lz-forest-track.html index 565e6e5f..ba9a732f 100644 --- a/docs/api/module-ext_lz-forest-track.html +++ b/docs/api/module-ext_lz-forest-track.html @@ -176,7 +176,7 @@

                                                                                                                                                                                                Home

                                                                                                                                                                                                Modules

                                                                                                                                                                                                • diff --git a/docs/api/module-ext_lz-intervals-enrichment.html b/docs/api/module-ext_lz-intervals-enrichment.html index c552cf3c..cf47e9a0 100644 --- a/docs/api/module-ext_lz-intervals-enrichment.html +++ b/docs/api/module-ext_lz-intervals-enrichment.html @@ -179,7 +179,7 @@

                                                                                                                                                                                                  Home

                                                                                                                                                                                                  Modules

                                                                                                                                                                                                  • diff --git a/docs/api/module-ext_lz-intervals-track.html b/docs/api/module-ext_lz-intervals-track.html index 83363466..e8008e17 100644 --- a/docs/api/module-ext_lz-intervals-track.html +++ b/docs/api/module-ext_lz-intervals-track.html @@ -182,7 +182,7 @@

                                                                                                                                                                                                    Home

                                                                                                                                                                                                    Modules

                                                                                                                                                                                                    • diff --git a/docs/api/module-ext_lz-tabix-source.html b/docs/api/module-ext_lz-tabix-source.html index 202fe158..212c8fca 100644 --- a/docs/api/module-ext_lz-tabix-source.html +++ b/docs/api/module-ext_lz-tabix-source.html @@ -186,7 +186,7 @@

                                                                                                                                                                                                      Home

                                                                                                                                                                                                      Modules

                                                                                                                                                                                                      • diff --git a/docs/api/module-ext_lz-widget-addons-covariates_model.html b/docs/api/module-ext_lz-widget-addons-covariates_model.html index 208dc84b..87a031ea 100644 --- a/docs/api/module-ext_lz-widget-addons-covariates_model.html +++ b/docs/api/module-ext_lz-widget-addons-covariates_model.html @@ -293,7 +293,7 @@

                                                                                                                                                                                                        Home

                                                                                                                                                                                                        Modules

                                                                                                                                                                                                        • diff --git a/docs/api/module-ext_lz-widget-addons-data_layers.html b/docs/api/module-ext_lz-widget-addons-data_layers.html index e628afed..ee2d84e9 100644 --- a/docs/api/module-ext_lz-widget-addons-data_layers.html +++ b/docs/api/module-ext_lz-widget-addons-data_layers.html @@ -169,7 +169,7 @@

                                                                                                                                                                                                          Home

                                                                                                                                                                                                          Modules

                                                                                                                                                                                                          • diff --git a/docs/api/module-ext_lz-widget-addons.html b/docs/api/module-ext_lz-widget-addons.html index d97f7e0a..133e0110 100644 --- a/docs/api/module-ext_lz-widget-addons.html +++ b/docs/api/module-ext_lz-widget-addons.html @@ -188,7 +188,7 @@

                                                                                                                                                                                                            Home

                                                                                                                                                                                                            Modules

                                                                                                                                                                                                            • diff --git a/docs/api/module-registry_base-RegistryBase.html b/docs/api/module-registry_base-RegistryBase.html index fb6ea4e5..d1cdb969 100644 --- a/docs/api/module-registry_base-RegistryBase.html +++ b/docs/api/module-registry_base-RegistryBase.html @@ -993,7 +993,7 @@

                                                                                                                                                                                                              Home

                                                                                                                                                                                                              Modules

                                                                                                                                                                                                              • diff --git a/docs/api/registry_adapters.js.html b/docs/api/registry_adapters.js.html index 22db4dd5..1b827204 100644 --- a/docs/api/registry_adapters.js.html +++ b/docs/api/registry_adapters.js.html @@ -86,7 +86,7 @@

                                                                                                                                                                                                                Home

                                                                                                                                                                                                                Modules

                                                                                                                                                                                                                • diff --git a/docs/api/registry_base.js.html b/docs/api/registry_base.js.html index 98559cf4..92da981f 100644 --- a/docs/api/registry_base.js.html +++ b/docs/api/registry_base.js.html @@ -167,7 +167,7 @@

                                                                                                                                                                                                                  Home

                                                                                                                                                                                                                  Modules

                                                                                                                                                                                                                  • diff --git a/docs/api/registry_data_layers.js.html b/docs/api/registry_data_layers.js.html index 98b096f0..6c081a5a 100644 --- a/docs/api/registry_data_layers.js.html +++ b/docs/api/registry_data_layers.js.html @@ -61,7 +61,7 @@

                                                                                                                                                                                                                    Home

                                                                                                                                                                                                                    Modules

                                                                                                                                                                                                                    • diff --git a/docs/api/registry_layouts.js.html b/docs/api/registry_layouts.js.html index 0f246e6b..04f92fde 100644 --- a/docs/api/registry_layouts.js.html +++ b/docs/api/registry_layouts.js.html @@ -182,7 +182,7 @@

                                                                                                                                                                                                                      Home

                                                                                                                                                                                                                      Modules

                                                                                                                                                                                                                      • diff --git a/docs/api/registry_matchers.js.html b/docs/api/registry_matchers.js.html index c0b46b65..86252aad 100644 --- a/docs/api/registry_matchers.js.html +++ b/docs/api/registry_matchers.js.html @@ -160,7 +160,7 @@

                                                                                                                                                                                                                        Home

                                                                                                                                                                                                                        Modules

                                                                                                                                                                                                                        • diff --git a/docs/api/registry_transforms.js.html b/docs/api/registry_transforms.js.html index 4131a7a9..df6d9fca 100644 --- a/docs/api/registry_transforms.js.html +++ b/docs/api/registry_transforms.js.html @@ -113,7 +113,7 @@

                                                                                                                                                                                                                          Home

                                                                                                                                                                                                                          Modules

                                                                                                                                                                                                                          • diff --git a/docs/api/registry_widgets.js.html b/docs/api/registry_widgets.js.html index b0c4ec9e..f6ab585f 100644 --- a/docs/api/registry_widgets.js.html +++ b/docs/api/registry_widgets.js.html @@ -59,7 +59,7 @@

                                                                                                                                                                                                                            Home

                                                                                                                                                                                                                            Modules

                                                                                                                                                                                                                            • diff --git a/esm/version.js b/esm/version.js index 245c3834..e105cc40 100644 --- a/esm/version.js +++ b/esm/version.js @@ -1 +1 @@ -export default '0.13.3'; +export default '0.13.4'; diff --git a/package-lock.json b/package-lock.json index df5a0be6..e6c5c40c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.13.3", + "version": "0.13.4", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 064b89b2..72a9c4bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.13.3", + "version": "0.13.4", "main": "dist/locuszoom.app.min.js", "module": "esm/index.js", "sideEffects": true, @@ -12,7 +12,7 @@ "gwas", "phewas" ], - "homepage": "http://locuszoom.org", + "homepage": "https://github.com/statgen/locuszoom", "license": "MIT", "author": "University of Michigan Center for Statistical Genetics", "contributors": [