diff --git a/.eslintrc.js b/.eslintrc.js index 2bc22599..37ac2752 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -45,7 +45,7 @@ module.exports = { 'node': true, }, 'parserOptions': { - 'ecmaVersion': 2016, + 'ecmaVersion': 2020, 'sourceType': 'module', }, }; diff --git a/README.md b/README.md index 126d5c98..c5fceb37 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,27 @@ LocusZoom is a Javascript/d3 embeddable plugin for interactively visualizing statistical genetic data from customizable sources. + +For more information, see our paper: + +*Boughton, A. P. et al. LocusZoom.js: interactive and embeddable visualization of genetic association study results. Bioinformatics (2021) [doi:10.1093/bioinformatics/btab186](https://doi.org/10.1093/bioinformatics/btab186).* + +**This is a low level library aimed at developers who want to customize their own data sharing/visualization tools. If you are a genetics researcher who just wants to make a fast visualization of your research results, try our user-friendly plot-your-own data services built on LocusZoom.js: [my.locuszoom.org](https://my.locuszoom.org/) and [LocalZoom](https://statgen.github.io/localzoom/)**. + + ![Build Status](https://github.com/statgen/locuszoom/workflows/Unit%20tests/badge.svg?branch=develop) 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). -![LocusZoom.js Standard Association Plot](http://statgen.github.io/locuszoom/wiki_images/locuszoom_standard_association_plot_0.5.2.png) +![LocusZoom.js Standard Association Plot](examples/locuszoom_standard_association_example.png) -## Making a LocusZoom Plot +## Making a LocusZoom Plot: Quickstart tutorial ### 1. Include Necessary JavaScript and CSS -The page you build that embeds the LocusZoom plugin must include the following resources, found in the `dist` directory: +The page you build that embeds the LocusZoom plugin must include the following resources, found in the `dist` directory (or preferably loaded via CDN): * `d3.js` [D3.js](https://d3js.org/) v5.16.0 is used to draw graphics in LocusZoom plots. It may be loaded [via a CDN](https://cdn.jsdelivr.net/npm/d3@^5.16.0). It must be present before LocusZoom is loaded. @@ -42,7 +50,7 @@ Here's an example of defining a data sources object for a remote API: ```javascript var data_sources = new LocusZoom.DataSources(); -data_sources.add("assoc", ["AssociationLZ", { url: "http://server.com/api/", params: {source: 1} }]); +data_sources.add("assoc", ["AssociationLZ", { url: "http://server.com/api/", source: 1 }]); ``` The above example adds an "AssociationLZ" data source (a predefined data source designed to make requests for association data) with a defined URL. The namespace for this data source is "assoc". @@ -73,7 +81,6 @@ var layout = { { id: "association", type: "scatter", - fields: ["assoc:position", "assoc:pvalue"], x_axis: { field: "assoc:position" }, y_axis: { field: "assoc:pvalue" } } @@ -96,33 +103,32 @@ A basic example may then look like this: ```html - - + + -
+
@@ -132,11 +138,11 @@ A basic example may then look like this: #### Use a Predefined Layout -The core LocusZoom library comes equipped with several predefined layouts, organized by type ("plot", "panel", "data_layer", and "toolbar"). You can see what layouts are predefined by reading the contents of `assets/js/app/Layouts.js` or in the browser by entering `LocusZoom.Layouts.list()` (or to list one specific type: `LocusZoom.Layouts.list(type)`). +The core LocusZoom library comes equipped with several predefined layouts, organized by type ("plot", "panel", "data_layer", and "toolbar"). You can see what layouts are predefined by reading the [documentation](https://statgen.github.io/locuszoom/docs/api/module-LocusZoom_Layouts.html) or introspecting in the browser by entering `LocusZoom.Layouts.list()` (or to list one specific type, like "data_layer": `LocusZoom.Layouts.list(type)`). Get any predefined layout by type and name using `LocusZoom.Layouts.get(type, name)`. -If your data matches the field names and formats of the [UMich PortalDev API](https://portaldev.sph.umich.edu/docs/api/v1/#overview-of-api-endpoints), these layouts will provide a quick way to get started. If your data obeys different format rules, customization may be necessary. +If your data matches the field names and formats of the [UMich PortalDev API](https://portaldev.sph.umich.edu/docs/api/v1/#overview-of-api-endpoints), these layouts will provide a quick way to get started. If your data obeys different format rules, customization may be necessary. (for example, some LocusZoom features assume the presence of a field called `log_pvalue`) See the [guide to working with layouts](https://statgen.github.io/locuszoom/docs/guides/rendering_layouts.html) for further details. @@ -150,7 +156,7 @@ const layout = { width: 1000, height: 500, panels: [ - LocusZoom.Layouts.get("panel", "gwas"), + LocusZoom.Layouts.get("panel", "association"), { id: "custom_panel", ...options @@ -166,24 +172,21 @@ const layout = { The `get()` function also accepts a partial layout to be merged with the predefined layout as a third argument, providing the ability to use predefined layouts as starting points for custom layouts with only minor differences. Example: ```javascript -const changes = { - label_font_size: 20, - transition: false -}; -LocusZoom.Layouts.get("data_layer", "genes", changes); +const overrides = { label_font_size: 20 }; +LocusZoom.Layouts.get("data_layer", "genes", overrides); ``` #### Predefining State by Building a State Object -**State** is a serializable JSON object that describes orientation to specific data from data sources, and specific interactions with the layout. This can include a specific query against various data sources or pre-selecting specific elements. Essentially, the state object is what tracks these types of user input under the hood in LocusZoom, and it can be predefined at initialization as a top-level parameter in the layout. For example: +**State** is JSON-serializable object containing information that can affect the entire plot (including all data retrieval requests). State can be set before or after the plot is initialized. For example, the following special-named fields will cause the plot to be loaded to a specific region of interest on first render: ```javascript const layout = LocusZoom.Layouts.get('plot', 'standard_association', { state: { chr: 6, start: 20379709, end: 20979709 } }) ``` -#### Predefining State With `data-region` +#### Alternate: setting the initial view via `data-region` -You can also describe the locus query aspect of the State (chromosome, start, and end position) using a `data-region` attribute of the containing element before populating it, like so: +You can also describe the locususing a `data-region` attribute of the containing element before populating it, like so: ```html
@@ -192,7 +195,6 @@ You can also describe the locus query aspect of the State (chromosome, start, an When `LocusZoom.populate()` is executed on the element defined above it will automatically parse any `data-region` parameter to convert those values into the initial state. ## Development Setup - ### Dependencies LocusZoom is an entirely client-side library designed to plug into arbitrary data sets, be they local files, APIs, or something else entirely. It has the following external dependencies: @@ -218,8 +220,8 @@ This build process will also write sourcemaps, to help with debugging code even * `npm run test` - Run unit tests (optional: `npm run test:coverage` to output a code coverage report) * `npm run dev` - Automatically rebuild the library whenever code changes (development mode) * `npm run build` - Run tests, and if they pass, build the library for release -* `npm run css` - Rebuild the CSS using SASS -* `npm run docs` - Build the library documentation +* `npm run css` - Rebuild the CSS using SASS (CSS rarely changes, so this doesn't get done automatically in dev mode) +* `npm run docs` - Build just the library documentation #### Automated Testing @@ -231,9 +233,9 @@ LocusZoom runs code quality checks via [ESLint](http://eslint.org/), the rules f ## Help and Support -Full documentation can be found here: [docs/](https://statgen.github.io/locuszoom/docs/) +Full API documentation and prose guides are available at: [https://statgen.github.io/locuszoom/docs/](https://statgen.github.io/locuszoom/docs/) -A LocusZoom discussion forum is available here: [groups.google.com/forum/#!forum/locuszoom](https://groups.google.com/forum/#!forum/locuszoom). +A LocusZoom discussion forum is available here: [https://groups.google.com/forum/#!forum/locuszoom](https://groups.google.com/forum/#!forum/locuszoom). For the most effective help, please specify that your question is about "LocusZoom.js". If you have questions or feedback please file an issue on the [LocusZoom.js GitHub repository](https://github.com/statgen/locuszoom/issues) or post at the discussion forum referenced above. diff --git a/assets/docs/data_retrieval.md b/assets/docs/data_retrieval.md index 863a73a6..ad61492d 100644 --- a/assets/docs/data_retrieval.md +++ b/assets/docs/data_retrieval.md @@ -14,7 +14,7 @@ Below is an example that defines how to retrieve the data for a "classic" LocusZ ```javascript const apiBase = 'https://portaldev.sph.umich.edu/api/v1/'; const data_sources = new LocusZoom.DataSources() - .add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', params: { source: 45, id_field: 'variant' }}]) + .add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', source: 45, id_field: 'variant' }]) .add('ld', ['LDServer', { url: 'https://portaldev.sph.umich.edu/ld/', source: '1000G', population: 'ALL', build: 'GRCh37' }]) .add('recomb', ['RecombLZ', { url: apiBase + 'annotation/recomb/results/', build: 'GRCh37' }]) .add('gene', ['GeneLZ', { url: apiBase + 'annotation/genes/', build: 'GRCh37' }]) @@ -27,15 +27,15 @@ Of course, defining datasets is only half of the process; see the [Getting Start In the example above, a new data source is added via a line of code such as the following: ```javascript -data_sources.add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', params: { source: 45, id_field: 'variant' }}]); +data_sources.add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', source: 45, id_field: 'variant' }]); ``` A lot is going on in this line! * `data_sources.add` defines a piece of information that *could* be used by the plot. (if no data layer asks for data from this source, then no API request will ever be made) * The first argument to the function is a *namespace name*. It is an arbitrary reference to this particular piece of data. For example, you might want to plot three association studies together in the same window, and they could be defined as `.add('mystudy', ...)`, `.add('somephenotype', ...)`, `.add('founditinthegwascatalog', ...)` - * In the [layouts guide](rendering_layouts.html), we will see how `data_layer.fields` uses these namespaces to identify what data to render. -* The second argument to the function is a list of values: the name of a [predefined adapter](../api/module-LocusZoom_Adapters.html) that defines how to retrieve this data, followed by an object of configuration options (like url and params) that control which data will be fetched. Each type of data has its own options; see the documentation for a guide to available choices. + * In the [layouts guide](rendering_layouts.html), we will see how **data layers** use these namespaces. +* The second argument to the function is a list of values: the name of a [predefined adapter](../api/module-LocusZoom_Adapters.html) that defines how to retrieve this data, followed by an object of configuration options (like url and source) that control which data will be fetched. Each type of data has its own options; see the documentation for a guide to available choices. * You are not limited to the types of data retrieval built into LocusZoom.js. See "creating your own adapter" for more information. ## The importance of genome build @@ -44,9 +44,9 @@ You may notice that in the example above, many of the datasets specify `build: ' We periodically update our API server. If you think new information is missing, please let us know. ## What should the data look like? -In theory, LocusZoom.js can display whatever data it is given: layouts allow any individual layout to specify what fields should be used for the x and y axes. +In theory, LocusZoom.js can display whatever data it is given: layouts allow any individual layer to specify what fields should be used for the x and y axes. -In practice, it is much more convenient to use pre-existing layouts that solve a common problem well out of the box: the set of options needed to control point size, shape, color, and labels is rather verbose, and highly custom behaviors entail a degree of complexity that is not always beginner friendly. For basic LocusZoom.js visualizations, our default layouts assume that you use the field names and format conventions defined in the [UM PortalDev API docs](https://portaldev.sph.umich.edu/docs/api/v1/). This is the quickest way to get started. +In practice, it is much more convenient to use pre-existing layouts that solve a common problem well out of the box: the set of options needed to control point size, shape, color, and labels is rather verbose, and highly custom behaviors entail a degree of complexity that is not always beginner friendly. For basic LocusZoom.js visualizations, our default layouts assume that you use the field names and format conventions defined in the [UM PortalDev API docs](https://portaldev.sph.umich.edu/docs/api/v1/). This is the quickest way to get started. Most layouts in the provided `LocusZoom.Layouts` registry will tell you what fields are expected (via the `_auto_fields` property), and most plots will log a console error message if the response is missing expected information. Most users will only need to implement their own way of retrieving GWAS summary statistics; the other annotations are standard datasets and can be freely used from our public API. For complex plots (like annotations of new data), see our [example gallery](https://statgen.github.io/locuszoom). @@ -83,6 +83,22 @@ Each data adapter in the chain is largely independent, and it is entirely normal If a single data layer needs to combine two kinds of data (eg association and LD), you will achieve the best results if the sources have some common assumptions about data format. Adapters are highly modular, but because they do not enforce a specific contract of field names or payload structure, you are responsible for ensuring that the resulting data works with the assumptions of your layout. +## Every layer has its own, private, view of the data +Each data layer in LocusZoom is intended to be independent of others. Thus, each layer must individually specify its own way to connect data together. + +Likewise, each layer defines a "local" way of identifying where to find the data it needs. For example, consider a layer layout as follows: + +```javascript +{ + namespace: {'assoc': 'mystudy'}, + id_field: 'assoc:variant' +} +``` + +The `namespace` is specified as a key-value pair of *local_name: global_data_source_name*. This instruction says: "whenever this layer asks for something from assoc, make a request to an item named mystudy". Every field in the layout refers to the local_name. This layer of indirection allows a layout to be used many times to plot different datasets, and only the namespace needs to be changed. + +Any changes made to the data within one layer should not affect copies of the same data in other places. This property makes it easier to display the same data in two different ways, without having to make a duplicate network request. + ## What if my data doesn't fit the expected format? The built-in adapters are designed to work with a specific set of known REST APIs and fetch data over the web, but we provide mechanisms to customize every aspect of the data retrieval process, including how to construct the query sent to the server and how to modify the fields returned. See the guidance on "custom adapters" below. @@ -93,37 +109,102 @@ In general, the more similar that your field names are to those used in premade If the only difference is field names, you can customize the layout to tell it where to find the required information. (see: [guide to layouts and rendering](rendering_layouts.html) for details) [Transformation functions](../api/module-LocusZoom_TransformationFunctions.html) (like `neglog10`) can then be used to ensure that custom data is formatted in a way suitable for rendering and plotting. +## Combining two kinds of data in one place +Sometimes, a single data layer will depend on information from two different sources (like an association plot colored by LD information). + +### Data operations (layout directive) +The act of combining two pieces of data is performed by *data operations*. In order to let the same piece of data be rendered in different ways, these instructions are placed within each data layer layout. *The decision on how to combine two pieces of information is specified at the point where the data is used*. + +A sample layout directive for data operations would be as follows: + +```javascript +{ + namespace: { 'assoc': 'mystudy', 'ld': 'some_ld' }, + data_operations: [ + { + type: 'fetch', + from: ['assoc', 'ld(assoc)'], + }, + { + type: 'left_match', + name: 'assoc_plus_ld', + requires: ['assoc', 'ld'], + // Tell the join function which field names to be used for the join. Each join function has its own possible parameters. + params: ['assoc:position', 'ld:position2'], + }, + ] +} +``` + +#### Dependencies +The first instruction in the example above specifies how to retrieve the data: `{type: 'fetch', from: ['assoc', 'ld(assoc)'}` + +A single "fetch" operation is used to specify all of the data retrieval. This specifies what information a data layer should retrieve. It refers to the "local" namespace name (like "assoc"), and tells locuszoom to make a request to the global datasource named "mystudy". + +Some adapters can not begin to define their request until they see the data from another adapter: eg LD information is retrieved relative to the most significant association variant in the region. This is a *dependency*, and one (or more) dependencies can be specified using the syntax `some_request(first_dependency, nth_dependency)`. LocusZoom will automatically reorder and parallelize requests based on the dependencies given. If several requests each have no dependencies, they will be performed in parallel. + +Each individual adapter will receive data it depends on as a function argument to `getData`. The string syntax reflects how the data is connected internally! In the example above, "ld" is only retrieved after a request to "assoc" is complete, and the LD adapter received the assoc data to help define the next request. + +> NOTE: Sometimes it is useful to extend an existing layout to fetch additional kinds of data. It can be annoying to extend a "list" field like fetch.from, so LocusZoom has some magic to help out: if an item is specified as a source of data for this layer (eg `namespace: {'assoc': 'assoc'}`), it will automatically be added to the `fetch.from` instruction. This means that **everything listed in `data_layer.namespace` will trigger a data retrieval request**. You only need to modify the contents of `fetch.from` if you want to specify that the new item depends on something else, eg "don't fetch LD until assoc data is ready: `ld(assoc)`". All of the built in LZ layouts are verbose and explicit, in an effort to reduce the amount of "magic" and make the examples easier to understand. + +#### Joins ("Data functions") +The second instruction in the example above is a *join*. It specifies how to compare multiple sets of data into one list of records ("one record per data point on the plot"). + +Any function defined in `LocusZoom.DataFunctions` can be referenced. Several builtin joins are provided (including `left_match`, `inner_match`, and `full_outer_match`). Any arbitrary join function can be added to the `LocusZoom.DataFunctions` registry, with the call signature `({plot_state, data_layer}}, [recordsetA, recordsetB...], ...params) => combined_results`. + +Data operations are synchronous; they are used for data formatting and cleanup. Use adapters for asynchronous operations like network requests. + +The plot will receive the last item in the dependency graph (taking into account both adapters and joins). If something looks strange, make sure that you have specified how to join all your data sources together. + +> TIP: Because data functions are given access to plot.state and the data layer instance that initiated the request, they are able to do surprisingly powerful things, like filtering the returned data in response to a global plot_state parameter or auto-defining a layout (`data_layer.layout`) in response to dynamic data (axis labels, color scheme, etc). This is a very advanced usage and has the potential for side effects; use sparingly! See the LocusZoom unit tests for a few examples of what is possible. + # Creating your own custom adapter -## Re-using code via subclasses +## Can I reuse existing code? +The built-in LocusZoom adapters can be used as-is in many cases, so long as the returned payload matches the expected format. You may need to write your own custom code (adapter subclass) in the following scenarios: + +1. If an expression must be evaluated in order to retrieve data (eg constructing URLs based on query parameters, or LD requests where the reference variant is auto-selected from the most significant hit in a GWAS) +2. If the actual headers, body, or request method must be customized in order to carry out the request. This happens when data is retrieved from a particular technology (REST vs GraphQL vs Tabix), or if the request must incorporate some form of authentication credentials. +3. If some of the fields in your custom API format need to be transformed or renamed in order to match expectations in LZ code. For example, the LD adapter may try to suggest an LD reference variant by looking for the GWAS variant with the largest `log_pvalue`. (over time, built-in LZ adapters trend towards being more strict about field names; it is easier to write reliable code when not having to deal with unpredictable data!) + +## Customizing data retrieval via subclasses Most custom sites will only need to change very small things to work with their data. For example, if your REST API uses the same payload format as the UM PortalDev API, but a different way of constructing queries, you can change just one function and define a new data adapter: ```javascript const AssociationLZ = LocusZoom.Adapters.get('AssociationLZ'); class CustomAssociation extends AssociationLZ { - getURL(state, chain, fields) { - // The inputs to the function can be used to influence what query is constructed. Eg, the current view region is stored in `plot.state`. - const {chr, start, end} = state; + _getURL(request_options) { + // Every adapter receives the info from plot.state, plus any additional request options calculated/added in the function `_buildRequestOptions` + // The inputs to the function can be used to influence what query is constructed. Eg, since the current view region is stored in `plot.state`: + const {chr, start, end} = request_options; // Fetch the region of interest from a hypothetical REST API that uses query parameters to define the region query, for a given study URL such as `data.example/gwas//?chr=_&start=_&end=_` - return `${this.url}/${this.params.study_id}/?chr=${encodeURIComponent(chr)}&start=${encodeURIComponent(start)}&end${encodeURIComponent(end)}` + return `${this._url}/${this.source}/?chr=${encodeURIComponent(chr)}&start=${encodeURIComponent(start)}&end${encodeURIComponent(end)}` + } + + _annotateRecords(records, options) { + // Imagine that your API returns a payload that mostly works, but a few fields are a little different than what is expected. + // Usually LocusZoom is pretty tolerant of changing field names- but because Association plots connect to so many extra annotations, certain magic features require a little extra attention to detail + records.forEach((item) => { + // LocusZoom connects assoc summstats to other datasets, by finding the most significant variant. To find that variant and ask for LD, it expects two special fields with very specific names, and sort of specific formats. If you already have these fields, great- if not, they can be manually added by custom code, even if no one will let you change the API server directly + item.log_pvalue = -Math.log10(item.pValue); // It's better if you send log_pvalue from the server directly, not calculate it on the front end (JS is subject to numerical underflow, and sending pValue to the browser may cause numerical underflow problems) + item.variant = `${item.chrom}:${item.pos}_${item.ref}/${item.alt}`; + }); + return records; } } // A custom adapter should be added to the registry before using it LocusZoom.Adapters.add('CustomAssociation', CustomAssociation); // From there, it can be used anywhere throughout LocusZoom, in the same way as any built-in adapter -data_sources.add('mystudy', ['CustomAssociation', {url: 'https://data.example/gwas', params: { study_id: 42 }}]); +data_sources.add('mystudy', ['CustomAssociation', {url: 'https://data.example/gwas', source: 42 }]); ``` -In the above example, an HTTP GET request will be sent to the server every time that new data is requested. If further control is required (like sending a POST request with custom body), you may need to override additional methods such as [fetchRequest](../api/module-LocusZoom_Adapters-BaseAdapter.html#fetchRequest). See below for more information, then consult the detailed developer documentation for details. +In the above example, an HTTP GET request will be sent to the server every time that new data is requested. If further control is required (like sending a POST request with custom body), you may need to override additional methods such as [fetchRequest](../api/module-LocusZoom_Adapters-BaseLZAdapter.html#_performRequest). See below for more information, then consult the detailed developer documentation for details. Common types of data retrieval that are most often customized: * GWAS summary statistics - * This fetches the data directly with minor cleanup. You can customize the built-in association adapter, or swap in another way of fetching the data (like tabix). -* User-provided linkage disequilibrium (LD) - * This contains special logic used to combine association data (from a previous request) with LD information. To ensure that the matching code works properly, we recommend matching the payload format of the public LDServer, but you can customize the `getURL` method to control where the data comes from. - * For performance reasons, connecting LD and association data together assumes that both datasets are sorted in order of increasing chromosome and position. -* PheWAS results + * This fetches the data directly with minor cleanup. You can customize the built-in association adapter, or swap in another way of fetching the data (like tabix). You may want to ensure that a field called `log_pvalue` is present, and possibly customize other fields as well. +* PheWAS results (not every server returns PheWAS results in the same format) ## What happens during a data request? The adapter performs many functions related to data retrieval: constructing the query, caching to avoid unnecessary network traffic, and parsing the data into a transformed representation suitable for use in rendering. @@ -131,55 +212,52 @@ The adapter performs many functions related to data retrieval: constructing the Methods are provided to override all or part of the process, called in roughly the order below: ```javascript -getData(state, fields, outnames, transformations) - getRequest(state, chain, fields) - getCacheKey(state, chain, fields) - fetchRequest(state, chain, fields) - getURL(state, chain, fields) - parseResponse(resp, chain, fields, outnames, transformations) - normalizeResponse(data) - annotateData(data, chain) - extractFields(data, fields, outnames, trans) - combineChainBody(data, chain, fields, outnames) +getData(plot_state, ...dependent_data) + _buildRequestOptions(plot_state, ...dependent_data) + _getCacheKey(request_options) + _performRequest(request_options) + _getURL(request_options) + // Parse JSON, convert columnar data to rows, etc + _normalizeResponse(raw_response, options) + cache.add(records) + // User-specified cleanup of the parsed response fields. Can be used for things like field renaming, record filtering, or adding new calculated fields on the fly + _annotateRecords(records, options) + // Usually not overridden: this method can be used to apply prefixes (assoc:id, catalog:id, etc) and to simplify down verbose responses to just a few `limit_fields` of interest + _postProcessResponse(records, options) ``` The parameters passed to getData are as follows: -* state - this is the current "state" of the plot. This contains information about the current region in view (`chr`, `start`, and `end`), which is often valuable in querying a remote data source for the data in a given region. -* fields - this is an array of field names that have been requested from this data source. Note that the "namespace:" part of the name has been removed in this array. Note: **most data adapters will return *only* the fields that are requested by a data layer**. Each data layer can request a different set of fields, and thus **different parts of the plot may have a different view of the same data.** -* outnames - this is an array with length equal to fields with the original requested field name. This value contains the data source namespace. The data output for each field should be given the name in this array. This is rarely used directly. -* transformations - this is an array with length equal to fields with the collection of value transformations functions specified by the user to be run on the returned field. This is rarely used directly. +* `plot_state`: Every adapter request contains a copy of `plot.state`, which stores global information (like view region chr/start/end) that can be used to customize the request. +* `...dependent_data`: If the adapter depends on prior requests, the parsed records from each prior request will be passed to this function (each function argument would be one dependent request, represented as an array of row-based record objects: `[{'assoc:variant': '1:23_A/C', 'assoc:log_pvalue': 75 }]`) + +This function will return row-format data representing the response for just that request. It will use a cached response if feasible. By default, LocusZoom will apply certain transformation to the returned response so that it is easier to use with a data layer (see adapter documentation for details). All fields in the original response will be returned as given. -### Step 1: Fetching data from a remote server -The first step of the process is to retrieve the data from an external location. `getRequest` is responsible for deciding whether the query can be satisfied by a previously cached request, and if not, sending the response to the server. At the conclusion of this step, we typically have a large unparsed string: eg REST APIs generally return JSON-formatted text, and tabix sources return lines of text for records in the region of interest. +### Step 1: Fetching data from a remote server and converting to records +The first step of the process is to retrieve the data from an external location. `_buildRequestOptions` can be used to store any parameters that customize the request, including information from `plot.state`. If the response is cached, the cache value will be returned; otherwise, a request will be initiated. Once the request is complete, the result will be parsed and cached for future use. + +At the conclusion of this step, we typically have an array of records, one object per row of data. The field names and contents are very close to what was returned by the API. Most custom data sources will focus on customizing two things: -* getURL (how to ask the external source for data) -* getCacheKey (decide whether the request can be satisfied by local data) +* `_getURL` (how to ask the external source for data) +* `_getCacheKey` (decide whether the request can be satisfied by local data) * By default this returns a string based on the region in view: `'${state.chr}_${state.start}_${state.end}'` * You may need to customize this if your source has other inputs required to uniquely define the query (like LD reference variant, or calculation parameters for credible set annotation). -### Step 2: Formatting and parsing the data -The `parseResponse` sequence handles the job of parsing the data. It can be used to convert many different API formats into a single standard form. There are four steps to the process: +### Step 2: Transforming data into a form usable by LocusZoom +In a prior step, the records were normalized, but kept in a form that is usually close to what the API returned. In this step, records are modified for use in the plot: -* `normalizeResponse` - Converts any data source response into a standard format. This can be used when you want to take advantage of existing data handling functionality of a particular adapter (like performing an interesting calculation), but your data comes from something like a tabix file that needs to be adjusted to match the expected format. +* `_normalizeResponse` - Converts any data source response into a standard format. This can be used when you want to take advantage of existing data handling functionality of a particular adapter (like performing an interesting calculation), but your data comes from something like a tabix file that needs to be adjusted to match the expected format. * Internally, most data layer rendering types assume that data is an array, with each datum element represented by an object: `[{a_field: 1, other_field: 1}]` * Some sources, such as the UM PortalDev API, represent the data in a column-oriented format instead. (`{a_field: [1], other_field: [1]}`) The default adapter will attempt to detect this and automatically transform those columns into the row-based one-record-per-datum format. -* `annotateData` - This can be used to add custom calculated fields to the data. For example, if your data source does not provide a variant marker field, one can be generated in javascript (by concatenating chromosome:position_ref/alt), without having to modify the web server. -* `extractFields` - Each data layer receives only the fields it asks for, and the data is reformatted in a way that clearly identifies where they come from (the namespace is prefixed onto each field name, eg `{'mynamespace:a_field': 1}`). - * The most common reason to override this method is if the data uses an extremely complex payload format (like genes), and a custom data layer expects to receive that entire structure as-is. If you are working with layouts, the most common sign of an adapter that does this is that the data layer asks for a nonexistent field (`gene:all` - a synthetic value whose sole purpose is to indicate that the source is used) -* `combineChainBody`: If a single data layer asks for data from more than one source, this function is responsible for combining several different pieces of information together. For example, in order to show an association plot with points colored by LD, the LD adapter implements custom code that annotates the association data with matching LD information. At the end of this function, the data layer will receive a single combined record per visualized data element. - -#### Working with the data "chain" -Each data layer is able to request data from multiple different sources. Internally, this process is referred to as the "chain" of linked data requested. LocusZoom.js assumes that every data layer is independent and decoupled: it follows that each data layer has its own chain of requests and its own parsing process. - -This chain defines how to share information between different adapters. It contains of two key pieces: - -* `body` - the actual consolidated payload. Each subsequent link in the chain receives all the data from the previous step as `chain.body` -* `headers` - this is a "meta" section used to store information used during the consolidation process. For example, the LD adapter needs to find the most significant variant from the previous step in the chain (association data) in order to query the API for LD. The name of that variant can be stored for subsequent use during the data retrieval process. - -Only `chain.body` is sent to the data layer. All other parts of the chain are discarded at the end of the data retrieval process. +* `_annotateRecords` - This can be used to modify the data returned in many useful ways: filtering, renaming fields, or adding new calculated fields. Example scenarios: + * A field called `pValue` can be transformed into one called `log_pvalue` + * If a tabix file returns two categories of data at once, then the adapter could decide which to show according to a user-selected option stored in `plot.state` (So long as both datasets are not too big, this trick works well with the `set_state` toolbar widget: it provides a cheap way to toggle between datasets, without requiring an extra trip to the server!) + * Adding custom calculated fields to the data. For example, if your data source does not provide a variant marker field, one can be generated in javascript (by concatenating chromosome:position_ref/alt), without having to modify the web server. +* `_postProcessResponse`: Most people don't customize this method. After all calculations are done, this is used to transform the data into a format useful by LocusZoom. Eg, field names are prefixed to reflect where the data came from, like `assoc:log_pvalue`. This happens last, so most custom code that modifies returned records doesn't have to deal with it. + * Most of the behaviors in this method can be overridden using adapter options, without writing custom code. (see documentation for details) + # See also * LocusZoom.js is able to share its data with external widgets on the page, via event listeners that allow those widgets to update whenever the user interacts with the plot (eg panning or zooming to change the region in view). See `subscribeToData` in the [guide to interactivity](interactivity.html) for more information. diff --git a/assets/docs/interactivity.md b/assets/docs/interactivity.md index 01ac079e..fe16eef8 100644 --- a/assets/docs/interactivity.md +++ b/assets/docs/interactivity.md @@ -63,7 +63,6 @@ Each LocusZoom rendering is controlled by a declarative set of layout options. I In practice, this is the key idea behind the `display_options` widget, a built-in feature that handles such mutations in a controlled fashion. If you are doing this using your own code, the following "gotchas" apply: -* When the layout is defined before first render, it uses abstract syntax (eg `{{namespace[assoc]field}}`. To modify an existing plot layout after it has been rendered, you will need to use concrete syntax in which the namespace has been filled in: `assoc2_mystudy:field`. * LocusZoom layouts are nested and hierarchical (plot --> panels[] --> data_layers[]). See the helper functions below for advice on how to write mutations that are more readable and maintainable. * Be conservative in how many fields you allow to be changed. Layouts allow almost any aspect of the plot to be customized, but it can be difficult to test every possible combination. It's generally easier to code and maintain controlled options (like a list of preset views). @@ -138,43 +137,17 @@ Using the same mechanisms and syntax as an LZ data layer, let arbitrary parts of Sample usage: ```javascript -const fields = ['aggregation:all', 'gene:all']; +// Receives exactly the same data as the specified datalayer ID (avoids having to duplicate namespace and data operations code) +const spec = { from_layer: 'panel1.layer1' }; const success_callback = (data) => console.log(data); const opts = { onerror: (err) => console.log(err) }; -plot.subscribeToData(fields, success_callback, opts); +plot.subscribeToData(spec, success_callback, opts); ``` - When data is received, calls *success_callback* with the resulting data (an array of objects, with each object representing one datapoint). `subscribeToData` can be used to draw tables or companion visualizations on the page, separate from LocusZoom but automatically updating to stay in sync as the user clicks or pans across the plot. Specify *onerror* as an option to provide an error handling callback. -### Caveat: namespaces -Note that the returned payload will contain namespaced fields: the data will appear in the same format as used internally by LocusZoom. Sometimes this is annoying because it means that any external widget using the data will need to account for LocusZoom's namespacing syntax. - -If you don't want to be bothered with namespacing, the following utility function may be useful: -```javascript -/** -* Remove the `sourcename:` prefix from field names in the data returned by an LZ datasource -* -* This is a convenience method for writing external widgets (like tables) that subscribe to the -* plot; typically we don't want to have to redefine the table layout every time someone selects -* a different association study. -* As with all convenience methods, it has limits: don't use it if the same field name is requested -* from two different sources! -* @param {Object} data An object representing the fields for one row of data -* @param {String} [prefer] Sometimes, two sources provide a field with same name. Specify which -* source will take precedence in the event of a conflict. -*/ -function deNamespace(data, prefer) { - return Object.keys(data).reduce((acc, key) => { - const new_key = key.replace(/.*?:/, ''); - if (!Object.prototype.hasOwnProperty.call(acc, new_key) || (!prefer || key.startsWith(prefer))) { - acc[new_key] = data[key]; - } - return acc; - }, {}); -} -``` +Sometimes you want exact control over what data is retrieved, rather than mirroring a data layer. In that case, replace `from_layer` with two options (`namespace` and `data_operations`) to manually specify how data is retrieved for this callback. See data layer documentation for syntax and usage. ### Advanced alternative Sometimes, the existing page already has several widgets sharing data, and it would be difficult to rewrite things after the fact in a way that ceded control of data to LocusZoom. In this case, some compromise needs to be reached: how can LocusZoom fetch what it needs (possibly rendering only a subset of the data available), without duplicating API calls to the server that have already been made elsewhere? diff --git a/assets/docs/rendering_layouts.md b/assets/docs/rendering_layouts.md index 15e03998..1c7a3acb 100644 --- a/assets/docs/rendering_layouts.md +++ b/assets/docs/rendering_layouts.md @@ -60,10 +60,10 @@ LocusZoom.Layouts.add('plot', 'standard_association', { responsive_resize: true, min_region_scale: 20000, max_region_scale: 1000000, - dashboard: LocusZoom.Layouts.get('dashboard', 'standard_plot', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar_widgets', 'standard_plot'), panels: [ - LocusZoom.Layouts.get('panel', 'association', { unnamespaced: true, height: 225 }), - LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true, height: 225 }) + LocusZoom.Layouts.get('panel', 'association', { height: 225 }), + LocusZoom.Layouts.get('panel', 'genes', { height: 225 }) ] }); ``` @@ -83,38 +83,22 @@ Consider this fragment of the standard association data layer, shown below: LocusZoom.Layouts.add('data_layer', 'association_pvalues', { namespace: { 'assoc': 'assoc', 'ld': 'ld' }, type: 'scatter', - 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', + id_field: 'assoc:variant', x_axis: { - field: '{{namespace[assoc]}}position' + field: 'assoc:position' } }); ``` Key things to notice are: -1. The data layer will only see the fields requested by name. Even if a field is present in the API payload, it will not be visible in the data layer unless explicitly referenced in the `fields` array for that data layer. -2. This layout is generic: the use of namespaces means "given association data from somewhere". See "using namespaces" below for more details on how to use an abstract layout with a specific dataset (via namespaces). -3. Other sections of the layout (such as `x_axis`) can reference the fields requested, using the same syntax. But the field must always be requested in the `fields` array. +1. The data layer will see all of the fields provided by the relevant data sources/adapters. Each field will be prefixed by the "local namespace" for that data (eg if both `assoc` and `ld` provide a field called `id`, both will be present and distinct in the joined data: `assoc:id` and `ld:id`) +2. This layout is generic: the use of namespaces means "given association data from somewhere". See "using namespaces" below. +3. Other sections of the layout (such as `x_axis`) can reference the fields requested, using the same syntax. -You will sometimes see fields referenced elsewhere with an additional syntax, like `{{namespace[assoc]}}variant|htmlescape`. The `|htmlescape` is a [*transform*](../api/module-LocusZoom_TransformationFunctions.html) that affects value display. The fields array only needs to specify the names of fields; transforms can be applied at any time later. +You will sometimes see fields referenced elsewhere with an additional syntax, like `assoc:variant|htmlescape`. The `|htmlescape` is a [*transform*](../api/module-LocusZoom_TransformationFunctions.html) that affects value display. Transforms can be applied anywhere that a field value is used. -#### No system of notation survives contact with developers -There are some exceptions to this rule- it is difficult to support every possible combination of data sources from every possible set of API conventions. - -One place where this breaks down is *dependent* sources- eg, LD information is requested relative to the most significant variant in the association data. Differences in field formatting or nomenclature can sometimes break the ability to find the relevant information that the second data source requires; efforts are made to handle common use cases. These sources gradually become more generic over time based on user feedback and needs. - -The other main exception to the `fields` mechanism involves API endpoints that return complex nested objects (eg the list of genes in a region, a standard dataset that few people will ever need to customize directly). By notation convention, the default LocusZoom layouts will indicate that special behavior is in effect via a dummy field called `all`, eg - -```js -{ - fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'] -} -``` - -> Explanation: a data layer will not fetch from a source unless the fields array references at least one piece of data from that source. Since the genes source contains special code to bypass fetching explicit fields, the data layer uses a dummy field to trigger the request. - -Most standard data types use the system of exact field names. A more detailed guide is beyond the scope of this tutorial; this behavior is governed by the `extractFields` method of `BaseAdapter`. (see: [guide to working with data](data_retrieval.html)) +Every data layer in the registry will contain an automatically-defined property called `_auto_fields`, describing the names of all fields expected by this layout object. This is a quick guide for a developer who wants to see a summary of what data is used. ### renameFields: resolving tiny differences in naming Sometimes, an existing layout is very close to the format of your data, but there are very small cosmetic differences. For example, your API might send a field `variant_name` instead of `variant`. @@ -123,7 +107,7 @@ In this case, a helper function is provided this will recursively rename every u ```javascript // For abstract layouts -layout = LocusZoom.Layouts.renameField(layout, '{{namespace[assoc]}}old_name', '{{namespace[assoc]}}new_name'); +layout = LocusZoom.Layouts.renameField(layout, 'assoc:old_name', 'assoc:new_name'); // For concrete layouts layout = LocusZoom.Layouts.renameField(layout, 'my_assoc:old_name', 'my_assoc:new_name'); @@ -135,6 +119,8 @@ layout = LocusZoom.Layouts.renameField(layout, 'assoc:pvalue|neg_log10', 'assoc: > NOTE: Sometimes, the differences in data/field names are more than cosmetic: for example, renaming `pvalue|neg_log10` to `log_pvalue|neg_log10` would not make sense. This helper method will attempt to warn you if template transformation functions are being used on the field you are changing, so that you can ensure that the resulting layouts uses your data in a way that fits the intended meaning. +> Over time, LocusZoom will become more stringent about what field names it expects to receive. As such, it may make more sense to rename certain fields from the server to match the layout (rather than renaming the layout to match the data). (the `_annotateRecords` method of a custom adapter can be used for this purpose) Most fields work either way; some, like `log_pvalue`, are a special case. + ## Working with the Registry Typically, LocusZoom layouts are loaded via the registry, a set of pre-made reusable layouts. The act of fetching a layout converts it from the abstract definition to one that works with a specific dataset. @@ -145,7 +131,7 @@ Since the registry just returns JSON-serializable objects, you could create a pl To see the list of pre-defined layouts (as well as any custom ones you have created): ```js > LocusZoom.Layouts.list(); -{plot: Array(4), panel: Array(7), data_layer: Array(9), dashboard: Array(4), dashboard_components: Array(1), tooltip: Array(5) } +{plot: Array(4), panel: Array(7), data_layer: Array(9), toolbar: Array(4), toolbar_widgets: Array(1), tooltip: Array(5) } ``` This will return a top level representation of the available types, showing the available categories. Note that even data layers are composed of smaller building blocks. This lets you use individual parts of a representation (like association tooltips) without committing to the other design choices for a common piece (like the association layer). @@ -159,44 +145,6 @@ Asking for just the plots shows a list of specific options. Typically, we try to You may find that the example gallery performs additional customizations on a layout, so this can be a source of ideas. Typically, we try very hard to not make major changes in a layout that is widely in use. Any backwards-incompatible changes will usually be identified in the [release notes](https://github.com/statgen/locuszoom/releases). -### Abstract vs concrete -When a layout is first loaded into the registry, it is defined to work in the abstract- given any data. This allows the same layout to be re-used on two different association datasets. The syntax used is `{{namespace[assoc]}}variant`, where namespaces are replaced by a specific datasource name later on. - -```js -LocusZoom.Layouts.add('data_layer', 'association_pvalues', { // Define a new datalayer - namespace: { 'assoc': 'assoc', 'ld': 'ld' }, // Provides default namespaces, eg look for "assoc" data in a source called "assoc" - 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'], -}); -``` - -It is the act of fetching the layout from the registry that turns it into a concrete one- "find the association data from a particular source". There are three ways to fetch something, and each behaves in a unique way: - -1. Fetch an existing layout, and tell it where to find the required data. (the third argument, "modifications", is given an explicit set of namespaces) - - ```js - > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { namespace: { assoc: 'my_dataset_1' } } ); - { - fields: ["my_dataset_1:variant","my_dataset_1:position","my_dataset_1:log_pvalue","my_dataset_1:log_pvalue|logtoscinotation","my_dataset_1:ref_allele","ld:state","ld:isrefvar"] - } - ``` -2. Fetch an existing layout, and use the "default" data sources. If you follow the examples very closely (eg naming your data source "assoc" and "ld"), this will automatically find the right data. - - ```js - > LocusZoom.Layouts.get('data_layer', 'association_pvalues'); - { - fields: ["assoc:variant", "assoc:position", "assoc:log_pvalue", "assoc:log_pvalue|logtoscinotation", "assoc:ref_allele", "ld:state", "ld:isrefvar"] - } - ``` - -3. Fetch an existing abstract layout for further modification, and keep it abstract. Note the special `unnamespaced: true` option, which causes the layout to be returned exactly as it appears in the registry (*abstract*). This option is used quite a lot in the LZ source code (`Layouts.js`), because it makes it easy to build a reusable abstract layout (like a panel) out of smaller reusable pieces (like datalayers). - - ```js - > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { unnamespaced: true }); - { - namespace: { assoc: 'assoc', ld: 'ld' }, - 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'], - } - ``` ### Modifying all (or part) of a layout If you are building your own API aimed at use with LocusZoom, then the path of least resistance is to use the same field names as the pre-defined layouts. @@ -214,18 +162,18 @@ Consider an association plot, where the only requested change is to use the righ The "modifications" object does not work as well for compound values, like a list, because this behavior is not well defined: changing the 5th element of a list could mean replacement, removal, or minor additions to fields... etc. In practice, this is quite often relevant... because panels and data layers are specified as lists. (order matters) -For complex scenarios like adding toolbar buttons or overriding the panels/data layers in a plot, you can build your own layout using all or some of the pieces of the layouts registry. One trick that is commonly used in the LocusZoom.js source code is to modify just one part of an existing array field via *self-calling functions* that immediately return a new, modified object. (this creates the modifications in-place, without leaving any temporary variables around afterwards) Eg, for a toolbar (dashboard) that adds just one extra button to an existing layout: +For complex scenarios like adding toolbar buttons or overriding the panels/data layers in a plot, you can build your own layout using all or some of the pieces of the layouts registry. One trick that is commonly used in the LocusZoom.js source code is to modify just one part of an existing array field via *self-calling functions* that immediately return a new, modified object. (this creates the modifications in-place, without leaving any temporary variables around afterwards) Eg, for a toolbar that adds just one extra button to an existing layout: ```js { - dashboard: (function () { - var base = LocusZoom.Layouts.get('dashboard', 'standard_panel', { unnamespaced: true }); - base.components.push({ + toolbar: (function () { + var base = LocusZoom.Layouts.get('toolbar', 'standard_panel'); + base.widgets.push({ type: 'toggle_legend', position: 'right' }); return base; - })() // Function calls itself immediately, so "dashboard" is set to the return value + })() // Function calls itself immediately, so "toolbar" is set to the return value } ``` @@ -246,7 +194,7 @@ const data_layer = { // Name of a function specified in `LocusZoom.ScaleFunctions` scale_function: 'if', // The field whose value will be passed to the scale function - field: '{{namespace[ld]}}isrefvar', + field: 'lz_is_ld_refvar', // Options that will be passed to the scale function; see documentation for available options parameters: { field_value: 1, @@ -255,7 +203,7 @@ const data_layer = { }, { scale_function: 'numerical_bin', - field: '{{namespace[ld]}}state', + field: 'ld:correlation', parameters: { breaks: [0, 0.2, 0.4, 0.6, 0.8], values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'], @@ -295,8 +243,9 @@ Consider the following example, which plots two association studies and a genes ```js // Other standard sources (genes, LD) omitted for clarity data_sources - .add("assoc_study1", ["AssociationLZ", {url: "/api/association/", params: { source: 1 }}]) - .add("assoc_study2", ["AssociationLZ", {url: "/api/association/", params: { source: 2 }}]); + .add("assoc_study1", ["AssociationLZ", {url: "/api/association/", source: 1 }]) + .add("assoc_study2", ["AssociationLZ", {url: "/api/association/", source: 2 }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]); ``` ```js @@ -318,20 +267,13 @@ const plot_layout = LocusZoom.Layouts.get('plot', 'standard_association', { // O title: { text: 'Study 2' }, }), // Even though genes are part of the original "standard association plot" layout, overriding the panels array means replacing *all* of the panels. - LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true, height: 400 }) // "unnamespaced" when using as a generic building block + LocusZoom.Layouts.get('panel', 'genes', { height: 400 }) // The layout provides a built-in default: "look for gene data in an adapter called gene". In this example, the default matches what sources were defined, so we don't need to override it. ] }); ``` -Namespaces are not only external- they propagate through to how the layer actually sees its data internally. The field names inside the layer are a composite of `sourcename:fieldname`. For example, this allows the same data layer to work with two pieces of information (like summary stats and LD) even if both API endpoints provide a common field name like `id`. Namespacing ensures that duplicate field names do not collide. +Namespaces are the only thing that needs to be changed in order to use a layout with a different source of data. Internally, things are referred to via the "local" name. Eg given `{ assoc: 'assoc_study2' }`, individual fields would be referenced as `assoc:some_field`, no matter where the data actually came from. -From the example above, the second panel (which fetches association data from `assoc_study2`) converts a "generic" specification like `{{namespace[assoc]}}variant` into a "concrete" use of one dataset: `assoc_study2:variant`. - -```js -> var layer_data = Object.keys(plot.panels['assoc_study2'].data_layers['associationpvalues'].data); -Object.keys(layer_data[0]); // See the field names used by the data for a single point -["assoc_study2:variant", "assoc_study2:position", "assoc_study2:log_pvalue", "assoc_study2:log_pvalue|logtoscinotation", "assoc_study2:ref_allele", "ld:state", "ld:isrefvar"] -``` ### Adding panels The above example demonstrates how to add multiple studies at the time of plot creation. However, sites like the T2D Portal have many datasets, and it can be helpful to let the user interactively choose which other panels to show after first render. New panels can be added dynamically! When doing so, the plot will grow to accommodate the new panel. @@ -347,44 +289,11 @@ var extra_panel_layout = LocusZoom.Layouts.get('panel', 'association', { // Must add both data sources and panels existing_datasources - .add("assoc_study3", ["AssociationLZ", {url: "/api/association/", params: { source: 3 }}]); + .add("assoc_study3", ["AssociationLZ", {url: "/api/association/", source: 3 }]); const new_panel = existing_plot.addPanel(extra_panel_layout); // Adds the panel and redraws plot ``` -### Common issues -One of the most common issues in working with namespaced layouts is the difference between *abstract* and *concrete* layouts. For example, imagine if the page contained a button to toggle the display of labels on the plot. This button might work by changing the plot layout options, then triggering a re-render. - -Here is how label options would be specified when defining a layout in the registry (abstract), so that labels were present on the very first re-render for any dataset that used this layout. Note that it identifies the key fields using a generic `namespace` reference: - -```js -const generic_layout_with_special_labels = { - // Other data layer fields omitted for clarity - label: { - text: '{{{{namespace[assoc]}}variant|htmlescape}}', - filters: [ // Only label points if they are above significance threshold - { field: '{{namespace[assoc]}}log_pvalue', operator: '>', value: 7.301 }, - ], - spacing: 6, - } -}; -``` - -However, once the final layout has been created and used to draw the plot, mutating the layout would require the actual field name (with namespace applied), specific to the panel being changed: - -```js -plot.panels['assoc_study2'].data_layers['associationpvalues'].layout.label = { - text: '{{assoc_study2:variant|htmlescape}}', // Extra outer curly braces around name = Value of field - filters: [ // Only label points if they are above significance threshold - { field: 'assoc_study2:log_pvalue', operator: '>', value: 7.301 }, // No curly braces: specifies name of field - ], - spacing: 6, -}; -plot.applyState(); // to re-render with labels -``` - -When you are not sure what notation convention to use, check the rest of your layout- the JS console is a very powerful tool, and development is much easier when you can introspect the actual behavior of your code. - ## Layouts also control behavior In this guide, we have mostly focused on Layouts as a tool for controlling how data is rendered. However, layouts also provide configuration directives to enable powerful behaviors such as zooming, matching, and filtering. See the [guide to interactivity](interactivity.html) for details. diff --git a/citation.cff b/citation.cff index 7dc426d7..d21060a5 100644 --- a/citation.cff +++ b/citation.cff @@ -10,8 +10,8 @@ authors: family-names: Welch given-names: Ryan - - family-names: Matthew - given-names: Flickinger + family-names: Flickinger + given-names: Matthew - family-names: VandeHaar given-names: Peter diff --git a/css/locuszoom.scss b/css/locuszoom.scss index cd6252ae..757c3286 100644 --- a/css/locuszoom.scss +++ b/css/locuszoom.scss @@ -16,7 +16,7 @@ svg.#{$namespace}-locuszoom { border: none; cursor: crosshair; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 10px; + font-size: 14px; rect.#{$namespace}-clickarea { fill: rgb(0,0,0); @@ -40,7 +40,7 @@ svg.#{$namespace}-locuszoom { } .#{$namespace}-panel-title { - font-size: 18px; + font-size: 150%; font-weight: 600; } @@ -57,11 +57,20 @@ svg.#{$namespace}-locuszoom { shape-rendering: crispEdges; } + .#{$namespace}-axis { + // Override the font-size applied by D3 + font-size: 100%; + } + .#{$namespace}-axis .#{$namespace}-label { - font-size: 12px; + font-size: 120%; font-weight: 600; } + .tick { + font-size: 100%; + } + .tick text:focus { outline-style: dotted; outline-width: 1px; @@ -92,7 +101,7 @@ svg.#{$namespace}-locuszoom { path.#{$namespace}-data_layer-scatter, path.#{$namespace}-data_layer-category_scatter { stroke: #{$default_black_shadow}; stroke-opacity: #{$default_black_shadow_opacity}; - stroke-width: 1px; + stroke-width: 0.8px; cursor: pointer; } @@ -458,7 +467,7 @@ div.#{$namespace}-data_layer-tooltip-arrow_bottom_right { top: 0px; right: 0px; padding: 2px 4px; - font-size: 10px; + font-size: 11px; font-weight: 300; background-color: #D8D8D8; color: #333333; diff --git a/dist/ext/lz-aggregation-tests.min.js b/dist/ext/lz-aggregation-tests.min.js index 7b4c436c..d79132f6 100644 --- a/dist/ext/lz-aggregation-tests.min.js +++ b/dist/ext/lz-aggregation-tests.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +var LzAggregationTests;(()=>{"use strict";var e={d:(t,r)=>{for(var s in r)e.o(r,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:r[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>o});const r=raremetal;function s(e){const t=e.Adapters.get("BaseLZAdapter");e.DataFunctions.add("gene_plus_aggregation",((e,[t,r])=>{const s={};return r.groups.forEach((function(e){Object.prototype.hasOwnProperty.call(s,e.group)||(s[e.group]=[]),s[e.group].push(e.pvalue)})),t.forEach((e=>{const t=e.gene_name,r=s[t];r&&(e.aggregation_best_pvalue=Math.min.apply(null,r))})),t})),e.Adapters.add("AggregationTestSourceLZ",class extends t{constructor(e){e.prefix_namespace=!1,super(e)}_buildRequestOptions(e){const{aggregation_tests:t={}}=e,{genoset_id:r=null,genoset_build:s=null,phenoset_build:o=null,pheno:n=null,calcs:a={},masks:u=[]}=t;return t.mask_ids=u.map((e=>e.name)),e.aggregation_tests=t,e}_getURL(e){return this._url}_getCacheKey(e){const{chr:t,start:r,end:s,aggregation_tests:o}=e,{genoset_id:n=null,genoset_build:a=null,phenoset_id:u=null,pheno:l=null,mask_ids:g}=o;return JSON.stringify({chrom:t,start:r,stop:s,genotypeDataset:n,phenotypeDataset:u,phenotype:l,samples:"ALL",genomeBuild:a,masks:g})}_performRequest(e){const t=this._getURL(e),r=this._getCacheKey(e);return fetch(t,{method:"POST",body:r,headers:{"Content-Type":"application/json"}}).then((e=>{if(!e.ok)throw new Error(e.statusText);return e.text()})).then((e=>{const t="string"==typeof e?JSON.parse(e):e;if(t.error)throw new Error(t.error);return t.data}))}_annotateRecords(e,t){const{aggregation_tests:s}=t,{calcs:o=[],mask_ids:n=[],masks:a=[]}=s;if(!e.groups)return{groups:[],variants:[]};e.groups=e.groups.filter((e=>"GENE"===e.groupType));const u=r.helpers.parsePortalJSON(e);let l=u[0];const g=u[1];if(l=l.byMask(n),!o||0===Object.keys(o).length)return{variants:[],groups:[],results:[]};return new r.helpers.PortalTestRunner(l,g,o).toJSON().then((function(e){const t=a.reduce(((e,t)=>(e[t.name]=t.description,e)),{});return e.data.groups.forEach((e=>{e.mask_name=t[e.mask]})),e.data})).catch((function(e){throw console.error(e),new Error("Failed to calculate aggregation test results")}))}}),e.Adapters.add("AssocFromAggregationLZ",class extends t{_buildRequestOptions(e,t){if(!t)throw new Error("Aggregation test results must be provided");return e._agg_results=t,e}_performRequest(e){return Promise.resolve(e._agg_results.variants)}_normalizeResponse(e){const t=new RegExp("(?:chr)?(.+):(\\d+)_?(\\w+)?/?([^_]+)?_?(.*)?");return e.map((e=>{const{variant:r,altFreq:s,pvalue:o}=e,n=r.match(t),[a,u,l,g]=n;return{variant:r,chromosome:u,position:+l,ref_allele:g,ref_allele_freq:1-s,log_pvalue:-Math.log10(o)}})).sort(((e,t)=>(e=e.variant)<(t=t.variant)?-1:e>t?1:0))}})}"undefined"!=typeof LocusZoom&&LocusZoom.use(s);const o=s;LzAggregationTests=t.default})(); //# sourceMappingURL=lz-aggregation-tests.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-aggregation-tests.min.js.map b/dist/ext/lz-aggregation-tests.min.js.map index f5a545ea..c8b8024a 100644 --- a/dist/ext/lz-aggregation-tests.min.js.map +++ b/dist/ext/lz-aggregation-tests.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 \"raremetal\"","webpack://[name]/./esm/ext/lz-aggregation-tests.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","raremetal","install","LocusZoom","BaseAdapter","Adapters","BaseApiAdapter","ConnectorSource","add","state","chain","fields","required_info","aggregation_tests","header","aggregation_genoset_id","genoset_id","aggregation_genoset_build","genoset_build","aggregation_phenoset_id","phenoset_id","aggregation_pheno","pheno","aggregation_calcs","calcs","mask_data","masks","aggregation_masks","aggregation_mask_ids","map","item","name","this","url","getURL","JSON","stringify","chrom","chr","start","stop","end","genotypeDataset","phenotypeDataset","phenotype","samples","genomeBuild","body","getCacheKey","fetch","method","headers","then","response","ok","Error","statusText","text","resp","json","parse","error","records","groups","variants","filter","groupType","parsed","helpers","byMask","keys","length","results","toJSON","res","mask_id_to_desc","reduce","acc","val","description","data","forEach","group","mask_name","mask","catch","e","console","config","from","super","arguments","parseInit","_from","discrete","constructor","SOURCE_NAME","Promise","resolve","REGEX_EPACTS","RegExp","one_variant","match","variant","chromosome","position","ref_allele","ref_allele_freq","altFreq","log_pvalue","Math","log10","pvalue","sort","a","b","aggregation_source_id","_source_name_mapping","gene_source_id","aggregationData","genesData","groupedAggregation","result","push","gene","gene_id","gene_name","tests","aggregation_best_pvalue","min","apply","use"],"mappings":";0CACA,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,4BCAlF,MAAM,EAA+BI,UCmCrC,SAASC,EAASC,GACd,MAAMC,EAAcD,EAAUE,SAASV,IAAI,eACrCW,EAAiBH,EAAUE,SAASV,IAAI,kBACxCY,EAAkBJ,EAAUE,SAASV,IAAI,mBAkP/CQ,EAAUE,SAASG,IAAI,0BAxOvB,cAAsCF,EAClC,OAAOG,EAAOC,EAAOC,GAIjB,MAAMC,EAAgBH,EAAMI,mBAAqB,GAE5CH,EAAMI,SACPJ,EAAMI,OAAS,IAGnBJ,EAAMI,OAAOC,uBAAyBH,EAAcI,YAAc,KAClEN,EAAMI,OAAOG,0BAA4BL,EAAcM,eAAiB,KACxER,EAAMI,OAAOK,wBAA0BP,EAAcQ,aAAe,KACpEV,EAAMI,OAAOO,kBAAoBT,EAAcU,OAAS,KACxDZ,EAAMI,OAAOS,kBAAoBX,EAAcY,OAAS,GACxD,MAAMC,EAAYb,EAAcc,OAAS,GAKzC,OAJAhB,EAAMI,OAAOa,kBAAoBF,EACjCf,EAAMI,OAAOc,qBAA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V,EAAYW,YAEzCC,MAAK,CAACC,EAAGC,KACRD,EAAIA,EAAEX,UACNY,EAAIA,EAAEZ,UAEM,EACDW,EAAIC,EACJ,EAGA,OAwDvBhH,EAAUE,SAASG,IAAI,6BAxCvB,cAAyCD,EACrC,sBACI,MAAO,CAAC,UAAW,kBAGvB,iBAAiByE,EAAMtE,GAInB,MAAM0G,EAAwBpF,KAAKqF,qBAAqC,eAClEC,EAAiBtF,KAAKqF,qBAA8B,QAGpDE,EAAkB7G,EAAMoF,SAASsB,GACjCI,EAAY9G,EAAMoF,SAASwB,GAE3BG,EAAqB,GAiB3B,OAfAF,EAAgBxD,OAAOkB,SAAQ,SAAUyC,GAChClI,OAAOM,UAAUC,eAAeC,KAAKyH,EAAoBC,EAAOxC,SACjEuC,EAAmBC,EAAOxC,OAAS,IAEvCuC,EAAmBC,EAAOxC,OAAOyC,KAAKD,EAAOV,WAIjDQ,EAAUvC,SAAQ,SAAU2C,GACxB,MAAMC,EAAUD,EAAKE,UACfC,EAAQN,EAAmBI,GAC7BE,IACAH,EAAKI,wBAA0BlB,KAAKmB,IAAIC,MAAM,KAAMH,OAGrDP,KAWM,oBAAdrH,WAGPA,UAAUgI,IAAIjI,GAIlB,U","file":"ext/lz-aggregation-tests.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__ = raremetal;","/**\n * LocusZoom extensions used to calculate and render aggregation test results. Because these calculations depend on an\n * external library, the special data adapters are defined here, rather than in LocusZoom core code.\n *\n * This extension provides a number of features that are closely tied to the aggregation tests demo,\n * and thus the specific UI and data operations are less of a drop-in generic addon than most other extensions.\n * This tool also depends on a calculation tool (like RAREMETAL-server) with access to sample specific genotypes.\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - LocusZoom\n * - raremetal.js (available via NPM or a related CDN)\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import aggTests from 'locuszoom/esm/ext/lz-aggregation-tests';\n * LocusZoom.use(aggTests);\n * ```\n *\n * Then use the layouts and data adapters made available by this extension. (see demos and documentation for guidance)\n * @private\n * @module\n */\n// This is defined as a UMD module, to work with multiple different module systems / bundlers\n// Arcane build note: everything defined here gets registered globally. This is not a \"pure\" module, and some build\n// systems may require being told that this file has side effects.\n\nimport {helpers} from 'raremetal.js';\n\nfunction install (LocusZoom) {\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n const BaseApiAdapter = LocusZoom.Adapters.get('BaseApiAdapter');\n const ConnectorSource = LocusZoom.Adapters.get('ConnectorSource');\n\n /**\n * Calculates gene or region-based tests based on provided data, using the raremetal.js library.\n * It will rarely be used by itself, but rather using a connector that attaches the results to data from\n * another source (like genes). Using a separate connector allows us to add caching and run this front-end\n * calculation only once, while using it in many different places.\n * @see module:ext/lz-aggregation-tests\n * @private\n */\n class AggregationTestSourceLZ extends BaseApiAdapter {\n getURL(state, chain, fields) {\n // Unlike most sources, calculations may require access to plot state data even after the initial request\n // This example source REQUIRES that the external UI widget would store the needed test definitions in a plot state\n // field called `aggregation_tests` (an object {masks: [], calcs: {})\n const required_info = state.aggregation_tests || {};\n\n if (!chain.header) {\n chain.header = {};\n }\n // All of these fields are required in order to use this datasource. TODO: Add validation?\n chain.header.aggregation_genoset_id = required_info.genoset_id || null; // Number\n chain.header.aggregation_genoset_build = required_info.genoset_build || null; // String\n chain.header.aggregation_phenoset_id = required_info.phenoset_id || null; // Number\n chain.header.aggregation_pheno = required_info.pheno || null; // String\n chain.header.aggregation_calcs = required_info.calcs || {}; // String[]\n const mask_data = required_info.masks || [];\n chain.header.aggregation_masks = mask_data; // {name:desc}[]\n chain.header.aggregation_mask_ids = mask_data.map(function (item) {\n return item.name;\n }); // Number[]\n return this.url;\n }\n\n getCacheKey(state, chain, fields) {\n this.getURL(state, chain, fields); // TODO: This just sets the chain.header fields\n return JSON.stringify({\n chrom: state.chr,\n start: state.start,\n stop: state.end,\n genotypeDataset: chain.header.aggregation_genoset_id,\n phenotypeDataset: chain.header.aggregation_phenoset_id,\n phenotype: chain.header.aggregation_pheno,\n samples: 'ALL',\n genomeBuild: chain.header.aggregation_genoset_build,\n masks: chain.header.aggregation_mask_ids,\n });\n }\n\n fetchRequest(state, chain, fields) {\n const url = this.getURL(state, chain, fields);\n const body = this.getCacheKey(state, chain, fields);\n const headers = {\n 'Content-Type': 'application/json',\n };\n\n return fetch(url, {method: 'POST', body: body, headers: headers}).then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then(function (resp) {\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n if (json.error) {\n // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests,\n // with a human-readable error description as a key\n // For now, this should be treated strictly as an error\n throw new Error(json.error);\n }\n return json;\n });\n }\n\n annotateData(records, chain) {\n // Operate on the calculated results. The result of this method will be added to chain.discrete\n\n // In a page using live API data, the UI would only request the masks it needs from the API.\n // But in our demos, sometimes boilerplate JSON has more masks than the UI asked for. Limit what calcs we run (by\n // type, and to the set of groups requested by the user)\n\n // The Raremetal-server API has a quirk: it returns a different payload structure if no groups are defined\n // for the request region. Detect when that happens and end the calculation immediately in that case\n if (!records.groups) {\n return { groups: [], variants: [] };\n }\n\n records.groups = records.groups.filter(function (item) {\n return item.groupType === 'GENE';\n });\n\n const parsed = helpers.parsePortalJSON(records);\n let groups = parsed[0];\n const variants = parsed[1];\n // Some APIs may return more data than we want (eg simple sites that are just serving up premade scorecov json files).\n // Filter the response to just what the user has chosen to analyze.\n groups = groups.byMask(chain.header.aggregation_mask_ids);\n\n // Determine what calculations to run\n const calcs = chain.header.aggregation_calcs;\n if (!calcs || Object.keys(calcs).length === 0) {\n // If no calcs have been requested, then return a dummy placeholder immediately\n return { variants: [], groups: [], results: [] };\n }\n const runner = new helpers.PortalTestRunner(groups, variants, calcs);\n\n return runner.toJSON()\n .then(function (res) {\n // Internally, raremetal helpers track how the calculation is done, but not any display-friendly values\n // We will annotate each mask name (id) with a human-friendly description for later use\n const mask_id_to_desc = chain.header.aggregation_masks.reduce(function (acc, val) {\n acc[val.name] = val.description;\n return acc;\n }, {});\n res.data.groups.forEach(function (group) {\n group.mask_name = mask_id_to_desc[group.mask];\n });\n return res.data;\n })\n .catch(function (e) {\n console.error(e);\n throw new Error('Failed to calculate aggregation test results');\n });\n }\n\n normalizeResponse(data) {\n return data;\n }\n\n combineChainBody(records, chain) {\n // aggregation tests are a bit unique, in that the data is rarely used directly- instead it is used to annotate many\n // other layers in different ways. The calculated result has been added to `chain.discrete`, but will not be returned\n // as part of the response body built up by the chain\n return chain.body;\n }\n\n }\n\n /**\n * Restructure RAREMETAL-SERVER data used to calculate aggregation tests into a format that can be used to\n * display a GWAS scatter plot.\n * @see module:ext/lz-aggregation-tests\n * @see module:LocusZoom_Adapters\n * @private\n */\n class AssocFromAggregationLZ extends BaseAdapter {\n constructor(config) {\n if (!config || !config.from) {\n throw 'Must specify the name of the source that contains association data';\n }\n super(...arguments);\n }\n parseInit(config) {\n super.parseInit(config);\n this._from = config.from;\n }\n\n getRequest(state, chain, fields) {\n // Does not actually make a request. Just pick off the specific bundle of data from a known payload structure.\n if (chain.discrete && !chain.discrete[this._from]) {\n throw `${this.constructor.SOURCE_NAME} cannot be used before loading required data for: ${this._from}`;\n }\n // Copy the data so that mutations (like sorting) don't affect the original\n return Promise.resolve(JSON.parse(JSON.stringify(chain.discrete[this._from]['variants'])));\n }\n\n normalizeResponse(data) {\n // The payload structure of the association source is slightly different than the one required by association\n // plots. For example, we need to parse variant names and convert to log_pvalue\n const REGEX_EPACTS = new RegExp('(?:chr)?(.+):(\\\\d+)_?(\\\\w+)?/?([^_]+)?_?(.*)?'); // match API variant strings\n return data.map((one_variant) => {\n const match = one_variant.variant.match(REGEX_EPACTS);\n return {\n variant: one_variant.variant,\n chromosome: match[1],\n position: +match[2],\n ref_allele: match[3],\n ref_allele_freq: 1 - one_variant.altFreq,\n log_pvalue: -Math.log10(one_variant.pvalue),\n };\n }).sort((a, b) => {\n a = a.variant;\n b = b.variant;\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n // names must be equal\n return 0;\n }\n });\n }\n }\n\n /**\n * A sample connector that aligns calculated aggregation test data with corresponding gene information. Returns a body\n * suitable for use with the genes datalayer.\n *\n * To use this source, one must specify a fields array that calls first the genes source, then a dummy field from\n * this source. The output will be to transparently add several new fields to the genes data.\n * @see module:ext/lz-aggregation-tests\n * @see module:LocusZoom_Adapters\n * @private\n */\n class GeneAggregationConnectorLZ extends ConnectorSource {\n _getRequiredSources() {\n return ['gene_ns', 'aggregation_ns'];\n }\n\n combineChainBody(data, chain) {\n // The genes layer receives all results, and displays only the best pvalue for each gene\n\n // Tie the calculated group-test results to genes with a matching name\n const aggregation_source_id = this._source_name_mapping['aggregation_ns'];\n const gene_source_id = this._source_name_mapping['gene_ns'];\n // This connector assumes that genes are the main body of records from the chain, and that aggregation tests are\n // a standalone source that has not acted on genes data yet\n const aggregationData = chain.discrete[aggregation_source_id];\n const genesData = chain.discrete[gene_source_id];\n\n const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test\n\n aggregationData.groups.forEach(function (result) {\n if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) {\n groupedAggregation[result.group] = [];\n }\n groupedAggregation[result.group].push(result.pvalue);\n });\n\n // Annotate any genes that have test results\n genesData.forEach(function (gene) {\n const gene_id = gene.gene_name;\n const tests = groupedAggregation[gene_id];\n if (tests) {\n gene.aggregation_best_pvalue = Math.min.apply(null, tests);\n }\n });\n return genesData;\n }\n }\n\n\n LocusZoom.Adapters.add('AggregationTestSourceLZ', AggregationTestSourceLZ);\n LocusZoom.Adapters.add('AssocFromAggregationLZ', AssocFromAggregationLZ);\n LocusZoom.Adapters.add('GeneAggregationConnectorLZ', GeneAggregationConnectorLZ);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/external \"raremetal\"","webpack://[name]/./esm/ext/lz-aggregation-tests.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","raremetal","install","LocusZoom","BaseUrlAdapter","Adapters","DataFunctions","add","state","genes_data","aggregation_data","groupedAggregation","groups","forEach","result","group","push","pvalue","gene","gene_id","gene_name","tests","aggregation_best_pvalue","Math","min","apply","config","prefix_namespace","super","aggregation_tests","genoset_id","genoset_build","phenoset_build","pheno","calcs","masks","mask_ids","map","item","name","options","this","_url","chr","start","end","phenoset_id","JSON","stringify","chrom","stop","genotypeDataset","phenotypeDataset","phenotype","samples","genomeBuild","url","_getURL","body","_getCacheKey","fetch","method","headers","then","response","ok","Error","statusText","text","resp","json","parse","error","data","records","variants","filter","groupType","parsed","helpers","byMask","keys","length","results","toJSON","res","mask_id_to_desc","reduce","acc","val","description","mask_name","mask","catch","e","console","agg_results","_agg_results","Promise","resolve","REGEX_EPACTS","RegExp","variant","altFreq","match","_","chromosome","position","ref_allele","ref_allele_freq","log_pvalue","log10","sort","a","b","use"],"mappings":";0CACA,IAAIA,EAAsB,CCA1B,EAAwB,CAACC,EAASC,KACjC,IAAI,IAA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AAMC,EAAkBnD,EAAMoD,QAAO,CAACC,EAAKC,KACvCD,EAAIC,EAAIlD,MAAQkD,EAAIC,YACbF,IACR,IAIH,OAHAH,EAAIZ,KAAK7D,OAAOC,SAASE,IACrBA,EAAM4E,UAAYL,EAAgBvE,EAAM6E,SAErCP,EAAIZ,QAEdoB,OAAM,SAAUC,GAEb,MADAC,QAAQvB,MAAMsB,GACR,IAAI5B,MAAM,sDAmFhC/D,EAAUE,SAASE,IAAI,yBAvEvB,cAAqCH,EACjC,qBAAqBI,EAAOwF,GAExB,IAAKA,EACD,MAAM,IAAI9B,MAAM,6CAGpB,OADA1D,EAAMyF,aAAeD,EACdxF,EAGX,gBAAgBgC,GACZ,OAAO0D,QAAQC,QAAQ3D,EAAQyD,aAAuB,UAG1D,mBAAmBxB,GAGf,MAAM2B,EAAe,IAAIC,OAAO,iDAChC,OAAO5B,EAAKpC,KAAKC,IACb,MAAM,QAAEgE,EAAO,QAAEC,EAAO,OAAEtF,GAAWqB,EAC/BkE,EAAQF,EAAQE,MAAMJ,IACrBK,EAAGC,EAAYC,EAAUC,GAAcJ,EAC9C,MAAO,CACHF,QAASA,EACTI,aACAC,UAAWA,EACXC,aACAC,gBAAiB,EAAIN,EACrBO,YAAavF,KAAKwF,MAAM9F,OAE7B+F,MAAK,CAACC,EAAGC,KACRD,EAAIA,EAAEX,UACNY,EAAIA,EAAEZ,UAEM,EACDW,EAAIC,EACJ,EAGA,OAoCF,oBAAd/G,WAGPA,UAAUgH,IAAIjH,GAIlB,U","file":"ext/lz-aggregation-tests.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__ = raremetal;","/**\n * LocusZoom extensions used to calculate and render aggregation test results. Because these calculations depend on an\n * external library, the special data adapters are defined here, rather than in LocusZoom core code.\n *\n * This extension provides a number of features that are closely tied to the aggregation tests demo,\n * and thus the specific UI and data operations are less of a drop-in generic addon than most other extensions.\n * This tool also depends on a calculation tool (like RAREMETAL-server) with access to sample specific genotypes.\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - LocusZoom\n * - raremetal.js (available via NPM or a related CDN)\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import aggTests from 'locuszoom/esm/ext/lz-aggregation-tests';\n * LocusZoom.use(aggTests);\n * ```\n *\n * Then use the layouts and data adapters made available by this extension. (see demos and documentation for guidance)\n * @private\n * @module\n */\n// This is defined as a UMD module, to work with multiple different module systems / bundlers\n// Arcane build note: everything defined here gets registered globally. This is not a \"pure\" module, and some build\n// systems may require being told that this file has side effects.\n\nimport {helpers} from 'raremetal.js';\n\nfunction install (LocusZoom) {\n const BaseUrlAdapter = LocusZoom.Adapters.get('BaseLZAdapter');\n\n /**\n * Calculates gene or region-based tests based on provided data, using the raremetal.js library.\n * It will rarely be used by itself, but rather using a connector that attaches the results to data from\n * another source (like genes). Using a separate connector allows us to add caching and run this front-end\n * calculation only once, while using it in many different places.\n * @see module:ext/lz-aggregation-tests\n * @private\n */\n class AggregationTestSourceLZ extends BaseUrlAdapter {\n constructor(config) {\n config.prefix_namespace = false;\n super(config);\n }\n\n _buildRequestOptions(state) {\n const { aggregation_tests = {} } = state;\n const {\n // eslint-disable-next-line no-unused-vars\n genoset_id = null, genoset_build = null, phenoset_build = null, pheno = null, calcs = {}, masks = [],\n } = aggregation_tests;\n\n aggregation_tests.mask_ids = masks.map((item) => item.name);\n // Many of these params will be undefined if no tests defined\n state.aggregation_tests = aggregation_tests;\n return state;\n }\n\n _getURL(options) {\n // Unlike most sources, calculations may require access to plot state data even after the initial request\n // This example source REQUIRES that the external UI widget would store the needed test definitions in a plot state\n // field called `aggregation_tests` (an object {masks: [], calcs: {})\n return this._url;\n }\n\n _getCacheKey(options) {\n const { chr, start, end, aggregation_tests } = options;\n const { genoset_id = null, genoset_build = null, phenoset_id = null, pheno = null, mask_ids } = aggregation_tests;\n\n return JSON.stringify({\n chrom: chr,\n start: start,\n stop: end,\n genotypeDataset: genoset_id,\n phenotypeDataset: phenoset_id,\n phenotype: pheno,\n samples: 'ALL',\n genomeBuild: genoset_build,\n masks: mask_ids,\n });\n }\n\n _performRequest(options) {\n const url = this._getURL(options);\n const body = this._getCacheKey(options); // cache key doubles as request body\n const headers = {\n 'Content-Type': 'application/json',\n };\n\n return fetch(url, {method: 'POST', body: body, headers: headers})\n .then((response) => {\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n return response.text();\n }).then((resp) => {\n const json = typeof resp == 'string' ? JSON.parse(resp) : resp;\n if (json.error) {\n // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests,\n // with a human-readable error description as a key\n // For now, this should be treated strictly as an error\n throw new Error(json.error);\n }\n return json.data;\n });\n }\n\n _annotateRecords(records, options) {\n // The server response gives covariance for a set of masks, but the actual calculations are done separately.\n // Eg, several types of aggtests might use the same covariance matrix.\n\n // TODO In practice, the test calculations are slow. Investigate caching full results (returning all from performRequest), not just covmat.\n // This code is largely for demonstration purposes and does not reflect modern best practices possible in LocusZoom (eg sources + dependencies to link together requests)\n const { aggregation_tests } = options;\n const { calcs = [], mask_ids = [], masks = [] } = aggregation_tests;\n\n // In a page using live API data, the UI would only request the masks it needs from the API.\n // But in our demos, sometimes boilerplate JSON has more masks than the UI asked for. Limit what calcs we run (by\n // type, and to the set of groups requested by the user)\n\n // The Raremetal-server API has a quirk: it returns a different payload structure if no groups are defined\n // for the request region. Detect when that happens and end the calculation immediately in that case\n if (!records.groups) {\n return { groups: [], variants: [] };\n }\n\n records.groups = records.groups.filter((item) => item.groupType === 'GENE');\n\n const parsed = helpers.parsePortalJSON(records);\n let groups = parsed[0];\n const variants = parsed[1];\n // Some APIs may return more data than we want (eg simple sites that are just serving up premade scorecov json files).\n // Filter the response to just what the user has chosen to analyze.\n groups = groups.byMask(mask_ids);\n\n // Determine what calculations to run\n if (!calcs || Object.keys(calcs).length === 0) {\n // If no calcs have been requested, then return a dummy placeholder immediately\n return { variants: [], groups: [], results: [] };\n }\n const runner = new helpers.PortalTestRunner(groups, variants, calcs);\n\n return runner.toJSON()\n .then(function (res) {\n // Internally, raremetal helpers track how the calculation is done, but not any display-friendly values\n // We will annotate each mask name (id) with a human-friendly description for later use\n const mask_id_to_desc = masks.reduce((acc, val) => {\n acc[val.name] = val.description;\n return acc;\n }, {});\n res.data.groups.forEach((group) => {\n group.mask_name = mask_id_to_desc[group.mask];\n });\n return res.data;\n })\n .catch(function (e) {\n console.error(e);\n throw new Error('Failed to calculate aggregation test results');\n });\n }\n }\n\n /**\n * Restructure RAREMETAL-SERVER data used to calculate aggregation tests into a format that can be used to\n * display a GWAS scatter plot.\n * @see module:ext/lz-aggregation-tests\n * @see module:LocusZoom_Adapters\n * @private\n */\n class AssocFromAggregationLZ extends BaseUrlAdapter {\n _buildRequestOptions(state, agg_results) {\n // This adapter just reformats an existing payload from cache (maybe this is better as a data_operation instead of an adapter nowadays?)\n if (!agg_results) {\n throw new Error('Aggregation test results must be provided');\n }\n state._agg_results = agg_results;\n return state;\n }\n\n _performRequest(options) {\n return Promise.resolve(options._agg_results['variants']);\n }\n\n _normalizeResponse(data) {\n // The payload structure of the association source is slightly different than the one required by association\n // plots. For example, we need to parse variant names and convert to log_pvalue\n const REGEX_EPACTS = new RegExp('(?:chr)?(.+):(\\\\d+)_?(\\\\w+)?/?([^_]+)?_?(.*)?'); // match API variant strings\n return data.map((item) => {\n const { variant, altFreq, pvalue } = item;\n const match = variant.match(REGEX_EPACTS);\n const [_, chromosome, position, ref_allele] = match;\n return {\n variant: variant,\n chromosome,\n position: +position,\n ref_allele,\n ref_allele_freq: 1 - altFreq,\n log_pvalue: -Math.log10(pvalue),\n };\n }).sort((a, b) => {\n a = a.variant;\n b = b.variant;\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n // names must be equal\n return 0;\n }\n });\n }\n }\n\n const genes_plus_aggregation = (state, [genes_data, aggregation_data]) => {\n // Used to highlight genes with significant aggtest results. Unlike a basic left join, it chooses one specific aggtest with the most significant results\n\n // Tie the calculated group-test results to genes with a matching name\n const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test\n\n aggregation_data.groups.forEach(function (result) {\n if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) {\n groupedAggregation[result.group] = [];\n }\n groupedAggregation[result.group].push(result.pvalue);\n });\n\n // Annotate any genes that have test results\n genes_data.forEach((gene) => {\n const gene_id = gene.gene_name;\n const tests = groupedAggregation[gene_id];\n if (tests) {\n gene.aggregation_best_pvalue = Math.min.apply(null, tests);\n }\n });\n return genes_data;\n };\n LocusZoom.DataFunctions.add('gene_plus_aggregation', genes_plus_aggregation);\n\n LocusZoom.Adapters.add('AggregationTestSourceLZ', AggregationTestSourceLZ);\n LocusZoom.Adapters.add('AssocFromAggregationLZ', AssocFromAggregationLZ);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/ext/lz-credible-sets.min.js b/dist/ext/lz-credible-sets.min.js index 9b7edae7..a29c5e2d 100644 --- a/dist/ext/lz-credible-sets.min.js +++ b/dist/ext/lz-credible-sets.min.js @@ -1,3 +1,16 @@ -/*! 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})(); +/*! Locuszoom 0.14.0 */ +var LzCredibleSets;(()=>{var e={803:function(e){var t;t=function(){return function(e){var t={};function r(o){if(t[o])return t[o].exports;var a=t[o]={i:o,l:!1,exports:{}};return e[o].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,o){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:o})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t,r){"use strict"; +/** + * @module stats + * @license MIT + * */ +function o(e){var t=[3.3871328727963665,133.14166789178438,1971.5909503065513,13731.69376550946,45921.95393154987,67265.7709270087,33430.57558358813,2509.0809287301227],r=[42.31333070160091,687.1870074920579,5394.196021424751,21213.794301586597,39307.89580009271,28729.085735721943,5226.495278852854],o=[1.4234371107496835,4.630337846156546,5.769497221460691,3.6478483247632045,1.2704582524523684,.2417807251774506,.022723844989269184,.0007745450142783414],a=[2.053191626637759,1.6763848301838038,.6897673349851,.14810397642748008,.015198666563616457,.0005475938084995345,1.0507500716444169e-9],i=[6.657904643501103,5.463784911164114,1.7848265399172913,.29656057182850487,.026532189526576124,.0012426609473880784,27115555687434876e-21,2.0103343992922881e-7],n=[.599832206555888,.1369298809227358,.014875361290850615,.0007868691311456133,18463183175100548e-21,1.421511758316446e-7,20442631033899397e-31],s=e-.5,l=void 0,c=void 0;if(Math.abs(s)<.425)return s*(((((((t[7]*(l=.180625-s*s)+t[6])*l+t[5])*l+t[4])*l+t[3])*l+t[2])*l+t[1])*l+t[0])/(((((((r[6]*l+r[5])*l+r[4])*l+r[3])*l+r[2])*l+r[1])*l+r[0])*l+1);if(!((l=s<0?e:1-e)>0))throw"Not implemented";return c=(l=Math.sqrt(-Math.log(l)))<=5?(((((((o[7]*(l-=1.6)+o[6])*l+o[5])*l+o[4])*l+o[3])*l+o[2])*l+o[1])*l+o[0])/(((((((a[6]*l+a[5])*l+a[4])*l+a[3])*l+a[2])*l+a[1])*l+a[0])*l+1):(((((((i[7]*(l-=5)+i[6])*l+i[5])*l+i[4])*l+i[3])*l+i[2])*l+i[1])*l+i[0])/(((((((n[6]*l+n[5])*l+n[4])*l+n[3])*l+n[2])*l+n[1])*l+n[0])*l+1),s<0&&(c=-c),c}Object.defineProperty(t,"__esModule",{value:!0});var a={ninv:o};t.ninv=o,t.default=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.marking=t.stats=t.scoring=void 0;var o=n(r(0)),a=n(r(2)),i=n(r(3));function n(e){return e&&e.__esModule?e:{default:e}}t.scoring=a.default,t.stats=o.default,t.marking=i.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._nlogp_to_z2=t.normalizeProbabilities=t.bayesFactors=void 0;var o=r(0);function a(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)||!e.length)throw"Must provide a non-empty array of pvalues";var r=e.map((function(e){return i(e)/2}));if(t){var o=Math.max.apply(Math,a(r))-708;o>0&&(r=r.map((function(e){return e-o})))}return r.map((function(e){return Math.exp(e)}))}function s(e){var t=e.reduce((function(e,t){return e+t}),0);return e.map((function(e){return e/t}))}var l={bayesFactors:n,normalizeProbabilities:s};t.default=l,t.bayesFactors=n,t.normalizeProbabilities=s,t._nlogp_to_z2=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],o=!0,a=!1,i=void 0;try{for(var n,s=e[Symbol.iterator]();!(o=(n=s.next()).done)&&(r.push(n.value),!t||r.length!==t);o=!0);}catch(e){a=!0,i=e}finally{try{!o&&s.return&&s.return()}finally{if(a)throw i}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}; +/** + * @module marking + * @license MIT + */function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.95;if(!Array.isArray(e)||!e.length)throw"Probs must be a non-empty array";if("number"!=typeof t||t<0||t>1||Number.isNaN(t))throw"Cutoff must be a number between 0 and 1";var r=e.reduce((function(e,t){return e+t}),0);if(r<=0)throw"Sum of provided probabilities must be > 0";for(var a=e.map((function(e,t){return[e,t]})).sort((function(e,t){return t[0]-e[0]})),i=0,n=new Array(a.length).fill(0),s=0;s{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var o={};(()=>{"use strict";r.d(o,{default:()=>a});var e=r(803);function t(t){const r=t.Adapters.get("BaseUMAdapter");t.Adapters.add("CredibleSetLZ",class extends r{constructor(e){super(...arguments),this._config=Object.assign({threshold:.95,significance_threshold:7.301},this._config),this._prefix_namespace=!1}_getCacheKey(e){return[e.credible_set_threshold||this._config.threshold,e.chr,e.start,e.end].join("_")}_buildRequestOptions(e,t){const r=super._buildRequestOptions(...arguments);return r._assoc_data=t,r}_performRequest(t){const{_assoc_data:r}=t;if(!r.length)return Promise.resolve([]);const o=this._findPrefixedKey(r[0],"log_pvalue"),a=this._config.threshold,i=r.map((e=>e[o]));if(!i.some((e=>e>=this._config.significance_threshold)))return Promise.resolve(r);try{const o=e.scoring.bayesFactors(i),n=e.scoring.normalizeProbabilities(o),s=e.marking.findCredibleSet(n,a),l=e.marking.rescaleCredibleSet(s),c=e.marking.markBoolean(s);for(let e=0;e{{assoc:variant|htmlescape}}
P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
{{#if credset:posterior_prob}}
Posterior probability: {{credset:posterior_prob|scinotation|htmlescape}}{{/if}}"});const a=function(){const e=t.Layouts.get("data_layer","association_pvalues",{id:"associationcredibleset",namespace:{assoc:"assoc",credset:"credset",ld:"ld"},data_operations:[{type:"fetch",from:["assoc","ld(assoc)","credset(assoc)"]},{type:"left_match",name:"credset_plus_ld",requires:["credset","ld"],params:["assoc:position","ld:position2"]}],fill_opacity:.7,tooltip:t.Layouts.get("tooltip","association_credible_set"),match:{send:"assoc:variant",receive:"assoc:variant"}});return e.color.unshift({field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#FFf000"}}),e}();t.Layouts.add("data_layer","association_credible_set",a);const i={namespace:{assoc:"assoc",credset:"credset"},data_operations:[{type:"fetch",from:["assoc","credset(assoc)"]}],id:"annotationcredibleset",type:"annotation_track",id_field:"assoc:variant",x_axis:{field:"assoc:position"},color:[{field:"lz_is_match",scale_function:"if",parameters:{field_value:!0,then:"#001cee"}},"#00CC00"],match:{send:"assoc:variant",receive:"assoc:variant"},filters:[{field:"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:t.Layouts.get("tooltip","annotation_credible_set"),tooltip_positioning:"top"};t.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:70},inner_border:"rgb(210, 210, 210)",toolbar:t.Layouts.get("toolbar","standard_panel"),axes:{x:{extent:"state",render:!1}},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[t.Layouts.get("data_layer","annotation_credible_set")]};t.Layouts.add("panel","annotation_credible_set",n);const s=function(){const e=t.Layouts.get("panel","association",{id:"associationcrediblesets",data_layers:[t.Layouts.get("data_layer","significance"),t.Layouts.get("data_layer","recomb_rate"),t.Layouts.get("data_layer","association_credible_set")]});return e.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:"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:"credset:contrib_fraction",scale_function:"if",parameters:{field_value:0,then:"#777777"}},{scale_function:"interpolate",field:"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"}]}}]}),e}();t.Layouts.add("panel","association_credible_set",s);const l={state:{},width:800,height:450,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:t.Layouts.get("toolbar","standard_association"),panels:[t.Layouts.get("panel","association_credible_set"),t.Layouts.get("panel","annotation_credible_set"),t.Layouts.get("panel","genes")]};t.Layouts.add("plot","association_credible_set",l)}"undefined"!=typeof LocusZoom&&LocusZoom.use(t);const a=t})(),LzCredibleSets=o.default})(); //# sourceMappingURL=lz-credible-sets.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-credible-sets.min.js.map b/dist/ext/lz-credible-sets.min.js.map index 8d480d88..88afad00 100644 --- a/dist/ext/lz-credible-sets.min.js.map +++ b/dist/ext/lz-credible-sets.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/external \"gwasCredibleSets\"","webpack://[name]/./esm/ext/lz-credible-sets.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","gwasCredibleSets","install","LocusZoom","BaseAdapter","Adapters","add","config","super","arguments","this","dependentSource","parseInit","params","fields","log_pvalue","Error","constructor","SOURCE_NAME","assign","threshold","significance_threshold","state","chain","credible_set_threshold","chr","start","end","join","body","length","Promise","resolve","self","nlogpvals","map","item","some","val","credset_data","scores","scoring","posteriorProbabilities","credibleSet","marking","credSetScaled","credSetBool","i","push","posterior_prob","contrib_fraction","is_member","e","console","error","data","outnames","trans","src","dest","keys","forEach","attr","association_credible_set_tooltip","l","Layouts","unnamespaced","html","namespace","closable","show","or","hide","and","association_credible_set_layer","base","id","fill_opacity","tooltip","match","send","receive","color","unshift","field","scale_function","parameters","field_value","then","annotation_credible_set_layer","type","id_field","x_axis","filters","operator","value","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip_positioning","annotation_credible_set","title","text","x","style","min_height","height","margin","top","right","bottom","left","inner_border","toolbar","axes","extent","render","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","data_layers","association_credible_set_panel","widgets","position","button_html","button_title","layer_name","default_config_display_name","options","display_name","display","point_shape","point_size","else","legend","shape","size","label","class","breaks","values","association_credible_set_plot","width","responsive_resize","min_region_scale","max_region_scale","panels","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,4BCAlF,MAAM,EAA+BI,iBCmCrC,SAASC,EAASC,GACd,MAAMC,EAAcD,EAAUE,SAASV,IAAI,eAwG3CQ,EAAUE,SAASC,IAAI,gBA/FvB,cAA4BF,EAUxB,YAAYG,GACRC,SAASC,WACTC,KAAKC,iBAAkB,EAG3B,UAAUJ,GAEN,GADAC,M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AAM,GACNC,MAAO,oBACPC,MAAO,+BAQ5BhF,EA7G4B,GA+GvC7D,EAAU8D,QAAQ3D,IAAI,QAAS,2BAA4ByH,GAQ3D,MAAMoB,EAAgC,CAClC7H,MAAO,GACP8H,MAAO,IACPrC,OAAQ,IACRsC,mBAAmB,EACnBC,iBAAkB,IAClBC,iBAAkB,IAClBjC,QAASnH,EAAU8D,QAAQtE,IAAI,UAAW,uBAAwB,CAAEuE,cAAc,IAClFsF,OAAQ,CACJrJ,EAAU8D,QAAQtE,IAAI,QAAS,2BAA4B,CAAEuE,cAAc,IAC3E/D,EAAU8D,QAAQtE,IAAI,QAAS,0BAA2B,CAAEuE,cAAc,IAC1E/D,EAAU8D,QAAQtE,IAAI,QAAS,QAAS,CAAEuE,cAAc,MAGhE/D,EAAU8D,QAAQ3D,IAAI,OAAQ,2BAA4B6I,GAIrC,oBAAdhJ,WAGPA,UAAUsJ,IAAIvJ,GAIlB,U","file":"ext/lz-credible-sets.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__ = gwasCredibleSets;","/**\n * Custom code used to power credible sets demonstration example. This is not part of the core LocusZoom library,\n * but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~CredibleSetLZ}\n * * {@link module:LocusZoom_Layouts~association_credible_set_tooltip}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set_tooltip}\n * * {@link module:LocusZoom_Layouts~association_credible_set}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set_layer}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set}\n * * {@link module:LocusZoom_Layouts~association_credible_set}\n * * {@link module:LocusZoom_Layouts~association_credible_set_plot}\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - LocusZoom\n * - gwas-credible-sets (available via NPM or a related CDN)\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import credibleSets from 'locuszoom/esm/ext/lz-credible-sets';\n * LocusZoom.use(credibleSets);\n * ```\n @module\n*/\n\nimport {marking, scoring} from 'gwas-credible-sets';\n\nfunction install (LocusZoom) {\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n\n /**\n * (**extension**) Custom data adapter that calculates the 95% credible set based on provided association data.\n * This source must be requested as the second step in a chain, after a previous step that returns fields required\n * for the calculation. (usually, it follows a request for GWAS summary statistics)\n * @alias module:LocusZoom_Adapters~CredibleSetLZ\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n class CredibleSetLZ extends BaseAdapter {\n /**\n * @param {String} config.params.fields.log_pvalue The name of the field containing -log10 pvalue information\n * @param {Number} [config.params.threshold=0.95] The credible set threshold (eg 95%). Will continue selecting SNPs\n * until the posterior probabilities add up to at least this fraction of the total.\n * @param {Number} [config.params.significance_threshold=7.301] Do not perform a credible set calculation for this\n * region unless AT LEAST ONE SNP (as -log10p) exceeds the line of GWAS signficance. Otherwise we are declaring a\n * credible set when there is no evidence of anything being significant at all. If one snp is significant, it will\n * create a credible set for the entire region; the resulting set may include things below the line of significance.\n */\n constructor(config) {\n super(...arguments);\n this.dependentSource = true; // Don't do calcs for a region with no assoc data\n }\n\n parseInit(config) {\n super.parseInit(...arguments);\n if (!(this.params.fields && this.params.fields.log_pvalue)) {\n throw new Error(`Source config for ${this.constructor.SOURCE_NAME} must specify how to find 'fields.log_pvalue'`);\n }\n\n // Set defaults. Default sig threshold is the line of GWAS significance. (as -log10p)\n this.params = Object.assign(\n { threshold: 0.95, significance_threshold: 7.301 },\n this.params\n );\n }\n\n getCacheKey (state, chain, fields) {\n const threshold = state.credible_set_threshold || this.params.threshold;\n return [threshold, state.chr, state.start, state.end].join('_');\n }\n\n fetchRequest(state, chain) {\n if (!chain.body.length) {\n // No credible set can be calculated because there is no association data for this region\n return Promise.resolve([]);\n }\n\n const self = this;\n // The threshold can be overridden dynamically via `plot.state`, or set when the source is created\n const threshold = state.credible_set_threshold || this.params.threshold;\n // Calculate raw bayes factors and posterior probabilities based on information returned from the API\n if (typeof chain.body[0][self.params.fields.log_pvalue] === 'undefined') {\n throw new Error('Credible set source could not locate the required fields from a previous request.');\n }\n const nlogpvals = chain.body.map((item) => item[self.params.fields.log_pvalue]);\n\n if (!nlogpvals.some((val) => val >= self.params.significance_threshold)) {\n // If NO points have evidence of significance, define the credible set to be empty\n // (rather than make a credible set that we don't think is meaningful)\n return Promise.resolve([]);\n }\n\n const credset_data = [];\n try {\n const scores = scoring.bayesFactors(nlogpvals);\n const posteriorProbabilities = scoring.normalizeProbabilities(scores);\n\n // Use scores to mark the credible set in various ways (depending on your visualization preferences,\n // some of these may not be needed)\n const credibleSet = marking.findCredibleSet(posteriorProbabilities, threshold);\n const credSetScaled = marking.rescaleCredibleSet(credibleSet);\n const credSetBool = marking.markBoolean(credibleSet);\n\n // Annotate each response record based on credible set membership\n for (let i = 0; i < chain.body.length; i++) {\n credset_data.push({\n posterior_prob: posteriorProbabilities[i],\n contrib_fraction: credSetScaled[i],\n is_member: credSetBool[i],\n });\n }\n } catch (e) {\n // If the calculation cannot be completed, return the data without annotation fields\n console.error(e);\n }\n return Promise.resolve(credset_data);\n }\n\n combineChainBody(data, chain, fields, outnames, trans) {\n // At this point namespacing has been applied; add the calculated fields for this source to the chain\n if (chain.body.length && data.length) {\n for (let i = 0; i < data.length; i++) {\n const src = data[i];\n const dest = chain.body[i];\n Object.keys(src).forEach(function (attr) {\n dest[attr] = src[attr];\n });\n }\n }\n return chain.body;\n }\n }\n\n LocusZoom.Adapters.add('CredibleSetLZ', CredibleSetLZ);\n\n // Add related layouts to the central global registry\n /**\n * (**extension**) Tooltip layout that appends credible set posterior probability to the default association tooltip (for SNPs in the credible set)\n * @alias module:LocusZoom_Layouts~association_credible_set_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_tooltip = function () {\n // Extend a known tooltip with an extra row of info showing posterior probabilities\n const l = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true });\n l.html += '{{#if {{namespace[credset]}}posterior_prob}}
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}{{/if}}';\n return l;\n }();\n\n LocusZoom.Layouts.add('tooltip', 'association_credible_set', association_credible_set_tooltip);\n\n /**\n * (**extension**) A tooltip layout for annotation (rug) tracks that provides information about credible set members\n * @alias module:LocusZoom_Layouts~annotation_credible_set_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set_tooltip = {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[assoc]}}variant|htmlescape}}
'\n + 'P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
' +\n '{{#if {{namespace[credset]}}posterior_prob}}
Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}{{/if}}',\n };\n LocusZoom.Layouts.add('tooltip', 'annotation_credible_set', annotation_credible_set_tooltip);\n\n /**\n * (**extension**) A data layer layout that shows GWAS summary statistics overlaid with credible set membership information\n * @alias module:LocusZoom_Layouts~association_credible_set_layer\n * @type data_layer\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n\n const association_credible_set_layer = function () {\n const base = LocusZoom.Layouts.get('data_layer', 'association_pvalues', {\n unnamespaced: true,\n id: 'associationcredibleset',\n namespace: { 'assoc': 'assoc', 'credset': 'credset', 'ld': 'ld' },\n fill_opacity: 0.7,\n tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set', { unnamespaced: true }),\n fields: [\n '{{namespace[assoc]}}variant', '{{namespace[assoc]}}position',\n '{{namespace[assoc]}}log_pvalue', '{{namespace[assoc]}}log_pvalue|logtoscinotation',\n '{{namespace[assoc]}}ref_allele',\n '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction',\n '{{namespace[credset]}}is_member',\n '{{namespace[ld]}}state', '{{namespace[ld]}}isrefvar',\n ],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n });\n base.color.unshift({\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#FFf000',\n },\n });\n return base;\n }();\n LocusZoom.Layouts.add('data_layer', 'association_credible_set', association_credible_set_layer);\n\n /**\n * (**extension**) A data layer layout that shows a vertical mark whenever a SNP is a member of the credible set\n * @alias module:LocusZoom_Layouts~annotation_credible_set_layer\n * @type data_layer\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set_layer = {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n id: 'annotationcredibleset',\n type: 'annotation_track',\n id_field: '{{namespace[assoc]}}variant',\n x_axis: {\n field: '{{namespace[assoc]}}position',\n },\n color: [\n {\n field: 'lz_is_match', // Special field name whose presence triggers custom rendering\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#001cee',\n },\n },\n '#00CC00',\n ],\n fields: ['{{namespace[assoc]}}variant', '{{namespace[assoc]}}position', '{{namespace[assoc]}}log_pvalue', '{{namespace[credset]}}posterior_prob', '{{namespace[credset]}}contrib_fraction', '{{namespace[credset]}}is_member'],\n match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' },\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: '{{namespace[credset]}}is_member', operator: '=', value: true },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set', { unnamespaced: true }),\n tooltip_positioning: 'top',\n };\n LocusZoom.Layouts.add('data_layer', 'annotation_credible_set', annotation_credible_set_layer);\n\n /**\n * (**extension**) A panel layout that shows a vertical mark whenever a SNP is a member of the credible set\n * @alias module:LocusZoom_Layouts~annotation_credible_set\n * @type panel\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set = {\n id: 'annotationcredibleset',\n title: { text: 'SNPs in 95% credible set', x: 50, style: { 'font-size': '14px' } },\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: LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true }),\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 LocusZoom.Layouts.get('data_layer', 'annotation_credible_set', { unnamespaced: true }),\n ],\n };\n LocusZoom.Layouts.add('panel', 'annotation_credible_set', annotation_credible_set);\n\n /**\n * (**extension**) A panel layout that shows GWAS summary statistics in a standard LocusZoom view, overlaid with credible set membership information\n * @alias module:LocusZoom_Layouts~association_credible_set\n * @type panel\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_panel = function () {\n const l = LocusZoom.Layouts.get('panel', 'association', {\n unnamespaced: true,\n id: 'associationcrediblesets',\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'significance', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'recomb_rate', { unnamespaced: true }),\n LocusZoom.Layouts.get('data_layer', 'association_credible_set', { unnamespaced: true }),\n ],\n });\n // Add \"display options\" button to control how credible set coloring is overlaid on the standard association plot\n l.toolbar.widgets.push(\n {\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n layer_name: 'associationcredibleset',\n default_config_display_name: 'Linkage Disequilibrium (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: '95% credible set (boolean)', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n point_shape: 'circle',\n point_size: 40,\n color: {\n field: '{{namespace[credset]}}is_member',\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#00CC00',\n else: '#CCCCCC',\n },\n },\n legend: [ // Tells the legend how to represent this display option\n {\n shape: 'circle',\n color: '#00CC00',\n size: 40,\n label: 'In credible set',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#CCCCCC',\n size: 40,\n label: 'Not in credible set',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n {\n // Second option. The same plot- or even the same field- can be colored in more than one way.\n display_name: '95% credible set (gradient by contribution)',\n display: {\n point_shape: 'circle',\n point_size: 40,\n color: [\n {\n field: '{{namespace[credset]}}contrib_fraction',\n scale_function: 'if',\n parameters: {\n field_value: 0,\n then: '#777777',\n },\n },\n {\n scale_function: 'interpolate',\n field: '{{namespace[credset]}}contrib_fraction',\n parameters: {\n breaks: [0, 1],\n values: ['#fafe87', '#9c0000'],\n },\n },\n ],\n legend: [\n {\n shape: 'circle',\n color: '#777777',\n size: 40,\n label: 'No contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#fafe87',\n size: 40,\n label: 'Some contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#9c0000',\n size: 40,\n label: 'Most contribution',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n ],\n }\n );\n return l;\n }();\n LocusZoom.Layouts.add('panel', 'association_credible_set', association_credible_set_panel);\n\n /**\n * (**extension**) A standard LocusZoom plot layout, with additional credible set information.\n * @alias module:LocusZoom_Layouts~association_credible_set_plot\n * @type plot\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_plot = {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }),\n panels: [\n LocusZoom.Layouts.get('panel', 'association_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'annotation_credible_set', { unnamespaced: true }),\n LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true }),\n ],\n };\n LocusZoom.Layouts.add('plot', 'association_credible_set', association_credible_set_plot);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/../../../../../webpack/universalModuleDefinition","webpack://[name]/../../../../../webpack/bootstrap 069b89435249357eaca3","webpack://[name]/../../../../../src/app/stats.js","webpack://[name]/../../../../../src/app/gwas-credible-sets.js","webpack://[name]/../../../../../src/app/scoring.js","webpack://[name]/../../../../../src/app/marking.js","webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/compat get default export","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/./esm/ext/lz-credible-sets.js"],"names":["factory","module","Object","prototype","hasOwnProperty","call","object","property","ninv","p","a","b","c","d","e","f","q","r","x","Math","abs","sqrt","log","rollup","scoring","stats","marking","_nlogp_to_z2","nlogp","pow","bayesFactors","nlogpvals","cap","Array","isArray","length","z2_2","map","item","capValue","max","exp","normalizeProbabilities","scores","sumValues","reduce","findCredibleSet","probs","cutoff","Number","isNaN","statsTotal","sortedStatsMap","index","sort","runningTotal","result","fill","i","value","score","markBoolean","credibleSetMembers","rescaleCredibleSet","sumMarkers","exports","__webpack_module_cache__","__webpack_require__","moduleId","__webpack_modules__","n","getter","__esModule","definition","key","o","defineProperty","enumerable","get","obj","prop","install","LocusZoom","BaseUMAdapter","Adapters","add","config","super","arguments","this","_config","assign","threshold","significance_threshold","_prefix_namespace","state","credible_set_threshold","chr","start","end","join","options","assoc_data","base","_buildRequestOptions","_assoc_data","Promise","resolve","assoc_logp_name","_findPrefixedKey","some","val","posteriorProbabilities","credibleSet","credSetScaled","credSetBool","_provider_name","console","error","association_credible_set_tooltip","l","Layouts","html","closable","show","or","hide","and","association_credible_set_layer","id","namespace","data_operations","type","from","name","requires","params","fill_opacity","tooltip","match","send","receive","color","unshift","field","scale_function","parameters","field_value","then","annotation_credible_set_layer","id_field","x_axis","filters","operator","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip_positioning","annotation_credible_set","title","text","style","min_height","height","margin","top","right","bottom","left","inner_border","toolbar","axes","extent","render","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","data_layers","association_credible_set_panel","widgets","push","position","button_html","button_title","layer_name","default_config_display_name","display_name","display","point_shape","point_size","else","legend","shape","size","label","class","breaks","values","association_credible_set_plot","width","responsive_resize","min_region_scale","max_region_scale","panels","use"],"mappings":";gDAAA,IAAiDA,IASxC,WACT,O,YCTA,SAGA,cAGA,QACA,oBAGA,YACA,IACA,KACA,YAUA,OANA,mCAGA,OAGA,UAqCA,OAhCA,MAGA,MAGA,oBACA,UACA,2BACA,gBACA,cACA,SAMA,gBACA,sBACA,WAA4B,OAAOC,EAAgB,SACnD,WAAkC,OAAOA,GAEzC,OADA,aACA,GAIA,kBAAuD,OAAOC,OAAOC,UAAUC,eAAeC,KAAKC,EAAQC,IAG3G,OAGA,S;;;;;A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AO,yBAEX,CACIH,MAAO,SACPxD,MAAO,UACPyD,KAAM,GACNC,MAAO,oBACPC,MAAO,yBAEX,CACIH,MAAO,SACPxD,MAAO,UACPyD,KAAM,GACNC,MAAO,oBACPC,MAAO,+BAQ5BjF,EA3G4B,GA6GvCtC,EAAUuC,QAAQpC,IAAI,QAAS,2BAA4BmG,GAQ3D,MAAMoB,EAAgC,CAClC7G,MAAO,GACP8G,MAAO,IACPrC,OAAQ,IACRsC,mBAAmB,EACnBC,iBAAkB,IAClBC,iBAAkB,IAClBjC,QAAS7F,EAAUuC,QAAQ3C,IAAI,UAAW,wBAC1CmI,OAAQ,CACJ/H,EAAUuC,QAAQ3C,IAAI,QAAS,4BAC/BI,EAAUuC,QAAQ3C,IAAI,QAAS,2BAC/BI,EAAUuC,QAAQ3C,IAAI,QAAS,WAGvCI,EAAUuC,QAAQpC,IAAI,OAAQ,2BAA4BuH,GAIrC,oBAAd1H,WAGPA,UAAUgI,IAAIjI,GAIlB,W","file":"ext/lz-credible-sets.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"gwasCredibleSets\"] = factory();\n\telse\n\t\troot[\"gwasCredibleSets\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 1);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 069b89435249357eaca3","/** \n * @module stats \n * @license MIT\n * */\n\n/**\n * The inverse of the standard normal CDF. May be used to determine the Z-score for the desired quantile.\n *\n * This is an implementation of algorithm AS241:\n * https://www.jstor.org/stable/2347330\n * \n * @param {number} p The desired quantile of the standard normal distribution.\n * @returns {number}\n */\nfunction ninv(p) {\n const SPLIT1 = 0.425;\n const SPLIT2 = 5.0;\n const CONST1 = 0.180625;\n const CONST2 = 1.6;\n const a = [\n 3.3871328727963666080E0,\n 1.3314166789178437745E2,\n 1.9715909503065514427E3,\n 1.3731693765509461125E4,\n 4.5921953931549871457E4,\n 6.7265770927008700853E4,\n 3.3430575583588128105E4,\n 2.5090809287301226727E3\n ];\n\n const b = [\n 4.2313330701600911252E1,\n 6.8718700749205790830E2,\n 5.3941960214247511077E3,\n 2.1213794301586595867E4,\n 3.9307895800092710610E4,\n 2.8729085735721942674E4,\n 5.2264952788528545610E3\n ];\n\n const c = [\n 1.42343711074968357734E0,\n 4.63033784615654529590E0,\n 5.76949722146069140550E0,\n 3.64784832476320460504E0,\n 1.27045825245236838258E0,\n 2.41780725177450611770E-1,\n 2.27238449892691845833E-2,\n 7.74545014278341407640E-4\n ];\n\n const d = [\n 2.05319162663775882187E0,\n 1.67638483018380384940E0,\n 6.89767334985100004550E-1,\n 1.48103976427480074590E-1,\n 1.51986665636164571966E-2,\n 5.47593808499534494600E-4,\n 1.05075007164441684324E-9\n ];\n\n const e = [\n 6.65790464350110377720E0,\n 5.46378491116411436990E0,\n 1.78482653991729133580E0,\n 2.96560571828504891230E-1,\n 2.65321895265761230930E-2,\n 1.24266094738807843860E-3,\n 2.71155556874348757815E-5,\n 2.01033439929228813265E-7\n ];\n\n const f = [\n 5.99832206555887937690E-1,\n 1.36929880922735805310E-1,\n 1.48753612908506148525E-2,\n 7.86869131145613259100E-4,\n 1.84631831751005468180E-5,\n 1.42151175831644588870E-7,\n 2.04426310338993978564E-15\n ];\n\n const q = p - 0.5;\n let r, x;\n\n if (Math.abs(q) < SPLIT1) {\n r = CONST1 - q * q;\n return q * ((((((( a[7] * r + a[6] ) * r + a[5] ) * r + a[4] ) * r\n + a[3] ) * r + a[2] ) * r + a[1] ) * r + a[0] ) /\n ((((((( b[6] * r + b[5] ) * r + b[4] ) * r + b[3] ) * r\n + b[2] ) * r + b[1] ) * r + b[0] ) * r + 1.0 );\n }\n else {\n if (q < 0) {\n r = p\n }\n else {\n r = 1.0 - p\n }\n\n if (r > 0) {\n r = Math.sqrt(-Math.log(r));\n if (r <= SPLIT2) {\n r -= CONST2;\n x = ((((((( c[7] * r + c[6] ) * r + c[5] ) * r + c[4] ) * r\n + c[3] ) * r + c[2] ) * r + c[1] ) * r + c[0] ) /\n ((((((( d[6] * r + d[5] ) * r + d[4] ) * r + d[3] ) * r\n + d[2] ) * r + d[1] ) * r + d[0] ) * r + 1.0 );\n }\n else {\n r -= SPLIT2;\n x = ((((((( e[7] * r + e[6] ) * r + e[5] ) * r + e[4] ) * r\n + e[3] ) * r + e[2] ) * r + e[1] ) * r + e[0] ) /\n ((((((( f[6] * r + f[5] ) * r + f[4] ) * r + f[3] ) * r\n + f[2] ) * r + f[1] ) * r + f[0] ) * r + 1.0 );\n }\n }\n else {\n throw('Not implemented')\n }\n\n if (q < 0) {\n x = -x\n }\n\n return x;\n }\n}\n\n// Hack: A single global object representing the contents of the module\nconst rollup = { ninv };\n\nexport { ninv };\nexport default rollup;\n\n\n\n// WEBPACK FOOTER //\n// ./src/app/stats.js","/** \n * Functions for calculating credible sets and Bayes factors from\n * genome-wide association study (GWAS) results. \n * @module gwas-credible-sets \n * @license MIT\n */\n\nimport stats from './stats';\nimport scoring from './scoring';\nimport marking from './marking';\n\n// HACK: Because a primary audience is targets that do not have any module system, we will expose submodules from the\n// top-level module. (by representing each sub-module as a \"rollup object\" that exposes its internal methods)\n// Then, submodules may be accessed as `window.gwasCredibleSets.stats`, etc\n\n// If you are using a real module system, please import from sub-modules directly- these global helpers are a bit of\n// a hack and may go away in the future\nexport { scoring, stats, marking };\n\n\n\n// WEBPACK FOOTER //\n// ./src/app/gwas-credible-sets.js","/** \n * @module scoring \n * @license MIT\n */\n\nimport { ninv } from './stats';\n\n\n/**\n * Convert a -log10 p-value to Z^2.\n *\n * Very large -log10 p-values (very small p-values) cannot be converted to a Z-statistic directly in the browser due to\n * limitations in javascript (64-bit floats.) These values are handled using an approximation:\n * for small p-values, Z_i^2 has a linear relationship with -log10 p-value.\n *\n * The approximation begins for -log10 p-values >= 300.\n *\n * @param nlogp\n * @return {number}\n * @private\n */\nfunction _nlogp_to_z2(nlogp) {\n const p = Math.pow(10, -nlogp);\n if (nlogp < 300) {\n // Use exact method when within the range of 64-bit floats (approx 10^-323)\n return Math.pow(ninv(p / 2), 2);\n }\n else {\n // For very small p-values, -log10(pval) and Z^2 have a linear relationship\n // This avoids issues with needing higher precision floats when doing the calculation\n // with ninv\n return (4.59884133027944 * nlogp) - 5.88085867031722\n }\n}\n\n/**\n * Calculate a Bayes factor exp(Z^2 / 2) based on p-values. If the Z-score is very large, the Bayes factors\n * are calculated in an inexact (capped) manner that makes the calculation tractable but preserves comparisons.\n * @param {Number[]} nlogpvals An array of -log10(p-value) entries\n * @param {Boolean} [cap=true] Whether to apply an inexact method. If false, some values in the return array may\n * be represented as \"Infinity\", but the Bayes factors will be directly calculated wherever possible.\n * @return {Number[]} An array of exp(Z^2 / 2) statistics\n */\nfunction bayesFactors(nlogpvals, cap=true) {\n if (!Array.isArray(nlogpvals) || ! nlogpvals.length) {\n throw 'Must provide a non-empty array of pvalues';\n }\n\n // 1. Convert the pvalues to Z^2 / 2 values. Divide by 2 before applying the cap, because it means fewer values will\n // need to be truncated. This does affect some of the raw bayes factors that are returned (when a cap is needed),\n // but the resulting credible set contents / posterior probabilities are unchanged.\n let z2_2 = nlogpvals.map(item => _nlogp_to_z2(item) / 2);\n\n // 2. Calculate bayes factor, using a truncation approach that prevents overrunning the max float64 value\n // (when Z^2 / 2 > 709 or so). As safeguard, we could (but currently don't) check that exp(Z^2 / 2) is not larger\n // than infinity.\n if (cap) {\n const capValue = Math.max(...z2_2) - 708; // The real cap is ~709; this should prevent any value from exceeding it\n if (capValue > 0) {\n z2_2 = z2_2.map(item => (item - capValue));\n }\n }\n return z2_2.map(item => Math.exp(item));\n}\n\n/**\n * Normalize so that sum of all elements = 1.0. This method must be applied to bayes factors before calculating any\n * credible set.\n *\n * @param {Number[]} scores An array of probability scores for all elements in the range\n * @returns {Number[]} Posterior probabilities\n */\nfunction normalizeProbabilities(scores) {\n const sumValues = scores.reduce((a, b) => a + b, 0);\n return scores.map(item => item / sumValues);\n}\n\nconst rollup = { bayesFactors, normalizeProbabilities };\nexport default rollup;\nexport { bayesFactors, normalizeProbabilities };\n\n// Export additional symbols for unit testing only (not part of public interface for the module)\nexport { _nlogp_to_z2 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/app/scoring.js","/**\n * @module marking\n * @license MIT\n */\n\n/**\n * Given an array of probabilities, determine which elements of the array fall within the X% credible set,\n * where X is the cutoff value.\n *\n * @param {Number[]} probs Calculated probabilities used to rank the credible set. This method will normalize the\n * provided input to ensure that the values sum to 1.0.\n * @param {Number} [cutoff=0.95] Keep taking items until we have accounted for >= this fraction of the total probability.\n * For example, 0.95 would represent the 95% credible set.\n * @return {Number[]} An array with posterior probabilities (for the items in the credible set), and zero for all\n * other elements. This array is the same length as the provided probabilities array.\n */\nfunction findCredibleSet(probs, cutoff=0.95) {\n // Type checking\n if (!Array.isArray(probs) || !probs.length) {\n throw 'Probs must be a non-empty array';\n }\n if (!(typeof cutoff === 'number' ) || cutoff < 0 || cutoff > 1.0 || Number.isNaN(cutoff)) {\n throw 'Cutoff must be a number between 0 and 1';\n }\n\n const statsTotal = probs.reduce((a, b) => a + b, 0);\n if (statsTotal <= 0) {\n throw 'Sum of provided probabilities must be > 0';\n }\n\n // Sort the probabilities by largest first, while preserving a map to original item order\n const sortedStatsMap = probs\n .map((item, index) => [item, index])\n .sort((a, b) => (b[0] - a[0]));\n\n let runningTotal = 0;\n const result = new Array(sortedStatsMap.length).fill(0);\n for (let i = 0; i < sortedStatsMap.length; i++) {\n let [value, index] = sortedStatsMap[i];\n if (runningTotal < cutoff) {\n // Convert from a raw score to posterior probability by dividing the item under consideration\n // by sum of all probabilities.\n const score = value / statsTotal;\n result[index] = score;\n runningTotal += score;\n } else {\n break;\n }\n }\n return result;\n}\n\n/**\n * Given a numeric [pre-calculated credible set]{@link #findCredibleSet}, return an array of booleans where true\n * denotes membership in the credible set.\n *\n * This is a helper method used when visualizing the members of the credible set by raw membership.\n *\n * @param {Number[]} credibleSetMembers An array indicating contributions to the credible set, where non-members are\n * represented by some falsy value.\n * @return {Boolean[]} An array of booleans identifying whether or not each item is in the credible set.\n * This array is the same length as the provided credible set array.\n */\nfunction markBoolean(credibleSetMembers) {\n return credibleSetMembers.map(item => !!item);\n}\n\n/**\n * Visualization helper method for rescaling data to a predictable output range, eg when range for a color gradient\n * must be specified in advance.\n *\n * Given an array of probabilities for items in a credible set, rescale the probabilities within only the credible\n * set to their total sum.\n *\n * Example for 95% credible set: [0.92, 0.06, 0.02] -> [0.938, 0.061, 0]. The first two elements here\n * belong to the credible set, the last element does not.\n *\n * @param {Number[]} credibleSetMembers Calculated probabilities used to rank the credible set.\n * @return {Number[]} The fraction of credible set probabilities each item accounts for.\n * This array is the same length as the provided credible set.\n */\nfunction rescaleCredibleSet(credibleSetMembers) {\n const sumMarkers = credibleSetMembers.reduce((a, b) => a + b, 0);\n return credibleSetMembers.map(item => item / sumMarkers);\n}\n\nconst rollup = { findCredibleSet, markBoolean, rescaleCredibleSet };\nexport default rollup;\nexport { findCredibleSet, markBoolean, rescaleCredibleSet };\n\n\n\n// WEBPACK FOOTER //\n// ./src/app/marking.js","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\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))","/**\n * Custom code used to power credible sets demonstration example. This is not part of the core LocusZoom library,\n * but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~CredibleSetLZ}\n * * {@link module:LocusZoom_Layouts~association_credible_set_tooltip}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set_tooltip}\n * * {@link module:LocusZoom_Layouts~association_credible_set}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set_layer}\n * * {@link module:LocusZoom_Layouts~annotation_credible_set}\n * * {@link module:LocusZoom_Layouts~association_credible_set}\n * * {@link module:LocusZoom_Layouts~association_credible_set_plot}\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import credibleSets from 'locuszoom/esm/ext/lz-credible-sets';\n * LocusZoom.use(credibleSets);\n * ```\n @module\n*/\n\nimport {marking, scoring} from 'gwas-credible-sets';\n\nfunction install (LocusZoom) {\n const BaseUMAdapter = LocusZoom.Adapters.get('BaseUMAdapter');\n\n /**\n * (**extension**) Custom data adapter that calculates the 95% credible set based on provided association data.\n * This source must be requested as the second step in a chain, after a previous step that returns fields required\n * for the calculation. (usually, it follows a request for GWAS summary statistics)\n * @alias module:LocusZoom_Adapters~CredibleSetLZ\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n class CredibleSetLZ extends BaseUMAdapter {\n /**\n * @param {Number} [config.params.threshold=0.95] The credible set threshold (eg 95%). Will continue selecting SNPs\n * until the posterior probabilities add up to at least this fraction of the total.\n * @param {Number} [config.params.significance_threshold=7.301] Do not perform a credible set calculation for this\n * region unless AT LEAST ONE SNP (as -log10p) exceeds the line of GWAS signficance. Otherwise we are declaring a\n * credible set when there is no evidence of anything being significant at all. If one snp is significant, it will\n * create a credible set for the entire region; the resulting set may include things below the line of significance.\n */\n constructor(config) {\n super(...arguments);\n // Set defaults. Default sig threshold is the line of GWAS significance. (as -log10p)\n this._config = Object.assign(\n { threshold: 0.95, significance_threshold: 7.301 },\n this._config,\n );\n this._prefix_namespace = false;\n }\n\n _getCacheKey (state) {\n const threshold = state.credible_set_threshold || this._config.threshold;\n return [threshold, state.chr, state.start, state.end].join('_');\n }\n\n _buildRequestOptions(options, assoc_data) {\n const base = super._buildRequestOptions(...arguments);\n base._assoc_data = assoc_data;\n return base;\n }\n\n _performRequest(options) {\n const {_assoc_data} = options;\n if (!_assoc_data.length) {\n // No credible set can be calculated because there is no association data for this region\n return Promise.resolve([]);\n }\n\n const assoc_logp_name = this._findPrefixedKey(_assoc_data[0], 'log_pvalue');\n\n const threshold = this._config.threshold;\n\n // Calculate raw bayes factors and posterior probabilities based on information returned from the API\n const nlogpvals = _assoc_data.map((item) => item[assoc_logp_name]);\n\n if (!nlogpvals.some((val) => val >= this._config.significance_threshold)) {\n // If NO points have evidence of significance, define the credible set to be empty\n // (rather than make a credible set that we don't think is meaningful)\n return Promise.resolve(_assoc_data);\n }\n\n try {\n const scores = scoring.bayesFactors(nlogpvals);\n const posteriorProbabilities = scoring.normalizeProbabilities(scores);\n\n // Use scores to mark the credible set in various ways (depending on your visualization preferences,\n // some of these may not be needed)\n const credibleSet = marking.findCredibleSet(posteriorProbabilities, threshold);\n const credSetScaled = marking.rescaleCredibleSet(credibleSet);\n const credSetBool = marking.markBoolean(credibleSet);\n\n // Annotate each response record based on credible set membership. This has the effect of joining\n // credset results to assoc data directly within the adapter (no separate join needed)\n for (let i = 0; i < _assoc_data.length; i++) {\n _assoc_data[i][`${options._provider_name}:posterior_prob`] = posteriorProbabilities[i];\n _assoc_data[i][`${options._provider_name}:contrib_fraction`] = credSetScaled[i];\n _assoc_data[i][`${options._provider_name}:is_member`] = credSetBool[i];\n }\n } catch (e) {\n // If the calculation cannot be completed, return the data without annotation fields\n console.error(e);\n }\n return Promise.resolve(_assoc_data);\n }\n }\n\n LocusZoom.Adapters.add('CredibleSetLZ', CredibleSetLZ);\n\n // Add related layouts to the central global registry\n /**\n * (**extension**) Tooltip layout that appends credible set posterior probability to the default association tooltip (for SNPs in the credible set)\n * @alias module:LocusZoom_Layouts~association_credible_set_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_tooltip = function () {\n // Extend a known tooltip with an extra row of info showing posterior probabilities\n const l = LocusZoom.Layouts.get('tooltip', 'standard_association');\n l.html += '{{#if credset:posterior_prob}}
Posterior probability: {{credset:posterior_prob|scinotation|htmlescape}}{{/if}}';\n return l;\n }();\n\n LocusZoom.Layouts.add('tooltip', 'association_credible_set', association_credible_set_tooltip);\n\n /**\n * (**extension**) A tooltip layout for annotation (rug) tracks that provides information about credible set members\n * @alias module:LocusZoom_Layouts~annotation_credible_set_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set_tooltip = {\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{assoc:variant|htmlescape}}
'\n + 'P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
' +\n '{{#if credset:posterior_prob}}
Posterior probability: {{credset:posterior_prob|scinotation|htmlescape}}{{/if}}',\n };\n LocusZoom.Layouts.add('tooltip', 'annotation_credible_set', annotation_credible_set_tooltip);\n\n /**\n * (**extension**) A data layer layout that shows GWAS summary statistics overlaid with credible set membership information\n * @alias module:LocusZoom_Layouts~association_credible_set_layer\n * @type data_layer\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n\n const association_credible_set_layer = function () {\n const base = LocusZoom.Layouts.get('data_layer', 'association_pvalues', {\n id: 'associationcredibleset',\n namespace: { 'assoc': 'assoc', 'credset': 'credset', 'ld': 'ld' },\n data_operations: [\n {\n type: 'fetch',\n from: ['assoc', 'ld(assoc)', 'credset(assoc)'],\n },\n {\n type: 'left_match',\n name: 'credset_plus_ld',\n requires: ['credset', 'ld'], // The credible sets demo wasn't fully moved over to the new data operations system, and as such it is a bit weird\n params: ['assoc:position', 'ld:position2'], // FIXME: old LZ used position, because it was less sensitive to format. We'd like to match assoc:variant = ld:variant2, but not every assoc source provides variant data in the way we need. This would need to be fixed via special formatting adjustment later.\n },\n ],\n fill_opacity: 0.7,\n tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set'),\n match: { send: 'assoc:variant', receive: 'assoc:variant' },\n });\n base.color.unshift({\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: '#FFf000',\n },\n });\n return base;\n }();\n LocusZoom.Layouts.add('data_layer', 'association_credible_set', association_credible_set_layer);\n\n /**\n * (**extension**) A data layer layout that shows a vertical mark whenever a SNP is a member of the credible set\n * @alias module:LocusZoom_Layouts~annotation_credible_set_layer\n * @type data_layer\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set_layer = {\n namespace: { 'assoc': 'assoc', 'credset': 'credset' },\n data_operations: [{\n type: 'fetch',\n from: ['assoc', 'credset(assoc)'],\n }],\n id: 'annotationcredibleset',\n type: 'annotation_track',\n id_field: 'assoc:variant',\n x_axis: {\n field: 'assoc:position',\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: '#001cee',\n },\n },\n '#00CC00',\n ],\n match: { send: 'assoc:variant', receive: 'assoc:variant' },\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: 'credset:is_member', operator: '=', value: true },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set'),\n tooltip_positioning: 'top',\n };\n LocusZoom.Layouts.add('data_layer', 'annotation_credible_set', annotation_credible_set_layer);\n\n /**\n * (**extension**) A panel layout that shows a vertical mark whenever a SNP is a member of the credible set\n * @alias module:LocusZoom_Layouts~annotation_credible_set\n * @type panel\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const annotation_credible_set = {\n id: 'annotationcredibleset',\n title: { text: 'SNPs in 95% credible set', x: 50, style: { 'font-size': '14px' } },\n min_height: 50,\n height: 50,\n margin: { top: 25, right: 50, bottom: 10, left: 70 },\n inner_border: 'rgb(210, 210, 210)',\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_panel'),\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 LocusZoom.Layouts.get('data_layer', 'annotation_credible_set'),\n ],\n };\n LocusZoom.Layouts.add('panel', 'annotation_credible_set', annotation_credible_set);\n\n /**\n * (**extension**) A panel layout that shows GWAS summary statistics in a standard LocusZoom view, overlaid with credible set membership information\n * @alias module:LocusZoom_Layouts~association_credible_set\n * @type panel\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_panel = function () {\n const l = LocusZoom.Layouts.get('panel', 'association', {\n id: 'associationcrediblesets',\n data_layers: [\n LocusZoom.Layouts.get('data_layer', 'significance'),\n LocusZoom.Layouts.get('data_layer', 'recomb_rate'),\n LocusZoom.Layouts.get('data_layer', 'association_credible_set'),\n ],\n });\n // Add \"display options\" button to control how credible set coloring is overlaid on the standard association plot\n l.toolbar.widgets.push(\n {\n type: 'display_options',\n position: 'right',\n color: 'blue',\n // Below: special config specific to this widget\n button_html: 'Display options...',\n button_title: 'Control how plot items are displayed',\n layer_name: 'associationcredibleset',\n default_config_display_name: 'Linkage Disequilibrium (default)', // display name for the default plot color option (allow user to revert to plot defaults)\n\n options: [\n {\n // First dropdown menu item\n display_name: '95% credible set (boolean)', // Human readable representation of field name\n display: { // Specify layout directives that control display of the plot for this option\n point_shape: 'circle',\n point_size: 40,\n color: {\n field: 'credset:is_member',\n scale_function: 'if',\n parameters: {\n field_value: true,\n then: '#00CC00',\n else: '#CCCCCC',\n },\n },\n legend: [ // Tells the legend how to represent this display option\n {\n shape: 'circle',\n color: '#00CC00',\n size: 40,\n label: 'In credible set',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#CCCCCC',\n size: 40,\n label: 'Not in credible set',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n {\n // Second option. The same plot- or even the same field- can be colored in more than one way.\n display_name: '95% credible set (gradient by contribution)',\n display: {\n point_shape: 'circle',\n point_size: 40,\n color: [\n {\n field: 'credset:contrib_fraction',\n scale_function: 'if',\n parameters: {\n field_value: 0,\n then: '#777777',\n },\n },\n {\n scale_function: 'interpolate',\n field: 'credset:contrib_fraction',\n parameters: {\n breaks: [0, 1],\n values: ['#fafe87', '#9c0000'],\n },\n },\n ],\n legend: [\n {\n shape: 'circle',\n color: '#777777',\n size: 40,\n label: 'No contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#fafe87',\n size: 40,\n label: 'Some contribution',\n class: 'lz-data_layer-scatter',\n },\n {\n shape: 'circle',\n color: '#9c0000',\n size: 40,\n label: 'Most contribution',\n class: 'lz-data_layer-scatter',\n },\n ],\n },\n },\n ],\n },\n );\n return l;\n }();\n LocusZoom.Layouts.add('panel', 'association_credible_set', association_credible_set_panel);\n\n /**\n * (**extension**) A standard LocusZoom plot layout, with additional credible set information.\n * @alias module:LocusZoom_Layouts~association_credible_set_plot\n * @type plot\n * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions\n */\n const association_credible_set_plot = {\n state: {},\n width: 800,\n height: 450,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'),\n panels: [\n LocusZoom.Layouts.get('panel', 'association_credible_set'),\n LocusZoom.Layouts.get('panel', 'annotation_credible_set'),\n LocusZoom.Layouts.get('panel', 'genes'),\n ],\n };\n LocusZoom.Layouts.add('plot', 'association_credible_set', association_credible_set_plot);\n}\n\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/ext/lz-dynamic-urls.min.js b/dist/ext/lz-dynamic-urls.min.js index 5aad6d90..8e54453a 100644 --- a/dist/ext/lz-dynamic-urls.min.js +++ b/dist/ext/lz-dynamic-urls.min.js @@ -1,3 +1,3 @@ -/*! Locuszoom 0.13.4 */ +/*! Locuszoom 0.14.0 */ 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 01e5e2a5..0f3e8cb6 100644 --- a/dist/ext/lz-forest-track.min.js +++ b/dist/ext/lz-forest-track.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +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.confidence_intervals.start_field&&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=>{const{start_field:e,end_field:a}=this.layout.confidence_intervals,i=this.parent.x_scale,s=i(t[a])-i(t[e]);return Math.max(s,1)},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{confidence_intervals:i}=this.layout;if(i&&i.start_field&&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-forest-track.min.js.map b/dist/ext/lz-forest-track.min.js.map index f1907e8e..8d59dca6 100644 --- a/dist/ext/lz-forest-track.min.js.map +++ b/dist/ext/lz-forest-track.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/ext/lz-forest-track.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","install","LocusZoom","BaseDataLayer","DataLayers","default_layout","point_size","point_shape","color","fill_opacity","y_axis","axis","id_field","confidence_intervals","start_field","end_field","Forest","layout","Layouts","merge","super","arguments","tooltip","x_center","this","parent","x_scale","data","x_axis","field","y_scale","y_center","resolveScalableParameter","offset","Math","sqrt","PI","x_min","x_max","y_min","y_max","track_data","_applyFilters","fields","includes","ci_selection","svg","group","selectAll","d","ci_transform","x","y","isNaN","ci_width","ci_height","enter","append","attr","getElementId","height","exit","remove","points_selection","initial_y","shape","size","i","type","shape_name","factory_name","charAt","toUpperCase","slice","on","element_data","emit","applyBehaviors","bind","add","axis_config","ci_config","min","max","_getDataExtent","dimension","config","Error","category_field","id","map","item","index","text","field_to_add","floor","ceiling","length","use"],"mappings":";qCACA,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,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ChC,MAAM6E,EAAiBhE,KAAKP,OAAOP,OAAO8E,eAC1C,IAAKA,EACD,MAAM,IAAID,MAAM,cAAc/D,KAAKP,OAAOwE,kCAG9C,OAAOjE,KAAKG,KAAK+D,KAAI,CAACC,EAAMC,KAAU,CAAGxC,EAAGwC,EAAQ,EAAGC,KAAMF,EAAKH,OAElE,MAAO,GAIf,yBAGI,MAAMM,EAAetE,KAAKP,OAAOP,OAAOmB,MACxC,IAAKiE,EACD,MAAM,IAAIP,MAAM,cAAc/D,KAAKP,OAAOwE,+BAU9C,OAPAjE,KAAKG,KAAOH,KAAKG,KAAK+D,KAAI,CAACC,EAAMC,KAC7BD,EAAKG,GAAgBF,EAAQ,EACtBD,KAGXnE,KAAKP,OAAOP,OAAOqF,MAAQ,EAC3BvE,KAAKP,OAAOP,OAAOsF,QAAUxE,KAAKG,KAAKsE,OAAS,EACzCzE,QAQM,oBAAdtB,WAGPA,UAAUgG,IAAIjG,GAGlB,U","file":"ext/lz-forest-track.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 * Forest plot track, designed for use with PheWAS style datasets.\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_DataLayers~forest}\n * * {@link module:LocusZoom_DataLayers~category_forest}\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import ForestTrack from 'locuszoom/esm/ext/lz-forest-track';\n * LocusZoom.use(ForestTrack);\n * ```\n *\n * Then use the layouts made available by this extension. (see demos and documentation for guidance)\n *\n * @module\n */\nimport * as d3 from 'd3';\n\n\nfunction install (LocusZoom) {\n const BaseDataLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n const default_layout = {\n point_size: 40,\n point_shape: 'square',\n color: '#888888',\n fill_opacity: 1,\n y_axis: {\n axis: 2,\n },\n id_field: 'id',\n confidence_intervals: {\n start_field: 'ci_start',\n end_field: 'ci_end',\n },\n };\n\n /**\n * (**extension**) Forest Data Layer\n * Implements a standard forest plot. In order to space out points, any layout using this must specify axis ticks\n * and extent in advance.\n *\n * If you are using dynamically fetched data, consider using `category_forest` instead.\n * @alias module:LocusZoom_DataLayers~forest\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-forest-track} for required extension and installation instructions\n */\n class Forest 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='square'] 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 each point\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1] Opacity (0..1) for each datum point\n * @param {string} layout.x_axis.field A field specifying the x-coordinate of the mark (eg square)\n * @param {string} layout.y_axis.field A field specifying the y-coordinate. Use `category_forest` if you just want to\n * lay out a series of forest markings in order without worrying about this.\n * @param [layout.confidence_intervals.start_field='ci_start'] The field that specifies the start of confidence interval\n * @param [layout.confidence_intervals.end_field='ci_end'] The field that specifies the start of confidence interval\n */\n constructor(layout) {\n layout = LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n }\n\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n return {\n x_min: x_center - offset,\n x_max: x_center + offset,\n y_min: y_center - offset,\n y_max: y_center + offset,\n };\n }\n\n /**\n * @fires event:element_clicked\n */\n render() {\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n\n // Generate confidence interval paths if fields are defined\n if (this.layout.confidence_intervals\n && this.layout.fields.includes(this.layout.confidence_intervals.start_field)\n && this.layout.fields.includes(this.layout.confidence_intervals.end_field)) {\n // Generate a selection for all forest plot confidence intervals\n const ci_selection = this.svg.group\n .selectAll('rect.lz-data_layer-forest.lz-data_layer-forest-ci')\n .data(track_data, (d) => {\n return d[this.layout.id_field];\n });\n\n const ci_transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.confidence_intervals.start_field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n const ci_width = (d) => {\n return this.parent[x_scale](d[this.layout.confidence_intervals.end_field])\n - this.parent[x_scale](d[this.layout.confidence_intervals.start_field]);\n };\n const ci_height = 1;\n // Create confidence interval rect elements\n ci_selection.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-ci')\n .attr('id', (d) => `${this.getElementId(d)}_ci`)\n .attr('transform', `translate(0, ${isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height})`)\n .merge(ci_selection)\n .attr('transform', ci_transform)\n .attr('width', ci_width)\n .attr('height', ci_height);\n\n // Remove old elements as needed\n ci_selection.exit()\n .remove();\n }\n\n // Generate a selection for all forest plot points\n const points_selection = this.svg.group\n .selectAll('path.lz-data_layer-forest.lz-data_layer-forest-point')\n .data(track_data, (d) => {\n return d[this.layout.id_field];\n });\n\n // Create elements, apply class, ID, and initial position\n const initial_y = isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height;\n\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.x_axis.field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n\n const fill = (d, i) => this.resolveScalableParameter(this.layout.color, d, i);\n const fill_opacity = (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i);\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => {\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const shape_name = this.resolveScalableParameter(this.layout.point_shape, d, i);\n const factory_name = `symbol${shape_name.charAt(0).toUpperCase() + shape_name.slice(1)}`;\n return d3[factory_name] || null;\n });\n\n points_selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-point')\n .attr('id', (d) => this.getElementId(d))\n .attr('transform', `translate(0, ${initial_y})`)\n .merge(points_selection)\n .attr('transform', transform)\n .attr('fill', fill)\n .attr('fill-opacity', fill_opacity)\n .attr('d', shape);\n\n // Remove old elements as needed\n points_selection.exit()\n .remove();\n\n // Apply behaviors to points\n this.svg.group\n .on('click.event_emitter', (element_data) => {\n this.parent.emit('element_clicked', element_data, true);\n }).call(this.applyBehaviors.bind(this));\n }\n }\n\n /**\n * (**extension**) A y-aligned forest plot in which the y-axis represents item labels, which are dynamically\n * chosen when data is loaded. Each item is assumed to include both data and confidence intervals.\n * This allows generating forest plots without defining the layout in advance.\n * @alias module:LocusZoom_DataLayers~category_forest\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-forest-track} for required extension and installation instructions\n */\n class CategoryForest extends Forest {\n _getDataExtent(data, axis_config) {\n // In a forest plot, the data range is determined by *three* fields (beta + CI start/end)\n const ci_config = this.layout.confidence_intervals;\n if (ci_config\n && this.layout.fields.includes(ci_config.start_field)\n && this.layout.fields.includes(ci_config.end_field)) {\n const min = (d) => +d[ci_config.start_field];\n const max = (d) => +d[ci_config.end_field];\n return [d3.min(data, min), d3.max(data, max)];\n }\n\n // If there are no confidence intervals set, then range must depend only on a single field\n return super._getDataExtent(data, axis_config);\n }\n\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n\n // Design assumption: one axis (y1 or y2) has the ticks, and the layout says which to use\n // Also assumes that every tick gets assigned a unique matching label\n const axis_num = this.layout.y_axis.axis;\n if (dimension === (`y${axis_num}`)) {\n const category_field = this.layout.y_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n\n return this.data.map((item, index) => ({ y: index + 1, text: item[category_field] }));\n } else {\n return [];\n }\n }\n\n applyCustomDataMethods () {\n // Add a synthetic yaxis field to ensure data is spread out on plot. Then, set axis floor and ceiling to\n // correct extents.\n const field_to_add = this.layout.y_axis.field;\n if (!field_to_add) {\n throw new Error(`Layout for ${this.layout.id} must specify yaxis.field`);\n }\n\n this.data = this.data.map((item, index) => {\n item[field_to_add] = index + 1;\n return item;\n });\n // Update axis extents based on one label for every point (with a bit of padding above and below)\n this.layout.y_axis.floor = 0;\n this.layout.y_axis.ceiling = this.data.length + 1;\n return this;\n }\n }\n\n LocusZoom.DataLayers.add('forest', Forest);\n LocusZoom.DataLayers.add('category_forest', CategoryForest);\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\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/ext/lz-forest-track.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","install","LocusZoom","BaseDataLayer","DataLayers","default_layout","point_size","point_shape","color","fill_opacity","y_axis","axis","id_field","confidence_intervals","start_field","end_field","Forest","layout","Layouts","merge","super","arguments","tooltip","x_center","this","parent","x_scale","data","x_axis","field","y_scale","y_center","resolveScalableParameter","offset","Math","sqrt","PI","x_min","x_max","y_min","y_max","track_data","_applyFilters","ci_selection","svg","group","selectAll","d","ci_transform","x","y","isNaN","ci_width","scale","result","max","ci_height","enter","append","attr","getElementId","height","exit","remove","points_selection","initial_y","shape","size","i","type","shape_name","factory_name","charAt","toUpperCase","slice","on","element_data","emit","applyBehaviors","bind","add","axis_config","min","_getDataExtent","dimension","config","includes","Error","category_field","id","map","item","index","text","field_to_add","floor","ceiling","length","use"],"mappings":";qCACA,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,4BCAlF,MAAM,EAA+BI,GC+BrC,SAASC,EAASC,GACd,MAAMC,EAAgBD,EAAUE,WAAWV,IAAI,iBACzCW,EAAiB,CACnBC,WAAY,GACZC,YAAa,SACbC,MAAO,UACPC,aAAc,EACdC,OAAQ,CACJC,KAAM,GAEVC,SAAU,KACVC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OAPAjE,KAAKG,KAAOH,KAAKG,KAAK+D,KAAI,CAACC,EAAMC,KAC7BD,EAAKG,GAAgBF,EAAQ,EACtBD,KAGXnE,KAAKP,OAAOP,OAAOqF,MAAQ,EAC3BvE,KAAKP,OAAOP,OAAOsF,QAAUxE,KAAKG,KAAKsE,OAAS,EACzCzE,QAQM,oBAAdtB,WAGPA,UAAUgG,IAAIjG,GAGlB,U","file":"ext/lz-forest-track.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 * Forest plot track, designed for use with PheWAS style datasets.\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_DataLayers~forest}\n * * {@link module:LocusZoom_DataLayers~category_forest}\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import ForestTrack from 'locuszoom/esm/ext/lz-forest-track';\n * LocusZoom.use(ForestTrack);\n * ```\n *\n * Then use the layouts made available by this extension. (see demos and documentation for guidance)\n *\n * @module\n */\nimport * as d3 from 'd3';\n\n\nfunction install (LocusZoom) {\n const BaseDataLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n const default_layout = {\n point_size: 40,\n point_shape: 'square',\n color: '#888888',\n fill_opacity: 1,\n y_axis: {\n axis: 2,\n },\n id_field: 'id',\n confidence_intervals: {\n start_field: 'ci_start',\n end_field: 'ci_end',\n },\n };\n\n /**\n * (**extension**) Forest Data Layer\n * Implements a standard forest plot. In order to space out points, any layout using this must specify axis ticks\n * and extent in advance.\n *\n * If you are using dynamically fetched data, consider using `category_forest` instead.\n * @alias module:LocusZoom_DataLayers~forest\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-forest-track} for required extension and installation instructions\n */\n class Forest 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='square'] 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 each point\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1] Opacity (0..1) for each datum point\n * @param {string} layout.x_axis.field A field specifying the x-coordinate of the mark (eg square)\n * @param {string} layout.y_axis.field A field specifying the y-coordinate. Use `category_forest` if you just want to\n * lay out a series of forest markings in order without worrying about this.\n * @param [layout.confidence_intervals.start_field='ci_start'] The field that specifies the start of confidence interval\n * @param [layout.confidence_intervals.end_field='ci_end'] The field that specifies the start of confidence interval\n */\n constructor(layout) {\n layout = LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n }\n\n _getTooltipPosition(tooltip) {\n const x_center = this.parent.x_scale(tooltip.data[this.layout.x_axis.field]);\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n const y_center = this.parent[y_scale](tooltip.data[this.layout.y_axis.field]);\n\n const point_size = this.resolveScalableParameter(this.layout.point_size, tooltip.data);\n const offset = Math.sqrt(point_size / Math.PI);\n return {\n x_min: x_center - offset,\n x_max: x_center + offset,\n y_min: y_center - offset,\n y_max: y_center + offset,\n };\n }\n\n /**\n * @fires event:element_clicked\n */\n render() {\n // Apply filters to only render a specified set of points\n const track_data = this._applyFilters();\n\n const x_scale = 'x_scale';\n const y_scale = `y${this.layout.y_axis.axis}_scale`;\n\n // Generate confidence interval paths if fields are defined\n if (this.layout.confidence_intervals &&\n this.layout.confidence_intervals.start_field &&\n this.layout.confidence_intervals.end_field) {\n // Generate a selection for all forest plot confidence intervals\n const ci_selection = this.svg.group\n .selectAll('rect.lz-data_layer-forest.lz-data_layer-forest-ci')\n .data(track_data, (d) => {\n return d[this.layout.id_field];\n });\n\n const ci_transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.confidence_intervals.start_field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n const ci_width = (d) => {\n const {start_field, end_field} = this.layout.confidence_intervals;\n const scale = this.parent[x_scale];\n const result = scale(d[end_field]) - scale(d[start_field]);\n return Math.max(result, 1);\n };\n const ci_height = 1;\n // Create confidence interval rect elements\n ci_selection.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-ci')\n .attr('id', (d) => `${this.getElementId(d)}_ci`)\n .attr('transform', `translate(0, ${isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height})`)\n .merge(ci_selection)\n .attr('transform', ci_transform)\n .attr('width', ci_width) // Math.max(ci_width, 1))\n .attr('height', ci_height);\n\n // Remove old elements as needed\n ci_selection.exit()\n .remove();\n }\n\n // Generate a selection for all forest plot points\n const points_selection = this.svg.group\n .selectAll('path.lz-data_layer-forest.lz-data_layer-forest-point')\n .data(track_data, (d) => {\n return d[this.layout.id_field];\n });\n\n // Create elements, apply class, ID, and initial position\n const initial_y = isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height;\n\n // Generate new values (or functions for them) for position, color, size, and shape\n const transform = (d) => {\n let x = this.parent[x_scale](d[this.layout.x_axis.field]);\n let y = this.parent[y_scale](d[this.layout.y_axis.field]);\n if (isNaN(x)) {\n x = -1000;\n }\n if (isNaN(y)) {\n y = -1000;\n }\n return `translate(${x}, ${y})`;\n };\n\n const fill = (d, i) => this.resolveScalableParameter(this.layout.color, d, i);\n const fill_opacity = (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i);\n\n const shape = d3.symbol()\n .size((d, i) => this.resolveScalableParameter(this.layout.point_size, d, i))\n .type((d, i) => {\n // Legend shape names are strings; need to connect this to factory. Eg circle --> d3.symbolCircle\n const shape_name = this.resolveScalableParameter(this.layout.point_shape, d, i);\n const factory_name = `symbol${shape_name.charAt(0).toUpperCase() + shape_name.slice(1)}`;\n return d3[factory_name] || null;\n });\n\n points_selection.enter()\n .append('path')\n .attr('class', 'lz-data_layer-forest lz-data_layer-forest-point')\n .attr('id', (d) => this.getElementId(d))\n .attr('transform', `translate(0, ${initial_y})`)\n .merge(points_selection)\n .attr('transform', transform)\n .attr('fill', fill)\n .attr('fill-opacity', fill_opacity)\n .attr('d', shape);\n\n // Remove old elements as needed\n points_selection.exit()\n .remove();\n\n // Apply behaviors to points\n this.svg.group\n .on('click.event_emitter', (element_data) => {\n this.parent.emit('element_clicked', element_data, true);\n }).call(this.applyBehaviors.bind(this));\n }\n }\n\n /**\n * (**extension**) A y-aligned forest plot in which the y-axis represents item labels, which are dynamically\n * chosen when data is loaded. Each item is assumed to include both data and confidence intervals.\n * This allows generating forest plots without defining the layout in advance.\n * @alias module:LocusZoom_DataLayers~category_forest\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-forest-track} for required extension and installation instructions\n */\n class CategoryForest extends Forest {\n _getDataExtent(data, axis_config) {\n // In a forest plot, the data range is determined by *three* fields (beta + CI start/end)\n const { confidence_intervals } = this.layout;\n if (confidence_intervals && confidence_intervals.start_field && confidence_intervals.end_field) {\n const min = (d) => +d[confidence_intervals.start_field];\n const max = (d) => +d[confidence_intervals.end_field];\n return [d3.min(data, min), d3.max(data, max)];\n }\n\n // If there are no confidence intervals set, then range must depend only on a single field\n return super._getDataExtent(data, axis_config);\n }\n\n getTicks(dimension, config) { // Overrides parent method\n if (!['x', 'y1', 'y2'].includes(dimension)) {\n throw new Error(`Invalid dimension identifier ${dimension}`);\n }\n\n // Design assumption: one axis (y1 or y2) has the ticks, and the layout says which to use\n // Also assumes that every tick gets assigned a unique matching label\n const axis_num = this.layout.y_axis.axis;\n if (dimension === (`y${axis_num}`)) {\n const category_field = this.layout.y_axis.category_field;\n if (!category_field) {\n throw new Error(`Layout for ${this.layout.id} must specify category_field`);\n }\n\n return this.data.map((item, index) => ({ y: index + 1, text: item[category_field] }));\n } else {\n return [];\n }\n }\n\n applyCustomDataMethods () {\n // Add a synthetic yaxis field to ensure data is spread out on plot. Then, set axis floor and ceiling to\n // correct extents.\n const field_to_add = this.layout.y_axis.field;\n if (!field_to_add) {\n throw new Error(`Layout for ${this.layout.id} must specify yaxis.field`);\n }\n\n this.data = this.data.map((item, index) => {\n item[field_to_add] = index + 1;\n return item;\n });\n // Update axis extents based on one label for every point (with a bit of padding above and below)\n this.layout.y_axis.floor = 0;\n this.layout.y_axis.ceiling = this.data.length + 1;\n return this;\n }\n }\n\n LocusZoom.DataLayers.add('forest', Forest);\n LocusZoom.DataLayers.add('category_forest', CategoryForest);\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\nexport default install;\n"],"sourceRoot":""} \ 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 2a9e431a..702c0e8f 100644 --- a/dist/ext/lz-intervals-enrichment.min.js +++ b/dist/ext/lz-intervals-enrichment.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +var LzIntervalsEnrichment;(()=>{"use strict";var e={d:(t,a)=>{for(var i in a)e.o(a,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:a[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>n});const a=Symbol.for("lzXCS"),i=Symbol.for("lzYCS"),s=Symbol.for("lzXCE"),l=Symbol.for("lzYCE");function r(e){const t={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"},r=e.DataLayers.get("BaseDataLayer");const n={namespace:{intervals:"intervals"},closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Tissue: {{intervals:tissueId|htmlescape}}
\n Range: {{intervals:chromosome|htmlescape}}: {{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}
\n -log10 p: {{intervals:pValue|neglog10|scinotation|htmlescape}}
\n Enrichment (n-fold): {{intervals:fold|scinotation|htmlescape}}"},o={id:"intervals_enrichment",type:"intervals_enrichment",tag:"intervals_enrichment",namespace:{intervals:"intervals"},match:{send:"intervals:tissueId"},id_field:"intervals:start",start_field:"intervals:start",end_field:"intervals:end",filters:[{field:"intervals:ancestry",operator:"=",value:"EU"},{field:"intervals:pValue",operator:"<=",value:.05},{field:"intervals:fold",operator:">",value:2}],y_axis:{axis:1,field:"intervals:fold",floor:0,upper_buffer:.1,min_extent:[0,10]},fill_opacity:.5,color:[{field:"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:n},c={id:"interval_matches",type:"highlight_regions",namespace:{intervals:"intervals"},match:{receive:"intervals:tissueId"},start_field:"intervals:start",end_field:"intervals:end",merge_field:"intervals:tissueId",filters:[{field:"lz_is_match",operator:"=",value:!0},{field:"intervals:ancestry",operator:"=",value:"EU"},{field:"intervals:pValue",operator:"<=",value:.05},{field:"intervals:fold",operator:">",value:2}],color:[{field:"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:70},inner_border:"rgb(210, 210, 210)",axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:34,tick_format:"region",extent:"state"},y1:{label:"enrichment (n-fold)",label_offset:40}},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:[o]},h={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:e.Layouts.get("toolbar","standard_association"),panels:[function(){const t=e.Layouts.get("panel","association");return t.data_layers.unshift(c),t}(),d,e.Layouts.get("panel","genes")]};e.DataLayers.add("intervals_enrichment",class extends r{constructor(a){e.Layouts.merge(a,t),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:t,end_field:r,bounding_box_padding:n,track_height:o}=this.layout,c=this.layout.y_axis.field,d=`y${this.layout.y_axis.axis}_scale`,{x_scale:h,[d]:f}=this.parent;e.forEach((e=>{e[a]=h(e[t]),e[s]=h(e[r]),e[i]=f(e[c])-this.getTrackHeight()/2+n,e[l]=e[i]+o})),e.sort(((e,t)=>{const i=e[s]-e[a];return t[s]-t[a]-i}));const _=this.svg.group.selectAll("rect").data(e);_.enter().append("rect").merge(_).attr("id",(e=>this.getElementId(e))).attr("x",(e=>e[a])).attr("y",(e=>e[i])).attr("width",(e=>e[s]-e[a])).attr("height",this.layout.track_height).attr("fill",((e,t)=>this.resolveScalableParameter(this.layout.color,e,t))).attr("fill-opacity",((e,t)=>this.resolveScalableParameter(this.layout.fill_opacity,e,t))),_.exit().remove(),this.svg.group.call(this.applyBehaviors.bind(this))}_getTooltipPosition(e){return{x_min:e.data[a],x_max:e.data[s],y_min:e.data[i],y_max:e.data[l]}}}),e.Layouts.add("tooltip","intervals_enrichment",n),e.Layouts.add("data_layer","intervals_enrichment",o),e.Layouts.add("panel","intervals_enrichment",d),e.Layouts.add("plot","intervals_association_enrichment",h)}"undefined"!=typeof LocusZoom&&LocusZoom.use(r);const n=r;LzIntervalsEnrichment=t.default})(); //# sourceMappingURL=lz-intervals-enrichment.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-intervals-enrichment.min.js.map b/dist/ext/lz-intervals-enrichment.min.js.map index f569fa57..29de6128 100644 --- a/dist/ext/lz-intervals-enrichment.min.js.map +++ b/dist/ext/lz-intervals-enrichment.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]/./esm/ext/lz-intervals-enrichment.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","XCS","Symbol","for","YCS","XCE","YCE","install","LocusZoom","default_layout","start_field","end_field","track_height","track_vertical_spacing","bounding_box_padding","color","fill_opacity","tooltip_positioning","BaseLayer","DataLayers","intervals_tooltip_layout","namespace","closable","show","or","hide","and","html","intervals_layer_layout","id","type","tag","match","send","fields","id_field","filters","field","operator","value","y_axis","axis","floor","upper_buffer","min_extent","scale_function","parameters","values","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip","intervals_highlight_layout","intervals","receive","merge_field","intervals_panel_layout","min_height","height","margin","top","right","bottom","left","inner_border","axes","x","label","label_offset","tick_format","extent","y1","interaction","drag_background_to_pan","drag_x_ticks_to_scale","drag_y1_ticks_to_scale","scroll_to_zoom","x_linked","data_layers","intervals_plot_layout","state","width","responsive_resize","min_region_scale","max_region_scale","toolbar","Layouts","unnamespaced","panels","base","unshift","add","layout","merge","super","arguments","this","track_data","_applyFilters","data","y_field","y_axis_name","x_scale","y_scale","parent","forEach","item","getTrackHeight","sort","a","b","aspan","selection","svg","group","selectAll","enter","append","attr","d","getElementId","i","resolveScalableParameter","exit","remove","applyBehaviors","bind","x_min","x_max","y_min","y_max","use"],"mappings":";6CACA,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,4BCmClF,MAAMI,EAAMC,OAAOC,IAAI,SACjBC,EAAMF,OAAOC,IAAI,SACjBE,EAAMH,OAAOC,IAAI,SACjBG,EAAMJ,OAAOC,IAAI,SAGvB,SAASI,EAAQC,GAIb,MAAMC,EAAiB,CACnBC,YAAa,QACbC,UAAW,MACXC,aAAc,GACdC,uBAAwB,EACxBC,qBAAsB,EACtBC,MAAO,UACPC,aAAc,GACdC,oBAAqB,YAGnBC,EAAYV,EAAUW,WAAWxB,IAAI,iBAkG3C,MAAMyB,EAA2B,CAC7BC,UAAW,CAAE,UAAa,aAC1BC,UAAU,EACVC,KAAM,CAAEC,GAAI,CAAC,cAAe,aAC5BC,KAAM,CAAEC,IAAK,CAAC,gBAAiB,eAC/BC,KAAM,+bAcJC,EAAyB,CAC3BP,UAAW,CAAE,UAAa,aAC1BQ,GAAI,uBACJC,KAAM,uBACNC,IAAK,uBACLC,MAAO,CAAEC,KAAM,oCACfC,OAAQ,CAAC,qCAAsC,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2KhCE,EAAUmF,QAAQK,IAAI,UAAW,uBAAwB5E,GACzDZ,EAAUmF,QAAQK,IAAI,aAAc,uBAAwBpE,GAC5DpB,EAAUmF,QAAQK,IAAI,QAAS,uBAAwBnC,GACvDrD,EAAUmF,QAAQK,IAAI,OAAQ,mCAAoCZ,GAG7C,oBAAd5E,WAGPA,UAAUgI,IAAIjI,GAIlB,U","file":"ext/lz-intervals-enrichment.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))","/**\n * Interval annotation track that groups annotations by enrichment value (a fixed y-axis) rather than by merged/split tracks.\n\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n\n * ### Features provided\n * * {@link module:LocusZoom_DataLayers~intervals_enrichment}\n * * {@link module:LocusZoom_Layouts~intervals_association_enrichment}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_panel}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_data_layer}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_tooltip}\n *\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 * ```javascript\n * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n *\n * ```javascript\n * import LocusZoom from 'locuszoom';\n * import IntervalsTrack from 'locuszoom/esm/ext/lz-intervals-track';\n * LocusZoom.use(IntervalsTrack);\n * ```\n *\n * Then use the layouts made available by this extension. (see demos and documentation for guidance)\n * @module\n */\n\n// Coordinates (start, end) are cached to facilitate rendering\nconst XCS = Symbol.for('lzXCS');\nconst YCS = Symbol.for('lzYCS');\nconst XCE = Symbol.for('lzXCE');\nconst YCE = Symbol.for('lzYCE');\n\n\nfunction install(LocusZoom) {\n /**\n * @memberof module:LocusZoom_DataLayers~intervals_enrichment\n */\n const default_layout = {\n start_field: 'start',\n end_field: 'end',\n track_height: 10,\n track_vertical_spacing: 3,\n bounding_box_padding: 2,\n color: '#B8B8B8',\n fill_opacity: 0.5,\n tooltip_positioning: 'vertical',\n };\n\n const BaseLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n\n /**\n * Intervals-by-enrichment Data Layer\n *\n * Implements a data layer that groups interval annotations by enrichment value (a fixed y-axis)\n * @alias module:LocusZoom_DataLayers~intervals_enrichment\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\n class LzIntervalsEnrichment extends BaseLayer {\n /**\n * @param {string} [layout.start_field='start'] The field that defines interval start position\n * @param {string} [layout.end_field='end'] The field that defines interval end position\n * @param {number} [layout.track_height=10] The height of each interval rectangle, in px\n * @param {number} [layout.track_vertical_spacing=3]\n * @param {number} [layout.bounding_box_padding=2]\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#B8B8B8'] The color of each datum rectangle\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=0.5] The opacity of\n * each rectangle. The default is semi-transparent, because low-significance tracks may overlap very closely.\n * @param {string} [layout.tooltip_positioning='vertical']\n */\n constructor(layout) {\n LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n }\n\n // Helper function to sum layout values to derive total height for a single interval track\n getTrackHeight() {\n return this.layout.track_height\n + this.layout.track_vertical_spacing\n + (2 * this.layout.bounding_box_padding);\n }\n\n render() {\n // Determine the appropriate layout for tracks. Store the previous categories (y axis ticks) to decide\n // whether the axis needs to be re-rendered.\n\n // Apply filters to only render a specified set of points. Hidden fields will still be given space to render, but not shown.\n const track_data = this._applyFilters(this.data);\n\n const {start_field, end_field, bounding_box_padding, track_height} = this.layout;\n const y_field = this.layout.y_axis.field;\n const y_axis_name = `y${this.layout.y_axis.axis}_scale`;\n const { x_scale, [y_axis_name]: y_scale } = this.parent;\n\n // Calculate coordinates for each point\n track_data.forEach((item) => {\n item[XCS] = x_scale(item[start_field]);\n item[XCE] = x_scale(item[end_field]);\n item[YCS] = y_scale(item[y_field]) - this.getTrackHeight() / 2 + bounding_box_padding;\n item[YCE] = item[YCS] + track_height;\n });\n\n track_data.sort((a, b) => {\n // Simplistic layout algorithm that adds wide rectangles to the DOM first, so that small rectangles\n // in the same space are clickable (SVG element order determines z-index)\n const aspan = a[XCE] - a[XCS];\n const bspan = b[XCE] - b[XCS];\n return bspan - aspan;\n });\n\n const selection = this.svg.group.selectAll('rect')\n .data(track_data);\n\n selection.enter()\n .append('rect')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => d[XCS])\n .attr('y', (d) => d[YCS])\n .attr('width', (d) => d[XCE] - d[XCS])\n .attr('height', this.layout.track_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 selection.exit()\n .remove();\n\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n }\n\n _getTooltipPosition(tooltip) {\n return {\n x_min: tooltip.data[XCS],\n x_max: tooltip.data[XCE],\n y_min: tooltip.data[YCS],\n y_max: tooltip.data[YCE],\n };\n }\n }\n\n /**\n * (**extension**) A basic tooltip with information to be shown over an intervals-by-enrichment datum\n * @alias module:LocusZoom_Layouts~intervals_enrichment_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_tooltip_layout = {\n namespace: { 'intervals': 'intervals' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n 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}}`,\n };\n\n /**\n * (**extension**) A data layer with some preconfigured options for intervals-by-enrichment display, in\n * which intervals are ranked by priority from enrichment analysis.\n *\n * @alias module:LocusZoom_Layouts~intervals_enrichment_data_layer\n * @type data_layer\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_layer_layout = {\n namespace: { 'intervals': 'intervals' },\n id: 'intervals_enrichment',\n type: 'intervals_enrichment',\n tag: 'intervals_enrichment',\n match: { send: '{{namespace[intervals]}}tissueId' },\n fields: ['{{namespace[intervals]}}chromosome', '{{namespace[intervals]}}start', '{{namespace[intervals]}}end', '{{namespace[intervals]}}pValue', '{{namespace[intervals]}}fold', '{{namespace[intervals]}}tissueId', '{{namespace[intervals]}}ancestry'],\n id_field: '{{namespace[intervals]}}start', // not a good ID field for overlapping intervals\n start_field: '{{namespace[intervals]}}start',\n end_field: '{{namespace[intervals]}}end',\n filters: [\n { field: '{{namespace[intervals]}}ancestry', operator: '=', value: 'EU' },\n { field: '{{namespace[intervals]}}pValue', operator: '<=', value: 0.05 },\n { field: '{{namespace[intervals]}}fold', operator: '>', value: 2.0 },\n ],\n y_axis: {\n axis: 1,\n field: '{{namespace[intervals]}}fold', // is this used for other than extent generation?\n floor: 0,\n upper_buffer: 0.10,\n min_extent: [0, 10],\n },\n fill_opacity: 0.5, // Many intervals overlap: show all, even if the ones below can't be clicked\n color: [\n {\n field: '{{namespace[intervals]}}tissueId',\n scale_function: 'stable_choice',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'],\n },\n },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: intervals_tooltip_layout,\n };\n\n // This is tied to a rather specific demo, so it's not added to the reusable registry\n // Highlights areas of a scatter plot that match the HuGeAMP-provided enrichment analysis data\n // Relies on matching behavior/ interaction (not visible initially)\n const intervals_highlight_layout = {\n id: 'interval_matches',\n type: 'highlight_regions',\n namespace: { intervals: 'intervals' },\n match: { receive: '{{namespace[intervals]}}tissueId' },\n fields: ['{{namespace[intervals]}}start', '{{namespace[intervals]}}end', '{{namespace[intervals]}}tissueId', '{{namespace[intervals]}}ancestry', '{{namespace[intervals]}}pValue', '{{namespace[intervals]}}fold'],\n start_field: '{{namespace[intervals]}}start',\n end_field: '{{namespace[intervals]}}end',\n merge_field: '{{namespace[intervals]}}tissueId',\n filters: [\n { field: 'lz_is_match', operator: '=', value: true },\n { field: '{{namespace[intervals]}}ancestry', operator: '=', value: 'EU' },\n { field: '{{namespace[intervals]}}pValue', operator: '<=', value: 0.05 },\n { field: '{{namespace[intervals]}}fold', operator: '>', value: 2.0 },\n ],\n color: [{\n field: '{{namespace[intervals]}}tissueId',\n scale_function: 'stable_choice',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'],\n },\n }],\n fill_opacity: 0.1,\n };\n\n /**\n * (**extension**) A panel containing an intervals-by-enrichment data layer\n * @alias module:LocusZoom_Layouts~intervals_enrichment_panel\n * @type panel\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_panel_layout = {\n id: 'intervals_enrichment',\n tag: 'intervals_enrichment',\n min_height: 250,\n height: 250,\n margin: { top: 35, right: 50, bottom: 40, left: 50 },\n inner_border: 'rgb(210, 210, 210)',\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: 'enrichment (n-fold)',\n label_offset: 28,\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: [intervals_layer_layout],\n };\n\n /**\n * (**extension**) A plot layout that shows association summary statistics, genes, and intervals-by-enrichment data.\n * This layout provides interactive matching: clicking an interval marking causes area of the scatter plot to be\n * highlighted for any annotations that match the specified category.\n * It is intended to work with data in the HuGeAMP format.\n * @alias module:LocusZoom_Layouts~intervals_association_enrichment\n * @type plot\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_plot_layout = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }),\n panels: [\n function () {\n const base = LocusZoom.Layouts.get('panel', 'association', { unnamespaced: true });\n base.data_layers.unshift(intervals_highlight_layout);\n return base;\n }(),\n intervals_panel_layout,\n LocusZoom.Layouts.get('panel', 'genes'),\n ],\n };\n\n LocusZoom.DataLayers.add('intervals_enrichment', LzIntervalsEnrichment);\n\n LocusZoom.Layouts.add('tooltip', 'intervals_enrichment', intervals_tooltip_layout);\n LocusZoom.Layouts.add('data_layer', 'intervals_enrichment', intervals_layer_layout);\n LocusZoom.Layouts.add('panel', 'intervals_enrichment', intervals_panel_layout);\n LocusZoom.Layouts.add('plot', 'intervals_association_enrichment', intervals_plot_layout);\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]/./esm/ext/lz-intervals-enrichment.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","XCS","Symbol","for","YCS","XCE","YCE","install","LocusZoom","default_layout","start_field","end_field","track_height","track_vertical_spacing","bounding_box_padding","color","fill_opacity","tooltip_positioning","BaseLayer","DataLayers","intervals_tooltip_layout","namespace","closable","show","or","hide","and","html","intervals_layer_layout","id","type","tag","match","send","id_field","filters","field","operator","value","y_axis","axis","floor","upper_buffer","min_extent","scale_function","parameters","values","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip","intervals_highlight_layout","intervals","receive","merge_field","intervals_panel_layout","min_height","height","margin","top","right","bottom","left","inner_border","axes","x","label","label_offset","tick_format","extent","y1","interaction","drag_background_to_pan","drag_x_ticks_to_scale","drag_y1_ticks_to_scale","scroll_to_zoom","x_linked","data_layers","intervals_plot_layout","state","width","responsive_resize","min_region_scale","max_region_scale","toolbar","Layouts","panels","base","unshift","add","layout","merge","super","arguments","this","track_data","_applyFilters","data","y_field","y_axis_name","x_scale","y_scale","parent","forEach","item","getTrackHeight","sort","a","b","aspan","selection","svg","group","selectAll","enter","append","attr","d","getElementId","i","resolveScalableParameter","exit","remove","applyBehaviors","bind","x_min","x_max","y_min","y_max","use"],"mappings":";6CACA,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,MCJ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H,GAAOqH,EAAEzH,KAChCwH,KAAK,SAAUtB,KAAKJ,OAAOnF,cAC3B6G,KAAK,QAAQ,CAACC,EAAGE,IAAMzB,KAAK0B,yBAAyB1B,KAAKJ,OAAOhF,MAAO2G,EAAGE,KAC3EH,KAAK,gBAAgB,CAACC,EAAGE,IAAMzB,KAAK0B,yBAAyB1B,KAAKJ,OAAO/E,aAAc0G,EAAGE,KAE/FT,EAAUW,OACLC,SAEL5B,KAAKiB,IAAIC,MACJrH,KAAKmG,KAAK6B,eAAeC,KAAK9B,OAGvC,oBAAoB5C,GAChB,MAAO,CACH2E,MAAO3E,EAAQ+C,KAAKrG,GACpBkI,MAAO5E,EAAQ+C,KAAKjG,GACpB+H,MAAO7E,EAAQ+C,KAAKlG,GACpBiI,MAAO9E,EAAQ+C,KAAKhG,OAyKhCE,EAAUkF,QAAQI,IAAI,UAAW,uBAAwB1E,GACzDZ,EAAUkF,QAAQI,IAAI,aAAc,uBAAwBlE,GAC5DpB,EAAUkF,QAAQI,IAAI,QAAS,uBAAwBlC,GACvDpD,EAAUkF,QAAQI,IAAI,OAAQ,mCAAoCX,GAG7C,oBAAd3E,WAGPA,UAAU8H,IAAI/H,GAIlB,U","file":"ext/lz-intervals-enrichment.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))","/**\n * Interval annotation track that groups annotations by enrichment value (a fixed y-axis) rather than by merged/split tracks.\n\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n\n * ### Features provided\n * * {@link module:LocusZoom_DataLayers~intervals_enrichment}\n * * {@link module:LocusZoom_Layouts~intervals_association_enrichment}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_panel}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_data_layer}\n * * {@link module:LocusZoom_Layouts~intervals_enrichment_tooltip}\n *\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 * ```javascript\n * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n *\n * ```javascript\n * import LocusZoom from 'locuszoom';\n * import IntervalsTrack from 'locuszoom/esm/ext/lz-intervals-track';\n * LocusZoom.use(IntervalsTrack);\n * ```\n *\n * Then use the layouts made available by this extension. (see demos and documentation for guidance)\n * @module\n */\n\n// Coordinates (start, end) are cached to facilitate rendering\nconst XCS = Symbol.for('lzXCS');\nconst YCS = Symbol.for('lzYCS');\nconst XCE = Symbol.for('lzXCE');\nconst YCE = Symbol.for('lzYCE');\n\n\nfunction install(LocusZoom) {\n /**\n * @memberof module:LocusZoom_DataLayers~intervals_enrichment\n */\n const default_layout = {\n start_field: 'start',\n end_field: 'end',\n track_height: 10,\n track_vertical_spacing: 3,\n bounding_box_padding: 2,\n color: '#B8B8B8',\n fill_opacity: 0.5,\n tooltip_positioning: 'vertical',\n };\n\n const BaseLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n\n /**\n * Intervals-by-enrichment Data Layer\n *\n * Implements a data layer that groups interval annotations by enrichment value (a fixed y-axis)\n * @alias module:LocusZoom_DataLayers~intervals_enrichment\n * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options\n */\n class LzIntervalsEnrichment extends BaseLayer {\n /**\n * @param {string} [layout.start_field='start'] The field that defines interval start position\n * @param {string} [layout.end_field='end'] The field that defines interval end position\n * @param {number} [layout.track_height=10] The height of each interval rectangle, in px\n * @param {number} [layout.track_vertical_spacing=3]\n * @param {number} [layout.bounding_box_padding=2]\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#B8B8B8'] The color of each datum rectangle\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=0.5] The opacity of\n * each rectangle. The default is semi-transparent, because low-significance tracks may overlap very closely.\n * @param {string} [layout.tooltip_positioning='vertical']\n */\n constructor(layout) {\n LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n }\n\n // Helper function to sum layout values to derive total height for a single interval track\n getTrackHeight() {\n return this.layout.track_height\n + this.layout.track_vertical_spacing\n + (2 * this.layout.bounding_box_padding);\n }\n\n render() {\n // Determine the appropriate layout for tracks. Store the previous categories (y axis ticks) to decide\n // whether the axis needs to be re-rendered.\n\n // Apply filters to only render a specified set of points. Hidden fields will still be given space to render, but not shown.\n const track_data = this._applyFilters(this.data);\n\n const {start_field, end_field, bounding_box_padding, track_height} = this.layout;\n const y_field = this.layout.y_axis.field;\n const y_axis_name = `y${this.layout.y_axis.axis}_scale`;\n const { x_scale, [y_axis_name]: y_scale } = this.parent;\n\n // Calculate coordinates for each point\n track_data.forEach((item) => {\n item[XCS] = x_scale(item[start_field]);\n item[XCE] = x_scale(item[end_field]);\n item[YCS] = y_scale(item[y_field]) - this.getTrackHeight() / 2 + bounding_box_padding;\n item[YCE] = item[YCS] + track_height;\n });\n\n track_data.sort((a, b) => {\n // Simplistic layout algorithm that adds wide rectangles to the DOM first, so that small rectangles\n // in the same space are clickable (SVG element order determines z-index)\n const aspan = a[XCE] - a[XCS];\n const bspan = b[XCE] - b[XCS];\n return bspan - aspan;\n });\n\n const selection = this.svg.group.selectAll('rect')\n .data(track_data);\n\n selection.enter()\n .append('rect')\n .merge(selection)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => d[XCS])\n .attr('y', (d) => d[YCS])\n .attr('width', (d) => d[XCE] - d[XCS])\n .attr('height', this.layout.track_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 selection.exit()\n .remove();\n\n this.svg.group\n .call(this.applyBehaviors.bind(this));\n }\n\n _getTooltipPosition(tooltip) {\n return {\n x_min: tooltip.data[XCS],\n x_max: tooltip.data[XCE],\n y_min: tooltip.data[YCS],\n y_max: tooltip.data[YCE],\n };\n }\n }\n\n /**\n * (**extension**) A basic tooltip with information to be shown over an intervals-by-enrichment datum\n * @alias module:LocusZoom_Layouts~intervals_enrichment_tooltip\n * @type tooltip\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_tooltip_layout = {\n namespace: { 'intervals': 'intervals' },\n closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: `Tissue: {{intervals:tissueId|htmlescape}}
\n Range: {{intervals:chromosome|htmlescape}}: {{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}
\n -log10 p: {{intervals:pValue|neglog10|scinotation|htmlescape}}
\n Enrichment (n-fold): {{intervals:fold|scinotation|htmlescape}}`,\n };\n\n /**\n * (**extension**) A data layer with some preconfigured options for intervals-by-enrichment display, in\n * which intervals are ranked by priority from enrichment analysis.\n *\n * @alias module:LocusZoom_Layouts~intervals_enrichment_data_layer\n * @type data_layer\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_layer_layout = {\n id: 'intervals_enrichment',\n type: 'intervals_enrichment',\n tag: 'intervals_enrichment',\n namespace: { 'intervals': 'intervals' },\n match: { send: 'intervals:tissueId' },\n id_field: 'intervals:start', // not a good ID field for overlapping intervals\n start_field: 'intervals:start',\n end_field: 'intervals:end',\n filters: [\n { field: 'intervals:ancestry', operator: '=', value: 'EU' },\n { field: 'intervals:pValue', operator: '<=', value: 0.05 },\n { field: 'intervals:fold', operator: '>', value: 2.0 },\n ],\n y_axis: {\n axis: 1,\n field: 'intervals:fold', // is this used for other than extent generation?\n floor: 0,\n upper_buffer: 0.10,\n min_extent: [0, 10],\n },\n fill_opacity: 0.5, // Many intervals overlap: show all, even if the ones below can't be clicked\n color: [\n {\n field: 'intervals:tissueId',\n scale_function: 'stable_choice',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'],\n },\n },\n ],\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: intervals_tooltip_layout,\n };\n\n // This is tied to a rather specific demo, so it's not added to the reusable registry\n // Highlights areas of a scatter plot that match the HuGeAMP-provided enrichment analysis data\n // Relies on matching behavior/ interaction (not visible initially)\n const intervals_highlight_layout = {\n id: 'interval_matches',\n type: 'highlight_regions',\n namespace: { intervals: 'intervals' },\n match: { receive: 'intervals:tissueId' },\n start_field: 'intervals:start',\n end_field: 'intervals:end',\n merge_field: 'intervals:tissueId',\n filters: [\n { field: 'lz_is_match', operator: '=', value: true },\n { field: 'intervals:ancestry', operator: '=', value: 'EU' },\n { field: 'intervals:pValue', operator: '<=', value: 0.05 },\n { field: 'intervals:fold', operator: '>', value: 2.0 },\n ],\n color: [{\n field: 'intervals:tissueId',\n scale_function: 'stable_choice',\n parameters: {\n values: ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'],\n },\n }],\n fill_opacity: 0.1,\n };\n\n /**\n * (**extension**) A panel containing an intervals-by-enrichment data layer\n * @alias module:LocusZoom_Layouts~intervals_enrichment_panel\n * @type panel\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_panel_layout = {\n id: 'intervals_enrichment',\n tag: 'intervals_enrichment',\n min_height: 250,\n height: 250,\n margin: { top: 35, right: 50, bottom: 40, left: 70 },\n inner_border: 'rgb(210, 210, 210)',\n axes: {\n x: {\n label: 'Chromosome {{chr}} (Mb)',\n label_offset: 34,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: 'enrichment (n-fold)',\n label_offset: 40,\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: [intervals_layer_layout],\n };\n\n /**\n * (**extension**) A plot layout that shows association summary statistics, genes, and intervals-by-enrichment data.\n * This layout provides interactive matching: clicking an interval marking causes area of the scatter plot to be\n * highlighted for any annotations that match the specified category.\n * It is intended to work with data in the HuGeAMP format.\n * @alias module:LocusZoom_Layouts~intervals_association_enrichment\n * @type plot\n * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions\n */\n const intervals_plot_layout = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'),\n panels: [\n function () {\n const base = LocusZoom.Layouts.get('panel', 'association');\n base.data_layers.unshift(intervals_highlight_layout);\n return base;\n }(),\n intervals_panel_layout,\n LocusZoom.Layouts.get('panel', 'genes'),\n ],\n };\n\n LocusZoom.DataLayers.add('intervals_enrichment', LzIntervalsEnrichment);\n\n LocusZoom.Layouts.add('tooltip', 'intervals_enrichment', intervals_tooltip_layout);\n LocusZoom.Layouts.add('data_layer', 'intervals_enrichment', intervals_layer_layout);\n LocusZoom.Layouts.add('panel', 'intervals_enrichment', intervals_panel_layout);\n LocusZoom.Layouts.add('plot', 'intervals_association_enrichment', intervals_plot_layout);\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/ext/lz-intervals-track.min.js b/dist/ext/lz-intervals-track.min.js index bf224e6a..708f1028 100644 --- a/dist/ext/lz-intervals-track.min.js +++ b/dist/ext/lz-intervals-track.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +var LzIntervalsTrack;(()=>{"use strict";var t={d:(e,a)=>{for(var r in a)t.o(a,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:a[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{default:()=>o});const a=d3,r=Symbol.for("lzXCS"),s=Symbol.for("lzYCS"),i=Symbol.for("lzXCE"),l=Symbol.for("lzYCE");function n(t){const e=t.Adapters.get("BaseUMAdapter"),n=t.Widgets.get("_Button"),o=t.Widgets.get("BaseWidget");function c(t,e){return e?`rgb(${e})`:null}const d={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"},g=t.DataLayers.get("BaseDataLayer");const _={closable:!1,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"{{intervals:state_name|htmlescape}}
{{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}"},h={namespace:{intervals:"intervals"},id:"intervals",type:"intervals",tag:"intervals",id_field:"{{intervals:start}}_{{intervals:end}}_{{intervals:state_name}}",start_field:"intervals:start",end_field:"intervals:end",track_split_field:"intervals:state_name",track_label_field:"intervals:state_name",split_tracks:!1,always_hide_legend:!0,color:[{field:"intervals:itemRgb",scale_function:"to_rgb"},{field:"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:_},u=t.Layouts.merge({id_field:"{{intervals:chromStart}}_{{intervals:chromEnd}}_{{intervals:name}}",start_field:"intervals:chromStart",end_field:"intervals:chromEnd",track_split_field:"intervals:name",track_label_field:"intervals:name",split_tracks:!0,always_hide_legend:!1,color:[{field:"intervals:itemRgb",scale_function:"to_rgb"},{field:"intervals:name",scale_function:"categorical_bin",parameters:{categories:[],values:[],null_value:"#B8B8B8"}}],tooltip:t.Layouts.merge({html:"Group: {{intervals:name|htmlescape}}
\nRegion: {{intervals:chromStart|htmlescape}}-{{intervals:chromEnd|htmlescape}}\n{{#if intervals:score}}
\nScore: {{intervals:score|htmlescape}}{{/if}}"},_)},h),p={id:"intervals",tag:"intervals",min_height:50,height:50,margin:{top:25,right:150,bottom:5,left:70},toolbar:function(){const e=t.Layouts.get("toolbar","standard_panel");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]},y=t.Layouts.merge({min_height:120,height:120,data_layers:[u]},p),b={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:t.Layouts.get("toolbar","standard_association"),panels:[t.Layouts.get("panel","association"),t.Layouts.merge({min_height:120,height:120},p),t.Layouts.get("panel","genes")]};t.Adapters.add("IntervalLZ",class extends e{_getURL(t){const e=`?filter=id in ${this._config.source} and chromosome eq '${t.chr}' and start le ${t.end} and end ge ${t.start}`;return`${super._getURL(t)}${e}`}}),t.DataLayers.add("intervals",class extends g{constructor(e){t.Layouts.merge(e,d),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 r=t[e];Object.prototype.hasOwnProperty.call(a,r)||(a[r]=[]),a[r].push(t)})),a}_arrangeTracksLinear(t,e=!0){if(e)return[t];const{start_field:a,end_field:r}=this.layout,s=[[]];return t.forEach(((t,e)=>{for(let e=0;e{d[t].forEach((t=>{t[r]=e(t[a]),t[i]=e(t[n]),t[s]=g*this.getTrackHeight()+o,t[l]=t[s]+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,r=e.color.find((function(t){return t.scale_function&&"categorical_bin"===t.scale_function})),s=a.color.find((function(t){return t.scale_function&&"categorical_bin"===t.scale_function}));if(!r)throw new Error("Interval tracks must define a `categorical_bin` color scale");const i=r.parameters.categories.length&&r.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);s.parameters.categories=c.map((function(t){return t[0]})),s.parameters.values=e,this.layout.legend=c.map((function(e,a){const r=e[0],i={shape:"rect",width:9,label:e[1],color:s.parameters.values[a]};return i[t.layout.track_split_field]=r,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",Math.max(t-this.layout.track_vertical_spacing,1))}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[r])).attr("y",(t=>t[s])).attr("width",(t=>Math.max(t[i]-t[r],1))).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[r],x_max:t.data[i],y_min:t.data[s],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,r=+this.layout.track_height||0,s=2*(+this.layout.bounding_box_padding||0)+(+this.layout.track_vertical_spacing||0),i=a*r+(a-1)*s;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((r=>{const s=r[this.layout.track_split_field];let i=t.findIndex((t=>t===s));-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:r.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=>c(0,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,r=this._base_layout.legend;if(r&&r.length)return r.map((t=>[t[this.layout.track_split_field],t.label,t.color]));const s={},i=[];return t.forEach((t=>{const r=t[a.layout.track_split_field];Object.prototype.hasOwnProperty.call(s,r)||(s[r]=null,i.push([r,t[this.layout.track_label_field],t[e]]))})),i}}),t.Layouts.add("tooltip","standard_intervals",_),t.Layouts.add("data_layer","intervals",h),t.Layouts.add("data_layer","bed_intervals",u),t.Layouts.add("panel","intervals",p),t.Layouts.add("panel","bed_intervals",y),t.Layouts.add("plot","interval_association",b),t.ScaleFunctions.add("to_rgb",c),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-intervals-track.min.js.map b/dist/ext/lz-intervals-track.min.js.map index cae22cd9..21015911 100644 --- a/dist/ext/lz-intervals-track.min.js.map +++ b/dist/ext/lz-intervals-track.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/ext/lz-intervals-track.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","XCS","Symbol","for","YCS","XCE","YCE","install","LocusZoom","BaseApiAdapter","Adapters","_Button","Widgets","_BaseWidget","default_layout","start_field","end_field","track_label_field","track_split_field","track_split_order","track_split_legend_to_y_axis","split_tracks","track_height","track_vertical_spacing","bounding_box_padding","always_hide_legend","color","fill_opacity","tooltip_positioning","BaseLayer","DataLayers","intervals_tooltip_layout","namespace","closable","show","or","hide","and","html","intervals_layer_layout","id","type","tag","fields","id_field","field","scale_function","parameters","categories","values","null_value","legend","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip","intervals_panel_layout","min_height","height","margin","top","right","bottom","left","toolbar","l","Layouts","unnamespaced","widgets","push","data_layer_id","position","axes","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","hidden","orientation","origin","x","y","pad_from_bottom","data_layers","intervals_plot_layout","state","width","responsive_resize","min_region_scale","max_region_scale","panels","merge","add","chain","query","header","bedtracksource","this","params","source","chr","end","start","url","layout","super","arguments","_previous_categories","_categories","initialize","_statusnodes_group","svg","group","append","attr","_datanodes_group","data","result","forEach","item","item_key","allow_overlap","grouped_data","index","i","length","row_to_test","last_item","x_scale","parent","_arrangeTrackSplit","_arrangeTracksLinear","keys","reverse","row_index","getTrackHeight","track","reduce","acc","val","concat","element","getBaseId","replace","self","base_layout","_base_layout","render_layout","base_color_scale","find","color_scale","Error","has_colors","has_legend","rgb_option","rgb_field","known_categories","_generateCategoriesFromData","colors","_makeColorScheme","map","pair","shape","label","_applyLayoutOptions","assigned_data","_assignTracks","every","updateSplitTrackAxis","track_data","_applyFilters","selectAll","remove","status_nodes","enter","d","getElementStatusNodeId","cliparea","exit","data_nodes","getElementId","resolveScalableParameter","applyBehaviors","bind","render","x_min","x_max","y_min","y_max","legend_axis","tracks","track_spacing","target_height","scaleHeightToData","ticks","range","findIndex","Math","abs","text","y_axis","axis","floor","ceiling","parent_plot","positionPanels","category_info","n_categories","unique_ids","ScaleFunctions","value","parent_panel","data_layer","button","setHtml","setColor","setTitle","setOnclick","toggleSplitTracks","scale_timeout","clearTimeout","setTimeout","update","use"],"mappings":";wCACA,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,4BCAlF,MAAM,EAA+BI,GCsC/BC,EAAMC,OAAOC,IAAI,SACjBC,EAAMF,OAAOC,IAAI,SACjBE,EAAMH,OAAOC,IAAI,SACjBG,EAAMJ,OAAOC,IAAI,SAGvB,SAASI,EAASC,GACd,MAAMC,EAAiBD,EAAUE,SAAShB,IAAI,kBACxCiB,EAAUH,EAAUI,QAAQlB,IAAI,WAChCmB,EAAcL,EAAUI,QAAQlB,IAAI,cAoF1C,MAAMoB,EAAiB,CACnBC,YAAa,QACbC,UAAW,MACXC,kBAAmB,aAKnBC,kBAAmB,WACnBC,kBAAmB,OACnBC,6BAA8B,EAC9BC,cAAc,EACdC,aAAc,GACdC,uBAAwB,EACxBC,qBAAsB,EACtBC,oBAAoB,EACpBC,MAAO,UACPC,aAAc,EACdC,oBAAqB,YAGnBC,EAAYrB,EAAUsB,WAAWpC,IAAI,iBAkc3C,MAAMqC,EAA2B,CAC7BC,UAAW,CAAE,UAAa,aAC1BC,UAAU,EACVC,KAAM,CAAEC,GAAI,CAAC,cAAe,aAC5BC,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KoH,QACLpH,KAAKoH,OAAOC,QAAQrL,GACpBgE,KAAKoH,OAAOxL,OACZoE,KAAKgC,OAAO1D,WACL0B,OAEPA,KAAKoH,OAAS,IAAI/M,EAAQ2F,MACrBsH,SAAStH,KAAKO,OAAOnF,OACrBiM,QAAQrL,GACRuL,SAAS,4DACTC,YAAW,KACRL,EAAWM,oBAIPzH,KAAK0H,eACLC,aAAa3H,KAAK0H,eAEtB1H,KAAK0H,cAAgBE,YAAW,KAC5B5H,KAAKkH,aAAalB,oBAClBhG,KAAK2G,YAAYC,mBAClB,GACH5G,KAAK6H,YAEN7H,KAAK6H,aA+mBH,oBAAd3N,WAGPA,UAAU4N,IAAI7N,GAIlB,U","file":"ext/lz-intervals-track.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 * Interval annotation track (for chromatin state, etc). Useful for BED file data with non-overlapping intervals.\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~IntervalLZ}\n * * {@link module:LocusZoom_Widgets~toggle_split_tracks}\n * * {@link module:LocusZoom_ScaleFunctions~to_rgb}\n * * {@link module:LocusZoom_DataLayers~intervals}\n * * {@link module:LocusZoom_Layouts~standard_intervals}\n * * {@link module:LocusZoom_Layouts~intervals_layer}\n * * {@link module:LocusZoom_Layouts~intervals}\n * * {@link module:LocusZoom_Layouts~interval_association}\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import IntervalsTrack from 'locuszoom/esm/ext/lz-intervals-track';\n * LocusZoom.use(IntervalsTrack);\n * ```\n *\n * Then use the features made available by this extension. (see demos and documentation for guidance)\n * @module\n */\n\nimport * as d3 from 'd3';\n\n\n// Coordinates (start, end) are cached to facilitate rendering\nconst XCS = Symbol.for('lzXCS');\nconst YCS = Symbol.for('lzYCS');\nconst XCE = Symbol.for('lzXCE');\nconst YCE = Symbol.for('lzYCE');\n\n\nfunction install (LocusZoom) {\n const BaseApiAdapter = LocusZoom.Adapters.get('BaseApiAdapter');\n const _Button = LocusZoom.Widgets.get('_Button');\n const _BaseWidget = LocusZoom.Widgets.get('BaseWidget');\n\n /**\n * (**extension**) Retrieve Interval Annotation Data (e.g. BED Tracks), as fetched from the LocusZoom API server (or compatible)\n * @public\n * @alias module:LocusZoom_Adapters~IntervalLZ\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n * @param {number} config.params.source The numeric ID for a specific dataset as assigned by the API server\n */\n class IntervalLZ extends BaseApiAdapter {\n getURL(state, chain, fields) {\n const source = chain.header.bedtracksource || this.params.source;\n const query = `?filter=id in ${source} and chromosome eq '${state.chr}' and start le ${state.end} and end ge ${state.start}`;\n return `${this.url}${query}`;\n }\n }\n\n /**\n * (**extension**) Button to toggle split tracks mode in an intervals track. This button only works as a panel-level toolbar\n * and when used with an intervals data layer from this extension.\n * @alias module:LocusZoom_Widgets~toggle_split_tracks\n * @see module:LocusZoom_Widgets~BaseWidget\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n class ToggleSplitTracks extends _BaseWidget {\n /**\n * @param {string} layout.data_layer_id The ID of the data layer that this button is intended to control.\n */\n constructor(layout) {\n super(...arguments);\n if (!layout.data_layer_id) {\n layout.data_layer_id = 'intervals';\n }\n if (!this.parent_panel.data_layers[layout.data_layer_id]) {\n throw new Error('Toggle split tracks widget specifies an invalid data layer ID');\n }\n }\n\n update() {\n const data_layer = this.parent_panel.data_layers[this.layout.data_layer_id];\n const html = data_layer.layout.split_tracks ? 'Merge Tracks' : 'Split Tracks';\n if (this.button) {\n this.button.setHtml(html);\n this.button.show();\n this.parent.position();\n return this;\n } else {\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(html)\n .setTitle('Toggle whether tracks are split apart or merged together')\n .setOnclick(() => {\n data_layer.toggleSplitTracks();\n // FIXME: the timeout calls to scale and position (below) cause full ~5 additional re-renders\n // If we can remove these it will greatly speed up re-rendering.\n // The key problem here is that the height is apparently not known in advance and is determined after re-render.\n if (this.scale_timeout) {\n clearTimeout(this.scale_timeout);\n }\n this.scale_timeout = setTimeout(() => {\n this.parent_panel.scaleHeightToData();\n this.parent_plot.positionPanels();\n }, 0);\n this.update();\n });\n return this.update();\n }\n }\n }\n\n\n /**\n * (**extension**) Convert a value \"\"rr,gg,bb\" (if given) to a css-friendly color string: \"rgb(rr,gg,bb)\".\n * This is tailored specifically to the color specification format embraced by the BED file standard.\n * @alias module:LocusZoom_ScaleFunctions~to_rgb\n * @param {Object} parameters This function has no defined configuration options\n * @param {String|null} value The value to convert to rgb\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n function to_rgb(parameters, value) {\n return value ? `rgb(${value})` : null;\n }\n\n const default_layout = {\n start_field: 'start',\n end_field: 'end',\n track_label_field: 'state_name', // Used to label items on the y-axis\n // Used to uniquely identify tracks for coloring. This tends to lead to more stable coloring/sorting\n // than using the label field- eg, state_ids allow us to set global colors across the entire dataset,\n // not just choose unique colors within a particular narrow region. (where changing region might lead to more\n // categories and different colors)\n track_split_field: 'state_id',\n track_split_order: 'DESC',\n track_split_legend_to_y_axis: 2,\n split_tracks: true,\n track_height: 15,\n track_vertical_spacing: 3,\n bounding_box_padding: 2,\n always_hide_legend: false,\n color: '#B8B8B8',\n fill_opacity: 1,\n tooltip_positioning: 'vertical',\n };\n\n const BaseLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n\n /**\n * (**extension**) Implements a data layer that will render interval annotation tracks (intervals must provide start and end values)\n * Each interval (such as from a BED file) will be rendered as a rectangle. All spans can be rendered on the same\n * row, or each (auto-detected) category can be rendered as one row per category.\n *\n * This layer is intended to work with a variety of datasets with special requirements. As such, it has a lot\n * of configuration options devoted to identifying how to fill in missing information (such as color)\n *\n * @alias module:LocusZoom_DataLayers~intervals\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n class LzIntervalsTrack extends BaseLayer {\n /**\n * @param {string} [layout.start_field='start'] The field that defines interval start position\n * @param {string} [layout.end_field='end'] The field that defines interval end position\n * @param {string} [layout.track_label_field='state_name'] Used to label items on the y-axis\n * @param {string} [layout.track_split_field='state_id'] Used to define categories on the y-axis. It is usually most convenient to use\n * the same value for state_field and label_field (eg 1:1 correspondence).\n * @param {*|'DESC'} [layout.track_split_order='DESC'] When in split tracks mode, should categories be shown in\n * the order given, or descending order\n * @param {number} [layout.track_split_legend_to_y_axis=2]\n * @param {boolean} [layout.split_tracks=true] Whether to show tracks as merged (one row) or split (many rows)\n * on initial render.\n * @param {number} [layout.track_height=15] The height of each interval rectangle, in px\n * @param {number} [layout.track_vertical_spacing=3]\n * @param {number} [layout.bounding_box_padding=2]\n * @param {boolean} [layout.always_hide_legend=false] Normally the legend is shown in merged mode and hidden\n * in split mode. For datasets with a very large number of categories, it may make sense to hide the legend at all times.\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#B8B8B8'] The color of each datum rectangle\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1]\n * @param {string} [layout.tooltip_positioning='vertical']\n */\n constructor(layout) {\n LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n this._previous_categories = [];\n this._categories = [];\n }\n\n initialize() {\n super.initialize();\n this._statusnodes_group = this.svg.group.append('g')\n .attr('class', 'lz-data-layer-intervals lz-data-layer-intervals-statusnode');\n this._datanodes_group = this.svg.group.append('g')\n .attr('class', 'lz-data_layer-intervals');\n }\n\n /**\n * Split data into tracks such that anything with a common grouping field is in the same track\n * @param data\n * @return {unknown[]}\n * @private\n */\n _arrangeTrackSplit(data) {\n const {track_split_field} = this.layout;\n const result = {};\n data.forEach((item) => {\n const item_key = item[track_split_field];\n if (!Object.prototype.hasOwnProperty.call(result, item_key)) {\n result[item_key] = [];\n }\n result[item_key].push(item);\n });\n return result;\n }\n\n /**\n * Split data into rows using a simple greedy algorithm such that no two items overlap (share same interval)\n * Assumes that the data are sorted so item1.start always <= item2.start.\n *\n * This function can also simply return all data on a single row. This functionality may become configurable\n * in the future but for now reflects a lack of clarity in the requirements/spec. The code to split\n * overlapping items is present but may not see direct use.\n */\n _arrangeTracksLinear(data, allow_overlap = true) {\n if (allow_overlap) {\n // If overlap is allowed, then all the data can live on a single row\n return [data];\n }\n\n // ASSUMPTION: Data is given to us already sorted by start position to facilitate grouping.\n // We do not sort here because JS \"sort\" is not stable- if there are many intervals that overlap, then we\n // can get different layouts (number/order of rows) on each call to \"render\".\n //\n // At present, we decide how to update the y-axis based on whether current and former number of rows are\n // the same. An unstable sort leads to layout thrashing/too many re-renders. FIXME: don't rely on counts\n const {start_field, end_field} = this.layout;\n\n const grouped_data = [[]]; // Prevent two items from colliding by rendering them to different rows, like genes\n data.forEach((item, index) => {\n for (let i = 0; i < grouped_data.length; i++) {\n // Iterate over all rows of the\n const row_to_test = grouped_data[i];\n const last_item = row_to_test[row_to_test.length - 1];\n // Some programs report open intervals, eg 0-1,1-2,2-3; these points are not considered to overlap (hence the test isn't \"<=\")\n const has_overlap = last_item && (item[start_field] < last_item[end_field]) && (last_item[start_field] < item[end_field]);\n if (!has_overlap) {\n // If there is no overlap, add item to current row, and move on to the next item\n row_to_test.push(item);\n return;\n }\n }\n // If this item would collide on all existing rows, create a new row\n grouped_data.push([item]);\n });\n return grouped_data;\n }\n\n /**\n * Annotate each item with the track number, and return.\n * @param {Object[]}data\n * @private\n * @return [String[], Object[]] Return the categories and the data array\n */\n _assignTracks(data) {\n // Flatten the grouped data.\n const {x_scale} = this.parent;\n const {start_field, end_field, bounding_box_padding, track_height} = this.layout;\n\n const grouped_data = this.layout.split_tracks ? this._arrangeTrackSplit(data) : this._arrangeTracksLinear(data, true);\n const categories = Object.keys(grouped_data);\n if (this.layout.track_split_order === 'DESC') {\n categories.reverse();\n }\n\n categories.forEach((key, row_index) => {\n const row = grouped_data[key];\n row.forEach((item) => {\n item[XCS] = x_scale(item[start_field]);\n item[XCE] = x_scale(item[end_field]);\n item[YCS] = row_index * this.getTrackHeight() + bounding_box_padding;\n item[YCE] = item[YCS] + track_height;\n // Store the row ID, so that clicking on a point can find the right status node (big highlight box)\n item.track = row_index;\n });\n });\n // We're mutating elements of the original data array as a side effect: the return value here is\n // interchangeable with `this.data` for subsequent usages\n // TODO: Can replace this with array.flat once polyfill support improves\n return [categories, Object.values(grouped_data).reduce((acc, val) => acc.concat(val), [])];\n }\n\n /**\n * When we are in \"split tracks mode\", it's convenient to wrap all individual annotations with a shared\n * highlight box that wraps everything on that row.\n *\n * This is done automatically by the \"setElementStatus\" code, if this function returns a non-null value\n *\n * To define shared highlighting on the track split field define the status node id override\n * to generate an ID common to the track when we're actively splitting data out to separate tracks\n * @override\n * @returns {String}\n */\n getElementStatusNodeId(element) {\n if (this.layout.split_tracks) {\n // Data nodes are bound to data objects, but the \"status_nodes\" selection is bound to numeric row IDs\n const track = typeof element === 'object' ? element.track : element;\n const base = `${this.getBaseId()}-statusnode-${track}`;\n return base.replace(/[^\\w]/g, '_');\n }\n // In merged tracks mode, there is no separate status node\n return null;\n }\n\n // Helper function to sum layout values to derive total height for a single interval track\n getTrackHeight() {\n return this.layout.track_height\n + this.layout.track_vertical_spacing\n + (2 * this.layout.bounding_box_padding);\n }\n\n // Modify the layout as necessary to ensure that appropriate color, label, and legend options are available\n // Even when not displayed, the legend is used to generate the y-axis ticks\n _applyLayoutOptions() {\n const self = this;\n const base_layout = this._base_layout;\n const render_layout = this.layout;\n const base_color_scale = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n const color_scale = render_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n if (!base_color_scale) {\n // This can be a placeholder (empty categories & values), but it needs to be there\n throw new Error('Interval tracks must define a `categorical_bin` color scale');\n }\n\n const has_colors = base_color_scale.parameters.categories.length && base_color_scale.parameters.values.length;\n const has_legend = base_layout.legend && base_layout.legend.length;\n\n if (!!has_colors ^ !!has_legend) {\n // Don't allow color OR legend to be set manually. It must be both, or neither.\n throw new Error('To use a manually specified color scheme, both color and legend options must be set.');\n }\n\n // Harvest any information about an explicit color field that should be considered when generating colors\n const rgb_option = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'to_rgb';\n });\n const rgb_field = rgb_option && rgb_option.field;\n\n // Auto-generate legend based on data\n const known_categories = this._generateCategoriesFromData(this.data, rgb_field); // [id, label, itemRgb] items\n\n if (!has_colors && !has_legend) {\n // If no color scheme pre-defined, then make a color scheme that is appropriate and apply to the plot\n // The legend must match the color scheme. If we generate one, then we must generate both.\n\n const colors = this._makeColorScheme(known_categories);\n color_scale.parameters.categories = known_categories.map(function (item) {\n return item[0];\n });\n color_scale.parameters.values = colors;\n\n this.layout.legend = known_categories.map(function (pair, index) {\n const id = pair[0];\n const label = pair[1];\n const item_color = color_scale.parameters.values[index];\n const item = { shape: 'rect', width: 9, label: label, color: item_color };\n item[self.layout.track_split_field] = id;\n return item;\n });\n }\n }\n\n // Implement the main render function\n render() {\n //// Autogenerate layout options if not provided\n this._applyLayoutOptions();\n\n // Determine the appropriate layout for tracks. Store the previous categories (y axis ticks) to decide\n // whether the axis needs to be re-rendered.\n this._previous_categories = this._categories;\n const [categories, assigned_data] = this._assignTracks(this.data);\n this._categories = categories;\n // Update the legend axis if the number of ticks changed\n const labels_changed = !categories.every( (item, index) => item === this._previous_categories[index]);\n if (labels_changed) {\n this.updateSplitTrackAxis(categories);\n return;\n }\n\n // Apply filters to only render a specified set of points. Hidden fields will still be given space to render, but not shown.\n const track_data = this._applyFilters(assigned_data);\n\n // Clear before every render so that, eg, highlighting doesn't persist if we load a region with different\n // categories (row 2 might be a different category and it's confusing if the row stays highlighted but changes meaning)\n // Highlighting will automatically get added back if it actually makes sense, courtesy of setElementStatus,\n // if a selected item is still in view after the new region loads.\n this._statusnodes_group.selectAll('rect')\n .remove();\n\n // Reselect in order to add new data\n const status_nodes = this._statusnodes_group.selectAll('rect')\n .data(d3.range(categories.length));\n\n if (this.layout.split_tracks) {\n // Status nodes: a big highlight box around all items of the same type. Used in split tracks mode,\n // because everything on the same row is the same category and a group makes sense\n // There are no status nodes in merged mode, because the same row contains many kinds of things\n\n // Status nodes are 1 per row, so \"data\" can just be a dummy list of possible row IDs\n // Each status node is a box that runs the length of the panel and receives a special \"colored box\" css\n // style when selected\n const height = this.getTrackHeight();\n status_nodes.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-intervals lz-data_layer-intervals-statusnode lz-data_layer-intervals-shared')\n .attr('rx', this.layout.bounding_box_padding)\n .attr('ry', this.layout.bounding_box_padding)\n .merge(status_nodes)\n .attr('id', (d) => this.getElementStatusNodeId(d))\n .attr('x', 0)\n .attr('y', (d) => (d * height))\n .attr('width', this.parent.layout.cliparea.width)\n .attr('height', height - this.layout.track_vertical_spacing);\n }\n status_nodes.exit()\n .remove();\n\n // Draw rectangles for the data (intervals)\n const data_nodes = this._datanodes_group.selectAll('rect')\n .data(track_data, (d) => d[this.layout.id_field]);\n\n data_nodes.enter()\n .append('rect')\n .merge(data_nodes)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => d[XCS])\n .attr('y', (d) => d[YCS])\n .attr('width', (d) => d[XCE] - d[XCS])\n .attr('height', this.layout.track_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 data_nodes.exit()\n .remove();\n\n this._datanodes_group\n .call(this.applyBehaviors.bind(this));\n\n // The intervals track allows legends to be dynamically generated, in which case space can only be\n // allocated after the panel has been rendered.\n if (this.parent && this.parent.legend) {\n this.parent.legend.render();\n }\n }\n\n _getTooltipPosition(tooltip) {\n return {\n x_min: tooltip.data[XCS],\n x_max: tooltip.data[XCE],\n y_min: tooltip.data[YCS],\n y_max: tooltip.data[YCE],\n };\n }\n\n // Redraw split track axis or hide it, and show/hide the legend, as determined\n // by current layout parameters and data\n updateSplitTrackAxis(categories) {\n const legend_axis = this.layout.track_split_legend_to_y_axis ? `y${this.layout.track_split_legend_to_y_axis}` : false;\n if (this.layout.split_tracks) {\n const tracks = +categories.length || 0;\n const track_height = +this.layout.track_height || 0;\n const track_spacing = 2 * (+this.layout.bounding_box_padding || 0) + (+this.layout.track_vertical_spacing || 0);\n const target_height = (tracks * track_height) + ((tracks - 1) * track_spacing);\n this.parent.scaleHeightToData(target_height);\n if (legend_axis && this.parent.legend) {\n this.parent.legend.hide();\n this.parent.layout.axes[legend_axis] = {\n render: true,\n ticks: [],\n range: {\n start: (target_height - (this.layout.track_height / 2)),\n end: (this.layout.track_height / 2),\n },\n };\n // There is a very tight coupling between the display directives: each legend item must identify a key\n // field for unique tracks. (Typically this is `state_id`, the same key field used to assign unique colors)\n // The list of unique keys corresponds to the order along the y-axis\n this.layout.legend.forEach((element) => {\n const key = element[this.layout.track_split_field];\n let track = categories.findIndex((item) => item === key);\n if (track !== -1) {\n if (this.layout.track_split_order === 'DESC') {\n track = Math.abs(track - tracks - 1);\n }\n this.parent.layout.axes[legend_axis].ticks.push({\n y: track - 1,\n text: element.label,\n });\n }\n });\n this.layout.y_axis = {\n axis: this.layout.track_split_legend_to_y_axis,\n floor: 1,\n ceiling: tracks,\n };\n }\n // This will trigger a re-render\n this.parent_plot.positionPanels();\n } else {\n if (legend_axis && this.parent.legend) {\n if (!this.layout.always_hide_legend) {\n this.parent.legend.show();\n }\n this.parent.layout.axes[legend_axis] = { render: false };\n this.parent.render();\n }\n }\n return this;\n }\n\n // Method to not only toggle the split tracks boolean but also update\n // necessary display values to animate a complete merge/split\n toggleSplitTracks() {\n this.layout.split_tracks = !this.layout.split_tracks;\n if (this.parent.legend && !this.layout.always_hide_legend) {\n this.parent.layout.margin.bottom = 5 + (this.layout.split_tracks ? 0 : this.parent.legend.layout.height + 5);\n }\n this.render();\n return this;\n }\n\n // Choose an appropriate color scheme based on the number of items in the track, and whether or not we are\n // using explicitly provided itemRgb information\n _makeColorScheme(category_info) {\n // If at least one element has an explicit itemRgb, assume the entire dataset has colors\n const has_explicit_colors = category_info.find((item) => item[2]);\n if (has_explicit_colors) {\n return category_info.map((item) => item[2]);\n }\n\n // Use a set of color schemes for common 15, 18, or 25 state models, as specified from:\n // https://egg2.wustl.edu/roadmap/web_portal/chr_state_learning.html\n // These are actually reversed so that dim colors come first, on the premise that usually these are the\n // most common states\n const n_categories = category_info.length;\n if (n_categories <= 15) {\n return ['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)'];\n } else if (n_categories <= 18) {\n return ['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)'];\n } else {\n // If there are more than 25 categories, the interval layer will fall back to the 'null value' option\n return ['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)'];\n }\n }\n\n /**\n * Find all of the unique tracks (a combination of name and ID information)\n * @param {Object} data\n * @param {String} [rgb_field] A field that contains an RGB value. Aimed at BED files with an itemRgb column\n * @private\n * @returns {Array} All [unique_id, label, color] pairs in data. The unique_id is the thing used to define groupings\n * most unambiguously.\n */\n _generateCategoriesFromData(data, rgb_field) {\n const self = this;\n // Use the hard-coded legend if available (ignoring any mods on re-render)\n const legend = this._base_layout.legend;\n if (legend && legend.length) {\n return legend.map((item) => [item[this.layout.track_split_field], item.label, item.color]);\n }\n\n // Generate options from data, if no preset legend exists\n const unique_ids = {}; // make categories unique\n const categories = [];\n\n data.forEach((item) => {\n const id = item[self.layout.track_split_field];\n if (!Object.prototype.hasOwnProperty.call(unique_ids, id)) {\n unique_ids[id] = null;\n // If rgbfield is null, then the last entry is undefined/null as well\n categories.push([id, item[this.layout.track_label_field], item[rgb_field]]);\n }\n });\n return categories;\n }\n }\n\n /**\n * (**extension**) A basic tooltip with information to be shown over an intervals datum\n * @alias module:LocusZoom_Layouts~standard_intervals\n * @type tooltip\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_tooltip_layout = {\n namespace: { 'intervals': 'intervals' },\n closable: false,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{{{namespace[intervals]}}state_name|htmlescape}}
{{{{namespace[intervals]}}start|htmlescape}}-{{{{namespace[intervals]}}end|htmlescape}}',\n };\n\n /**\n * (**extension**) A data layer with some preconfigured options for intervals display. This example was designed for chromHMM output,\n * in which various states are assigned numeric state IDs and (<= as many) text state names\n * @alias module:LocusZoom_Layouts~intervals_layer\n * @type data_layer\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_layer_layout = {\n namespace: { 'intervals': 'intervals' },\n id: 'intervals',\n type: 'intervals',\n tag: 'intervals',\n fields: ['{{namespace[intervals]}}start', '{{namespace[intervals]}}end', '{{namespace[intervals]}}state_id', '{{namespace[intervals]}}state_name', '{{namespace[intervals]}}itemRgb'],\n id_field: '{{namespace[intervals]}}start', // FIXME: This is not a good D3 \"are these datums redundant\" ID for datasets with multiple intervals heavily overlapping\n start_field: '{{namespace[intervals]}}start',\n end_field: '{{namespace[intervals]}}end',\n track_split_field: '{{namespace[intervals]}}state_name',\n track_label_field: '{{namespace[intervals]}}state_name',\n split_tracks: false,\n always_hide_legend: true,\n color: [\n {\n // If present, an explicit color field will override any other option (and be used to auto-generate legend)\n field: '{{namespace[intervals]}}itemRgb',\n scale_function: 'to_rgb',\n },\n {\n // TODO: Consider changing this to stable_choice in the future, for more stable coloring\n field: '{{namespace[intervals]}}state_name',\n scale_function: 'categorical_bin',\n parameters: {\n // Placeholder. Empty categories and values will automatically be filled in when new data loads.\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n },\n ],\n legend: [], // Placeholder; auto-filled when data loads.\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: intervals_tooltip_layout,\n };\n\n /**\n * (**extension**) A panel containing an intervals data layer, eg for BED tracks\n * @alias module:LocusZoom_Layouts~intervals\n * @type panel\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_panel_layout = {\n id: 'intervals',\n tag: 'intervals',\n min_height: 50,\n height: 50,\n margin: { top: 25, right: 150, bottom: 5, left: 50 },\n toolbar: (function () {\n const l = LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true });\n l.widgets.push({\n type: 'toggle_split_tracks',\n data_layer_id: 'intervals',\n position: 'right',\n });\n return l;\n })(),\n axes: {},\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n legend: {\n hidden: true,\n orientation: 'horizontal',\n origin: { x: 50, y: 0 },\n pad_from_bottom: 5,\n },\n data_layers: [intervals_layer_layout],\n };\n\n /**\n * (**extension**) A plot layout that shows association summary statistics, genes, and interval data. This example assumes\n * chromHMM data. (see panel layout)\n * @alias module:LocusZoom_Layouts~interval_association\n * @type plot\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_plot_layout = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }),\n panels: [\n LocusZoom.Layouts.get('panel', 'association'),\n LocusZoom.Layouts.merge({ unnamespaced: true, min_height: 120, height: 120 }, intervals_panel_layout),\n LocusZoom.Layouts.get('panel', 'genes'),\n ],\n };\n\n LocusZoom.Adapters.add('IntervalLZ', IntervalLZ);\n LocusZoom.DataLayers.add('intervals', LzIntervalsTrack);\n\n LocusZoom.Layouts.add('tooltip', 'standard_intervals', intervals_tooltip_layout);\n LocusZoom.Layouts.add('data_layer', 'intervals', intervals_layer_layout);\n LocusZoom.Layouts.add('panel', 'intervals', intervals_panel_layout);\n LocusZoom.Layouts.add('plot', 'interval_association', intervals_plot_layout);\n\n LocusZoom.ScaleFunctions.add('to_rgb', to_rgb);\n\n LocusZoom.Widgets.add('toggle_split_tracks', ToggleSplitTracks);\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/ext/lz-intervals-track.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","d3","XCS","Symbol","for","YCS","XCE","YCE","install","LocusZoom","BaseUMAdapter","Adapters","_Button","Widgets","_BaseWidget","to_rgb","parameters","value","default_layout","start_field","end_field","track_label_field","track_split_field","track_split_order","track_split_legend_to_y_axis","split_tracks","track_height","track_vertical_spacing","bounding_box_padding","always_hide_legend","color","fill_opacity","tooltip_positioning","BaseLayer","DataLayers","intervals_tooltip_layout","closable","show","or","hide","and","html","intervals_layer_layout","namespace","id","type","tag","id_field","field","scale_function","categories","values","null_value","legend","behaviors","onmouseover","action","status","onmouseout","onclick","exclusive","onshiftclick","tooltip","bed_intervals_layer_layout","Layouts","merge","intervals_panel_layout","min_height","height","margin","top","right","bottom","left","toolbar","l","widgets","push","data_layer_id","position","axes","interaction","drag_background_to_pan","scroll_to_zoom","x_linked","hidden","orientation","origin","x","y","pad_from_bottom","data_layers","bed_intervals_panel_layout","intervals_plot_layout","state","width","responsive_resize","min_region_scale","max_region_scale","panels","add","request_options","query","this","_config","source","chr","end","start","super","_getURL","layout","arguments","_previous_categories","_categories","initialize","_statusnodes_group","svg","group","append","attr","_datanodes_group","data","result","forEach","item","item_key","allow_overlap","grouped_data","index","i","length","row_to_test","last_item","x_scale","parent","_arrangeTrackSplit","_arrangeTracksLinear","keys","reverse","row_index","getTrackHeight","track","reduce","acc","val","concat","element","getBaseId","replace","self","base_layout","_base_layout","render_layout","base_color_scale","find","color_scale","Error","has_colors","has_legend","rgb_option","rgb_field","known_categories","_generateCategoriesFromData","colors","_makeColorScheme","map","pair","shape","label","_applyLayoutOptions","assigned_data","_assignTracks","every","updateSplitTrackAxis","track_data","_applyFilters","selectAll","remove","status_nodes","enter","d","getElementStatusNodeId","cliparea","Math","max","exit","data_nodes","getElementId","resolveScalableParameter","applyBehaviors","bind","render","x_min","x_max","y_min","y_max","legend_axis","tracks","track_spacing","target_height","scaleHeightToData","ticks","range","findIndex","abs","text","y_axis","axis","floor","ceiling","parent_plot","positionPanels","category_info","n_categories","unique_ids","ScaleFunctions","parent_panel","data_layer","button","setHtml","setColor","setTitle","setOnclick","toggleSplitTracks","scale_timeout","clearTimeout","setTimeout","update","use"],"mappings":";wCACA,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,4BCAlF,MAAM,EAA+BI,GCwC/BC,EAAMC,OAAOC,IAAI,SACjBC,EAAMF,OAAOC,IAAI,SACjBE,EAAMH,OAAOC,IAAI,SACjBG,EAAMJ,OAAOC,IAAI,SAGvB,SAASI,EAASC,GACd,MAAMC,EAAgBD,EAAUE,SAAShB,IAAI,iBACvCiB,EAAUH,EAAUI,QAAQlB,IAAI,WAChCmB,EAAcL,EAAUI,QAAQlB,IAAI,cAkF1C,SAASoB,EAAOC,EAAYC,GACxB,OAAOA,EAAQ,OAAOA,KAAW,KAGrC,MAAMC,EAAiB,CACnBC,YAAa,QACbC,UAAW,MACXC,kBAAmB,aAKnBC,kBAAmB,WACnBC,kBAAmB,OACnBC,6BAA8B,EAC9BC,cAAc,EACdC,aAAc,GACdC,uBAAwB,EACxBC,qBAAsB,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W,qBAAsBjE,GACvD1B,EAAUuD,QAAQoC,IAAI,aAAc,YAAa1D,GACjDjC,EAAUuD,QAAQoC,IAAI,aAAc,gBAAiBrC,GACrDtD,EAAUuD,QAAQoC,IAAI,QAAS,YAAalC,GAC5CzD,EAAUuD,QAAQoC,IAAI,QAAS,gBAAiBR,GAChDnF,EAAUuD,QAAQoC,IAAI,OAAQ,uBAAwBP,GAEtDpF,EAAU+M,eAAepH,IAAI,SAAUrF,GAEvCN,EAAUI,QAAQuF,IAAI,sBA9sBtB,cAAgCtF,EAI5B,YAAYiG,GAKR,GAJAF,SAASG,WACJD,EAAOjC,gBACRiC,EAAOjC,cAAgB,cAEtByB,KAAKkH,aAAa9H,YAAYoB,EAAOjC,eACtC,MAAM,IAAI+E,MAAM,iEAIxB,SACI,MAAM6D,EAAanH,KAAKkH,aAAa9H,YAAYY,KAAKQ,OAAOjC,eACvDrC,EAAOiL,EAAW3G,OAAOtF,aAAe,eAAiB,eAC/D,OAAI8E,KAAKoH,QACLpH,KAAKoH,OAAOC,QAAQnL,GACpB8D,KAAKoH,OAAOtL,OACZkE,KAAKgC,OAAOxD,WACLwB,OAEPA,KAAKoH,OAAS,IAAI/M,EAAQ2F,MACrBsH,SAAStH,KAAKQ,OAAOjF,OACrB8L,QAAQnL,GACRqL,SAAS,4DACTC,YAAW,KACRL,EAAWM,oBAIPzH,KAAK0H,eACLC,aAAa3H,KAAK0H,eAEtB1H,KAAK0H,cAAgBE,YAAW,KAC5B5H,KAAKkH,aAAahB,oBAClBlG,KAAK4G,YAAYC,mBAClB,GACH7G,KAAK6H,YAEN7H,KAAK6H,aAwqBH,oBAAd3N,WAGPA,UAAU4N,IAAI7N,GAIlB,U","file":"ext/lz-intervals-track.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 * Interval annotation track (for chromatin state, etc). Useful for BED file data with non-overlapping intervals.\n * This is not part of the core LocusZoom library, but can be included as a standalone file.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~IntervalLZ}\n * * {@link module:LocusZoom_Widgets~toggle_split_tracks}\n * * {@link module:LocusZoom_ScaleFunctions~to_rgb}\n * * {@link module:LocusZoom_DataLayers~intervals}\n * * {@link module:LocusZoom_Layouts~standard_intervals}\n * * {@link module:LocusZoom_Layouts~bed_intervals_layer}\n * * {@link module:LocusZoom_Layouts~intervals_layer}\n * * {@link module:LocusZoom_Layouts~intervals}\n * * {@link module:LocusZoom_Layouts~bed_intervals}\n * * {@link module:LocusZoom_Layouts~interval_association}\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import IntervalsTrack from 'locuszoom/esm/ext/lz-intervals-track';\n * LocusZoom.use(IntervalsTrack);\n * ```\n *\n * Then use the features made available by this extension. (see demos and documentation for guidance)\n * @module\n */\n\nimport * as d3 from 'd3';\n\n\n// Coordinates (start, end) are cached to facilitate rendering\nconst XCS = Symbol.for('lzXCS');\nconst YCS = Symbol.for('lzYCS');\nconst XCE = Symbol.for('lzXCE');\nconst YCE = Symbol.for('lzYCE');\n\n\nfunction install (LocusZoom) {\n const BaseUMAdapter = LocusZoom.Adapters.get('BaseUMAdapter');\n const _Button = LocusZoom.Widgets.get('_Button');\n const _BaseWidget = LocusZoom.Widgets.get('BaseWidget');\n\n /**\n * (**extension**) Retrieve Interval Annotation Data (e.g. BED Tracks), as fetched from the LocusZoom API server (or compatible)\n * @public\n * @alias module:LocusZoom_Adapters~IntervalLZ\n * @see module:LocusZoom_Adapters~BaseUMAdapter\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n * @param {number} config.params.source The numeric ID for a specific dataset as assigned by the API server\n */\n class IntervalLZ extends BaseUMAdapter {\n _getURL(request_options) {\n const source = this._config.source;\n const query = `?filter=id in ${source} and chromosome eq '${request_options.chr}' and start le ${request_options.end} and end ge ${request_options.start}`;\n\n const base = super._getURL(request_options);\n return `${base}${query}`;\n }\n }\n\n /**\n * (**extension**) Button to toggle split tracks mode in an intervals track. This button only works as a panel-level toolbar\n * and when used with an intervals data layer from this extension.\n * @alias module:LocusZoom_Widgets~toggle_split_tracks\n * @see module:LocusZoom_Widgets~BaseWidget\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n class ToggleSplitTracks extends _BaseWidget {\n /**\n * @param {string} layout.data_layer_id The ID of the data layer that this button is intended to control.\n */\n constructor(layout) {\n super(...arguments);\n if (!layout.data_layer_id) {\n layout.data_layer_id = 'intervals';\n }\n if (!this.parent_panel.data_layers[layout.data_layer_id]) {\n throw new Error('Toggle split tracks widget specifies an invalid data layer ID');\n }\n }\n\n update() {\n const data_layer = this.parent_panel.data_layers[this.layout.data_layer_id];\n const html = data_layer.layout.split_tracks ? 'Merge Tracks' : 'Split Tracks';\n if (this.button) {\n this.button.setHtml(html);\n this.button.show();\n this.parent.position();\n return this;\n } else {\n this.button = new _Button(this)\n .setColor(this.layout.color)\n .setHtml(html)\n .setTitle('Toggle whether tracks are split apart or merged together')\n .setOnclick(() => {\n data_layer.toggleSplitTracks();\n // FIXME: the timeout calls to scale and position (below) cause full ~5 additional re-renders\n // If we can remove these it will greatly speed up re-rendering.\n // The key problem here is that the height is apparently not known in advance and is determined after re-render.\n if (this.scale_timeout) {\n clearTimeout(this.scale_timeout);\n }\n this.scale_timeout = setTimeout(() => {\n this.parent_panel.scaleHeightToData();\n this.parent_plot.positionPanels();\n }, 0);\n this.update();\n });\n return this.update();\n }\n }\n }\n\n\n /**\n * (**extension**) Convert a value \"\"rr,gg,bb\" (if given) to a css-friendly color string: \"rgb(rr,gg,bb)\".\n * This is tailored specifically to the color specification format embraced by the BED file standard.\n * @alias module:LocusZoom_ScaleFunctions~to_rgb\n * @param {Object} parameters This function has no defined configuration options\n * @param {String|null} value The value to convert to rgb\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n function to_rgb(parameters, value) {\n return value ? `rgb(${value})` : null;\n }\n\n const default_layout = {\n start_field: 'start',\n end_field: 'end',\n track_label_field: 'state_name', // Used to label items on the y-axis\n // Used to uniquely identify tracks for coloring. This tends to lead to more stable coloring/sorting\n // than using the label field- eg, state_ids allow us to set global colors across the entire dataset,\n // not just choose unique colors within a particular narrow region. (where changing region might lead to more\n // categories and different colors)\n track_split_field: 'state_id',\n track_split_order: 'DESC',\n track_split_legend_to_y_axis: 2,\n split_tracks: true,\n track_height: 15,\n track_vertical_spacing: 3,\n bounding_box_padding: 2,\n always_hide_legend: false,\n color: '#B8B8B8',\n fill_opacity: 1,\n tooltip_positioning: 'vertical',\n };\n\n const BaseLayer = LocusZoom.DataLayers.get('BaseDataLayer');\n\n /**\n * (**extension**) Implements a data layer that will render interval annotation tracks (intervals must provide start and end values)\n * Each interval (such as from a BED file) will be rendered as a rectangle. All spans can be rendered on the same\n * row, or each (auto-detected) category can be rendered as one row per category.\n *\n * This layer is intended to work with a variety of datasets with special requirements. As such, it has a lot\n * of configuration options devoted to identifying how to fill in missing information (such as color)\n *\n * @alias module:LocusZoom_DataLayers~intervals\n * @see module:LocusZoom_DataLayers~BaseDataLayer\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n class LzIntervalsTrack extends BaseLayer {\n /**\n * @param {string} [layout.start_field='start'] The field that defines interval start position\n * @param {string} [layout.end_field='end'] The field that defines interval end position\n * @param {string} [layout.track_label_field='state_name'] Used to label items on the y-axis\n * @param {string} [layout.track_split_field='state_id'] Used to define categories on the y-axis. It is usually most convenient to use\n * the same value for state_field and label_field (eg 1:1 correspondence).\n * @param {*|'DESC'} [layout.track_split_order='DESC'] When in split tracks mode, should categories be shown in\n * the order given, or descending order\n * @param {number} [layout.track_split_legend_to_y_axis=2]\n * @param {boolean} [layout.split_tracks=true] Whether to show tracks as merged (one row) or split (many rows)\n * on initial render.\n * @param {number} [layout.track_height=15] The height of each interval rectangle, in px\n * @param {number} [layout.track_vertical_spacing=3]\n * @param {number} [layout.bounding_box_padding=2]\n * @param {boolean} [layout.always_hide_legend=false] Normally the legend is shown in merged mode and hidden\n * in split mode. For datasets with a very large number of categories, it may make sense to hide the legend at all times.\n * @param {string|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#B8B8B8'] The color of each datum rectangle\n * @param {number|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=1]\n * @param {string} [layout.tooltip_positioning='vertical']\n */\n constructor(layout) {\n LocusZoom.Layouts.merge(layout, default_layout);\n super(...arguments);\n this._previous_categories = [];\n this._categories = [];\n }\n\n initialize() {\n super.initialize();\n this._statusnodes_group = this.svg.group.append('g')\n .attr('class', 'lz-data-layer-intervals lz-data-layer-intervals-statusnode');\n this._datanodes_group = this.svg.group.append('g')\n .attr('class', 'lz-data_layer-intervals');\n }\n\n /**\n * Split data into tracks such that anything with a common grouping field is in the same track\n * @param data\n * @return {unknown[]}\n * @private\n */\n _arrangeTrackSplit(data) {\n const {track_split_field} = this.layout;\n const result = {};\n data.forEach((item) => {\n const item_key = item[track_split_field];\n if (!Object.prototype.hasOwnProperty.call(result, item_key)) {\n result[item_key] = [];\n }\n result[item_key].push(item);\n });\n return result;\n }\n\n /**\n * Split data into rows using a simple greedy algorithm such that no two items overlap (share same interval)\n * Assumes that the data are sorted so item1.start always <= item2.start.\n *\n * This function can also simply return all data on a single row. This functionality may become configurable\n * in the future but for now reflects a lack of clarity in the requirements/spec. The code to split\n * overlapping items is present but may not see direct use.\n */\n _arrangeTracksLinear(data, allow_overlap = true) {\n if (allow_overlap) {\n // If overlap is allowed, then all the data can live on a single row\n return [data];\n }\n\n // ASSUMPTION: Data is given to us already sorted by start position to facilitate grouping.\n // We do not sort here because JS \"sort\" is not stable- if there are many intervals that overlap, then we\n // can get different layouts (number/order of rows) on each call to \"render\".\n //\n // At present, we decide how to update the y-axis based on whether current and former number of rows are\n // the same. An unstable sort leads to layout thrashing/too many re-renders. FIXME: don't rely on counts\n const {start_field, end_field} = this.layout;\n\n const grouped_data = [[]]; // Prevent two items from colliding by rendering them to different rows, like genes\n data.forEach((item, index) => {\n for (let i = 0; i < grouped_data.length; i++) {\n // Iterate over all rows of the\n const row_to_test = grouped_data[i];\n const last_item = row_to_test[row_to_test.length - 1];\n // Some programs report open intervals, eg 0-1,1-2,2-3; these points are not considered to overlap (hence the test isn't \"<=\")\n const has_overlap = last_item && (item[start_field] < last_item[end_field]) && (last_item[start_field] < item[end_field]);\n if (!has_overlap) {\n // If there is no overlap, add item to current row, and move on to the next item\n row_to_test.push(item);\n return;\n }\n }\n // If this item would collide on all existing rows, create a new row\n grouped_data.push([item]);\n });\n return grouped_data;\n }\n\n /**\n * Annotate each item with the track number, and return.\n * @param {Object[]}data\n * @private\n * @return [String[], Object[]] Return the categories and the data array\n */\n _assignTracks(data) {\n // Flatten the grouped data.\n const {x_scale} = this.parent;\n const {start_field, end_field, bounding_box_padding, track_height} = this.layout;\n\n const grouped_data = this.layout.split_tracks ? this._arrangeTrackSplit(data) : this._arrangeTracksLinear(data, true);\n const categories = Object.keys(grouped_data);\n if (this.layout.track_split_order === 'DESC') {\n categories.reverse();\n }\n\n categories.forEach((key, row_index) => {\n const row = grouped_data[key];\n row.forEach((item) => {\n item[XCS] = x_scale(item[start_field]);\n item[XCE] = x_scale(item[end_field]);\n item[YCS] = row_index * this.getTrackHeight() + bounding_box_padding;\n item[YCE] = item[YCS] + track_height;\n // Store the row ID, so that clicking on a point can find the right status node (big highlight box)\n item.track = row_index;\n });\n });\n // We're mutating elements of the original data array as a side effect: the return value here is\n // interchangeable with `this.data` for subsequent usages\n // TODO: Can replace this with array.flat once polyfill support improves\n return [categories, Object.values(grouped_data).reduce((acc, val) => acc.concat(val), [])];\n }\n\n /**\n * When we are in \"split tracks mode\", it's convenient to wrap all individual annotations with a shared\n * highlight box that wraps everything on that row.\n *\n * This is done automatically by the \"setElementStatus\" code, if this function returns a non-null value\n *\n * To define shared highlighting on the track split field define the status node id override\n * to generate an ID common to the track when we're actively splitting data out to separate tracks\n * @override\n * @returns {String}\n */\n getElementStatusNodeId(element) {\n if (this.layout.split_tracks) {\n // Data nodes are bound to data objects, but the \"status_nodes\" selection is bound to numeric row IDs\n const track = typeof element === 'object' ? element.track : element;\n const base = `${this.getBaseId()}-statusnode-${track}`;\n return base.replace(/[^\\w]/g, '_');\n }\n // In merged tracks mode, there is no separate status node\n return null;\n }\n\n // Helper function to sum layout values to derive total height for a single interval track\n getTrackHeight() {\n return this.layout.track_height\n + this.layout.track_vertical_spacing\n + (2 * this.layout.bounding_box_padding);\n }\n\n // Modify the layout as necessary to ensure that appropriate color, label, and legend options are available\n // Even when not displayed, the legend is used to generate the y-axis ticks\n _applyLayoutOptions() {\n const self = this;\n const base_layout = this._base_layout;\n const render_layout = this.layout;\n const base_color_scale = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n const color_scale = render_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n if (!base_color_scale) {\n // This can be a placeholder (empty categories & values), but it needs to be there\n throw new Error('Interval tracks must define a `categorical_bin` color scale');\n }\n\n const has_colors = base_color_scale.parameters.categories.length && base_color_scale.parameters.values.length;\n const has_legend = base_layout.legend && base_layout.legend.length;\n\n if (!!has_colors ^ !!has_legend) {\n // Don't allow color OR legend to be set manually. It must be both, or neither.\n throw new Error('To use a manually specified color scheme, both color and legend options must be set.');\n }\n\n // Harvest any information about an explicit color field that should be considered when generating colors\n const rgb_option = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'to_rgb';\n });\n const rgb_field = rgb_option && rgb_option.field;\n\n // Auto-generate legend based on data\n const known_categories = this._generateCategoriesFromData(this.data, rgb_field); // [id, label, itemRgb] items\n\n if (!has_colors && !has_legend) {\n // If no color scheme pre-defined, then make a color scheme that is appropriate and apply to the plot\n // The legend must match the color scheme. If we generate one, then we must generate both.\n\n const colors = this._makeColorScheme(known_categories);\n color_scale.parameters.categories = known_categories.map(function (item) {\n return item[0];\n });\n color_scale.parameters.values = colors;\n\n this.layout.legend = known_categories.map(function (pair, index) {\n const id = pair[0];\n const label = pair[1];\n const item_color = color_scale.parameters.values[index];\n const item = { shape: 'rect', width: 9, label: label, color: item_color };\n item[self.layout.track_split_field] = id;\n return item;\n });\n }\n }\n\n // Implement the main render function\n render() {\n //// Autogenerate layout options if not provided\n this._applyLayoutOptions();\n\n // Determine the appropriate layout for tracks. Store the previous categories (y axis ticks) to decide\n // whether the axis needs to be re-rendered.\n this._previous_categories = this._categories;\n const [categories, assigned_data] = this._assignTracks(this.data);\n this._categories = categories;\n // Update the legend axis if the number of ticks changed\n const labels_changed = !categories.every( (item, index) => item === this._previous_categories[index]);\n if (labels_changed) {\n this.updateSplitTrackAxis(categories);\n return;\n }\n\n // Apply filters to only render a specified set of points. Hidden fields will still be given space to render, but not shown.\n const track_data = this._applyFilters(assigned_data);\n\n // Clear before every render so that, eg, highlighting doesn't persist if we load a region with different\n // categories (row 2 might be a different category and it's confusing if the row stays highlighted but changes meaning)\n // Highlighting will automatically get added back if it actually makes sense, courtesy of setElementStatus,\n // if a selected item is still in view after the new region loads.\n this._statusnodes_group.selectAll('rect')\n .remove();\n\n // Reselect in order to add new data\n const status_nodes = this._statusnodes_group.selectAll('rect')\n .data(d3.range(categories.length));\n\n if (this.layout.split_tracks) {\n // Status nodes: a big highlight box around all items of the same type. Used in split tracks mode,\n // because everything on the same row is the same category and a group makes sense\n // There are no status nodes in merged mode, because the same row contains many kinds of things\n\n // Status nodes are 1 per row, so \"data\" can just be a dummy list of possible row IDs\n // Each status node is a box that runs the length of the panel and receives a special \"colored box\" css\n // style when selected\n const height = this.getTrackHeight();\n status_nodes.enter()\n .append('rect')\n .attr('class', 'lz-data_layer-intervals lz-data_layer-intervals-statusnode lz-data_layer-intervals-shared')\n .attr('rx', this.layout.bounding_box_padding)\n .attr('ry', this.layout.bounding_box_padding)\n .merge(status_nodes)\n .attr('id', (d) => this.getElementStatusNodeId(d))\n .attr('x', 0)\n .attr('y', (d) => (d * height))\n .attr('width', this.parent.layout.cliparea.width)\n .attr('height', Math.max(height - this.layout.track_vertical_spacing, 1));\n }\n status_nodes.exit()\n .remove();\n\n // Draw rectangles for the data (intervals)\n const data_nodes = this._datanodes_group.selectAll('rect')\n .data(track_data, (d) => d[this.layout.id_field]);\n\n data_nodes.enter()\n .append('rect')\n .merge(data_nodes)\n .attr('id', (d) => this.getElementId(d))\n .attr('x', (d) => d[XCS])\n .attr('y', (d) => d[YCS])\n .attr('width', (d) => Math.max(d[XCE] - d[XCS], 1))\n .attr('height', this.layout.track_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 data_nodes.exit()\n .remove();\n\n this._datanodes_group\n .call(this.applyBehaviors.bind(this));\n\n // The intervals track allows legends to be dynamically generated, in which case space can only be\n // allocated after the panel has been rendered.\n if (this.parent && this.parent.legend) {\n this.parent.legend.render();\n }\n }\n\n _getTooltipPosition(tooltip) {\n return {\n x_min: tooltip.data[XCS],\n x_max: tooltip.data[XCE],\n y_min: tooltip.data[YCS],\n y_max: tooltip.data[YCE],\n };\n }\n\n // Redraw split track axis or hide it, and show/hide the legend, as determined\n // by current layout parameters and data\n updateSplitTrackAxis(categories) {\n const legend_axis = this.layout.track_split_legend_to_y_axis ? `y${this.layout.track_split_legend_to_y_axis}` : false;\n if (this.layout.split_tracks) {\n const tracks = +categories.length || 0;\n const track_height = +this.layout.track_height || 0;\n const track_spacing = 2 * (+this.layout.bounding_box_padding || 0) + (+this.layout.track_vertical_spacing || 0);\n const target_height = (tracks * track_height) + ((tracks - 1) * track_spacing);\n this.parent.scaleHeightToData(target_height);\n if (legend_axis && this.parent.legend) {\n this.parent.legend.hide();\n this.parent.layout.axes[legend_axis] = {\n render: true,\n ticks: [],\n range: {\n start: (target_height - (this.layout.track_height / 2)),\n end: (this.layout.track_height / 2),\n },\n };\n // There is a very tight coupling between the display directives: each legend item must identify a key\n // field for unique tracks. (Typically this is `state_id`, the same key field used to assign unique colors)\n // The list of unique keys corresponds to the order along the y-axis\n this.layout.legend.forEach((element) => {\n const key = element[this.layout.track_split_field];\n let track = categories.findIndex((item) => item === key);\n if (track !== -1) {\n if (this.layout.track_split_order === 'DESC') {\n track = Math.abs(track - tracks - 1);\n }\n this.parent.layout.axes[legend_axis].ticks.push({\n y: track - 1,\n text: element.label,\n });\n }\n });\n this.layout.y_axis = {\n axis: this.layout.track_split_legend_to_y_axis,\n floor: 1,\n ceiling: tracks,\n };\n }\n // This will trigger a re-render\n this.parent_plot.positionPanels();\n } else {\n if (legend_axis && this.parent.legend) {\n if (!this.layout.always_hide_legend) {\n this.parent.legend.show();\n }\n this.parent.layout.axes[legend_axis] = { render: false };\n this.parent.render();\n }\n }\n return this;\n }\n\n // Method to not only toggle the split tracks boolean but also update\n // necessary display values to animate a complete merge/split\n toggleSplitTracks() {\n this.layout.split_tracks = !this.layout.split_tracks;\n if (this.parent.legend && !this.layout.always_hide_legend) {\n this.parent.layout.margin.bottom = 5 + (this.layout.split_tracks ? 0 : this.parent.legend.layout.height + 5);\n }\n this.render();\n return this;\n }\n\n // Choose an appropriate color scheme based on the number of items in the track, and whether or not we are\n // using explicitly provided itemRgb information\n _makeColorScheme(category_info) {\n // If at least one element has an explicit itemRgb, assume the entire dataset has colors. BED intervals require rgb triplets,so assume that colors will always be \"r,g,b\" format.\n const has_explicit_colors = category_info.find((item) => item[2]);\n if (has_explicit_colors) {\n return category_info.map((item) => to_rgb({}, item[2]));\n }\n\n // Use a set of color schemes for common 15, 18, or 25 state models, as specified from:\n // https://egg2.wustl.edu/roadmap/web_portal/chr_state_learning.html\n // These are actually reversed so that dim colors come first, on the premise that usually these are the\n // most common states\n const n_categories = category_info.length;\n if (n_categories <= 15) {\n return ['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)'];\n } else if (n_categories <= 18) {\n return ['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)'];\n } else {\n // If there are more than 25 categories, the interval layer will fall back to the 'null value' option\n return ['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)'];\n }\n }\n\n /**\n * Find all of the unique tracks (a combination of name and ID information)\n * @param {Object} data\n * @param {String} [rgb_field] A field that contains an RGB value. Aimed at BED files with an itemRgb column\n * @private\n * @returns {Array} All [unique_id, label, color] pairs in data. The unique_id is the thing used to define groupings\n * most unambiguously.\n */\n _generateCategoriesFromData(data, rgb_field) {\n const self = this;\n // Use the hard-coded legend if available (ignoring any mods on re-render)\n const legend = this._base_layout.legend;\n if (legend && legend.length) {\n return legend.map((item) => [item[this.layout.track_split_field], item.label, item.color]);\n }\n\n // Generate options from data, if no preset legend exists\n const unique_ids = {}; // make categories unique\n const categories = [];\n\n data.forEach((item) => {\n const id = item[self.layout.track_split_field];\n if (!Object.prototype.hasOwnProperty.call(unique_ids, id)) {\n unique_ids[id] = null;\n // If rgbfield is null, then the last entry is undefined/null as well\n categories.push([id, item[this.layout.track_label_field], item[rgb_field]]);\n }\n });\n return categories;\n }\n }\n\n /**\n * (**extension**) A basic tooltip with information to be shown over an intervals datum\n * @alias module:LocusZoom_Layouts~standard_intervals\n * @type tooltip\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_tooltip_layout = {\n closable: false,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{intervals:state_name|htmlescape}}
{{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}',\n };\n\n /**\n * (**extension**) A data layer with some preconfigured options for intervals display. This example was designed for chromHMM output,\n * in which various states are assigned numeric state IDs and (<= as many) text state names.\n *\n * This layout is deprecated; most usages would be better served by the bed_intervals_layer layout instead.\n * @alias module:LocusZoom_Layouts~intervals_layer\n * @type data_layer\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_layer_layout = {\n namespace: { 'intervals': 'intervals' },\n id: 'intervals',\n type: 'intervals',\n tag: 'intervals',\n id_field: '{{intervals:start}}_{{intervals:end}}_{{intervals:state_name}}',\n start_field: 'intervals:start',\n end_field: 'intervals:end',\n track_split_field: 'intervals:state_name',\n track_label_field: 'intervals:state_name',\n split_tracks: false,\n always_hide_legend: true,\n color: [\n {\n // If present, an explicit color field will override any other option (and be used to auto-generate legend)\n field: 'intervals:itemRgb',\n scale_function: 'to_rgb',\n },\n {\n // TODO: Consider changing this to stable_choice in the future, for more stable coloring\n field: 'intervals:state_name',\n scale_function: 'categorical_bin',\n parameters: {\n // Placeholder. Empty categories and values will automatically be filled in when new data loads.\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n },\n ],\n legend: [], // Placeholder; auto-filled when data loads.\n behaviors: {\n onmouseover: [\n { action: 'set', status: 'highlighted' },\n ],\n onmouseout: [\n { action: 'unset', status: 'highlighted' },\n ],\n onclick: [\n { action: 'toggle', status: 'selected', exclusive: true },\n ],\n onshiftclick: [\n { action: 'toggle', status: 'selected' },\n ],\n },\n tooltip: intervals_tooltip_layout,\n };\n\n\n /**\n * (**extension**) A data layer with some preconfigured options for intervals display. This example was designed for standard BED3+ files and the field names emitted by the LzParsers extension.\n * @alias module:LocusZoom_Layouts~bed_intervals_layer\n * @type data_layer\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const bed_intervals_layer_layout = LocusZoom.Layouts.merge({\n id_field: '{{intervals:chromStart}}_{{intervals:chromEnd}}_{{intervals:name}}',\n start_field: 'intervals:chromStart',\n end_field: 'intervals:chromEnd',\n track_split_field: 'intervals:name',\n track_label_field: 'intervals:name',\n split_tracks: true,\n always_hide_legend: false,\n color: [\n {\n // If present, an explicit color field will override any other option (and be used to auto-generate legend)\n field: 'intervals:itemRgb',\n scale_function: 'to_rgb',\n },\n {\n // TODO: Consider changing this to stable_choice in the future, for more stable coloring\n field: 'intervals:name',\n scale_function: 'categorical_bin',\n parameters: {\n // Placeholder. Empty categories and values will automatically be filled in when new data loads.\n categories: [],\n values: [],\n null_value: '#B8B8B8',\n },\n },\n ],\n tooltip: LocusZoom.Layouts.merge({\n html: `Group: {{intervals:name|htmlescape}}
\nRegion: {{intervals:chromStart|htmlescape}}-{{intervals:chromEnd|htmlescape}}\n{{#if intervals:score}}
\nScore: {{intervals:score|htmlescape}}{{/if}}`,\n }, intervals_tooltip_layout),\n }, intervals_layer_layout);\n\n\n /**\n * (**extension**) A panel containing an intervals data layer, eg for BED tracks. This is a legacy layout whose field names were specific to one partner site.\n * @alias module:LocusZoom_Layouts~intervals\n * @type panel\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_panel_layout = {\n id: 'intervals',\n tag: 'intervals',\n min_height: 50,\n height: 50,\n margin: { top: 25, right: 150, bottom: 5, left: 70 },\n toolbar: (function () {\n const l = LocusZoom.Layouts.get('toolbar', 'standard_panel');\n l.widgets.push({\n type: 'toggle_split_tracks',\n data_layer_id: 'intervals',\n position: 'right',\n });\n return l;\n })(),\n axes: {},\n interaction: {\n drag_background_to_pan: true,\n scroll_to_zoom: true,\n x_linked: true,\n },\n legend: {\n hidden: true,\n orientation: 'horizontal',\n origin: { x: 50, y: 0 },\n pad_from_bottom: 5,\n },\n data_layers: [intervals_layer_layout],\n };\n\n /**\n * (**extension**) A panel containing an intervals data layer, eg for BED tracks. These field names match those returned by the LzParsers extension.\n * @alias module:LocusZoom_Layouts~bed_intervals\n * @type panel\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const bed_intervals_panel_layout = LocusZoom.Layouts.merge({\n // Normal BED tracks show the panel legend in collapsed mode!\n min_height: 120,\n height: 120,\n data_layers: [bed_intervals_layer_layout],\n }, intervals_panel_layout);\n\n /**\n * (**extension**) A plot layout that shows association summary statistics, genes, and interval data. This example assumes\n * chromHMM data. (see panel layout) Few people will use the full intervals plot layout directly outside of an example.\n * @alias module:LocusZoom_Layouts~interval_association\n * @type plot\n * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions\n */\n const intervals_plot_layout = {\n state: {},\n width: 800,\n responsive_resize: true,\n min_region_scale: 20000,\n max_region_scale: 1000000,\n toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'),\n panels: [\n LocusZoom.Layouts.get('panel', 'association'),\n LocusZoom.Layouts.merge({ min_height: 120, height: 120 }, intervals_panel_layout),\n LocusZoom.Layouts.get('panel', 'genes'),\n ],\n };\n\n LocusZoom.Adapters.add('IntervalLZ', IntervalLZ);\n LocusZoom.DataLayers.add('intervals', LzIntervalsTrack);\n\n LocusZoom.Layouts.add('tooltip', 'standard_intervals', intervals_tooltip_layout);\n LocusZoom.Layouts.add('data_layer', 'intervals', intervals_layer_layout);\n LocusZoom.Layouts.add('data_layer', 'bed_intervals', bed_intervals_layer_layout);\n LocusZoom.Layouts.add('panel', 'intervals', intervals_panel_layout);\n LocusZoom.Layouts.add('panel', 'bed_intervals', bed_intervals_panel_layout);\n LocusZoom.Layouts.add('plot', 'interval_association', intervals_plot_layout);\n\n LocusZoom.ScaleFunctions.add('to_rgb', to_rgb);\n\n LocusZoom.Widgets.add('toggle_split_tracks', ToggleSplitTracks);\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/ext/lz-parsers.min.js b/dist/ext/lz-parsers.min.js new file mode 100644 index 00000000..3e6b48dd --- /dev/null +++ b/dist/ext/lz-parsers.min.js @@ -0,0 +1,3 @@ +/*! Locuszoom 0.14.0 */ +var LzParsers;(()=>{"use strict";var e={d:(r,t)=>{for(var l in t)e.o(t,l)&&!e.o(r,l)&&Object.defineProperty(r,l,{enumerable:!0,get:t[l]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)},r={};e.d(r,{default:()=>d});const t=new Set(["",".","NA","N/A","n/a","nan","-nan","NaN","-NaN","null","NULL","None",null]),l=/([\d.-]+)([\sxeE]*)([0-9-]*)/;function n(e){return Number.isInteger(e)}function o(e,r=t,l=null){return e.map((e=>r.has(e)?l:e))}function a(e){return e.replace(/^chr/g,"").toUpperCase()}function s(e,r=!1){if(null===e)return e;const t=+e;if(r)return t;if(t<0||t>1)throw new Error("p value is not in the allowed range");if(0===t){if("0"===e)return 1/0;let[,r,,t]=e.match(l);return r=+r,t=""!==t?+t:0,0===r?1/0:-(Math.log10(+r)+ +t)}return-Math.log10(t)}function u(e){return null==e||"."===e?null:e}function i(e){return(e=u(e))?+e:null}const c=/^(?:chr)?([a-zA-Z0-9]+?)[_:-](\d+)[_:|-]?(\w+)?[/_:|-]?([^_]+)?_?(.*)?/;function f(e,r=!1){const t=e&&e.match(c);if(t)return t.slice(1);if(r)return null;throw new Error(`Could not understand marker format for ${e}. Should be of format chr:pos or chr:pos_ref/alt`)}function p(e){const r=f(e);if(!r)throw new Error(`Unable to normalize marker format for variant: ${e}`);const[t,l,n,o]=r;let a=`${t}:${l}`;return n&&o&&(a+=`_${n}/${o}`),a}function _(e,r){const t=Array(r.length+1).fill(null).map((()=>Array(e.length+1).fill(null)));for(let r=0;r<=e.length;r+=1)t[0][r]=r;for(let e=0;e<=r.length;e+=1)t[e][0]=e;for(let l=1;l<=r.length;l+=1)for(let n=1;n<=e.length;n+=1){const o=e[n-1]===r[l-1]?0:1;t[l][n]=Math.min(t[l][n-1]+1,t[l-1][n]+1,t[l-1][n-1]+o)}return t[r.length][e.length]}function m(e,r,t=2){let l=t+1,n=null;for(let t=0;t_(o,e))));ae.variant1===r.ld_refvar))}}e.Adapters.add("UserTabixLD",l)}}"undefined"!=typeof LocusZoom&&LocusZoom.use(h);const d={install:h,makeBed12Parser:function({normalize:e=!0}={}){return r=>{const t=r.trim().split("\t");let[l,n,o,s,c,f,p,_,m,h,d,v]=t;if(!(l&&n&&o))throw new Error("Sample data must provide all required BED columns");if(f=u(f),e&&(l=a(l),n=+n+1,o=+o,c=i(c),p=i(p),_=i(_),m=u(m),h=i(h),d=u(d),d=d?d.replace(/,$/,"").split(",").map((e=>+e)):null,v=u(v),v=v?v.replace(/,$/,"").split(",").map((e=>+e+1)):null,d&&v&&h&&(d.length!==h||v.length!==h)))throw new Error("Block size and start information should provide the same number of items as in blockCount");return{chrom:l,chromStart:n,chromEnd:o,name:s,score:c,strand:f,thickStart:p,thickEnd:_,itemRgb:m,blockCount:h,blockSizes:d,blockStarts:v}}},makeGWASParser:function({marker_col:e,chrom_col:r,pos_col:l,ref_col:o,alt_col:u,pvalue_col:i,is_neg_log_pvalue:c=!1,rsid_col:p,beta_col:_,stderr_beta_col:m,allele_freq_col:h,allele_count_col:d,n_samples_col:v,is_alt_effect:g=!0,delimiter:w="\t"}){if(n(e)&&n(r)&&n(l))throw new Error("Must specify either marker OR chr + pos");if(!(n(e)||n(r)&&n(l)))throw new Error("Must specify how to locate marker");if(n(d)&&n(h))throw new Error("Allele count and frequency options are mutually exclusive");if(n(d)&&!n(v))throw new Error("To calculate allele frequency from counts, you must also provide n_samples");return b=>{const k=b.split(w);let y,E,q,A,N,$,S,L=null,z=null,P=null,C=null;if(n(e))[y,E,q,A]=f(k[e-1],!1);else{if(!n(r)||!n(l))throw new Error("Must specify all fields required to identify the variant");y=k[r-1],E=k[l-1]}if(y=a(y),y.startsWith("RS"))throw new Error(`Invalid chromosome specified: value "${y}" is an rsID`);n(o)&&(q=k[o-1]),n(u)&&(A=k[u-1]),n(p)&&(L=k[p-1]),t.has(q)&&(q=null),t.has(A)&&(A=null),t.has(L)?L=null:L&&(L=L.toLowerCase(),L.startsWith("rs")||(L=`rs${L}`));const O=s(k[i-1],c);q=q||null,A=A||null,n(h)&&(N=k[h-1]),n(d)&&($=k[d-1],S=k[v-1]),n(_)&&(z=k[_-1],z=t.has(z)?null:+z),n(m)&&(P=k[m-1],P=t.has(P)?null:+P),(h||d)&&(C=function({freq:e,allele_count:r,n_samples:l,is_alt_effect:n=!0}){if(void 0!==e&&void 0!==r)throw new Error("Frequency and allele count options are mutually exclusive");let o;if(void 0===e&&(t.has(r)||t.has(l)))return null;if(void 0===e&&void 0!==r)o=+r/+l/2;else{if(t.has(e))return null;o=+e}if(o<0||o>1)throw new Error("Allele frequency is not in the allowed range");return n?o:1-o}({freq:N,allele_count:$,n_samples:S,is_alt_effect:g}));const R=q&&A?`_${q}/${A}`:"";return{chromosome:y,position:+E,ref_allele:q?q.toUpperCase():null,alt_allele:A?A.toUpperCase():null,variant:`${y}:${E}${R}`,rsid:L,log_pvalue:O,beta:z,stderr_beta:P,alt_allele_freq:C}}},guessGWAS:function(e,r,t=1){const l=e.map((e=>e?e.toLowerCase():e));l[0].replace("/^#+/","");const n=function(e,r){let t;const l=(e,r,l)=>{const n=o(r.map((r=>r[e])));try{t=n.map((e=>s(e,l)))}catch(e){return!1}return t.every((e=>!Number.isNaN(e)))},n=m(["neg_log_pvalue","log_pvalue","log_pval","logpvalue"],e),a=m(["pvalue","p.value","p-value","pval","p_score","p","p_value"],e);return null!==n&&l(n,r,!0)?{pvalue_col:n+1,is_neg_log_pvalue:!0}:a&&l(a,r,!1)?{pvalue_col:a+1,is_neg_log_pvalue:!1}:null}(l,r);if(!n)return null;l[n.pvalue_col-1]=null;const a=function(e,r){const t=r[0];let l=m(["snpid","marker","markerid","snpmarker","chr:position"],e);if(null!==l&&f(t[l],!0))return l+=1,{marker_col:l};const n=e.slice(),o=[["chrom_col",["chrom","chr","chromosome"],!0],["pos_col",["position","pos","begin","beg","bp","end","ps","base_pair_location"],!0],["ref_col",["A1","ref","reference","allele0","allele1"],!1],["alt_col",["A2","alt","alternate","allele1","allele2"],!1]],a={};for(let e=0;e{l[a[e]]=null}));const u=function(e,r){function t(e,r){const t=o(r.map((r=>r[e])));let l;try{l=t.filter((e=>null!==e)).map((e=>+e))}catch(e){return!1}return l.every((e=>!Number.isNaN(e)))}const l=m(["beta","effect_size","alt_effsize","effect"],e,0),n=m(["stderr_beta","stderr","sebeta","effect_size_sd","se","standard_error"],e,0),a={};return null!==l&&t(l,r)&&(a.beta_col=l+1),null!==n&&t(n,r)&&(a.stderr_beta_col=n+1),a}(l,r);return n&&a?Object.assign({},n,a,u||{}):null},makePlinkLdParser:function({normalize:e=!0}={}){return r=>{let[t,l,n,o,s,u,i]=r.trim().split("\t");return e&&(t=a(t),o=a(o),n=p(n),u=p(u),l=+l,s=+s,i=+i),{chromosome1:t,position1:l,variant1:n,chromosome2:o,position2:s,variant2:u,correlation:i}}}};LzParsers=r.default})(); +//# sourceMappingURL=lz-parsers.min.js.map \ No newline at end of file diff --git a/dist/ext/lz-parsers.min.js.map b/dist/ext/lz-parsers.min.js.map new file mode 100644 index 00000000..36db2cba --- /dev/null +++ b/dist/ext/lz-parsers.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/./esm/ext/lz-parsers/utils.js","webpack://[name]/./esm/ext/lz-parsers/bed.js","webpack://[name]/./esm/helpers/parse.js","webpack://[name]/./esm/ext/lz-parsers/gwas/sniffers.js","webpack://[name]/./esm/ext/lz-parsers/index.js","webpack://[name]/./esm/ext/lz-parsers/gwas/parsers.js","webpack://[name]/./esm/ext/lz-parsers/ld.js"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Set","REGEX_PVAL","has","num","Number","isInteger","missingToNull","values","nulls","placeholder","map","v","normalizeChr","chromosome","replace","toUpperCase","parsePvalToLog","value","is_neg_log","val","Error","Infinity","base","exponent","match","Math","log10","_bedMissing","_hasNum","REGEX_MARKER","parseMarker","test","slice","normalizeMarker","variant","chrom","pos","ref","alt","normalized","levenshtein","a","b","distanceMatrix","Array","length","fill","i","j","indicator","min","findColumn","column_synonyms","header_names","threshold","best_score","best_match","header","score","s","install","LocusZoom","Adapters","TabixUrlSource","LDServer","UserTabixLD","config","limit_fields","super","state","assoc_data","_buildRequestOptions","arguments","ld_refvar","__find_ld_refvar","_skip_request","options","Promise","resolve","_performRequest","records","filter","item","add","use","makeBed12Parser","normalize","line","tokens","trim","split","chromStart","chromEnd","name","strand","thickStart","thickEnd","itemRgb","blockCount","blockSizes","blockStarts","marker_col","chrom_col","pos_col","ref_col","alt_col","pvalue_col","is_neg_log_pvalue","rsid_col","beta_col","stderr_beta_col","allele_freq_col","allele_count_col","n_samples_col","is_alt_effect","delimiter","fields","chr","freq","allele_count","n_samples","rsid","beta","stderr_beta","alt_allele_freq","startsWith","toLowerCase","log_pval","undefined","result","parseAlleleFrequency","ref_alt","position","ref_allele","alt_allele","log_pvalue","header_row","data_rows","offset","headers","pval_config","ps","validateP","col","data","is_log","cleaned_vals","row","p","e","every","isNaN","log_p_col","p_col","getPvalColumn","position_config","first_row","headers_marked","find","col_name","choices","is_required","getChromPosRefAltColumns","keys","forEach","beta_config","validate_numeric","nums","ret","getEffectSizeColumns","assign","chromosome1","position1","variant1","chromosome2","position2","variant2","correlation"],"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,I,4BCOlF,MAAM,EAAiB,IAAII,IAAI,CAAC,GAAI,IAAK,KAAM,MAAO,MAAO,MAAO,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,OAAQ,OAK7GC,EAAa,+BAUnB,SAASC,EAAIC,GACT,OAAOC,OAAOC,UAAUF,GAQ5B,SAASG,EAAcC,EAAQC,EAAQ,EAAgBC,EAAc,MAEjE,OAAOF,EAAOG,KAAKC,GAAOH,EAAMN,IAAIS,GAAKF,EAAcE,IAQ3D,SAASC,EAAaC,GAClB,OAAOA,EAAWC,QAAQ,QAAS,IAAIC,cAU3C,SAASC,EAAeC,EAAOC,GAAa,GAExC,GAAc,OAAVD,EACA,OAAOA,EAEX,MAAME,GAAOF,EACb,GAAIC,EACA,OAAOC,EAGX,GAAIA,EAAM,GAAKA,E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,EAAakK,GAC3BD,EAAW5I,EAAgB4I,GAC3BG,EAAW/I,EAAgB+I,GAC3BJ,GAAaA,EACbG,GAAaA,EACbE,GAAeA,GAGZ,CAACN,cAAaC,YAAWC,WAAUC,cAAaC,YAAWC,WAAUC,kB","file":"ext/lz-parsers.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))","/**\n * Constant values used by GWAS parser\n */\n\n/**\n * @private\n */\nconst MISSING_VALUES = new Set(['', '.', 'NA', 'N/A', 'n/a', 'nan', '-nan', 'NaN', '-NaN', 'null', 'NULL', 'None', null]);\n\n/**\n * @private\n */\nconst REGEX_PVAL = /([\\d.-]+)([\\sxeE]*)([0-9-]*)/;\n\n\n/**\n * Utility helper that checks for the presence of a numeric value (incl 0),\n * eg \"has column specified\"\n * @private\n * @param num\n * @returns {boolean}\n */\nfunction has(num) {\n return Number.isInteger(num);\n}\n\n/**\n * Convert all missing values to a standardized input form\n * Useful for columns like pvalue, where a missing value explicitly allowed\n * @private\n */\nfunction missingToNull(values, nulls = MISSING_VALUES, placeholder = null) {\n // TODO Make this operate on a single value; cache for efficiency?\n return values.map((v) => (nulls.has(v) ? placeholder : v));\n}\n\n/**\n * Normalize chromosome representations\n * @private\n * @param {String} chromosome\n */\nfunction normalizeChr(chromosome) {\n return chromosome.replace(/^chr/g, '').toUpperCase();\n}\n\n/**\n * Parse (and validate) a given number, and return the -log10 pvalue.\n * @private\n * @param value\n * @param {boolean} is_neg_log\n * @returns {number|null} The -log10 pvalue\n */\nfunction parsePvalToLog(value, is_neg_log = false) {\n // TODO: In future, generalize this for other values prone to underflow\n if (value === null) {\n return value;\n }\n const val = +value;\n if (is_neg_log) { // Take as is\n return val;\n }\n // Regular pvalue: validate and convert\n if (val < 0 || val > 1) {\n throw new Error('p value is not in the allowed range');\n }\n // 0-values are explicitly allowed and will convert to infinity by design, as they often\n // indicate underflow errors in the input data.\n if (val === 0) {\n // Determine whether underflow is due to the source data, or value conversion\n if (value === '0') {\n // The source data is bad, so insert an obvious placeholder value\n return Infinity;\n }\n // h/t @welchr: aggressively turn the underflowing string value into -log10 via regex\n // Only do this if absolutely necessary, because it is a performance hit\n\n let [, base, , exponent] = value.match(REGEX_PVAL);\n base = +base;\n\n if (exponent !== '') {\n exponent = +exponent;\n } else {\n exponent = 0;\n }\n if (base === 0) {\n return Infinity;\n }\n return -(Math.log10(+base) + +exponent);\n }\n return -Math.log10(val);\n}\n\n/**\n * @private\n */\nfunction parseAlleleFrequency({ freq, allele_count, n_samples, is_alt_effect = true }) {\n if (freq !== undefined && allele_count !== undefined) {\n throw new Error('Frequency and allele count options are mutually exclusive');\n }\n\n let result;\n if (freq === undefined && (MISSING_VALUES.has(allele_count) || MISSING_VALUES.has(n_samples))) {\n // Allele count parsing\n return null;\n }\n if (freq === undefined && allele_count !== undefined) {\n result = +allele_count / +n_samples / 2;\n } else if (MISSING_VALUES.has(freq)) { // Frequency-based parsing\n return null;\n } else {\n result = +freq;\n }\n\n // No matter how the frequency is specified, this stuff is always done\n if (result < 0 || result > 1) {\n throw new Error('Allele frequency is not in the allowed range');\n }\n if (!is_alt_effect) { // Orient the frequency to the alt allele\n return 1 - result;\n }\n return result;\n}\n\nexport {\n MISSING_VALUES,\n missingToNull as _missingToNull,\n has,\n normalizeChr,\n // Exports for unit testing\n parseAlleleFrequency,\n parsePvalToLog,\n};\n","/**\n * Parse BED-family files, which have 3-12 columns\n * https://genome.ucsc.edu/FAQ/FAQformat.html#format1\n */\n\nimport {normalizeChr} from './utils';\n\n/**\n * @private\n */\nfunction _bedMissing(value) {\n // BED files specify . as the missing/ null value character\n if (value === null || value === undefined || value === '.') {\n return null;\n }\n return value;\n}\n\n/**\n * @private\n */\nfunction _hasNum(value) {\n // Return a number, or null if value marked as missing\n value = _bedMissing(value);\n return value ? +value : null;\n}\n\n/**\n * Parse a BED file, according to the widely used UCSC (quasi-)specification\n *\n * NOTE: This original version is aimed at tabix region queries, and carries an implicit assumption that data is the\n * only thing that will be parsed. It makes no attempt to identify or handle header rows / metadata fields.\n *\n * @function\n * @alias module:ext/lz-parsers~makeBed12Parser\n * @param {object} options\n * @param {Boolean} options.normalize Whether to normalize the output to the format expected by LocusZoom (eg type coercion\n * for numbers, removing chr chromosome prefixes, and using 1-based and inclusive coordinates instead of 0-based disjoint intervals)\n * @return function A configured parser function that runs on one line of text from an input file\n */\nfunction makeBed12Parser({normalize = true} = {}) {\n /*\n * @param {String} line The line of text to be parsed\n */\n return (line) => {\n const tokens = line.trim().split('\\t');\n // The BED file format has 12 standardized columns. 3 are required and 9 are optional. At present, we will not\n // attempt to parse any remaining tokens, or nonstandard files that reuse columns with a different meaning.\n // https://en.wikipedia.org/wiki/BED_(file_format)\n let [\n chrom,\n chromStart,\n chromEnd,\n name,\n score,\n strand,\n thickStart,\n thickEnd,\n itemRgb,\n blockCount,\n blockSizes,\n blockStarts,\n ] = tokens;\n\n if (!(chrom && chromStart && chromEnd)) {\n throw new Error('Sample data must provide all required BED columns');\n }\n\n strand = _bedMissing(strand);\n\n if (normalize) {\n // Mandatory fields\n chrom = normalizeChr(chrom);\n chromStart = +chromStart + 1; // BED is 0 based start, but LZ plots start at 1\n chromEnd = +chromEnd; // 0-based positions, intervals exclude end position\n\n // Optional fields, require checking for blanks\n score = _hasNum(score);\n thickStart = _hasNum(thickStart);\n thickEnd = _hasNum(thickEnd);\n\n itemRgb = _bedMissing(itemRgb);\n\n // LocusZoom doesn't use these fields for rendering. Parsing below is theoretical/best-effort.\n blockCount = _hasNum(blockCount);\n\n blockSizes = _bedMissing(blockSizes);\n blockSizes = !blockSizes ? null : blockSizes.replace(/,$/, '').split(',').map((value) => +value); // Comma separated list of sizes -> array of integers\n\n blockStarts = _bedMissing(blockStarts);\n blockStarts = !blockStarts ? null : blockStarts.replace(/,$/, '').split(',').map((value) => +value + 1); // Comma separated list of sizes -> array of integers (start positions)\n\n if (blockSizes && blockStarts && blockCount && (blockSizes.length !== blockCount || blockStarts.length !== blockCount)) {\n throw new Error('Block size and start information should provide the same number of items as in blockCount');\n }\n }\n return {\n chrom,\n chromStart,\n chromEnd,\n name,\n score,\n strand,\n thickStart,\n thickEnd,\n itemRgb,\n blockCount,\n blockSizes,\n blockStarts,\n };\n };\n}\n\nexport { makeBed12Parser };\n","/**\n * Parse useful entities\n */\n\n/**\n * @private\n */\nconst REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n\n/**\n * Parse a single marker, cleaning up values as necessary\n * @private\n * @param {String} value\n * @param {boolean} test If called in testing mode, do not throw an exception\n * @returns {Array} chr, pos, ref, alt (if match found; ref and alt optional)\n */\nfunction parseMarker(value, test = false) {\n const match = value && value.match(REGEX_MARKER);\n if (match) {\n return match.slice(1);\n }\n if (!test) {\n throw new Error(`Could not understand marker format for ${value}. Should be of format chr:pos or chr:pos_ref/alt`);\n } else {\n return null;\n }\n}\n\n/**\n * Normalize a provided variant string into the EPACTS-style `chrom:pos_ref/alt` format expected by LocusZoom and the Michigan LD Server\n * This allows harmonizing various input data to a consistent format\n * @private\n * @param {String} variant A string that specifies variant information in one of several common formats (like chr1:99_A/C, 1-99-A-C, 1:99:A:C, etc)\n */\nfunction normalizeMarker(variant) {\n const match = parseMarker(variant);\n if (!match) {\n throw new Error(`Unable to normalize marker format for variant: ${variant}`);\n }\n const [chrom, pos, ref, alt] = match;\n let normalized = `${chrom}:${pos}`;\n if (ref && alt) {\n normalized += `_${ref}/${alt}`;\n }\n return normalized;\n}\n\n\nexport {\n parseMarker,\n normalizeMarker,\n};\n","/**\n * Sniffers: auto detect file format and parsing options for GWAS files.\n */\n\nimport { parseMarker } from '../../../helpers/parse';\nimport { MISSING_VALUES, parsePvalToLog, _missingToNull } from '../utils';\n\n/**\n * @private\n */\nfunction isNumeric(val) {\n // Check whether an unparsed string is a numeric value\"\n if (MISSING_VALUES.has(val)) {\n return true;\n }\n return !Number.isNaN(+val);\n}\n\nfunction isHeader(row, { comment_char = '#', delimiter = '\\t' } = {}) {\n // This assumes two basic rules: the line is not a comment, and gwas data is more likely\n // to be numeric than headers\n return row.startsWith(comment_char) || row.split(delimiter).every((item) => !isNumeric(item));\n}\n\n/**\n * Compute the levenshtein distance between two strings. Useful for finding the single best column\n * name that matches a given rule.\n * @private\n */\nfunction levenshtein(a, b) { // https://github.com/trekhleb/javascript-algorithms\n // Create empty edit distance matrix for all possible modifications of\n // substrings of a to substrings of b.\n const distanceMatrix = Array(b.length + 1)\n .fill(null)\n .map(() => Array(a.length + 1)\n .fill(null));\n\n // Fill the first row of the matrix.\n // If this is first row then we're transforming empty string to a.\n // In this case the number of transformations equals to size of a substring.\n for (let i = 0; i <= a.length; i += 1) {\n distanceMatrix[0][i] = i;\n }\n\n // Fill the first column of the matrix.\n // If this is first column then we're transforming empty string to b.\n // In this case the number of transformations equals to size of b substring.\n for (let j = 0; j <= b.length; j += 1) {\n distanceMatrix[j][0] = j;\n }\n\n for (let j = 1; j <= b.length; j += 1) {\n for (let i = 1; i <= a.length; i += 1) {\n const indicator = a[i - 1] === b[j - 1] ? 0 : 1;\n distanceMatrix[j][i] = Math.min(\n distanceMatrix[j][i - 1] + 1, // deletion\n distanceMatrix[j - 1][i] + 1, // insertion\n distanceMatrix[j - 1][i - 1] + indicator, // substitution\n );\n }\n }\n return distanceMatrix[b.length][a.length];\n}\n\n/**\n * Return the index of the first column name that meets acceptance criteria\n * @private\n * @param {String[]} column_synonyms\n * @param {String[]}header_names\n * @param {Number} threshold Tolerance for fuzzy matching (# edits)\n * @return {Number|null} Index of the best matching column, or null if no match possible\n */\nfunction findColumn(column_synonyms, header_names, threshold = 2) {\n // Find the column name that best matches\n let best_score = threshold + 1;\n let best_match = null;\n for (let i = 0; i < header_names.length; i++) {\n const header = header_names[i];\n if (header === null) {\n // If header is empty, don't consider it for a match\n // Nulling a header provides a way to exclude something from future searching\n continue; // eslint-disable-line no-continue\n }\n const score = Math.min(...column_synonyms.map((s) => levenshtein(header, s)));\n if (score < best_score) {\n best_score = score;\n best_match = i;\n }\n }\n return best_match;\n}\n\n\n/**\n * Return parser configuration for pvalues\n *\n * Returns 1-based column indices, for compatibility with parsers\n * @private\n * @param header_row\n * @param data_rows\n * @returns {{}}\n */\nfunction getPvalColumn(header_row, data_rows) {\n // TODO: Allow overrides\n const LOGPVALUE_FIELDS = ['neg_log_pvalue', 'log_pvalue', 'log_pval', 'logpvalue'];\n const PVALUE_FIELDS = ['pvalue', 'p.value', 'p-value', 'pval', 'p_score', 'p', 'p_value'];\n\n let ps;\n const validateP = (col, data, is_log) => { // Validate pvalues\n const cleaned_vals = _missingToNull(data.map((row) => row[col]));\n try {\n ps = cleaned_vals.map((p) => parsePvalToLog(p, is_log));\n } catch (e) {\n return false;\n }\n return ps.every((val) => !Number.isNaN(val));\n };\n\n const log_p_col = findColumn(LOGPVALUE_FIELDS, header_row);\n const p_col = findColumn(PVALUE_FIELDS, header_row);\n\n if (log_p_col !== null && validateP(log_p_col, data_rows, true)) {\n return {\n pvalue_col: log_p_col + 1,\n is_neg_log_pvalue: true,\n };\n }\n if (p_col && validateP(p_col, data_rows, false)) {\n return {\n pvalue_col: p_col + 1,\n is_neg_log_pvalue: false,\n };\n }\n // Could not auto-determine an appropriate pvalue column\n return null;\n}\n\n/**\n * @private\n */\nfunction getChromPosRefAltColumns(header_row, data_rows) {\n // Returns 1-based column indices, for compatibility with parsers\n // Get from either a marker, or 4 separate columns\n const MARKER_FIELDS = ['snpid', 'marker', 'markerid', 'snpmarker', 'chr:position'];\n const CHR_FIELDS = ['chrom', 'chr', 'chromosome'];\n const POS_FIELDS = ['position', 'pos', 'begin', 'beg', 'bp', 'end', 'ps', 'base_pair_location'];\n\n // TODO: How to handle orienting ref vs effect?\n // Order matters: consider ambiguous field names for ref before alt\n const REF_FIELDS = ['A1', 'ref', 'reference', 'allele0', 'allele1'];\n const ALT_FIELDS = ['A2', 'alt', 'alternate', 'allele1', 'allele2'];\n\n const first_row = data_rows[0];\n let marker_col = findColumn(MARKER_FIELDS, header_row);\n if (marker_col !== null && parseMarker(first_row[marker_col], true)) {\n marker_col += 1;\n return { marker_col };\n }\n\n // If single columns were incomplete, attempt to auto detect 4 separate columns. All 4 must\n // be found for this function to report a match.\n const headers_marked = header_row.slice();\n const find = [\n ['chrom_col', CHR_FIELDS, true],\n ['pos_col', POS_FIELDS, true],\n ['ref_col', REF_FIELDS, false],\n ['alt_col', ALT_FIELDS, false],\n ];\n const config = {};\n for (let i = 0; i < find.length; i++) {\n const [col_name, choices, is_required] = find[i];\n const col = findColumn(choices, headers_marked);\n if (col === null && is_required) {\n return null;\n }\n if (col !== null) {\n config[col_name] = col + 1;\n // Once a column has been assigned, remove it from consideration\n headers_marked[col] = null;\n }\n }\n return config;\n}\n\n/**\n * Identify which columns contain effect size (beta) and stderr of the effect size\n * @private\n * @param {String[]} header_names\n * @param {Array[]} data_rows\n * @returns {{}}\n */\nfunction getEffectSizeColumns(header_names, data_rows) {\n const BETA_FIELDS = ['beta', 'effect_size', 'alt_effsize', 'effect'];\n const STDERR_BETA_FIELDS = ['stderr_beta', 'stderr', 'sebeta', 'effect_size_sd', 'se', 'standard_error'];\n\n function validate_numeric(col, data) {\n const cleaned_vals = _missingToNull(data.map((row) => row[col]));\n let nums;\n try {\n nums = cleaned_vals.filter((val) => val !== null).map((val) => +val);\n } catch (e) {\n return false;\n }\n return nums.every((val) => !Number.isNaN(val));\n }\n\n const beta_col = findColumn(BETA_FIELDS, header_names, 0);\n const stderr_beta_col = findColumn(STDERR_BETA_FIELDS, header_names, 0);\n\n const ret = {};\n if (beta_col !== null && validate_numeric(beta_col, data_rows)) {\n ret.beta_col = beta_col + 1;\n }\n if (stderr_beta_col !== null && validate_numeric(stderr_beta_col, data_rows)) {\n ret.stderr_beta_col = stderr_beta_col + 1;\n }\n return ret;\n}\n\n/**\n * Attempt to guess the correct parser settings given a set of header rows and a set of data rows\n * @private\n * @param {String[]} header_row\n * @param {String[][]} data_rows\n * @param {int} offset Used to convert between 0 and 1-based indexing.\n * @return {Object|null} Returns null if a complete configuration could not suggested.\n */\nfunction guessGWAS(header_row, data_rows, offset = 1) {\n // 1. Find a specific set of info: marker OR chr/pos/ref/alt ; pvalue OR log_pvalue\n // 2. Validate that we will be able to parse the required info: fields present and make sense\n // 3. Based on the field names selected, attempt to infer meaning: verify whether log is used,\n // and check ref/alt vs effect/noneffect\n // 4. Return a parser config object if all tests pass, OR null.\n\n // Normalize case and remove leading comment marks from line for easier comparison\n const headers = header_row.map((item) => (item ? item.toLowerCase() : item));\n headers[0].replace('/^#+/', '');\n // Lists of fields are drawn from Encore (AssocResultReader) and Pheweb (conf_utils.py)\n const pval_config = getPvalColumn(headers, data_rows, offset);\n if (!pval_config) {\n return null;\n }\n headers[pval_config.pvalue_col - 1] = null; // Remove this column from consideration\n const position_config = getChromPosRefAltColumns(headers, data_rows);\n if (!position_config) {\n return null;\n }\n // Remove the position config from consideration for future matches\n Object.keys(position_config).forEach((key) => {\n headers[position_config[key]] = null;\n });\n\n const beta_config = getEffectSizeColumns(headers, data_rows);\n\n if (pval_config && position_config) {\n return Object.assign({}, pval_config, position_config, beta_config || {});\n }\n return null;\n}\n\nexport {\n // Public members\n guessGWAS,\n // Symbols exported for testing\n isHeader as _isHeader,\n getPvalColumn as _getPvalColumn,\n findColumn as _findColumn,\n levenshtein as _levenshtein,\n};\n","/**\n * Optional LocusZoom extension: must be included separately, and after LocusZoom has been loaded\n *\n * This plugin exports helper function, as well as a few optional extra helpers for rendering the plot. The GWAS parsers can be used without registering the plugin.\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 * \n * ```\n *\n * To use with ES6 modules, import the helper functions and use them with your layout:\n *\n * ```\n * import { install, makeGWASParser, makeBed12Parser, makePlinkLDParser } from 'locuszoom/esm/ext/lz-parsers';\n * LocusZoom.use(install);\n * ```\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~UserTabixLD} (if the {@link module:ext/lz-tabix-source} extension is loaded first)\n *\n * @module ext/lz-parsers\n */\n\nimport { makeBed12Parser } from './bed';\nimport { makeGWASParser } from './gwas/parsers';\nimport { guessGWAS } from './gwas/sniffers';\nimport { makePlinkLdParser } from './ld';\n\n\n// Most of this plugin consists of standalone functions. But we can add a few simple custom classes to the registry that help to use parsed output\nfunction install(LocusZoom) {\n if (LocusZoom.Adapters.has('TabixUrlSource')) {\n // Custom Tabix adapter depends on another extension being loaded first\n const TabixUrlSource = LocusZoom.Adapters.get('TabixUrlSource');\n const LDServer = LocusZoom.Adapters.get('LDServer');\n\n /**\n * Load user-provided LD from a tabix file, and filter the returned set of records based on a reference variant. (will attempt to choose a reference variant based on the most significant association variant, if no state.ldrefvar is specified)\n * @public\n * @alias module:LocusZoom_Adapters~UserTabixLD\n * @extends module:LocusZoom_Adapters~TabixUrlSource\n * @see {@link module:ext/lz-tabix-source} for required extension and installation instructions\n * @see {@link module:ext/lz-parsers} for required extension and installation instructions\n */\n class UserTabixLD extends TabixUrlSource {\n constructor(config) {\n if (!config.limit_fields) {\n config.limit_fields = ['variant2', 'position2', 'correlation'];\n }\n super(config);\n }\n\n _buildRequestOptions(state, assoc_data) {\n if (!assoc_data) {\n throw new Error('LD request must depend on association data');\n }\n // If no state refvar is provided, find the most significant variant in any provided assoc data.\n // Assumes that assoc satisfies the \"assoc\" fields contract, eg has fields variant and log_pvalue\n const base = super._buildRequestOptions(...arguments);\n if (!assoc_data.length) {\n base._skip_request = true;\n return base;\n }\n\n // NOTE: Reuses a method from another adapter to mix in functionality\n base.ld_refvar = LDServer.prototype.__find_ld_refvar(state, assoc_data);\n return base;\n }\n\n _performRequest(options) {\n // Skip request if this one depends on other data, and we are in a region with no data\n if (options._skip_request) {\n return Promise.resolve([]);\n }\n return super._performRequest(options);\n }\n\n _annotateRecords(records, options) {\n // A single PLINK LD file could contain several reference variants (SNP_A) in the same region.\n // Only show LD relative to the user-selected refvar in this plot.\n return records.filter((item) => item['variant1'] === options.ld_refvar);\n }\n }\n\n\n LocusZoom.Adapters.add('UserTabixLD', UserTabixLD);\n }\n}\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n// Support UMD (single symbol export)\nconst all = { install, makeBed12Parser, makeGWASParser, guessGWAS, makePlinkLdParser };\n\nexport default all;\n\nexport { install, makeBed12Parser, makeGWASParser, guessGWAS, makePlinkLdParser };\n","import {parseMarker} from '../../../helpers/parse';\n\nimport {\n MISSING_VALUES,\n has,\n parseAlleleFrequency,\n parsePvalToLog, normalizeChr,\n} from '../utils';\n\n\n/**\n * Specify how to parse a GWAS file, given certain column information.\n * Outputs an object with fields in portal API format.\n *\n * All column options must be provided as 1-indexed column IDs (human-friendly argument values)\n * @function\n * @alias module:ext/lz-parsers~makeGWASParser\n * @param options\n * @param [options.marker_col] A single identifier that specifies all of chrom, pos, ref, and alt as a single string field. Eg 1:23_A/C\n * @param [options.chrom_col] Chromosome\n * @param [options.pos_col] Position\n * @param [options.ref_col] Reference allele (relative to human reference genome, eg GRCh37 or 38).\n * @param [options.alt_col] Alt allele. Some programs specify generic A1/A2 instead; it is the job of the user to identify which columns of this GWAS are ref and alt.\n * @param [options.rsid_col] rsID\n * @param options.pvalue_col p-value (or -log10p)\n * @param [options.beta_col]\n * @param [options.stderr_beta_col]\n * @param [options.allele_freq_col] Specify allele frequencies directly\n * @param [options.allele_count_col] Specify allele frequencies in terms of count and n_samples\n * @param [options.n_samples_col]\n * @param [options.is_alt_effect=true] Some programs specify beta and frequency information in terms of ref, others alt. Identify effect allele to orient values to the correct allele.\n * @param [options.is_neg_log_pvalue=false]\n * @param [options.delimiter='\\t'] Since this parser is usually used with tabix data, this is rarely changed (tabix does not accept other delimiters)\n * @return {function(string)} A parser function that can be called on each line of text with the provided options\n */\nfunction makeGWASParser(\n {\n // Required fields\n marker_col, // Identify the variant: marker OR chrom/pos/ref/alt\n chrom_col,\n pos_col,\n ref_col,\n alt_col,\n pvalue_col, // pvalue (or log_pvalue; see options below)\n // Optional fields\n is_neg_log_pvalue = false,\n rsid_col,\n beta_col,\n stderr_beta_col,\n allele_freq_col, // Frequency: given directly, OR in terms of counts\n allele_count_col,\n n_samples_col,\n is_alt_effect = true, // whether effect allele is oriented towards alt. We don't support files like METAL, where ref/alt may switch places per line of the file\n delimiter = '\\t',\n },\n) {\n // Column IDs should be 1-indexed (human friendly)\n if (has(marker_col) && has(chrom_col) && has(pos_col)) {\n throw new Error('Must specify either marker OR chr + pos');\n }\n if (!(has(marker_col) || (has(chrom_col) && has(pos_col)))) {\n throw new Error('Must specify how to locate marker');\n }\n\n if (has(allele_count_col) && has(allele_freq_col)) {\n throw new Error('Allele count and frequency options are mutually exclusive');\n }\n if (has(allele_count_col) && !has(n_samples_col)) {\n throw new Error('To calculate allele frequency from counts, you must also provide n_samples');\n }\n\n\n return (line) => {\n const fields = line.split(delimiter);\n let chr;\n let pos;\n let ref;\n let alt;\n let rsid = null;\n\n let freq;\n let beta = null;\n let stderr_beta = null;\n let alt_allele_freq = null;\n let allele_count;\n let n_samples;\n\n if (has(marker_col)) {\n [chr, pos, ref, alt] = parseMarker(fields[marker_col - 1], false);\n } else if (has(chrom_col) && has(pos_col)) {\n chr = fields[chrom_col - 1];\n pos = fields[pos_col - 1];\n } else {\n throw new Error('Must specify all fields required to identify the variant');\n }\n\n chr = normalizeChr(chr);\n if (chr.startsWith('RS')) {\n throw new Error(`Invalid chromosome specified: value \"${chr}\" is an rsID`);\n }\n\n if (has(ref_col)) {\n ref = fields[ref_col - 1];\n }\n\n if (has(alt_col)) {\n alt = fields[alt_col - 1];\n }\n\n if (has(rsid_col)) {\n rsid = fields[rsid_col - 1];\n }\n\n if (MISSING_VALUES.has(ref)) {\n ref = null;\n }\n if (MISSING_VALUES.has(alt)) {\n alt = null;\n }\n\n if (MISSING_VALUES.has(rsid)) {\n rsid = null;\n } else if (rsid) {\n rsid = rsid.toLowerCase();\n if (!rsid.startsWith('rs')) {\n rsid = `rs${rsid}`;\n }\n }\n\n const log_pval = parsePvalToLog(fields[pvalue_col - 1], is_neg_log_pvalue);\n ref = ref || null;\n alt = alt || null;\n\n if (has(allele_freq_col)) {\n freq = fields[allele_freq_col - 1];\n }\n if (has(allele_count_col)) {\n allele_count = fields[allele_count_col - 1];\n n_samples = fields[n_samples_col - 1];\n }\n\n if (has(beta_col)) {\n beta = fields[beta_col - 1];\n beta = MISSING_VALUES.has(beta) ? null : (+beta);\n }\n\n if (has(stderr_beta_col)) {\n stderr_beta = fields[stderr_beta_col - 1];\n stderr_beta = MISSING_VALUES.has(stderr_beta) ? null : (+stderr_beta);\n }\n\n if (allele_freq_col || allele_count_col) {\n alt_allele_freq = parseAlleleFrequency({\n freq,\n allele_count,\n n_samples,\n is_alt_effect,\n });\n }\n const ref_alt = (ref && alt) ? `_${ref}/${alt}` : '';\n return {\n chromosome: chr,\n position: +pos,\n ref_allele: ref ? ref.toUpperCase() : null,\n alt_allele: alt ? alt.toUpperCase() : null,\n variant: `${chr}:${pos}${ref_alt}`,\n rsid,\n log_pvalue: log_pval,\n beta,\n stderr_beta,\n alt_allele_freq,\n };\n };\n}\n\n\nexport { makeGWASParser };\n","/**\n * Parsers for custom user-specified LD\n */\n\nimport {normalizeChr} from './utils';\nimport {normalizeMarker} from '../../helpers/parse';\n\n/**\n * Parse the output of plink v1.9 R2 calculations relative to one (or a few) target SNPs.\n * See: https://www.cog-genomics.org/plink/1.9/ld and\n * reformatting commands at https://www.cog-genomics.org/plink/1.9/other\n * @function\n * @alias module:ext/lz-parsers~makePlinkLdParser\n * @param {object} options\n * @param {boolean} [options.normalize=true] Normalize fields to expected datatypes and format; if false, returns raw strings as given in the file\n * @return {function} A configured parser function that runs on one line of text from an input file\n */\nfunction makePlinkLdParser({normalize = true} = {}) {\n return (line) => {\n // Sample headers are below: SNP_A and SNP_B are based on ID column of the VCF\n // CHR_A BP_A SNP_A CHR_B BP_B SNP_B R2\n let [chromosome1, position1, variant1, chromosome2, position2, variant2, correlation] = line.trim().split('\\t');\n if (normalize) {\n chromosome1 = normalizeChr(chromosome1);\n chromosome2 = normalizeChr(chromosome2);\n variant1 = normalizeMarker(variant1);\n variant2 = normalizeMarker(variant2);\n position1 = +position1;\n position2 = +position2;\n correlation = +correlation;\n }\n\n return {chromosome1, position1, variant1, chromosome2, position2, variant2, correlation};\n };\n}\n\nexport { makePlinkLdParser };\n"],"sourceRoot":""} \ 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 87d428b1..60aea16c 100644 --- a/dist/ext/lz-tabix-source.min.js +++ b/dist/ext/lz-tabix-source.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +var LzTabix;(()=>{var t={398:t=>{var i=15,e=-2,n=-3,r=-5,s=13,a=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=[96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,192,80,7,10,0,8,96,0,8,32,0,9,160,0,8,0,0,8,128,0,8,64,0,9,224,80,7,6,0,8,88,0,8,24,0,9,144,83,7,59,0,8,120,0,8,56,0,9,208,81,7,17,0,8,104,0,8,40,0,9,176,0,8,8,0,8,136,0,8,72,0,9,240,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,200,81,7,13,0,8,100,0,8,36,0,9,168,0,8,4,0,8,132,0,8,68,0,9,232,80,7,8,0,8,92,0,8,28,0,9,152,84,7,83,0,8,124,0,8,60,0,9,216,82,7,23,0,8,108,0,8,44,0,9,184,0,8,12,0,8,140,0,8,76,0,9,248,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,196,81,7,11,0,8,98,0,8,34,0,9,164,0,8,2,0,8,130,0,8,66,0,9,228,80,7,7,0,8,90,0,8,26,0,9,148,84,7,67,0,8,122,0,8,58,0,9,212,82,7,19,0,8,106,0,8,42,0,9,180,0,8,10,0,8,138,0,8,74,0,9,244,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,204,81,7,15,0,8,102,0,8,38,0,9,172,0,8,6,0,8,134,0,8,70,0,9,236,80,7,9,0,8,94,0,8,30,0,9,156,84,7,99,0,8,126,0,8,62,0,9,220,82,7,27,0,8,110,0,8,46,0,9,188,0,8,14,0,8,142,0,8,78,0,9,252,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,194,80,7,10,0,8,97,0,8,33,0,9,162,0,8,1,0,8,129,0,8,65,0,9,226,80,7,6,0,8,89,0,8,25,0,9,146,83,7,59,0,8,121,0,8,57,0,9,210,81,7,17,0,8,105,0,8,41,0,9,178,0,8,9,0,8,137,0,8,73,0,9,242,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,202,81,7,13,0,8,101,0,8,37,0,9,170,0,8,5,0,8,133,0,8,69,0,9,234,80,7,8,0,8,93,0,8,29,0,9,154,84,7,83,0,8,125,0,8,61,0,9,218,82,7,23,0,8,109,0,8,45,0,9,186,0,8,13,0,8,141,0,8,77,0,9,250,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,198,81,7,11,0,8,99,0,8,35,0,9,166,0,8,3,0,8,131,0,8,67,0,9,230,80,7,7,0,8,91,0,8,27,0,9,150,84,7,67,0,8,123,0,8,59,0,9,214,82,7,19,0,8,107,0,8,43,0,9,182,0,8,11,0,8,139,0,8,75,0,9,246,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,206,81,7,15,0,8,103,0,8,39,0,9,174,0,8,7,0,8,135,0,8,71,0,9,238,80,7,9,0,8,95,0,8,31,0,9,158,84,7,99,0,8,127,0,8,63,0,9,222,82,7,27,0,8,111,0,8,47,0,9,190,0,8,15,0,8,143,0,8,79,0,9,254,96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,193,80,7,10,0,8,96,0,8,32,0,9,161,0,8,0,0,8,128,0,8,64,0,9,225,80,7,6,0,8,88,0,8,24,0,9,145,83,7,59,0,8,120,0,8,56,0,9,209,81,7,17,0,8,104,0,8,40,0,9,177,0,8,8,0,8,136,0,8,72,0,9,241,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,201,81,7,13,0,8,100,0,8,36,0,9,169,0,8,4,0,8,132,0,8,68,0,9,233,80,7,8,0,8,92,0,8,28,0,9,153,84,7,83,0,8,124,0,8,60,0,9,217,82,7,23,0,8,108,0,8,44,0,9,185,0,8,12,0,8,140,0,8,76,0,9,249,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,197,81,7,11,0,8,98,0,8,34,0,9,165,0,8,2,0,8,130,0,8,66,0,9,229,80,7,7,0,8,90,0,8,26,0,9,149,84,7,67,0,8,122,0,8,58,0,9,213,82,7,19,0,8,106,0,8,42,0,9,181,0,8,10,0,8,138,0,8,74,0,9,245,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,205,81,7,15,0,8,102,0,8,38,0,9,173,0,8,6,0,8,134,0,8,70,0,9,237,80,7,9,0,8,94,0,8,30,0,9,157,84,7,99,0,8,126,0,8,62,0,9,221,82,7,27,0,8,110,0,8,46,0,9,189,0,8,14,0,8,142,0,8,78,0,9,253,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,195,80,7,10,0,8,97,0,8,33,0,9,163,0,8,1,0,8,129,0,8,65,0,9,227,80,7,6,0,8,89,0,8,25,0,9,147,83,7,59,0,8,121,0,8,57,0,9,211,81,7,17,0,8,105,0,8,41,0,9,179,0,8,9,0,8,137,0,8,73,0,9,243,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,203,81,7,13,0,8,101,0,8,37,0,9,171,0,8,5,0,8,133,0,8,69,0,9,235,80,7,8,0,8,93,0,8,29,0,9,155,84,7,83,0,8,125,0,8,61,0,9,219,82,7,23,0,8,109,0,8,45,0,9,187,0,8,13,0,8,141,0,8,77,0,9,251,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,199,81,7,11,0,8,99,0,8,35,0,9,167,0,8,3,0,8,131,0,8,67,0,9,231,80,7,7,0,8,91,0,8,27,0,9,151,84,7,67,0,8,123,0,8,59,0,9,215,82,7,19,0,8,107,0,8,43,0,9,183,0,8,11,0,8,139,0,8,75,0,9,247,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,207,81,7,15,0,8,103,0,8,39,0,9,175,0,8,7,0,8,135,0,8,71,0,9,239,80,7,9,0,8,95,0,8,31,0,9,159,84,7,99,0,8,127,0,8,63,0,9,223,82,7,27,0,8,111,0,8,47,0,9,191,0,8,15,0,8,143,0,8,79,0,9,255],h=[80,5,1,87,5,257,83,5,17,91,5,4097,81,5,5,89,5,1025,85,5,65,93,5,16385,80,5,3,88,5,513,84,5,33,92,5,8193,82,5,9,90,5,2049,86,5,129,192,5,24577,80,5,2,87,5,385,83,5,25,91,5,6145,81,5,7,89,5,1537,85,5,97,93,5,24577,80,5,4,88,5,769,84,5,49,92,5,12289,82,5,13,90,5,3073,86,5,193,192,5,24577],l=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],f=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,112,112],u=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],d=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function _(){}function c(){this.was=[0]}_.prototype.inflateInit=function(t,i){return t||(t=15),i&&(i=!1),this.istate=new c,this.istate.inflateInit(this,i?-t:t)},_.prototype.inflate=function(t){return null==this.istate?e:this.istate.inflate(this,t)},_.prototype.inflateEnd=function(){if(null==this.istate)return e;var t=istate.inflateEnd(this);return this.istate=null,t},_.prototype.inflateSync=function(){return istate.inflateSync(this)},_.prototype.inflateSetDictionary=function(t,i){return istate.inflateSetDictionary(this,t,i)},c.prototype.inflateReset=function(t){return null==t||null==t.istate?e:(t.total_in=t.total_out=0,t.msg=null,t.istate.mode=0!=t.istate.nowrap?7:0,t.istate.blocks.reset(t,null),0)},c.prototype.inflateEnd=function(t){return null!=this.blocks&&this.blocks.free(t),this.blocks=null,0},c.prototype.inflateInit=function(t,i){return t.msg=null,this.blocks=null,nowrap=0,i<0&&(i=-i,nowrap=1),i<8||i>15?(this.inflateEnd(t),e):(this.wbits=i,t.istate.blocks=new v(t,0!=t.istate.nowrap?null:this,1<>4)>t.istate.wbits){t.istate.mode=s,t.msg="invalid window size",t.istate.marker=5;break}t.istate.mode=1;case 1:if(0==t.avail_in)return a;if(a=i,t.avail_in--,t.total_in++,o=255&t.next_in[t.next_in_index++],((t.istate.method<<8)+o)%31!=0){t.istate.mode=s,t.msg="incorrect header check",t.istate.marker=5;break}if(0==(32&o)){t.istate.mode=7;break}t.istate.mode=2;case 2:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need=(255&t.next_in[t.next_in_index++])<<24&4278190080,t.istate.mode=3;case 3:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need+=(255&t.next_in[t.next_in_index++])<<16&16711680,t.istate.mode=4;case 4:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need+=(255&t.next_in[t.next_in_index++])<<8&65280,t.istate.mode=5;case 5:return 0==t.avail_in?a:(a=i,t.avail_in--,t.total_in++,t.istate.need+=255&t.next_in[t.next_in_index++],t.adler=t.istate.need,t.istate.mode=6,2);case 6:return t.istate.mode=s,t.msg="need dictionary",t.istate.marker=0,e;case 7:if((a=t.istate.blocks.proc(t,a))==n){t.istate.mode=s,t.istate.marker=0;break}if(0==a&&(a=i),1!=a)return a;if(a=i,t.istate.blocks.reset(t,t.istate.was),0!=t.istate.nowrap){t.istate.mode=12;break}t.istate.mode=8;case 8:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need=(255&t.next_in[t.next_in_index++])<<24&4278190080,t.istate.mode=9;case 9:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need+=(255&t.next_in[t.next_in_index++])<<16&16711680,t.istate.mode=10;case 10:if(0==t.avail_in)return a;a=i,t.avail_in--,t.total_in++,t.istate.need+=(255&t.next_in[t.next_in_index++])<<8&65280,t.istate.mode=11;case 11:if(0==t.avail_in)return a;if(a=i,t.avail_in--,t.total_in++,t.istate.need+=255&t.next_in[t.next_in_index++],t.istate.was[0]!=t.istate.need){t.istate.mode=s,t.msg="incorrect data check",t.istate.marker=5;break}t.istate.mode=12;case 12:return 1;case s:return n;default:return e}},c.prototype.inflateSetDictionary=function(t,i,r){var s=0,a=r;return null==t||null==t.istate||6!=t.istate.mode?e:t._adler.adler32(1,i,0,r)!=t.adler?n:(t.adler=t._adler.adler32(0,null,0,0),a>=1<>>1){case 0:o>>>=3,o>>>=r=7&(h-=3),h-=r,this.mode=1;break;case 1:w(v=new Int32Array(1),p=new Int32Array(1),m=[],y=[],t),this.codes.init(v[0],p[0],m[0],0,y[0],0,t),o>>>=3,h-=3,this.mode=6;break;case 2:o>>>=3,h-=3,this.mode=3;break;case 3:return o>>>=3,h-=3,this.mode=s,t.msg="invalid block type",i=n,this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i)}break;case 1:for(;h<32;){if(0==f)return this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);i=0,f--,o|=(255&t.next_in[l++])<>>16&65535)!=(65535&o))return this.mode=s,t.msg="invalid stored block lengths",i=n,this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);this.left=65535&o,o=h=0,this.mode=0!=this.left?2:0!=this.last?7:0;break;case 2:if(0==f)return this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,write=u,this.inflate_flush(t,i);if(0==d&&(u==end&&0!=read&&(d=(u=0)f&&(r=f),r>d&&(r=d),g(t.next_in,l,this.window,u,r),l+=r,f-=r,u+=r,d-=r,0!=(this.left-=r))break;this.mode=0!=this.last?7:0;break;case 3:for(;h<14;){if(0==f)return this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);i=0,f--,o|=(255&t.next_in[l++])<29||(r>>5&31)>29)return this.mode=9,t.msg="too many length or distance symbols",i=n,this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);if(r=258+(31&r)+(r>>5&31),null==this.blens||this.blens.length>>=14,h-=14,this.index=0,mode=4;case 4:for(;this.index<4+(this.table>>>10);){for(;h<3;){if(0==f)return this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);i=0,f--,o|=(255&t.next_in[l++])<>>=3,h-=3}for(;this.index<19;)this.blens[b[this.index++]]=0;if(this.bb[0]=7,0!=(r=this.inftree.inflate_trees_bits(this.blens,this.bb,this.tb,this.hufts,t)))return(i=r)==n&&(this.blens=null,this.mode=9),this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,write=u,this.inflate_flush(t,i);this.index=0,this.mode=5;case 5:for(;r=this.table,this.index<258+(31&r)+(r>>5&31);){var c,x;for(r=this.bb[0];h>>=r,h-=r,this.blens[this.index++]=x;else{for(_=18==x?7:x-14,c=18==x?11:3;h>>=r)&a[_],o>>>=_,h-=_,(_=this.index)+c>258+(31&(r=this.table))+(r>>5&31)||16==x&&_<1)return this.blens=null,this.mode=9,t.msg="invalid bit length repeat",i=n,this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);x=16==x?this.blens[_-1]:0;do{this.blens[_++]=x}while(0!=--c);this.index=_}}this.tb[0]=-1;var v=new Int32Array(1),p=new Int32Array(1),m=new Int32Array(1),y=new Int32Array(1);if(v[0]=9,p[0]=6,r=this.table,0!=(r=this.inftree.inflate_trees_dynamic(257+(31&r),1+(r>>5&31),this.blens,v,p,m,y,this.hufts,t)))return r==n&&(this.blens=null,this.mode=s),i=r,this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,this.inflate_flush(t,i);this.codes.init(v[0],p[0],this.hufts,m[0],this.hufts,y[0],t),this.mode=6;case 6:if(this.bitb=o,this.bitk=h,t.avail_in=f,t.total_in+=l-t.next_in_index,t.next_in_index=l,this.write=u,1!=(i=this.codes.proc(this,t,i)))return this.inflate_flush(t,i);if(i=0,this.codes.free(t),l=t.next_in_index,f=t.avail_in,o=this.bitb,h=this.bitk,d=(u=this.write)t.avail_out&&(e=t.avail_out),0!=e&&i==r&&(i=0),t.avail_out-=e,t.total_out+=e,null!=this.checkfn&&(t.adler=this.check=t._adler.adler32(this.check,this.window,s,e)),g(this.window,s,t.next_out,n,e),n+=e,(s+=e)==this.end&&(s=0,this.write==this.end&&(this.write=0),(e=this.write-s)>t.avail_out&&(e=t.avail_out),0!=e&&i==r&&(i=0),t.avail_out-=e,t.total_out+=e,null!=this.checkfn&&(t.adler=this.check=t._adler.adler32(this.check,this.window,s,e)),g(this.window,s,t.next_out,n,e),n+=e,s+=e),t.next_out_index=n,this.read=s,i};function p(){}function m(){}function w(t,i,e,n,r){return t[0]=9,i[0]=5,e[0]=o,n[0]=h,0}p.prototype.init=function(t,i,e,n,r,s,a){this.mode=0,this.lbits=t,this.dbits=i,this.ltree=e,this.ltree_index=n,this.dtree=r,this.dtree_index=s,this.tree=null},p.prototype.proc=function(t,i,r){var s,o,h,l,f,u,d,_=0,c=0,x=0;for(x=i.next_in_index,l=i.avail_in,_=t.bitb,c=t.bitk,u=(f=t.write)=258&&l>=10&&(t.bitb=_,t.bitk=c,i.avail_in=l,i.total_in+=x-i.next_in_index,i.next_in_index=x,t.write=f,r=this.inflate_fast(this.lbits,this.dbits,this.ltree,this.ltree_index,this.dtree,this.dtree_index,t,i),x=i.next_in_index,l=i.avail_in,_=t.bitb,c=t.bitk,u=(f=t.write)>>=this.tree[o+1],c-=this.tree[o+1],0==(h=this.tree[o])){this.lit=this.tree[o+2],this.mode=6;break}if(0!=(16&h)){this.get=15&h,this.len=this.tree[o+2],this.mode=2;break}if(0==(64&h)){this.need=h,this.tree_index=o/3+this.tree[o+2];break}if(0!=(32&h)){this.mode=7;break}return this.mode=9,i.msg="invalid literal/length code",r=n,t.bitb=_,t.bitk=c,i.avail_in=l,i.total_in+=x-i.next_in_index,i.next_in_index=x,t.write=f,t.inflate_flush(i,r);case 2:for(s=this.get;c>=s,c-=s,this.need=this.dbits,this.tree=this.dtree,this.tree_index=this.dtree_index,this.mode=3;case 3:for(s=this.need;c>=this.tree[o+1],c-=this.tree[o+1],0!=(16&(h=this.tree[o]))){this.get=15&h,this.dist=this.tree[o+2],this.mode=4;break}if(0==(64&h)){this.need=h,this.tree_index=o/3+this.tree[o+2];break}return this.mode=9,i.msg="invalid distance code",r=n,t.bitb=_,t.bitk=c,i.avail_in=l,i.total_in+=x-i.next_in_index,i.next_in_index=x,t.write=f,t.inflate_flush(i,r);case 4:for(s=this.get;c>=s,c-=s,this.mode=5;case 5:for(d=f-this.dist;d<0;)d+=t.end;for(;0!=this.len;){if(0==u&&(f==t.end&&0!=t.read&&(u=(f=0)7&&(c-=8,l++,x--),t.write=f,r=t.inflate_flush(i,r),u=(f=t.write)>=u[S+1],x-=u[S+1],0!=(16&_)){for(_&=15,k=u[S+2]+(c&a[_]),c>>=_,x-=_;x<15;)v--,c|=(255&l.next_in[b++])<>=u[S+1],x-=u[S+1],0!=(16&_)){for(_&=15;x<_;)v--,c|=(255&l.next_in[b++])<>=_,x-=_,m-=k,p>=A)C=p-A,h.window[p++]=h.window[C++],h.window[p++]=h.window[C++],k-=2;else{C=p-A;do{C+=h.end}while(C<0);if(k>(_=h.end-C)){if(k-=_,p-C>0&&_>p-C)do{h.window[p++]=h.window[C++]}while(0!=--_);else g(h.window,C,h.window,p,_),p+=_,C+=_,_=0;C=0}}do{h.window[p++]=h.window[C++]}while(0!=--k);break}if(0!=(64&_))return l.msg="invalid distance code",v+=k=x>>3<(k=l.avail_in-v)?x>>3:k,b-=k,x-=k<<3,h.bitb=c,h.bitk=x,l.avail_in=v,l.total_in+=b-l.next_in_index,l.next_in_index=b,h.write=p,n;f+=u[S+2],_=u[S=3*(d+(f+=c&a[_]))]}break}if(0!=(64&_))return 0!=(32&_)?(v+=k=x>>3<(k=l.avail_in-v)?x>>3:k,b-=k,x-=k<<3,h.bitb=c,h.bitk=x,l.avail_in=v,l.total_in+=b-l.next_in_index,l.next_in_index=b,h.write=p,1):(l.msg="invalid literal/length code",v+=k=x>>3<(k=l.avail_in-v)?x>>3:k,b-=k,x-=k<<3,h.bitb=c,h.bitk=x,l.avail_in=v,l.total_in+=b-l.next_in_index,l.next_in_index=b,h.write=p,n);if(f+=u[S+2],0==(_=u[S=3*(d+(f+=c&a[_]))])){c>>=u[S+1],x-=u[S+1],h.window[p++]=u[S+2],m--;break}}else c>>=u[S+1],x-=u[S+1],h.window[p++]=u[S+2],m--}while(m>=258&&v>=10);return v+=k=x>>3<(k=l.avail_in-v)?x>>3:k,b-=k,x-=k<<3,h.bitb=c,h.bitk=x,l.avail_in=v,l.total_in+=b-l.next_in_index,l.next_in_index=b,h.write=p,0},m.prototype.huft_build=function(t,e,s,a,o,h,l,f,u,d,_){var c,x,b,v,p,m,w,y,k,A,C,S,R,I,L;A=0,p=s;do{this.c[t[e+A]]++,A++,p--}while(0!=p);if(this.c[0]==s)return l[0]=-1,f[0]=0,0;for(y=f[0],m=1;m<=i&&0==this.c[m];m++);for(w=m,yp&&(y=p),f[0]=y,I=1<S+y;){if(v++,L=(L=b-(S+=y))>y?y:L,(x=1<<(m=w-S))>c+1&&(x-=c+1,R=w,m1440)return n;this.u[v]=C=this.hn[0],this.hn[0]+=L,0!=v?(this.x[v]=p,this.r[0]=m,this.r[1]=y,m=p>>>S-y,this.r[2]=C-this.u[v-1]-m,g(this.r,0,u,3*(this.u[v-1]+m),3)):l[0]=C}for(this.r[1]=w-S,A>=s?this.r[0]=192:_[A]>>S;m>>=1)p^=m;for(p^=m,k=(1<257?(x==n?c.msg="oversubscribed distance tree":x==r?(c.msg="incomplete distance tree",x=n):-4!=x&&(c.msg="empty distance tree with lengths",x=n),x):0)},m.prototype.initWorkArea=function(t){null==this.hn&&(this.hn=new Int32Array(1),this.v=new Int32Array(t),this.c=new Int32Array(16),this.r=new Int32Array(3),this.u=new Int32Array(i),this.x=new Int32Array(16)),this.v.length100?k(new Uint8Array(t.buffer,t.byteOffset+i,r),e,n):function(t,i,e,n,r){for(var s=0;s{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},e.o=(t,i)=>Object.prototype.hasOwnProperty.call(t,i);var n={};(()=>{"use strict";e.d(n,{default:()=>q});function t(t){return r(i(s(t)))}function i(t){return o(h(a(t),8*t.length))}function r(t){for(var i="",e=t.length,n=0;n8*t.length?i+="":i+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>>6*(3-s)&63);return i}function s(t){for(var i,e,n="",r=-1;++r>>6&31,128|63&i):i<=65535?n+=String.fromCharCode(224|i>>>12&15,128|i>>>6&63,128|63&i):i<=2097151&&(n+=String.fromCharCode(240|i>>>18&7,128|i>>>12&63,128|i>>>6&63,128|63&i));return n}function a(t){for(var i=Array(t.length>>2),e=0;e>5]|=(255&t.charCodeAt(e/8))<<24-e%32;return i}function o(t){for(var i="",e=0;e<32*t.length;e+=8)i+=String.fromCharCode(t[e>>5]>>>24-e%32&255);return i}function h(t,i){t[i>>5]|=128<<24-i%32,t[15+(i+64>>9<<4)]=i;for(var e=Array(80),n=1732584193,r=-271733879,s=-1732584194,a=271733878,o=-1009589776,h=0;h>16)+(i>>16)+(e>>16)<<16|65535&e}function d(t,i){return t<>>32-i}function _(t){this.value=t,this.listeners=[]}function c(){this.queue=[]}_.prototype.addListener=function(t){this.listeners.push(t)},_.prototype.addListenerAndFire=function(t){this.listeners.push(t),t(this.value)},_.prototype.removeListener=function(t){var i,e;i=this.listeners,(e=function(t,i){if(!t)return-1;for(var e=0;e=0&&i.splice(e,1)},_.prototype.get=function(){return this.value},_.prototype.set=function(t){this.value=t;for(var i=0;i=0&&navigator.userAgent.indexOf("Chrome")<0;function m(t){if(!t)return null;for(var i=new Uint8Array(t.length),e=0;e1e8)throw"Monster fetch!";r.setRequestHeader("Range","bytes="+e.start+"-"+e.end),e.end-e.start+1}r.onreadystatechange=function(){if(4==r.readyState)return 200==r.status||206==r.status?i(r.responseText):i(null)},e.opts.credentials&&(r.withCredentials=!0),r.send()}catch(t){return i(null)}})).catch((function(t){return console.log(t),i(null,t)}))},b.prototype.salted=function(){var t=function(t){var i={};for(var e in t)i[e]=t[e];return i}(this.opts);return t.salt=!0,new b(this.url,this.start,this.end,t)},b.prototype.getURL=function(){return this.opts.resolver?this.opts.resolver(this.url).then((function(t){return"string"==typeof t?t:t.url})):Promise.resolve(this.url)},b.prototype.fetch=function(i,e){var n=this,r=(e=e||{}).attempt||1,s=e.truncatedLength;if(r>3)return i(null);this.getURL().then((function(a){try{var o;e.timeout&&!n.opts.credentials&&(o=setTimeout((function(){return console.log("timing out "+a),l.abort(),i(null,"Timeout")}),e.timeout));var h,l=new XMLHttpRequest;if((p||n.opts.salt)&&a.indexOf("?")<0&&(a=a+"?salt="+t(Date.now()+","+ ++v)),l.open("GET",a,!0),l.overrideMimeType("text/plain; charset=x-user-defined"),n.end){if(n.end-n.start>1e8)throw"Monster fetch!";l.setRequestHeader("Range","bytes="+n.start+"-"+n.end),h=n.end-n.start+1}l.responseType="arraybuffer",l.onreadystatechange=function(){if(4==l.readyState){if(o&&clearTimeout(o),200==l.status||206==l.status){if(l.response){var t=l.response.byteLength;return!h||h==t||s&&t==s?i(l.response):n.fetch(i,{attempt:r+1,truncatedLength:t})}if(l.mozResponseArrayBuffer)return i(l.mozResponseArrayBuffer);var e=l.responseText;return!h||h==e.length||s&&e.length==s?i(m(l.responseText)):n.fetch(i,{attempt:r+1,truncatedLength:e.length})}return n.fetch(i,{attempt:r+1})}},n.opts.credentials&&(l.withCredentials=!0),l.send()}catch(t){return i(null)}})).catch((function(t){return console.log(t),i(null,t)}))};var w=new ArrayBuffer(8);new Uint8Array(w),new Float32Array(w);function y(t,i){return t[i+3]<<24|t[i+2]<<16|t[i+1]<<8|t[i]}var g=e(398);function k(t,i){this.block=t,this.offset=i}function A(t,i,e){var n=4294967296*(255&t[i+6])+16777216*(255&t[i+5])+65536*(255&t[i+4])+256*(255&t[i+3])+(255&t[i+2]),r=t[i+1]<<8|t[i];return 0!=n||0!=r||e?new k(n,r):null}function C(t,i){i=Math.min(i||1,t.byteLength-50);for(var e=[],n=[0],r=0;n[0]n._max&&(n._max=t._max):(e.push(n),n=t)})),e.push(n),this._ranges=e}function L(t,i){return t._mini._min?1:t._maxt._max?1:0}R.prototype.min=function(){return this._min},R.prototype.max=function(){return this._max},R.prototype.contains=function(t){return t>=this._min&&t<=this._max},R.prototype.isContiguous=function(){return!0},R.prototype.ranges=function(){return[this]},R.prototype._pushRanges=function(t){t.push(this)},R.prototype.toString=function(){return"["+this._min+"-"+this._max+"]"},I.prototype.min=function(){return this._ranges[0].min()},I.prototype.max=function(){return this._ranges[this._ranges.length-1].max()},I.prototype.lower_bound=function(t){var i=this.ranges();if(t>this.max())return i.length;if(ti[r]._max)e=r+1;else{if(!(tt._max&&(t._max=e[n]._max),this._ranges.splice(i,n-i+1,t)}}else this._ranges.push(t)},I.prototype.isContiguous=function(){return this._ranges.length>1},I.prototype.ranges=function(){return this._ranges},I.prototype._pushRanges=function(t){for(var i=0;i0&&(t+=","),t+=this._ranges[i].toString();return t};function T(){}function U(t,i){return new Promise((function(e,n){var r,s,a,o;r=new b(t),s=new b(i),a=function(t,i){i?n(i):e(t)},(o=new T).data=r,o.tbi=s,o.tbi.fetch((function(t){if(!t)return a(null,"Couldn't access Tabix");var i=C(t,t.byteLength),e=new Uint8Array(i);if(21578324!=y(e,0))return a(null,"Not a tabix index");var n=y(e,4);o.format=y(e,8),o.colSeq=y(e,12),o.colStart=y(e,16),o.colEnd=y(e,20),o.meta=y(e,24),o.skip=y(e,28),y(e,32),o.indices=[];var r=36;o.chrToIndex={},o.indexToChr=[];for(var s=0;s0&&(p+=65536),p0&&(o.indices[u]=new Uint8Array(i,d,r-d))}o.headerMax=f,a(o)}),{timeout:5e4})}))}function E(t){const i=t.Adapters.get("BaseLZAdapter");t.Adapters.add("TabixUrlSource",class extends i{constructor(t){if(super(t),!t.parser_func||!t.url_data&&!t.reader)throw new Error("Tabix source is missing required configuration options");if(this.parser=t.parser_func,this.url_data=t.url_data,this.url_tbi=t.url_tbi||`${this.url_data}.tbi`,this._overfetch=t.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.url_data?this._reader_promise=U(this.url_data,this.url_tbi).catch((function(){throw new Error("Failed to create a tabix reader from the provided URL")})):this._reader_promise=Promise.resolve(t.reader)}_performRequest(t){return new Promise(((i,e)=>{const n=t.start,r=t.end,s=this._overfetch*(r-n),a=t.start-s,o=t.end+s;this._reader_promise.then((n=>{n.fetch(t.chr,a,o,(function(t,n){n&&e(new Error("Could not read requested region. This may indicate an error with the .tbi index.")),i(t)}))}))}))}_normalizeResponse(t){return t.map(this.parser)}})}T.prototype.blocksForRange=function(t,i,e){var n=this.indices[t];if(!n)return[];for(var r=function(t,i){var e,n=[];for(--i,n.push(0),e=1+(t>>26);e<=1+(i>>26);++e)n.push(e);for(e=9+(t>>23);e<=9+(i>>23);++e)n.push(e);for(e=73+(t>>20);e<=73+(i>>20);++e)n.push(e);for(e=585+(t>>17);e<=585+(i>>17);++e)n.push(e);for(e=4681+(t>>14);e<=4681+(i>>14);++e)n.push(e);return n}(i,e),s=[],a=0;a>14,v-1),w=Math.min(e>>14,v-1);for(a=m;a<=w;++a){var g=A(n,f+4+8*a);g&&((!p||g.block=p.block&&C.maxv.offset>=p.offset&&k.push(C)}h=k;var R=[];for(a=0;a0){var L=R[0];for(a=1;a=a.length)return n(l);if(h){var s=new Uint8Array(h);return r.readRecords(s,a[f].minv.offset,l,i,e,o),h=null,++f,t()}var u=a[f],d=u.minv.block,_=u.maxv.block+65536;r.data.slice(d,_-d).fetch((function(i){try{return h=C(i,u.maxv.block-u.minv.block+1),t()}catch(t){return n(null,t)}}))}()}catch(t){n(null,t)}},T.prototype.readRecords=function(t,i,e,n,r,s){t:for(;;){for(var a="";i0&&(f=parseInt(h[this.colEnd-1])),65536&this.format&&++l,l<=r&&f>=n&&e.push(a)}continue t}a+=String.fromCharCode(o)}return}},T.prototype.fetchHeader=function(t,i){var e={metaOnly:!0,skipped:!1,nLines:0};i=i||e,Object.keys(e).forEach((function(t){i.hasOwnProperty(t)||(i[t]=e[t])}));var n=this;n.data.slice(0,n.headerMax).fetch((function(e){if(!e)return t(null,"Fetch failed");for(var r=new Uint8Array(C(e,e.byteLength)),s=0,a="",o=[];s {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\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__ = tabix;","/**\n * An adapter that fetches data from a remote Tabix-indexed datafile, instead of a RESTful API.\n * Requires a generic user-specified parser function.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~TabixUrlSource}\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - Vendor assets\n * - LocusZoom\n * - tabix-reader (available via NPM or a related CDN)\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import LzTabixSource from 'locuszoom/esm/ext/lz-tabix-source';\n * LocusZoom.use(LzTabixSource);\n * ```\n *\n * Then use the Adapter made available by this extension. For example:\n *\n * ```javascript\n * data_sources.add(\"assoc\", [\"TabixUrlSource\", {\n * url_data: 'https://s3-bucket.example/tabix-indexed-bgzip-file.gz',\n * parser_func: (line_of_text) => object_of_parsed_data_for_this_line,\n * // Tabix performs region queries. If you are fetching interval data (one end outside the edge of the plot), then\n * // \"overfetching\" can help to ensure that data partially outside the view region is retrieved\n * // If you are fetching single-point data like association summary stats, then overfetching is unnecessary\n * params: { overfetch: 0.25 }\n * }]);\n * ```\n *\n * @module\n */\nimport tabix from 'tabix-reader';\n\n\nfunction install(LocusZoom) {\n const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter');\n\n /**\n * Loads data from a remote Tabix file (if the file host has been configured with proper\n * CORS and Range header support). For instructions on how to configure a remote file host such as S3 or\n * Google Cloud storage to serve files in the manner required, see:\n * https://docs.cancergenomicscloud.org/docs/enabling-cross-origin-resource-sharing-cors#CORS\n *\n * @alias module:LocusZoom_Adapters~TabixUrlSource\n * @see {@link module:ext/lz-tabix-source} for required extension and installation instructions\n * @see module:LocusZoom_Adapters~BaseApiAdapter\n * @param {function} config.parser_func A function that parses a single line of text and returns (usually) a\n * structured object of data fields\n * @param {string} config.url_data The URL for the bgzipped and tabix-indexed file\n * @param {string} [config.url_tbi] The URL for the tabix index. Defaults to `url_data` + '.tbi'\n * @param {number} [config.params.overfetch = 0] Optionally fetch more data than is required to satisfy the\n * region query. (specified as a fraction of the region size, 0-1).\n * Useful for sources where interesting features might lie near the edges of the plot, eg BED track intervals.\n */\n class TabixUrlSource extends BaseAdapter {\n parseInit(init) {\n if (!init.parser_func || !init.url_data) {\n throw new Error('Tabix source is missing required configuration options');\n }\n this.parser = init.parser_func;\n // TODO: In the future, accept a pre-configured reader instance (as an alternative to the URL). Most useful\n // for UIs that want to validate the tabix file before adding it to the plot, like LocalZoom.\n this.url_data = init.url_data;\n this.url_tbi = init.url_tbi || `${this.url_data}.tbi`;\n\n // In tabix mode, sometimes we want to fetch a slightly larger region than is displayed, in case a\n // feature is on the edge of what the tabix query would return.\n // Specify overfetch in units of % of total region size. (\"fetch 10% extra before and after\")\n const params = init.params || {};\n this.params = params;\n this._overfetch = params.overfetch || 0;\n\n if (this._overfetch < 0 || this._overfetch > 1) {\n throw new Error('Overfetch must be specified as a fraction (0-1) of the requested region size');\n }\n\n // Assuming that the `tabix-reader` library has been loaded via a CDN, this will create the reader\n // Since fetching the index is a remote operation, all reader usages will be via an async interface.\n this._reader_promise = tabix.urlReader(this.url_data, this.url_tbi).catch(function () {\n throw new Error('Failed to create a tabix reader from the provided URL');\n });\n }\n\n fetchRequest(state /*, chain, fields */) {\n return new Promise((resolve, reject) => {\n // Ensure that the reader is fully created (and index available), then make a query\n const region_start = state.start;\n const region_end = state.end;\n const extra_amount = this._overfetch * (region_end - region_start);\n\n const start = state.start - extra_amount;\n const end = state.end + extra_amount;\n this._reader_promise.then((reader) => {\n reader.fetch(state.chr, start, end, function (data, err) {\n if (err) {\n reject(new Error('Could not read requested region. This may indicate an error with the .tbi index.'));\n }\n resolve(data);\n });\n });\n });\n }\n\n normalizeResponse(data) {\n // Parse the data from lines of text to objects\n return data.map(this.parser);\n }\n }\n\n LocusZoom.Adapters.add('TabixUrlSource', TabixUrlSource);\n}\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://[name]/./node_modules/jszlib/js/inflate.js","webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/define property getters","webpack://[name]/webpack/runtime/hasOwnProperty shorthand","webpack://[name]/./node_modules/tabix-reader/src/lib/sha1.js","webpack://[name]/./node_modules/tabix-reader/src/lib/utils.js","webpack://[name]/./node_modules/tabix-reader/src/lib/bin.js","webpack://[name]/./node_modules/tabix-reader/src/lib/lh3utils.js","webpack://[name]/./node_modules/tabix-reader/src/lib/spans.js","webpack://[name]/./node_modules/tabix-reader/src/lib/tabix.js","webpack://[name]/./node_modules/tabix-reader/src/main.js","webpack://[name]/./esm/ext/lz-tabix-source.js"],"names":["BMAX","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","BAD","inflate_mask","fixed_tl","fixed_td","cplens","cplext","cpdist","cpdext","ZStream","Inflate","this","was","prototype","inflateInit","w","nowrap","istate","inflate","f","inflateEnd","ret","inflateSync","inflateSetDictionary","dictionary","dictLength","inflateReset","z","total_in","total_out","msg","mode","blocks","reset","free","wbits","InfBlocks","r","b","next_in","avail_in","method","next_in_index","marker","need","adler","proc","index","length","_adler","adler32","set_dictionary","mark","n","p","m","inflateSyncPoint","sync_point","INFBLOCKS_BORDER","checkfn","hufts","Int32Array","MANY","window","Uint8Array","end","left","table","blens","bb","tb","codes","InfCodes","last","bitk","bitb","read","write","check","inftree","InfTree","c","t","k","q","inflate_flush","inflate_trees_fixed","bl","bd","tl","td","init","arrayCopy","i","inflate_trees_bits","j","inflate_trees_dynamic","d","start","next_out_index","avail_out","next_out","tl_index","td_index","lbits","dbits","ltree","ltree_index","dtree","dtree_index","tree","s","tindex","e","inflate_fast","tree_index","lit","get","len","dist","tp","tp_index","ml","md","tp_index_t_3","huft_build","bindex","hp","hn","v","a","g","h","l","mask","xp","y","x","u","result","initWorkArea","nl","nd","vsize","hasSubarray","subarray","src","srcOffset","dest","destOffset","count","arrayCopy_fast","BYTES_PER_ELEMENT","buffer","byteOffset","arrayCopy_slow","set","module","exports","inflateBuffer","afterUncOffset","byteLength","oBlockList","totalSize","obuf","status","newob","push","out","cursor","__webpack_module_cache__","__webpack_require__","moduleId","__webpack_modules__","definition","key","o","Object","defineProperty","enumerable","obj","prop","hasOwnProperty","call","rstr2b64","rstr_sha1","str2rstr_utf8","binb2rstr","binb_sha1","rstr2binb","input","output","triplet","charCodeAt","charAt","String","fromCharCode","Array","olda","oldb","oldc","oldd","olde","bit_rol","safe_add","sha1_ft","sha1_kt","lsw","num","cnt","Observed","value","listeners","Awaited","queue","addListener","addListenerAndFire","removeListener","arrayIndexOf","splice","provide","undefined","res","await","blob","URLFetchable","url","opts","trim","replace","slice","webkitSlice","salted","fetch","callback","reader","FileReader","onloadend","ev","bstringToBuffer","readAsBinaryString","FileReaderSync","readAsArrayBuffer","ns","ne","seed","isSafari","navigator","userAgent","indexOf","ba","fetchAsText","thisB","getURL","then","req","XMLHttpRequest","salt","Date","now","open","setRequestHeader","onreadystatechange","readyState","responseText","credentials","withCredentials","send","catch","err","console","log","shallowCopy","resolver","urlOrObj","Promise","resolve","attempt","truncatedLength","timeout","setTimeout","abort","overrideMimeType","responseType","clearTimeout","response","mozResponseArrayBuffer","convertBuffer","ArrayBuffer","Float32Array","readInt","offset","Vob","block","readVob","allowZero","bint","unbgzf","data","lim","Math","min","ptr","xlen","unc","Chunk","minv","maxv","toString","Range","max","_min","_max","_Compound","ranges","sorted","sort","_rangeOrder","merged","current","shift","forEach","range","_ranges","contains","pos","isContiguous","_pushRanges","lower_bound","floor","lb","insertRange","ub","ri","TabixFile","urlReader","dataUrl","indexUrl","reject","tbi","tabix","header","unchead","uncba","nref","format","colSeq","colStart","colEnd","meta","skip","indices","chrToIndex","indexToChr","name","ch","substring","minBlockIndex","ref","blockStart","nbin","nintv","bi","headerMax","install","LocusZoom","BaseLZAdapter","Adapters","add","config","super","parser_func","url_data","Error","parser","url_tbi","_overfetch","overfetch","_reader_promise","options","region_start","region_end","extra_amount","chr","records","map","blocksForRange","refId","intBinsL","beg","list","reg2bins","intBins","leafChunks","otherChunks","bin","nchnk","cs","ce","lowest","minLin","maxLin","prunedOtherChunks","chnk","intChunks","c0","c1","dif","mergedChunks","cur","nc","chrId","chunks","canonicalChr","tramp","readRecords","fetchMin","fetchMax","sink","LINE_LOOP","line","toks","split","fmin","parseInt","fmax","fetchHeader","defaults","metaOnly","skipped","nLines","keys","self","lines","use"],"mappings":";iCAgBA,IAIIA,EAAO,GAiBPC,GAAgB,EAChBC,GAAc,EAEdC,GAAa,EAgBbC,EAAI,GAEJC,EAAe,CAAC,EAAY,EAAY,EAAY,EAAY,GAAY,GAAY,GAAY,IAAY,IAAY,IAAY,KAAY,KAAY,KAAY,KAAY,MAAY,MAAY,OAgBhNC,EAAW,CACX,GAAG,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,GAAI,GAAG,EAAE,IAC/B,GAAG,EAAE,GAAI,EAAE,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,IAC9B,GAAG,EAAE,GAAI,EAAE,EAAE,GAAI,EAAE,EAAE,GAAI,EAAE,EAAE,IAC7B,EAAE,EAAE,EAAG,EAAE,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,IAC5B,GAAG,EAAE,EAAG,EAAE,EAAE,GAAI,EAAE,EAAE,GAAI,EAAE,EAAE,IAC5B,GAAG,EAAE,GAAI,EAAE,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,IAC9B,GAAG,EAAE,GAAI,EAAE,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,IAC9B,EAAE,EAAE,EAAG,EAAE,EAAE,IAAK,EAAE,EAAE,GAAI,EAAE,EAAE,IAC5B,GAAG,EAAE,EAAG,EAAE,EAAE,GAAI,EA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9BoD,EAAK7C,eAAeP,KACrBoD,EAAKpD,GAAO4P,EAAS5P,OAI7B,IAAIiQ,EAAOra,KAIXqa,EAAKtI,KAAKpE,MAAM,EAAG0M,EAAKrE,WAAWlI,OAAM,SAAS0K,GAC9C,IAAKA,EACD,OAAOzK,EAAS,KAAM,gBAI1B,IAFA,IAAIgB,EAAK,IAAI1L,WAAWyO,EAAO0G,EAAMA,EAAKlP,aACtC6I,EAAM,EAAGsH,EAAO,GAAIa,EAAQ,GACzBnI,EAAMpD,EAAG1M,QAAQ,CACpB,IAAImT,EAAKzG,EAAGoD,KACZ,GAAU,IAANqD,EAAU,CACV,KAAKhI,EAAKyM,UAAYR,EAAKnO,WAAW,IAAM+O,EAAKnF,MAC5C1H,EAAK0M,SAAWI,EAAMjY,OAASgY,EAAKlF,MACpC3H,EAAK2M,QAAUG,EAAMjY,OAASmL,EAAK2M,QAKpC,OAAOpM,EAASuM,GAHhBA,EAAM1Q,KAAK6P,GACXA,EAAO,QAKXA,GAAQjO,OAAOC,aAAa+J,GAGpCzH,EAASuM,OExMQ,oBAAdpE,WAGPA,UAAUqE,IAAItE,GAIlB,W","file":"ext/lz-tabix-source.min.js","sourcesContent":["/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n// \n// Javascript ZLib\n// By Thomas Down 2010-2011\n//\n// Based very heavily on portions of jzlib (by ymnk@jcraft.com), who in\n// turn credits Jean-loup Gailly and Mark Adler for the original zlib code.\n//\n// inflate.js: ZLib inflate code\n//\n\n//\n// Shared constants\n//\n\nvar MAX_WBITS=15; // 32K LZ77 window\nvar DEF_WBITS=MAX_WBITS;\nvar MAX_MEM_LEVEL=9;\nvar MANY=1440;\nvar BMAX = 15;\n\n// preset dictionary flag in zlib header\nvar PRESET_DICT=0x20;\n\nvar Z_NO_FLUSH=0;\nvar Z_PARTIAL_FLUSH=1;\nvar Z_SYNC_FLUSH=2;\nvar Z_FULL_FLUSH=3;\nvar Z_FINISH=4;\n\nvar Z_DEFLATED=8;\n\nvar Z_OK=0;\nvar Z_STREAM_END=1;\nvar Z_NEED_DICT=2;\nvar Z_ERRNO=-1;\nvar Z_STREAM_ERROR=-2;\nvar Z_DATA_ERROR=-3;\nvar Z_MEM_ERROR=-4;\nvar Z_BUF_ERROR=-5;\nvar Z_VERSION_ERROR=-6;\n\nvar METHOD=0; // waiting for method byte\nvar FLAG=1; // waiting for flag byte\nvar DICT4=2; // four dictionary check bytes to go\nvar DICT3=3; // three dictionary check bytes to go\nvar DICT2=4; // two dictionary check bytes to go\nvar DICT1=5; // one dictionary check byte to go\nvar DICT0=6; // waiting for inflateSetDictionary\nvar BLOCKS=7; // decompressing blocks\nvar CHECK4=8; // four check bytes to go\nvar CHECK3=9; // three check bytes to go\nvar CHECK2=10; // two check bytes to go\nvar CHECK1=11; // one check byte to go\nvar DONE=12; // finished check, done\nvar BAD=13; // got an error--stay here\n\nvar inflate_mask = [0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff];\n\nvar IB_TYPE=0; // get type bits (3, including end bit)\nvar IB_LENS=1; // get lengths for stored\nvar IB_STORED=2;// processing stored block\nvar IB_TABLE=3; // get table lengths\nvar IB_BTREE=4; // get bit lengths tree for a dynamic block\nvar IB_DTREE=5; // get length, distance trees for a dynamic block\nvar IB_CODES=6; // processing fixed or dynamic block\nvar IB_DRY=7; // output remaining window bytes\nvar IB_DONE=8; // finished last block, done\nvar IB_BAD=9; // ot a data error--stuck here\n\nvar fixed_bl = 9;\nvar fixed_bd = 5;\n\nvar fixed_tl = [\n 96,7,256, 0,8,80, 0,8,16, 84,8,115,\n 82,7,31, 0,8,112, 0,8,48, 0,9,192,\n 80,7,10, 0,8,96, 0,8,32, 0,9,160,\n 0,8,0, 0,8,128, 0,8,64, 0,9,224,\n 80,7,6, 0,8,88, 0,8,24, 0,9,144,\n 83,7,59, 0,8,120, 0,8,56, 0,9,208,\n 81,7,17, 0,8,104, 0,8,40, 0,9,176,\n 0,8,8, 0,8,136, 0,8,72, 0,9,240,\n 80,7,4, 0,8,84, 0,8,20, 85,8,227,\n 83,7,43, 0,8,116, 0,8,52, 0,9,200,\n 81,7,13, 0,8,100, 0,8,36, 0,9,168,\n 0,8,4, 0,8,132, 0,8,68, 0,9,232,\n 80,7,8, 0,8,92, 0,8,28, 0,9,152,\n 84,7,83, 0,8,124, 0,8,60, 0,9,216,\n 82,7,23, 0,8,108, 0,8,44, 0,9,184,\n 0,8,12, 0,8,140, 0,8,76, 0,9,248,\n 80,7,3, 0,8,82, 0,8,18, 85,8,163,\n 83,7,35, 0,8,114, 0,8,50, 0,9,196,\n 81,7,11, 0,8,98, 0,8,34, 0,9,164,\n 0,8,2, 0,8,130, 0,8,66, 0,9,228,\n 80,7,7, 0,8,90, 0,8,26, 0,9,148,\n 84,7,67, 0,8,122, 0,8,58, 0,9,212,\n 82,7,19, 0,8,106, 0,8,42, 0,9,180,\n 0,8,10, 0,8,138, 0,8,74, 0,9,244,\n 80,7,5, 0,8,86, 0,8,22, 192,8,0,\n 83,7,51, 0,8,118, 0,8,54, 0,9,204,\n 81,7,15, 0,8,102, 0,8,38, 0,9,172,\n 0,8,6, 0,8,134, 0,8,70, 0,9,236,\n 80,7,9, 0,8,94, 0,8,30, 0,9,156,\n 84,7,99, 0,8,126, 0,8,62, 0,9,220,\n 82,7,27, 0,8,110, 0,8,46, 0,9,188,\n 0,8,14, 0,8,142, 0,8,78, 0,9,252,\n 96,7,256, 0,8,81, 0,8,17, 85,8,131,\n 82,7,31, 0,8,113, 0,8,49, 0,9,194,\n 80,7,10, 0,8,97, 0,8,33, 0,9,162,\n 0,8,1, 0,8,129, 0,8,65, 0,9,226,\n 80,7,6, 0,8,89, 0,8,25, 0,9,146,\n 83,7,59, 0,8,121, 0,8,57, 0,9,210,\n 81,7,17, 0,8,105, 0,8,41, 0,9,178,\n 0,8,9, 0,8,137, 0,8,73, 0,9,242,\n 80,7,4, 0,8,85, 0,8,21, 80,8,258,\n 83,7,43, 0,8,117, 0,8,53, 0,9,202,\n 81,7,13, 0,8,101, 0,8,37, 0,9,170,\n 0,8,5, 0,8,133, 0,8,69, 0,9,234,\n 80,7,8, 0,8,93, 0,8,29, 0,9,154,\n 84,7,83, 0,8,125, 0,8,61, 0,9,218,\n 82,7,23, 0,8,109, 0,8,45, 0,9,186,\n 0,8,13, 0,8,141, 0,8,77, 0,9,250,\n 80,7,3, 0,8,83, 0,8,19, 85,8,195,\n 83,7,35, 0,8,115, 0,8,51, 0,9,198,\n 81,7,11, 0,8,99, 0,8,35, 0,9,166,\n 0,8,3, 0,8,131, 0,8,67, 0,9,230,\n 80,7,7, 0,8,91, 0,8,27, 0,9,150,\n 84,7,67, 0,8,123, 0,8,59, 0,9,214,\n 82,7,19, 0,8,107, 0,8,43, 0,9,182,\n 0,8,11, 0,8,139, 0,8,75, 0,9,246,\n 80,7,5, 0,8,87, 0,8,23, 192,8,0,\n 83,7,51, 0,8,119, 0,8,55, 0,9,206,\n 81,7,15, 0,8,103, 0,8,39, 0,9,174,\n 0,8,7, 0,8,135, 0,8,71, 0,9,238,\n 80,7,9, 0,8,95, 0,8,31, 0,9,158,\n 84,7,99, 0,8,127, 0,8,63, 0,9,222,\n 82,7,27, 0,8,111, 0,8,47, 0,9,190,\n 0,8,15, 0,8,143, 0,8,79, 0,9,254,\n 96,7,256, 0,8,80, 0,8,16, 84,8,115,\n 82,7,31, 0,8,112, 0,8,48, 0,9,193,\n\n 80,7,10, 0,8,96, 0,8,32, 0,9,161,\n 0,8,0, 0,8,128, 0,8,64, 0,9,225,\n 80,7,6, 0,8,88, 0,8,24, 0,9,145,\n 83,7,59, 0,8,120, 0,8,56, 0,9,209,\n 81,7,17, 0,8,104, 0,8,40, 0,9,177,\n 0,8,8, 0,8,136, 0,8,72, 0,9,241,\n 80,7,4, 0,8,84, 0,8,20, 85,8,227,\n 83,7,43, 0,8,116, 0,8,52, 0,9,201,\n 81,7,13, 0,8,100, 0,8,36, 0,9,169,\n 0,8,4, 0,8,132, 0,8,68, 0,9,233,\n 80,7,8, 0,8,92, 0,8,28, 0,9,153,\n 84,7,83, 0,8,124, 0,8,60, 0,9,217,\n 82,7,23, 0,8,108, 0,8,44, 0,9,185,\n 0,8,12, 0,8,140, 0,8,76, 0,9,249,\n 80,7,3, 0,8,82, 0,8,18, 85,8,163,\n 83,7,35, 0,8,114, 0,8,50, 0,9,197,\n 81,7,11, 0,8,98, 0,8,34, 0,9,165,\n 0,8,2, 0,8,130, 0,8,66, 0,9,229,\n 80,7,7, 0,8,90, 0,8,26, 0,9,149,\n 84,7,67, 0,8,122, 0,8,58, 0,9,213,\n 82,7,19, 0,8,106, 0,8,42, 0,9,181,\n 0,8,10, 0,8,138, 0,8,74, 0,9,245,\n 80,7,5, 0,8,86, 0,8,22, 192,8,0,\n 83,7,51, 0,8,118, 0,8,54, 0,9,205,\n 81,7,15, 0,8,102, 0,8,38, 0,9,173,\n 0,8,6, 0,8,134, 0,8,70, 0,9,237,\n 80,7,9, 0,8,94, 0,8,30, 0,9,157,\n 84,7,99, 0,8,126, 0,8,62, 0,9,221,\n 82,7,27, 0,8,110, 0,8,46, 0,9,189,\n 0,8,14, 0,8,142, 0,8,78, 0,9,253,\n 96,7,256, 0,8,81, 0,8,17, 85,8,131,\n 82,7,31, 0,8,113, 0,8,49, 0,9,195,\n 80,7,10, 0,8,97, 0,8,33, 0,9,163,\n 0,8,1, 0,8,129, 0,8,65, 0,9,227,\n 80,7,6, 0,8,89, 0,8,25, 0,9,147,\n 83,7,59, 0,8,121, 0,8,57, 0,9,211,\n 81,7,17, 0,8,105, 0,8,41, 0,9,179,\n 0,8,9, 0,8,137, 0,8,73, 0,9,243,\n 80,7,4, 0,8,85, 0,8,21, 80,8,258,\n 83,7,43, 0,8,117, 0,8,53, 0,9,203,\n 81,7,13, 0,8,101, 0,8,37, 0,9,171,\n 0,8,5, 0,8,133, 0,8,69, 0,9,235,\n 80,7,8, 0,8,93, 0,8,29, 0,9,155,\n 84,7,83, 0,8,125, 0,8,61, 0,9,219,\n 82,7,23, 0,8,109, 0,8,45, 0,9,187,\n 0,8,13, 0,8,141, 0,8,77, 0,9,251,\n 80,7,3, 0,8,83, 0,8,19, 85,8,195,\n 83,7,35, 0,8,115, 0,8,51, 0,9,199,\n 81,7,11, 0,8,99, 0,8,35, 0,9,167,\n 0,8,3, 0,8,131, 0,8,67, 0,9,231,\n 80,7,7, 0,8,91, 0,8,27, 0,9,151,\n 84,7,67, 0,8,123, 0,8,59, 0,9,215,\n 82,7,19, 0,8,107, 0,8,43, 0,9,183,\n 0,8,11, 0,8,139, 0,8,75, 0,9,247,\n 80,7,5, 0,8,87, 0,8,23, 192,8,0,\n 83,7,51, 0,8,119, 0,8,55, 0,9,207,\n 81,7,15, 0,8,103, 0,8,39, 0,9,175,\n 0,8,7, 0,8,135, 0,8,71, 0,9,239,\n 80,7,9, 0,8,95, 0,8,31, 0,9,159,\n 84,7,99, 0,8,127, 0,8,63, 0,9,223,\n 82,7,27, 0,8,111, 0,8,47, 0,9,191,\n 0,8,15, 0,8,143, 0,8,79, 0,9,255\n];\nvar fixed_td = [\n 80,5,1, 87,5,257, 83,5,17, 91,5,4097,\n 81,5,5, 89,5,1025, 85,5,65, 93,5,16385,\n 80,5,3, 88,5,513, 84,5,33, 92,5,8193,\n 82,5,9, 90,5,2049, 86,5,129, 192,5,24577,\n 80,5,2, 87,5,385, 83,5,25, 91,5,6145,\n 81,5,7, 89,5,1537, 85,5,97, 93,5,24577,\n 80,5,4, 88,5,769, 84,5,49, 92,5,12289,\n 82,5,13, 90,5,3073, 86,5,193, 192,5,24577\n];\n\n // Tables for deflate from PKZIP's appnote.txt.\n var cplens = [ // Copy lengths for literal codes 257..285\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n ];\n\n // see note #13 above about 258\n var cplext = [ // Extra bits for literal codes 257..285\n 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,\n 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid\n ];\n\n var cpdist = [ // Copy offsets for distance codes 0..29\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577\n ];\n\n var cpdext = [ // Extra bits for distance codes\n 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,\n 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,\n 12, 12, 13, 13];\n\n//\n// ZStream.java\n//\n\nfunction ZStream() {\n}\n\n\nZStream.prototype.inflateInit = function(w, nowrap) {\n if (!w) {\n\tw = DEF_WBITS;\n }\n if (nowrap) {\n\tnowrap = false;\n }\n this.istate = new Inflate();\n return this.istate.inflateInit(this, nowrap?-w:w);\n}\n\nZStream.prototype.inflate = function(f) {\n if(this.istate==null) return Z_STREAM_ERROR;\n return this.istate.inflate(this, f);\n}\n\nZStream.prototype.inflateEnd = function(){\n if(this.istate==null) return Z_STREAM_ERROR;\n var ret=istate.inflateEnd(this);\n this.istate = null;\n return ret;\n}\nZStream.prototype.inflateSync = function(){\n // if(istate == null) return Z_STREAM_ERROR;\n return istate.inflateSync(this);\n}\nZStream.prototype.inflateSetDictionary = function(dictionary, dictLength){\n // if(istate == null) return Z_STREAM_ERROR;\n return istate.inflateSetDictionary(this, dictionary, dictLength);\n}\n\n/*\n\n public int deflateInit(int level){\n return deflateInit(level, MAX_WBITS);\n }\n public int deflateInit(int level, boolean nowrap){\n return deflateInit(level, MAX_WBITS, nowrap);\n }\n public int deflateInit(int level, int bits){\n return deflateInit(level, bits, false);\n }\n public int deflateInit(int level, int bits, boolean nowrap){\n dstate=new Deflate();\n return dstate.deflateInit(this, level, nowrap?-bits:bits);\n }\n public int deflate(int flush){\n if(dstate==null){\n return Z_STREAM_ERROR;\n }\n return dstate.deflate(this, flush);\n }\n public int deflateEnd(){\n if(dstate==null) return Z_STREAM_ERROR;\n int ret=dstate.deflateEnd();\n dstate=null;\n return ret;\n }\n public int deflateParams(int level, int strategy){\n if(dstate==null) return Z_STREAM_ERROR;\n return dstate.deflateParams(this, level, strategy);\n }\n public int deflateSetDictionary (byte[] dictionary, int dictLength){\n if(dstate == null)\n return Z_STREAM_ERROR;\n return dstate.deflateSetDictionary(this, dictionary, dictLength);\n }\n\n*/\n\n/*\n // Flush as much pending output as possible. All deflate() output goes\n // through this function so some applications may wish to modify it\n // to avoid allocating a large strm->next_out buffer and copying into it.\n // (See also read_buf()).\n void flush_pending(){\n int len=dstate.pending;\n\n if(len>avail_out) len=avail_out;\n if(len==0) return;\n\n if(dstate.pending_buf.length<=dstate.pending_out ||\n next_out.length<=next_out_index ||\n dstate.pending_buf.length<(dstate.pending_out+len) ||\n next_out.length<(next_out_index+len)){\n System.out.println(dstate.pending_buf.length+\", \"+dstate.pending_out+\n\t\t\t \", \"+next_out.length+\", \"+next_out_index+\", \"+len);\n System.out.println(\"avail_out=\"+avail_out);\n }\n\n System.arraycopy(dstate.pending_buf, dstate.pending_out,\n\t\t next_out, next_out_index, len);\n\n next_out_index+=len;\n dstate.pending_out+=len;\n total_out+=len;\n avail_out-=len;\n dstate.pending-=len;\n if(dstate.pending==0){\n dstate.pending_out=0;\n }\n }\n\n // Read a new buffer from the current input stream, update the adler32\n // and total number of bytes read. All deflate() input goes through\n // this function so some applications may wish to modify it to avoid\n // allocating a large strm->next_in buffer and copying from it.\n // (See also flush_pending()).\n int read_buf(byte[] buf, int start, int size) {\n int len=avail_in;\n\n if(len>size) len=size;\n if(len==0) return 0;\n\n avail_in-=len;\n\n if(dstate.noheader==0) {\n adler=_adler.adler32(adler, next_in, next_in_index, len);\n }\n System.arraycopy(next_in, next_in_index, buf, start, len);\n next_in_index += len;\n total_in += len;\n return len;\n }\n\n public void free(){\n next_in=null;\n next_out=null;\n msg=null;\n _adler=null;\n }\n}\n*/\n\n\n//\n// Inflate.java\n//\n\nfunction Inflate() {\n this.was = [0];\n}\n\nInflate.prototype.inflateReset = function(z) {\n if(z == null || z.istate == null) return Z_STREAM_ERROR;\n \n z.total_in = z.total_out = 0;\n z.msg = null;\n z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD;\n z.istate.blocks.reset(z, null);\n return Z_OK;\n}\n\nInflate.prototype.inflateEnd = function(z){\n if(this.blocks != null)\n this.blocks.free(z);\n this.blocks=null;\n return Z_OK;\n}\n\nInflate.prototype.inflateInit = function(z, w){\n z.msg = null;\n this.blocks = null;\n\n // handle undocumented nowrap option (no zlib header or check)\n nowrap = 0;\n if(w < 0){\n w = - w;\n nowrap = 1;\n }\n\n // set window size\n if(w<8 ||w>15){\n this.inflateEnd(z);\n return Z_STREAM_ERROR;\n }\n this.wbits=w;\n\n z.istate.blocks=new InfBlocks(z, \n\t\t\t\t z.istate.nowrap!=0 ? null : this,\n\t\t\t\t 1<>4)+8>z.istate.wbits){\n z.istate.mode = BAD;\n z.msg=\"invalid window size\";\n z.istate.marker = 5; // can't try inflateSync\n break;\n }\n z.istate.mode=FLAG;\n case FLAG:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n b = (z.next_in[z.next_in_index++])&0xff;\n\n if((((z.istate.method << 8)+b) % 31)!=0){\n z.istate.mode = BAD;\n z.msg = \"incorrect header check\";\n z.istate.marker = 5; // can't try inflateSync\n break;\n }\n\n if((b&PRESET_DICT)==0){\n z.istate.mode = BLOCKS;\n break;\n }\n z.istate.mode = DICT4;\n case DICT4:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000;\n z.istate.mode=DICT3;\n case DICT3:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000;\n z.istate.mode=DICT2;\n case DICT2:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00;\n z.istate.mode=DICT1;\n case DICT1:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need += (z.next_in[z.next_in_index++]&0xff);\n z.adler = z.istate.need;\n z.istate.mode = DICT0;\n return Z_NEED_DICT;\n case DICT0:\n z.istate.mode = BAD;\n z.msg = \"need dictionary\";\n z.istate.marker = 0; // can try inflateSync\n return Z_STREAM_ERROR;\n case BLOCKS:\n\n r = z.istate.blocks.proc(z, r);\n if(r == Z_DATA_ERROR){\n z.istate.mode = BAD;\n z.istate.marker = 0; // can try inflateSync\n break;\n }\n if(r == Z_OK){\n r = f;\n }\n if(r != Z_STREAM_END){\n return r;\n }\n r = f;\n z.istate.blocks.reset(z, z.istate.was);\n if(z.istate.nowrap!=0){\n z.istate.mode=DONE;\n break;\n }\n z.istate.mode=CHECK4;\n case CHECK4:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000;\n z.istate.mode=CHECK3;\n case CHECK3:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000;\n z.istate.mode = CHECK2;\n case CHECK2:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00;\n z.istate.mode = CHECK1;\n case CHECK1:\n\n if(z.avail_in==0)return r;r=f;\n\n z.avail_in--; z.total_in++;\n z.istate.need+=(z.next_in[z.next_in_index++]&0xff);\n\n if(((z.istate.was[0])) != ((z.istate.need))){\n z.istate.mode = BAD;\n z.msg = \"incorrect data check\";\n z.istate.marker = 5; // can't try inflateSync\n break;\n }\n\n z.istate.mode = DONE;\n case DONE:\n return Z_STREAM_END;\n case BAD:\n return Z_DATA_ERROR;\n default:\n return Z_STREAM_ERROR;\n }\n }\n }\n\n\nInflate.prototype.inflateSetDictionary = function(z, dictionary, dictLength) {\n var index=0;\n var length = dictLength;\n if(z==null || z.istate == null|| z.istate.mode != DICT0)\n return Z_STREAM_ERROR;\n\n if(z._adler.adler32(1, dictionary, 0, dictLength)!=z.adler){\n return Z_DATA_ERROR;\n }\n\n z.adler = z._adler.adler32(0, null, 0, 0);\n\n if(length >= (1<>> 1){\n case 0: // stored \n {b>>>=(3);k-=(3);}\n t = k & 7; // go to byte boundary\n\n {b>>>=(t);k-=(t);}\n this.mode = IB_LENS; // get length of stored block\n break;\n case 1: // fixed\n {\n var bl=new Int32Array(1);\n\t var bd=new Int32Array(1);\n var tl=[];\n\t var td=[];\n\n\t inflate_trees_fixed(bl, bd, tl, td, z);\n this.codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);\n }\n\n {b>>>=(3);k-=(3);}\n\n this.mode = IB_CODES;\n break;\n case 2: // dynamic\n\n {b>>>=(3);k-=(3);}\n\n this.mode = IB_TABLE;\n break;\n case 3: // illegal\n\n {b>>>=(3);k-=(3);}\n this.mode = BAD;\n z.msg = \"invalid block type\";\n r = Z_DATA_ERROR;\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t}\n\tbreak;\n case IB_LENS:\n\twhile(k<(32)){\n\t if(n!=0){\n\t r=Z_OK;\n\t }\n\t else{\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;\n\t z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t };\n\t n--;\n\t b|=(z.next_in[p++]&0xff)<>> 16) & 0xffff) != (b & 0xffff)){\n\t this.mode = BAD;\n\t z.msg = \"invalid stored block lengths\";\n\t r = Z_DATA_ERROR;\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t}\n\tthis.left = (b & 0xffff);\n\tb = k = 0; // dump bits\n\tthis.mode = this.left!=0 ? IB_STORED : (this.last!=0 ? IB_DRY : IB_TYPE);\n\tbreak;\n case IB_STORED:\n\tif (n == 0){\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t write=q;\n\t return this.inflate_flush(z,r);\n\t}\n\n\tif(m==0){\n\t if(q==end&&read!=0){\n\t q=0; m=(qn) t = n;\n\tif(t>m) t = m;\n\tarrayCopy(z.next_in, p, this.window, q, t);\n\tp += t; n -= t;\n\tq += t; m -= t;\n\tif ((this.left -= t) != 0)\n\t break;\n\tthis.mode = (this.last != 0 ? IB_DRY : IB_TYPE);\n\tbreak;\n case IB_TABLE:\n\n\twhile(k<(14)){\n\t if(n!=0){\n\t r=Z_OK;\n\t }\n\t else{\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;\n\t z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t };\n\t n--;\n\t b|=(z.next_in[p++]&0xff)< 29 || ((t >> 5) & 0x1f) > 29)\n\t {\n\t this.mode = IB_BAD;\n\t z.msg = \"too many length or distance symbols\";\n\t r = Z_DATA_ERROR;\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t }\n\tt = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);\n\tif(this.blens==null || this.blens.length>>=(14);k-=(14);}\n\n\tthis.index = 0;\n\tmode = IB_BTREE;\n case IB_BTREE:\n\twhile (this.index < 4 + (this.table >>> 10)){\n\t while(k<(3)){\n\t if(n!=0){\n\t r=Z_OK;\n\t }\n\t else{\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;\n\t z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t };\n\t n--;\n\t b|=(z.next_in[p++]&0xff)<>>=(3);k-=(3);}\n\t}\n\n\twhile(this.index < 19){\n\t this.blens[INFBLOCKS_BORDER[this.index++]] = 0;\n\t}\n\n\tthis.bb[0] = 7;\n\tt = this.inftree.inflate_trees_bits(this.blens, this.bb, this.tb, this.hufts, z);\n\tif (t != Z_OK){\n\t r = t;\n\t if (r == Z_DATA_ERROR){\n\t this.blens=null;\n\t this.mode = IB_BAD;\n\t }\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t write=q;\n\t return this.inflate_flush(z,r);\n\t}\n\n\tthis.index = 0;\n\tthis.mode = IB_DTREE;\n case IB_DTREE:\n\twhile (true){\n\t t = this.table;\n\t if(!(this.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){\n\t break;\n\t }\n\n\t var h; //int[]\n\t var i, j, c;\n\n\t t = this.bb[0];\n\n\t while(k<(t)){\n\t if(n!=0){\n\t r=Z_OK;\n\t }\n\t else{\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;\n\t z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t };\n\t n--;\n\t b|=(z.next_in[p++]&0xff)<>>=(t);k-=(t);\n\t this.blens[this.index++] = c;\n\t }\n\t else { // c == 16..18\n\t i = c == 18 ? 7 : c - 14;\n\t j = c == 18 ? 11 : 3;\n\n\t while(k<(t+i)){\n\t if(n!=0){\n\t\tr=Z_OK;\n\t }\n\t else{\n\t\tthis.bitb=b; this.bitk=k; \n\t\tz.avail_in=n;\n\t\tz.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t\tthis.write=q;\n\t\treturn this.inflate_flush(z,r);\n\t };\n\t n--;\n\t b|=(z.next_in[p++]&0xff)<>>=(t);k-=(t);\n\n\t j += (b & inflate_mask[i]);\n\n\t b>>>=(i);k-=(i);\n\n\t i = this.index;\n\t t = this.table;\n\t if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||\n\t\t(c == 16 && i < 1)){\n\t this.blens=null;\n\t this.mode = IB_BAD;\n\t z.msg = \"invalid bit length repeat\";\n\t r = Z_DATA_ERROR;\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t }\n\n\t c = c == 16 ? this.blens[i-1] : 0;\n\t do{\n\t this.blens[i++] = c;\n\t }\n\t while (--j!=0);\n\t this.index = i;\n\t }\n\t}\n\n\tthis.tb[0]=-1;\n\t{\n\t var bl=new Int32Array(1);\n\t var bd=new Int32Array(1);\n\t var tl=new Int32Array(1);\n\t var td=new Int32Array(1);\n\t bl[0] = 9; // must be <= 9 for lookahead assumptions\n\t bd[0] = 6; // must be <= 9 for lookahead assumptions\n\n\t t = this.table;\n\t t = this.inftree.inflate_trees_dynamic(257 + (t & 0x1f), \n\t\t\t\t\t 1 + ((t >> 5) & 0x1f),\n\t\t\t\t\t this.blens, bl, bd, tl, td, this.hufts, z);\n\n\t if (t != Z_OK){\n\t if (t == Z_DATA_ERROR){\n\t this.blens=null;\n\t this.mode = BAD;\n\t }\n\t r = t;\n\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z,r);\n\t }\n\t this.codes.init(bl[0], bd[0], this.hufts, tl[0], this.hufts, td[0], z);\n\t}\n\tthis.mode = IB_CODES;\n case IB_CODES:\n\tthis.bitb=b; this.bitk=k;\n\tz.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\tthis.write=q;\n\n\tif ((r = this.codes.proc(this, z, r)) != Z_STREAM_END){\n\t return this.inflate_flush(z, r);\n\t}\n\tr = Z_OK;\n\tthis.codes.free(z);\n\n\tp=z.next_in_index; n=z.avail_in;b=this.bitb;k=this.bitk;\n\tq=this.write;m = (q < this.read ? this.read-q-1 : this.end-q);\n\n\tif (this.last==0){\n\t this.mode = IB_TYPE;\n\t break;\n\t}\n\tthis.mode = IB_DRY;\n case IB_DRY:\n\tthis.write=q; \n\tr = this.inflate_flush(z, r); \n\tq=this.write; m = (q < this.read ? this.read-q-1 : this.end-q);\n\tif (this.read != this.write){\n\t this.bitb=b; this.bitk=k; \n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t this.write=q;\n\t return this.inflate_flush(z, r);\n\t}\n\tmode = DONE;\n case IB_DONE:\n\tr = Z_STREAM_END;\n\n\tthis.bitb=b; this.bitk=k; \n\tz.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\tthis.write=q;\n\treturn this.inflate_flush(z, r);\n case IB_BAD:\n\tr = Z_DATA_ERROR;\n\n\tthis.bitb=b; this.bitk=k; \n\tz.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\tthis.write=q;\n\treturn this.inflate_flush(z, r);\n\n default:\n\tr = Z_STREAM_ERROR;\n\n\tthis.bitb=b; this.bitk=k; \n\tz.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\tthis.write=q;\n\treturn this.inflate_flush(z, r);\n }\n }\n }\n\nInfBlocks.prototype.free = function(z){\n this.reset(z, null);\n this.window=null;\n this.hufts=null;\n}\n\nInfBlocks.prototype.set_dictionary = function(d, start, n){\n arrayCopy(d, start, window, 0, n);\n this.read = this.write = n;\n}\n\n // Returns true if inflate is currently at the end of a block generated\n // by Z_SYNC_FLUSH or Z_FULL_FLUSH. \nInfBlocks.prototype.sync_point = function(){\n return this.mode == IB_LENS;\n}\n\n // copy as much as possible from the sliding window to the output area\nInfBlocks.prototype.inflate_flush = function(z, r){\n var n;\n var p;\n var q;\n\n // local copies of source and destination pointers\n p = z.next_out_index;\n q = this.read;\n\n // compute number of bytes to copy as far as end of window\n n = ((q <= this.write ? this.write : this.end) - q);\n if (n > z.avail_out) n = z.avail_out;\n if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;\n\n // update counters\n z.avail_out -= n;\n z.total_out += n;\n\n // update check information\n if(this.checkfn != null)\n z.adler=this.check=z._adler.adler32(this.check, this.window, q, n);\n\n // copy as far as end of window\n arrayCopy(this.window, q, z.next_out, p, n);\n p += n;\n q += n;\n\n // see if more to copy at beginning of window\n if (q == this.end){\n // wrap pointers\n q = 0;\n if (this.write == this.end)\n this.write = 0;\n\n // compute bytes to copy\n n = this.write - q;\n if (n > z.avail_out) n = z.avail_out;\n if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;\n\n // update counters\n z.avail_out -= n;\n z.total_out += n;\n\n // update check information\n if(this.checkfn != null)\n\tz.adler=this.check=z._adler.adler32(this.check, this.window, q, n);\n\n // copy\n arrayCopy(this.window, q, z.next_out, p, n);\n p += n;\n q += n;\n }\n\n // update pointers\n z.next_out_index = p;\n this.read = q;\n\n // done\n return r;\n }\n\n//\n// InfCodes.java\n//\n\nvar IC_START=0; // x: set up for LEN\nvar IC_LEN=1; // i: get length/literal/eob next\nvar IC_LENEXT=2; // i: getting length extra (have base)\nvar IC_DIST=3; // i: get distance next\nvar IC_DISTEXT=4;// i: getting distance extra\nvar IC_COPY=5; // o: copying bytes in window, waiting for space\nvar IC_LIT=6; // o: got literal, waiting for output space\nvar IC_WASH=7; // o: got eob, possibly still output waiting\nvar IC_END=8; // x: got eob and all data flushed\nvar IC_BADCODE=9;// x: got error\n\nfunction InfCodes() {\n}\n\nInfCodes.prototype.init = function(bl, bd, tl, tl_index, td, td_index, z) {\n this.mode=IC_START;\n this.lbits=bl;\n this.dbits=bd;\n this.ltree=tl;\n this.ltree_index=tl_index;\n this.dtree = td;\n this.dtree_index=td_index;\n this.tree=null;\n}\n\nInfCodes.prototype.proc = function(s, z, r){ \n var j; // temporary storage\n var t; // temporary pointer (int[])\n var tindex; // temporary pointer\n var e; // extra bits or operation\n var b=0; // bit buffer\n var k=0; // bits in bit buffer\n var p=0; // input data pointer\n var n; // bytes available there\n var q; // output window write pointer\n var m; // bytes to end of window or read pointer\n var f; // pointer to copy strings from\n\n // copy input/output information to locals (UPDATE macro restores)\n p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;\n q=s.write;m=q= 258 && n >= 10){\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\t r = this.inflate_fast(this.lbits, this.dbits, \n\t\t\t this.ltree, this.ltree_index, \n\t\t\t this.dtree, this.dtree_index,\n\t\t\t s, z);\n\n\t p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;\n\t q=s.write;m=q>>=(this.tree[tindex+1]);\n\tk-=(this.tree[tindex+1]);\n\n\te=this.tree[tindex];\n\n\tif(e == 0){ // literal\n\t this.lit = this.tree[tindex+2];\n\t this.mode = IC_LIT;\n\t break;\n\t}\n\tif((e & 16)!=0 ){ // length\n\t this.get = e & 15;\n\t this.len = this.tree[tindex+2];\n\t this.mode = IC_LENEXT;\n\t break;\n\t}\n\tif ((e & 64) == 0){ // next table\n\t this.need = e;\n\t this.tree_index = tindex/3 + this.tree[tindex+2];\n\t break;\n\t}\n\tif ((e & 32)!=0){ // end of block\n\t this.mode = IC_WASH;\n\t break;\n\t}\n\tthis.mode = IC_BADCODE; // invalid code\n\tz.msg = \"invalid literal/length code\";\n\tr = Z_DATA_ERROR;\n\n\ts.bitb=b;s.bitk=k;\n\tz.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\ts.write=q;\n\treturn s.inflate_flush(z,r);\n\n case IC_LENEXT: // i: getting length extra (have base)\n\tj = this.get;\n\n\twhile(k<(j)){\n\t if(n!=0)r=Z_OK;\n\t else{\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\t return s.inflate_flush(z,r);\n\t }\n\t n--; b|=(z.next_in[p++]&0xff)<>=j;\n\tk-=j;\n\n\tthis.need = this.dbits;\n\tthis.tree = this.dtree;\n\tthis.tree_index = this.dtree_index;\n\tthis.mode = IC_DIST;\n case IC_DIST: // i: get distance next\n\tj = this.need;\n\n\twhile(k<(j)){\n\t if(n!=0)r=Z_OK;\n\t else{\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\t return s.inflate_flush(z,r);\n\t }\n\t n--; b|=(z.next_in[p++]&0xff)<>=this.tree[tindex+1];\n\tk-=this.tree[tindex+1];\n\n\te = (this.tree[tindex]);\n\tif((e & 16)!=0){ // distance\n\t this.get = e & 15;\n\t this.dist = this.tree[tindex+2];\n\t this.mode = IC_DISTEXT;\n\t break;\n\t}\n\tif ((e & 64) == 0){ // next table\n\t this.need = e;\n\t this.tree_index = tindex/3 + this.tree[tindex+2];\n\t break;\n\t}\n\tthis.mode = IC_BADCODE; // invalid code\n\tz.msg = \"invalid distance code\";\n\tr = Z_DATA_ERROR;\n\n\ts.bitb=b;s.bitk=k;\n\tz.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\ts.write=q;\n\treturn s.inflate_flush(z,r);\n\n case IC_DISTEXT: // i: getting distance extra\n\tj = this.get;\n\n\twhile(k<(j)){\n\t if(n!=0)r=Z_OK;\n\t else{\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\t return s.inflate_flush(z,r);\n\t }\n\t n--; b|=(z.next_in[p++]&0xff)<>=j;\n\tk-=j;\n\n\tthis.mode = IC_COPY;\n case IC_COPY: // o: copying bytes in window, waiting for space\n f = q - this.dist;\n while(f < 0){ // modulo window size-\"while\" instead\n f += s.end; // of \"if\" handles invalid distances\n\t}\n\twhile (this.len!=0){\n\n\t if(m==0){\n\t if(q==s.end&&s.read!=0){q=0;m=q 7){ // return unused byte, if any\n\t k -= 8;\n\t n++;\n\t p--; // can always return one\n\t}\n\n\ts.write=q; r=s.inflate_flush(z,r);\n\tq=s.write;m=q= 258 && n >= 10\n // get literal/length code\n while(k<(20)){ // max bits for literal/length code\n\tn--;\n\tb|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);\n\n\ts.window[q++] = tp[tp_index_t_3+2];\n\tm--;\n\tcontinue;\n }\n do {\n\n\tb>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);\n\n\tif((e&16)!=0){\n\t e &= 15;\n\t c = tp[tp_index_t_3+2] + (b & inflate_mask[e]);\n\n\t b>>=e; k-=e;\n\n\t // decode distance base of block to copy\n\t while(k<(15)){ // max bits for distance code\n\t n--;\n\t b|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);\n\n\t if((e&16)!=0){\n\t // get extra bits to add to distance base\n\t e &= 15;\n\t while(k<(e)){ // get extra bits (up to 13)\n\t\tn--;\n\t\tb|=(z.next_in[p++]&0xff)<>=(e); k-=(e);\n\n\t // do the copy\n\t m -= c;\n\t if (q >= d){ // offset before dest\n\t\t// just copy\n\t\tr=q-d;\n\t\tif(q-r>0 && 2>(q-r)){ \n\t\t s.window[q++]=s.window[r++]; // minimum count is three,\n\t\t s.window[q++]=s.window[r++]; // so unroll loop a little\n\t\t c-=2;\n\t\t}\n\t\telse{\n\t\t s.window[q++]=s.window[r++]; // minimum count is three,\n\t\t s.window[q++]=s.window[r++]; // so unroll loop a little\n\t\t c-=2;\n\t\t}\n\t }\n\t else{ // else offset after destination\n r=q-d;\n do{\n r+=s.end; // force pointer in window\n }while(r<0); // covers invalid distances\n\t\te=s.end-r;\n\t\tif(c>e){ // if source crosses,\n\t\t c-=e; // wrapped copy\n\t\t if(q-r>0 && e>(q-r)){ \n\t\t do{s.window[q++] = s.window[r++];}\n\t\t while(--e!=0);\n\t\t }\n\t\t else{\n\t\t arrayCopy(s.window, r, s.window, q, e);\n\t\t q+=e; r+=e; e=0;\n\t\t }\n\t\t r = 0; // copy rest from start of window\n\t\t}\n\n\t }\n\n\t // copy all or what's left\n do{s.window[q++] = s.window[r++];}\n\t\twhile(--c!=0);\n\t break;\n\t }\n\t else if((e&64)==0){\n\t t+=tp[tp_index_t_3+2];\n\t t+=(b&inflate_mask[e]);\n\t tp_index_t_3=(tp_index+t)*3;\n\t e=tp[tp_index_t_3];\n\t }\n\t else{\n\t z.msg = \"invalid distance code\";\n\n\t c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\n\t return Z_DATA_ERROR;\n\t }\n\t }\n\t while(true);\n\t break;\n\t}\n\n\tif((e&64)==0){\n\t t+=tp[tp_index_t_3+2];\n\t t+=(b&inflate_mask[e]);\n\t tp_index_t_3=(tp_index+t)*3;\n\t if((e=tp[tp_index_t_3])==0){\n\n\t b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);\n\n\t s.window[q++]=tp[tp_index_t_3+2];\n\t m--;\n\t break;\n\t }\n\t}\n\telse if((e&32)!=0){\n\n\t c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;\n \n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\n\t return Z_STREAM_END;\n\t}\n\telse{\n\t z.msg=\"invalid literal/length code\";\n\n\t c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;\n\n\t s.bitb=b;s.bitk=k;\n\t z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n\t s.write=q;\n\n\t return Z_DATA_ERROR;\n\t}\n } \n while(true);\n } \n while(m>=258 && n>= 10);\n\n // not enough input or output--restore pointers and return\n c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;\n\n s.bitb=b;s.bitk=k;\n z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;\n s.write=q;\n\n return Z_OK;\n}\n\n//\n// InfTree.java\n//\n\nfunction InfTree() {\n}\n\nInfTree.prototype.huft_build = function(b, bindex, n, s, d, e, t, m, hp, hn, v) {\n\n // Given a list of code lengths and a maximum table size, make a set of\n // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR\n // if the given code set is incomplete (the tables are still built in this\n // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of\n // lengths), or Z_MEM_ERROR if not enough memory.\n\n var a; // counter for codes of length k\n var f; // i repeats in table every f entries\n var g; // maximum code length\n var h; // table level\n var i; // counter, current code\n var j; // counter\n var k; // number of bits in current code\n var l; // bits per table (returned in m)\n var mask; // (1 << w) - 1, to avoid cc -O bug on HP\n var p; // pointer into c[], b[], or v[]\n var q; // points to current table\n var w; // bits before this table == (l * h)\n var xp; // pointer into x\n var y; // number of dummy codes added\n var z; // number of entries in current table\n\n // Generate counts for each bit length\n\n p = 0; i = n;\n do {\n this.c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX\n }while(i!=0);\n\n if(this.c[0] == n){ // null input--all zero length codes\n t[0] = -1;\n m[0] = 0;\n return Z_OK;\n }\n\n // Find minimum and maximum length, bound *m by those\n l = m[0];\n for (j = 1; j <= BMAX; j++)\n if(this.c[j]!=0) break;\n k = j; // minimum code length\n if(l < j){\n l = j;\n }\n for (i = BMAX; i!=0; i--){\n if(this.c[i]!=0) break;\n }\n g = i; // maximum code length\n if(l > i){\n l = i;\n }\n m[0] = l;\n\n // Adjust last length count to fill out codes, if needed\n for (y = 1 << j; j < i; j++, y <<= 1){\n if ((y -= this.c[j]) < 0){\n return Z_DATA_ERROR;\n }\n }\n if ((y -= this.c[i]) < 0){\n return Z_DATA_ERROR;\n }\n this.c[i] += y;\n\n // Generate starting offsets into the value table for each length\n this.x[1] = j = 0;\n p = 1; xp = 2;\n while (--i!=0) { // note that i == g from above\n this.x[xp] = (j += this.c[p]);\n xp++;\n p++;\n }\n\n // Make a table of values in order of bit lengths\n i = 0; p = 0;\n do {\n if ((j = b[bindex+p]) != 0){\n this.v[this.x[j]++] = i;\n }\n p++;\n }\n while (++i < n);\n n = this.x[g]; // set n to length of v\n\n // Generate the Huffman codes and for each, make the table entries\n this.x[0] = i = 0; // first Huffman code is zero\n p = 0; // grab values in bit order\n h = -1; // no tables yet--level -1\n w = -l; // bits decoded == (l * h)\n this.u[0] = 0; // just to keep compilers happy\n q = 0; // ditto\n z = 0; // ditto\n\n // go through the bit lengths (k already is bits in shortest code)\n for (; k <= g; k++){\n a = this.c[k];\n while (a--!=0){\n\t// here i is the Huffman code of length k bits for value *p\n\t// make tables up to required level\n while (k > w + l){\n h++;\n w += l; // previous table always l bits\n\t // compute minimum size table less than or equal to l bits\n z = g - w;\n z = (z > l) ? l : z; // table size upper limit\n if((f=1<<(j=k-w))>a+1){ // try a k-w bit table\n // too few codes for k-w bit table\n f -= a + 1; // deduct codes from patterns left\n xp = k;\n if(j < z){\n while (++j < z){ // try smaller tables up to z bits\n if((f <<= 1) <= this.c[++xp])\n break; // enough codes to use up j bits\n f -= this.c[xp]; // else deduct codes from patterns\n }\n\t }\n }\n z = 1 << j; // table entries for j-bit table\n\n\t // allocate new table\n if (this.hn[0] + z > MANY){ // (note: doesn't matter for fixed)\n return Z_DATA_ERROR; // overflow of MANY\n }\n this.u[h] = q = /*hp+*/ this.hn[0]; // DEBUG\n this.hn[0] += z;\n \n\t // connect to last table, if there is one\n\t if(h!=0){\n this.x[h]=i; // save pattern for backing up\n this.r[0]=j; // bits in this table\n this.r[1]=l; // bits to dump before this table\n j=i>>>(w - l);\n this.r[2] = (q - this.u[h-1] - j); // offset to this table\n arrayCopy(this.r, 0, hp, (this.u[h-1]+j)*3, 3); // connect to last table\n }\n else{\n t[0] = q; // first table is returned result\n\t }\n }\n\n\t// set up table entry in r\n this.r[1] = (k - w);\n if (p >= n){\n this.r[0] = 128 + 64; // out of values--invalid code\n\t}\n else if (v[p] < s){\n this.r[0] = (this.v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block\n this.r[2] = this.v[p++]; // simple code is just the value\n }\n else{\n this.r[0]=(e[this.v[p]-s]+16+64); // non-simple--look up in lists\n this.r[2]=d[this.v[p++] - s];\n }\n\n // fill code-like entries with r\n f=1<<(k-w);\n for (j=i>>>w;j>>= 1){\n i ^= j;\n\t}\n i ^= j;\n\n\t// backup over finished tables\n mask = (1 << w) - 1; // needed on HP, cc -O bug\n while ((i & mask) != this.x[h]){\n h--; // don't need to update q\n w -= l;\n mask = (1 << w) - 1;\n }\n }\n }\n // Return Z_BUF_ERROR if we were given an incomplete table\n return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;\n}\n\nInfTree.prototype.inflate_trees_bits = function(c, bb, tb, hp, z) {\n var result;\n this.initWorkArea(19);\n this.hn[0]=0;\n result = this.huft_build(c, 0, 19, 19, null, null, tb, bb, hp, this.hn, this.v);\n\n if(result == Z_DATA_ERROR){\n z.msg = \"oversubscribed dynamic bit lengths tree\";\n }\n else if(result == Z_BUF_ERROR || bb[0] == 0){\n z.msg = \"incomplete dynamic bit lengths tree\";\n result = Z_DATA_ERROR;\n }\n return result;\n}\n\nInfTree.prototype.inflate_trees_dynamic = function(nl, nd, c, bl, bd, tl, td, hp, z) {\n var result;\n\n // build literal/length tree\n this.initWorkArea(288);\n this.hn[0]=0;\n result = this.huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, this.hn, this.v);\n if (result != Z_OK || bl[0] == 0){\n if(result == Z_DATA_ERROR){\n z.msg = \"oversubscribed literal/length tree\";\n }\n else if (result != Z_MEM_ERROR){\n z.msg = \"incomplete literal/length tree\";\n result = Z_DATA_ERROR;\n }\n return result;\n }\n\n // build distance tree\n this.initWorkArea(288);\n result = this.huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, this.hn, this.v);\n\n if (result != Z_OK || (bd[0] == 0 && nl > 257)){\n if (result == Z_DATA_ERROR){\n z.msg = \"oversubscribed distance tree\";\n }\n else if (result == Z_BUF_ERROR) {\n z.msg = \"incomplete distance tree\";\n result = Z_DATA_ERROR;\n }\n else if (result != Z_MEM_ERROR){\n z.msg = \"empty distance tree with lengths\";\n result = Z_DATA_ERROR;\n }\n return result;\n }\n\n return Z_OK;\n}\n/*\n static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth\n int[] bd, //distance desired/actual bit depth\n int[][] tl,//literal/length tree result\n int[][] td,//distance tree result \n ZStream z //for memory allocation\n\t\t\t\t ){\n\n*/\n\nfunction inflate_trees_fixed(bl, bd, tl, td, z) {\n bl[0]=fixed_bl;\n bd[0]=fixed_bd;\n tl[0]=fixed_tl;\n td[0]=fixed_td;\n return Z_OK;\n}\n\nInfTree.prototype.initWorkArea = function(vsize){\n if(this.hn==null){\n this.hn=new Int32Array(1);\n this.v=new Int32Array(vsize);\n this.c=new Int32Array(BMAX+1);\n this.r=new Int32Array(3);\n this.u=new Int32Array(BMAX);\n this.x=new Int32Array(BMAX+1);\n }\n if(this.v.length 100) {\n arrayCopy_fast(new Uint8Array(src.buffer, src.byteOffset + srcOffset, count), dest, destOffset);\n } else { \n arrayCopy_slow(src, srcOffset, dest, destOffset, count);\n }\n\n}\n\nfunction arrayCopy_slow(src, srcOffset, dest, destOffset, count) {\n\n // dlog('_slow call: srcOffset=' + srcOffset + '; destOffset=' + destOffset + '; count=' + count);\n\n for (var i = 0; i < count; ++i) {\n dest[destOffset + i] = src[srcOffset + i];\n }\n}\n\nfunction arrayCopy_fast(src, dest, destOffset) {\n dest.set(src, destOffset);\n}\n\n\n // largest prime smaller than 65536\nvar ADLER_BASE=65521; \n // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1\nvar ADLER_NMAX=5552;\n\nfunction adler32(adler, /* byte[] */ buf, index, len){\n if(buf == null){ return 1; }\n\n var s1=adler&0xffff;\n var s2=(adler>>16)&0xffff;\n var k;\n\n while(len > 0) {\n k=len=16){\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n s1+=buf[index++]&0xff; s2+=s1;\n k-=16;\n }\n if(k!=0){\n do{\n s1+=buf[index++]&0xff; s2+=s1;\n }\n while(--k!=0);\n }\n s1%=ADLER_BASE;\n s2%=ADLER_BASE;\n }\n return (s2<<16)|s1;\n}\n\n\n\nfunction jszlib_inflate_buffer(buffer, start, length, afterUncOffset) {\n if (!start) {\n buffer = new Uint8Array(buffer);\n } else if (!length) {\n buffer = new Uint8Array(buffer, start, buffer.byteLength - start);\n } else {\n buffer = new Uint8Array(buffer, start, length);\n }\n\n var z = new ZStream();\n z.inflateInit(DEF_WBITS, true);\n z.next_in = buffer;\n z.next_in_index = 0;\n z.avail_in = buffer.length;\n\n var oBlockList = [];\n var totalSize = 0;\n while (true) {\n var obuf = new Uint8Array(32000);\n z.next_out = obuf;\n z.next_out_index = 0;\n z.avail_out = obuf.length;\n var status = z.inflate(Z_NO_FLUSH);\n if (status != Z_OK && status != Z_STREAM_END && status != Z_BUF_ERROR) {\n throw z.msg;\n }\n if (z.avail_out != 0) {\n var newob = new Uint8Array(obuf.length - z.avail_out);\n arrayCopy(obuf, 0, newob, 0, (obuf.length - z.avail_out));\n obuf = newob;\n }\n oBlockList.push(obuf);\n totalSize += obuf.length;\n if (status == Z_STREAM_END || status == Z_BUF_ERROR) {\n break;\n }\n }\n\n if (afterUncOffset) {\n afterUncOffset[0] = (start || 0) + z.next_in_index;\n }\n\n if (oBlockList.length == 1) {\n return oBlockList[0].buffer;\n } else {\n var out = new Uint8Array(totalSize);\n var cursor = 0;\n for (var i = 0; i < oBlockList.length; ++i) {\n var b = oBlockList[i];\n arrayCopy(b, 0, out, cursor, b.length);\n cursor += b.length;\n }\n return out.buffer;\n }\n}\n\nif (typeof(module) !== 'undefined') {\n module.exports = {\n inflateBuffer: jszlib_inflate_buffer,\n arrayCopy: arrayCopy\n };\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\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))","/*\r\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined\r\n * in FIPS 180-1\r\n * Version 2.2 Copyright Paul Johnston 2000 - 2009.\r\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\r\n * Distributed under the BSD License\r\n * See http://pajhome.org.uk/crypt/md5 for details.\r\n */\r\n\r\n/*\r\n * Configurable variables. You may need to tweak these to be compatible with\r\n * the server-side, but the defaults work in most cases.\r\n */\r\nvar hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */\r\nvar b64pad = \"\"; /* base-64 pad character. \"=\" for strict RFC compliance */\r\n\r\n/*\r\n * These are the functions you'll usually want to call\r\n * They take string arguments and return either hex or base-64 encoded strings\r\n */\r\nfunction hex_sha1(s) { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }\r\nfunction b64_sha1(s) { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }\r\nfunction any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }\r\nfunction hex_hmac_sha1(k, d)\r\n { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }\r\nfunction b64_hmac_sha1(k, d)\r\n { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }\r\nfunction any_hmac_sha1(k, d, e)\r\n { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }\r\n\r\n/*\r\n * Perform a simple self-test to see if the VM is working\r\n */\r\nfunction sha1_vm_test()\r\n{\r\n return hex_sha1(\"abc\").toLowerCase() == \"a9993e364706816aba3e25717850c26c9cd0d89d\";\r\n}\r\n\r\n/*\r\n * Calculate the SHA1 of a raw string\r\n */\r\nfunction rstr_sha1(s)\r\n{\r\n return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));\r\n}\r\n\r\n/*\r\n * Calculate the HMAC-SHA1 of a key and some data (raw strings)\r\n */\r\nfunction rstr_hmac_sha1(key, data)\r\n{\r\n var bkey = rstr2binb(key);\r\n if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8);\r\n\r\n var ipad = Array(16), opad = Array(16);\r\n for(var i = 0; i < 16; i++)\r\n {\r\n ipad[i] = bkey[i] ^ 0x36363636;\r\n opad[i] = bkey[i] ^ 0x5C5C5C5C;\r\n }\r\n\r\n var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);\r\n return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));\r\n}\r\n\r\n/*\r\n * Convert a raw string to a hex string\r\n */\r\nfunction rstr2hex(input)\r\n{\r\n // try { hexcase } catch(e) { hexcase=0; }\r\n var hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\r\n var output = \"\";\r\n var x;\r\n for(var i = 0; i < input.length; i++)\r\n {\r\n x = input.charCodeAt(i);\r\n output += hex_tab.charAt((x >>> 4) & 0x0F)\r\n + hex_tab.charAt( x & 0x0F);\r\n }\r\n return output;\r\n}\r\n\r\n/*\r\n * Convert a raw string to a base-64 string\r\n */\r\nfunction rstr2b64(input)\r\n{\r\n // try { b64pad } catch(e) { b64pad=''; }\r\n var tab = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\r\n var output = \"\";\r\n var len = input.length;\r\n for(var i = 0; i < len; i += 3)\r\n {\r\n var triplet = (input.charCodeAt(i) << 16)\r\n | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)\r\n | (i + 2 < len ? input.charCodeAt(i+2) : 0);\r\n for(var j = 0; j < 4; j++)\r\n {\r\n if(i * 8 + j * 6 > input.length * 8) output += b64pad;\r\n else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);\r\n }\r\n }\r\n return output;\r\n}\r\n\r\n/*\r\n * Convert a raw string to an arbitrary string encoding\r\n */\r\nfunction rstr2any(input, encoding)\r\n{\r\n var divisor = encoding.length;\r\n var remainders = Array();\r\n var i, q, x, quotient;\r\n\r\n /* Convert to an array of 16-bit big-endian values, forming the dividend */\r\n var dividend = Array(Math.ceil(input.length / 2));\r\n for(i = 0; i < dividend.length; i++)\r\n {\r\n dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);\r\n }\r\n\r\n /*\r\n * Repeatedly perform a long division. The binary array forms the dividend,\r\n * the length of the encoding is the divisor. Once computed, the quotient\r\n * forms the dividend for the next step. We stop when the dividend is zero.\r\n * All remainders are stored for later use.\r\n */\r\n while(dividend.length > 0)\r\n {\r\n quotient = Array();\r\n x = 0;\r\n for(i = 0; i < dividend.length; i++)\r\n {\r\n x = (x << 16) + dividend[i];\r\n q = Math.floor(x / divisor);\r\n x -= q * divisor;\r\n if(quotient.length > 0 || q > 0)\r\n quotient[quotient.length] = q;\r\n }\r\n remainders[remainders.length] = x;\r\n dividend = quotient;\r\n }\r\n\r\n /* Convert the remainders to the output string */\r\n var output = \"\";\r\n for(i = remainders.length - 1; i >= 0; i--)\r\n output += encoding.charAt(remainders[i]);\r\n\r\n /* Append leading zero equivalents */\r\n var full_length = Math.ceil(input.length * 8 /\r\n (Math.log(encoding.length) / Math.log(2)))\r\n for(i = output.length; i < full_length; i++)\r\n output = encoding[0] + output;\r\n\r\n return output;\r\n}\r\n\r\n/*\r\n * Encode a string as utf-8.\r\n * For efficiency, this assumes the input is valid utf-16.\r\n */\r\nfunction str2rstr_utf8(input)\r\n{\r\n var output = \"\";\r\n var i = -1;\r\n var x, y;\r\n\r\n while(++i < input.length)\r\n {\r\n /* Decode utf-16 surrogate pairs */\r\n x = input.charCodeAt(i);\r\n y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;\r\n if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)\r\n {\r\n x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);\r\n i++;\r\n }\r\n\r\n /* Encode output as utf-8 */\r\n if(x <= 0x7F)\r\n output += String.fromCharCode(x);\r\n else if(x <= 0x7FF)\r\n output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),\r\n 0x80 | ( x & 0x3F));\r\n else if(x <= 0xFFFF)\r\n output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),\r\n 0x80 | ((x >>> 6 ) & 0x3F),\r\n 0x80 | ( x & 0x3F));\r\n else if(x <= 0x1FFFFF)\r\n output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),\r\n 0x80 | ((x >>> 12) & 0x3F),\r\n 0x80 | ((x >>> 6 ) & 0x3F),\r\n 0x80 | ( x & 0x3F));\r\n }\r\n return output;\r\n}\r\n\r\n/*\r\n * Encode a string as utf-16\r\n */\r\nfunction str2rstr_utf16le(input)\r\n{\r\n var output = \"\";\r\n for(var i = 0; i < input.length; i++)\r\n output += String.fromCharCode( input.charCodeAt(i) & 0xFF,\r\n (input.charCodeAt(i) >>> 8) & 0xFF);\r\n return output;\r\n}\r\n\r\nfunction str2rstr_utf16be(input)\r\n{\r\n var output = \"\";\r\n for(var i = 0; i < input.length; i++)\r\n output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,\r\n input.charCodeAt(i) & 0xFF);\r\n return output;\r\n}\r\n\r\n/*\r\n * Convert a raw string to an array of big-endian words\r\n * Characters >255 have their high-byte silently ignored.\r\n */\r\nfunction rstr2binb(input)\r\n{\r\n var output = Array(input.length >> 2);\r\n for(var i = 0; i < output.length; i++)\r\n output[i] = 0;\r\n for(var i = 0; i < input.length * 8; i += 8)\r\n output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);\r\n return output;\r\n}\r\n\r\n/*\r\n * Convert an array of big-endian words to a string\r\n */\r\nfunction binb2rstr(input)\r\n{\r\n var output = \"\";\r\n for(var i = 0; i < input.length * 32; i += 8)\r\n output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);\r\n return output;\r\n}\r\n\r\n/*\r\n * Calculate the SHA-1 of an array of big-endian words, and a bit length\r\n */\r\nfunction binb_sha1(x, len)\r\n{\r\n /* append padding */\r\n x[len >> 5] |= 0x80 << (24 - len % 32);\r\n x[((len + 64 >> 9) << 4) + 15] = len;\r\n\r\n var w = Array(80);\r\n var a = 1732584193;\r\n var b = -271733879;\r\n var c = -1732584194;\r\n var d = 271733878;\r\n var e = -1009589776;\r\n\r\n for(var i = 0; i < x.length; i += 16)\r\n {\r\n var olda = a;\r\n var oldb = b;\r\n var oldc = c;\r\n var oldd = d;\r\n var olde = e;\r\n\r\n for(var j = 0; j < 80; j++)\r\n {\r\n if(j < 16) w[j] = x[i + j];\r\n else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\r\n var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),\r\n safe_add(safe_add(e, w[j]), sha1_kt(j)));\r\n e = d;\r\n d = c;\r\n c = bit_rol(b, 30);\r\n b = a;\r\n a = t;\r\n }\r\n\r\n a = safe_add(a, olda);\r\n b = safe_add(b, oldb);\r\n c = safe_add(c, oldc);\r\n d = safe_add(d, oldd);\r\n e = safe_add(e, olde);\r\n }\r\n return Array(a, b, c, d, e);\r\n\r\n}\r\n\r\n/*\r\n * Perform the appropriate triplet combination function for the current\r\n * iteration\r\n */\r\nfunction sha1_ft(t, b, c, d)\r\n{\r\n if(t < 20) return (b & c) | ((~b) & d);\r\n if(t < 40) return b ^ c ^ d;\r\n if(t < 60) return (b & c) | (b & d) | (c & d);\r\n return b ^ c ^ d;\r\n}\r\n\r\n/*\r\n * Determine the appropriate additive constant for the current iteration\r\n */\r\nfunction sha1_kt(t)\r\n{\r\n return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :\r\n (t < 60) ? -1894007588 : -899497514;\r\n}\r\n\r\n/*\r\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\r\n * to work around bugs in some JS interpreters.\r\n */\r\nfunction safe_add(x, y)\r\n{\r\n var lsw = (x & 0xFFFF) + (y & 0xFFFF);\r\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\r\n return (msw << 16) | (lsw & 0xFFFF);\r\n}\r\n\r\n/*\r\n * Bitwise rotate a 32-bit number to the left.\r\n */\r\nfunction bit_rol(num, cnt)\r\n{\r\n return (num << cnt) | (num >>> (32 - cnt));\r\n}\r\n\r\nexport { b64_sha1, hex_sha1 };\r\n","/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n//\n// Dalliance Genome Explorer\n// (c) Thomas Down 2006-2010\n//\n// utils.js: odds, sods, and ends.\n//\n\nimport {b64_sha1} from './sha1';\n\nvar NUM_REGEXP = new RegExp('[0-9]+');\n\nfunction stringToNumbersArray(str) {\n var nums = new Array();\n var m;\n while (m = NUM_REGEXP.exec(str)) {\n nums.push(m[0]);\n str = str.substring(m.index + (m[0].length));\n }\n return nums;\n}\n\nvar STRICT_NUM_REGEXP = new RegExp('^[0-9]+$');\n\nfunction stringToInt(str) {\n str = str.replace(new RegExp(',', 'g'), '');\n if (!STRICT_NUM_REGEXP.test(str)) {\n return null;\n }\n return str | 0;\n}\n\nfunction pusho(obj, k, v) {\n if (obj[k]) {\n obj[k].push(v);\n } else {\n obj[k] = [v];\n }\n}\n\nfunction pushnewo(obj, k, v) {\n var a = obj[k];\n if (a) {\n for (var i = 0; i < a.length; ++i) { // indexOf requires JS16 :-(.\n if (a[i] == v) {\n return;\n }\n }\n a.push(v);\n } else {\n obj[k] = [v];\n }\n}\n\n\nfunction pick(a, b, c, d) {\n if (a) {\n return a;\n } else if (b) {\n return b;\n } else if (c) {\n return c;\n } else if (d) {\n return d;\n }\n}\n\nfunction arrayEquals(a, b) {\n if (!a || !b || a.length !== b.length)\n return false;\n\n for (var i = 0; i < a.length; ++i) {\n if (a[i] !== b[i])\n return false;\n }\n\n return true;\n}\n\nfunction arrayIndexOf(a, x) {\n if (!a) {\n return -1;\n }\n\n for (var i = 0; i < a.length; ++i) {\n if (a[i] === x) {\n return i;\n }\n }\n return -1;\n}\n\nfunction arrayRemove(a, x) {\n var i = arrayIndexOf(a, x);\n if (i >= 0) {\n a.splice(i, 1);\n return true;\n }\n return false;\n}\n\n//\n// DOM utilities\n//\n\n\nfunction makeElement(tag, children, attribs, styles) {\n var ele = document.createElement(tag);\n if (children) {\n if (!(children instanceof Array)) {\n children = [children];\n }\n for (var i = 0; i < children.length; ++i) {\n var c = children[i];\n if (c) {\n if (typeof c == 'string') {\n c = document.createTextNode(c);\n } else if (typeof c == 'number') {\n c = document.createTextNode('' + c);\n }\n ele.appendChild(c);\n }\n }\n }\n\n if (attribs) {\n for (var l in attribs) {\n try {\n ele[l] = attribs[l];\n } catch (e) {\n console.log('error setting ' + l);\n throw(e);\n }\n }\n }\n if (styles) {\n for (var l in styles) {\n ele.style[l] = styles[l];\n }\n }\n return ele;\n}\n\nfunction makeElementNS(namespace, tag, children, attribs) {\n var ele = document.createElementNS(namespace, tag);\n if (children) {\n if (!(children instanceof Array)) {\n children = [children];\n }\n for (var i = 0; i < children.length; ++i) {\n var c = children[i];\n if (typeof c == 'string') {\n c = document.createTextNode(c);\n }\n ele.appendChild(c);\n }\n }\n\n setAttrs(ele, attribs);\n return ele;\n}\n\nvar attr_name_cache = {};\n\nfunction setAttr(node, key, value) {\n var attr = attr_name_cache[key];\n if (!attr) {\n var _attr = '';\n for (var c = 0; c < key.length; ++c) {\n var cc = key.substring(c, c + 1);\n var lcc = cc.toLowerCase();\n if (lcc != cc) {\n _attr = _attr + '-' + lcc;\n } else {\n _attr = _attr + cc;\n }\n }\n attr_name_cache[key] = _attr;\n attr = _attr;\n }\n node.setAttribute(attr, value);\n}\n\nfunction setAttrs(node, attribs) {\n if (attribs) {\n for (var l in attribs) {\n setAttr(node, l, attribs[l]);\n }\n }\n}\n\n\nfunction removeChildren(node) {\n if (!node || !node.childNodes) {\n return;\n }\n\n while (node.childNodes.length > 0) {\n node.removeChild(node.firstChild);\n }\n}\n\n\n//\n// WARNING: not for general use!\n//\n\nfunction miniJSONify(o, exc) {\n if (typeof o === 'undefined') {\n return 'undefined';\n } else if (o == null) {\n return 'null';\n } else if (typeof o == 'string') {\n return \"'\" + o + \"'\";\n } else if (typeof o == 'number') {\n return \"\" + o;\n } else if (typeof o == 'boolean') {\n return \"\" + o;\n } else if (typeof o == 'object') {\n if (o instanceof Array) {\n var s = null;\n for (var i = 0; i < o.length; ++i) {\n s = (s == null ? '' : (s + ', ')) + miniJSONify(o[i], exc);\n }\n return '[' + (s ? s : '') + ']';\n } else {\n exc = exc || {};\n var s = null;\n for (var k in o) {\n if (exc[k])\n continue;\n if (k != undefined && typeof (o[k]) != 'function') {\n s = (s == null ? '' : (s + ', ')) + k + ': ' + miniJSONify(o[k], exc);\n }\n }\n return '{' + (s ? s : '') + '}';\n }\n } else {\n return (typeof o);\n }\n}\n\nfunction shallowCopy(o) {\n var n = {};\n for (var k in o) {\n n[k] = o[k];\n }\n return n;\n}\n\nfunction Observed(x) {\n this.value = x;\n this.listeners = [];\n}\n\nObserved.prototype.addListener = function (f) {\n this.listeners.push(f);\n};\n\nObserved.prototype.addListenerAndFire = function (f) {\n this.listeners.push(f);\n f(this.value);\n};\n\nObserved.prototype.removeListener = function (f) {\n arrayRemove(this.listeners, f);\n};\n\nObserved.prototype.get = function () {\n return this.value;\n};\n\nObserved.prototype.set = function (x) {\n this.value = x;\n for (var i = 0; i < this.listeners.length; ++i) {\n this.listeners[i](x);\n }\n};\n\nfunction Awaited() {\n this.queue = [];\n}\n\nAwaited.prototype.provide = function (x) {\n if (this.res !== undefined) {\n throw \"Resource has already been provided.\";\n }\n\n this.res = x;\n for (var i = 0; i < this.queue.length; ++i) {\n this.queue[i](x);\n }\n this.queue = null; // avoid leaking closures.\n};\n\nAwaited.prototype.await = function (f) {\n if (this.res !== undefined) {\n f(this.res);\n return this.res;\n } else {\n this.queue.push(f);\n }\n};\n\nvar __dalliance_saltSeed = 0;\n\nfunction saltURL(url) {\n return url + '?salt=' + b64_sha1('' + Date.now() + ',' + (++__dalliance_saltSeed));\n}\n\nfunction textXHR(url, callback, opts) {\n if (opts && opts.salt)\n url = saltURL(url);\n\n try {\n var timeout;\n if (opts && opts.timeout) {\n timeout = setTimeout(\n function () {\n console.log('timing out ' + url);\n req.abort();\n return callback(null, 'Timeout');\n },\n opts.timeout\n );\n }\n\n var req = new XMLHttpRequest();\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n if (timeout)\n clearTimeout(timeout);\n if (req.status < 200 || req.status >= 300) {\n callback(null, 'Error code ' + req.status);\n } else {\n callback(req.responseText);\n }\n }\n };\n\n req.open('GET', url, true);\n req.responseType = 'text';\n\n if (opts && opts.credentials) {\n req.withCredentials = true;\n }\n req.send();\n } catch (e) {\n callback(null, 'Exception ' + e);\n }\n}\n\nfunction relativeURL(base, rel) {\n // FIXME quite naive -- good enough for trackhubs?\n\n if (rel.indexOf('http:') == 0 || rel.indexOf('https:') == 0) {\n return rel;\n }\n\n var li = base.lastIndexOf('/');\n if (li >= 0) {\n return base.substr(0, li + 1) + rel;\n } else {\n return rel;\n }\n}\n\nvar AMINO_ACID_TRANSLATION = {\n 'TTT': 'F',\n 'TTC': 'F',\n 'TTA': 'L',\n 'TTG': 'L',\n 'CTT': 'L',\n 'CTC': 'L',\n 'CTA': 'L',\n 'CTG': 'L',\n 'ATT': 'I',\n 'ATC': 'I',\n 'ATA': 'I',\n 'ATG': 'M',\n 'GTT': 'V',\n 'GTC': 'V',\n 'GTA': 'V',\n 'GTG': 'V',\n 'TCT': 'S',\n 'TCC': 'S',\n 'TCA': 'S',\n 'TCG': 'S',\n 'CCT': 'P',\n 'CCC': 'P',\n 'CCA': 'P',\n 'CCG': 'P',\n 'ACT': 'T',\n 'ACC': 'T',\n 'ACA': 'T',\n 'ACG': 'T',\n 'GCT': 'A',\n 'GCC': 'A',\n 'GCA': 'A',\n 'GCG': 'A',\n 'TAT': 'Y',\n 'TAC': 'Y',\n 'TAA': '*', // stop\n 'TAG': '*', // stop\n 'CAT': 'H',\n 'CAC': 'H',\n 'CAA': 'Q',\n 'CAG': 'Q',\n 'AAT': 'N',\n 'AAC': 'N',\n 'AAA': 'K',\n 'AAG': 'K',\n 'GAT': 'D',\n 'GAC': 'D',\n 'GAA': 'E',\n 'GAG': 'E',\n 'TGT': 'C',\n 'TGC': 'C',\n 'TGA': '*', // stop\n 'TGG': 'W',\n 'CGT': 'R',\n 'CGC': 'R',\n 'CGA': 'R',\n 'CGG': 'R',\n 'AGT': 'S',\n 'AGC': 'S',\n 'AGA': 'R',\n 'AGG': 'R',\n 'GGT': 'G',\n 'GGC': 'G',\n 'GGA': 'G',\n 'GGG': 'G'\n};\n\nfunction resolveUrlToPage(rel) {\n return makeElement('a', null, { href: rel }).href;\n}\n\n//\n// Missing APIs\n//\n\nif (!('trim' in String.prototype)) {\n String.prototype.trim = function () {\n return this.replace(/^\\s+/, '').replace(/\\s+$/, '');\n };\n}\n\nexport {\n textXHR,\n relativeURL,\n resolveUrlToPage,\n shallowCopy,\n pusho,\n arrayIndexOf,\n arrayEquals,\n pick,\n makeElement,\n makeElementNS,\n removeChildren,\n miniJSONify,\n Observed,\n Awaited,\n AMINO_ACID_TRANSLATION\n};\n","/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n//\n// Dalliance Genome Explorer\n// (c) Thomas Down 2006-2011\n//\n// bin.js general binary data support\n//\n\n\nimport { b64_sha1 } from './sha1';\nimport { shallowCopy } from './utils';\n\nfunction BlobFetchable(b) {\n this.blob = b;\n}\n\nBlobFetchable.prototype.slice = function (start, length) {\n var b;\n\n if (this.blob.slice) {\n if (length) {\n b = this.blob.slice(start, start + length);\n } else {\n b = this.blob.slice(start);\n }\n } else {\n if (length) {\n b = this.blob.webkitSlice(start, start + length);\n } else {\n b = this.blob.webkitSlice(start);\n }\n }\n return new BlobFetchable(b);\n};\n\nBlobFetchable.prototype.salted = function () {\n return this;\n};\n\nif (typeof (FileReader) !== 'undefined') {\n // console.log('defining async BlobFetchable.fetch');\n\n BlobFetchable.prototype.fetch = function (callback) {\n var reader = new FileReader();\n reader.onloadend = function (ev) {\n callback(bstringToBuffer(reader.result));\n };\n reader.readAsBinaryString(this.blob);\n }\n\n} else {\n BlobFetchable.prototype.fetch = function (callback) {\n var reader = new FileReaderSync();\n try {\n var res = reader.readAsArrayBuffer(this.blob);\n callback(res);\n } catch (e) {\n callback(null, e);\n }\n }\n}\n\nfunction URLFetchable(url, start, end, opts) {\n if (!opts) {\n if (typeof start === 'object') {\n opts = start;\n start = undefined;\n } else {\n opts = {};\n }\n }\n\n this.url = url;\n this.start = start || 0;\n if (end) {\n this.end = end;\n }\n this.opts = opts;\n}\n\nURLFetchable.prototype.slice = function (s, l) {\n if (s < 0) {\n throw 'Bad slice ' + s;\n }\n\n var ns = this.start, ne = this.end;\n if (ns && s) {\n ns = ns + s;\n } else {\n ns = s || ns;\n }\n if (l && ns) {\n ne = ns + l - 1;\n } else {\n ne = ne || l - 1;\n }\n return new URLFetchable(this.url, ns, ne, this.opts);\n};\n\nvar seed = 0;\nvar isSafari = typeof (navigator) !== 'undefined' &&\n navigator.userAgent.indexOf('Safari') >= 0 &&\n navigator.userAgent.indexOf('Chrome') < 0;\n\nURLFetchable.prototype.fetchAsText = function (callback) {\n var thisB = this;\n\n this.getURL().then(function (url) {\n try {\n var req = new XMLHttpRequest();\n var length;\n if ((isSafari || thisB.opts.salt) && url.indexOf('?') < 0) {\n url = url + '?salt=' + b64_sha1('' + Date.now() + ',' + (++seed));\n }\n req.open('GET', url, true);\n\n if (thisB.end) {\n if (thisB.end - thisB.start > 100000000) {\n throw 'Monster fetch!';\n }\n req.setRequestHeader('Range', 'bytes=' + thisB.start + '-' + thisB.end);\n length = thisB.end - thisB.start + 1;\n }\n\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n if (req.status == 200 || req.status == 206) {\n return callback(req.responseText);\n } else {\n return callback(null);\n }\n }\n };\n if (thisB.opts.credentials) {\n req.withCredentials = true;\n }\n req.send();\n } catch (e) {\n return callback(null);\n }\n }).catch(function (err) {\n console.log(err);\n return callback(null, err);\n });\n};\n\nURLFetchable.prototype.salted = function () {\n var o = shallowCopy(this.opts);\n o.salt = true;\n return new URLFetchable(this.url, this.start, this.end, o);\n};\n\nURLFetchable.prototype.getURL = function () {\n if (this.opts.resolver) {\n return this.opts.resolver(this.url).then(function (urlOrObj) {\n if (typeof urlOrObj === 'string') {\n return urlOrObj;\n } else {\n return urlOrObj.url;\n }\n });\n } else {\n return Promise.resolve(this.url);\n }\n};\n\nURLFetchable.prototype.fetch = function (callback, opts) {\n var thisB = this;\n\n opts = opts || {};\n var attempt = opts.attempt || 1;\n var truncatedLength = opts.truncatedLength;\n if (attempt > 3) {\n return callback(null);\n }\n\n this.getURL().then(function (url) {\n try {\n var timeout;\n if (opts.timeout && !thisB.opts.credentials) {\n timeout = setTimeout(\n function () {\n console.log('timing out ' + url);\n req.abort();\n return callback(null, 'Timeout');\n },\n opts.timeout\n );\n }\n\n var req = new XMLHttpRequest();\n var length;\n if ((isSafari || thisB.opts.salt) && url.indexOf('?') < 0) {\n url = url + '?salt=' + b64_sha1('' + Date.now() + ',' + (++seed));\n }\n req.open('GET', url, true);\n req.overrideMimeType('text/plain; charset=x-user-defined');\n if (thisB.end) {\n if (thisB.end - thisB.start > 100000000) {\n throw 'Monster fetch!';\n }\n req.setRequestHeader('Range', 'bytes=' + thisB.start + '-' + thisB.end);\n length = thisB.end - thisB.start + 1;\n }\n req.responseType = 'arraybuffer';\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n if (timeout)\n clearTimeout(timeout);\n if (req.status == 200 || req.status == 206) {\n if (req.response) {\n var bl = req.response.byteLength;\n if (length && length != bl && (!truncatedLength || bl != truncatedLength)) {\n return thisB.fetch(callback, { attempt: attempt + 1, truncatedLength: bl });\n } else {\n return callback(req.response);\n }\n } else if (req.mozResponseArrayBuffer) {\n return callback(req.mozResponseArrayBuffer);\n } else {\n var r = req.responseText;\n if (length && length != r.length && (!truncatedLength || r.length != truncatedLength)) {\n return thisB.fetch(callback, { attempt: attempt + 1, truncatedLength: r.length });\n } else {\n return callback(bstringToBuffer(req.responseText));\n }\n }\n } else {\n return thisB.fetch(callback, { attempt: attempt + 1 });\n }\n }\n };\n if (thisB.opts.credentials) {\n req.withCredentials = true;\n }\n req.send();\n } catch (e) {\n return callback(null);\n }\n }).catch(function (err) {\n console.log(err);\n return callback(null, err);\n });\n}\n\nfunction bstringToBuffer(result) {\n if (!result) {\n return null;\n }\n\n var ba = new Uint8Array(result.length);\n for (var i = 0; i < ba.length; ++i) {\n ba[i] = result.charCodeAt(i);\n }\n return ba.buffer;\n}\n\n// Read from Uint8Array\n\nvar convertBuffer = new ArrayBuffer(8);\nvar ba = new Uint8Array(convertBuffer);\nvar fa = new Float32Array(convertBuffer);\n\nfunction readFloat(buf, offset) {\n ba[0] = buf[offset];\n ba[1] = buf[offset + 1];\n ba[2] = buf[offset + 2];\n ba[3] = buf[offset + 3];\n return fa[0];\n}\n\nfunction readInt64(ba, offset) {\n return (ba[offset + 7] << 24) | (ba[offset + 6] << 16) | (ba[offset + 5] << 8) | (ba[offset + 4]);\n}\n\nconst M1 = 256,\n M2 = M1 * 256,\n M3 = M2 * 256,\n M4 = M3 * 256,\n M5 = M4 * 256;\n\nfunction readInt64LE(ba, offset) {\n return (ba[offset]) + (ba[offset + 1] * M1) + (ba[offset + 2] * M2) + (ba[offset + 3] * M3) + (ba[offset + 4] * M4) + (ba[offset + 5] * M5);\n}\n\nfunction readInt64BE(ba, offset) {\n return (ba[offset + 7]) + (ba[offset + 6] * M1) + (ba[offset + 5] * M2) + (ba[offset + 4] * M3) + (ba[offset + 3] * M4) + (ba[offset + 2] * M5);\n}\n\nfunction readInt(ba, offset) {\n return (ba[offset + 3] << 24) | (ba[offset + 2] << 16) | (ba[offset + 1] << 8) | (ba[offset]);\n}\n\nfunction readShort(ba, offset) {\n return (ba[offset + 1] << 8) | (ba[offset]);\n}\n\nfunction readByte(ba, offset) {\n return ba[offset];\n}\n\nfunction readIntBE(ba, offset) {\n return (ba[offset] << 24) | (ba[offset + 1] << 16) | (ba[offset + 2] << 8) | (ba[offset + 3]);\n}\n\nexport {\n BlobFetchable,\n URLFetchable,\n readInt,\n readIntBE,\n readInt64,\n readInt64LE,\n readInt64BE,\n readShort,\n readByte,\n readFloat\n};\n","/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n//\n// Dalliance Genome Explorer\n// (c) Thomas Down 2006-2011\n//\n// lh3utils.js: common support for lh3's file formats\n//\n\nimport { arrayCopy, inflateBuffer as jszlib_inflate_buffer } from 'jszlib';\n\n\nfunction Vob(b, o) {\n this.block = b;\n this.offset = o;\n}\n\nVob.prototype.toString = function() {\n return '' + this.block + ':' + this.offset;\n};\n\nfunction readVob(ba, offset, allowZero) {\n var block = ((ba[offset+6] & 0xff) * 0x100000000) + ((ba[offset+5] & 0xff) * 0x1000000) + ((ba[offset+4] & 0xff) * 0x10000) + ((ba[offset+3] & 0xff) * 0x100) + ((ba[offset+2] & 0xff));\n var bint = (ba[offset+1] << 8) | (ba[offset]);\n if (block == 0 && bint == 0 && !allowZero) {\n return null; // Should only happen in the linear index?\n } else {\n return new Vob(block, bint);\n }\n}\n\nfunction unbgzf(data, lim) {\n lim = Math.min(lim || 1, data.byteLength - 50);\n var oBlockList = [];\n var ptr = [0];\n var totalSize = 0;\n\n while (ptr[0] < lim) {\n var ba = new Uint8Array(data, ptr[0], 12); // FIXME is this enough for all credible BGZF block headers?\n var xlen = (ba[11] << 8) | (ba[10]);\n // dlog('xlen[' + (ptr[0]) +']=' + xlen);\n var unc = jszlib_inflate_buffer(data, 12 + xlen + ptr[0], Math.min(65536, data.byteLength - 12 - xlen - ptr[0]), ptr);\n ptr[0] += 8;\n totalSize += unc.byteLength;\n oBlockList.push(unc);\n }\n\n if (oBlockList.length == 1) {\n return oBlockList[0];\n } else {\n var out = new Uint8Array(totalSize);\n var cursor = 0;\n for (var i = 0; i < oBlockList.length; ++i) {\n var b = new Uint8Array(oBlockList[i]);\n arrayCopy(b, 0, out, cursor, b.length);\n cursor += b.length;\n }\n return out.buffer;\n }\n}\n\nfunction Chunk(minv, maxv) {\n this.minv = minv; this.maxv = maxv;\n}\n\n\n//\n// Binning (transliterated from SAM1.3 spec)\n//\n\n/* calculate bin given an alignment covering [beg,end) (zero-based, half-close-half-open) */\nfunction reg2bin(beg, end)\n{\n --end;\n if (beg>>14 == end>>14) return ((1<<15)-1)/7 + (beg>>14);\n if (beg>>17 == end>>17) return ((1<<12)-1)/7 + (beg>>17);\n if (beg>>20 == end>>20) return ((1<<9)-1)/7 + (beg>>20);\n if (beg>>23 == end>>23) return ((1<<6)-1)/7 + (beg>>23);\n if (beg>>26 == end>>26) return ((1<<3)-1)/7 + (beg>>26);\n return 0;\n}\n\n/* calculate the list of bins that may overlap with region [beg,end) (zero-based) */\nvar MAX_BIN = (((1<<18)-1)/7);\nfunction reg2bins(beg, end)\n{\n var i = 0, k, list = [];\n --end;\n list.push(0);\n for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) list.push(k);\n for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) list.push(k);\n for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) list.push(k);\n for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) list.push(k);\n for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) list.push(k);\n return list;\n}\n\nexport { unbgzf, readVob, reg2bin, reg2bins, Chunk };\n","/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n//\n// Dalliance Genome Explorer\n// (c) Thomas Down 2006-2010\n//\n// spans.js: JavaScript Intset/Location port.\n//\n\nfunction Range(min, max)\n{\n if (typeof(min) != 'number' || typeof(max) != 'number')\n throw 'Bad range ' + min + ',' + max;\n this._min = min;\n this._max = max;\n}\n\nRange.prototype.min = function() {\n return this._min;\n};\n\nRange.prototype.max = function() {\n return this._max;\n};\n\nRange.prototype.contains = function(pos) {\n return pos >= this._min && pos <= this._max;\n};\n\nRange.prototype.isContiguous = function() {\n return true;\n};\n\nRange.prototype.ranges = function() {\n return [this];\n};\n\nRange.prototype._pushRanges = function(ranges) {\n ranges.push(this);\n};\n\nRange.prototype.toString = function() {\n return '[' + this._min + '-' + this._max + ']';\n};\n\nfunction _Compound(ranges) {\n // given: a set of unsorted possibly overlapping ranges\n // sort the input ranges\n var sorted = ranges.sort(_rangeOrder);\n // merge overlaps between adjacent ranges\n var merged = [];\n var current = sorted.shift();\n sorted.forEach(function(range) {\n if (range._min <= current._max) {\n if (range._max > current._max) {\n current._max = range._max;\n }\n }\n else {\n merged.push(current);\n current = range;\n }\n });\n merged.push(current);\n this._ranges = merged;\n}\n\n_Compound.prototype.min = function() {\n return this._ranges[0].min();\n};\n\n_Compound.prototype.max = function() {\n return this._ranges[this._ranges.length - 1].max();\n};\n\n// returns the index of the first range that is not less than pos\n_Compound.prototype.lower_bound = function(pos) {\n // first check if pos is out of range\n var r = this.ranges();\n if (pos > this.max()) return r.length;\n if (pos < this.min()) return 0;\n // do a binary search\n var a=0, b=r.length - 1;\n while (a <= b) {\n var m = Math.floor((a+b)/2);\n if (pos > r[m]._max) {\n a = m+1;\n }\n else if (pos < r[m]._min) {\n b = m-1;\n }\n else {\n return m;\n }\n }\n return a;\n};\n\n_Compound.prototype.contains = function(pos) {\n var lb = this.lower_bound(pos);\n if (lb < this._ranges.length && this._ranges[lb].contains(pos)) {\n return true;\n }\n return false;\n};\n\n_Compound.prototype.insertRange = function(range) {\n var lb = this.lower_bound(range._min);\n if (lb === this._ranges.length) { // range follows this\n this._ranges.push(range);\n return;\n }\n\n var r = this.ranges();\n if (range._max < r[lb]._min) { // range preceeds lb\n this._ranges.splice(lb,0,range);\n return;\n }\n\n // range overlaps lb (at least)\n if (r[lb]._min < range._min) range._min = r[lb]._min;\n var ub = lb+1;\n while (ub < r.length && r[ub]._min <= range._max) {\n ub++;\n }\n ub--;\n // ub is the upper bound of the new range\n if (r[ub]._max > range._max) range._max = r[ub]._max;\n\n // splice range into this._ranges\n this._ranges.splice(lb,ub-lb+1,range);\n return;\n};\n\n_Compound.prototype.isContiguous = function() {\n return this._ranges.length > 1;\n};\n\n_Compound.prototype.ranges = function() {\n return this._ranges;\n};\n\n_Compound.prototype._pushRanges = function(ranges) {\n for (var ri = 0; ri < this._ranges.length; ++ri)\n ranges.push(this._ranges[ri]);\n};\n\n_Compound.prototype.toString = function() {\n var s = '';\n for (var r = 0; r < this._ranges.length; ++r) {\n if (r>0) {\n s = s + ',';\n }\n s = s + this._ranges[r].toString();\n }\n return s;\n};\n\nfunction union(s0, s1) {\n if (! (s0 instanceof _Compound)) {\n if (! (s0 instanceof Array))\n s0 = [s0];\n s0 = new _Compound(s0);\n }\n\n if (s1)\n s0.insertRange(s1);\n\n return s0;\n}\n\nfunction intersection(s0, s1) {\n var r0 = s0.ranges();\n var r1 = s1.ranges();\n var l0 = r0.length, l1 = r1.length;\n var i0 = 0, i1 = 0;\n var or = [];\n\n while (i0 < l0 && i1 < l1) {\n var s0 = r0[i0], s1 = r1[i1];\n var lapMin = Math.max(s0.min(), s1.min());\n var lapMax = Math.min(s0.max(), s1.max());\n if (lapMax >= lapMin) {\n or.push(new Range(lapMin, lapMax));\n }\n if (s0.max() > s1.max()) {\n ++i1;\n } else {\n ++i0;\n }\n }\n\n if (or.length == 0) {\n return null; // FIXME\n } else if (or.length == 1) {\n return or[0];\n } else {\n return new _Compound(or);\n }\n}\n\nfunction coverage(s) {\n var tot = 0;\n var rl = s.ranges();\n for (var ri = 0; ri < rl.length; ++ri) {\n var r = rl[ri];\n tot += (r.max() - r.min() + 1);\n }\n return tot;\n}\n\n\n\nfunction rangeOrder(a, b)\n{\n if (a.min() < b.min()) {\n return -1;\n } else if (a.min() > b.min()) {\n return 1;\n } else if (a.max() < b.max()) {\n return -1;\n } else if (b.max() > a.max()) {\n return 1;\n } else {\n return 0;\n }\n}\n\nfunction _rangeOrder(a, b)\n{\n if (a._min < b._min) {\n return -1;\n } else if (a._min > b._min) {\n return 1;\n } else if (a._max < b._max) {\n return -1;\n } else if (b._max > a._max) {\n return 1;\n } else {\n return 0;\n }\n}\n\n\nexport {\n Range,\n union,\n intersection,\n coverage,\n rangeOrder,\n _rangeOrder\n};\n","/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */\n\n//\n// Dalliance Genome Explorer\n// (c) Thomas Down 2006-2011\n//\n// tabix.js: basic support for tabix-indexed flatfiles\n//\n\n\nimport { readInt, readShort, readByte, readInt64, readFloat } from './bin';\nimport { readVob, unbgzf,reg2bins, Chunk } from './lh3utils';\nimport { intersection, Range, union } from './spans';\n\n\nvar TABIX_MAGIC = 0x01494254;\n\nfunction TabixFile() {}\n\nfunction connectTabix(data, tbi, callback) {\n var tabix = new TabixFile();\n tabix.data = data;\n tabix.tbi = tbi;\n\n tabix.tbi.fetch(function(header) { // Do we really need to fetch the whole thing? :-(\n if (!header) {\n return callback(null, \"Couldn't access Tabix\");\n }\n\n var unchead = unbgzf(header, header.byteLength);\n var uncba = new Uint8Array(unchead);\n var magic = readInt(uncba, 0);\n if (magic != TABIX_MAGIC) {\n return callback(null, 'Not a tabix index');\n }\n\n var nref = readInt(uncba, 4);\n tabix.format = readInt(uncba, 8);\n tabix.colSeq = readInt(uncba, 12);\n tabix.colStart = readInt(uncba, 16);\n tabix.colEnd = readInt(uncba, 20);\n tabix.meta = readInt(uncba, 24);\n tabix.skip = readInt(uncba, 28);\n var nameLength = readInt(uncba, 32);\n\n tabix.indices = [];\n\n var p = 36;\n tabix.chrToIndex = {};\n tabix.indexToChr = [];\n for (var i = 0; i < nref; ++i) {\n var name = ''\n\n while (true) {\n var ch = uncba[p++];\n if (ch == 0)\n break;\n\n name += String.fromCharCode(ch);\n }\n\n tabix.chrToIndex[name] = i;\n if (name.indexOf('chr') == 0) {\n tabix.chrToIndex[name.substring(3)] = i;\n } else {\n tabix.chrToIndex['chr' + name] = i;\n }\n tabix.indexToChr.push(name);\n }\n\n var minBlockIndex = 1000000000;\n for (var ref = 0; ref < nref; ++ref) {\n var blockStart = p;\n var nbin = readInt(uncba, p); p += 4;\n for (var b = 0; b < nbin; ++b) {\n var bin = readInt(uncba, p);\n var nchnk = readInt(uncba, p+4);\n p += 8 + (nchnk * 16);\n }\n var nintv = readInt(uncba, p); p += 4;\n\n var q = p;\n for (var i = 0; i < nintv; ++i) {\n var v = readVob(uncba, q); q += 8;\n if (v) {\n var bi = v.block;\n if (v.offset > 0)\n bi += 65536;\n\n if (bi < minBlockIndex)\n minBlockIndex = bi;\n break;\n }\n }\n p += (nintv * 8);\n\n\n var ub = uncba;\n if (nbin > 0) {\n tabix.indices[ref] = new Uint8Array(unchead, blockStart, p - blockStart);\n }\n }\n\n tabix.headerMax = minBlockIndex;\n\n callback(tabix);\n }, {timeout: 50000});\n}\n\n// Copy-paste from BamFile\n\nTabixFile.prototype.blocksForRange = function(refId, min, max) {\n var index = this.indices[refId];\n if (!index) {\n return [];\n }\n\n var intBinsL = reg2bins(min, max);\n var intBins = [];\n for (var i = 0; i < intBinsL.length; ++i) {\n intBins[intBinsL[i]] = true;\n }\n var leafChunks = [], otherChunks = [];\n\n var nbin = readInt(index, 0);\n var p = 4;\n for (var b = 0; b < nbin; ++b) {\n var bin = readInt(index, p);\n var nchnk = readInt(index, p+4);\n p += 8;\n if (intBins[bin]) {\n for (var c = 0; c < nchnk; ++c) {\n var cs = readVob(index, p, true);\n var ce = readVob(index, p + 8, true);\n (bin < 4681 ? otherChunks : leafChunks).push(new Chunk(cs, ce));\n p += 16;\n }\n } else {\n p += (nchnk * 16);\n }\n }\n\n var nintv = readInt(index, p);\n var lowest = null;\n var minLin = Math.min(min>>14, nintv - 1), maxLin = Math.min(max>>14, nintv - 1);\n for (var i = minLin; i <= maxLin; ++i) {\n var lb = readVob(index, p + 4 + (i * 8));\n if (!lb) {\n continue;\n }\n if (!lowest || lb.block < lowest.block || lb.offset < lowest.offset) {\n lowest = lb;\n }\n }\n\n var prunedOtherChunks = [];\n if (lowest != null) {\n for (var i = 0; i < otherChunks.length; ++i) {\n var chnk = otherChunks[i];\n if (chnk.maxv.block >= lowest.block && chnk.maxv.offset >= lowest.offset) {\n prunedOtherChunks.push(chnk);\n }\n }\n }\n otherChunks = prunedOtherChunks;\n\n var intChunks = [];\n for (var i = 0; i < otherChunks.length; ++i) {\n intChunks.push(otherChunks[i]);\n }\n for (var i = 0; i < leafChunks.length; ++i) {\n intChunks.push(leafChunks[i]);\n }\n\n intChunks.sort(function(c0, c1) {\n var dif = c0.minv.block - c1.minv.block;\n if (dif != 0) {\n return dif;\n } else {\n return c0.minv.offset - c1.minv.offset;\n }\n });\n var mergedChunks = [];\n if (intChunks.length > 0) {\n var cur = intChunks[0];\n for (var i = 1; i < intChunks.length; ++i) {\n var nc = intChunks[i];\n if (nc.minv.block == cur.maxv.block /* && nc.minv.offset == cur.maxv.offset */) { // no point splitting mid-block\n cur = new Chunk(cur.minv, nc.maxv);\n } else {\n mergedChunks.push(cur);\n cur = nc;\n }\n }\n mergedChunks.push(cur);\n }\n\n return mergedChunks;\n}\n\nTabixFile.prototype.fetch = function(chr, min, max, callback) {\n var thisB = this;\n\n var chrId = this.chrToIndex[chr];\n if (chrId == undefined)\n return callback([]);\n\n var canonicalChr = this.indexToChr[chrId];\n\n var chunks;\n if (chrId === undefined) {\n chunks = [];\n } else {\n chunks = this.blocksForRange(chrId, min, max);\n if (!chunks) {\n callback(null, 'Error in index fetch');\n }\n }\n\n var records = [];\n var index = 0;\n var data;\n\n function tramp() {\n if (index >= chunks.length) {\n return callback(records);\n } else if (!data) {\n var c = chunks[index];\n var fetchMin = c.minv.block;\n var fetchMax = c.maxv.block + (1<<16); // *sigh*\n thisB.data.slice(fetchMin, fetchMax - fetchMin).fetch(function(r) { //2^16 fetch, 65536 bytes\n try {\n data = unbgzf(r, c.maxv.block - c.minv.block + 1);\n return tramp();\n } catch (e) {\n return callback(null, e);\n }\n });\n } else {\n var ba = new Uint8Array(data);\n thisB.readRecords(ba, chunks[index].minv.offset, records, min, max, canonicalChr);\n data = null;\n ++index;\n return tramp();\n }\n }\n\n try {\n tramp();\n } catch (e) {\n callback(null, e);\n }\n}\n\nTabixFile.prototype.readRecords = function(ba, offset, sink, min, max, chr) {\n LINE_LOOP:\n while (true) {\n var line = '';\n while (offset < ba.length) {\n var ch = ba[offset++];\n if (ch == 10) {\n var toks = line.split('\\t');\n\n if (toks[this.colSeq - 1] == chr) {\n var fmin = parseInt(toks[this.colStart - 1]);\n var fmax = fmin;\n if (this.colEnd > 0)\n fmax = parseInt(toks[this.colEnd - 1]);\n if (this.format & 0x10000) ++fmin;\n\n if (fmin <= max && fmax >= min)\n sink.push(line);\n }\n continue LINE_LOOP;\n } else {\n line += String.fromCharCode(ch);\n }\n }\n return;\n }\n}\n\nTabixFile.prototype.fetchHeader = function(callback, opts) {\n // This routine fetches a large block of data from the start of the file, and then selects \"headers\" based\n // on one of three possible criteria:\n // - metaOnly (tabix -H compatible): only lines that begin with the meta character are accepted\n // - skipped (get all \"skipped\" rows, based on tabix -S parameter when indexing)\n // - nLines (peek at the first x lines, which may return data as well as headers)\n\n // In all cases, the callback will return as soon as we reach the first line that does not meet these conditions.\n var defaults = { metaOnly: true, skipped: false, nLines: 0 };\n opts = opts || defaults;\n Object.keys(defaults).forEach(function(key) {\n if (!opts.hasOwnProperty(key)) {\n opts[key] = defaults[key];\n }\n });\n\n var self = this;\n var fetchPtr = 0, ptr = 0, line='';\n var lines = [];\n\n self.data.slice(0, self.headerMax).fetch(function(chnk) {\n if (!chnk) {\n return callback(null, \"Fetch failed\");\n }\n var ba = new Uint8Array(unbgzf(chnk, chnk.byteLength));\n var ptr = 0, line = '', lines = [];\n while (ptr < ba.length) {\n var ch = ba[ptr++];\n if (ch == 10) {\n if ((opts.metaOnly && line.charCodeAt(0) == self.meta) ||\n (opts.skipped && lines.length < self.skip) ||\n (opts.nLines && lines.length < opts.nLines))\n {\n lines.push(line);\n line = '';\n } else {\n return callback(lines);\n }\n } else {\n line += String.fromCharCode(ch);\n }\n }\n callback(lines);\n });\n};\n\nexport { connectTabix, TABIX_MAGIC };\n","import { connectTabix } from './lib/tabix';\nimport { URLFetchable, BlobFetchable } from './lib/bin';\n\n\n// Wrap the reader in a Promise API for LZ compatibility\nfunction urlReader(dataUrl, indexUrl) {\n return new Promise(function(resolve, reject) {\n connectTabix(new URLFetchable(dataUrl), new URLFetchable(indexUrl),\n function (reader, err) {\n if (err) {\n reject(err);\n } else {\n resolve(reader);\n }\n });\n });\n}\n\nfunction blobReader(data_file, tabix_file) {\n return new Promise(function(resolve, reject) {\n connectTabix(new BlobFetchable(data_file), new BlobFetchable(tabix_file),\n function (reader, err) {\n if (err) {\n reject(err);\n } else {\n resolve(reader);\n }\n });\n });\n}\n\nexport { urlReader, blobReader };\n","/**\n * An adapter that fetches data from a remote Tabix-indexed datafile, instead of a RESTful API.\n * Requires a generic user-specified parser function.\n *\n * ### Features provided\n * * {@link module:LocusZoom_Adapters~TabixUrlSource}\n *\n * ### Loading and usage\n * The page must incorporate and load all libraries before this file can be used, including:\n * - Vendor assets\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 * \n * ```\n *\n * To use with ES6 modules, the plugin must be loaded and registered explicitly before use:\n * ```\n * import LocusZoom from 'locuszoom';\n * import LzTabixSource from 'locuszoom/esm/ext/lz-tabix-source';\n * LocusZoom.use(LzTabixSource);\n * ```\n *\n * Then use the Adapter made available by this extension. For example:\n *\n * ```javascript\n * data_sources.add(\"assoc\", [\"TabixUrlSource\", {\n * url_data: 'https://s3-bucket.example/tabix-indexed-bgzip-file.gz',\n * parser_func: (line_of_text) => object_of_parsed_data_for_this_line,\n * // Tabix performs region queries. If you are fetching interval data (one end outside the edge of the plot), then\n * // \"overfetching\" can help to ensure that data partially outside the view region is retrieved\n * // If you are fetching single-point data like association summary stats, then overfetching is unnecessary\n * overfetch: 0.25\n * }]);\n * ```\n *\n * @module\n */\nimport { urlReader } from 'tabix-reader';\n\n\nfunction install(LocusZoom) {\n const BaseLZAdapter = LocusZoom.Adapters.get('BaseLZAdapter');\n\n /**\n * Loads data from a remote Tabix file (if the file host has been configured with proper\n * CORS and Range header support). For instructions on how to configure a remote file host such as S3 or\n * Google Cloud storage to serve files in the manner required, see:\n * https://docs.cancergenomicscloud.org/docs/enabling-cross-origin-resource-sharing-cors#CORS\n *\n * @alias module:LocusZoom_Adapters~TabixUrlSource\n * @see {@link module:ext/lz-tabix-source} for required extension and installation instructions\n * @see module:LocusZoom_Adapters~BaseLZAdapter\n * @param {function} config.parser_func A function that parses a single line of text and returns (usually) a\n * structured object of data fields\n * @param {string} config.url_data The URL for the bgzipped and tabix-indexed file\n * @param {string} [config.url_tbi] The URL for the tabix index. Defaults to `url_data` + '.tbi'\n * @param {Promise} [config.reader] The URL for tabix-reader instance that provides the data. Mutually exclusive with providing a URL.\n * Most LocusZoom usages will not pass an external reader. This option exists for websites like LocalZoom that accept\n * many file formats and want to perform input validation before creating the plot: \"select parser options\", etc.\n * @param {number} [config.overfetch = 0] Optionally fetch more data than is required to satisfy the\n * region query. (specified as a fraction of the region size, 0-1).\n * Useful for sources where interesting features might lie near the edges of the plot, eg BED track intervals.\n */\n class TabixUrlSource extends BaseLZAdapter {\n constructor(config) {\n super(config);\n if (!config.parser_func || !(config.url_data || config.reader)) {\n throw new Error('Tabix source is missing required configuration options');\n }\n this.parser = config.parser_func;\n this.url_data = config.url_data;\n this.url_tbi = config.url_tbi || `${this.url_data}.tbi`;\n\n // In tabix mode, sometimes we want to fetch a slightly larger region than is displayed, in case a\n // feature is on the edge of what the tabix query would return.\n // Specify overfetch in units of % of total region size. (\"fetch 10% extra before and after\")\n this._overfetch = config.overfetch || 0;\n\n if (this._overfetch < 0 || this._overfetch > 1) {\n throw new Error('Overfetch must be specified as a fraction (0-1) of the requested region size');\n }\n\n // Assuming that the `tabix-reader` library has been loaded via a CDN, this will create the reader\n // Since fetching the index is a remote operation, all reader usages will be via an async interface.\n if (this.url_data) {\n this._reader_promise = urlReader(this.url_data, this.url_tbi).catch(function () {\n throw new Error('Failed to create a tabix reader from the provided URL');\n });\n } else {\n this._reader_promise = Promise.resolve(config.reader);\n }\n }\n\n _performRequest(options) {\n return new Promise((resolve, reject) => {\n // Ensure that the reader is fully created (and index available), then make a query\n const region_start = options.start;\n const region_end = options.end;\n const extra_amount = this._overfetch * (region_end - region_start);\n\n const start = options.start - extra_amount;\n const end = options.end + extra_amount;\n this._reader_promise.then((reader) => {\n reader.fetch(options.chr, start, end, function (data, err) {\n if (err) {\n reject(new Error('Could not read requested region. This may indicate an error with the .tbi index.'));\n }\n resolve(data);\n });\n });\n });\n }\n\n _normalizeResponse(records) {\n // Parse the data from lines of text to objects\n return records.map(this.parser);\n }\n }\n\n LocusZoom.Adapters.add('TabixUrlSource', TabixUrlSource);\n}\n\nif (typeof LocusZoom !== 'undefined') {\n // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use()\n // eslint-disable-next-line no-undef\n LocusZoom.use(install);\n}\n\n\nexport default install;\n\n"],"sourceRoot":""} \ 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 c5b86e27..7d24f42c 100644 --- a/dist/ext/lz-widget-addons.min.js +++ b/dist/ext/lz-widget-addons.min.js @@ -1,3 +1,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})(); +/*! Locuszoom 0.14.0 */ +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");return e.html+='Condition on Variant
',e}(),r=function(){const e=t.Layouts.get("toolbar","standard_association");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 1e7b9d05..7f195841 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,EAAmB,CAAC,cAAe,WAAY,SAAU,QAK/D,SAASC,EAAQC,GACb,MAAMC,EAAUD,EAAUE,QAAQpB,IAAI,WAChCqB,EAAcH,EAAUE,QAAQpB,IAAI,cA8P1C,MAAMsB,EAA2B,WAC7B,MAAMC,EAA+BL,EAAUM,QAAQxB,IAAI,UAAW,uBAAwB,CAAEyB,cAAc,IAE9G,OADAF,EAA6BG,MAAQ,2JAC9BH,EAHsB,GAM3BI,EAAwB,WAC1B,MAAMC,EAAgCV,EAAUM,QAAQxB,IAAI,UAAW,uBAAwB,CAAEyB,cAAc,IAO/G,OANAG,EAA8BC,QAAQC,KAAK,C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EAAY,IAEhBtB,EAAIJ,OAAO,MAAMA,OAAO,KACnBK,KAAK,QAAS,uCAAuCtC,KAAKwB,OAAOC,QAAQkC,KACzEpB,MAAM,cAAe,OACrBC,GAAG,SAAS,KACTU,EAAWQ,KACX1D,KAAKM,OAAOgB,KAAKO,cAEpBvC,KAAKA,MAGd,MAAMuE,EAAkB,IAAR5C,EACV6C,EAAa7C,IAASjB,KAAK6C,aAAaC,0BAA0BjC,OAAS,EAC3EkD,EAAK1B,EAAIJ,OAAO,MACtB8B,EAAG9B,OAAO,KACLK,KAAK,QAAS,qEAAqEtC,KAAKwB,OAAOC,QAAQqC,EAAY,YAAc,MACjIvB,MAAM,cAAe,OACrBC,GAAG,SAAS,KACTU,EAAWc,WAAYhE,KAAKM,OAAOgB,KAAKO,cAE3CvC,KAAK,KACLgD,KAAK,QAAS,kCACnByB,EAAG9B,OAAO,KACLK,KAAK,QAAS,sEAAsEtC,KAAKwB,OAAOC,QAAQoC,EAAS,YAAc,MAC/HtB,MAAM,cAAe,OACrBC,GAAG,SAAS,KACTU,EAAWe,cAAejE,KAAKM,OAAOgB,KAAKO,cAE9CvC,KAAK,KACLgD,KAAK,QAAS,iCACnByB,EAAG9B,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 +{"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","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,GAgGxB,SAASC,EAASC,GAGd,OAAOC,KAAKC,MAAMD,KAAKE,UAAUH,ICzErC,MAAMI,EAAe,CAAC,YAAa,SAAU,OAAQ,QAC/CC,EAAoB,CAAC,cAAe,WAAY,QAAS,UACzDC,EAAmB,CAAC,cAAe,WAAY,SAAU,QAK/D,SAASC,EAAQC,GACb,MAAMC,EAAUD,EAAUE,QAAQpB,IAAI,WAChCqB,EAAcH,EAAUE,QAAQpB,IAAI,cA8P1C,MAAMsB,EAA2B,WAC7B,MAAMC,EAA+BL,EAAUM,QAAQxB,IAAI,UAAW,wBAEtE,OADAuB,EAA6BE,MAAQ,2JAC9BF,EAHsB,GAM3BG,EAAwB,WAC1B,MAAMC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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 shared namespaces to a layout, recursively.\n *\n * Overriding namespaces can be used to identify where to retrieve data from, but not to add new data sources to a layout.\n * For that, a key would have to be added to `layout.namespace` directly.\n *\n * Detail: This function is a bit magical. Whereas most layouts overrides are copied over verbatim (merging objects and nested keys), applyNamespaces will *only* copy\n * over keys that are relevant to that data layer. Eg, if overrides specifies a key called \"red_herring\",\n * an association data layer will ignore that data source entirely, and not copy it into `assoc_layer.namespace`.\n *\n * Only items under a key called `namespace` are given this special treatment. This allows a single call to `Layouts.get('plot'...)` to specify\n * namespace overrides for many layers in one convenient place, without accidentally telling every layer to request all possible data for itself.\n * @private\n */\nfunction applyNamespaces(layout, shared_namespaces) {\n shared_namespaces = shared_namespaces || {};\n if (!layout || typeof layout !== 'object' || typeof shared_namespaces !== 'object') {\n throw new Error('Layout and shared namespaces must be provided as objects');\n }\n\n for (let [field_name, item] of Object.entries(layout)) {\n if (field_name === 'namespace') {\n Object.keys(item).forEach((requested_ns) => {\n const override = shared_namespaces[requested_ns];\n if (override) {\n item[requested_ns] = override;\n }\n });\n } else if (item !== null && (typeof item === 'object')) {\n layout[field_name] = applyNamespaces(item, shared_namespaces);\n }\n }\n return layout;\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 // FIXME: initial attempt to replace this with a more efficient deep clone method caused merge() to break; revisit in future.\n // Replacing this with a proper clone would be the key blocker to allowing functions and non-JSON values (like infinity) in layout objects\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/**\n * Find all references to namespaced fields within a layout object. This is used to validate that a set of provided\n * data adapters will actually give all the information required to draw the plot.\n * @param {Object} layout\n * @param {Array|null} prefixes A list of allowed namespace prefixes. (used to differentiate between real fields,\n * and random sentences that match an arbitrary pattern.\n * @param {RegExp|null} field_finder On recursive calls, pass the regexp we constructed the first time\n * @return {Set}\n */\nfunction findFields(layout, prefixes, field_finder = null) {\n const fields = new Set();\n if (!field_finder) {\n if (!prefixes.length) {\n // A layer that doesn't ask for external data does not need to check if the provider returns expected fields\n return fields;\n }\n const all_ns = prefixes.join('|');\n\n // Locates any reference within a template string to to `ns:field`, `{{ns:field}}`, or `{{#if ns:field}}`.\n // By knowing the list of allowed NS prefixes, we can be much more confident in avoiding spurious matches\n field_finder = new RegExp(`(?:{{)?(?:#if *)?((?:${all_ns}):\\\\w+)`, 'g');\n }\n\n for (const value of Object.values(layout)) {\n const value_type = typeof value;\n let matches = [];\n if (value_type === 'string') {\n let a_match;\n while ((a_match = field_finder.exec(value)) !== null) {\n matches.push(a_match[1]);\n }\n } else if (value !== null && value_type === 'object') {\n matches = findFields(value, prefixes, field_finder);\n } else {\n // Only look for field names in strings or compound values\n continue;\n }\n for (let m of matches) {\n fields.add(m);\n }\n }\n return fields;\n}\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, findFields, 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');\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');\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 7368c255..9f76a52c 100644 --- a/dist/locuszoom.app.min.js +++ b/dist/locuszoom.app.min.js @@ -1,3 +1,3 @@ -/*! 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})(); +/*! Locuszoom 0.14.0 */ +var LocusZoom;(()=>{var t={483:(t,e,s)=>{"use strict";const i=s(919);t.exports=function(t,...e){if(!t){if(1===e.length&&e[0]instanceof Error)throw e[0];throw new i(e)}}},919:(t,e,s)=>{"use strict";const i=s(820);t.exports=class extends Error{constructor(t){super(t.filter((t=>""!==t)).map((t=>"string"==typeof t?t:t instanceof Error?t.message:i(t))).join(" ")||"Unknown error"),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e.assert)}}},820:t=>{"use strict";t.exports=function(...t){try{return JSON.stringify.apply(null,t)}catch(t){return"[Cannot display object: "+t.message+"]"}}},681:(t,e,s)=>{"use strict";const i=s(483),a={};e.B=class{constructor(){this._items=[],this.nodes=[]}add(t,e){const s=[].concat((e=e||{}).before||[]),a=[].concat(e.after||[]),n=e.group||"?",o=e.sort||0;i(!s.includes(n),`Item cannot come before itself: ${n}`),i(!s.includes("?"),"Item cannot come before unassociated items"),i(!a.includes(n),`Item cannot come after itself: ${n}`),i(!a.includes("?"),"Item cannot come after unassociated items"),Array.isArray(t)||(t=[t]);for(const e of t){const t={seq:this._items.length,sort:o,before:s,after:a,group:n,node:e};this._items.push(t)}if(!e.manual){const t=this._sort();i(t,"item","?"!==n?`added into group ${n}`:"","created a dependencies error")}return this.nodes}merge(t){Array.isArray(t)||(t=[t]);for(const e of t)if(e)for(const t of e._items)this._items.push(Object.assign({},t));this._items.sort(a.mergeSort);for(let t=0;tt.sort===e.sort?0:t.sort{function e(t){if("string"==typeof t.source.flags)return t.source.flags;var e=[];return t.global&&e.push("g"),t.ignoreCase&&e.push("i"),t.multiline&&e.push("m"),t.sticky&&e.push("y"),t.unicode&&e.push("u"),e.join("")}t.exports=function t(s){if("function"==typeof s)return s;var i=Array.isArray(s)?[]:{};for(var a in s){var n=s[a],o={}.toString.call(n).slice(8,-1);i[a]="Array"==o||"Object"==o?t(n):"Date"==o?new Date(n.getTime()):"RegExp"==o?RegExp(n.source,e(n)):n}return i}}},e={};function s(i){if(e[i])return e[i].exports;var a=e[i]={exports:{}};return t[i](a,a.exports,s),a.exports}s.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return s.d(e,{a:e}),e},s.d=(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},s.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};(()=>{"use strict";s.d(i,{default:()=>ds});var t={};s.r(t),s.d(t,{AssociationLZ:()=>M,BaseAdapter:()=>$,BaseApiAdapter:()=>z,BaseLZAdapter:()=>k,BaseUMAdapter:()=>E,GeneConstraintLZ:()=>A,GeneLZ:()=>N,GwasCatalogLZ:()=>S,LDServer:()=>O,PheWASLZ:()=>j,RecombLZ:()=>T,StaticSource:()=>L});var e={};s.r(e),s.d(e,{htmlescape:()=>F,is_numeric:()=>H,log10:()=>D,logtoscinotation:()=>U,neglog10:()=>B,scinotation:()=>q,urlencode:()=>G});var a={};s.r(a),s.d(a,{BaseWidget:()=>yt,_Button:()=>ft,display_options:()=>Ot,download:()=>vt,download_png:()=>wt,filter_field:()=>xt,menu:()=>St,move_panel_down:()=>kt,move_panel_up:()=>zt,region_scale:()=>bt,remove_panel:()=>$t,resize_to_data:()=>Nt,set_state:()=>Tt,shift_region:()=>Et,title:()=>mt,toggle_legend:()=>At,zoom_region:()=>Mt});var n={};s.r(n),s.d(n,{categorical_bin:()=>Vt,effect_direction:()=>Qt,if_value:()=>Zt,interpolate:()=>Xt,numerical_bin:()=>Kt,ordinal_cycle:()=>Wt,stable_choice:()=>Yt});var o={};s.r(o),s.d(o,{BaseDataLayer:()=>ie,annotation_track:()=>ne,arcs:()=>he,category_scatter:()=>me,genes:()=>de,highlight_regions:()=>re,line:()=>_e,orthogonal_line:()=>ge,scatter:()=>fe});var r={};s.r(r),s.d(r,{data_layer:()=>es,panel:()=>ss,plot:()=>is,toolbar:()=>ts,toolbar_widgets:()=>Qe,tooltip:()=>Xe});const l="0.14.0";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}}class d{constructor(t,e,s={},i=null,a=null){this.key=t,this.value=e,this.metadata=s,this.prev=i,this.next=a}}class u{constructor(t=3){if(this._max_size=t,this._cur_size=0,this._store=new Map,this._head=null,this._tail=null,null===t||t<0)throw new Error('Cache "max_size" must be >= 0')}has(t){return this._store.has(t)}get(t){const e=this._store.get(t);return e?(this._head!==e&&this.add(t,e.value),e.value):null}add(t,e,s={}){if(0===this._max_size)return;const i=this._store.get(t);i&&this._remove(i);const a=new d(t,e,s,null,this._head);if(this._head?this._head.prev=a:this._tail=a,this._head=a,this._store.set(t,a),this._max_size>=0&&this._cur_size>=this._max_size){const t=this._tail;this._tail=this._tail.prev,this._remove(t)}this._cur_size+=1}clear(){this._head=null,this._tail=null,this._cur_size=0,this._store=new Map}remove(t){const e=this._store.get(t);return!!e&&(this._remove(e),!0)}_remove(t){null!==t.prev?t.prev.next=t.next:this._head=t.next,null!==t.next?t.next.prev=t.prev:this._tail=t.prev,this._store.delete(t.key),this._cur_size-=1}find(t){let e=this._head;for(;e;){const s=e.next;if(t(e))return e;e=s}}}var _=s(957),p=s.n(_);function g(t){return"object"!=typeof t?t:p()(t)}var y=s(681);function f(t,e,s,i=!0){if(!s.length)return[];const a=s.map((t=>function(t){const e=/^(?\w+)$|((?\w+)+\(\s*(?[^)]+?)\s*\))/.exec(t);if(!e)throw new Error(`Unable to parse dependency specification: ${t}`);let{name_alone:s,name_deps:i,deps:a}=e.groups;return s?[s,[]]:(a=a.split(/\s*,\s*/),[i,a])}(t))),n=new Map(a),o=new y.B;for(let[t,e]of n.entries())try{o.add(t,{after:e,group:t})}catch(e){throw new Error(`Invalid or possible circular dependency specification for: ${t}`)}const r=o.nodes,l=new Map;for(let s of r){const i=e.get(s);if(!i)throw new Error(`Data has been requested from source '${s}', but no matching source was provided`);const a=n.get(s)||[],o=Promise.all(a.map((t=>l.get(t)))).then((e=>{const a=Object.assign({_provider_name:s},t);return i.getData(a,...e)}));l.set(s,o)}return Promise.all([...l.values()]).then((t=>i?t[t.length-1]:t))}function m(t,e){const s=new Map;for(let i of t){const t=i[e];if(void 0===t)throw new Error(`All records must specify a value for the field "${e}"`);if("object"==typeof t)throw new Error("Attempted to group on a field with non-primitive values");let a=s.get(t);a||(a=[],s.set(t,a)),a.push(i)}return s}function b(t,e,s,i,a){const n=m(s,a),o=[];for(let s of e){const e=s[i],a=n.get(e)||[];a.length?o.push(...a.map((t=>Object.assign({},g(t),g(s))))):"inner"!==t&&o.push(g(s))}if("outer"===t){const t=m(e,i);for(let e of s){const s=e[a];(t.get(s)||[]).length||o.push(g(e))}}return o}function x(t,e,s,i){return b("left",...arguments)}const v=/^(?:chr)?([a-zA-Z0-9]+?)[_:-](\d+)[_:|-]?(\w+)?[/_:|-]?([^_]+)?_?(.*)?/;function w(t,e=!1){const s=t&&t.match(v);if(s)return s.slice(1);if(e)return null;throw new Error(`Could not understand marker format for ${t}. Should be of format chr:pos or chr:pos_ref/alt`)}class ${constructor(){throw new Error('The "BaseAdapter" and "BaseApiAdapter" classes have been replaced in LocusZoom 0.14. See migration guide for details.')}}class z extends ${}class k extends class extends class{constructor(t={}){this._config=t;const{cache_enabled:e=!0,cache_size:s=3}=t;this._enable_cache=e,this._cache=new u(s)}_buildRequestOptions(t,e){return Object.assign({},t)}_getCacheKey(t){if(this._enable_cache)throw new Error("Method not implemented");return null}_performRequest(t){throw new Error("Not implemented")}_normalizeResponse(t,e){return t}_annotateRecords(t,e){return t}_postProcessResponse(t,e){return t}getData(t={},...e){t=this._buildRequestOptions(t,...e);const s=this._getCacheKey(t);let i;return this._enable_cache&&this._cache.has(s)?i=this._cache.get(s):(i=Promise.resolve(this._performRequest(t)).then((e=>this._normalizeResponse(e,t))),this._cache.add(s,i,t._cache_meta),i.catch((t=>this._cache.remove(s)))),i.then((t=>g(t))).then((e=>this._annotateRecords(e,t))).then((e=>this._postProcessResponse(e,t)))}}{constructor(t={}){super(t),this._url=t.url}_getCacheKey(t){return this._getURL(t)}_getURL(t){return this._url}_performRequest(t){const e=this._getURL(t);if(!this._url)throw new Error('Web based resources must specify a resource URL as option "url"');return fetch(e).then((t=>{if(!t.ok)throw new Error(t.statusText);return t.text()}))}_normalizeResponse(t,e){return"string"==typeof t?JSON.parse(t):t}}{constructor(t={}){t.params&&(console.warn('Deprecation warning: all options in "config.params" should now be specified as top level keys.'),Object.assign(t,t.params||{}),delete t.params),super(t);const{prefix_namespace:e=!0,limit_fields:s}=t;this._prefix_namespace=e,this._limit_fields=!!s&&new Set(s)}_getCacheKey(t){let{chr:e,start:s,end:i}=t;const a=this._cache.find((({metadata:t})=>e===t.chr&&s>=t.start&&i<=t.end));return a&&({chr:e,start:s,end:i}=a.metadata),t._cache_meta={chr:e,start:s,end:i},`${e}_${s}_${i}`}_postProcessResponse(t,e){if(!this._prefix_namespace||!Array.isArray(t))return t;const{_limit_fields:s}=this,{_provider_name:i}=e;return t.map((t=>Object.entries(t).reduce(((t,[e,a])=>(s&&!s.has(e)||(t[`${i}:${e}`]=a),t)),{})))}_findPrefixedKey(t,e){const s=new RegExp(`:${e}$`),i=Object.keys(t).find((t=>s.test(t)));if(!i)throw new Error(`Could not locate the required key name: ${e} in dependent data`);return i}}class E extends k{constructor(t={}){super(t),this._genome_build=t.genome_build||t.build}_validateBuildSource(t,e){if(t&&e||!t&&!e)throw new Error(`${this.constructor.name} must provide a parameter specifying either "build" or "source". It should not specify both.`);if(t&&!["GRCh37","GRCh38"].includes(t))throw new Error(`${this.constructor.name} must specify a valid 'genome_build'`)}_normalizeResponse(t,e){let s=super._normalizeResponse(...arguments);if(s=s.data||s,Array.isArray(s))return s;const i=Object.keys(s),a=s[i[0]].length;if(!i.every((function(t){return s[t].length===a})))throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`);const n=[],o=Object.keys(s);for(let t=0;t25||"GRCh38"===s)return Promise.resolve([]);e=`{${e.join(" ")} }`;const i=this._getURL(t),a=JSON.stringify({query:e});return fetch(i,{method:"POST",body:a,headers:{"Content-Type":"application/json"}}).then((t=>t.ok?t.text():[])).catch((t=>[]))}_normalizeResponse(t){if("string"!=typeof t)return t;return JSON.parse(t).data}}class O extends E{constructor(t){t.limit_fields||(t.limit_fields=["variant2","position2","correlation"]),super(t)}__find_ld_refvar(t,e){const s=this._findPrefixedKey(e[0],"variant"),i=this._findPrefixedKey(e[0],"log_pvalue");let a,n={};if(t.ldrefvar)a=t.ldrefvar,n=e.find((t=>t[s]===a))||{};else{let t=0;for(let o of e){const{[s]:e,[i]:r}=o;r>t&&(t=r,a=e,n=o)}}n.lz_is_ld_refvar=!0;const o=w(a,!0);if(!o)throw new Error("Could not request LD for a missing or incomplete marker format");const[r,l,h,c]=o;a=`${r}:${l}`,h&&c&&(a+=`_${h}/${c}`);const d=+l;return d&&t.ldrefvar&&t.chr&&(r!==String(t.chr)||dt.end)?(t.ldrefvar=null,this.__find_ld_refvar(t,e)):a}_buildRequestOptions(t,e){if(!e)throw new Error("LD request must depend on association data");const s=super._buildRequestOptions(...arguments);if(!e.length)return s._skip_request=!0,s;s.ld_refvar=this.__find_ld_refvar(t,e);const i=t.genome_build||this._config.build||"GRCh37";let a=t.ld_source||this._config.source||"1000G";const n=t.ld_pop||this._config.population||"ALL";return"1000G"===a&&"GRCh38"===i&&(a="1000G-FRZ09"),this._validateBuildSource(i,null),Object.assign({},s,{genome_build:i,ld_source:a,ld_population:n})}_getURL(t){const e=this._config.method||"rsquare",{chr:s,start:i,end:a,ld_refvar:n,genome_build:o,ld_source:r,ld_population:l}=t;return[super._getURL(t),"genome_builds/",o,"/references/",r,"/populations/",l,"/variants","?correlation=",e,"&variant=",encodeURIComponent(n),"&chrom=",encodeURIComponent(s),"&start=",encodeURIComponent(i),"&stop=",encodeURIComponent(a)].join("")}_getCacheKey(t){const e=super._getCacheKey(t),{ld_refvar:s,ld_source:i,ld_population:a}=t;return`${e}_${s}_${i}_${a}`}_performRequest(t){if(t._skip_request)return Promise.resolve([]);const e=this._getURL(t);let s={data:{}},i=function(t){return fetch(t).then().then((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){s.data[e]=(s.data[e]||[]).concat(t.data[e])})),t.next?i(t.next):s}))};return i(e)}}class T extends E{constructor(t){t.limit_fields||(t.limit_fields=["position","recomb_rate"]),super(t)}_getURL(t){const e=t.genome_build||this._config.build;let s=this._config.source;this._validateBuildSource(e,s);const i=e?`&build=${e}`:` and id in ${s}`;return`${super._getURL(t)}?filter=chromosome eq '${t.chr}' and position le ${t.end} and position ge ${t.start}${i}`}}class L extends k{constructor(t={}){super(...arguments);const{data:e}=t;if(!e||Array.isArray(t))throw new Error("'StaticSource' must provide data as required option 'config.data'");this._data=e}_performRequest(t){return Promise.resolve(this._data)}}class j extends E{_getURL(t){const e=(t.genome_build?[t.genome_build]:null)||this._config.build;if(!e||!Array.isArray(e)||!e.length)throw new Error(["Adapter",this.constructor.name,"requires that you specify array of one or more desired genome build names"].join(" "));return[super._getURL(t),"?filter=variant eq '",encodeURIComponent(t.variant),"'&format=objects&",e.map((function(t){return`build=${encodeURIComponent(t)}`})).join("&")].join("")}_getCacheKey(t){return this._getURL(t)}}const P=new c;for(let[e,s]of Object.entries(t))P.add(e,s);P.add("StaticJSON",L),P.add("LDLZ2",O);const R=P,I=d3,C={verbs:["highlight","select","fade","hide"],adjectives:["highlighted","selected","faded","hidden"]};function D(t){return isNaN(t)||t<=0?null:Math.log(t)/Math.LN10}function B(t){return isNaN(t)||t<=0?null:-Math.log(t)/Math.LN10}function U(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 q(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 F(t){return t?(t=`${t}`).replace(/['"<>&`]/g,(function(t){switch(t){case"'":return"'";case'"':return""";case"<":return"<";case">":return">";case"&":return"&";case"`":return"`"}})):""}function H(t){return"number"==typeof t}function G(t){return encodeURIComponent(t)}const J=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,s]of Object.entries(e))J.add(t,s);const Z=J;class K{constructor(t){if(!/^(?:\w+:\w+|^\w+)(?:\|\w+)*$/.test(t))throw new Error(`Invalid field specifier: '${t}'`);const[e,...s]=t.split("|");this.full_name=t,this.field_name=e,this.transformations=s.map((t=>Z.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.field_name]?s=t[this.field_name]:e&&void 0!==e[this.field_name]&&(s=e[this.field_name]),t[this.full_name]=this._applyTransformations(s)}return t[this.full_name]}}const V=/^(\*|[\w]+)/,W=/^\[\?\(@((?:\.[\w]+)+) *===? *([0-9.eE-]+|"[^"]*"|'[^']*')\)\]/;function Y(t){if(".."===t.substr(0,2)){if("["===t[2])return{text:"..",attr:"*",depth:".."};const e=V.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=V.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=W.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 X(t,e){let s;for(let i of e)s=t,t=t[i];return[s,e[e.length-1],t]}function Q(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(...Q(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(...Q(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(...Q(t[s.attr],i).map((t=>[s.attr].concat(t))));for(let[n,o]of Object.entries(t))a.push(...Q(o,e).map((t=>[n].concat(t)))),"*"===s.attr&&a.push(...Q(o,i).map((t=>[n].concat(t))))}}else if(s.attrs)for(let[e,n]of Object.entries(t)){const[t,o,r]=X(n,s.attrs);r===s.value&&a.push(...Q(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 tt(t,e){const s=function(t,e){let s=[];for(let i of Q(t,e))s.push(X(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=Y(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 et=Math.sqrt(3),st={draw(t,e){const s=-Math.sqrt(e/(3*et));t.moveTo(0,2*-s),t.lineTo(-et*s,s),t.lineTo(et*s,s),t.closePath()}};function it(t,e){if(e=e||{},!t||"object"!=typeof t||"object"!=typeof e)throw new Error("Layout and shared namespaces must be provided as objects");for(let[s,i]of Object.entries(t))"namespace"===s?Object.keys(i).forEach((t=>{const s=e[t];s&&(i[t]=s)})):null!==i&&"object"==typeof i&&(t[s]=it(i,e));return t}function at(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]=at(t[s],e[s])):t[s]=nt(e[s])}return t}function nt(t){return JSON.parse(JSON.stringify(t))}function ot(t){if(!t)return null;if("triangledown"===t)return st;const e=`symbol${t.charAt(0).toUpperCase()+t.slice(1)}`;return I[e]||null}function rt(t,e,s=null){const i=new Set;if(!s){if(!e.length)return i;const t=e.join("|");s=new RegExp(`(?:{{)?(?:#if *)?((?:${t}):\\w+)`,"g")}for(const a of Object.values(t)){const t=typeof a;let n=[];if("string"===t){let t;for(;null!==(t=s.exec(a));)n.push(t[1])}else{if(null===a||"object"!==t)continue;n=rt(a,e,s)}for(let t of n)i.add(t)}return i}function lt(t,e,s,i=!0){const a=typeof t;if(Array.isArray(t))return t.map((t=>lt(t,e,s,i)));if("object"===a&&null!==t)return Object.keys(t).reduce(((a,n)=>(a[n]=lt(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 ht(t,e,s){return function(t,e,s){return tt(t,e).map((([t,e,i])=>{const a="function"==typeof s?s(i):s;return t[e]=a,a}))}(t,e,s)}function ct(t,e){return function(t,e){return tt(t,e).map((t=>t[2]))}(t,e)}class dt{constructor(t,e,s){this._callable=ls.get(t),this._initiator=e,this._params=s||[]}getData(t,...e){const s={plot_state:t,data_layer:this._initiator};return Promise.resolve(this._callable(s,e,...this._params))}}const ut=class{constructor(t){this._sources=t}config_to_sources(t={},e=[],s){const i=new Map,a=Object.keys(t);let n=e.find((t=>"fetch"===t.type));n||(n={type:"fetch",from:a},e.unshift(n));const o=/^\w+$/;for(let[e,s]of Object.entries(t)){if(!o.test(e))throw new Error(`Invalid namespace name: '${e}'. Must contain only alphanumeric characters`);const t=this._sources.get(s);if(!t)throw new Error(`A data layer has requested an item not found in DataSources: data type '${e}' from ${s}`);i.set(e,t),n.from.find((t=>t.split("(")[0]===e))||n.from.push(e)}let r=Array.from(n.from);for(let t of e){let{type:e,name:a,requires:n,params:o}=t;if("fetch"!==e){let l=0;if(a||(a=t.name=`join${l}`,l+=1),i.has(a))throw new Error(`Configuration error: within a layer, join name '${a}' must be unique`);n.forEach((t=>{if(!i.has(t))throw new Error(`Data operation cannot operate on unknown provider '${t}'`)}));const h=new dt(e,s,o);i.set(a,h),r.push(`${a}(${n.join(", ")})`)}}return[i,r]}getData(t,e,s){return s.length?f(t,e,s,!0):Promise.resolve([])}};function _t(){return{showing:!1,selector:null,content_selector:null,hide_delay:null,show:(t,e)=>(this.curtain.showing||(this.curtain.selector=I.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&>(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 pt(){return{showing:!1,selector:null,content_selector:null,progress_selector:null,cancel_selector:null,show:t=>(this.loader.showing||(this.loader.selector=I.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 gt(t,e){e=e||{};for(let[s,i]of Object.entries(e))t.style(s,i)}class yt{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&>(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 ft{constructor(t){if(!(t instanceof yt))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=I.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),_=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",`${_}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(gt,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 mt extends yt{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 bt extends yt{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(qt(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&>(this.selector,this.layout.style),this}}class xt extends yt{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 vt extends yt{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 ft(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=I.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*+I.select(this).attr("dy").substring(-2).slice(0,-2);I.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 wt extends vt{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 $t extends yt{update(){return this.button||(this.button=new ft(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),I.select(t.parent.svg.node().parentNode).on(`mouseover.${t.getBaseId()}.toolbar`,null),I.select(t.parent.svg.node().parentNode).on(`mouseout.${t.getBaseId()}.toolbar`,null),t.parent.removePanel(t.id)})),this.button.show()),this}}class zt extends yt{update(){if(this.button){const t=0===this.parent_panel.layout.y_index;return this.button.disable(t),this}return this.button=new ft(this).setColor(this.layout.color).setHtml("▴").setTitle("Move panel up").setOnclick((()=>{this.parent_panel.moveUp(),this.update()})),this.button.show(),this.update()}}class kt extends yt{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 ft(this).setColor(this.layout.color).setHtml("▾").setTitle("Move panel down").setOnclick((()=>{this.parent_panel.moveDown(),this.update()})),this.button.show(),this.update()}}class Et extends yt{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?"+":"-"}${qt(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 ft(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 Mt extends yt{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 ft(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 St extends yt{update(){return this.button||(this.button=new ft(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 Nt extends yt{constructor(t){super(...arguments)}update(){return this.button||(this.button=new ft(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 At extends yt{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 ft(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 Ot extends yt{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]=nt(e))})),this._selected_item="default",this.button=new ft(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 Tt extends yt{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 ft(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 Lt=new c;for(let[t,e]of Object.entries(a))Lt.add(t,e);const jt=Lt;class Pt{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.toolbar.widgets;return Array.isArray(t)&&t.forEach((t=>{this.addWidget(t)})),"panel"===this.type&&I.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}addWidget(t){try{const e=jt.create(t.type,t,this);return this.widgets.push(e),e}catch(t){console.warn("Failed to create widget"),console.error(t)}}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=I.select(this.parent.svg.node().parentNode).insert("div",":first-child");break;case"panel":this.selector=I.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 Rt={orientation:"vertical",origin:{x:0,y:0},width:10,height:10,padding:5,label_size:14,hidden:!1};class It{constructor(t){return this.parent=t,this.id=`${this.parent.getBaseId()}.legend`,this.parent.layout.legend=at(this.parent.layout.legend||{},Rt),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=>{const n=this.parent.data_layers[a].layout.legend;Array.isArray(n)&&n.forEach((a=>{const n=this.elements_group.append("g").attr("transform",`translate(${e}, ${s})`),o=+a.label_size||+this.layout.label_size;let r=0,l=o/2+t/2;i=Math.max(i,o+t);const h=a.shape||"",c=ot(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(gt,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(gt,a.style||{}),r=e+t,i=Math.max(i,s+t)}else if("ribbon"===h){const e=+a.width||25,s=+a.height||e,i="horizontal"===(a.orientation||"vertical");let o=a.color_stops;const h=n.append("g"),c=h.append("g"),d=h.append("g");let u=0;if(a.tick_labels){let t;t=i?[0,e*o.length-1]:[s*o.length-1,0];const n=I.scaleLinear().domain(I.extent(a.tick_labels)).range(t),r=(i?I.axisTop:I.axisRight)(n).tickSize(3).tickValues(a.tick_labels).tickFormat((t=>t));d.call(r).attr("class","lz-axis"),u=d.node().getBoundingClientRect().height}i?(d.attr("transform",`translate(0, ${u})`),c.attr("transform",`translate(0, ${u})`)):(h.attr("transform","translate(5, 0)"),d.attr("transform",`translate(${e}, 0)`)),i||(o=o.slice(),o.reverse());for(let t=0;tt&&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 Ct={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 Dt{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)throw new Error('Panel layouts must specify "id"');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`);this.id=t.id,this._initialized=!1,this._layout_idx=null,this.svg={},this.layout=at(t||{},Ct),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=at(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(gt,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=xe.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){const e=this.data_layers[t];if(!e)throw new Error(`Unable to remove data layer, ID not found: ${t}`);return e.destroyAllTooltips(),e.svg.container&&e.svg.container.remove(),this.layout.data_layers.splice(e._layout_idx,1),delete this.state[e._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);const{cliparea:t}=this.layout,{margin:e}=this.layout;this.inner_border.attr("x",e.left).attr("y",e.top).attr("width",this.parent_plot.layout.width-(e.left+e.right)).attr("height",this.layout.height-(e.top+e.bottom)),this.layout.inner_border&&this.inner_border.style("stroke-width",1).style("stroke",this.layout.inner_border),this.setTitle(),this.generateExtents();const s=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},i={},a=this.layout.axes;if(this.x_extent){const t={start:0,end:this.layout.cliparea.width};a.x.range&&(t.start=a.x.range.start||t.start,t.end=a.x.range.end||t.end),i.x=[t.start,t.end],i.x_shifted=[t.start,t.end]}if(this.y1_extent){const e={start:t.height,end:0};a.y1.range&&(e.start=a.y1.range.start||e.start,e.end=a.y1.range.end||e.end),i.y1=[e.start,e.end],i.y1_shifted=[e.start,e.end]}if(this.y2_extent){const e={start:t.height,end:0};a.y2.range&&(e.start=a.y2.range.start||e.start,e.end=a.y2.range.end||e.end),i.y2=[e.start,e.end],i.y2_shifted=[e.start,e.end]}let{_interaction:n}=this.parent;const o=n.dragging;if(n.panel_id&&(n.panel_id===this.id||n.linked_panel_ids.includes(this.id))){let a,r=null;if(n.zooming&&"function"==typeof this.x_scale){const s=Math.abs(this.x_extent[1]-this.x_extent[0]),o=Math.round(this.x_scale.invert(i.x_shifted[1]))-Math.round(this.x_scale.invert(i.x_shifted[0]));let r=n.zooming.scale;const l=Math.floor(o*(1/r));r<1&&!isNaN(this.parent.layout.max_region_scale)?r=1/(Math.min(l,this.parent.layout.max_region_scale)/o):r>1&&!isNaN(this.parent.layout.min_region_scale)&&(r=1/(Math.max(l,this.parent.layout.min_region_scale)/o));const h=Math.floor(s*r);a=n.zooming.center-e.left-this.layout.origin.x;const c=a/t.width,d=Math.max(Math.floor(this.x_scale.invert(i.x_shifted[0])-(h-o)*c),1);i.x_shifted=[this.x_scale(d),this.x_scale(d+h)]}else if(o)switch(o.method){case"background":i.x_shifted[0]=+o.dragged_x,i.x_shifted[1]=t.width+o.dragged_x;break;case"x_tick":I.event&&I.event.shiftKey?(i.x_shifted[0]=+o.dragged_x,i.x_shifted[1]=t.width+o.dragged_x):(a=o.start_x-e.left-this.layout.origin.x,r=s(a/(a+o.dragged_x),3),i.x_shifted[0]=0,i.x_shifted[1]=Math.max(t.width*(1/r),1));break;case"y1_tick":case"y2_tick":{const n=`y${o.method[1]}_shifted`;I.event&&I.event.shiftKey?(i[n][0]=t.height+o.dragged_y,i[n][1]=+o.dragged_y):(a=t.height-(o.start_y-e.top-this.layout.origin.y),r=s(a/(a-o.dragged_y),3),i[n][0]=t.height,i[n][1]=t.height-t.height*(1/r))}}}if(["x","y1","y2"].forEach((t=>{this[`${t}_extent`]&&(this[`${t}_scale`]=I.scaleLinear().domain(this[`${t}_extent`]).range(i[`${t}_shifted`]),this[`${t}_extent`]=[this[`${t}_scale`].invert(i[t][0]),this[`${t}_scale`].invert(i[t][1])],this[`${t}_scale`]=I.scaleLinear().domain(this[`${t}_extent`]).range(i[t]),this.renderAxis(t))})),this.layout.interaction.scroll_to_zoom){const t=()=>{if(!I.event.shiftKey&&!I.event.altKey)return void(this.parent._canInteract(this.id)&&this.loader.show("Press [SHIFT] or [ALT] while scrolling to zoom").hide(1e3));if(I.event.preventDefault(),!this.parent._canInteract(this.id))return;const t=I.mouse(this.svg.container.node()),e=Math.max(-1,Math.min(1,I.event.wheelDelta||-I.event.detail||-I.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(),n=this.parent._interaction,n.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=>{const e=this.layout.axes[t];Object.keys(e).length&&!1!==e.render?(e.render=!0,e.label=e.label||null):e.render=!1})),this.layout.data_layers.forEach((t=>{this.addDataLayer(t)})),this}setDimensions(t,e){const s=this.layout;return void 0!==t&&void 0!==e&&!isNaN(t)&&t>=0&&!isNaN(e)&&e>=0&&(this.parent.layout.width=Math.round(+t),s.height=Math.max(Math.round(+e),s.min_height)),s.cliparea.width=Math.max(this.parent_plot.layout.width-(s.margin.left+s.margin.right),0),s.cliparea.height=Math.max(s.height-(s.margin.top+s.margin.bottom),0),this.svg.clipRect&&this.svg.clipRect.attr("width",this.parent.layout.width).attr("height",s.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;const{cliparea:n,margin:o}=this.layout;return!isNaN(t)&&t>=0&&(o.top=Math.max(Math.round(+t),0)),!isNaN(e)&&e>=0&&(o.right=Math.max(Math.round(+e),0)),!isNaN(s)&&s>=0&&(o.bottom=Math.max(Math.round(+s),0)),!isNaN(i)&&i>=0&&(o.left=Math.max(Math.round(+i),0)),o.top+o.bottom>this.layout.height&&(a=Math.floor((o.top+o.bottom-this.layout.height)/2),o.top-=a,o.bottom-=a),o.left+o.right>this.parent_plot.layout.width&&(a=Math.floor((o.left+o.right-this.parent_plot.layout.width)/2),o.left-=a,o.right-=a),["top","right","bottom","left"].forEach((t=>{o[t]=Math.max(o[t],0)})),n.width=Math.max(this.parent_plot.layout.width-(o.left+o.right),0),n.height=Math.max(this.layout.height-(o.top+o.bottom),0),n.origin.x=o.left,n.origin.y=o.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=_t.call(this),this.loader=pt.call(this),this.layout.show_loading_indicator&&this.addBasicLoader(!1),this.toolbar=new Pt(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 It(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(I.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(){const{parent:t}=this,e=this.layout.y_index;return t._panel_ids_by_y_index[e-1]&&(t._panel_ids_by_y_index[e]=t._panel_ids_by_y_index[e-1],t._panel_ids_by_y_index[e-1]=this.id,t.applyPanelYIndexesToPanelLayouts(),t.positionPanels()),this}moveDown(){const{_panel_ids_by_y_index:t}=this.parent;return t[this.layout.y_index+1]&&(t[this.layout.y_index]=t[this.layout.y_index+1],t[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=I.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`]=I.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=at(s,e),at(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&&(_=parseFloat(_.toFixed(c)));u.push(_),(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;eqt(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=I.selectAll(`g#${this.getBaseId().replace(".","\\.")}\\.${t}_axis g.tick`),s=this;e.each((function(e,i){const a=I.select(this).select("text");s[`${t}_ticks`][i].style&>(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(Ht(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 I.select(this).node().focus&&I.select(this).node().focus();let i="x"===t?"ew-resize":"ns-resize";I.event&&I.event.shiftKey&&(i="move"),I.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(){I.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)}))}}C.verbs.forEach(((t,e)=>{const s=C.adjectives[e],i=`un${t}`;Dt.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},Dt.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const Bt={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 Ut{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,at(this.layout,Bt),this._base_layout=nt(this.layout),this.state=this.layout.state,this.lzd=new ut(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 Dt(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){const e=this.panels[t];if(!e)throw new Error(`Unable to remove panel, ID not found: ${t}`);return this._panel_boundaries.hide(),this.clearPanelData(t),e.loader.hide(),e.toolbar.destroy(!0),e.curtain.hide(),e.svg.container&&e.svg.container.remove(),this.layout.panels.splice(e._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){const{from_layer:s,namespace:i,data_operations:a,onerror:n}=t,o=n||function(t){console.error("An error occurred while acting on an external callback",t)};if(s){const t=`${this.getBaseId()}.`,i=s.startsWith(t)?s:`${t}${s}`;let a=!1;for(let t of Object.values(this.panels))if(a=Object.values(t.data_layers).some((t=>t.getBaseId()===i)),a)break;if(!a)throw new Error(`Could not subscribe to unknown data layer ${i}`);const n=t=>{if(t.data.layer===i)try{e(t.data.content,this)}catch(t){o(t)}};return this.on("data_from_layer",n),n}if(!i)throw new Error("subscribeToData must specify the desired data: either 'from_layer' or 'namespace' option");const[r,l]=this.lzd.config_to_sources(i,a),h=()=>{try{this.lzd.getData(this.state,r,l).then((t=>e(t,this))).catch(o)}catch(t){o(t)}};return this.on("data_rendered",h),h}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}mutateLayout(){Object.values(this.panels).forEach((t=>{Object.values(t.data_layers).forEach((t=>t.mutateLayout()))}))}_canInteract(t){t=t||null;const{_interaction:e}=this;return t?(void 0===e.panel_id||e.panel_id===t)&&!this.loading_data:!(e.dragging||e.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"!==I.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");return this.layout.responsive_resize=!!this.layout.responsive_resize,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 of Object.values(this.panels))e.layout.interaction.x_linked&&(t.left=Math.max(t.left,e.layout.margin.left),t.right=Math.max(t.right,e.layout.margin.right));let e=0;return this._panel_ids_by_y_index.forEach((s=>{const i=this.panels[s],a=i.layout;if(i.setOrigin(0,e),e+=this.panels[s].layout.height,a.interaction.x_linked){const e=Math.max(t.left-a.margin.left,0)+Math.max(t.right-a.margin.right,0);a.width+=e,a.margin.left=t.left,a.margin.right=t.right,a.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){I.select(this.container).classed("lz-container-responsive",!0);const t=()=>window.requestAnimationFrame((()=>this.rescaleSVG()));if(window.addEventListener("resize",t),this.trackExternalListener(window,"resize",t),"undefined"!=typeof IntersectionObserver){const t={root:document.documentElement,threshold:.9};new IntersectionObserver(((t,e)=>{t.some((t=>t.intersectionRatio>0))&&this.rescaleSVG()}),t).observe(this.container)}const e=()=>this.setDimensions();window.addEventListener("load",e),this.trackExternalListener(window,"load",e)}if(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=_t.call(this),this.loader=pt.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=I.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=I.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+I.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=I.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=I.drag();e.on("start",(()=>{this.dragging=!0})),e.on("end",(()=>{this.dragging=!1})),e.on("drag",(()=>{this.parent.setDimensions(this.parent.layout.width+I.event.dx,this.parent._total_height+I.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&&I.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 Pt(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=I.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=()=>{const{_interaction:t}=this;if(t.dragging){const e=I.mouse(this.svg.node());I.event&&I.event.preventDefault(),t.dragging.dragged_x=e[0]-t.dragging.start_x,t.dragging.dragged_y=e[1]-t.dragging.start_y,this.panels[t.panel_id].render(),t.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=I.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 Dt&&s&&this._canInteract()))return this.stopDrag();const i=I.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(){const{_interaction:t}=this;if(!t.dragging)return this;if("object"!=typeof this.panels[t.panel_id])return this._interaction={},this;const e=this.panels[t.panel_id],s=(t,s,i)=>{e._data_layer_ids_by_z_index.forEach((a=>{const n=e.data_layers[a].layout[`${t}_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(t.dragging.method){case"background":case"x_tick":0!==t.dragging.dragged_x&&(s("x",1,e.x_extent),this.applyState({start:e.x_extent[0],end:e.x_extent[1]}));break;case"y1_tick":case"y2_tick":if(0!==t.dragging.dragged_y){const i=parseInt(t.dragging.method[1]);s("y",i,e[`y${i}_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 qt(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 Ft(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 Ht(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 )?([\w+_:|]+)|(#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 K(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 Gt=new h;Gt.add("=",((t,e)=>t===e)),Gt.add("!=",((t,e)=>t!=e)),Gt.add("<",((t,e)=>tt<=e)),Gt.add(">",((t,e)=>t>e)),Gt.add(">=",((t,e)=>t>=e)),Gt.add("%",((t,e)=>t%e)),Gt.add("in",((t,e)=>e&&e.includes(t))),Gt.add("match",((t,e)=>t&&t.includes(e)));const Jt=Gt,Zt=(t,e)=>void 0===e||t.field_value!==e?void 0!==t.else?t.else:null:t.then,Kt=(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,Wt=(t,e,s)=>{const i=t.values;return i[s%i.length]};let Yt=(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)?I.interpolate(i[n-1],i[n])(t):a}};function Qt(t,e){if(void 0===e)return null;const{beta_field:s,stderr_beta_field:i,"+":a=null,"-":n=null}=t;if(!s||!i)throw new Error("effect_direction must specify how to find required 'beta' and 'stderr_beta' fields");const o=e[s],r=e[i];if(void 0!==o)if(void 0!==r){if(o-1.96*r>0)return a;if(o+1.96*r<0)return n||null}else{if(o>0)return a;if(o<0)return n}return null}const te=new h;for(let[t,e]of Object.entries(n))te.add(t,e);te.add("if",Zt);const ee=te,se={id:"",type:"",tag:"custom_data_type",namespace:{},data_operations:[],id_field:"id",filters:null,match:{},x_axis:{},y_axis:{},legend:null,tooltip:{},tooltip_positioning:"horizontal",behaviors:{}};class ie{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=at(t||{},se),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=nt(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},this._data_contract=new Set,this._entities=new Map,this._dependencies=[],this.mutateLayout()}render(){throw new Error("Method must be implemented")}moveForward(){const t=this.parent._data_layer_ids_by_z_index,e=this.layout.z_index;return t[e+1]&&(t[e]=t[e+1],t[e+1]=this.id,this.parent.resortDataLayers()),this}moveBack(){const t=this.parent._data_layer_ids_by_z_index,e=this.layout.z_index;return t[e-1]&&(t[e]=t[e-1],t[e-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}mutateLayout(){if(this.parent_plot){const{namespace:t,data_operations:e}=this.layout;this._data_contract=rt(this.layout,Object.keys(t));const[s,i]=this.parent_plot.lzd.config_to_sources(t,e,this);this._entities=s,this._dependencies=i}}_getDataExtent(t,e){return t=t||this.data,I.extent(t,(t=>+new K(e.field).resolve(t)))}getElementId(t){const e=Symbol.for("lzID");if(t[e])return t[e];const s=this.layout.id_field;let i=t[s];if(void 0===i&&/{{[^{}]*}}/.test(s)&&(i=Ht(s,t,{})),null==i)throw new Error("Unable to generate element ID");const a=i.toString().replace(/\W/g,""),n=`${this.getBaseId()}-${a}`.replace(/([:.[\],])/g,"_");return t[e]=n,n}getElementStatusNodeId(t){return null}getElementById(t){const e=I.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=Jt.get(this.layout.match&&this.layout.match.operator||"="),s=this.parent_plot.state.lz_match_value,i=t?new K(t):null;if(this.data.length&&this._data_contract.size){const t=new Set(this._data_contract);for(let e of this.data)if(Object.keys(e).forEach((e=>t.delete(e))),!t.size)break;t.size&&console.debug(`Data layer '${this.getBaseId()}' did not receive all expected fields from retrieved data. Missing fields are: ${[...t]}\n Common reasons for this error include API payloads with missing fields, or data layer layouts that use two kinds of data and need join logic in "data_operations" \n If this field is optional, you can safely ignore this message. Examples include {{#if value}} tags or conditional color rules.\n`)}return this.data.forEach(((a,n)=>{t&&null!=s&&(a.lz_is_match=e(i.resolve(a),s)),a.getDataLayer=()=>this,a.getPanel=()=>this.parent||null,a.getPlot=()=>{const t=this.parent;return t?t.parent:null}})),this.applyCustomDataMethods(),this}applyCustomDataMethods(){return this}resolveScalableParameter(t,e,s){let i=null;if(Array.isArray(t)){let a=0;for(;null===i&&ad-(p+v)?"top":"bottom"):"horizontal"===w&&(v=0,w=_<=r.width/2?"left":"right"),"top"===w||"bottom"===w){const t=Math.max(c.width/2-_,0),e=Math.max(c.width/2+_-u,0);y=h.x+_-c.width/2-e+t,b=h.x+_-y-7,"top"===w?(g=h.y+p-(v+c.height+8),f="down",m=c.height-1):(g=h.y+p+v+8,f="up",m=-8)}else{if("left"!==w&&"right"!==w)throw new Error("Unrecognized placement value");"left"===w?(y=h.x+_+x+8,f="left",b=-8):(y=h.x+_-c.width-x-8,f="right",b=c.width-1),p-c.height/2<=0?(g=h.y+p-10.5-6,m=6):p+c.height/2>=d?(g=h.y+p+7+6-c.height,m=c.height-14-6):(g=h.y+p-c.height/2,m=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_${f}`).style("left",`${b}px`).style("top",`${m}px`),this}filter(t,e,s,i){let a=!0;return t.forEach((t=>{const{field:s,operator:i,value:n}=t,o=Jt.get(i),r=this.getElementAnnotation(e);o(s?new K(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;C.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:I.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(Ht(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){const s=this.layout.tooltip;if("object"!=typeof s)return this;const i=this.getElementId(t),a=(t,e,s)=>{let i=null;if("object"!=typeof t||null===t)return null;if(Array.isArray(e))s=s||"and",i=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=a(t,e[o],o),null===i?i=n:"and"===s?i=i&&n:"or"===s&&(i=i||n)}}return i};let n={};"string"==typeof s.show?n={and:[s.show]}:"object"==typeof s.show&&(n=s.show);let o={};"string"==typeof s.hide?o={and:[s.hide]}:"object"==typeof s.hide&&(o=s.hide);const r=this._layer_state;var l={};C.adjectives.forEach((t=>{const e=`un${t}`;l[t]=r.status_flags[t].has(i),l[e]=!l[t]}));const h=a(l,n),c=a(l,o),d=r.status_flags.has_tooltip.has(i);return!h||!e&&!d||c?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),I.select(`#${a}`).classed(`lz-data_layer-${this.layout.type}-${t}`,s);const n=this.getElementStatusNodeId(e);null!==n&&I.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 K(l).resolve(e),active:s},!0),this}setAllElementStatus(t,e){if(void 0===t||!C.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||I.select(I.event.target).datum(),s===!!I.event.ctrlKey&&i===!!I.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=Ht(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._entities,this._dependencies).then((t=>{this.data=t,this.applyDataMethods(),this._initialized=!0,this.parent.emit("data_from_layer",{layer:this.getBaseId(),content:nt(t)},!0)}))}}C.verbs.forEach(((t,e)=>{const s=C.adjectives[e],i=`un${t}`;ie.prototype[`${t}Element`]=function(t,e=!1){return e=!!e,this.setElementStatus(s,t,!0,e),this},ie.prototype[`${i}Element`]=function(t,e){return e=void 0!==e&&!!e,this.setElementStatus(s,t,!1,e),this},ie.prototype[`${t}AllElements`]=function(){return this.setAllElementStatus(s,!0),this},ie.prototype[`${i}AllElements`]=function(){return this.setAllElementStatus(s,!1),this}}));const ae={color:"#000000",filters:null,tooltip_positioning:"vertical",hitarea_width:8};class ne extends ie{constructor(t){if(!Array.isArray(t.filters))throw new Error("Annotation track must specify array of filters for selecting points to annotate");at(t,ae),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 oe={color:"#CCCCCC",fill_opacity:.5,filters:null,regions:[],id_field:"id",start_field:"start",end_field:"end",merge_field:null};class re extends ie{constructor(t){if(at(t,oe),t.interaction||t.behaviors)throw new Error("highlight_regions layer does not support mouse events");if(t.regions.length&&t.namespace&&Object.keys(t.namespace).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)=>I.ascending(t[s],e[s])||I.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 le={color:"seagreen",hitarea_width:"10px",style:{fill:"none","stroke-width":"1px","stroke-opacity":"100%"},tooltip_positioning:"top"};class he extends ie{constructor(t){t=at(t,le),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 I.line().x((t=>t[0])).y((t=>t[1])).curve(I.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(gt,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 ce={stroke:"rgb(54, 54, 150)",color:"#363696",label_font_size:15,label_exon_spacing:3,exon_height:10,bounding_box_padding:3,track_vertical_spacing:5,tooltip_positioning:"top"};class de extends ie{constructor(t){t=at(t,ce),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=I.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=I.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=I.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=I.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=I.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=I.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 ue={style:{fill:"none","stroke-width":"2px"},interpolate:"curveLinear",x_axis:{field:"x"},y_axis:{field:"y",axis:1},hitarea_width:5,tooltip:null};class _e extends ie{constructor(t){if((t=at(t,ue)).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?I.area().x((t=>+n(t[e]))).y0(+o(0)).y1((t=>+o(t[s]))):I.line().x((t=>+n(t[e]))).y((t=>+o(t[s]))).curve(I[this.layout.interpolate]),i.merge(this.path).attr("d",a).call(gt,this.layout.style),i.exit().remove()}setElementStatus(t,e,s){return this.setAllElementStatus(t,s)}setAllElementStatus(t,e){if(void 0===t||!C.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 pe={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 ge extends ie{constructor(t){t=at(t,pe),["horizontal","vertical"].includes(t.orientation)||(t.orientation="horizontal"),super(...arguments)}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=I.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(gt,this.layout.style).call(this.applyBehaviors.bind(this)),i.exit().remove()}_getTooltipPosition(t){try{const t=I.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 ye={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 fe extends ie{constructor(t){(t=at(t,ye)).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=I.select(this);if(+r.attr("x")+r.node().getBoundingClientRect().width+s>n){const e=i?I.select(t._label_lines.nodes()[a]):null;o(r,e)}})),t._label_texts.each((function(e,n){const r=I.select(this);if("end"===r.style("text-anchor"))return;let l=+r.attr("x");const h=r.node().getBoundingClientRect(),c=i?I.select(t._label_lines.nodes()[n]):null;t._label_texts.each((function(){const t=I.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.topp?(g=d-+n,d=+n,u-=g):u+l.height/2>p&&(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)=>I.select(e[s]).attr("y")))}this._label_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 _(){if(u.length){const t=u[Math.floor((u.length-1)/2)];r.push(t)}c=d=null,u=[]}function p(t,e,s){c=t,d=e,u.push(s)}return t.forEach((t=>{const g=t[l],y=t[h],f=g>=e&&g<=s&&y>=a&&y<=n;t.lz_is_match||!f?(_(),r.push(t)):null===c?p(g,y,t):Math.abs(g-c)<=i&&Math.abs(y-d)<=o?u.push(t):(_(),p(g,y,t))})),_(),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=>Ht(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(gt,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(gt,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=I.symbol().size(((t,e)=>this.resolveScalableParameter(this.layout.point_size,t,e))).type(((t,e)=>ot(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._label_iterations=0,this.separate_labels()),this.svg.group.on("click.event_emitter",(()=>{const t=I.select(I.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 me extends fe{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 be=new c;for(let[t,e]of Object.entries(o))be.add(t,e);const xe=be,ve=7.301,we={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{assoc:variant|htmlescape}}
\n P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{assoc:ref_allele|htmlescape}}
\n {{#if lz_is_ld_refvar}}LD Reference Variant{{#else}}\n Make LD Reference{{/if}}
'},$e=function(){const t=nt(we);return t.html+="{{#if lz_show_label}}Hide{{#else}}Show{{/if}} label",t}(),ze={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'},ke={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:'{{catalog:variant|htmlescape}}
Catalog entries: {{n_catalog_matches|htmlescape}}
Top Trait: {{catalog:trait|htmlescape}}
Top P Value: {{catalog:log_pvalue|logtoscinotation}}
More: GWAS catalog / dbSNP'},Ee={closable:!0,show:{or:["highlighted","selected"]},hide:{and:["unhighlighted","unselected"]},html:"Regulatory element
{{access:start1|htmlescape}}-{{access:end1|htmlescape}}
Promoter
{{access:start2|htmlescape}}-{{access:end2|htmlescape}}
{{#if access:target}}Target: {{access:target|htmlescape}}
{{/if}}Score: {{access:score|htmlescape}}"},Me={id:"significance",type:"orthogonal_line",tag:"significance",orientation:"horizontal",offset:ve},Se={id:"recombrate",namespace:{recomb:"recomb"},data_operations:[{type:"fetch",from:["recomb"]}],type:"line",tag:"recombination",z_index:1,style:{stroke:"#0000FF","stroke-width":"1.5px"},x_axis:{field:"recomb:position"},y_axis:{axis:2,field:"recomb:recomb_rate",floor:0,ceiling:100}},Ne={namespace:{assoc:"assoc",ld:"ld"},data_operations:[{type:"fetch",from:["assoc","ld(assoc)"]},{type:"left_match",name:"assoc_plus_ld",requires:["assoc","ld"],params:["assoc:position","ld:position2"]}],id:"associationpvalues",type:"scatter",tag:"association",id_field:"assoc:variant",coalesce:{active:!0},point_shape:[{scale_function:"if",field:"lz_is_ld_refvar",parameters:{field_value:!0,then:"diamond"}},{scale_function:"effect_direction",parameters:{"+":"triangle","-":"triangledown",beta_field:"assoc:beta",stderr_beta_field:"assoc:se"}},"circle"],point_size:{scale_function:"if",field:"lz_is_ld_refvar",parameters:{field_value:!0,then:80,else:40}},color:[{scale_function:"if",field:"lz_is_ld_refvar",parameters:{field_value:!0,then:"#9632b8"}},{scale_function:"numerical_bin",field:"ld:correlation",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:[{label:"LD (r²)",label_size:14},{shape:"ribbon",orientation:"vertical",width:10,height:15,color_stops:["rgb(70, 54, 153)","rgb(38, 188, 225)","rgb(110, 254, 104)","rgb(248, 195, 42)","rgb(219, 61, 17)"],tick_labels:[0,.2,.4,.6,.8,1]}],label:null,z_index:2,x_axis:{field:"assoc:position"},y_axis:{axis:1,field:"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:nt(we)},Ae={id:"coaccessibility",type:"arcs",tag:"coaccessibility",namespace:{access:"access"},data_operations:[{type:"fetch",from:["access"]}],match:{send:"access:target",receive:"access:target"},id_field:"{{access:start1}}_{{access:end1}}_{{access:start2}}_{{access:end2}}_{{access:score}}_{{access:target}}",filters:[{field:"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:"access:start1",field2:"access:start2"},y_axis:{axis:1,field:"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:nt(Ee)},Oe=function(){let t=nt(Ne);return t=at({id:"associationpvaluescatalog",fill_opacity:.7},t),t.data_operations.push({type:"assoc_to_gwas_catalog",name:"assoc_catalog",requires:["assoc_plus_ld","catalog"],params:["assoc:position","catalog:pos","catalog:log_pvalue"]}),t.tooltip.html+='{{#if catalog:rsid}}
See hits in GWAS catalog{{/if}}',t.namespace.catalog="catalog",t}(),Te={id:"phewaspvalues",type:"category_scatter",tag:"phewas",namespace:{phewas:"phewas"},data_operations:[{type:"fetch",from:["phewas"]}],point_shape:[{scale_function:"effect_direction",parameters:{"+":"triangle","-":"triangledown",beta_field:"phewas:beta",stderr_beta_field:"phewas:se"}},"circle"],point_size:70,tooltip_positioning:"vertical",id_field:"{{phewas:trait_group}}_{{phewas:trait_label}}",x_axis:{field:"lz_auto_x",category_field:"phewas:trait_group",lower_buffer:.025,upper_buffer:.025},y_axis:{axis:1,field:"phewas:log_pvalue",floor:0,upper_buffer:.15},color:[{field:"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: {{phewas:trait_label|htmlescape}}
\nTrait Category: {{phewas:trait_group|htmlescape}}
\nP-value: {{phewas:log_pvalue|logtoscinotation|htmlescape}}\n{{#if phewas:beta|is_numeric}}
β: {{phewas:beta|scinotation|htmlescape}}
{{/if}}\n{{#if phewas:se|is_numeric}}SE (β): {{phewas:se|scinotation|htmlescape}}{{/if}}"},behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},label:{text:"{{phewas:trait_label}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"phewas:log_pvalue",operator:">=",value:20}],style:{"font-size":"14px","font-weight":"bold",fill:"#333333"}}},Le={namespace:{gene:"gene",constraint:"constraint"},data_operations:[{type:"fetch",from:["gene","constraint(gene)"]},{name:"gene_constraint",type:"genes_to_gnomad_constraint",requires:["gene","constraint"]}],id:"genes",type:"genes",tag:"genes",id_field:"gene_id",behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:nt(ze)},je=at({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"]}]},nt(Le)),Pe={namespace:{assoc:"assoc",catalog:"catalog"},data_operations:[{type:"fetch",from:["assoc","catalog"]},{type:"assoc_to_gwas_catalog",name:"assoc_plus_ld",requires:["assoc","catalog"],params:["assoc:position","catalog:pos","catalog:log_pvalue"]}],id:"annotation_catalog",type:"annotation_track",tag:"gwascatalog",id_field:"assoc:variant",x_axis:{field:"assoc:position"},color:"#0000CC",filters:[{field:"catalog:rsid",operator:"!=",value:null},{field:"catalog:log_pvalue",operator:">",value:ve}],behaviors:{onmouseover:[{action:"set",status:"highlighted"}],onmouseout:[{action:"unset",status:"highlighted"}],onclick:[{action:"toggle",status:"selected",exclusive:!0}]},tooltip:nt(ke),tooltip_positioning:"top"},Re={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"}]},Ie={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}}]},Ce={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"}}]},De={widgets:[{type:"title",title:"LocusZoom",subtitle:'v0.14.0',position:"left"},{type:"download",position:"right",group_position:"end"},{type:"download_png",position:"right",group_position:"start"}]},Be=function(){const t=nt(De);return t.widgets.push(nt(Re)),t}(),Ue=function(){const t=nt(De);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}(),qe={id:"association",tag:"association",min_height:200,height:300,margin:{top:35,right:55,bottom:40,left:70},inner_border:"rgb(210, 210, 210)",toolbar:function(){const t=nt(Ce);return t.widgets.push({type:"toggle_legend",position:"right"}),t}(),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:38,tick_format:"region",extent:"state"},y1:{label:"-log10 p-value",label_offset:50},y2:{label:"Recombination Rate (cM/Mb)",label_offset:46}},legend:{orientation:"vertical",origin:{x:75,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:[nt(Me),nt(Se),nt(Ne)]},Fe={id:"coaccessibility",tag:"coaccessibility",min_height:150,height:180,margin:{top:35,right:55,bottom:40,left:70},inner_border:"rgb(210, 210, 210)",toolbar:nt(Ce),axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:38,tick_format:"region",extent:"state"},y1:{label:"Score",label_offset:40,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:[nt(Ae)]},He=function(){let t=nt(qe);return t=at({id:"associationcatalog"},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:"{{catalog:trait}}",spacing:6,lines:{style:{"stroke-width":"2px",stroke:"#333333","stroke-dasharray":"2px 2px"}},filters:[{field:"catalog:trait",operator:"!=",value:null},{field:"catalog:log_pvalue",operator:">",value:ve},{field:"ld:correlation",operator:">",value:.4}],style:{"font-size":"12px","font-weight":"bold",fill:"#333333"}}}}]}),t.data_layers=[nt(Me),nt(Se),nt(Oe)],t}(),Ge={id:"genes",tag:"genes",min_height:150,height:225,margin:{top:20,right:55,bottom:20,left:70},axes:{},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},toolbar:function(){const t=nt(Ce);return t.widgets.push({type:"resize_to_data",position:"right",button_html:"Resize"},nt(Ie)),t}(),data_layers:[nt(je)]},Je={id:"phewas",tag:"phewas",min_height:300,height:300,margin:{top:20,right:55,bottom:120,left:70},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:50}},data_layers:[nt(Me),nt(Te)]},Ze={id:"annotationcatalog",tag:"gwascatalog",min_height:50,height:50,margin:{top:25,right:55,bottom:10,left:70},inner_border:"rgb(210, 210, 210)",toolbar:nt(Ce),axes:{x:{extent:"state",render:!1}},interaction:{drag_background_to_pan:!0,scroll_to_zoom:!0,x_linked:!0},data_layers:[nt(Pe)]},Ke={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:Be,panels:[nt(qe),nt(Ge)]},Ve={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:Be,panels:[Ze,He,Ge]},We={width:800,responsive_resize:!0,toolbar:De,panels:[nt(Je),at({height:300,margin:{bottom:40},axes:{x:{label:"Chromosome {{chr}} (Mb)",label_offset:38,tick_format:"region",extent:"state"}}},nt(Ge))],mouse_guide:!1},Ye={state:{},width:800,responsive_resize:!0,min_region_scale:2e4,max_region_scale:1e6,toolbar:nt(De),panels:[nt(Fe),function(){const t=Object.assign({height:270},nt(Ge)),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}()]},Xe={standard_association:we,standard_association_with_label:$e,standard_genes:ze,catalog_variant:ke,coaccessibility:Ee},Qe={ldlz2_pop_selector:Re,gene_selector_menu:Ie},ts={standard_panel:Ce,standard_plot:De,standard_association:Be,region_nav_plot:Ue},es={significance:Me,recomb_rate:Se,association_pvalues:Ne,coaccessibility:Ae,association_pvalues_catalog:Oe,phewas_pvalues:Te,genes:Le,genes_filtered:je,annotation_catalog:Pe},ss={association:qe,coaccessibility:Fe,association_catalog:He,genes:Ge,phewas:Je,annotation_catalog:Ze},is={standard_association:Ke,association_catalog:Ve,standard_phewas:We,coaccessibility:Ye};const as=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);const a=s.namespace;i.namespace||delete s.namespace;let n=at(s,i);return a&&(n=it(n,a)),nt(n)}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=nt(s);return"data_layer"===t&&a.namespace&&(a._auto_fields=[...rt(a,Object.keys(a.namespace))].sort()),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 at(t,e)}renameField(){return lt(...arguments)}mutate_attrs(){return ht(...arguments)}query_attrs(){return ct(...arguments)}};for(let[t,e]of Object.entries(r))for(let[s,i]of Object.entries(e))as.add(t,s,i);const ns=as,os=new h;function rs(t){return(e,s,...i)=>{if(2!==s.length)throw new Error("Join functions must receive exactly two recordsets");return t(...s,...i)}}os.add("left_match",rs(x)),os.add("inner_match",rs((function(t,e,s,i){return b("inner",...arguments)}))),os.add("full_outer_match",rs((function(t,e,s,i){return b("outer",...arguments)}))),os.add("assoc_to_gwas_catalog",rs((function(t,e,s,i,a){if(!t.length)return t;const n=m(e,i),o=[];for(let t of n.values()){let e,s=0;for(let i of t){const t=i[a];t>=s&&(e=i,s=t)}e.n_catalog_matches=t.length,o.push(e)}return x(t,o,s,i)}))),os.add("genes_to_gnomad_constraint",rs((function(t,e){return t.forEach((function(t){const s=`_${t.gene_name.replace(/[^A-Za-z0-9_]/g,"_")}`,i=e[s]&&e[s].gnomad_constraint;i&&Object.keys(i).forEach((function(e){let s=i[e];void 0===t[e]&&("number"==typeof s&&s.toString().includes(".")&&(s=parseFloat(s.toFixed(2))),t[e]=s)}))})),t})));const ls=os;const hs={version:l,populate:function(t,e,s){if(void 0===t)throw new Error("LocusZoom.populate selector not defined");let i;return I.select(t).html(""),I.select(t).call((function(t){if(void 0===t.node().id){let e=0;for(;!I.select(`#lz-${e}`).empty();)e++;t.attr("id",`#lz-${e}`)}if(i=new Ut(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=Ft(s[2]),e=Ft(s[4]);return{chr:s[1],start:t-e,end:t+e}}return{chr:s[1],start:Ft(s[2]),end:Ft(s[4])}}if(s=e.exec(t),s)return{chr:s[1],position:Ft(s[2])};return null}(t.node().dataset.region);Object.keys(e).forEach((function(t){i.state[t]=e[t]}))}i.svg=I.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(gt,i.layout.style),i.setDimensions(),i.positionPanels(),i.initialize(),e&&i.refresh()})),i},DataSources:class extends h{constructor(t){super(),this._registry=t||R}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:R,DataLayers:xe,DataFunctions:ls,Layouts:ns,MatchFunctions:Jt,ScaleFunctions:ee,TransformationFunctions:Z,Widgets:jt,get KnownDataSources(){return console.warn('Deprecation warning: KnownDataSources has been renamed to "Adapters"'),R}},cs=[];hs.use=function(t,...e){if(!cs.includes(t)){if(e.unshift(hs),"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)}cs.push(t)}};const ds=hs})(),LocusZoom=i.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 b4aed111..a443f5a9 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,E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AO,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 +{"version":3,"sources":["webpack://[name]/./node_modules/@hapi/hoek/lib/assert.js","webpack://[name]/./node_modules/@hapi/hoek/lib/error.js","webpack://[name]/./node_modules/@hapi/hoek/lib/stringify.js","webpack://[name]/./node_modules/@hapi/topo/lib/index.js","webpack://[name]/./node_modules/just-clone/index.js","webpack://[name]/webpack/bootstrap","webpack://[name]/webpack/runtime/compat get default export","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/undercomplicate/lru_cache.js","webpack://[name]/./esm/data/undercomplicate/util.js","webpack://[name]/./esm/data/undercomplicate/requests.js","webpack://[name]/./esm/data/undercomplicate/joins.js","webpack://[name]/./esm/helpers/parse.js","webpack://[name]/./esm/data/adapters.js","webpack://[name]/./esm/data/undercomplicate/adapter.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/registry/data_ops.js","webpack://[name]/./esm/data/sources.js","webpack://[name]/./esm/index.js"],"names":["AssertError","module","exports","condition","args","length","Error","Stringify","super","filter","arg","map","message","join","captureStackTrace","this","assert","JSON","stringify","apply","err","Assert","internals","_items","nodes","options","before","concat","after","group","sort","includes","Array","isArray","node","item","seq","push","manual","valid","_sort","others","other","Object","assign","mergeSort","i","graph","graphAfters","create","groups","expandedGroups","graphNodeItem","ancestors","children","child","visited","sorted","next","j","shouldSeeCount","seenCount","k","seqIndex","value","sortedItem","a","b","getRegExpFlags","regExp","source","flags","global","ignoreCase","multiline","sticky","unicode","clone","obj","result","key","type","toString","call","slice","Date","getTime","RegExp","__webpack_module_cache__","__webpack_require__","moduleId","__webpack_modules__","n","getter","__esModule","d","definition","o","defineProperty","enumerable","get","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","RegistryBase","Map","name","has","override","set","delete","from","keys","ClassRegistry","parent_name","source_name","overrides","console","warn","arguments","base","sub","add","LLNode","metadata","prev","LRUCache","max_size","_max_size","_cur_size","_store","_head","_tail","cached","prior","_remove","old","match_callback","data","getLinkedData","shared_options","entities","dependencies","consolidate","parsed","spec","exec","name_alone","name_deps","deps","split","_parse_declaration","dag","toposort","entries","e","order","responses","provider","depends_on","this_result","Promise","all","then","prior_results","_provider_name","getData","values","all_results","groupBy","records","group_key","item_group","_any_match","left","right","left_key","right_key","right_index","results","left_match_value","right_matches","right_item","left_index","right_match_value","left_match","REGEX_MARKER","parseMarker","test","match","BaseApiAdapter","BaseLZAdapter","config","_config","cache_enabled","cache_size","_enable_cache","_cache","dependent_data","response_text","_buildRequestOptions","cache_key","_getCacheKey","resolve","_performRequest","text","_normalizeResponse","_cache_meta","catch","remove","_annotateRecords","_postProcessResponse","_url","url","_getURL","fetch","response","ok","statusText","parse","params","prefix_namespace","limit_fields","_prefix_namespace","_limit_fields","Set","chr","start","end","superset","find","md","row","reduce","acc","label","a_record","fieldname","suffixer","BaseUMAdapter","_genome_build","genome_build","build","constructor","N","every","fields","record","AssociationLZ","_source_id","request_options","GwasCatalogLZ","_validateBuildSource","source_query","GeneLZ","GeneConstraintLZ","state","genes_data","unique_gene_names","gene","gene_name","query","replace","body","method","headers","LDServer","assoc_data","assoc_variant_name","_findPrefixedKey","assoc_logp_name","refvar","best_hit","ldrefvar","best_logp","variant","log_pvalue","lz_is_ld_refvar","chrom","pos","ref","alt","coord","String","__find_ld_refvar","_skip_request","ld_refvar","ld_source","ld_population","ld_pop","population","encodeURIComponent","combined","chainRequests","payload","forEach","RecombLZ","StaticSource","_data","PheWASLZ","registry","d3","STATUSES","verbs","adjectives","log10","isNaN","Math","log","LN10","neglog10","logtoscinotation","exp","ceil","diff","pow","toFixed","scinotation","abs","floor","toExponential","htmlescape","s","is_numeric","urlencode","template_string","funcs","substring","func","_collectTransforms","Field","field","transforms","full_name","field_name","transformations","val","transform","extra","undefined","_applyTransformations","ATTR_REGEX","EXPR_REGEX","get_next_token","q","substr","attr","depth","m","attrs","get_item_at_deep_path","path","parent","tokens_to_keys","selectors","sel","remaining_selectors","paths","p","_","__","subject","uniqPaths","arr","elem","localeCompare","_query","matches","items","get_items_from_tokens","normalize_query","selector","tokenize","sqrt3","sqrt","triangledown","context","size","y","moveTo","lineTo","closePath","applyNamespaces","layout","shared_namespaces","requested_ns","merge","custom_layout","default_layout","property","custom_type","default_type","deepCopy","nameToSymbol","shape","factory_name","charAt","toUpperCase","findFields","prefixes","field_finder","all_ns","value_type","a_match","renameField","old_name","new_name","warn_transforms","this_type","escaped","filter_regex","match_val","regex","mutate_attrs","value_or_callable","value_or_callback","old_value","new_value","mutate","query_attrs","DataOperation","join_type","initiator","_callable","_initiator","_params","plot_state","dependent_recordsets","data_layer","sources","_sources","namespace_options","data_operations","namespace_local_names","dependency_order","unshift","ns_pattern","local_name","global_name","dep_spec","requires","namecount","require_name","task","generateCurtain","showing","content_selector","hide_delay","show","content","css","curtain","parent_plot","svg","parentNode","insert","id","append","html","on","hide","update","clearTimeout","applyStyles","page_origin","_getPageOrigin","height","_total_height","style","x","width","delay","setTimeout","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","position","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","index","indexOf","_getTarget","splice","_clearFilter","emit","filter_id","Number","input_size","timer","debounce","_getValue","_setFilter","render","DownloadSVG","_filename","filename","_button_html","button_html","_button_title","button_title","setColor","setHtml","setTitle","setOnMouseover","_getBlobUrl","URL","revokeObjectURL","setOnMouseout","root","ancestor_pattern","extractedCSSText","styleSheets","cssRules","rule","selectorText","cssText","element","styleElement","createElement","setAttribute","innerHTML","refNode","hasChildNodes","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","radioId","has_option","choice","defaultName","default_config_display_name","display","SetState","state_field","show_selected","new_state","choice_name","choice_value","Toolbar","widgets","hide_timeout","addWidget","widget","error","_panel_boundaries","dragging","_interaction","orientation","origin","padding","label_size","Legend","background_rect","elements","elements_group","line_height","_data_layer_ids_by_z_index","reverse","layer_legend","label_x","label_y","shape_factory","path_y","is_horizontal","color_stops","all_elements","ribbon_group","axis_group","axis_offset","tick_labels","range","scale","domain","axis","tickSize","tickValues","tickFormat","v","to_next_marking","radius","PI","bcr","right_x","pad_from_bottom","pad_from_right","min_height","margin","background_click","cliparea","axes","y1","y2","interaction","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","_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","parseFloat","y_axis","z_index","dlid","idx","layout_idx","data_layer_layout","target_layer","destroyAllTooltips","container","applyDataLayerZIndexesToDataLayerLayouts","setAllElementStatus","clipRect","inner_border","generateExtents","constrain","limit_exponent","neg_min","neg_max","pos_min","pos_max","Infinity","ranges","axes_config","base_x_range","x_shifted","base_y1_range","y1_shifted","base_y2_range","y2_shifted","current_drag","panel_id","linked_panel_ids","anchor","scalar","zooming","current_extent_size","current_scaled_extent_size","round","invert","zoom_factor","potential_extent_size","new_extent_size","center","offset_ratio","new_x_extent_start","dragged_x","start_x","y_shifted","dragged_y","start_y","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","namespace","mousedown","startDrag","select","applyPanelYIndexesToPanelLayouts","positionPanels","reMap","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","tick_format","t","tick_selector","parseFields","tick_mouseover","focus","cursor","target_height","dh","getAbsoluteDataHeight","toggle","verb","adjective","antiverb","min_width","responsive_resize","panel_boundaries","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","target_panel","clearPanelData","opts","success_callback","from_layer","onerror","error_callback","base_prefix","layer_target","startsWith","is_valid_layer","some","listener","config_to_sources","new_data","state_changes","mods","attempted_scale","validated_region","attempted_midpoint","temp","_updateStatePosition","loading_data","applyAllElementStatus","tracker","registered_events","listeners","removeEventListener","lastElementChild","removeChild","outerHTML","mutateLayout","bounding_client_rect","x_offset","scrollLeft","y_offset","offset","offsetParent","offsetTop","offsetLeft","clientRect","addPanel","height_scaling_factor","panel_width","panel_height","final_height","x_linked_margins","resize_listener","window","requestAnimationFrame","rescaleSVG","addEventListener","trackExternalListener","IntersectionObserver","threshold","observer","entry","intersectionRatio","observe","load_listener","mouse_guide_svg","mouse_guide_vertical_svg","mouse_guide_horizontal_svg","_mouse_guide","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","ret","positionStringToInt","suffixre","mult","tokens","variable","branch","close","astify","token","shift","dest","else","ast","cache","render_node","item_value","target_value","if_value","parameters","field_value","numerical_bin","breaks","null_value","curr","categorical_bin","categories","ordinal_cycle","stable_choice","max_cache_size","clear","hash","charCodeAt","interpolate","nullval","upper_idx","brk","normalized_input","isFinite","effect_direction","input","beta_field","stderr_beta_field","plus_result","neg_result","beta_val","se_val","id_field","tooltip","tooltip_positioning","behaviors","BaseDataLayer","_base_id","_filter_func","_tooltips","_global_statuses","_data_contract","_entities","_dependencies","layer_order","current_index","resortDataLayers","getElementId","extra_fields","axis_config","id_key","for","element_id","empty","field_to_match","receive","match_function","broadcast_value","field_resolver","fields_unseen","debug","lz_is_match","getDataLayer","getPanel","getPlot","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","updateTooltip","positionTooltip","closable","destroyTooltip","element_or_id","temporary","_getTooltipPosition","_drawTooltip","first_time","tooltip_layout","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","dax","abound","bbound","_label_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","custom_namespaces","_auto_fields","contents","list","_wrap_join","handle","catalog_data","assoc_key","catalog_key","catalog_logp_name","catalog_by_variant","catalog_flat","claims","best_variant","best","n_catalog_matches","constraint_data","alias","constraint","LocusZoom","version","iterator","dataset","region","parsed_state","chrpos","parsePositionQuery","refresh","DataSources","_registry","source_id","Adapters","DataLayers","DataFunctions","Layouts","MatchFunctions","ScaleFunctions","TransformationFunctions","Widgets","INSTALLED_PLUGINS","use","plugin","install"],"mappings":";sDAEA,MAAMA,EAAc,EAAQ,KAK5BC,EAAOC,QAAU,SAAUC,KAAcC,GAErC,IAAID,EAAJ,CAIA,GAAoB,IAAhBC,EAAKC,QACLD,EAAK,aAAcE,MAEnB,MAAMF,EAAK,GAGf,MAAM,IAAIJ,EAAYI,M,2BCjB1B,MAAMG,EAAY,EAAQ,KAM1BN,EAAOC,QAAU,cAAcI,MAE3B,YAAYF,GASRI,MAPaJ,EACRK,QAAQC,GAAgB,KAARA,IAChBC,KAAKD,GAEoB,iBAARA,EAAmBA,EAAMA,aAAeJ,MAAQI,EAAIE,QAAUL,EAAUG,KAGnFG,KAAK,MAAQ,iBAEe,mBAA5BP,MAAMQ,mBACbR,MAAMQ,kBAAkBC,KAAMb,EAAQc,W,qBCjBlDf,EAAOC,QAAU,YAAaE,GAE1B,IACI,OAAOa,KAAKC,UAAUC,MAAM,KAA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sGg2B,KAE1H,GAAIt0B,MAAMC,QAAQE,GAAO,CACrB,MAAO8C,EAAMxD,GAAWU,EACxBA,EAAOpB,KAAKi7C,UAAU/4C,OAAOgC,EAAMxD,GAMvC,OAHAU,EAAK85C,UAAY3lB,EAEjB91B,MAAMqH,IAAIyuB,EAAWn0B,EAAM4E,GACpBhG,OCnBXm7C,SAAQ,EACRC,WAAU,GACVC,cAAa,GACbC,QAAO,GACPC,eAAc,GACdC,eAAc,GACdC,wBAAuB,EACvBC,QAAO,GAEP,uBAEI,OADAj1C,QAAQC,KAAK,wEACN,IAYTi1C,GAAoB,GAQ1BpB,GAAUqB,IAAM,SAASC,KAAWx8C,GAEhC,IAAIs8C,GAAkB36C,SAAS66C,GAA/B,CAMA,GADAx8C,EAAKkb,QAAQggC,IACiB,mBAAnBsB,EAAOC,QACdD,EAAOC,QAAQ17C,MAAMy7C,EAAQx8C,OAC1B,IAAsB,mBAAXw8C,EAGd,MAAM,IAAIt8C,MAAM,mFAFhBs8C,EAAOz7C,MAAM,KAAMf,GAIvBs8C,GAAkBr6C,KAAKu6C,KAI3B,a","file":"locuszoom.app.min.js","sourcesContent":["'use strict';\n\nconst AssertError = require('./error');\n\nconst internals = {};\n\n\nmodule.exports = function (condition, ...args) {\n\n if (condition) {\n return;\n }\n\n if (args.length === 1 &&\n args[0] instanceof Error) {\n\n throw args[0];\n }\n\n throw new AssertError(args);\n};\n","'use strict';\n\nconst Stringify = require('./stringify');\n\n\nconst internals = {};\n\n\nmodule.exports = class extends Error {\n\n constructor(args) {\n\n const msgs = args\n .filter((arg) => arg !== '')\n .map((arg) => {\n\n return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg);\n });\n\n super(msgs.join(' ') || 'Unknown error');\n\n if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$\n Error.captureStackTrace(this, exports.assert);\n }\n }\n};\n","'use strict';\n\nconst internals = {};\n\n\nmodule.exports = function (...args) {\n\n try {\n return JSON.stringify.apply(null, args);\n }\n catch (err) {\n return '[Cannot display object: ' + err.message + ']';\n }\n};\n","'use strict';\n\nconst Assert = require('@hapi/hoek/lib/assert');\n\n\nconst internals = {};\n\n\nexports.Sorter = class {\n\n constructor() {\n\n this._items = [];\n this.nodes = [];\n }\n\n add(nodes, options) {\n\n options = options || {};\n\n // Validate rules\n\n const before = [].concat(options.before || []);\n const after = [].concat(options.after || []);\n const group = options.group || '?';\n const sort = options.sort || 0; // Used for merging only\n\n Assert(!before.includes(group), `Item cannot come before itself: ${group}`);\n Assert(!before.includes('?'), 'Item cannot come before unassociated items');\n Assert(!after.includes(group), `Item cannot come after itself: ${group}`);\n Assert(!after.includes('?'), 'Item cannot come after unassociated items');\n\n if (!Array.isArray(nodes)) {\n nodes = [nodes];\n }\n\n for (const node of nodes) {\n const item = {\n seq: this._items.length,\n sort,\n before,\n after,\n group,\n node\n };\n\n this._items.push(item);\n }\n\n // Insert event\n\n if (!options.manual) {\n const valid = this._sort();\n Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error');\n }\n\n return this.nodes;\n }\n\n merge(others) {\n\n if (!Array.isArray(others)) {\n others = [others];\n }\n\n for (const other of others) {\n if (other) {\n for (const item of other._items) {\n this._items.push(Object.assign({}, item)); // Shallow cloned\n }\n }\n }\n\n // Sort items\n\n this._items.sort(internals.mergeSort);\n for (let i = 0; i < this._items.length; ++i) {\n this._items[i].seq = i;\n }\n\n const valid = this._sort();\n Assert(valid, 'merge created a dependencies error');\n\n return this.nodes;\n }\n\n sort() {\n\n const valid = this._sort();\n Assert(valid, 'sort created a dependencies error');\n\n return this.nodes;\n }\n\n _sort() {\n\n // Construct graph\n\n const graph = {};\n const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives\n const groups = Object.create(null);\n\n for (const item of this._items) {\n const seq = item.seq; // Unique across all items\n const group = item.group;\n\n // Determine Groups\n\n groups[group] = groups[group] || [];\n groups[group].push(seq);\n\n // Build intermediary graph using 'before'\n\n graph[seq] = item.before;\n\n // Build second intermediary graph with 'after'\n\n for (const after of item.after) {\n graphAfters[after] = graphAfters[after] || [];\n graphAfters[after].push(seq);\n }\n }\n\n // Expand intermediary graph\n\n for (const node in graph) {\n const expandedGroups = [];\n\n for (const graphNodeItem in graph[node]) {\n const group = graph[node][graphNodeItem];\n groups[group] = groups[group] || [];\n expandedGroups.push(...groups[group]);\n }\n\n graph[node] = expandedGroups;\n }\n\n // Merge intermediary graph using graphAfters into final graph\n\n for (const group in graphAfters) {\n if (groups[group]) {\n for (const node of groups[group]) {\n graph[node].push(...graphAfters[group]);\n }\n }\n }\n\n // Compile ancestors\n\n const ancestors = {};\n for (const node in graph) {\n const children = graph[node];\n for (const child of children) {\n ancestors[child] = ancestors[child] || [];\n ancestors[child].push(node);\n }\n }\n\n // Topo sort\n\n const visited = {};\n const sorted = [];\n\n for (let i = 0; i < this._items.length; ++i) { // Looping through item.seq values out of order\n let next = i;\n\n if (ancestors[i]) {\n next = null;\n for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values\n if (visited[j] === true) {\n continue;\n }\n\n if (!ancestors[j]) {\n ancestors[j] = [];\n }\n\n const shouldSeeCount = ancestors[j].length;\n let seenCount = 0;\n for (let k = 0; k < shouldSeeCount; ++k) {\n if (visited[ancestors[j][k]]) {\n ++seenCount;\n }\n }\n\n if (seenCount === shouldSeeCount) {\n next = j;\n break;\n }\n }\n }\n\n if (next !== null) {\n visited[next] = true;\n sorted.push(next);\n }\n }\n\n if (sorted.length !== this._items.length) {\n return false;\n }\n\n const seqIndex = {};\n for (const item of this._items) {\n seqIndex[item.seq] = item;\n }\n\n this._items = [];\n this.nodes = [];\n\n for (const value of sorted) {\n const sortedItem = seqIndex[value];\n this.nodes.push(sortedItem.node);\n this._items.push(sortedItem);\n }\n\n return true;\n }\n};\n\n\ninternals.mergeSort = (a, b) => {\n\n return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1);\n};\n","module.exports = clone;\n\n/*\n Deep clones all properties except functions\n\n var arr = [1, 2, 3];\n var subObj = {aa: 1};\n var obj = {a: 3, b: 5, c: arr, d: subObj};\n var objClone = clone(obj);\n arr.push(4);\n subObj.bb = 2;\n obj; // {a: 3, b: 5, c: [1, 2, 3, 4], d: {aa: 1}}\n objClone; // {a: 3, b: 5, c: [1, 2, 3], d: {aa: 1, bb: 2}}\n*/\n\nfunction clone(obj) {\n if (typeof obj == 'function') {\n return obj;\n }\n var result = Array.isArray(obj) ? [] : {};\n for (var key in obj) {\n // include prototype properties\n var value = obj[key];\n var type = {}.toString.call(value).slice(8, -1);\n if (type == 'Array' || type == 'Object') {\n result[key] = clone(value);\n } else if (type == 'Date') {\n result[key] = new Date(value.getTime());\n } else if (type == 'RegExp') {\n result[key] = RegExp(value.source, getRegExpFlags(value));\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction getRegExpFlags(regExp) {\n if (typeof regExp.source.flags == 'string') {\n return regExp.source.flags;\n } else {\n var flags = [];\n regExp.global && flags.push('g');\n regExp.ignoreCase && flags.push('i');\n regExp.multiline && flags.push('m');\n regExp.sticky && flags.push('y');\n regExp.unicode && flags.push('u');\n return flags.join('');\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\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.14.0';\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 * Implement an LRU Cache\n */\n\n\nclass LLNode {\n /**\n * A single node in the linked list. Users will only need to deal with this class if using \"approximate match\" (`cache.find()`)\n * @memberOf module:undercomplicate\n * @param {string} key\n * @param {*} value\n * @param {object} metadata\n * @param {LLNode} prev\n * @param {LLNode} next\n */\n constructor(key, value, metadata = {}, prev = null, next = null) {\n this.key = key;\n this.value = value;\n this.metadata = metadata;\n this.prev = prev;\n this.next = next;\n }\n}\n\nclass LRUCache {\n /**\n * Least-recently used cache implementation, with \"approximate match\" semantics\n * @memberOf module:undercomplicate\n * @param {number} [max_size=3]\n */\n constructor(max_size = 3) {\n this._max_size = max_size;\n this._cur_size = 0; // replace with map.size so we aren't managing manually?\n this._store = new Map();\n\n // Track LRU state\n this._head = null;\n this._tail = null;\n\n // Validate options\n if (max_size === null || max_size < 0) {\n throw new Error('Cache \"max_size\" must be >= 0');\n }\n }\n\n /**\n * Check key membership without updating LRU\n * @param key\n * @returns {boolean}\n */\n has(key) {\n return this._store.has(key);\n }\n\n /**\n * Retrieve value from cache (if present) and update LRU cache to say an item was recently used\n * @param key\n * @returns {null|*}\n */\n get(key) {\n const cached = this._store.get(key);\n if (!cached) {\n return null;\n }\n if (this._head !== cached) {\n // Rewrite the cached value to ensure it is head of the list\n this.add(key, cached.value);\n }\n return cached.value;\n }\n\n /**\n * Add an item. Forcibly replaces the existing cached value for the same key.\n * @param key\n * @param value\n * @param {Object} [metadata={}) Metadata associated with an item. Metadata can be used for lookups (`cache.find`) to test for a cache hit based on non-exact match\n */\n add(key, value, metadata = {}) {\n if (this._max_size === 0) {\n // Don't cache items if cache has 0 size.\n return;\n }\n\n const prior = this._store.get(key);\n if (prior) {\n this._remove(prior);\n }\n\n const node = new LLNode(key, value, metadata, null, this._head);\n\n if (this._head) {\n this._head.prev = node;\n } else {\n this._tail = node;\n }\n\n this._head = node;\n this._store.set(key, node);\n\n if (this._max_size >= 0 && this._cur_size >= this._max_size) {\n const old = this._tail;\n this._tail = this._tail.prev;\n this._remove(old);\n }\n this._cur_size += 1;\n }\n\n\n // Cache manipulation methods\n clear() {\n this._head = null;\n this._tail = null;\n this._cur_size = 0;\n this._store = new Map();\n }\n\n // Public method, remove by key\n remove(key) {\n const cached = this._store.get(key);\n if (!cached) {\n return false;\n }\n this._remove(cached);\n return true;\n }\n\n // Internal implementation, useful when working on list\n _remove(node) {\n if (node.prev !== null) {\n node.prev.next = node.next;\n } else {\n this._head = node.next;\n }\n\n if (node.next !== null) {\n node.next.prev = node.prev;\n } else {\n this._tail = node.prev;\n }\n this._store.delete(node.key);\n this._cur_size -= 1;\n }\n\n /**\n * Find a matching item in the cache, or return null. This is useful for \"approximate match\" semantics,\n * to check if something qualifies as a cache hit despite not having the exact same key.\n * (Example: zooming into a region, where the smaller region is a subset of something already cached)\n * @param {function} match_callback A function to be used to test the node as a possible match (returns true or false)\n * @returns {null|LLNode}\n */\n find(match_callback) {\n let node = this._head;\n while (node) {\n const next = node.next;\n if (match_callback(node)) {\n return node;\n }\n node = next;\n }\n }\n}\n\nexport { LRUCache };\n","/**\n * @private\n */\n\nimport justclone from 'just-clone';\n\n/**\n * The \"just-clone\" library only really works for objects and arrays. If given a string, it would mess things up quite a lot.\n * @param {object} data\n * @returns {*}\n */\nfunction clone(data) {\n if (typeof data !== 'object') {\n return data;\n }\n return justclone(data);\n}\n\nexport { clone };\n","/**\n * Perform a series of requests, respecting order of operations\n * @private\n */\n\nimport {Sorter} from '@hapi/topo';\n\n\nfunction _parse_declaration(spec) {\n // Parse a dependency declaration like `assoc` or `ld(assoc)` or `join(assoc, ld)`. Return node and edges that can be used to build a graph.\n const parsed = /^(?\\w+)$|((?\\w+)+\\(\\s*(?[^)]+?)\\s*\\))/.exec(spec);\n if (!parsed) {\n throw new Error(`Unable to parse dependency specification: ${spec}`);\n }\n\n let {name_alone, name_deps, deps} = parsed.groups;\n if (name_alone) {\n return [name_alone, []];\n }\n\n deps = deps.split(/\\s*,\\s*/);\n return [name_deps, deps];\n}\n\n/**\n * Perform a request for data from a set of providers, taking into account dependencies between requests.\n * This can be a mix of network requests or other actions (like join tasks), provided that the provider be some\n * object that implements a method `instance.getData`\n *\n * Each data layer in LocusZoom will translate the internal configuration into a format used by this function.\n * This function is never called directly in custom user code. In locuszoom, Requester Handles You\n *\n * TODO Future: It would be great to add a warning if the final element in the DAG does not reference all dependencies. This is a limitation of the current toposort library we use.\n *\n * @param {object} shared_options Options passed globally to all requests. In LocusZoom, this is often a copy of \"plot.state\"\n * @param {Map} entities A lookup of named entities that implement the method `instance.getData -> Promise`\n * @param {String[]} dependencies A description of how to fetch entities, and what they depend on, like `['assoc', 'ld(assoc)']`.\n * **Order will be determined by a DAG and the last item in the DAG is all that is returned.**\n * @param {boolean} [consolidate=true] Whether to return all results (almost never used), or just the last item in the resolved DAG.\n * This can be a pitfall in common usage: if you forget a \"join/consolidate\" task, the last result may appear to be missing some data.\n * @returns {Promise}\n */\nfunction getLinkedData(shared_options, entities, dependencies, consolidate = true) {\n if (!dependencies.length) {\n return [];\n }\n\n const parsed = dependencies.map((spec) => _parse_declaration(spec));\n const dag = new Map(parsed);\n\n // Define the order to perform requests in, based on a DAG\n const toposort = new Sorter();\n for (let [name, deps] of dag.entries()) {\n try {\n toposort.add(name, {after: deps, group: name});\n } catch (e) {\n throw new Error(`Invalid or possible circular dependency specification for: ${name}`);\n }\n }\n const order = toposort.nodes;\n\n // Verify that all requested entities exist by name!\n const responses = new Map();\n for (let name of order) {\n const provider = entities.get(name);\n if (!provider) {\n throw new Error(`Data has been requested from source '${name}', but no matching source was provided`);\n }\n\n // Each promise should only be triggered when the things it depends on have been resolved\n const depends_on = dag.get(name) || [];\n const prereq_promises = Promise.all(depends_on.map((name) => responses.get(name)));\n\n const this_result = prereq_promises.then((prior_results) => {\n // Each request will be told the name of the provider that requested it. This can be used during post-processing,\n // eg to use the same endpoint adapter twice and label where the fields came from (assoc.id, assoc2.id)\n // This has a secondary effect: it ensures that any changes made to \"shared\" options in one adapter will\n // not leak out to others via a mutable shared object reference.\n const options = Object.assign({_provider_name: name}, shared_options);\n return provider.getData(options, ...prior_results);\n });\n responses.set(name, this_result);\n }\n return Promise.all([...responses.values()])\n .then((all_results) => {\n if (consolidate) {\n // Some usages- eg fetch + data join tasks- will only require the last response in the sequence\n // Consolidate mode is the common use case, since returning a list of responses is not so helpful (depends on order of request, not order specified)\n return all_results[all_results.length - 1];\n }\n return all_results;\n });\n}\n\n\nexport {getLinkedData};\n\n// For testing only\nexport {_parse_declaration};\n","/**\n * Very simple client-side data joins. Useful for aligning records from two datasets based on a common key.\n */\nimport { clone } from './util';\n\n\n/**\n * Simple grouping function, used to identify sets of records for joining.\n *\n * Used internally by join helpers, exported mainly for unit testing\n * @memberOf module:undercomplicate\n * @param {object[]} records\n * @param {string} group_key\n * @returns {Map}\n */\nfunction groupBy(records, group_key) {\n const result = new Map();\n for (let item of records) {\n const item_group = item[group_key];\n\n if (typeof item_group === 'undefined') {\n throw new Error(`All records must specify a value for the field \"${group_key}\"`);\n }\n if (typeof item_group === 'object') {\n // If we can't group this item, then don't (exclude object, array, map, null, etc from grouping keys)\n throw new Error('Attempted to group on a field with non-primitive values');\n }\n\n let group = result.get(item_group);\n if (!group) {\n group = [];\n result.set(item_group, group);\n }\n group.push(item);\n }\n return result;\n}\n\n\nfunction _any_match(type, left, right, left_key, right_key) {\n // Helper that consolidates logic for all three join types\n const right_index = groupBy(right, right_key);\n const results = [];\n for (let item of left) {\n const left_match_value = item[left_key];\n const right_matches = right_index.get(left_match_value) || [];\n if (right_matches.length) {\n // Record appears on both left and right; equiv to an inner join\n results.push(...right_matches.map((right_item) => Object.assign({}, clone(right_item), clone(item))));\n } else if (type !== 'inner') {\n // Record appears on left but not right\n results.push(clone(item));\n }\n }\n\n if (type === 'outer') {\n // Outer join part! We've already added all left-only and left-right matches; all that's left is the items that only appear on right side\n const left_index = groupBy(left, left_key);\n for (let item of right) {\n const right_match_value = item[right_key];\n const left_matches = left_index.get(right_match_value) || [];\n if (!left_matches.length) {\n results.push(clone(item));\n }\n }\n }\n return results;\n}\n\n/**\n * Equivalent to LEFT OUTER JOIN in SQL. Return all left records, joined to matching right data where appropriate.\n * @memberOf module:undercomplicate\n * @param {Object[]} left The left side recordset\n * @param {Object[]} right The right side recordset\n * @param {string} left_key The join field in left records\n * @param {string} right_key The join field in right records\n * @returns {Object[]}\n */\nfunction left_match(left, right, left_key, right_key) {\n return _any_match('left', ...arguments);\n}\n\n/**\n * Equivalent to INNER JOIN in SQL. Only return record joins if the key field has a match on both left and right.\n * @memberOf module:undercomplicate\n * @param {object[]} left The left side recordset\n * @param {object[]} right The right side recordset\n * @param {string} left_key The join field in left records\n * @param {string} right_key The join field in right records\n * @returns {Object[]}\n */\nfunction inner_match(left, right, left_key, right_key) {\n return _any_match('inner', ...arguments);\n}\n\n/**\n * Equivalent to FULL OUTER JOIN in SQL. Return records in either recordset, joined where appropriate.\n * @memberOf module:undercomplicate\n * @param {object[]} left The left side recordset\n * @param {object[]} right The right side recordset\n * @param {string} left_key The join field in left records\n * @param {string} right_key The join field in right records\n * @returns {Object[]}\n */\nfunction full_outer_match(left, right, left_key, right_key) {\n return _any_match('outer', ...arguments);\n}\n\nexport {left_match, inner_match, full_outer_match, groupBy};\n","/**\n * Parse useful entities\n */\n\n/**\n * @private\n */\nconst REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\\d+)[_:|-]?(\\w+)?[/_:|-]?([^_]+)?_?(.*)?/;\n\n/**\n * Parse a single marker, cleaning up values as necessary\n * @private\n * @param {String} value\n * @param {boolean} test If called in testing mode, do not throw an exception\n * @returns {Array} chr, pos, ref, alt (if match found; ref and alt optional)\n */\nfunction parseMarker(value, test = false) {\n const match = value && value.match(REGEX_MARKER);\n if (match) {\n return match.slice(1);\n }\n if (!test) {\n throw new Error(`Could not understand marker format for ${value}. Should be of format chr:pos or chr:pos_ref/alt`);\n } else {\n return null;\n }\n}\n\n/**\n * Normalize a provided variant string into the EPACTS-style `chrom:pos_ref/alt` format expected by LocusZoom and the Michigan LD Server\n * This allows harmonizing various input data to a consistent format\n * @private\n * @param {String} variant A string that specifies variant information in one of several common formats (like chr1:99_A/C, 1-99-A-C, 1:99:A:C, etc)\n */\nfunction normalizeMarker(variant) {\n const match = parseMarker(variant);\n if (!match) {\n throw new Error(`Unable to normalize marker format for variant: ${variant}`);\n }\n const [chrom, pos, ref, alt] = match;\n let normalized = `${chrom}:${pos}`;\n if (ref && alt) {\n normalized += `_${ref}/${alt}`;\n }\n return normalized;\n}\n\n\nexport {\n parseMarker,\n normalizeMarker,\n};\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/\", source: 1 }]);\n * data_sources.add(\"trait2\", [\"AssociationLZ\", { url: \"http://server.com/api/single/\", 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\nimport {BaseUrlAdapter} from './undercomplicate';\n\nimport {parseMarker} from '../helpers/parse';\n\n/**\n * Replaced with the BaseLZAdapter class.\n * @public\n * @deprecated\n */\nclass BaseAdapter {\n constructor() {\n throw new Error('The \"BaseAdapter\" and \"BaseApiAdapter\" classes have been replaced in LocusZoom 0.14. See migration guide for details.');\n }\n}\n\n/**\n * Removed 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 * @deprecated\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\n\n/**\n * @extends module:undercomplicate.BaseUrlAdapter\n * @inheritDoc\n */\nclass BaseLZAdapter extends BaseUrlAdapter {\n /**\n * @param [config.cache_enabled=true]\n * @param [config.cache_size=3]\n * @param [config.url]\n * @param [config.prefix_namespace=true] Whether to modify the API response by prepending namespace to each field name.\n * Most adapters will do this by default, so that each field is unambiguously defined based on where it comes from. (this helps to disambiguate two providers that return similar field names, like assoc:variant and catalog:variant)\n * Typically, this is only disabled if the response payload is very unusual\n * @param {String[]} [config.limit_fields=null] If an API returns far more data than is needed, this can be used to simplify\n * the payload by excluding unused fields. This can help to reduce memory usage for really big server responses like LD.\n */\n constructor(config = {}) {\n if (config.params) {\n // Backwards-compat: prevent old sources from breaking in subtle ways because config options are no longer split between two places.\n console.warn('Deprecation warning: all options in \"config.params\" should now be specified as top level keys.');\n Object.assign(config, config.params || {});\n delete config.params; // fields are moved, not just copied in both places; Custom code will need to reflect new reality!\n }\n super(config);\n\n // Prefix the namespace for this source to all fieldnames: id -> assoc.id\n // This is useful for almost all layers because the layout object says where to find every field, exactly.\n // For some very complex data structure- mainly the Genes API payload- the datalayer might want to operate on\n // that complex set of fields directly. Disable _prefix_namespace to get field names as they appear\n // in the response. (gene_name instead of genes.gene_name)\n const { prefix_namespace = true, limit_fields } = config;\n this._prefix_namespace = prefix_namespace;\n this._limit_fields = limit_fields ? new Set(limit_fields) : false; // Optional and typically only used for very standard datasets like LD or catalog, where API returns >> what is displayed. People want to show their own custom annos for assoc plots pretty often, so the most-often-customized adapters don't specify limit_fields\n }\n\n /**\n * Determine how a particular request will be identified in cache. Most LZ requests are region based,\n * so the default is a string concatenation of `chr_start_end`. This adapter is \"region aware\"- if the user\n * zooms in, it won't trigger a network request because we alread have the data needed.\n * @param options Receives plot.state plus any other request options defined by this source\n * @returns {string}\n * @public\n */\n _getCacheKey(options) {\n // Most LZ adapters are fetching REGION data, and it makes sense to treat zooming as a cache hit by default\n let {chr, start, end} = options; // Current view: plot.state\n\n // Does a prior cache hit qualify as a superset of the ROI?\n const superset = this._cache.find(({metadata: md}) => chr === md.chr && start >= md.start && end <= md.end);\n if (superset) {\n ({ chr, start, end } = superset.metadata);\n }\n\n // The default cache key is region-based, and this method only returns the region-based part of the cache hit\n // That way, methods that override the key can extend the base value and still get the benefits of region-overlap-check\n options._cache_meta = { chr, start, end };\n return `${chr}_${start}_${end}`;\n }\n\n /**\n * Add the \"local namespace\" as a prefix for every field returned for this request. Eg if the association api\n * returns a field called variant, and the source is referred to as \"assoc\" within a particular data layer, then\n * the returned records will have a field called \"assoc:variant\"\n *\n * @param records\n * @param options\n * @returns {*}\n * @public\n */\n _postProcessResponse(records, options) {\n if (!this._prefix_namespace || !Array.isArray(records)) {\n return records;\n }\n\n // Transform fieldnames to include the namespace name as a prefix. For example, a data layer that asks for\n // assoc data might see \"variant\" as \"assoc.variant\"\n const { _limit_fields } = this;\n const { _provider_name } = options;\n\n return records.map((row) => {\n return Object.entries(row).reduce(\n (acc, [label, value]) => {\n // Rename API fields to format `namespace:fieldname`. If an adapter specifies limit_fields, then remove any unused API fields from the final payload.\n if (!_limit_fields || _limit_fields.has(label)) {\n acc[`${_provider_name}:${label}`] = value;\n }\n return acc;\n },\n {},\n );\n });\n }\n\n /**\n * Convenience method, manually called in LZ sources that deal with dependent data.\n *\n * In the last step of fetching data, LZ adds a prefix to each field name.\n * This means that operations like \"build query based on prior data\" can't just ask for \"log_pvalue\" because\n * they are receiving \"assoc:log_pvalue\" or some such unknown prefix.\n *\n * This helper lets us use dependent data more easily. Not every adapter needs to use this method.\n *\n * @param {Object} a_record One record (often the first one in a set of records)\n * @param {String} fieldname The desired fieldname, eg \"log_pvalue\"\n */\n _findPrefixedKey(a_record, fieldname) {\n const suffixer = new RegExp(`:${fieldname}$`);\n const match = Object.keys(a_record).find((key) => suffixer.test(key));\n if (!match) {\n throw new Error(`Could not locate the required key name: ${fieldname} in dependent data`);\n }\n return match;\n }\n}\n\n\n/**\n * The base adapter for the UMich Portaldev API server. This adds a few custom behaviors that handle idiosyncrasies\n * of one particular web server.\n * @extends module:LocusZoom_Adapters~BaseLZAdapter\n * @inheritDoc\n */\nclass BaseUMAdapter extends BaseLZAdapter {\n /**\n * @param {Object} config\n * @param {String} [config.build] The genome build to be used by all requests for this adapter. (UMich APIs are all genome build aware). \"GRCh37\" or \"GRCh38\"\n */\n constructor(config = {}) {\n super(config);\n // The UM portaldev API accepts an (optional) parameter \"genome_build\"\n this._genome_build = config.genome_build || config.build;\n }\n\n _validateBuildSource(build, source) {\n // Build OR Source, not both\n if ((build && source) || !(build || source)) {\n throw new Error(`${this.constructor.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(`${this.constructor.name} must specify a valid 'genome_build'`);\n }\n }\n\n // Special behavior for the UM portaldev API: col -> row format normalization\n /**\n * Some endpoints in the UM portaldev API returns columns of data, rather than rows. Convert the response to record objects, each row of a table being represented as an object of {field:value} pairs.\n * @param response_text\n * @param options\n * @returns {Object[]}\n * @public\n */\n _normalizeResponse(response_text, options) {\n let data = super._normalizeResponse(...arguments);\n // Most portaldev endpoints (though not all) store the desired response in just one specific part of the payload\n data = data.data || data;\n\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 columns, and create an object for each row 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\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~BaseUMAdapter\n * @inheritDoc\n *\n * @param {Number} config.source The source ID for the dataset of interest, used to construct the request URL\n */\nclass AssociationLZ extends BaseUMAdapter {\n constructor(config = {}) {\n super(config);\n\n // We don't validate the source option because a depressing number of people use AssociationLZ to serve non-dynamic JSON files\n const { source } = config;\n this._source_id = source;\n }\n\n _getURL (request_options) {\n const {chr, start, end} = request_options;\n const base = super._getURL(request_options);\n return `${base}results/?filter=analysis in ${this._source_id} and chromosome in '${chr}' and position ge ${start} and position le ${end}`;\n }\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~BaseUMAdapter\n */\nclass GwasCatalogLZ extends BaseUMAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param [config.build] The genome build to use when requesting the specific genomic region.\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.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 if (!config.limit_fields) {\n config.limit_fields = ['log_pvalue', 'pos', 'rsid', 'trait', 'variant'];\n }\n super(config);\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n _getURL(request_options) {\n const build = request_options.genome_build || this._config.build;\n const source = this._config.source;\n this._validateBuildSource(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\n const base = super._getURL(request_options);\n return `${base}?format=objects&sort=pos&filter=chrom eq '${request_options.chr}' and pos ge ${request_options.start} and pos le ${request_options.end}${source_query}`;\n }\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~BaseUMAdapter\n * @param {string} config.url The base URL for the remote data\n * @param [config.build] The genome build to use\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.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 BaseUMAdapter {\n constructor(config = {}) {\n super(config);\n\n // The UM Genes API has a very complex internal format and the genes layer is written to work with it exactly as given.\n // We will avoid transforming or modifying the payload.\n this._prefix_namespace = false;\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n _getURL(request_options) {\n const build = request_options.genome_build || this._config.build;\n let source = this._config.source;\n this._validateBuildSource(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\n const base = super._getURL(request_options);\n return `${base}?filter=chrom eq '${request_options.chr}' and start le ${request_options.end} and end ge ${request_options.start}${source_query}`;\n }\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~BaseUMAdapter\n */\nclass GeneConstraintLZ extends BaseLZAdapter {\n /**\n * @param {string} config.url The base URL for the remote data\n * @param [config.build] The genome build to use\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._prefix_namespace = false;\n }\n\n _buildRequestOptions(state, genes_data) {\n const build = state.genome_build || this._config.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 = new Set();\n for (let gene of genes_data) {\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 unique_gene_names.add(gene.gene_name);\n }\n\n state.query = [...unique_gene_names.values()].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 state.build = build;\n return Object.assign({}, state);\n }\n\n _performRequest(options) {\n let {query, build} = options;\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 to set max cost ~25 genes)\n // - No genes in region (hence no constraint info)\n return Promise.resolve([]);\n }\n query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas\n\n const url = this._getURL(options);\n\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 * The gnomAD API has a very complex internal data format. Bypass any record parsing or transform steps.\n */\n _normalizeResponse(response_text) {\n if (typeof response_text !== 'string') {\n // If the query short-circuits, we receive an empty list instead of a string\n return response_text;\n }\n const data = JSON.parse(response_text);\n return data.data;\n }\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 and yse that as the LD reference variant.\n *\n * THIS ADAPTER EXPECTS TO RECEIVE ASSOCIATION DATA WITH FIELDS `variant` and `log_pvalue`. It may not work correctly\n * if this information is not provided.\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. 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~BaseUMAdapter\n */\nclass LDServer extends BaseUMAdapter {\n /**\n * @param {string} config.url The base URL for the remote data.\n * @param [config.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.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.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.method='rsquare'] The metric used to calculate LD\n */\n constructor(config) {\n if (!config.limit_fields) {\n config.limit_fields = ['variant2', 'position2', 'correlation'];\n }\n super(config);\n }\n\n __find_ld_refvar(state, assoc_data) {\n const assoc_variant_name = this._findPrefixedKey(assoc_data[0], 'variant');\n const assoc_logp_name = this._findPrefixedKey(assoc_data[0], 'log_pvalue');\n\n // Determine the reference variant (via user selected OR automatic-per-track)\n let refvar;\n let best_hit = {};\n if (state.ldrefvar) {\n // State/ldrefvar would store the variant in the format used by assoc data, so no need to clean up to match in data\n refvar = state.ldrefvar;\n best_hit = assoc_data.find((item) => item[assoc_variant_name] === refvar) || {};\n } else {\n // find highest log-value and associated var spec\n let best_logp = 0;\n for (let item of assoc_data) {\n const { [assoc_variant_name]: variant, [assoc_logp_name]: log_pvalue} = item;\n if (log_pvalue > best_logp) {\n best_logp = log_pvalue;\n refvar = variant;\n best_hit = item;\n }\n }\n }\n\n // Add a special field that is not part of the assoc or LD data from the server, but has significance for plotting.\n // Since we already know the best hit, it's easier to do this here rather than in annotate or join phase.\n best_hit.lz_is_ld_refvar = true;\n\n // Above, we compared the ldrefvar to the assoc data. But for talking to the LD server,\n // the variant fields must be normalized to a specific format. All later LD operations will use that format.\n const match = parseMarker(refvar, true);\n if (!match) {\n throw new Error('Could not request LD for a missing or incomplete marker format');\n }\n\n const [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 refvar = `${chrom}:${pos}`; // FIXME: is this a server request that we can skip?\n if (ref && alt) {\n refvar += `_${ref}/${alt}`;\n }\n\n const coord = +pos;\n // Last step: sanity check the proposed reference variant. Is it inside the view region? If not, we're probably\n // remembering a user choice from before user jumped to a new region. LD should be relative to something nearby.\n if ((coord && state.ldrefvar && state.chr) && (chrom !== String(state.chr) || coord < state.start || coord > state.end)) {\n // Rerun this method, after clearing out the proposed reference variant. NOTE: Adapter call receives a\n // *copy* of plot.state, so wiping here doesn't remove the original value.\n state.ldrefvar = null;\n return this.__find_ld_refvar(state, assoc_data);\n }\n\n // Return the reference variant, in a normalized format suitable for LDServer queries\n return refvar;\n }\n\n _buildRequestOptions(state, assoc_data) {\n if (!assoc_data) {\n throw new Error('LD request must depend on association data');\n }\n\n // If no state refvar is provided, find the most significant variant in any provided assoc data.\n // Assumes that assoc satisfies the \"assoc\" fields contract, eg has fields variant and log_pvalue\n const base = super._buildRequestOptions(...arguments);\n if (!assoc_data.length) {\n // No variants, so no need to annotate association data with LD!\n // NOTE: Revisit. This could have odd cache implications (eg, when joining two assoc datasets to LD, and only the second dataset has data in the region)\n base._skip_request = true;\n return base;\n }\n\n base.ld_refvar = this.__find_ld_refvar(state, assoc_data);\n\n // The LD source/pop can be overridden from plot.state, so that user choices can override initial source config\n const genome_build = state.genome_build || this._config.build || 'GRCh37'; // This isn't expected to change after the data is plotted.\n let ld_source = state.ld_source || this._config.source || '1000G';\n const ld_population = state.ld_pop || this._config.population || 'ALL'; // LDServer panels will always have an ALL\n\n if (ld_source === '1000G' && genome_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 ld_source = '1000G-FRZ09';\n }\n\n this._validateBuildSource(genome_build, null); // LD doesn't need to validate `source` option\n return Object.assign({}, base, { genome_build, ld_source, ld_population });\n }\n\n _getURL(request_options) {\n const method = this._config.method || 'rsquare';\n const {\n chr, start, end,\n ld_refvar,\n genome_build, ld_source, ld_population,\n } = request_options;\n\n const base = super._getURL(request_options);\n\n return [\n base, 'genome_builds/', genome_build, '/references/', ld_source, '/populations/', ld_population, '/variants',\n '?correlation=', method,\n '&variant=', encodeURIComponent(ld_refvar),\n '&chrom=', encodeURIComponent(chr),\n '&start=', encodeURIComponent(start),\n '&stop=', encodeURIComponent(end),\n ].join('');\n }\n\n _getCacheKey(options) {\n // LD is keyed by more than just region; append other parameters to the base cache key\n const base = super._getCacheKey(options);\n const { ld_refvar, ld_source, ld_population } = options;\n return `${base}_${ld_refvar}_${ld_source}_${ld_population}`;\n }\n\n _performRequest(options) {\n // Skip request if this one depends on other data, and we are in a region with no data\n if (options._skip_request) {\n // TODO: A skipped request leads to a cache value; possible edge cases where this could get weird.\n return Promise.resolve([]);\n }\n\n const url = this._getURL(options);\n\n // The UM LDServer uses API pagination; fetch all data by chaining requests when pages are detected\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/**\n * Retrieve Recombination Rate Data, as fetched from the LocusZoom API server (or compatible)\n * @public\n * @see module:LocusZoom_Adapters~BaseUMAdapter\n * @param {string} config.url The base URL for the remote data\n * @param [config.build] The genome build to use\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.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 BaseUMAdapter {\n constructor(config) {\n if (!config.limit_fields) {\n config.limit_fields = ['position', 'recomb_rate'];\n }\n super(config);\n }\n\n /**\n * Add query parameters to the URL to construct a query for the specified region\n */\n _getURL(request_options) {\n const build = request_options.genome_build || this._config.build;\n let source = this._config.source;\n this._validateBuildSource(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\n const base = super._getURL(request_options);\n return `${base}?filter=chromosome eq '${request_options.chr}' and position le ${request_options.end} and position ge ${request_options.start}${source_query}`;\n }\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~BaseLZAdapter\n * @param {object} config.data The data to be returned by this source (subject to namespacing rules)\n */\nclass StaticSource extends BaseLZAdapter {\n constructor(config = {}) {\n // Does not receive any config; the only argument is the raw data, embedded when source is created\n super(...arguments);\n const { data } = config;\n if (!data || Array.isArray(config)) { // old usages may provide an array directly instead of as config key\n throw new Error(\"'StaticSource' must provide data as required option 'config.data'\");\n }\n this._data = data;\n }\n\n _performRequest(options) {\n return Promise.resolve(this._data);\n }\n}\n\n\n/**\n * Retrieve PheWAS data retrieved from a LocusZoom/PortalDev compatible API\n * @public\n * @see module:LocusZoom_Adapters~BaseUMAdapter\n * @param {string} config.url The base URL for the remote data\n * @param {String[]} config.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 BaseUMAdapter {\n _getURL(request_options) {\n const build = (request_options.genome_build ? [request_options.genome_build] : null) || this._config.build;\n if (!build || !Array.isArray(build) || !build.length) {\n throw new Error(['Adapter', this.constructor.name, 'requires that you specify array of one or more desired genome build names'].join(' '));\n }\n const base = super._getURL(request_options);\n const url = [\n base,\n \"?filter=variant eq '\", encodeURIComponent(request_options.variant), \"'&format=objects&\",\n build.map(function (item) {\n return `build=${encodeURIComponent(item)}`;\n }).join('&'),\n ];\n return url.join('');\n }\n\n _getCacheKey(options) {\n // Not a region based source; don't do anything smart for cache check\n return this._getURL(options);\n }\n}\n\n// Deprecated symbols\nexport { BaseAdapter, BaseApiAdapter };\n\n// Usually used as a parent class for custom code\nexport { BaseLZAdapter, BaseUMAdapter };\n\n// Usually used as a standalone class\nexport {\n AssociationLZ,\n GeneConstraintLZ,\n GeneLZ,\n GwasCatalogLZ,\n LDServer,\n PheWASLZ,\n RecombLZ,\n StaticSource,\n};\n","import {LRUCache} from './lru_cache';\nimport {clone} from './util';\n\n/**\n * @param {boolean} [config.cache_enabled=true] Whether to enable the LRU cache, and store a copy of the normalized and parsed response data.\n * Turned on by default for most remote requests; turn off if you are using another datastore (like Vuex) or if the response body uses too much memory.\n * @param {number} [config.cache_size=3] How many requests to cache. Track-dependent annotations like LD might benefit\n * from caching more items, while very large payloads (like, um, TOPMED LD) might benefit from a smaller cache size.\n * For most LocusZoom usages, the cache is \"region aware\": zooming in will use cached data, not a separate request\n * @inheritDoc\n * @memberOf module:undercomplicate\n */\nclass BaseAdapter {\n constructor(config = {}) {\n this._config = config;\n const {\n // Cache control\n cache_enabled = true,\n cache_size = 3,\n } = config;\n this._enable_cache = cache_enabled;\n this._cache = new LRUCache(cache_size);\n }\n\n /**\n * Build an object with options that control the request. This can take into account both explicit options, and prior data.\n * @param {Object} options Any global options passed in via `getData`. Eg, in locuszoom, every request is passed a copy of `plot.state` as the options object, in which case every adapter would expect certain basic information like `chr, start, end` to be available.\n * @param {Object[]} dependent_data If the source is called with dependencies, this function will receive one argument with the fully parsed response data from each other source it depends on. Eg, `ld(assoc)` means that the LD adapter would be called with the data from an association request as a function argument. Each dependency is its own argument: there can be 0, 1, 2, ...N arguments.\n * @returns {*} An options object containing initial options, plus any calculated values relevant to the request.\n * @public\n */\n _buildRequestOptions(options, dependent_data) {\n // Perform any pre-processing required that may influence the request. Receives an array with the payloads\n // for each request that preceded this one in the dependency chain\n // This method may optionally take dependent data into account. For many simple adapters, there won't be any dependent data!\n return Object.assign({}, options);\n }\n\n /**\n * Determine how this request is uniquely identified in cache. Usually this is an exact match for the same key, but it doesn't have to be.\n * The LRU cache implements a `find` method, which means that a cache item can optionally be identified by its node\n * `metadata` (instead of exact key match).\n * This is useful for situations where the user zooms in to a smaller region and wants the original request to\n * count as a cache hit. See subclasses for example.\n * @param {object} options Request options from `_buildRequestOptions`\n * @returns {*} This is often a string concatenating unique values for a compound cache key, like `chr_start_end`. If null, it is treated as a cache miss.\n * @public\n */\n _getCacheKey(options) {\n /* istanbul ignore next */\n if (this._enable_cache) {\n throw new Error('Method not implemented');\n }\n return null;\n }\n\n /**\n * Perform the act of data retrieval (eg from a URL, blob, or JSON entity)\n * @param {object} options Request options from `_buildRequestOptions`\n * @returns {Promise}\n * @public\n */\n _performRequest(options) {\n /* istanbul ignore next */\n throw new Error('Not implemented');\n }\n\n /**\n * Convert the response format into a list of objects, one per datapoint. Eg split lines of a text file, or parse a blob of json.\n * @param {*} response_text The raw response from performRequest, be it text, binary, etc. For most web based APIs, it is assumed to be text, and often JSON.\n * @param {Object} options Request options. These are not typically used when normalizing a response, but the object is available.\n * @returns {*} A list of objects, each object representing one row of data `{column_name: value_for_row}`\n * @public\n */\n _normalizeResponse(response_text, options) {\n return response_text;\n }\n\n /**\n * Perform custom client-side operations on the retrieved data. For example, add calculated fields or\n * perform rapid client-side filtering on cached data. Annotations are applied after cache, which means\n * that the same network request can be dynamically annotated/filtered in different ways in response to user interactions.\n *\n * This result is currently not cached, but it may become so in the future as responsibility for dynamic UI\n * behavior moves to other layers of the application.\n * @param {Object[]} records\n * @param {Object} options\n * @returns {*}\n * @public\n */\n _annotateRecords(records, options) {\n return records;\n }\n\n /**\n * A hook to transform the response after all operations are done. For example, this can be used to prefix fields\n * with a namespace unique to the request, like `log_pvalue` -> `assoc:log_pvalue`. (by applying namespace prefixes to field names last,\n * annotations and validation can happen on the actual API payload, without having to guess what the fields were renamed to).\n * @param records\n * @param options\n * @public\n */\n _postProcessResponse(records, options) {\n return records;\n }\n\n /**\n * All adapters must implement this method to asynchronously return data. All other methods are simply internal hooks to customize the actual request for data.\n * @param {object} options Shared options for this request. In LocusZoom, this is typically a copy of `plot.state`.\n * @param {Array[]} dependent_data Zero or more recordsets corresponding to each individual adapter that this one depends on.\n * Can be used to build a request that takes into account prior data.\n * @returns {Promise<*>}\n */\n getData(options = {}, ...dependent_data) {\n // Public facing method to define, perform, and process the request\n options = this._buildRequestOptions(options, ...dependent_data);\n\n const cache_key = this._getCacheKey(options);\n\n // Then retrieval and parse steps: parse + normalize response, annotate\n let result;\n if (this._enable_cache && this._cache.has(cache_key)) {\n result = this._cache.get(cache_key);\n } else {\n // Cache the promise (to avoid race conditions in conditional fetch). If anything (like `_getCacheKey`)\n // sets a special option value called `_cache_meta`, this will be used to annotate the cache entry\n // For example, this can be used to decide whether zooming into a view could be satisfied by a cache entry,\n // even if the actual cache key wasn't an exact match. (see subclasses for an example; this class is generic)\n result = Promise.resolve(this._performRequest(options))\n // Note: we cache the normalized (parsed) response\n .then((text) => this._normalizeResponse(text, options));\n this._cache.add(cache_key, result, options._cache_meta);\n // We are caching a promise, which means we want to *un*cache a promise that rejects, eg a failed or interrupted request\n // Otherwise, temporary failures couldn't be resolved by trying again in a moment\n // TODO: In the future, consider providing a way to skip requests (eg, a sentinel value to flag something\n // as not cacheable, like \"no dependent data means no request... but maybe in another place this is used, there will be different dependent data and a request would make sense\")\n result.catch((e) => this._cache.remove(cache_key));\n }\n\n return result\n // Return a deep clone of the data, so that there are no shared mutable references to a parsed object in cache\n .then((data) => clone(data))\n .then((records) => this._annotateRecords(records, options))\n .then((records) => this._postProcessResponse(records, options));\n }\n}\n\n\n/**\n * Fetch data over the web, usually from a REST API that returns JSON\n * @param {string} config.url The URL to request\n * @extends module:undercomplicate.BaseAdapter\n * @inheritDoc\n * @memberOf module:undercomplicate\n */\nclass BaseUrlAdapter extends BaseAdapter {\n constructor(config = {}) {\n super(config);\n this._url = config.url;\n }\n\n\n /**\n * Default cache key is the URL for this request\n * @public\n */\n _getCacheKey(options) {\n return this._getURL(options);\n }\n\n /**\n * In many cases, the base url should be modified with query parameters based on request options.\n * @param options\n * @returns {*}\n * @private\n */\n _getURL(options) {\n return this._url;\n }\n\n _performRequest(options) {\n const url = this._getURL(options);\n // Many resources will modify the URL to add query or segment parameters. Base method provides option validation.\n // (not validating in constructor allows URL adapter to be used as more generic parent class)\n if (!this._url) {\n throw new Error('Web based resources must specify a resource URL as option \"url\"');\n }\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 _normalizeResponse(response_text, options) {\n if (typeof response_text === 'string') {\n return JSON.parse(response_text);\n }\n // Some custom usages will return other datatypes. These would need to be handled by custom normalization logic in a subclass.\n return response_text;\n }\n}\n\nexport { BaseAdapter, BaseUrlAdapter };\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 // Two scenarios: we are requesting a field by full name, OR there are transforms to apply\n // `fieldname` or `namespace:fieldname` followed by `|filter1|filterN`\n const field_pattern = /^(?:\\w+:\\w+|^\\w+)(?:\\|\\w+)*$/;\n if (!field_pattern.test(field)) {\n throw new Error(`Invalid field specifier: '${field}'`);\n }\n\n const [name, ...transforms] = field.split('|');\n\n this.full_name = field; // fieldname + transforms\n this.field_name = name; // just fieldname\n this.transformations = transforms.map((name) => TRANSFORMS.get(name));\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 // Four resolutions: a) This is cached, b) this can be calculated from a known field, c) this is a known annotation rather than from an API, d) This field doesn't exist and returns as null\n if (typeof data[this.full_name] == 'undefined') { // Check for cached result\n let val = null;\n if (data[this.field_name] !== undefined) { // Fallback: value sans transforms\n val = data[this.field_name];\n } else if (extra && extra[this.field_name] !== undefined) { // Fallback: check annotations\n val = extra[this.field_name];\n } // Don't warn if no value found, because sometimes only certain rows will have a specific field (esp happens with annotations)\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 shared namespaces to a layout, recursively.\n *\n * Overriding namespaces can be used to identify where to retrieve data from, but not to add new data sources to a layout.\n * For that, a key would have to be added to `layout.namespace` directly.\n *\n * Detail: This function is a bit magical. Whereas most layouts overrides are copied over verbatim (merging objects and nested keys), applyNamespaces will *only* copy\n * over keys that are relevant to that data layer. Eg, if overrides specifies a key called \"red_herring\",\n * an association data layer will ignore that data source entirely, and not copy it into `assoc_layer.namespace`.\n *\n * Only items under a key called `namespace` are given this special treatment. This allows a single call to `Layouts.get('plot'...)` to specify\n * namespace overrides for many layers in one convenient place, without accidentally telling every layer to request all possible data for itself.\n * @private\n */\nfunction applyNamespaces(layout, shared_namespaces) {\n shared_namespaces = shared_namespaces || {};\n if (!layout || typeof layout !== 'object' || typeof shared_namespaces !== 'object') {\n throw new Error('Layout and shared namespaces must be provided as objects');\n }\n\n for (let [field_name, item] of Object.entries(layout)) {\n if (field_name === 'namespace') {\n Object.keys(item).forEach((requested_ns) => {\n const override = shared_namespaces[requested_ns];\n if (override) {\n item[requested_ns] = override;\n }\n });\n } else if (item !== null && (typeof item === 'object')) {\n layout[field_name] = applyNamespaces(item, shared_namespaces);\n }\n }\n return layout;\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 // FIXME: initial attempt to replace this with a more efficient deep clone method caused merge() to break; revisit in future.\n // Replacing this with a proper clone would be the key blocker to allowing functions and non-JSON values (like infinity) in layout objects\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/**\n * Find all references to namespaced fields within a layout object. This is used to validate that a set of provided\n * data adapters will actually give all the information required to draw the plot.\n * @param {Object} layout\n * @param {Array|null} prefixes A list of allowed namespace prefixes. (used to differentiate between real fields,\n * and random sentences that match an arbitrary pattern.\n * @param {RegExp|null} field_finder On recursive calls, pass the regexp we constructed the first time\n * @return {Set}\n */\nfunction findFields(layout, prefixes, field_finder = null) {\n const fields = new Set();\n if (!field_finder) {\n if (!prefixes.length) {\n // A layer that doesn't ask for external data does not need to check if the provider returns expected fields\n return fields;\n }\n const all_ns = prefixes.join('|');\n\n // Locates any reference within a template string to to `ns:field`, `{{ns:field}}`, or `{{#if ns:field}}`.\n // By knowing the list of allowed NS prefixes, we can be much more confident in avoiding spurious matches\n field_finder = new RegExp(`(?:{{)?(?:#if *)?((?:${all_ns}):\\\\w+)`, 'g');\n }\n\n for (const value of Object.values(layout)) {\n const value_type = typeof value;\n let matches = [];\n if (value_type === 'string') {\n let a_match;\n while ((a_match = field_finder.exec(value)) !== null) {\n matches.push(a_match[1]);\n }\n } else if (value !== null && value_type === 'object') {\n matches = findFields(value, prefixes, field_finder);\n } else {\n // Only look for field names in strings or compound values\n continue;\n }\n for (let m of matches) {\n fields.add(m);\n }\n }\n return fields;\n}\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, findFields, renameField };\n","/**\n * @module\n * @private\n */\nimport {getLinkedData} from './undercomplicate';\n\nimport { DATA_OPS } from '../registry';\n\n\nclass DataOperation {\n /**\n * Perform a data operation (such as a join)\n * @param {String} join_type\n * @param initiator The entity that initiated the request for data. Usually, this is the data layer. This argument exists so that a data_operation could do things like auto-define axis labels/ color scheme in response to dynamic data. It has potential for side effects if misused, so use sparingly!\n * @param params Optional user/layout parameters to be passed to the data function\n */\n constructor(join_type, initiator, params) {\n this._callable = DATA_OPS.get(join_type);\n this._initiator = initiator;\n this._params = params || [];\n }\n\n getData(plot_state, ...dependent_recordsets) {\n // Most operations are joins: they receive two pieces of data (eg left + right)\n // Other ops are possible, like consolidating just one set of records to best value per key\n // Hence all dependencies are passed as first arg: [dep1, dep2, dep3...]\n\n // Every data operation receives plot_state, reference to the data layer that called it, the input data, & any additional options\n const context = {plot_state, data_layer: this._initiator};\n return Promise.resolve(this._callable(context, dependent_recordsets, ...this._params));\n }\n}\n\n\n/**\n * The Requester manages fetching of data across multiple data sources. It is used internally by LocusZoom data layers.\n * It passes plot.state information to each adapter, and ensures that a series of requests can be performed in a\n * designated order.\n *\n * Each data layer calls the requester object directly, and as such, each data layer has a private view of data: it can\n * perform its own calculations, filter results, and apply transforms without influencing other layers.\n * (while still respecting a shared cache where appropriate)\n *\n * This object is not part of the public interface. It should almost **never** be replaced or modified directly.\n *\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 /**\n * Parse the data layer configuration when a layer is first created.\n * Validate config, and return entities and dependencies in a format usable for data retrieval.\n * This is used by data layers, and also other data-retrieval functions (like subscribeToDate).\n *\n * Inherent assumptions:\n * 1. A data layer will always know its data up front, and layout mutations will only affect what is displayed.\n * 2. People will be able to add new data adapters (tracks), but if they are removed, the accompanying layers will be\n * removed at the same time. Otherwise, the pre-parsed data fetching logic could could preserve a reference to the\n * removed adapter.\n * @param {Object} namespace_options\n * @param {Array} data_operations\n * @param {Object|null} initiator The entity that initiated the request (the data layer). Passed to data operations,\n * but not adapters. By baking this reference into each data operation, functions can do things like autogenerate\n * axis tick marks or color schemes based on dyanmic data. This is an advanced usage and should be handled with care!\n * @returns {Array} Map of entities and list of dependencies\n */\n config_to_sources(namespace_options = {}, data_operations = [], initiator) {\n const entities = new Map();\n const namespace_local_names = Object.keys(namespace_options);\n\n // 1. Specify how to coordinate data. Precedence:\n // a) EXPLICIT fetch logic,\n // b) IMPLICIT auto-generate fetch order if there is only one NS,\n // c) Throw \"spec required\" error if > 1, because 2 adapters may need to be fetched in a sequence\n let dependency_order = data_operations.find((item) => item.type === 'fetch'); // explicit spec: {fetch, from}\n if (!dependency_order) {\n dependency_order = { type: 'fetch', from: namespace_local_names };\n data_operations.unshift(dependency_order);\n }\n\n // Validate that all NS items are available to the root requester in DataSources. All layers recognize a\n // default value, eg people copying the examples tend to have defined a datasource called \"assoc\"\n const ns_pattern = /^\\w+$/;\n for (let [local_name, global_name] of Object.entries(namespace_options)) {\n if (!ns_pattern.test(local_name)) {\n throw new Error(`Invalid namespace name: '${local_name}'. Must contain only alphanumeric characters`);\n }\n\n const source = this._sources.get(global_name);\n if (!source) {\n throw new Error(`A data layer has requested an item not found in DataSources: data type '${local_name}' from ${global_name}`);\n }\n entities.set(local_name, source);\n\n // Note: Dependency spec checker will consider \"ld(assoc)\" to match a namespace called \"ld\"\n if (!dependency_order.from.find((dep_spec) => dep_spec.split('(')[0] === local_name)) {\n // Sometimes, a new piece of data (namespace) will be added to a layer. Often this doesn't have any dependencies, other than adding a new join.\n // To make it easier to EXTEND existing layers, by default, we'll push any unknown namespaces to data_ops.fetch\n // Thus the default behavior is \"fetch all namespaces as though they don't depend on anything.\n // If they depend on something, only then does \"data_ops[@type=fetch].from\" need to be mutated\n dependency_order.from.push(local_name);\n }\n }\n\n let dependencies = Array.from(dependency_order.from);\n\n // Now check all joins. Are namespaces valid? Are they requesting known data?\n for (let config of data_operations) {\n let {type, name, requires, params} = config;\n if (type !== 'fetch') {\n let namecount = 0;\n if (!name) {\n name = config.name = `join${namecount}`;\n namecount += 1;\n }\n\n if (entities.has(name)) {\n throw new Error(`Configuration error: within a layer, join name '${name}' must be unique`);\n }\n requires.forEach((require_name) => {\n if (!entities.has(require_name)) {\n throw new Error(`Data operation cannot operate on unknown provider '${require_name}'`);\n }\n });\n\n const task = new DataOperation(type, initiator, params);\n entities.set(name, task);\n dependencies.push(`${name}(${requires.join(', ')})`); // Dependency resolver uses the form item(depA, depB)\n }\n }\n return [entities, dependencies];\n }\n\n /**\n * @param {Object} plot_state Plot state, which will be passed to every adapter. Includes view extent (chr, start, end)\n * @param {Map} entities A list of adapter and join tasks. This is created internally from data layer layouts.\n * Keys are layer-local namespaces for data types (like assoc), and values are adapter or join task instances\n * (things that implement a method getData).\n * @param {String[]} dependencies Instructions on what adapters to fetch from, in what order\n * @returns {Promise}\n */\n getData(plot_state, entities, dependencies) {\n if (!dependencies.length) {\n return Promise.resolve([]);\n }\n // The last dependency (usually the last join operation) determines the last thing returned.\n return getLinkedData(plot_state, entities, dependencies, true);\n }\n}\n\n\nexport default Requester;\n\nexport {DataOperation as _JoinTask};\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 const options = this.parent.layout.toolbar.widgets;\n if (Array.isArray(options)) {\n options.forEach((layout) => {\n this.addWidget(layout);\n });\n }\n\n // Add mouseover event handlers to show/hide panel toolbar (plot toolbar will always be shown)\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 * Add a new widget to the toolbar.\n * FIXME: Kludgy to use. In the very rare cases where a widget is added dynamically, the caller will need to:\n * - add the widget to plot.layout.toolbar.widgets, AND calling it with the same object reference here.\n * - call widget.show() to ensure that the widget is initialized and rendered correctly\n * When creating an existing plot defined in advance, neither of these actions is needed and so we don't do this by default.\n * @param {Object} layout The layout object describing the desired widget\n * @returns {layout.type}\n */\n addWidget(layout) {\n try {\n const widget = WIDGETS.create(layout.type, layout, this);\n this.widgets.push(widget);\n return widget;\n } catch (e) {\n console.warn('Failed to create widget');\n console.error(e);\n }\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: 14,\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 const layer_legend = this.parent.data_layers[id].layout.legend;\n if (Array.isArray(layer_legend)) {\n layer_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;\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 === 'ribbon') {\n // Color ribbons describe a series of color stops: small boxes of color across a continuous\n // scale. Drawn horizontally, or vertically, like:\n // [red | orange | yellow | green ] label\n // For example, this can be used with the numerical-bin color scale to describe LD color stops in a compact way.\n const width = +element.width || 25;\n const height = +element.height || width;\n const is_horizontal = (element.orientation || 'vertical') === 'horizontal';\n let color_stops = element.color_stops;\n\n const all_elements = selector.append('g');\n const ribbon_group = all_elements.append('g');\n const axis_group = all_elements.append('g');\n let axis_offset = 0;\n if (element.tick_labels) {\n let range;\n if (is_horizontal) {\n range = [0, width * color_stops.length - 1]; // 1 px offset to align tick with inner borders\n } else {\n range = [height * color_stops.length - 1, 0];\n }\n const scale = d3.scaleLinear()\n .domain(d3.extent(element.tick_labels)) // Assumes tick labels are always numeric in this mode\n .range(range);\n const axis = (is_horizontal ? d3.axisTop : d3.axisRight)(scale)\n .tickSize(3)\n .tickValues(element.tick_labels)\n .tickFormat((v) => v);\n axis_group\n .call(axis)\n .attr('class', 'lz-axis');\n let bcr = axis_group.node().getBoundingClientRect();\n axis_offset = bcr.height;\n }\n if (is_horizontal) {\n // Shift axis down (so that tick marks aren't above the origin)\n axis_group\n .attr('transform', `translate(0, ${axis_offset})`);\n // Ribbon appears below axis\n ribbon_group\n .attr('transform', `translate(0, ${axis_offset})`);\n } else {\n // Vertical mode: Shift axis ticks to the right of the ribbon\n all_elements.attr('transform', 'translate(5, 0)');\n axis_group\n .attr('transform', `translate(${width}, 0)`);\n }\n\n if (!is_horizontal) {\n // Vertical mode: renders top -> bottom but scale is usually specified low..high\n color_stops = color_stops.slice();\n color_stops.reverse();\n }\n for (let i = 0; i < color_stops.length; i++) {\n const color = color_stops[i];\n const to_next_marking = is_horizontal ? `translate(${width * i}, 0)` : `translate(0, ${height * i})`;\n ribbon_group\n .append('rect')\n .attr('class', element.class || '')\n .attr('stroke', 'black')\n .attr('transform', to_next_marking)\n .attr('stroke-width', 0.5)\n .attr('width', width)\n .attr('height', height)\n .attr('fill', color)\n .call(applyStyles, element.style || {});\n }\n\n // Note: In vertical mode, it's usually easier to put the label above the legend as a separate marker\n // This is because the legend element label is drawn last (can't use it's size to position the ribbon, which is drawn first)\n if (!is_horizontal && element.label) {\n throw new Error('Legend labels not supported for vertical ribbons (use a separate legend item as text instead)');\n }\n // This only makes sense for horizontal labels.\n label_x = (width * color_stops.length + padding);\n label_y += axis_offset;\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. Required.\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] The distance between the axis title and the axis. Use this to prevent\n * the title from overlapping with tick mark labels. If there is not enough space for the label, be sure to increase the panel margins (left or right) accordingly.\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 if (typeof layout.id !== 'string' || !layout.id) {\n throw new Error('Panel layouts must specify \"id\"');\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 // 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 const target_layer = this.data_layers[id];\n if (!target_layer) {\n throw new Error(`Unable to remove data layer, ID not found: ${id}`);\n }\n\n // Destroy all tooltips for the data layer\n target_layer.destroyAllTooltips();\n\n // Remove the svg container for the data layer if it exists\n if (target_layer.svg.container) {\n target_layer.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(target_layer._layout_idx, 1);\n delete this.state[target_layer._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 // 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 const { cliparea } = this.layout;\n\n // Set and position the inner border, style if necessary\n const { margin } = this.layout;\n this.inner_border\n .attr('x', margin.left)\n .attr('y', margin.top)\n .attr('width', this.parent_plot.layout.width - (margin.left + margin.right))\n .attr('height', this.layout.height - (margin.top + 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 const axes_config = this.layout.axes;\n if (this.x_extent) {\n const base_x_range = { start: 0, end: this.layout.cliparea.width };\n if (axes_config.x.range) {\n base_x_range.start = axes_config.x.range.start || base_x_range.start;\n base_x_range.end = axes_config.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: cliparea.height, end: 0 };\n if (axes_config.y1.range) {\n base_y1_range.start = axes_config.y1.range.start || base_y1_range.start;\n base_y1_range.end = axes_config.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: cliparea.height, end: 0 };\n if (axes_config.y2.range) {\n base_y2_range.start = axes_config.y2.range.start || base_y2_range.start;\n base_y2_range.end = axes_config.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 let { _interaction } = this.parent;\n const current_drag = _interaction.dragging;\n if (_interaction.panel_id && (_interaction.panel_id === this.id || _interaction.linked_panel_ids.includes(this.id))) {\n let anchor, scalar = null;\n if (_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 = _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 = _interaction.zooming.center - margin.left - this.layout.origin.x;\n const offset_ratio = anchor / 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 (current_drag) {\n switch (current_drag.method) {\n case 'background':\n ranges.x_shifted[0] = +current_drag.dragged_x;\n ranges.x_shifted[1] = cliparea.width + current_drag.dragged_x;\n break;\n case 'x_tick':\n if (d3.event && d3.event.shiftKey) {\n ranges.x_shifted[0] = +current_drag.dragged_x;\n ranges.x_shifted[1] = cliparea.width + current_drag.dragged_x;\n } else {\n anchor = current_drag.start_x - margin.left - this.layout.origin.x;\n scalar = constrain(anchor / (anchor + current_drag.dragged_x), 3);\n ranges.x_shifted[0] = 0;\n ranges.x_shifted[1] = Math.max(cliparea.width * (1 / scalar), 1);\n }\n break;\n case 'y1_tick':\n case 'y2_tick': {\n const y_shifted = `y${current_drag.method[1]}_shifted`;\n if (d3.event && d3.event.shiftKey) {\n ranges[y_shifted][0] = cliparea.height + current_drag.dragged_y;\n ranges[y_shifted][1] = +current_drag.dragged_y;\n } else {\n anchor = cliparea.height - (current_drag.start_y - margin.top - this.layout.origin.y);\n scalar = constrain(anchor / (anchor - current_drag.dragged_y), 3);\n ranges[y_shifted][0] = cliparea.height;\n ranges[y_shifted][1] = cliparea.height - (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 // Redefine b/c might have been changed during call to parent re-render\n _interaction = this.parent._interaction;\n _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((id) => {\n const axis = this.layout.axes[id];\n if (!Object.keys(axis).length || axis.render === false) {\n // The default layout sets the axis to an empty object, so set its render boolean here\n axis.render = false;\n } else {\n axis.render = true;\n axis.label = 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 const layout = this.layout;\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 layout.height = Math.max(Math.round(+height), layout.min_height);\n }\n }\n layout.cliparea.width = Math.max(this.parent_plot.layout.width - (layout.margin.left + layout.margin.right), 0);\n layout.cliparea.height = Math.max(layout.height - (layout.margin.top + layout.margin.bottom), 0);\n if (this.svg.clipRect) {\n this.svg.clipRect\n .attr('width', this.parent.layout.width)\n .attr('height', 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 const { cliparea, margin } = this.layout;\n if (!isNaN(top) && top >= 0) {\n margin.top = Math.max(Math.round(+top), 0);\n }\n if (!isNaN(right) && right >= 0) {\n margin.right = Math.max(Math.round(+right), 0);\n }\n if (!isNaN(bottom) && bottom >= 0) {\n margin.bottom = Math.max(Math.round(+bottom), 0);\n }\n if (!isNaN(left) && left >= 0) {\n 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 (margin.top + margin.bottom > this.layout.height) {\n extra = Math.floor(((margin.top + margin.bottom) - this.layout.height) / 2);\n margin.top -= extra;\n margin.bottom -= extra;\n }\n if (margin.left + margin.right > this.parent_plot.layout.width) {\n extra = Math.floor(((margin.left + margin.right) - this.parent_plot.layout.width) / 2);\n margin.left -= extra;\n margin.right -= extra;\n }\n ['top', 'right', 'bottom', 'left'].forEach((m) => {\n margin[m] = Math.max(margin[m], 0);\n });\n cliparea.width = Math.max(this.parent_plot.layout.width - (margin.left + margin.right), 0);\n cliparea.height = Math.max(this.layout.height - (margin.top + margin.bottom), 0);\n cliparea.origin.x = margin.left;\n cliparea.origin.y = 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 // 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 const { parent } = this;\n const y_index = this.layout.y_index;\n if (parent._panel_ids_by_y_index[y_index - 1]) {\n parent._panel_ids_by_y_index[y_index] = parent._panel_ids_by_y_index[y_index - 1];\n parent._panel_ids_by_y_index[y_index - 1] = this.id;\n parent.applyPanelYIndexesToPanelLayouts();\n 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 const { _panel_ids_by_y_index } = this.parent;\n if (_panel_ids_by_y_index[this.layout.y_index + 1]) {\n _panel_ids_by_y_index[this.layout.y_index] = _panel_ids_by_y_index[this.layout.y_index + 1];\n _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 // 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 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 // 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 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 )?([\\w+_:|]+)|(#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 * One particular data layer has completed a request for data. This event is primarily used internally by the `subscribeToData` function, and the syntax may change in the future.\n * @event data_from_layer\n * @property {object} data\n * @property {String} data.layer The fully qualified ID of the layer emitting this event\n * @property {Object[]} data.content The data used to draw this layer: an array where each element represents one row/ datum\n * element. It reflects all namespaces and data operations used by that layer.\n * @see event:any_lz_event\n */\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 const target_panel = this.panels[id];\n if (!target_panel) {\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 target_panel.loader.hide();\n target_panel.toolbar.destroy(true);\n target_panel.curtain.hide();\n\n // Remove the svg container for the panel if it exists\n if (target_panel.svg.container) {\n target_panel.svg.container.remove();\n }\n\n // Delete the panel and its presence in the plot layout and state\n this.layout.panels.splice(target_panel._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 * @param {Object} plot A reference to the plot object. This can be useful for listeners that react to the\n * structure of the data, instead of just displaying something.\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 * @listens event:data_from_layer\n * @param {Object} [opts] Options\n * @param {String} [opts.from_layer=null] The ID string (`panel_id.layer_id`) of a specific data layer to be watched.\n * @param {Object} [opts.namespace] An object specifying where to find external data. See data layer documentation for details.\n * @param {Object} [opts.data_operations] An array of data operations. If more than one source of data is requested,\n * this is usually required in order to specify dependency order and join operations. See data layer documentation for details.\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 {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 * @return {function} The newly created event listener, to allow for later cleanup/removal\n */\n subscribeToData(opts, success_callback) {\n const { from_layer, namespace, data_operations, onerror } = opts;\n\n // Register an event listener that is notified whenever new data has been rendered\n const error_callback = onerror || function (err) {\n console.error('An error occurred while acting on an external callback', err);\n };\n\n if (from_layer) {\n // Option 1: Subscribe to a data layer. Receive a copy of the exact data it receives; no need to duplicate NS or data operations code in two places.\n const base_prefix = `${this.getBaseId()}.`;\n // Allow users to provide either `plot.panel.layer`, or `panel.layer`. The latter usually leads to more reusable code.\n const layer_target = from_layer.startsWith(base_prefix) ? from_layer : `${base_prefix}${from_layer}`;\n\n // Ensure that a valid layer exists to watch\n let is_valid_layer = false;\n for (let p of Object.values(this.panels)) {\n is_valid_layer = Object.values(p.data_layers).some((d) => d.getBaseId() === layer_target);\n if (is_valid_layer) {\n break;\n }\n }\n if (!is_valid_layer) {\n throw new Error(`Could not subscribe to unknown data layer ${layer_target}`);\n }\n\n const listener = (eventData) => {\n if (eventData.data.layer !== layer_target) {\n // Same event name fires for many layers; only fire success cb for the one layer we want\n return;\n }\n try {\n success_callback(eventData.data.content, this);\n } catch (error) {\n error_callback(error);\n }\n };\n\n this.on('data_from_layer', listener);\n return listener;\n }\n\n // Second option: subscribe to an explicit list of fields and namespaces. This is useful if the same piece of\n // data has to be displayed in multiple ways, eg if we just want an annotation (which is normally visualized\n // in connection to some other visualization)\n if (!namespace) {\n throw new Error(\"subscribeToData must specify the desired data: either 'from_layer' or 'namespace' option\");\n }\n\n const [entities, dependencies] = this.lzd.config_to_sources(namespace, data_operations); // Does not pass reference to initiator- we don't want external subscribers with the power to mutate the whole plot.\n const listener = () => {\n try {\n // NOTE TO FUTURE SELF: since this event does something async and not tied to a returned promise, unit tests will behave strangely,\n // even though this method totally works. Don't spend another hour scratching your head; this is the line to blame.\n this.lzd.getData(this.state, entities, dependencies)\n .then((new_data) => success_callback(new_data, 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 /**\n * Plots can change how data is displayed by layout mutations. In rare cases, such as swapping from one source of LD to another,\n * these layout mutations won't be picked up instantly. This method notifies the plot to recalculate any cached properties,\n * like data fetching logic, that might depend on initial layout. It does not trigger a re-render by itself.\n * @public\n */\n mutateLayout() {\n Object.values(this.panels).forEach((panel) => {\n Object.values(panel.data_layers).forEach((layer) => layer.mutateLayout());\n });\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 const { _interaction } = this;\n if (panel_id) {\n return ((typeof _interaction.panel_id == 'undefined' || _interaction.panel_id === panel_id) && !this.loading_data);\n } else {\n return !(_interaction.dragging || _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 // 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 // Add panels\n this.layout.panels.forEach((panel_layout) => {\n this.addPanel(panel_layout);\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 panel of Object.values(this.panels)) {\n if (panel.layout.interaction.x_linked) {\n x_linked_margins.left = Math.max(x_linked_margins.left, panel.layout.margin.left);\n x_linked_margins.right = Math.max(x_linked_margins.right, panel.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 const panel_layout = panel.layout;\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 // 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 // If this is a responsive layout then set a namespaced/unique onresize event listener on the window\n const resize_listener = () => window.requestAnimationFrame(() => this.rescaleSVG());\n\n window.addEventListener('resize', resize_listener);\n this.trackExternalListener(window, 'resize', resize_listener);\n\n // Many libraries collapse/hide tab widgets using display:none, which doesn't trigger the resize listener\n // High threshold: Don't fire listeners on every 1px change, but allow this to work if the plot position is a bit cockeyed\n if (typeof IntersectionObserver !== 'undefined') { // don't do this in old browsers\n const options = { root: document.documentElement, threshold: 0.9 };\n const observer = new IntersectionObserver((entries, observer) => {\n if (entries.some((entry) => entry.intersectionRatio > 0)) {\n this.rescaleSVG();\n }\n }, options);\n // IntersectionObservers will be cleaned up when DOM node removed; no need to track them for manual cleanup\n observer.observe(this.container);\n }\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 // 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 const { _interaction } = this;\n if (_interaction.dragging) {\n const coords = d3.mouse(this.svg.node());\n if (d3.event) {\n d3.event.preventDefault();\n }\n _interaction.dragging.dragged_x = coords[0] - _interaction.dragging.start_x;\n _interaction.dragging.dragged_y = coords[1] - _interaction.dragging.start_y;\n this.panels[_interaction.panel_id].render();\n _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 const { _interaction } = this;\n if (!_interaction.dragging) {\n return this;\n }\n\n if (typeof this.panels[_interaction.panel_id] != 'object') {\n this._interaction = {};\n return this;\n }\n const panel = this.panels[_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 (_interaction.dragging.method) {\n case 'background':\n case 'x_tick':\n if (_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 (_interaction.dragging.dragged_y !== 0) {\n const y_axis_number = parseInt(_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 {*} value value\n */\nconst if_value = (parameters, value) => {\n if (typeof value == 'undefined' || parameters.field_value !== value) {\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 {*} value value\n * @returns {*}\n */\nconst numerical_bin = (parameters, value) => {\n const breaks = parameters.breaks || [];\n const values = parameters.values || [];\n if (typeof value == 'undefined' || value === null || isNaN(+value)) {\n return (parameters.null_value ? parameters.null_value : null);\n }\n const threshold = breaks.reduce(function (prev, curr) {\n if (+value < prev || (+value >= prev && +value < 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 * @function ordinal_cycle\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 *\n * @function stable_choice\n *\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, value) => {\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 value == 'undefined' || value === null || isNaN(+value)) {\n return nullval;\n }\n if (+value <= parameters.breaks[0]) {\n return values[0];\n } else if (+value >= 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] <= +value && breaks[idx] >= +value) {\n upper_idx = idx;\n }\n });\n if (upper_idx === null) {\n return nullval;\n }\n const normalized_input = (+value - 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\n/**\n * Calculate the effect direction based on beta, or the combination of beta and standard error.\n * Typically used with phewas plots, to show point shape based on the beta and stderr_beta fields.\n *\n * @function effect_direction\n * @param parameters\n * @param parameters.'+' The value to return if the effect direction is positive\n * @param parameters.'-' The value to return if the effect direction is positive\n * @param parameters.beta_field The name of the field containing beta\n * @param parameters.stderr_beta_field The name of the field containing stderr_beta\n * @param {Object} input This function should receive the entire datum object, rather than one single field\n * @returns {null}\n */\nfunction effect_direction(parameters, input) {\n if (input === undefined) {\n return null;\n }\n\n const { beta_field, stderr_beta_field, '+': plus_result = null, '-': neg_result = null } = parameters;\n\n if (!beta_field || !stderr_beta_field) {\n throw new Error(`effect_direction must specify how to find required 'beta' and 'stderr_beta' fields`);\n }\n\n const beta_val = input[beta_field];\n const se_val = input[stderr_beta_field];\n\n if (beta_val !== undefined) {\n if (se_val !== undefined) {\n if ((beta_val - 1.96 * se_val) > 0) {\n return plus_result;\n } else if ((beta_val + 1.96 * se_val) < 0) {\n return neg_result || null;\n }\n } else {\n if (beta_val > 0) {\n return plus_result;\n } else if (beta_val < 0) {\n return neg_result;\n }\n }\n }\n // Note: The original PheWeb implementation allowed odds ratio in place of beta/se. LZ core is a bit more rigid\n // about expected data formats for layouts.\n return null;\n}\n\nexport { categorical_bin, stable_choice, if_value, interpolate, numerical_bin, ordinal_cycle, effect_direction };\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, findFields, 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 * @typedef {object} DataOperation A synchronous function that modifies data returned from adapters, in order to clean up or reformat prior to plotting.\n * @property {module:LocusZoom_DataFunctions|'fetch'} type\n * @property {String[]} [from] For operations of type \"fetch\", this is required. By default, it will fill in any items provided in \"namespace\" (everything specified in namespace triggers an adapter/network request)\n * A namespace should be manually specified in this array when there are dependencies (one request depends on the content of what is returned from another namespace).\n * Eg, for ld to be fetched after association data, specify \"ld(assoc)\". Most LocusZoom examples fill in all items, in order to make the examples more clear.\n * @property {String} [name] The name of this operation. This only needs to be specified if a data layer performs several operations, and needs to refer to the result of a prior operation.\n * Eg, if the retrieved data is combined via several left joins in series: `name: \"assoc_plus_ld\"` -> feeds into `{name: \"final\", requires: [\"assoc_plus_ld\"]}`\n * @property {String[]} requires The names of each adapter required. This does not need to specify dependencies, just\n * the names of other namespaces (or data operations) whose results must be available before a join can be performed\n * @property {String[]} params Any user-defined parameters that should be passed to the particular join function\n * (see: {@link module:LocusZoom_DataFunctions} for details). For example, this could specify the left and right key fields for a join function, based on the expected field names used in this data layer: `params: ['assoc:position', 'ld:position2']`\n * Separate from this section, data functions will also receive a copy of \"plot.state\" automatically.\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 * A special \"ribbon\" option can be use to draw a series of explicit, numeric-only color stops (a row of colored squares, such as to indicate LD)\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\" or \"ribbon\".\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\" or \"ribbon\".\n * @property {'vertical'|'horizontal'} [orientation='vertical'] For shape \"ribbon\", specifies whether to draw the ribbon vertically or horizontally.\n * @property {Array} [tick_labels] For shape \"ribbon\", specifies the tick labels that correspond to each colorstop value. Tick labels appear at all box edges: this array should have 1 more item than the number of colorstops.\n * @property {String[]} [color_stops] For shape \"ribbon\", specifies the colors of each box in the row of colored squares. There should be 1 fewer item in color_stops than the number of tick labels.\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 */\nconst default_layout = {\n id: '',\n type: '',\n tag: 'custom_data_type',\n namespace: {},\n data_operations: [],\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.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, and persistent across re-renders (because it is\n * used to identify where to draw tooltips, eg, if the plot is dragged or zoomed). If no single field uniquely\n * identifies all items, a template expression can be used to create an ID from multiple fields instead. (it is\n * your job to assure that all of the expected fields are present in every element)\n * @param {object} layout.namespace A set of key value pairs representing how to map the local usage of data (\"assoc\")\n * to the globally unique name for something defined in LocusZoom.DataSources.\n * Namespaces allow a single layout to be reused to plot many tracks of the same type: \"given some form of association data, plot it\".\n * These pairs take the form of { local_name: global_name }. (and all data layer layouts provide a default) In order to reuse\n * a layout with a new provider of data- like plotting two association studies stacked together-\n * only the namespace section of the layout needs to be overridden.\n * Eg, `LocusZoom.Layouts.get('data_layers', 'association_pvalues', { namespace: { assoc: 'assoc_study_2' }})`\n * @param {module:LocusZoom_DataLayers~DataOperation[]} layout.data_operations A set of data operations that will be performed on the data returned from the data adapters specified in `namespace`. (see: {@link module:LocusZoom_DataFunctions})\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 // On first load, pre-parse the data specification once, so that it can be used for all other data retrieval\n this._data_contract = new Set(); // List of all fields requested by the layout\n this._entities = new Map();\n this._dependencies = [];\n this.mutateLayout(); // Parse data spec and any other changes that need to reflect the layout\n }\n\n /****** Public interface: methods for manipulating the layer from other parts of LZ */\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 const layer_order = this.parent._data_layer_ids_by_z_index;\n const current_index = this.layout.z_index;\n if (layer_order[current_index + 1]) {\n layer_order[current_index] = layer_order[current_index + 1];\n layer_order[current_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 const layer_order = this.parent._data_layer_ids_by_z_index;\n const current_index = this.layout.z_index;\n if (layer_order[current_index - 1]) {\n layer_order[current_index] = layer_order[current_index - 1];\n layer_order[current_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 /**\n * A list of operations that should be run when the layout is mutated\n * Typically, these are things done once when a layout is first specified, that would not automatically\n * update when the layout was changed.\n * @public\n */\n mutateLayout() {\n // Are we fetching data from external providers? If so, validate that those API calls would meet the expected contract.\n if (this.parent_plot) { // Don't run this method if instance isn't mounted to a plot, eg unit tests that don't require requester\n const { namespace, data_operations } = this.layout;\n this._data_contract = findFields(this.layout, Object.keys(namespace));\n const [entities, dependencies] = this.parent_plot.lzd.config_to_sources(namespace, data_operations, this);\n this._entities = entities;\n this._dependencies = dependencies;\n }\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 *\n * The ID should also be stable across re-renders, so that tooltips and highlights may be reapplied to that\n * element as we switch regions or drag left/right. If the element is not unique along a single field (eg PheWAS data),\n * a unique ID can be generated via a template expression like `{{phewas:pheno}}-{{phewas:trait_label}}`\n * @protected\n * @param {Object} element The data associated with a particular 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 // Two ways to get element ID: field can specify an exact field name, or, we can parse a template expression\n const id_field = this.layout.id_field;\n let value = element[id_field];\n if (typeof value === 'undefined' && /{{[^{}]*}}/.test(id_field)) {\n // No field value was found directly, but if it looks like a template expression, next, try parsing that\n // WARNING: In this mode, it doesn't validate that all requested fields from the template are present. Only use this if you trust the data being given to the plot!\n value = parseFields(id_field, element, {}); // Not allowed to use annotations b/c IDs should be stable, and annos may be transient\n }\n if (value === null || value === undefined) {\n // Neither exact field nor template options produced an ID\n throw new Error('Unable to generate element ID');\n }\n const element_id = value.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 * Abstract method. It should be overridden by data layers that implement separate status\n * nodes, such as genes or intervals.\n * Fetch an ID that may bind a data element to a separate visual node for displaying status\n * Examples of this might be highlighting a gene with a surrounding box to show select/highlight statuses, or\n * a group of unrelated intervals (all markings grouped within a category).\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\n // Does the data from the API satisfy the list of fields expected by this layout?\n // Not every record will have every possible field (example: left joins like assoc + ld). The check is \"did\n // we see this field at least once in any record at all\".\n if (this.data.length && this._data_contract.size) {\n const fields_unseen = new Set(this._data_contract);\n for (let record of this.data) {\n Object.keys(record).forEach((field) => fields_unseen.delete(field));\n if (!fields_unseen.size) {\n // Once every requested field has been seen in at least one record, no need to look at more records\n break;\n }\n }\n if (fields_unseen.size) {\n // Current implementation is a soft warning, so that certain \"incremental enhancement\" features\n // (like rsIDs in tooltips) can fail gracefully if the API does not provide the requested info.\n // Template syntax like `{{#if fieldname}}` means that throwing an Error is not always the right answer for missing data.\n console.debug(`Data layer '${this.getBaseId()}' did not receive all expected fields from retrieved data. Missing fields are: ${[...fields_unseen]}\n Common reasons for this error include API payloads with missing fields, or data layer layouts that use two kinds of data and need join logic in \"data_operations\" \n If this field is optional, you can safely ignore this message. Examples include {{#if value}} tags or conditional color rules.\n`);\n }\n }\n\n this.data.forEach((item, i) => {\n // Basic toHTML() method - return the stringified value in the id_field, if defined.\n\n // When this layer receives data, mark whether points match (via a synthetic boolean field)\n // Any field-based layout directives (color, size, shape) can then be used to control display\n if (field_to_match && broadcast_value !== null && broadcast_value !== undefined) {\n item.lz_is_match = match_function(field_resolver.resolve(item), broadcast_value);\n }\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 });\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 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 * 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 const tooltip_layout = this.layout.tooltip;\n if (typeof tooltip_layout != '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 tooltip_layout.show == 'string') {\n show_directive = { and: [ tooltip_layout.show ] };\n } else if (typeof tooltip_layout.show == 'object') {\n show_directive = tooltip_layout.show;\n }\n\n let hide_directive = {};\n if (typeof tooltip_layout.hide == 'string') {\n hide_directive = { and: [ tooltip_layout.hide ] };\n } else if (typeof tooltip_layout.hide == 'object') {\n hide_directive = tooltip_layout.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._entities, this._dependencies)\n .then((new_data) => {\n this.data = new_data;\n this.applyDataMethods();\n this._initialized = true;\n // Allow listeners (like subscribeToData) to see the information associated with a layer\n this.parent.emit(\n 'data_from_layer',\n { layer: this.getBaseId(), content: deepCopy(new_data) }, // TODO: revamp event signature post layer-eventing-mixin\n true,\n );\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.length && layout.namespace && Object.keys(layout.namespace).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: 15,\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 // FIXME: Make gene text font sizes scalable\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 tooltip: null,\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\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._label_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._label_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._label_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 closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: `{{assoc:variant|htmlescape}}
\n P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
\n Ref. Allele: {{assoc:ref_allele|htmlescape}}
\n {{#if lz_is_ld_refvar}}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 closable: true,\n show: { or: ['highlighted', 'selected'] },\n hide: { and: ['unhighlighted', 'unselected'] },\n html: '{{catalog:variant|htmlescape}}
'\n + 'Catalog entries: {{n_catalog_matches|htmlescape}}
'\n + 'Top Trait: {{catalog:trait|htmlescape}}
'\n + 'Top P Value: {{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 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 '{{access:start1|htmlescape}}-{{access:end1|htmlescape}}
' +\n 'Promoter
' +\n '{{access:start2|htmlescape}}-{{access:end2|htmlescape}}
' +\n '{{#if access:target}}Target: {{access:target|htmlescape}}
{{/if}}' +\n 'Score: {{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 id: 'recombrate',\n namespace: { 'recomb': 'recomb' },\n data_operations: [\n { type: 'fetch', from: ['recomb'] },\n ],\n type: 'line',\n tag: 'recombination',\n z_index: 1,\n style: {\n 'stroke': '#0000FF',\n 'stroke-width': '1.5px',\n },\n x_axis: {\n field: 'recomb:position',\n },\n y_axis: {\n axis: 2,\n field: '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 data_operations: [\n {\n type: 'fetch',\n from: ['assoc', 'ld(assoc)'],\n },\n {\n type: 'left_match',\n name: 'assoc_plus_ld',\n requires: ['assoc', 'ld'],\n params: ['assoc:position', 'ld:position2'], // FIXME: old LZ used position, because it was less sensitive to format. We'd like to match assoc:variant = ld:variant2, but not every assoc source provides variant data in the way we need. This would need to be fixed via special formatting adjustment later.\n },\n ],\n id: 'associationpvalues',\n type: 'scatter',\n tag: 'association',\n id_field: 'assoc:variant',\n coalesce: {\n active: true,\n },\n point_shape: [\n {\n scale_function: 'if',\n field: 'lz_is_ld_refvar',\n parameters: {\n field_value: true,\n then: 'diamond',\n },\n },\n {\n // Not every dataset will provide these params\n scale_function: 'effect_direction',\n parameters: {\n '+': 'triangle',\n '-': 'triangledown',\n // The scale function receives the entire datum object, so it needs to be told where to find individual fields\n beta_field: 'assoc:beta',\n stderr_beta_field: 'assoc:se',\n },\n },\n 'circle',\n ],\n point_size: {\n scale_function: 'if',\n field: 'lz_is_ld_refvar',\n parameters: {\n field_value: true,\n then: 80,\n else: 40,\n },\n },\n color: [\n {\n scale_function: 'if',\n field: 'lz_is_ld_refvar',\n parameters: {\n field_value: true,\n then: '#9632b8',\n },\n },\n {\n scale_function: 'numerical_bin',\n field: 'ld:correlation',\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 { label: 'LD (r²)', label_size: 14 }, // We're omitting the refvar symbol for now, but can show it with // shape: 'diamond', color: '#9632b8'\n {\n shape: 'ribbon',\n orientation: 'vertical',\n width: 10,\n height: 15,\n color_stops: ['rgb(70, 54, 153)', 'rgb(38, 188, 225)', 'rgb(110, 254, 104)', 'rgb(248, 195, 42)', 'rgb(219, 61, 17)'],\n tick_labels: [0, 0.2, 0.4, 0.6, 0.8, 1.0],\n },\n ],\n label: null,\n z_index: 2,\n x_axis: {\n field: 'assoc:position',\n },\n y_axis: {\n axis: 1,\n field: '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 id: 'coaccessibility',\n type: 'arcs',\n tag: 'coaccessibility',\n namespace: { 'access': 'access' },\n data_operations: [\n { type: 'fetch', from: ['access'] },\n ],\n match: { send: 'access:target', receive: 'access:target' },\n // Note: in the datasets this was tested with, these fields together defined a unique loop. Other datasets might work differently and need a different ID.\n id_field: '{{access:start1}}_{{access:end1}}_{{access:start2}}_{{access:end2}}_{{access:score}}_{{access:target}}',\n filters: [\n { field: '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: 'access:start1',\n field2: 'access:start2',\n },\n y_axis: {\n axis: 1,\n field: '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\n base.data_operations.push({\n type: 'assoc_to_gwas_catalog',\n name: 'assoc_catalog',\n requires: ['assoc_plus_ld', 'catalog'],\n params: ['assoc:position', 'catalog:pos', 'catalog:log_pvalue'],\n });\n\n base.tooltip.html += '{{#if catalog:rsid}}
See hits in GWAS catalog{{/if}}';\n base.namespace.catalog = 'catalog';\n return base;\n}();\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 id: 'phewaspvalues',\n type: 'category_scatter',\n tag: 'phewas',\n namespace: { 'phewas': 'phewas' },\n data_operations: [\n { type: 'fetch', from: ['phewas'] },\n ],\n point_shape: [\n {\n scale_function: 'effect_direction',\n parameters: {\n '+': 'triangle',\n '-': 'triangledown',\n // The scale function receives the entire datum object, so it needs to be told where to find individual fields\n beta_field: 'phewas:beta',\n stderr_beta_field: 'phewas:se',\n },\n },\n 'circle',\n ],\n point_size: 70,\n tooltip_positioning: 'vertical',\n id_field: '{{phewas:trait_group}}_{{phewas:trait_label}}',\n x_axis: {\n field: 'lz_auto_x', // Automatically added by the category_scatter layer\n category_field: 'phewas:trait_group',\n lower_buffer: 0.025,\n upper_buffer: 0.025,\n },\n y_axis: {\n axis: 1,\n field: 'phewas:log_pvalue',\n floor: 0,\n upper_buffer: 0.15,\n },\n color: [{\n field: '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: `Trait: {{phewas:trait_label|htmlescape}}
\nTrait Category: {{phewas:trait_group|htmlescape}}
\nP-value: {{phewas:log_pvalue|logtoscinotation|htmlescape}}\n{{#if phewas:beta|is_numeric}}
β: {{phewas:beta|scinotation|htmlescape}}
{{/if}}\n{{#if phewas:se|is_numeric}}SE (β): {{phewas:se|scinotation|htmlescape}}{{/if}}`,\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: '{{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: '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 data_operations: [\n {\n type: 'fetch',\n from: ['gene', 'constraint(gene)'],\n },\n {\n name: 'gene_constraint',\n type: 'genes_to_gnomad_constraint',\n requires: ['gene', 'constraint'],\n },\n ],\n id: 'genes',\n type: 'genes',\n tag: 'genes',\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 data_operations: [\n {\n type: 'fetch', from: ['assoc', 'catalog'],\n },\n {\n type: 'assoc_to_gwas_catalog',\n name: 'assoc_plus_ld',\n requires: ['assoc', 'catalog'],\n params: ['assoc:position', 'catalog:pos', 'catalog:log_pvalue'],\n },\n ],\n id: 'annotation_catalog',\n type: 'annotation_track',\n tag: 'gwascatalog',\n id_field: 'assoc:variant',\n x_axis: {\n field: 'assoc:position',\n },\n color: '#0000CC',\n filters: [\n // Specify which points to show on the track. Any selection must satisfy ALL filters\n { field: 'catalog:rsid', operator: '!=', value: null },\n { field: '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: 300,\n margin: { top: 35, right: 55, bottom: 40, left: 70 },\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: 38,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: '-log10 p-value',\n label_offset: 50,\n },\n y2: {\n label: 'Recombination Rate (cM/Mb)',\n label_offset: 46,\n },\n },\n legend: {\n orientation: 'vertical',\n origin: { x: 75, 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: 55, bottom: 40, left: 70 },\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: 38,\n tick_format: 'region',\n extent: 'state',\n },\n y1: {\n label: 'Score',\n label_offset: 40,\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 }, 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: '{{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: 'catalog:trait', operator: '!=', value: null },\n { field: 'catalog:log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP },\n { field: 'ld:correlation', operator: '>', value: 0.4 },\n ],\n style: {\n 'font-size': '12px',\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: 55, bottom: 20, left: 70 },\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: 55, bottom: 120, left: 70 },\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: 50,\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: 55, bottom: 10, left: 70 },\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: 38,\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, findFields} 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 applying namespaces.\n let base = super.get(type).get(name);\n\n // Most keys are merged directly. Namespaces are handled a little differently, as they act like global overrides.\n // (eg ask for plot layout, and modify multiple nested data layers where a particular namespace is referenced)\n const custom_namespaces = overrides.namespace;\n if (!base.namespace) {\n // Iff namespaces are a top level key, we'll allow them to be merged directly with the base layout\n // NOTE: The \"merge namespace\" behavior means that data layers can add new data easily, but this method\n // can't be used to remove namespaces when extending something. (you'll need to layout.namespaces = {} separately).\n delete overrides.namespace;\n }\n let result = merge(overrides, base);\n\n if (custom_namespaces) {\n result = applyNamespaces(result, custom_namespaces);\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\n // Special behavior for datalayers: all registry data layers will attempt to identify the fields requested\n // from external sources. This is purely a hint, because not every layout is generated through the registry.\n if (type === 'data_layer' && copy.namespace) {\n copy._auto_fields = [...findFields(copy, Object.keys(copy.namespace))].sort();\n }\n\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","/**\n * \"Data operation\" functions, with call signature ({plot_state, data_layer}, [recordsetA, recordsetB...], ...params) => combined_results\n *\n * After data is retrieved from adapters, Data Operations will be run on the resulting data. The most common operation\n * is a \"join\", such as combining association + LD together into a single set of records for plotting. Several join\n * functions (that operate by analogy to SQL) are provided built-in.\n *\n * Other use cases (even if no examples are in the built in code, see unit tests for what is possible):\n * 1. Grouping or filtering records; data operations can consider dynamic properties stored in plot.state.\n * (in the future, adapters may cache more aggressively; if you want to provide your own code for filtering returned data,\n * this is the recommended path to do so)\n * 2. Since the context argument also contains a reference to the data layer instance (and thus the parent panel and plot),\n * a data operation can modify the layout when new data is received, without having to create a custom data layer class. Eg,\n * for datasets where the categories are not known before first render, this could generate automatic x-axis ticks\n * (PheWAS), automatic panel legends or color schemes (BED tracks), etc.\n *\n * Usually, a data operation receives two recordsets (the left and right members of the join, like \"assoc\" and \"ld\").\n * In practice, any number of recordsets can be passed to one join function. There are performance penalties to making too many network\n * requests when rendering a web page, so in practice, joining too many distinct data entities in this fashion is\n * uncommon. (if possible, try to provide your data with fewer adapters/network requests!)\n *\n * In a few cases, the rules of how to combine datasets are very specific to those two types of data. Some,\n * particularly for advanced features, may carry assumptions about field names/ formatting.\n * (example: choosing the best EBI GWAS catalog entry for a variant may look for a field called `log_pvalue` instead of `pvalue`,\n * or it may match two datasets based on a specific way of identifying the variant)\n *\n * @module LocusZoom_DataFunctions\n */\nimport {joins} from '../data/undercomplicate';\n\nimport {RegistryBase} from './base';\n\n/**\n * A plugin registry that allows plots to use both pre-defined and user-provided \"data join\" functions.\n * @alias module:LocusZoom~DataFunctions\n * @type {module:registry/base~RegistryBase}\n */\nconst registry = new RegistryBase();\n\nfunction _wrap_join(handle) {\n // Validate number of arguments and convert call signature from (context, deps, ...params) to (left, right, ...params).\n\n // Many of our join functions are implemented with a different number of arguments than what a datafunction\n // actually receives. (eg, a join function is generic and doesn't care about \"context\" information like plot.state)\n // This wrapper is simple shared code to handle required validation and conversion stuff.\n return (context, deps, ...params) => {\n if (deps.length !== 2) {\n throw new Error('Join functions must receive exactly two recordsets');\n }\n return handle(...deps, ...params);\n };\n}\n\n// Highly specialized join: connect assoc data to GWAS catalog data. This isn't a simple left join, because it tries to\n// pick the most significant claim in the catalog for a variant, rather than joining every possible match.\n// This is specifically intended for sources that obey the ASSOC and CATALOG fields contracts.\nfunction assoc_to_gwas_catalog(assoc_data, catalog_data, assoc_key, catalog_key, catalog_logp_name) {\n if (!assoc_data.length) {\n return assoc_data;\n }\n\n // Prepare the genes catalog: group the data by variant, create simplified dataset with top hit for each\n const catalog_by_variant = joins.groupBy(catalog_data, catalog_key);\n\n const catalog_flat = []; // Store only the top significant claim for each catalog variant entry\n for (let claims of catalog_by_variant.values()) {\n // Find max item within this set of claims, push that to catalog_\n let best = 0;\n let best_variant;\n for (let item of claims) {\n const val = item[catalog_logp_name];\n if ( val >= best) {\n best_variant = item;\n best = val;\n }\n }\n best_variant.n_catalog_matches = claims.length;\n catalog_flat.push(best_variant);\n }\n return joins.left_match(assoc_data, catalog_flat, assoc_key, catalog_key);\n}\n\n// Highly specialized join: connect gnomAD constraint data to genes data. These are two very nonstandard payloads and need a special function to connect them.\nfunction genes_to_gnomad_constraint(genes_data, constraint_data) {\n genes_data.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 = constraint_data[alias] && constraint_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 genes_data;\n}\n\n\n/**\n * Perform a left outer join, based on records where the field values at `left_key` and `right_key` are identical\n *\n * By analogy with SQL, the result will include all values in the left recordset, annotated (where applicable) with all keys from matching records in the right recordset\n *\n * @function\n * @name left_match\n * @param {Object} plot_state\n * @param {Array[]} recordsets\n * @param {String} left_key\n * @params {String} right_key\n */\nregistry.add('left_match', _wrap_join(joins.left_match));\n\n/**\n * Perform an inner join, based on records where the field values at `left_key` and `right_key` are identical\n *\n * By analogy with SQL, the result will include all fields from both recordsets, but only for records where both the left and right keys are defined, and equal. If a record is not in one or both recordsets, it will be excluded from the result.\n *\n * @function\n * @name inner_match\n * @param {Object} plot_state\n * @param {Array[]} recordsets\n * @param {String} left_key\n * @params {String} right_key\n */\nregistry.add('inner_match', _wrap_join(joins.inner_match));\n\n/**\n * Perform a full outer join, based on records where the field values at `left_key` and `right_key` are identical\n *\n * By analogy with SQL, the result will include all records from both the left and right recordsets. If there are matching records, then the relevant items will include fields from both records combined into one.\n *\n * @function\n * @name full_outer_match\n * @param {Object} plot_state\n * @param {Array[]} recordsets\n * @param {String} left_key\n * @params {String} right_key\n */\nregistry.add('full_outer_match', _wrap_join(joins.full_outer_match));\n\n/**\n * A single purpose join function that combines GWAS data with best claim from the EBI GWAS catalog. Essentially this is a left join modified to make further decisions about which records to use.\n *\n * @function\n * @name assoc_to_gwas_catalog\n * @param {Object} plot_state\n * @param {Array[]} recordsets An array with two items: assoc records, then catalog records\n * @param {String} assoc_key The name of the key field in association data, eg variant ID\n * @param {String} catalog_key The name of the key field in gwas catalog data, eg variant ID\n * @param {String} catalog_log_p_name The name of the \"log_pvalue\" field in gwas catalog data, used to choose the most significant claim for a given variant\n */\nregistry.add('assoc_to_gwas_catalog', _wrap_join(assoc_to_gwas_catalog));\n\n/**\n * A single purpose join function that combines gene data (UM Portaldev API format) with gene constraint data (gnomAD api format).\n *\n * This acts as a left join that has to perform custom operations to parse two very unusual recordset formats.\n *\n * @function\n * @name genes_to_gnomad_constraint\n * @param {Object} plot_state\n * @param {Array[]} recordsets An array with two items: UM Portaldev API gene records, then gnomAD gene constraint data\n */\nregistry.add('genes_to_gnomad_constraint', _wrap_join(genes_to_gnomad_constraint));\n\nexport default registry;\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 DATA_OPS as DataFunctions,\n LAYOUTS as Layouts,\n MATCHERS as MatchFunctions,\n SCALABLE as ScaleFunctions,\n TRANSFORMS as TransformationFunctions,\n WIDGETS as Widgets,\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 DataFunctions,\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/dist/locuszoom.css b/dist/locuszoom.css index 2145bb75..abb56d7e 100644 --- a/dist/locuszoom.css +++ b/dist/locuszoom.css @@ -1 +1 @@ -svg.lz-locuszoom{background-color:#fff;border:none;cursor:crosshair;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:10px}svg.lz-locuszoom rect.lz-clickarea{fill:#000;fill-opacity:0;cursor:pointer}svg.lz-locuszoom .lz-mouse_guide rect{fill:#d2d2d2;fill-opacity:.85}svg.lz-locuszoom .lz-mouse_guide rect.lz-mouse_guide-vertical{width:1px;height:100%}svg.lz-locuszoom .lz-mouse_guide rect.lz-mouse_guide-horizontal{width:100%;height:1px}svg.lz-locuszoom .lz-panel-title{font-size:18px;font-weight:600}svg.lz-locuszoom .lz-panel-background{fill:#fff;fill-opacity:.01}svg.lz-locuszoom .lz-axis path,svg.lz-locuszoom .lz-axis line{fill:none;stroke:rgb(24, 24, 24);stroke-opacity:1;shape-rendering:crispEdges}svg.lz-locuszoom .lz-axis .lz-label{font-size:12px;font-weight:600}svg.lz-locuszoom .tick text:focus{outline-style:dotted;outline-width:1px;outline-color:#424242;outline-offset:2px}svg.lz-locuszoom .lz-legend-background{fill:#f5f5f5;fill-opacity:1;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom path.lz-data_layer-arcs-selected{stroke:rgb(24, 24, 24) !important;stroke-opacity:1 !important;stroke-width:2px !important}svg.lz-locuszoom path.lz-data_layer-arcs-highlighted{stroke:rgb(24, 24, 24) !important;stroke-opacity:0.4 !important;stroke-width:2px !important}svg.lz-locuszoom path.lz-data_layer-scatter,svg.lz-locuszoom path.lz-data_layer-category_scatter{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:1px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-scatter-highlighted,svg.lz-locuszoom path.lz-data_layer-category_scatter-highlighted{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-scatter-selected,svg.lz-locuszoom path.lz-data_layer-category_scatter-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-scatter-faded,svg.lz-locuszoom path.lz-data_layer-category_scatter-faded{fill-opacity:.1;stroke-opacity:.1}svg.lz-locuszoom path.lz-data_layer-scatter-hidden,svg.lz-locuszoom path.lz-data_layer-category_scatter-hidden{display:none}svg.lz-locuszoom text.lz-data_layer-scatter-label,svg.lz-locuszoom text.lz-data_layer-category_scatter-label{fill:rgb(24, 24, 24);fill-opacity:1;alignment-baseline:middle}svg.lz-locuszoom line.lz-data_layer-scatter-label,svg.lz-locuszoom line.lz-data_layer-category_scatter-label{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-annotation_track{cursor:pointer}svg.lz-locuszoom path.lz-data_layer-annotation_track-highlighted,svg.lz-locuszoom path.lz-data_layer-annotation_track-selected{stroke-opacity:1}svg.lz-locuszoom path.lz-data_layer-line{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-line-faded{stroke-opacity:.2}svg.lz-locuszoom path.lz-data_layer-line-hidden{display:none}svg.lz-locuszoom path.lz-data_layer-line-hitarea{fill:none;stroke:none;cursor:pointer}svg.lz-locuszoom g.lz-data_layer-genes{cursor:pointer}svg.lz-locuszoom g.lz-data_layer-genes-faded{opacity:.1}svg.lz-locuszoom g.lz-data_layer-genes-hidden{display:none}svg.lz-locuszoom text.lz-data_layer-genes.lz-label{font-style:italic}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode{fill:#363696;fill-opacity:0;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode-highlighted{fill:#363696;fill-opacity:.1;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode-selected{fill:#363696;fill-opacity:.15;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-boundary{stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-exon{stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom g.lz-data_layer-intervals-faded{opacity:.1}svg.lz-locuszoom g.lz-data_layer-intervals-hidden{display:none}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode{fill:#363696;fill-opacity:0;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode-highlighted{fill:#363696;fill-opacity:.2;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode-selected{fill:#363696;fill-opacity:.35;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom g.lz-data_layer-intervals{stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals-highlighted,svg.lz-locuszoom rect.lz-data_layer-intervals-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom path.lz-data_layer-forest{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:1px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-forest-highlighted{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-forest-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-forest-faded{fill-opacity:.1;stroke-opacity:.1}svg.lz-locuszoom path.lz-data_layer-forest-hidden{display:none}svg.lz-locuszoom rect.lz-data_layer-forest.lz-data_layer-ci{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}div.lz-data_layer-tooltip{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;position:absolute;padding:6px;background:#ebebeb;border:1px solid rgb(24, 24, 24);border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4)}div.lz-data_layer-tooltip h1,div.lz-data_layer-tooltip h2,div.lz-data_layer-tooltip h3,div.lz-data_layer-tooltip h4,div.lz-data_layer-tooltip h5,div.lz-data_layer-tooltip h6{margin-top:.1em;margin-bottom:.3em}div.lz-data_layer-tooltip h1{font-size:200%}div.lz-data_layer-tooltip h2{font-size:175%}div.lz-data_layer-tooltip h3{font-size:150%}div.lz-data_layer-tooltip h4{font-size:135%}div.lz-data_layer-tooltip h5{font-size:125%}div.lz-data_layer-tooltip h6{font-size:110%}div.lz-data_layer-tooltip table{display:table;border-collapse:separate;border-spacing:1px;margin-bottom:.2em}div.lz-data_layer-tooltip th:first-child,div.lz-data_layer-tooltip td:first-child{padding-left:0px}div.lz-data_layer-tooltip th,div.lz-data_layer-tooltip td{padding:6px;text-align:left;border-bottom:1px solid #e1e1e1}div.lz-data_layer-tooltip button{text-decoration:none;height:auto;line-height:inherit;padding:.2em .5em .2em .5em;background-color:#d8d8d8;color:rgb(24, 24, 24);border:1px solid rgb(24, 24, 24);border-radius:4px;pointer-events:auto;outline:none}div.lz-data_layer-tooltip button:hover{cursor:pointer;background-color:rgb(24, 24, 24);color:rgb(232, 232, 232)}div.lz-data_layer-tooltip .lz-tooltip-close-button{color:rgba(24, 24, 24, 0.4);border:1px solid rgba(24, 24, 24, 0.4);background-color:rgba(235,235,235,.4);float:right;position:relative;top:-6px;right:-6px;margin:0px 0px 6px 6px}div.lz-data_layer-tooltip-arrow_up{width:0;height:0;pointer-events:none;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_down{width:0;height:0;pointer-events:none;border-left:7px solid transparent;border-right:7px solid transparent;border-top:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_right{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-bottom:7px solid transparent;border-left:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_left{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-bottom:7px solid transparent;border-right:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_top_left{width:0;height:0;pointer-events:none;border-top:7px solid rgb(24, 24, 24);border-left:7px solid rgb(24, 24, 24);border-bottom:7px solid transparent;border-right:7px solid transparent}div.lz-data_layer-tooltip-arrow_top_right{width:0;height:0;pointer-events:none;border-top:7px solid rgb(24, 24, 24);border-left:7px solid transparent;border-bottom:7px solid transparent;border-right:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_bottom_left{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-left:7px solid rgb(24, 24, 24);border-bottom:7px solid rgb(24, 24, 24);border-right:7px solid transparent}div.lz-data_layer-tooltip-arrow_bottom_right{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-left:7px solid transparent;border-bottom:7px solid rgb(24, 24, 24);border-right:7px solid rgb(24, 24, 24)}.lz-container{display:inline-block;overflow:hidden}.lz-container-responsive{width:100%;display:inline-block;overflow:hidden}.lz-curtain{position:absolute;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:16px;font-weight:600;background:rgba(216,216,216,.8)}.lz-curtain .lz-curtain-content{position:absolute;display:block;width:100%;top:50%;transform:translateY(-50%);margin:0 auto;padding:0px 20px;overflow-y:auto}.lz-curtain .lz-curtain-dismiss{position:absolute;top:0px;right:0px;padding:2px 4px;font-size:10px;font-weight:300;background-color:#d8d8d8;color:#333;border:1px solid #333;border-radius:0px 0px 0px 4px;pointer-events:auto;cursor:pointer}.lz-curtain .lz-curtain-dismiss:hover{background-color:#333;color:#d8d8d8}.lz-loader{position:absolute;font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;padding:6px;background:#f0ebe4;border:1px solid rgb(24, 24, 24);border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4)}.lz-loader .lz-loader-content{position:relative;display:block;width:100%}.lz-loader .lz-loader-progress-container{position:relative;display:block;width:100%;height:2px;padding-top:6px}.lz-loader .lz-loader-progress{position:absolute;left:0%;width:0%;height:2px;background-color:rgba(24, 24, 24, 0.4)}.lz-loader .lz-loader-progress-animated{animation-name:lz-loader-animate;animation-duration:1.5s;animation-iteration-count:infinite;animation-timing-function:ease-in-out}@keyframes lz-loader-animate{0%{width:0%;left:0%}50%{width:100%;left:0%}100%{width:0%;left:100%}}.lz-plot-toolbar{padding-left:0px;padding-right:0px;padding-top:4px;padding-bottom:3px}.lz-plot-toolbar .lz-toolbar-button{text-decoration:none;padding:3px 7px 3px 7px;height:auto;line-height:inherit;border-radius:4px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center}.lz-plot-toolbar .lz-toolbar-button-group-start{border-radius:4px 0px 0px 4px !important}.lz-plot-toolbar .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}.lz-plot-toolbar .lz-toolbar-button-group-end{border-radius:0px 4px 4px 0px !important;border-left-width:0px !important}.lz-plot-toolbar>.lz-toolbar-left{float:left;margin-right:1.5em}.lz-plot-toolbar>.lz-toolbar-right{float:right;margin-left:1.5em}.lz-plot-toolbar>.lz-toolbar-group-start{margin-right:0em !important}.lz-plot-toolbar>.lz-toolbar-group-middle{margin-left:0em !important;margin-right:0em !important}.lz-plot-toolbar>.lz-toolbar-group-end{margin-left:0em !important}.lz-panel-toolbar{padding-left:2px;padding-right:2px;padding-top:2px;padding-bottom:0px}.lz-panel-toolbar .lz-toolbar-button{text-decoration:none;padding:2px 6px 2px 6px;height:auto;line-height:inherit;border-radius:3px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center}.lz-panel-toolbar .lz-toolbar-button-group-start{border-radius:3px 0px 0px 3px !important}.lz-panel-toolbar .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}.lz-panel-toolbar .lz-toolbar-button-group-end{border-radius:0px 3px 3px 0px !important;border-left-width:0px !important}.lz-panel-toolbar input{line-height:normal}.lz-panel-toolbar>.lz-toolbar-left{float:left;margin-right:0px}.lz-panel-toolbar>.lz-toolbar-right{float:right;margin-left:0px}.lz-toolbar{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:80%}.lz-toolbar .lz-toolbar-title{margin-bottom:.3em}.lz-toolbar .lz-toolbar-title h3{font-size:150%;font-weight:bold;margin:0em}.lz-toolbar .lz-toolbar-title small{font-size:80%;font-weight:normal}div.lz-toolbar-menu{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;position:absolute;padding:6px;border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4);box-sizing:border-box;overflow:hidden}div.lz-toolbar-menu .lz-toolbar-menu-content{display:block;width:100%;height:100%;overflow-y:auto}div.lz-toolbar-menu .lz-toolbar-menu-content h1,div.lz-toolbar-menu .lz-toolbar-menu-content h2,div.lz-toolbar-menu .lz-toolbar-menu-content h3,div.lz-toolbar-menu .lz-toolbar-menu-content h4,div.lz-toolbar-menu .lz-toolbar-menu-content h5,div.lz-toolbar-menu .lz-toolbar-menu-content h6{margin-top:.1em;margin-bottom:.3em}div.lz-toolbar-menu .lz-toolbar-menu-content h1{font-size:200%}div.lz-toolbar-menu .lz-toolbar-menu-content h2{font-size:175%}div.lz-toolbar-menu .lz-toolbar-menu-content h3{font-size:150%}div.lz-toolbar-menu .lz-toolbar-menu-content h4{font-size:135%}div.lz-toolbar-menu .lz-toolbar-menu-content h5{font-size:125%}div.lz-toolbar-menu .lz-toolbar-menu-content h6{font-size:110%}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button{text-decoration:none;padding:2px 6px 2px 6px;height:auto;line-height:inherit;border-radius:3px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center;font-weight:300;letter-spacing:0;text-transform:none;margin:0}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-start{border-radius:3px 0px 0px 3px !important}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-end{border-radius:0px 3px 3px 0px !important;border-left-width:0px !important}div.lz-toolbar-menu table{display:table;border-collapse:collapse;border-spacing:0px;margin-bottom:.4em;width:100%}div.lz-toolbar-menu th:first-child,div.lz-toolbar-menu td:first-child{vertical-align:top}div.lz-toolbar-menu tr:nth-child(odd){background-color:rgba(0,0,0,.08)}div.lz-toolbar-menu th,div.lz-toolbar-menu td{padding:4px;text-align:left;vertical-align:middle;border:none;line-height:1}.lz-toolbar-button-gray{background-color:rgba(216,216,216,.6);border:1px solid rgba(51,51,51,.6);color:rgba(51,51,51,.6)}.lz-toolbar-button-gray:not(.lz-toolbar-button-gray-disabled):not(.lz-toolbar-button-gray-highlighted):hover{background-color:#d8d8d8;border:1px solid #333;color:#333}.lz-toolbar-button-gray-highlighted{border:1px solid #333;background-color:#333;color:#d8d8d8 !important}.lz-toolbar-button-gray-disabled{background-color:rgba(216,216,216,.6);border:1px solid rgba(153,153,153,.6);color:rgba(153,153,153,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-red{background-color:rgba(230,195,195,.6);border:1px solid rgba(89,49,49,.6);color:rgba(89,49,49,.6)}.lz-toolbar-button-red:not(.lz-toolbar-button-red-disabled):not(.lz-toolbar-button-red-highlighted):hover{background-color:#e6c3c3;border:1px solid #593131;color:#593131}.lz-toolbar-button-red-highlighted{border:1px solid #593131;background-color:#593131;color:#e6c3c3 !important}.lz-toolbar-button-red-disabled{background-color:rgba(230,195,195,.6);border:1px solid rgba(179,134,134,.6);color:rgba(179,134,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-orange{background-color:rgba(230,213,195,.6);border:1px solid rgba(89,69,49,.6);color:rgba(89,69,49,.6)}.lz-toolbar-button-orange:not(.lz-toolbar-button-orange-disabled):not(.lz-toolbar-button-orange-highlighted):hover{background-color:#e6d5c3;border:1px solid #594531;color:#594531}.lz-toolbar-button-orange-highlighted{border:1px solid #594531;background-color:#594531;color:#e6d5c3 !important}.lz-toolbar-button-orange-disabled{background-color:rgba(230,213,195,.6);border:1px solid rgba(179,156,134,.6);color:rgba(179,156,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-yellow{background-color:rgba(230,230,195,.6);border:1px solid rgba(89,89,49,.6);color:rgba(89,89,49,.6)}.lz-toolbar-button-yellow:not(.lz-toolbar-button-yellow-disabled):not(.lz-toolbar-button-yellow-highlighted):hover{background-color:#e6e6c3;border:1px solid #595931;color:#595931}.lz-toolbar-button-yellow-highlighted{border:1px solid #595931;background-color:#595931;color:#e6e6c3 !important}.lz-toolbar-button-yellow-disabled{background-color:rgba(230,230,195,.6);border:1px solid rgba(179,179,134,.6);color:rgba(179,179,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-green{background-color:rgba(204,230,195,.6);border:1px solid rgba(59,89,49,.6);color:rgba(59,89,49,.6)}.lz-toolbar-button-green:not(.lz-toolbar-button-green-disabled):not(.lz-toolbar-button-green-highlighted):hover{background-color:#cce6c3;border:1px solid #3b5931;color:#3b5931}.lz-toolbar-button-green-highlighted{border:1px solid #3b5931;background-color:#3b5931;color:#cce6c3 !important}.lz-toolbar-button-green-disabled{background-color:rgba(204,230,195,.6);border:1px solid rgba(145,179,134,.6);color:rgba(145,179,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-blue{background-color:rgba(195,210,230,.6);border:1px solid rgba(49,66,89,.6);color:rgba(49,66,89,.6)}.lz-toolbar-button-blue:not(.lz-toolbar-button-blue-disabled):not(.lz-toolbar-button-blue-highlighted):hover{background-color:#c3d2e6;border:1px solid #314259;color:#314259}.lz-toolbar-button-blue-highlighted{border:1px solid #314259;background-color:#314259;color:#c3d2e6 !important}.lz-toolbar-button-blue-disabled{background-color:rgba(195,210,230,.6);border:1px solid rgba(134,153,179,.6);color:rgba(134,153,179,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-purple{background-color:rgba(221,195,230,.6);border:1px solid rgba(80,49,89,.6);color:rgba(80,49,89,.6)}.lz-toolbar-button-purple:not(.lz-toolbar-button-purple-disabled):not(.lz-toolbar-button-purple-highlighted):hover{background-color:#ddc3e6;border:1px solid #503159;color:#503159}.lz-toolbar-button-purple-highlighted{border:1px solid #503159;background-color:#503159;color:#ddc3e6 !important}.lz-toolbar-button-purple-disabled{background-color:rgba(221,195,230,.6);border:1px solid rgba(167,134,179,.6);color:rgba(167,134,179,.6);pointer-events:none;cursor:wait}.lz-toolbar-menu-gray{background-color:#e8e8e8;border:1px solid #333}.lz-toolbar-menu-red{background:#f0e4e4;border:1px solid #593131}.lz-toolbar-menu-orange{background:#f0eae4;border:1px solid #594531}.lz-toolbar-menu-yellow{background:#f0f0e4;border:1px solid #595931}.lz-toolbar-menu-green{background:#e7f0e4;border:1px solid #3b5931}.lz-toolbar-menu-blue{background:#e4e9f0;border:1px solid #314259}.lz-toolbar-menu-purple{background:#ede4f0;border:1px solid #503159}div.lz-panel-boundary{position:absolute;height:3px;cursor:row-resize;display:block;padding-top:10px;padding-bottom:10px}div.lz-panel-boundary span{display:block;border-radius:1px;background:rgba(216,216,216,0);border:1px solid rgba(216,216,216,0);height:3px}div.lz-panel-boundary:hover span{background:#d8d8d8;border:1px solid rgb(24, 24, 24)}div.lz-panel-boundary:active span{background:#a6a6a6;border:1px solid rgb(24, 24, 24)}div.lz-panel-corner-boundary{position:absolute;height:16px;width:16px;cursor:nwse-resize;display:block;padding:10px}div.lz-panel-corner-boundary span.lz-panel-corner-boundary-outer{display:block;width:0px;height:0px;border-bottom:16px solid transparent;border-left:16px solid transparent;position:absolute;top:10px;left:10px}div.lz-panel-corner-boundary span.lz-panel-corner-boundary-inner{display:block;width:0px;height:0px;border-bottom:13px solid transparent;border-left:13px solid transparent;position:absolute;top:12px;left:12px}div.lz-panel-corner-boundary:hover span.lz-panel-corner-boundary-outer{border-bottom:16px solid rgb(24, 24, 24)}div.lz-panel-corner-boundary:hover span.lz-panel-corner-boundary-inner{border-bottom:13px solid #d8d8d8}div.lz-panel-corner-boundary:active span.lz-panel-corner-boundary-inner{border-bottom:13px solid #a6a6a6}/*# sourceMappingURL=locuszoom.css.map */ +svg.lz-locuszoom{background-color:#fff;border:none;cursor:crosshair;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px}svg.lz-locuszoom rect.lz-clickarea{fill:#000;fill-opacity:0;cursor:pointer}svg.lz-locuszoom .lz-mouse_guide rect{fill:#d2d2d2;fill-opacity:.85}svg.lz-locuszoom .lz-mouse_guide rect.lz-mouse_guide-vertical{width:1px;height:100%}svg.lz-locuszoom .lz-mouse_guide rect.lz-mouse_guide-horizontal{width:100%;height:1px}svg.lz-locuszoom .lz-panel-title{font-size:150%;font-weight:600}svg.lz-locuszoom .lz-panel-background{fill:#fff;fill-opacity:.01}svg.lz-locuszoom .lz-axis path,svg.lz-locuszoom .lz-axis line{fill:none;stroke:rgb(24, 24, 24);stroke-opacity:1;shape-rendering:crispEdges}svg.lz-locuszoom .lz-axis{font-size:100%}svg.lz-locuszoom .lz-axis .lz-label{font-size:120%;font-weight:600}svg.lz-locuszoom .tick{font-size:100%}svg.lz-locuszoom .tick text:focus{outline-style:dotted;outline-width:1px;outline-color:#424242;outline-offset:2px}svg.lz-locuszoom .lz-legend-background{fill:#f5f5f5;fill-opacity:1;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom path.lz-data_layer-arcs-selected{stroke:rgb(24, 24, 24) !important;stroke-opacity:1 !important;stroke-width:2px !important}svg.lz-locuszoom path.lz-data_layer-arcs-highlighted{stroke:rgb(24, 24, 24) !important;stroke-opacity:0.4 !important;stroke-width:2px !important}svg.lz-locuszoom path.lz-data_layer-scatter,svg.lz-locuszoom path.lz-data_layer-category_scatter{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:.8px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-scatter-highlighted,svg.lz-locuszoom path.lz-data_layer-category_scatter-highlighted{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-scatter-selected,svg.lz-locuszoom path.lz-data_layer-category_scatter-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-scatter-faded,svg.lz-locuszoom path.lz-data_layer-category_scatter-faded{fill-opacity:.1;stroke-opacity:.1}svg.lz-locuszoom path.lz-data_layer-scatter-hidden,svg.lz-locuszoom path.lz-data_layer-category_scatter-hidden{display:none}svg.lz-locuszoom text.lz-data_layer-scatter-label,svg.lz-locuszoom text.lz-data_layer-category_scatter-label{fill:rgb(24, 24, 24);fill-opacity:1;alignment-baseline:middle}svg.lz-locuszoom line.lz-data_layer-scatter-label,svg.lz-locuszoom line.lz-data_layer-category_scatter-label{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-annotation_track{cursor:pointer}svg.lz-locuszoom path.lz-data_layer-annotation_track-highlighted,svg.lz-locuszoom path.lz-data_layer-annotation_track-selected{stroke-opacity:1}svg.lz-locuszoom path.lz-data_layer-line{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-line-faded{stroke-opacity:.2}svg.lz-locuszoom path.lz-data_layer-line-hidden{display:none}svg.lz-locuszoom path.lz-data_layer-line-hitarea{fill:none;stroke:none;cursor:pointer}svg.lz-locuszoom g.lz-data_layer-genes{cursor:pointer}svg.lz-locuszoom g.lz-data_layer-genes-faded{opacity:.1}svg.lz-locuszoom g.lz-data_layer-genes-hidden{display:none}svg.lz-locuszoom text.lz-data_layer-genes.lz-label{font-style:italic}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode{fill:#363696;fill-opacity:0;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode-highlighted{fill:#363696;fill-opacity:.1;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-data_layer-genes-statusnode-selected{fill:#363696;fill-opacity:.15;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-boundary{stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom rect.lz-data_layer-genes.lz-exon{stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom g.lz-data_layer-intervals-faded{opacity:.1}svg.lz-locuszoom g.lz-data_layer-intervals-hidden{display:none}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode{fill:#363696;fill-opacity:0;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode-highlighted{fill:#363696;fill-opacity:.2;stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals.lz-data_layer-intervals-statusnode-selected{fill:#363696;fill-opacity:.35;stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom g.lz-data_layer-intervals{stroke-width:0px}svg.lz-locuszoom rect.lz-data_layer-intervals-highlighted,svg.lz-locuszoom rect.lz-data_layer-intervals-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}svg.lz-locuszoom path.lz-data_layer-forest{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:1px;cursor:pointer}svg.lz-locuszoom path.lz-data_layer-forest-highlighted{stroke:rgb(24, 24, 24);stroke-opacity:0.4;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-forest-selected{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:4px}svg.lz-locuszoom path.lz-data_layer-forest-faded{fill-opacity:.1;stroke-opacity:.1}svg.lz-locuszoom path.lz-data_layer-forest-hidden{display:none}svg.lz-locuszoom rect.lz-data_layer-forest.lz-data_layer-ci{stroke:rgb(24, 24, 24);stroke-opacity:1;stroke-width:1px}div.lz-data_layer-tooltip{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;position:absolute;padding:6px;background:#ebebeb;border:1px solid rgb(24, 24, 24);border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4)}div.lz-data_layer-tooltip h1,div.lz-data_layer-tooltip h2,div.lz-data_layer-tooltip h3,div.lz-data_layer-tooltip h4,div.lz-data_layer-tooltip h5,div.lz-data_layer-tooltip h6{margin-top:.1em;margin-bottom:.3em}div.lz-data_layer-tooltip h1{font-size:200%}div.lz-data_layer-tooltip h2{font-size:175%}div.lz-data_layer-tooltip h3{font-size:150%}div.lz-data_layer-tooltip h4{font-size:135%}div.lz-data_layer-tooltip h5{font-size:125%}div.lz-data_layer-tooltip h6{font-size:110%}div.lz-data_layer-tooltip table{display:table;border-collapse:separate;border-spacing:1px;margin-bottom:.2em}div.lz-data_layer-tooltip th:first-child,div.lz-data_layer-tooltip td:first-child{padding-left:0px}div.lz-data_layer-tooltip th,div.lz-data_layer-tooltip td{padding:6px;text-align:left;border-bottom:1px solid #e1e1e1}div.lz-data_layer-tooltip button{text-decoration:none;height:auto;line-height:inherit;padding:.2em .5em .2em .5em;background-color:#d8d8d8;color:rgb(24, 24, 24);border:1px solid rgb(24, 24, 24);border-radius:4px;pointer-events:auto;outline:none}div.lz-data_layer-tooltip button:hover{cursor:pointer;background-color:rgb(24, 24, 24);color:rgb(232, 232, 232)}div.lz-data_layer-tooltip .lz-tooltip-close-button{color:rgba(24, 24, 24, 0.4);border:1px solid rgba(24, 24, 24, 0.4);background-color:rgba(235,235,235,.4);float:right;position:relative;top:-6px;right:-6px;margin:0px 0px 6px 6px}div.lz-data_layer-tooltip-arrow_up{width:0;height:0;pointer-events:none;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_down{width:0;height:0;pointer-events:none;border-left:7px solid transparent;border-right:7px solid transparent;border-top:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_right{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-bottom:7px solid transparent;border-left:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_left{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-bottom:7px solid transparent;border-right:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_top_left{width:0;height:0;pointer-events:none;border-top:7px solid rgb(24, 24, 24);border-left:7px solid rgb(24, 24, 24);border-bottom:7px solid transparent;border-right:7px solid transparent}div.lz-data_layer-tooltip-arrow_top_right{width:0;height:0;pointer-events:none;border-top:7px solid rgb(24, 24, 24);border-left:7px solid transparent;border-bottom:7px solid transparent;border-right:7px solid rgb(24, 24, 24)}div.lz-data_layer-tooltip-arrow_bottom_left{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-left:7px solid rgb(24, 24, 24);border-bottom:7px solid rgb(24, 24, 24);border-right:7px solid transparent}div.lz-data_layer-tooltip-arrow_bottom_right{width:0;height:0;pointer-events:none;border-top:7px solid transparent;border-left:7px solid transparent;border-bottom:7px solid rgb(24, 24, 24);border-right:7px solid rgb(24, 24, 24)}.lz-container{display:inline-block;overflow:hidden}.lz-container-responsive{width:100%;display:inline-block;overflow:hidden}.lz-curtain{position:absolute;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:16px;font-weight:600;background:rgba(216,216,216,.8)}.lz-curtain .lz-curtain-content{position:absolute;display:block;width:100%;top:50%;transform:translateY(-50%);margin:0 auto;padding:0px 20px;overflow-y:auto}.lz-curtain .lz-curtain-dismiss{position:absolute;top:0px;right:0px;padding:2px 4px;font-size:11px;font-weight:300;background-color:#d8d8d8;color:#333;border:1px solid #333;border-radius:0px 0px 0px 4px;pointer-events:auto;cursor:pointer}.lz-curtain .lz-curtain-dismiss:hover{background-color:#333;color:#d8d8d8}.lz-loader{position:absolute;font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;padding:6px;background:#f0ebe4;border:1px solid rgb(24, 24, 24);border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4)}.lz-loader .lz-loader-content{position:relative;display:block;width:100%}.lz-loader .lz-loader-progress-container{position:relative;display:block;width:100%;height:2px;padding-top:6px}.lz-loader .lz-loader-progress{position:absolute;left:0%;width:0%;height:2px;background-color:rgba(24, 24, 24, 0.4)}.lz-loader .lz-loader-progress-animated{animation-name:lz-loader-animate;animation-duration:1.5s;animation-iteration-count:infinite;animation-timing-function:ease-in-out}@keyframes lz-loader-animate{0%{width:0%;left:0%}50%{width:100%;left:0%}100%{width:0%;left:100%}}.lz-plot-toolbar{padding-left:0px;padding-right:0px;padding-top:4px;padding-bottom:3px}.lz-plot-toolbar .lz-toolbar-button{text-decoration:none;padding:3px 7px 3px 7px;height:auto;line-height:inherit;border-radius:4px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center}.lz-plot-toolbar .lz-toolbar-button-group-start{border-radius:4px 0px 0px 4px !important}.lz-plot-toolbar .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}.lz-plot-toolbar .lz-toolbar-button-group-end{border-radius:0px 4px 4px 0px !important;border-left-width:0px !important}.lz-plot-toolbar>.lz-toolbar-left{float:left;margin-right:1.5em}.lz-plot-toolbar>.lz-toolbar-right{float:right;margin-left:1.5em}.lz-plot-toolbar>.lz-toolbar-group-start{margin-right:0em !important}.lz-plot-toolbar>.lz-toolbar-group-middle{margin-left:0em !important;margin-right:0em !important}.lz-plot-toolbar>.lz-toolbar-group-end{margin-left:0em !important}.lz-panel-toolbar{padding-left:2px;padding-right:2px;padding-top:2px;padding-bottom:0px}.lz-panel-toolbar .lz-toolbar-button{text-decoration:none;padding:2px 6px 2px 6px;height:auto;line-height:inherit;border-radius:3px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center}.lz-panel-toolbar .lz-toolbar-button-group-start{border-radius:3px 0px 0px 3px !important}.lz-panel-toolbar .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}.lz-panel-toolbar .lz-toolbar-button-group-end{border-radius:0px 3px 3px 0px !important;border-left-width:0px !important}.lz-panel-toolbar input{line-height:normal}.lz-panel-toolbar>.lz-toolbar-left{float:left;margin-right:0px}.lz-panel-toolbar>.lz-toolbar-right{float:right;margin-left:0px}.lz-toolbar{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:80%}.lz-toolbar .lz-toolbar-title{margin-bottom:.3em}.lz-toolbar .lz-toolbar-title h3{font-size:150%;font-weight:bold;margin:0em}.lz-toolbar .lz-toolbar-title small{font-size:80%;font-weight:normal}div.lz-toolbar-menu{font-family:"Helvetica Neue",Helvetica,Aria,sans-serif;font-size:12px;position:absolute;padding:6px;border-radius:4px;box-shadow:2px 2px 2px rgba(24, 24, 24, 0.4);box-sizing:border-box;overflow:hidden}div.lz-toolbar-menu .lz-toolbar-menu-content{display:block;width:100%;height:100%;overflow-y:auto}div.lz-toolbar-menu .lz-toolbar-menu-content h1,div.lz-toolbar-menu .lz-toolbar-menu-content h2,div.lz-toolbar-menu .lz-toolbar-menu-content h3,div.lz-toolbar-menu .lz-toolbar-menu-content h4,div.lz-toolbar-menu .lz-toolbar-menu-content h5,div.lz-toolbar-menu .lz-toolbar-menu-content h6{margin-top:.1em;margin-bottom:.3em}div.lz-toolbar-menu .lz-toolbar-menu-content h1{font-size:200%}div.lz-toolbar-menu .lz-toolbar-menu-content h2{font-size:175%}div.lz-toolbar-menu .lz-toolbar-menu-content h3{font-size:150%}div.lz-toolbar-menu .lz-toolbar-menu-content h4{font-size:135%}div.lz-toolbar-menu .lz-toolbar-menu-content h5{font-size:125%}div.lz-toolbar-menu .lz-toolbar-menu-content h6{font-size:110%}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button{text-decoration:none;padding:2px 6px 2px 6px;height:auto;line-height:inherit;border-radius:3px;pointer-events:auto;outline:none;white-space:nowrap;cursor:pointer;box-sizing:border-box;align-items:flex-start;text-align:center;font-weight:300;letter-spacing:0;text-transform:none;margin:0}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-start{border-radius:3px 0px 0px 3px !important}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-middle{border-radius:0px !important;border-left-width:0px !important}div.lz-toolbar-menu .lz-toolbar-menu-content .lz-toolbar-button-group-end{border-radius:0px 3px 3px 0px !important;border-left-width:0px !important}div.lz-toolbar-menu table{display:table;border-collapse:collapse;border-spacing:0px;margin-bottom:.4em;width:100%}div.lz-toolbar-menu th:first-child,div.lz-toolbar-menu td:first-child{vertical-align:top}div.lz-toolbar-menu tr:nth-child(odd){background-color:rgba(0,0,0,.08)}div.lz-toolbar-menu th,div.lz-toolbar-menu td{padding:4px;text-align:left;vertical-align:middle;border:none;line-height:1}.lz-toolbar-button-gray{background-color:rgba(216,216,216,.6);border:1px solid rgba(51,51,51,.6);color:rgba(51,51,51,.6)}.lz-toolbar-button-gray:not(.lz-toolbar-button-gray-disabled):not(.lz-toolbar-button-gray-highlighted):hover{background-color:#d8d8d8;border:1px solid #333;color:#333}.lz-toolbar-button-gray-highlighted{border:1px solid #333;background-color:#333;color:#d8d8d8 !important}.lz-toolbar-button-gray-disabled{background-color:rgba(216,216,216,.6);border:1px solid rgba(153,153,153,.6);color:rgba(153,153,153,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-red{background-color:rgba(230,195,195,.6);border:1px solid rgba(89,49,49,.6);color:rgba(89,49,49,.6)}.lz-toolbar-button-red:not(.lz-toolbar-button-red-disabled):not(.lz-toolbar-button-red-highlighted):hover{background-color:#e6c3c3;border:1px solid #593131;color:#593131}.lz-toolbar-button-red-highlighted{border:1px solid #593131;background-color:#593131;color:#e6c3c3 !important}.lz-toolbar-button-red-disabled{background-color:rgba(230,195,195,.6);border:1px solid rgba(179,134,134,.6);color:rgba(179,134,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-orange{background-color:rgba(230,213,195,.6);border:1px solid rgba(89,69,49,.6);color:rgba(89,69,49,.6)}.lz-toolbar-button-orange:not(.lz-toolbar-button-orange-disabled):not(.lz-toolbar-button-orange-highlighted):hover{background-color:#e6d5c3;border:1px solid #594531;color:#594531}.lz-toolbar-button-orange-highlighted{border:1px solid #594531;background-color:#594531;color:#e6d5c3 !important}.lz-toolbar-button-orange-disabled{background-color:rgba(230,213,195,.6);border:1px solid rgba(179,156,134,.6);color:rgba(179,156,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-yellow{background-color:rgba(230,230,195,.6);border:1px solid rgba(89,89,49,.6);color:rgba(89,89,49,.6)}.lz-toolbar-button-yellow:not(.lz-toolbar-button-yellow-disabled):not(.lz-toolbar-button-yellow-highlighted):hover{background-color:#e6e6c3;border:1px solid #595931;color:#595931}.lz-toolbar-button-yellow-highlighted{border:1px solid #595931;background-color:#595931;color:#e6e6c3 !important}.lz-toolbar-button-yellow-disabled{background-color:rgba(230,230,195,.6);border:1px solid rgba(179,179,134,.6);color:rgba(179,179,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-green{background-color:rgba(204,230,195,.6);border:1px solid rgba(59,89,49,.6);color:rgba(59,89,49,.6)}.lz-toolbar-button-green:not(.lz-toolbar-button-green-disabled):not(.lz-toolbar-button-green-highlighted):hover{background-color:#cce6c3;border:1px solid #3b5931;color:#3b5931}.lz-toolbar-button-green-highlighted{border:1px solid #3b5931;background-color:#3b5931;color:#cce6c3 !important}.lz-toolbar-button-green-disabled{background-color:rgba(204,230,195,.6);border:1px solid rgba(145,179,134,.6);color:rgba(145,179,134,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-blue{background-color:rgba(195,210,230,.6);border:1px solid rgba(49,66,89,.6);color:rgba(49,66,89,.6)}.lz-toolbar-button-blue:not(.lz-toolbar-button-blue-disabled):not(.lz-toolbar-button-blue-highlighted):hover{background-color:#c3d2e6;border:1px solid #314259;color:#314259}.lz-toolbar-button-blue-highlighted{border:1px solid #314259;background-color:#314259;color:#c3d2e6 !important}.lz-toolbar-button-blue-disabled{background-color:rgba(195,210,230,.6);border:1px solid rgba(134,153,179,.6);color:rgba(134,153,179,.6);pointer-events:none;cursor:wait}.lz-toolbar-button-purple{background-color:rgba(221,195,230,.6);border:1px solid rgba(80,49,89,.6);color:rgba(80,49,89,.6)}.lz-toolbar-button-purple:not(.lz-toolbar-button-purple-disabled):not(.lz-toolbar-button-purple-highlighted):hover{background-color:#ddc3e6;border:1px solid #503159;color:#503159}.lz-toolbar-button-purple-highlighted{border:1px solid #503159;background-color:#503159;color:#ddc3e6 !important}.lz-toolbar-button-purple-disabled{background-color:rgba(221,195,230,.6);border:1px solid rgba(167,134,179,.6);color:rgba(167,134,179,.6);pointer-events:none;cursor:wait}.lz-toolbar-menu-gray{background-color:#e8e8e8;border:1px solid #333}.lz-toolbar-menu-red{background:#f0e4e4;border:1px solid #593131}.lz-toolbar-menu-orange{background:#f0eae4;border:1px solid #594531}.lz-toolbar-menu-yellow{background:#f0f0e4;border:1px solid #595931}.lz-toolbar-menu-green{background:#e7f0e4;border:1px solid #3b5931}.lz-toolbar-menu-blue{background:#e4e9f0;border:1px solid #314259}.lz-toolbar-menu-purple{background:#ede4f0;border:1px solid #503159}div.lz-panel-boundary{position:absolute;height:3px;cursor:row-resize;display:block;padding-top:10px;padding-bottom:10px}div.lz-panel-boundary span{display:block;border-radius:1px;background:rgba(216,216,216,0);border:1px solid rgba(216,216,216,0);height:3px}div.lz-panel-boundary:hover span{background:#d8d8d8;border:1px solid rgb(24, 24, 24)}div.lz-panel-boundary:active span{background:#a6a6a6;border:1px solid rgb(24, 24, 24)}div.lz-panel-corner-boundary{position:absolute;height:16px;width:16px;cursor:nwse-resize;display:block;padding:10px}div.lz-panel-corner-boundary span.lz-panel-corner-boundary-outer{display:block;width:0px;height:0px;border-bottom:16px solid transparent;border-left:16px solid transparent;position:absolute;top:10px;left:10px}div.lz-panel-corner-boundary span.lz-panel-corner-boundary-inner{display:block;width:0px;height:0px;border-bottom:13px solid transparent;border-left:13px solid transparent;position:absolute;top:12px;left:12px}div.lz-panel-corner-boundary:hover span.lz-panel-corner-boundary-outer{border-bottom:16px solid rgb(24, 24, 24)}div.lz-panel-corner-boundary:hover span.lz-panel-corner-boundary-inner{border-bottom:13px solid #d8d8d8}div.lz-panel-corner-boundary:active span.lz-panel-corner-boundary-inner{border-bottom:13px solid #a6a6a6}/*# sourceMappingURL=locuszoom.css.map */ diff --git a/dist/locuszoom.css.map b/dist/locuszoom.css.map index 9ff48e62..f81e376f 100644 --- a/dist/locuszoom.css.map +++ b/dist/locuszoom.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["../css/locuszoom.scss"],"names":[],"mappings":"AAYA,iBAEE,sBACA,YACA,iBACA,wDACA,eAEA,mCACE,UACA,eACA,eAIA,sCACE,aACA,iBAEF,8DACE,UACA,YAEF,gEACE,WACA,WAIJ,iCACE,eACA,gBAGF,sCACE,UACA,iBAGF,8DAEC,UACA,uBACA,iBACA,2BAGD,oCACE,eACA,gBAGF,kCACE,qBACA,kBACA,sBACA,mBAGF,uCACE,aACA,eACA,uBACD,iBACC,iBAGF,kDACE,kCACA,4BACA,4BAGF,qDACE,kCACA,8BACA,4BAGF,iGACE,uBACA,mBACA,iBACA,eAGF,yHACE,uBACA,mBACA,iBAGF,mHACE,uBACA,iBACA,iBAGF,6GACE,gBACA,kBAGF,+GACE,aAGF,6GACE,qBACA,eACA,0BAGF,6GACE,uBACA,iBACA,iBAGF,qDACE,eAGF,+HACE,iBAGF,yCACE,uBACA,iBACA,iBACA,eAGF,+CACE,kBAGF,gDACE,aAGF,iDACE,UACA,YACA,eAGF,uCACE,eAGF,6CACE,WAGF,8CACE,aAGF,mDACE,kBAGF,yEACE,aACA,eACA,iBAGF,qFACE,aACA,gBACA,iBAGF,kFACE,aACA,iBACA,uBACA,iBACA,iBAGF,sDACE,iBACA,iBAGF,kDACE,iBACA,iBAGF,iDACE,WAGF,kDACE,aAGF,iFACE,aACA,eACA,iBAGF,6FACE,aACA,gBACA,iBAGF,0FACE,aACA,iBACA,uBACA,iBACA,iBAGF,2CACE,iBAGF,iHACE,uBACA,iBACA,iBAGF,2CACE,uBACA,mBACA,iBACA,eAGF,uDACE,uBACA,mBACA,iBAGF,oDACE,uBACA,iBACA,iBAGF,iDACE,gBACA,kBAGF,kDACE,aAGF,4DACE,uBACA,iBACA,iBAMJ,0BACE,uDACA,eACA,kBACA,YACA,mBACA,iCACA,kBACA,6CAEA,8KACE,gBACA,mBAGF,4CACA,4CACA,4CACA,4CACA,4CACA,4CAEA,gCACE,cACA,yBACA,mBACA,mBAEF,kFACE,iBAEF,0DACE,YACA,gBACA,gCAGF,iCACE,qBACA,YACA,oBACA,4BACA,yBACA,sBACA,iCACA,kBACA,oBACA,aAEF,uCACE,eACA,iCACA,yBAGF,mDACE,4BACA,uCACA,sCACA,YACA,kBACA,SACA,WACA,uBAKJ,mCACE,QACA,SACA,oBACA,kCACA,mCACA,wCAGF,qCACE,QACA,SACA,oBACA,kCACA,mCACA,qCAGF,sCACE,QACA,SACA,oBACA,iCACA,oCACA,sCAGF,qCACE,QACA,SACA,oBACA,iCACA,oCACA,uCAGF,yCACE,QACA,SACA,oBACA,qCACA,sCACA,oCACA,mCAGF,0CACE,QACA,SACA,oBACA,qCACA,kCACA,oCACA,uCAGF,4CACE,QACA,SACA,oBACA,iCACA,sCACA,wCACA,mCAGF,6CACE,QACA,SACA,oBACA,iCACA,kCACA,wCACA,uCAGF,cACE,qBACA,gBAGF,yBACE,WACA,qBACA,gBAGF,YAEE,kBACA,wDACA,eACA,gBACA,gCAEA,gCACE,kBACA,cACA,WACA,QACA,2BACA,cACA,iBACA,gBAGF,gCACE,kBACA,QACA,UACA,gBACA,eACA,gBACA,yBACA,WACA,sBACA,8BACA,oBACA,eAGF,sCACE,sBACA,cAKJ,WAEE,kBACA,uDACA,eACA,YACA,mBACA,iCACA,kBACA,6CAEA,8BACE,kBACA,cACA,WAGF,yCACE,kBACA,cACA,WACA,WACA,gBAGF,+BACE,kBACA,QACA,SACA,WACA,uCAGF,wCACE,iCACA,wBACA,mCACA,sCAKJ,6BACE,oBACA,uBACA,yBAGF,iBACE,iBACA,kBACA,gBACA,mBAEA,oCACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBAGF,yFACA,+GACA,wHAIF,kCACE,WACA,mBAGF,mCACE,YACA,kBAGF,yCACE,4BAGF,0CACE,2BACA,4BAGF,uCACE,2BAGF,kBACE,iBACA,kBACA,gBACA,mBAEA,qCACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBAGF,0FACA,gHACA,yHAEA,wBACE,mBAIJ,mCACE,WACA,iBAGF,oCACE,YACA,gBAGF,YAEE,uDACA,cAEA,8BACE,mBACA,iCACE,eACA,iBACA,WAEF,oCACE,cACA,mBAMN,oBACE,uDACA,eACA,kBACA,YACA,kBACA,6CACA,sBACA,gBAEA,6CACE,cACA,WACA,YACA,gBAEA,gSACE,gBACA,mBAGF,+DACA,+DACA,+DACA,+DACA,+DACA,+DAEA,gEACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBACA,gBACA,iBACA,oBACA,SAGF,qHACA,2IACA,oJAIF,0BACE,cACA,yBACA,mBACA,mBACA,WAEF,sEACE,mBAEF,sCACE,iCAEF,8CACE,YACA,gBACA,sBACA,YACA,cAIJ,wBACE,sCACA,mCACA,wBAEF,6GACE,yBACA,sBACA,WAEF,oCACE,sBACA,sBACA,yBAEF,iCACE,sCACA,sCACA,2BACA,oBACA,YAGF,uBACE,sCACA,mCACA,wBAEF,0GACE,yBACA,yBACA,cAEF,mCACE,yBACA,yBACA,yBAEF,gCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,yBACE,sCACA,mCACA,wBAEF,gHACE,yBACA,yBACA,cAEF,qCACE,yBACA,yBACA,yBAEF,kCACE,sCACA,sCACA,2BACA,oBACA,YAGF,wBACE,sCACA,mCACA,wBAEF,6GACE,yBACA,yBACA,cAEF,oCACE,yBACA,yBACA,yBAEF,iCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,sBACE,yBACA,sBAGF,qBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,uBACE,mBACA,yBAGF,sBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,sBACE,kBACA,WACA,kBACA,cACA,iBACA,oBAGF,2BACE,cACA,kBACA,+BACA,qCACA,WAGF,iCACE,mBACA,iCAGF,kCACE,mBACA,iCAGF,6BACE,kBACA,YACA,WACA,mBACA,cACA,aAGF,iEACE,cACA,UACA,WACA,qCACA,mCACA,kBACA,SACA,UAGF,iEACE,cACA,UACA,WACA,qCACA,mCACA,kBACA,SACA,UAGF,uEACE,yCAGF,uEACE,iCAGF,wEACE","file":"locuszoom.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["../css/locuszoom.scss"],"names":[],"mappings":"AAYA,iBAEE,sBACA,YACA,iBACA,wDACA,eAEA,mCACE,UACA,eACA,eAIA,sCACE,aACA,iBAEF,8DACE,UACA,YAEF,gEACE,WACA,WAIJ,iCACE,eACA,gBAGF,sCACE,UACA,iBAGF,8DAEC,UACA,uBACA,iBACA,2BAGD,0BAEE,eAGF,oCACE,eACA,gBAGF,uBACE,eAGF,kCACE,qBACA,kBACA,sBACA,mBAGF,uCACE,aACA,eACA,uBACD,iBACC,iBAGF,kDACE,kCACA,4BACA,4BAGF,qDACE,kCACA,8BACA,4BAGF,iGACE,uBACA,mBACA,kBACA,eAGF,yHACE,uBACA,mBACA,iBAGF,mHACE,uBACA,iBACA,iBAGF,6GACE,gBACA,kBAGF,+GACE,aAGF,6GACE,qBACA,eACA,0BAGF,6GACE,uBACA,iBACA,iBAGF,qDACE,eAGF,+HACE,iBAGF,yCACE,uBACA,iBACA,iBACA,eAGF,+CACE,kBAGF,gDACE,aAGF,iDACE,UACA,YACA,eAGF,uCACE,eAGF,6CACE,WAGF,8CACE,aAGF,mDACE,kBAGF,yEACE,aACA,eACA,iBAGF,qFACE,aACA,gBACA,iBAGF,kFACE,aACA,iBACA,uBACA,iBACA,iBAGF,sDACE,iBACA,iBAGF,kDACE,iBACA,iBAGF,iDACE,WAGF,kDACE,aAGF,iFACE,aACA,eACA,iBAGF,6FACE,aACA,gBACA,iBAGF,0FACE,aACA,iBACA,uBACA,iBACA,iBAGF,2CACE,iBAGF,iHACE,uBACA,iBACA,iBAGF,2CACE,uBACA,mBACA,iBACA,eAGF,uDACE,uBACA,mBACA,iBAGF,oDACE,uBACA,iBACA,iBAGF,iDACE,gBACA,kBAGF,kDACE,aAGF,4DACE,uBACA,iBACA,iBAMJ,0BACE,uDACA,eACA,kBACA,YACA,mBACA,iCACA,kBACA,6CAEA,8KACE,gBACA,mBAGF,4CACA,4CACA,4CACA,4CACA,4CACA,4CAEA,gCACE,cACA,yBACA,mBACA,mBAEF,kFACE,iBAEF,0DACE,YACA,gBACA,gCAGF,iCACE,qBACA,YACA,oBACA,4BACA,yBACA,sBACA,iCACA,kBACA,oBACA,aAEF,uCACE,eACA,iCACA,yBAGF,mDACE,4BACA,uCACA,sCACA,YACA,kBACA,SACA,WACA,uBAKJ,mCACE,QACA,SACA,oBACA,kCACA,mCACA,wCAGF,qCACE,QACA,SACA,oBACA,kCACA,mCACA,qCAGF,sCACE,QACA,SACA,oBACA,iCACA,oCACA,sCAGF,qCACE,QACA,SACA,oBACA,iCACA,oCACA,uCAGF,yCACE,QACA,SACA,oBACA,qCACA,sCACA,oCACA,mCAGF,0CACE,QACA,SACA,oBACA,qCACA,kCACA,oCACA,uCAGF,4CACE,QACA,SACA,oBACA,iCACA,sCACA,wCACA,mCAGF,6CACE,QACA,SACA,oBACA,iCACA,kCACA,wCACA,uCAGF,cACE,qBACA,gBAGF,yBACE,WACA,qBACA,gBAGF,YAEE,kBACA,wDACA,eACA,gBACA,gCAEA,gCACE,kBACA,cACA,WACA,QACA,2BACA,cACA,iBACA,gBAGF,gCACE,kBACA,QACA,UACA,gBACA,eACA,gBACA,yBACA,WACA,sBACA,8BACA,oBACA,eAGF,sCACE,sBACA,cAKJ,WAEE,kBACA,uDACA,eACA,YACA,mBACA,iCACA,kBACA,6CAEA,8BACE,kBACA,cACA,WAGF,yCACE,kBACA,cACA,WACA,WACA,gBAGF,+BACE,kBACA,QACA,SACA,WACA,uCAGF,wCACE,iCACA,wBACA,mCACA,sCAKJ,6BACE,oBACA,uBACA,yBAGF,iBACE,iBACA,kBACA,gBACA,mBAEA,oCACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBAGF,yFACA,+GACA,wHAIF,kCACE,WACA,mBAGF,mCACE,YACA,kBAGF,yCACE,4BAGF,0CACE,2BACA,4BAGF,uCACE,2BAGF,kBACE,iBACA,kBACA,gBACA,mBAEA,qCACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBAGF,0FACA,gHACA,yHAEA,wBACE,mBAIJ,mCACE,WACA,iBAGF,oCACE,YACA,gBAGF,YAEE,uDACA,cAEA,8BACE,mBACA,iCACE,eACA,iBACA,WAEF,oCACE,cACA,mBAMN,oBACE,uDACA,eACA,kBACA,YACA,kBACA,6CACA,sBACA,gBAEA,6CACE,cACA,WACA,YACA,gBAEA,gSACE,gBACA,mBAGF,+DACA,+DACA,+DACA,+DACA,+DACA,+DAEA,gEACE,qBACA,wBACA,YACA,oBACA,kBACA,oBACA,aACA,mBACA,eACA,sBACA,uBACA,kBACA,gBACA,iBACA,oBACA,SAGF,qHACA,2IACA,oJAIF,0BACE,cACA,yBACA,mBACA,mBACA,WAEF,sEACE,mBAEF,sCACE,iCAEF,8CACE,YACA,gBACA,sBACA,YACA,cAIJ,wBACE,sCACA,mCACA,wBAEF,6GACE,yBACA,sBACA,WAEF,oCACE,sBACA,sBACA,yBAEF,iCACE,sCACA,sCACA,2BACA,oBACA,YAGF,uBACE,sCACA,mCACA,wBAEF,0GACE,yBACA,yBACA,cAEF,mCACE,yBACA,yBACA,yBAEF,gCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,yBACE,sCACA,mCACA,wBAEF,gHACE,yBACA,yBACA,cAEF,qCACE,yBACA,yBACA,yBAEF,kCACE,sCACA,sCACA,2BACA,oBACA,YAGF,wBACE,sCACA,mCACA,wBAEF,6GACE,yBACA,yBACA,cAEF,oCACE,yBACA,yBACA,yBAEF,iCACE,sCACA,sCACA,2BACA,oBACA,YAGF,0BACE,sCACA,mCACA,wBAEF,mHACE,yBACA,yBACA,cAEF,sCACE,yBACA,yBACA,yBAEF,mCACE,sCACA,sCACA,2BACA,oBACA,YAGF,sBACE,yBACA,sBAGF,qBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,uBACE,mBACA,yBAGF,sBACE,mBACA,yBAGF,wBACE,mBACA,yBAGF,sBACE,kBACA,WACA,kBACA,cACA,iBACA,oBAGF,2BACE,cACA,kBACA,+BACA,qCACA,WAGF,iCACE,mBACA,iCAGF,kCACE,mBACA,iCAGF,6BACE,kBACA,YACA,WACA,mBACA,cACA,aAGF,iEACE,cACA,UACA,WACA,qCACA,mCACA,kBACA,SACA,UAGF,iEACE,cACA,UACA,WACA,qCACA,mCACA,kBACA,SACA,UAGF,uEACE,yCAGF,uEACE,iCAGF,wEACE","file":"locuszoom.css"} \ No newline at end of file diff --git a/docs/api/LLNode.html b/docs/api/LLNode.html new file mode 100644 index 00000000..38d9d43d --- /dev/null +++ b/docs/api/LLNode.html @@ -0,0 +1,342 @@ + + + + + JSDoc: Class: LLNode + + + + + + + + + + +
+ +

Class: LLNode

+ + + + + + +
+ +
+ +

+ undercomplicateLLNode(key, value, metadata, prev, next)

+ +

Implement an LRU Cache

+ + +
+ +
+
+ + + + +

Constructor

+ + + +

new LLNode(key, value, metadata, prev, next)

+ + + + + + +
+

A single node in the linked list. Users will only need to deal with this class if using "approximate match" (cache.find())

+
+ + + + + + + + + +
Parameters:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
key + + +string + + + + + +
value + + +* + + + + + +
metadata + + +object + + + + + +
prev + + +LLNode + + + + + + null + +
next + + +LLNode + + + + + + null + +
+ + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + + +
+ + + + + + + \ No newline at end of file diff --git a/docs/api/LayoutRegistry.html b/docs/api/LayoutRegistry.html index 659fb5bc..e58b9eb1 100644 --- a/docs/api/LayoutRegistry.html +++ b/docs/api/LayoutRegistry.html @@ -288,7 +288,7 @@
Parameters:
Source:
@@ -498,7 +498,7 @@
Parameters:
Source:
@@ -677,7 +677,7 @@
Parameters:
Source:
@@ -963,7 +963,7 @@
Parameters:
Source:
@@ -1189,7 +1189,7 @@
Parameters:
Source:
@@ -1357,7 +1357,7 @@
Parameters:
Source:
@@ -1424,13 +1424,13 @@
Returns:

diff --git a/docs/api/Line.html b/docs/api/Line.html index e2e22c07..35601068 100644 --- a/docs/api/Line.html +++ b/docs/api/Line.html @@ -379,7 +379,7 @@
Properties
Source:
@@ -487,7 +487,7 @@

renderSource:
@@ -673,7 +673,7 @@
Parameters:
Source:
@@ -719,13 +719,13 @@
Parameters:

diff --git a/docs/api/Panel.html b/docs/api/Panel.html index 2178c81f..adb7109b 100644 --- a/docs/api/Panel.html +++ b/docs/api/Panel.html @@ -105,8 +105,6 @@
Parameters:
- <optional>
- @@ -117,12 +115,10 @@
Parameters:
- '' - -

An identifier string that must be unique across all panels in the plot

+

An identifier string that must be unique across all panels in the plot. Required.

@@ -1292,7 +1288,8 @@
Parameters:
- +

The distance between the axis title and the axis. Use this to prevent +the title from overlapping with tick mark labels. If there is not enough space for the label, be sure to increase the panel margins (left or right) accordingly.

@@ -2032,11 +2029,15 @@
Type:
-

(protected) curtain :Object

+

(protected) _event_hooks :Object

+
+

Known event hooks that the panel can respond to

+
+
Type:
@@ -2082,13 +2083,20 @@
Type:
Source:
+
See:
+
+ +
+ @@ -2100,14 +2108,10 @@
Type:
-

data_layers :Object.<String, BaseDataLayer>

- +

(protected) curtain :Object

-
-

Direct access to data layer instances, keyed by data layer ID. Used primarily for introspection/ development.

-
@@ -2115,7 +2119,7 @@
Type:
  • Mix and match
  • +
  • Every layer has its own, private, view of the data
  • What if my data doesn’t fit the expected format?
  • +
  • Combining two kinds of data in one place +
  • Creating your own custom adapter
  • See also
  • @@ -122,7 +128,7 @@

    Your first plot: defining

    Below is an example that defines how to retrieve the data for a “classic” LocusZoom plot, in which GWAS, LD, and recombination rate are overlaid on a scatter plot, with genes and gnomAD constraint information on another track below. In total, five REST API endpoints are used to create this plot: four standard datasets, and one user-provided summary statistics file.

    const apiBase = 'https://portaldev.sph.umich.edu/api/v1/';
     const data_sources = new LocusZoom.DataSources()
    -    .add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', params: { source: 45, id_field: 'variant' }}])
    +    .add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', source: 45, id_field: 'variant' }])
         .add('ld', ['LDServer', { url: 'https://portaldev.sph.umich.edu/ld/', source: '1000G', population: 'ALL', build: 'GRCh37' }])
         .add('recomb', ['RecombLZ', { url: apiBase + 'annotation/recomb/results/', build: 'GRCh37' }])
         .add('gene', ['GeneLZ', { url: apiBase + 'annotation/genes/', build: 'GRCh37' }])
    @@ -130,15 +136,15 @@ 

    Your first plot: defining

    Of course, defining datasets is only half of the process; see the Getting Started Guide for how to define rendering instructions (layout) and combine these pieces together to create the LocusZoom plot.

    Understanding the example

    In the example above, a new data source is added via a line of code such as the following:

    -
    data_sources.add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', params: { source: 45, id_field: 'variant' }}]);
    +
    data_sources.add('assoc', ['AssociationLZ', {url: apiBase + 'statistic/single/', source: 45, id_field: 'variant' }]);

    A lot is going on in this line!

    • data_sources.add defines a piece of information that could be used by the plot. (if no data layer asks for data from this source, then no API request will ever be made)
    • The first argument to the function is a namespace name. It is an arbitrary reference to this particular piece of data. For example, you might want to plot three association studies together in the same window, and they could be defined as .add('mystudy', ...), .add('somephenotype', ...), .add('founditinthegwascatalog', ...)
        -
      • In the layouts guide, we will see how data_layer.fields uses these namespaces to identify what data to render.
      • +
      • In the layouts guide, we will see how data layers use these namespaces.
    • -
    • The second argument to the function is a list of values: the name of a predefined adapter that defines how to retrieve this data, followed by an object of configuration options (like url and params) that control which data will be fetched. Each type of data has its own options; see the documentation for a guide to available choices. +
    • The second argument to the function is a list of values: the name of a predefined adapter that defines how to retrieve this data, followed by an object of configuration options (like url and source) that control which data will be fetched. Each type of data has its own options; see the documentation for a guide to available choices.
      • You are not limited to the types of data retrieval built into LocusZoom.js. See “creating your own adapter” for more information.
    • @@ -147,8 +153,8 @@

      The importance of genome build

      You may notice that in the example above, many of the datasets specify build: 'GRCh37. For “standard” datasets that are widely used (LD, genes, recombination, and GWAS catalog), the UMich APIs will automatically try to fetch the most up-to-date list of genes and GWAS catalog entries for the specified genome build. We currently support build GRCh37 and GRCh38. Be sure to use the genome build that matches your dataset.

      We periodically update our API server. If you think new information is missing, please let us know.

      What should the data look like?

      -

      In theory, LocusZoom.js can display whatever data it is given: layouts allow any individual layout to specify what fields should be used for the x and y axes.

      -

      In practice, it is much more convenient to use pre-existing layouts that solve a common problem well out of the box: the set of options needed to control point size, shape, color, and labels is rather verbose, and highly custom behaviors entail a degree of complexity that is not always beginner friendly. For basic LocusZoom.js visualizations, our default layouts assume that you use the field names and format conventions defined in the UM PortalDev API docs. This is the quickest way to get started.

      +

      In theory, LocusZoom.js can display whatever data it is given: layouts allow any individual layer to specify what fields should be used for the x and y axes.

      +

      In practice, it is much more convenient to use pre-existing layouts that solve a common problem well out of the box: the set of options needed to control point size, shape, color, and labels is rather verbose, and highly custom behaviors entail a degree of complexity that is not always beginner friendly. For basic LocusZoom.js visualizations, our default layouts assume that you use the field names and format conventions defined in the UM PortalDev API docs. This is the quickest way to get started. Most layouts in the provided LocusZoom.Layouts registry will tell you what fields are expected (via the _auto_fields property), and most plots will log a console error message if the response is missing expected information.

      Most users will only need to implement their own way of retrieving GWAS summary statistics; the other annotations are standard datasets and can be freely used from our public API. For complex plots (like annotations of new data), see our example gallery.

      How data gets to the plot

      If you are building a custom tool for exploring data, it is common to show the same data in several ways (eg, a LocusZoom plot next to a table of results). The user will have a better experience if the two widgets are synchronized to always show the same data, which raises a question: which widget is responsible for making the API request?

      @@ -173,6 +179,15 @@

      Example: Loading data from

      Mix and match

      Each data adapter in the chain is largely independent, and it is entirely normal to mix data from several sources: for example, GWAS data from a tabix file alongside genes data from the UMich API server.

      If a single data layer needs to combine two kinds of data (eg association and LD), you will achieve the best results if the sources have some common assumptions about data format. Adapters are highly modular, but because they do not enforce a specific contract of field names or payload structure, you are responsible for ensuring that the resulting data works with the assumptions of your layout.

      +

      Every layer has its own, private, view of the data

      +

      Each data layer in LocusZoom is intended to be independent of others. Thus, each layer must individually specify its own way to connect data together.

      +

      Likewise, each layer defines a “local” way of identifying where to find the data it needs. For example, consider a layer layout as follows:

      +
      {
      +  namespace: {'assoc': 'mystudy'},
      +  id_field: 'assoc:variant'
      +}
      +

      The namespace is specified as a key-value pair of local_name: global_data_source_name. This instruction says: “whenever this layer asks for something from assoc, make a request to an item named mystudy”. Every field in the layout refers to the local_name. This layer of indirection allows a layout to be used many times to plot different datasets, and only the namespace needs to be changed.

      +

      Any changes made to the data within one layer should not affect copies of the same data in other places. This property makes it easier to display the same data in two different ways, without having to make a duplicate network request.

      What if my data doesn’t fit the expected format?

      The built-in adapters are designed to work with a specific set of known REST APIs and fetch data over the web, but we provide mechanisms to customize every aspect of the data retrieval process, including how to construct the query sent to the server and how to modify the fields returned. See the guidance on “custom adapters” below.

      In general, the more similar that your field names are to those used in premade layouts, the easier it will be to get started with common tasks. Certain features require additional assumptions about field format, and these sorts of differences may cause behavioral (instead of cosmetic) issues. For example:

      @@ -181,91 +196,140 @@

      What if my data doesn’
    • JavaScript is not able to accurately represent very small pvalues (numbers smaller than ~ 5e-324), and will truncate them to 0, changing the meaning of your data. For this reason, we recommend sending your data to the web page already transformed to -log pvalue format; this is much less susceptible to problems with numerical underflow.

    If the only difference is field names, you can customize the layout to tell it where to find the required information. (see: guide to layouts and rendering for details) Transformation functions (like neglog10) can then be used to ensure that custom data is formatted in a way suitable for rendering and plotting.

    +

    Combining two kinds of data in one place

    +

    Sometimes, a single data layer will depend on information from two different sources (like an association plot colored by LD information).

    +

    Data operations (layout directive)

    +

    The act of combining two pieces of data is performed by data operations. In order to let the same piece of data be rendered in different ways, these instructions are placed within each data layer layout. The decision on how to combine two pieces of information is specified at the point where the data is used.

    +

    A sample layout directive for data operations would be as follows:

    +
    {
    +    namespace: { 'assoc': 'mystudy', 'ld': 'some_ld' },
    +    data_operations: [
    +        {
    +            type: 'fetch',
    +            from: ['assoc', 'ld(assoc)'],
    +        },
    +        {
    +            type: 'left_match',
    +            name: 'assoc_plus_ld',
    +            requires: ['assoc', 'ld'],
    +            // Tell the join function which field names to be used for the join. Each join function has its own possible parameters.
    +            params: ['assoc:position', 'ld:position2'], 
    +        },
    +    ]
    +}
    +

    Dependencies

    +

    The first instruction in the example above specifies how to retrieve the data: {type: 'fetch', from: ['assoc', 'ld(assoc)'}

    +

    A single “fetch” operation is used to specify all of the data retrieval. This specifies what information a data layer should retrieve. It refers to the “local” namespace name (like “assoc”), and tells locuszoom to make a request to the global datasource named “mystudy”.

    +

    Some adapters can not begin to define their request until they see the data from another adapter: eg LD information is retrieved relative to the most significant association variant in the region. This is a dependency, and one (or more) dependencies can be specified using the syntax some_request(first_dependency, nth_dependency). LocusZoom will automatically reorder and parallelize requests based on the dependencies given. If several requests each have no dependencies, they will be performed in parallel.

    +

    Each individual adapter will receive data it depends on as a function argument to getData. The string syntax reflects how the data is connected internally! In the example above, “ld” is only retrieved after a request to “assoc” is complete, and the LD adapter received the assoc data to help define the next request.

    +
    +

    NOTE: Sometimes it is useful to extend an existing layout to fetch additional kinds of data. It can be annoying to extend a “list” field like fetch.from, so LocusZoom has some magic to help out: if an item is specified as a source of data for this layer (eg namespace: {'assoc': 'assoc'}), it will automatically be added to the fetch.from instruction. This means that everything listed in data_layer.namespace will trigger a data retrieval request. You only need to modify the contents of fetch.from if you want to specify that the new item depends on something else, eg “don’t fetch LD until assoc data is ready: ld(assoc)”. All of the built in LZ layouts are verbose and explicit, in an effort to reduce the amount of “magic” and make the examples easier to understand.

    +
    +

    Joins (“Data functions”)

    +

    The second instruction in the example above is a join. It specifies how to compare multiple sets of data into one list of records (“one record per data point on the plot”).

    +

    Any function defined in LocusZoom.DataFunctions can be referenced. Several builtin joins are provided (including left_match, inner_match, and full_outer_match). Any arbitrary join function can be added to the LocusZoom.DataFunctions registry, with the call signature ({plot_state, data_layer}}, [recordsetA, recordsetB...], ...params) => combined_results.

    +

    Data operations are synchronous; they are used for data formatting and cleanup. Use adapters for asynchronous operations like network requests.

    +

    The plot will receive the last item in the dependency graph (taking into account both adapters and joins). If something looks strange, make sure that you have specified how to join all your data sources together.

    +
    +

    TIP: Because data functions are given access to plot.state and the data layer instance that initiated the request, they are able to do surprisingly powerful things, like filtering the returned data in response to a global plot_state parameter or auto-defining a layout (data_layer.layout) in response to dynamic data (axis labels, color scheme, etc). This is a very advanced usage and has the potential for side effects; use sparingly! See the LocusZoom unit tests for a few examples of what is possible.

    +

    Creating your own custom adapter

    -

    Re-using code via subclasses

    +

    Can I reuse existing code?

    +

    The built-in LocusZoom adapters can be used as-is in many cases, so long as the returned payload matches the expected format. You may need to write your own custom code (adapter subclass) in the following scenarios:

    +
      +
    1. If an expression must be evaluated in order to retrieve data (eg constructing URLs based on query parameters, or LD requests where the reference variant is auto-selected from the most significant hit in a GWAS)
    2. +
    3. If the actual headers, body, or request method must be customized in order to carry out the request. This happens when data is retrieved from a particular technology (REST vs GraphQL vs Tabix), or if the request must incorporate some form of authentication credentials.
    4. +
    5. If some of the fields in your custom API format need to be transformed or renamed in order to match expectations in LZ code. For example, the LD adapter may try to suggest an LD reference variant by looking for the GWAS variant with the largest log_pvalue. (over time, built-in LZ adapters trend towards being more strict about field names; it is easier to write reliable code when not having to deal with unpredictable data!)
    6. +
    +

    Customizing data retrieval via subclasses

    Most custom sites will only need to change very small things to work with their data. For example, if your REST API uses the same payload format as the UM PortalDev API, but a different way of constructing queries, you can change just one function and define a new data adapter:

    -
    const AssociationLZ = LocusZoom.Adapters.get('AssociationLZ');
    -class CustomAssociation extends AssociationLZ {
    -    getURL(state, chain, fields) {
    -        // The inputs to the function can be used to influence what query is constructed. Eg, the current view region is stored in `plot.state`.
    -        const {chr, start, end} = state;
    -        // Fetch the region of interest from a hypothetical REST API that uses query parameters to define the region query, for a given study URL such as `data.example/gwas/<id>/?chr=_&start=_&end=_`
    -        return `${this.url}/${this.params.study_id}/?chr=${encodeURIComponent(chr)}&start=${encodeURIComponent(start)}&end${encodeURIComponent(end)}`
    -  }
    -}
    -// A custom adapter should be added to the registry before using it
    -LocusZoom.Adapters.add('CustomAssociation', CustomAssociation);
    -
    -// From there, it can be used anywhere throughout LocusZoom, in the same way as any built-in adapter
    -data_sources.add('mystudy', ['CustomAssociation', {url: 'https://data.example/gwas', params: { study_id: 42 }}]);
    -

    In the above example, an HTTP GET request will be sent to the server every time that new data is requested. If further control is required (like sending a POST request with custom body), you may need to override additional methods such as fetchRequest. See below for more information, then consult the detailed developer documentation for details.

    +
    const AssociationLZ = LocusZoom.Adapters.get('AssociationLZ');
    +class CustomAssociation extends AssociationLZ {
    +    _getURL(request_options) {
    +        // Every adapter receives the info from plot.state, plus any additional request options calculated/added in the function `_buildRequestOptions`
    +        // The inputs to the function can be used to influence what query is constructed. Eg, since the current view region is stored in `plot.state`:
    +        const {chr, start, end} = request_options;
    +        // Fetch the region of interest from a hypothetical REST API that uses query parameters to define the region query, for a given study URL such as `data.example/gwas/<id>/?chr=_&start=_&end=_`
    +        return `${this._url}/${this.source}/?chr=${encodeURIComponent(chr)}&start=${encodeURIComponent(start)}&end${encodeURIComponent(end)}`
    +  }
    +  
    +  _annotateRecords(records, options) {
    +      // Imagine that your API returns a payload that mostly works, but a few fields are a little different than what is expected.
    +      // Usually LocusZoom is pretty tolerant of changing field names- but because Association plots connect to so many extra annotations, certain magic features require a little extra attention to detail
    +      records.forEach((item) => {
    +          // LocusZoom connects assoc summstats to other datasets, by finding the most significant variant. To find that variant and ask for LD, it expects two special fields with very specific names, and sort of specific formats. If you already have these fields, great- if not, they can be manually added by custom code, even if no one will let you change the API server directly
    +          item.log_pvalue = -Math.log10(item.pValue);  // It's better if you send log_pvalue from the server directly, not calculate it on the front end (JS is subject to numerical underflow, and sending pValue to the browser may cause numerical underflow problems)
    +          item.variant = `${item.chrom}:${item.pos}_${item.ref}/${item.alt}`;
    +      });
    +      return records;
    +  }
    +}
    +// A custom adapter should be added to the registry before using it
    +LocusZoom.Adapters.add('CustomAssociation', CustomAssociation);
    +
    +// From there, it can be used anywhere throughout LocusZoom, in the same way as any built-in adapter
    +data_sources.add('mystudy', ['CustomAssociation', {url: 'https://data.example/gwas', source: 42 }]);
    +

    In the above example, an HTTP GET request will be sent to the server every time that new data is requested. If further control is required (like sending a POST request with custom body), you may need to override additional methods such as fetchRequest. See below for more information, then consult the detailed developer documentation for details.

    Common types of data retrieval that are most often customized:

    • GWAS summary statistics
        -
      • This fetches the data directly with minor cleanup. You can customize the built-in association adapter, or swap in another way of fetching the data (like tabix).
      • -
    • -
    • User-provided linkage disequilibrium (LD) -
        -
      • This contains special logic used to combine association data (from a previous request) with LD information. To ensure that the matching code works properly, we recommend matching the payload format of the public LDServer, but you can customize the getURL method to control where the data comes from.
      • -
      • For performance reasons, connecting LD and association data together assumes that both datasets are sorted in order of increasing chromosome and position.
      • +
      • This fetches the data directly with minor cleanup. You can customize the built-in association adapter, or swap in another way of fetching the data (like tabix). You may want to ensure that a field called log_pvalue is present, and possibly customize other fields as well.
    • -
    • PheWAS results
    • +
    • PheWAS results (not every server returns PheWAS results in the same format)

    What happens during a data request?

    The adapter performs many functions related to data retrieval: constructing the query, caching to avoid unnecessary network traffic, and parsing the data into a transformed representation suitable for use in rendering.

    Methods are provided to override all or part of the process, called in roughly the order below:

    -
    getData(state, fields, outnames, transformations)
    -    getRequest(state, chain, fields)
    -        getCacheKey(state, chain, fields)
    -        fetchRequest(state, chain, fields)
    -            getURL(state, chain, fields)
    -    parseResponse(resp, chain, fields, outnames, transformations)
    -        normalizeResponse(data)
    -        annotateData(data, chain)
    -        extractFields(data, fields, outnames, trans)
    -        combineChainBody(data, chain, fields, outnames)
    +
    getData(plot_state, ...dependent_data)
    +    _buildRequestOptions(plot_state, ...dependent_data)
    +    _getCacheKey(request_options)
    +    _performRequest(request_options)
    +        _getURL(request_options)
    +    // Parse JSON, convert columnar data to rows, etc
    +    _normalizeResponse(raw_response, options)
    +        cache.add(records)
    +    // User-specified cleanup of the parsed response fields. Can be used for things like field renaming, record filtering, or adding new calculated fields on the fly
    +    _annotateRecords(records, options)
    +    // Usually not overridden: this method can be used to apply prefixes (assoc:id, catalog:id, etc) and to simplify down verbose responses to just a few `limit_fields` of interest
    +    _postProcessResponse(records, options)

    The parameters passed to getData are as follows:

      -
    • state - this is the current “state” of the plot. This contains information about the current region in view (chr, start, and end), which is often valuable in querying a remote data source for the data in a given region.
    • -
    • fields - this is an array of field names that have been requested from this data source. Note that the “namespace:” part of the name has been removed in this array. Note: most data adapters will return only the fields that are requested by a data layer. Each data layer can request a different set of fields, and thus different parts of the plot may have a different view of the same data.
    • -
    • outnames - this is an array with length equal to fields with the original requested field name. This value contains the data source namespace. The data output for each field should be given the name in this array. This is rarely used directly.
    • -
    • transformations - this is an array with length equal to fields with the collection of value transformations functions specified by the user to be run on the returned field. This is rarely used directly.
    • +
    • plot_state: Every adapter request contains a copy of plot.state, which stores global information (like view region chr/start/end) that can be used to customize the request.
    • +
    • ...dependent_data: If the adapter depends on prior requests, the parsed records from each prior request will be passed to this function (each function argument would be one dependent request, represented as an array of row-based record objects: [{'assoc:variant': '1:23_A/C', 'assoc:log_pvalue': 75 }])
    -

    Step 1: Fetching data from a remote server

    -

    The first step of the process is to retrieve the data from an external location. getRequest is responsible for deciding whether the query can be satisfied by a previously cached request, and if not, sending the response to the server. At the conclusion of this step, we typically have a large unparsed string: eg REST APIs generally return JSON-formatted text, and tabix sources return lines of text for records in the region of interest.

    +

    This function will return row-format data representing the response for just that request. It will use a cached response if feasible. By default, LocusZoom will apply certain transformation to the returned response so that it is easier to use with a data layer (see adapter documentation for details). All fields in the original response will be returned as given.

    +

    Step 1: Fetching data from a remote server and converting to records

    +

    The first step of the process is to retrieve the data from an external location. _buildRequestOptions can be used to store any parameters that customize the request, including information from plot.state. If the response is cached, the cache value will be returned; otherwise, a request will be initiated. Once the request is complete, the result will be parsed and cached for future use.

    +

    At the conclusion of this step, we typically have an array of records, one object per row of data. The field names and contents are very close to what was returned by the API.

    Most custom data sources will focus on customizing two things:

      -
    • getURL (how to ask the external source for data)
    • -
    • getCacheKey (decide whether the request can be satisfied by local data) +
    • _getURL (how to ask the external source for data)
    • +
    • _getCacheKey (decide whether the request can be satisfied by local data)
      • By default this returns a string based on the region in view: '${state.chr}_${state.start}_${state.end}'
      • You may need to customize this if your source has other inputs required to uniquely define the query (like LD reference variant, or calculation parameters for credible set annotation).
    -

    Step 2: Formatting and parsing the data

    -

    The parseResponse sequence handles the job of parsing the data. It can be used to convert many different API formats into a single standard form. There are four steps to the process:

    +

    Step 2: Transforming data into a form usable by LocusZoom

    +

    In a prior step, the records were normalized, but kept in a form that is usually close to what the API returned. In this step, records are modified for use in the plot:

      -
    • normalizeResponse - Converts any data source response into a standard format. This can be used when you want to take advantage of existing data handling functionality of a particular adapter (like performing an interesting calculation), but your data comes from something like a tabix file that needs to be adjusted to match the expected format. +
    • _normalizeResponse - Converts any data source response into a standard format. This can be used when you want to take advantage of existing data handling functionality of a particular adapter (like performing an interesting calculation), but your data comes from something like a tabix file that needs to be adjusted to match the expected format.
      • Internally, most data layer rendering types assume that data is an array, with each datum element represented by an object: [{a_field: 1, other_field: 1}]
      • Some sources, such as the UM PortalDev API, represent the data in a column-oriented format instead. ({a_field: [1], other_field: [1]}) The default adapter will attempt to detect this and automatically transform those columns into the row-based one-record-per-datum format.
    • -
    • annotateData - This can be used to add custom calculated fields to the data. For example, if your data source does not provide a variant marker field, one can be generated in javascript (by concatenating chromosome:position_ref/alt), without having to modify the web server.
    • -
    • extractFields - Each data layer receives only the fields it asks for, and the data is reformatted in a way that clearly identifies where they come from (the namespace is prefixed onto each field name, eg {'mynamespace:a_field': 1}). +
    • _annotateRecords - This can be used to modify the data returned in many useful ways: filtering, renaming fields, or adding new calculated fields. Example scenarios:
        -
      • The most common reason to override this method is if the data uses an extremely complex payload format (like genes), and a custom data layer expects to receive that entire structure as-is. If you are working with layouts, the most common sign of an adapter that does this is that the data layer asks for a nonexistent field (gene:all - a synthetic value whose sole purpose is to indicate that the source is used)
      • +
      • A field called pValue can be transformed into one called log_pvalue
      • +
      • If a tabix file returns two categories of data at once, then the adapter could decide which to show according to a user-selected option stored in plot.state (So long as both datasets are not too big, this trick works well with the set_state toolbar widget: it provides a cheap way to toggle between datasets, without requiring an extra trip to the server!)
      • +
      • Adding custom calculated fields to the data. For example, if your data source does not provide a variant marker field, one can be generated in javascript (by concatenating chromosome:position_ref/alt), without having to modify the web server.
    • -
    • combineChainBody: If a single data layer asks for data from more than one source, this function is responsible for combining several different pieces of information together. For example, in order to show an association plot with points colored by LD, the LD adapter implements custom code that annotates the association data with matching LD information. At the end of this function, the data layer will receive a single combined record per visualized data element.
    • -
    -

    Working with the data “chain”

    -

    Each data layer is able to request data from multiple different sources. Internally, this process is referred to as the “chain” of linked data requested. LocusZoom.js assumes that every data layer is independent and decoupled: it follows that each data layer has its own chain of requests and its own parsing process.

    -

    This chain defines how to share information between different adapters. It contains of two key pieces:

    +
  • _postProcessResponse: Most people don’t customize this method. After all calculations are done, this is used to transform the data into a format useful by LocusZoom. Eg, field names are prefixed to reflect where the data came from, like assoc:log_pvalue. This happens last, so most custom code that modifies returned records doesn’t have to deal with it.
      -
    • body - the actual consolidated payload. Each subsequent link in the chain receives all the data from the previous step as chain.body
    • -
    • headers - this is a “meta” section used to store information used during the consolidation process. For example, the LD adapter needs to find the most significant variant from the previous step in the chain (association data) in order to query the API for LD. The name of that variant can be stored for subsequent use during the data retrieval process.
    • +
    • Most of the behaviors in this method can be overridden using adapter options, without writing custom code. (see documentation for details)
    • +
  • -

    Only chain.body is sent to the data layer. All other parts of the chain are discarded at the end of the data retrieval process.

    See also

    • LocusZoom.js is able to share its data with external widgets on the page, via event listeners that allow those widgets to update whenever the user interacts with the plot (eg panning or zooming to change the region in view). See subscribeToData in the guide to interactivity for more information.
      diff --git a/docs/guides/interactivity.html b/docs/guides/interactivity.html index 1ace033a..57d3c01c 100644 --- a/docs/guides/interactivity.html +++ b/docs/guides/interactivity.html @@ -108,7 +108,6 @@

      Table of Contents

    • Events communicate with the outside world
    • Share data with other widgets via subscribeToData
    • Filters control what is shown @@ -183,7 +182,6 @@

      Layout mutations change what

      Each LocusZoom rendering is controlled by a declarative set of layout options. In practice, this means that a clever developer can change key options (eg point color, or what field is shown on the y-axis) simply by modifying (mutating) the layout, then re-rendering.

      In practice, this is the key idea behind the display_options widget, a built-in feature that handles such mutations in a controlled fashion. If you are doing this using your own code, the following “gotchas” apply:

        -
      • When the layout is defined before first render, it uses abstract syntax (eg {{namespace[assoc]field}}. To modify an existing plot layout after it has been rendered, you will need to use concrete syntax in which the namespace has been filled in: assoc2_mystudy:field.
      • LocusZoom layouts are nested and hierarchical (plot –> panels[] –> data_layers[]). See the helper functions below for advice on how to write mutations that are more readable and maintainable.
      • Be conservative in how many fields you allow to be changed. Layouts allow almost any aspect of the plot to be customized, but it can be difficult to test every possible combination. It’s generally easier to code and maintain controlled options (like a list of preset views).
      @@ -241,36 +239,14 @@

      Events communicate with the o

      Share data with other widgets via subscribeToData

      Using the same mechanisms and syntax as an LZ data layer, let arbitrary parts of the page listen for new data by asking for the (namespaced) fields of interest.

      Sample usage:

      -
      const fields = ['aggregation:all', 'gene:all'];
      -const success_callback = (data) => console.log(data);
      -const opts = { onerror: (err) => console.log(err) };
      -
      -plot.subscribeToData(fields, success_callback, opts);
      +
      // Receives exactly the same data as the specified datalayer ID (avoids having to duplicate namespace and data operations code)
      +const spec = { from_layer: 'panel1.layer1' };
      +const success_callback = (data) => console.log(data);
      +const opts = { onerror: (err) => console.log(err) };
      +
      +plot.subscribeToData(spec, success_callback, opts);

      When data is received, calls success_callback with the resulting data (an array of objects, with each object representing one datapoint). subscribeToData can be used to draw tables or companion visualizations on the page, separate from LocusZoom but automatically updating to stay in sync as the user clicks or pans across the plot. Specify onerror as an option to provide an error handling callback.

      -

      Caveat: namespaces

      -

      Note that the returned payload will contain namespaced fields: the data will appear in the same format as used internally by LocusZoom. Sometimes this is annoying because it means that any external widget using the data will need to account for LocusZoom’s namespacing syntax.

      -

      If you don’t want to be bothered with namespacing, the following utility function may be useful:

      -
      /**
      -* Remove the `sourcename:` prefix from field names in the data returned by an LZ datasource
      -*
      -* This is a convenience method for writing external widgets (like tables) that subscribe to the
      -* plot; typically we don't want to have to redefine the table layout every time someone selects
      -* a different association study.
      -* As with all convenience methods, it has limits: don't use it if the same field name is requested
      -* from two different sources!
      -* @param {Object} data An object representing the fields for one row of data
      -* @param {String} [prefer] Sometimes, two sources provide a field with same name. Specify which
      -* source will take precedence in the event of a conflict.
      -*/
      -function deNamespace(data, prefer) {
      -    return Object.keys(data).reduce((acc, key) => {
      -        const new_key = key.replace(/.*?:/, '');
      -        if (!Object.prototype.hasOwnProperty.call(acc, new_key) || (!prefer || key.startsWith(prefer))) {
      -            acc[new_key] = data[key];
      -        }
      -        return acc;
      -    }, {});
      -}
      +

      Sometimes you want exact control over what data is retrieved, rather than mirroring a data layer. In that case, replace from_layer with two options (namespace and data_operations) to manually specify how data is retrieved for this callback. See data layer documentation for syntax and usage.

      Advanced alternative

      Sometimes, the existing page already has several widgets sharing data, and it would be difficult to rewrite things after the fact in a way that ceded control of data to LocusZoom. In this case, some compromise needs to be reached: how can LocusZoom fetch what it needs (possibly rendering only a subset of the data available), without duplicating API calls to the server that have already been made elsewhere?

      Reactive rendering frameworks sometimes solve the problem of sharing mutable data via a shared local cache (store) that represents data from the server. LocusZoom can then make requests to that store, and the store is then responsible for deciding whether a new server request is needed. This allows the result of a single API request to power all widgets on the page without redundant network traffic. The store call can then return a promise representing either local data, or the result of a server request, as appropriate.

      @@ -279,27 +255,27 @@

      Advanced alternative

      Filters control what is shown

      Filters can be used to control what elements are shown on a panel. This will hide elements, but preserve the space that those elements would have occupied: eg, the axis limits will reflect all of the data, not just what is currently shown.

      Filters are specified in data layout layouts, and can be applied to most data layer types.

      -
      {
      -  ...options,
      -  filters: [
      -    { field: '{{namespace[access]}}score', operator: '!=', value: null },
      -  ],
      -}
      +
      {
      +  ...options,
      +  filters: [
      +    { field: '{{namespace[access]}}score', operator: '!=', value: null },
      +  ],
      +}

      Scatter plots have an additional option to show labels for some or all data elements. This is controlled via adding a similar filter block inside label:

      -
      {
      -  id: 'phewaspvalues',
      -  ...options,
      -  label: {
      -    text: '{{{{namespace[phewas]}}trait_label}}',
      -    filters: [
      -      {
      -        field: '{{namespace[phewas]}}log_pvalue',
      -        operator: '>=',
      -        value: 20,
      -      },
      -    ],
      -  }
      -}
      +
      {
      +  id: 'phewaspvalues',
      +  ...options,
      +  label: {
      +    text: '{{{{namespace[phewas]}}trait_label}}',
      +    filters: [
      +      {
      +        field: '{{namespace[phewas]}}log_pvalue',
      +        operator: '>=',
      +        value: 20,
      +      },
      +    ],
      +  }
      +}

      The following filters are available:

      • =: field value exactly matches the provided value
      • @@ -328,31 +304,31 @@

        Annotations preser

        LocusZoom typically maintains a separation of concerns, in which data layers are responsible for rendering the data provided by an adapter. For the most part, the display layer is not responsible for changing data, and it does not preserve state across renderings

        However, there are some situations where a user might wish to modify how the data is shown: eg “show a label for this one specific point”.

        The basic mechanism for this is called annotations:

        -
        // External code, or tooltips, may set a value
        -data_layer.setElementAnnotation(element_data, key, value);
        -data_layer.getElementAnnotation(item, key);
        +
        // External code, or tooltips, may set a value
        +data_layer.setElementAnnotation(element_data, key, value);
        +data_layer.getElementAnnotation(item, key);

        Essentially, a rendering annotation stores an additional field for a given data point, but that field is stored internally rather than being sent by the data adapter. It can be used in any layout directive that operates on fields: size, shape, color, labels, etc.

        The value can be anything you wish. However, LocusZoom works best when field values are primitives (like strings or integers).

        Typically this is used by tooltips, allowing the user to click a link and modify how a point is shown. See the example below:

        -
        const tooltip = {
        -  // In this example, we take advantage of the fact that each tooltip is bound to the data for a specific point. Internally, D3 stores this information in a field called node.__data__, and we can use this to get the data for a tooltip.
        -  html: `<a href="javascript:void(0);" 
        -          onclick="var item = this.parentNode.__data__, layer = item.getDataLayer(); 
        -          var current = layer.getElementAnnotation(item, 'lz_show_label'); 
        -          layer.setElementAnnotation(item, 'lz_show_label', !current );
        -          layer.parent_plot.applyState();">Toggle label</a>`;`
        -}
        -
        -// The annotation is an additional field, but it doesn't come from the datasource. It can be used in any layout directive that operates on fields: size, shape, color, labels, etc..
        -const scatter_layout = {
        -  ...options,
        -  label: {
        -    ...label_options,
        -    filters: [
        -      { field: 'lz_show_label', operator: '=', value: true }
        -    ],
        -  }
        -};
        +
        const tooltip = {
        +  // In this example, we take advantage of the fact that each tooltip is bound to the data for a specific point. Internally, D3 stores this information in a field called node.__data__, and we can use this to get the data for a tooltip.
        +  html: `<a href="javascript:void(0);" 
        +          onclick="var item = this.parentNode.__data__, layer = item.getDataLayer(); 
        +          var current = layer.getElementAnnotation(item, 'lz_show_label'); 
        +          layer.setElementAnnotation(item, 'lz_show_label', !current );
        +          layer.parent_plot.applyState();">Toggle label</a>`;`
        +}
        +
        +// The annotation is an additional field, but it doesn't come from the datasource. It can be used in any layout directive that operates on fields: size, shape, color, labels, etc..
        +const scatter_layout = {
        +  ...options,
        +  label: {
        +    ...label_options,
        +    filters: [
        +      { field: 'lz_show_label', operator: '=', value: true }
        +    ],
        +  }
        +};

        Matching similar elements across panels

        The primary benefit of LocusZoom is to show results in context, allowing the user to create connections between multiple sources of information.

        When a lot of data is being shown at once, it can be hard to identify exactly which points line up across tracks- each one is quite small! Fortunately, there is a mechanism by which two panels can communicate to find related elements: matching.

        @@ -364,20 +340,20 @@

        Matching similar elements acros
      • The special tag added to these points (lz_is_match) is treated as an extra field, and can be used in any scalable layout directive to control point size, shape, color, filters, etc. This field doesn’t come from the API or data adapter- it is an internal value that is checked on every render.
      • Usage example:

        -
        {
        -  ...options,
        -  // Note that a data layer can send AND receive. This means that it can respond to its own events: "when a match point is clicked, turn that point red"
        -  match: { send: '{{namespace[access]}}target', receive: '{{namespace[access]}}target' },
        -  color: [
        -    {
        -      field: 'lz_is_match', // When a match is detected, it is tagged with a special field name that can be used to trigger custom rendering
        -      scale_function: 'if',
        -      parameters: {
        -        field_value: true,
        -        then: '#ff0000',
        -      },
        -    },
        -}
        +
        {
        +  ...options,
        +  // Note that a data layer can send AND receive. This means that it can respond to its own events: "when a match point is clicked, turn that point red"
        +  match: { send: '{{namespace[access]}}target', receive: '{{namespace[access]}}target' },
        +  color: [
        +    {
        +      field: 'lz_is_match', // When a match is detected, it is tagged with a special field name that can be used to trigger custom rendering
        +      scale_function: 'if',
        +      parameters: {
        +        field_value: true,
        +        then: '#ff0000',
        +      },
        +    },
        +}

        TIP: Matching builds on the primitives described above: it responds to a specific internal event (match_requested), and broadcasts a field to all layers via plot.state.lz_match_value . This means that outside code can also cause the plot to render matching elements, by initiating the rendering update manually: plot.applyState({lz_match_value: your_value_here })

        @@ -386,10 +362,10 @@

        Matching similar elements acros

        Matching rules can be customized

        Matching is not limited to exact value equality. Using a third parameter (“operator”), matching rules can use any of the comparison functions in LocusZoom.MatchFunctions. As described in the description of filtering rules above, match rules can also take into account transforms that modify the field value before it is broadcast, or, how the broadcast value is compared to a specific field. Custom logic (operators) can also be added via MatchFunctions and accessed via name.

        -
        {
        -    ...options,
        -    match: { send: '{{namespace[access]}}target|htmlescape', receive: '{{namespace[access]}}target|htmlescape', operator: '!=' },
        -}
        +
        {
        +    ...options,
        +    match: { send: '{{namespace[access]}}target|htmlescape', receive: '{{namespace[access]}}target|htmlescape', operator: '!=' },
        +}

        NOTE: Remember that the template transforms are also extensible! Each |templatefunction refers to a function in LocusZoom.TransformationFunctions. Add your own via LocusZoom.TransformationFunctions.add('my_function', (value) => othervalue). Custom plugins allow you to create very powerful custom presentations.

        @@ -403,119 +379,119 @@

        Tooltips

        The first interactive feature that most LocusZoom users notice is the tooltip: a simple box that appears with more information when a user interacts with a point.

        In addition to showing data associated with a field, tooltips can be customized with interactive action links that modify plot.state (eg setting the LD reference variant), or trigger annotations (like showing a label).

        A tooltip is defined as an object describing when to display it, as well as the HTML template to render. It responds to the same LocusZoom template syntax supported elsewhere. For example, values can be embedded in the string with curly braces ({{assoc:fieldname}}) and a simple conditional syntax is supported to only render text if a value is defined: {{#if sourcename:field_name}} Conditional text {{#else}} Optional else block {{/if}}.

        -
        {
        -  // Inherits namespaces from the layer that uses this tooltip
        -  namespace: { 'assoc': 'assoc' },
        -  closable: true,
        -  // Show/hide logic is defined by the "element status" for a given piece of data. See `behaviors` for how these statuses get applied.
        -  show: { or: ['highlighted', 'selected'] },
        -  hide: { and: ['unhighlighted', 'unselected'] },
        -  // The tooltip text is an HTML template with access to fields in the data. Be sure to apply HTML-escaping to any user-provided data.
        -  html: `<strong>{{{{namespace[assoc]}}variant|htmlescape}}</strong>`,
        -}
        +
        {
        +  // Inherits namespaces from the layer that uses this tooltip
        +  namespace: { 'assoc': 'assoc' },
        +  closable: true,
        +  // Show/hide logic is defined by the "element status" for a given piece of data. See `behaviors` for how these statuses get applied.
        +  show: { or: ['highlighted', 'selected'] },
        +  hide: { and: ['unhighlighted', 'unselected'] },
        +  // The tooltip text is an HTML template with access to fields in the data. Be sure to apply HTML-escaping to any user-provided data.
        +  html: `<strong>{{{{namespace[assoc]}}variant|htmlescape}}</strong>`,
        +}

        Behaviors

        By default, almost every LocusZoom data element shows a tooltip on mouseover, and keeps that tooltip open when the element is clicked. However, this can be customized.

        See below for an example of a layer where clicking a point acts as a link to a new page.

        -
        {
        -  ...layer_options,
        -  behaviors: {
        -    onmouseover: [
        -      // Most tooltips are configured to appear when the element is highlighted (along with applying any other display tweaks to the page). A guide to statuses is outside the scope of this tutorial, but the default "mouse move actions" are shown for the sake of completeness.
        -      { action: 'set', status: 'highlighted' },
        -    ],
        -    onmouseout: [
        -      { action: 'unset', status: 'highlighted' },
        -    ],
        -    onclick: [
        -        // The href parameter supports LocusZoom's template syntax, allowing data fields to be used in the URL
        -      { action: "link", href: "https://pheweb.org/pheno/{{{{namespace[phewas]}}phewas_code}}" }
        -    ],
        -  },
        -}
        +
        {
        +  ...layer_options,
        +  behaviors: {
        +    onmouseover: [
        +      // Most tooltips are configured to appear when the element is highlighted (along with applying any other display tweaks to the page). A guide to statuses is outside the scope of this tutorial, but the default "mouse move actions" are shown for the sake of completeness.
        +      { action: 'set', status: 'highlighted' },
        +    ],
        +    onmouseout: [
        +      { action: 'unset', status: 'highlighted' },
        +    ],
        +    onclick: [
        +        // The href parameter supports LocusZoom's template syntax, allowing data fields to be used in the URL
        +      { action: "link", href: "https://pheweb.org/pheno/{{{{namespace[phewas]}}phewas_code}}" }
        +    ],
        +  },
        +}

        Toolbar Widgets

        Toggle between render modes with display_options

        The display_options widget renders a dropdown menu with several possible visualization settings. Each time an item is clicked, it will override the default properties.

        To avoid duplication of code, the original display settings are automatically captured and shown as the “Default” option. Other options in the dropdown menu are specified as a list of layout directives that will be merged into the data layer.

        -
        const gene_selector_widget = {
        -  type: 'display_options',
        -  // Below: special config specific to this widget
        -  button_html: 'Filter...',
        -  button_title: 'Choose which genes to show',
        -  // If you are tracking website analytics, this widget can announce when it performs an action. Since this generic widget might be used in several different ways in the same plot, you can give each widget a custom event name to help tell the buttons apart.
        -  // This is totally optional- most sites will be fine just ignoring the event altogether!  
        -  custom_event_name: 'widget_gene_filter_choice',
        -  // Must specify the data layer id (within this panel) that will be controlled by the button
        -  layer_name: 'genes',
        -  default_config_display_name: 'Coding genes & rRNA',
        -  options: [
        -    // Specify how each item in the dropdown menu will work
        -    {
        -      display_name: 'All features',
        -      display: {
        -        filters: null,
        -      },
        -    },
        -  ],
        -}
        +
        const gene_selector_widget = {
        +  type: 'display_options',
        +  // Below: special config specific to this widget
        +  button_html: 'Filter...',
        +  button_title: 'Choose which genes to show',
        +  // If you are tracking website analytics, this widget can announce when it performs an action. Since this generic widget might be used in several different ways in the same plot, you can give each widget a custom event name to help tell the buttons apart.
        +  // This is totally optional- most sites will be fine just ignoring the event altogether!  
        +  custom_event_name: 'widget_gene_filter_choice',
        +  // Must specify the data layer id (within this panel) that will be controlled by the button
        +  layer_name: 'genes',
        +  default_config_display_name: 'Coding genes & rRNA',
        +  options: [
        +    // Specify how each item in the dropdown menu will work
        +    {
        +      display_name: 'All features',
        +      display: {
        +        filters: null,
        +      },
        +    },
        +  ],
        +}

        NOTE: The display options widget operates on a whitelist of layout directives: there are some things it cannot customize. This whitelist is expanded based on user requests. Rewriting (mutating) the entire layout is very powerful, and this gradual approach ensures that each new option is tested carefully before being added to a standard widget.

        Modify data retrieval via set_state

        Some data adapters alter how they fetch information based on variables in plot.state. For example, the LDServer can choose to fetch LD from a particular reference population.

        The set_state widget provides a way to set a particular variable (state_field ) to the provided value. When an option is clicked, it will trigger a re-render, including any updated data.

        -
        const ldlz2_pop_selector_menu = {
        -  // **Note**: this widget is aimed at the LDServer datasource, and the UM 1000G LDServer
        -  type: 'set_state',
        -  button_html: 'LD Population: ',
        -  show_selected: true,
        -  button_title: 'Select LD Population: ',
        -  state_field: 'ld_pop',
        -  // This list below is hardcoded to work with the UMich LDServer, default 1000G populations
        -  //  It can be customized to work with other LD servers that specify population differently
        -  // https://portaldev.sph.umich.edu/ld/genome_builds/GRCh37/references/1000G/populations
        -  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' },
        -  ],
        -};
        +
        const ldlz2_pop_selector_menu = {
        +  // **Note**: this widget is aimed at the LDServer datasource, and the UM 1000G LDServer
        +  type: 'set_state',
        +  button_html: 'LD Population: ',
        +  show_selected: true,
        +  button_title: 'Select LD Population: ',
        +  state_field: 'ld_pop',
        +  // This list below is hardcoded to work with the UMich LDServer, default 1000G populations
        +  //  It can be customized to work with other LD servers that specify population differently
        +  // https://portaldev.sph.umich.edu/ld/genome_builds/GRCh37/references/1000G/populations
        +  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' },
        +  ],
        +};

        Control what is shown with filter_field

        Sometimes, a region plot has a lot of information, and the user wants to restrict what is shown. This can be helpful in coaccessibility tracks, for example, which have a very large number of loops.

        This widget appears as a text box in panel toolbars. Options allow control over a specific filter,

        -
        {
        -  type: 'filter_field',
        -  // Must specify the data layer id relative to the panel in which this widget appears
        -  layer_name: 'coaccessibility',
        -  field: '{{namespace[access]}}score',
        -  field_display_html: 'Score',
        -  operator: '>=',
        -  // Optionally, the value entered into the text box can be coerced into a number.
        -  data_type: 'number',
        -}
        +
        {
        +  type: 'filter_field',
        +  // Must specify the data layer id relative to the panel in which this widget appears
        +  layer_name: 'coaccessibility',
        +  field: '{{namespace[access]}}score',
        +  field_display_html: 'Score',
        +  operator: '>=',
        +  // Optionally, the value entered into the text box can be coerced into a number.
        +  data_type: 'number',
        +}

        Extensions

        A major feature of LocusZoom is the ability to update the plot in response to user events. When a user finds an interesting view, they often wish to share that exact region with colleagues.

        We provide an optional LocusZoom extension to help with this. It can be added via a script tag (dist/ext/lz-dynamic-urls.min.js)

        The plot region will appear in the URL as query parameters. For example, https://statgen.github.io/locuszoom/?chrom=10&start=114550452&end=115067678

        -
        ////// Before creating the plot, check the URL to see if a specific viewing region has requested. If so, make that the default when the plot is first rendered.
        -
        -// The web site owner has control over how their URL looks. Here, the parameter "chr" appears in the URL as "chrom". Any top-level parameter in plot.state can be serialized into the URL. LocusZoom will only try to manage the parameters named here.
        -var stateUrlMapping = {chr: "chrom", start: "start", end: "end"};
        -var initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping);
        -if (!Object.keys(initialState).length) {
        -    initialState = {chr: 10, start: 114550452, end: 115067678};
        -}
        -// Draw the plot, providing the desired region to draw
        -const layout = LocusZoom.Layouts.get("plot", "standard_association", {state: initialState});
        -window.plot = LocusZoom.populate("#lz-plot", data_sources, layout);
        -
        -// Set up event listeners: Changes in the plot can be reflected in the URL, and vice versa (eg browser back button can go back to
        -//   a previously viewed region)
        -LzDynamicUrls.plotUpdatesUrl(plot, stateUrlMapping);
        -LzDynamicUrls.plotWatchesUrl(plot, stateUrlMapping);
        +
        ////// Before creating the plot, check the URL to see if a specific viewing region has requested. If so, make that the default when the plot is first rendered.
        +
        +// The web site owner has control over how their URL looks. Here, the parameter "chr" appears in the URL as "chrom". Any top-level parameter in plot.state can be serialized into the URL. LocusZoom will only try to manage the parameters named here.
        +var stateUrlMapping = {chr: "chrom", start: "start", end: "end"};
        +var initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping);
        +if (!Object.keys(initialState).length) {
        +    initialState = {chr: 10, start: 114550452, end: 115067678};
        +}
        +// Draw the plot, providing the desired region to draw
        +const layout = LocusZoom.Layouts.get("plot", "standard_association", {state: initialState});
        +window.plot = LocusZoom.populate("#lz-plot", data_sources, layout);
        +
        +// Set up event listeners: Changes in the plot can be reflected in the URL, and vice versa (eg browser back button can go back to
        +//   a previously viewed region)
        +LzDynamicUrls.plotUpdatesUrl(plot, stateUrlMapping);
        +LzDynamicUrls.plotWatchesUrl(plot, stateUrlMapping);

        Note: If your web site is a single page application (like vue-router), then another piece of javascript may already be controlling the page URL. DynamicUrls is mainly intended for web sites where the server returns the HTML for each page.

        diff --git a/docs/guides/rendering_layouts.html b/docs/guides/rendering_layouts.html index 57bce8ae..085a6c25 100644 --- a/docs/guides/rendering_layouts.html +++ b/docs/guides/rendering_layouts.html @@ -106,7 +106,6 @@

        Table of Contents

      • Working with the Registry
      • Nested rule example: scalable parameters
      • @@ -118,7 +117,6 @@

        Table of Contents

      • Layouts also control behavior
      • Where to find more information
      • @@ -161,10 +159,10 @@

        How to read a layout

        responsive_resize: true, min_region_scale: 20000, max_region_scale: 1000000, - dashboard: LocusZoom.Layouts.get('dashboard', 'standard_plot', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar_widgets', 'standard_plot'), panels: [ - LocusZoom.Layouts.get('panel', 'association', { unnamespaced: true, height: 225 }), - LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true, height: 225 }) + LocusZoom.Layouts.get('panel', 'association', { height: 225 }), + LocusZoom.Layouts.get('panel', 'genes', { height: 225 }) ] });

    In this view, we have abstracted away all the details of what is plotted, and we can just see the basic pieces: this plot has two panels (association data and genes data) that are displayed separately on the same screen. At the plot level, each panel is 225px high, so the total plot height will be the sum of panels (450 px); if more panels are added, the plot height will increase to match. The actual details of what to render are defined as nested layouts (association and genes panels), and the registry also contains predefined options for each of these smaller pieces- LocusZoom.Layouts.get(...) returns a JSON object.

    @@ -176,102 +174,69 @@

    Will this layout work with my data?<
    LocusZoom.Layouts.add('data_layer', 'association_pvalues', {
         namespace: { 'assoc': 'assoc', 'ld': 'ld' },
         type: 'scatter',
    -    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',
    -    x_axis: {
    -        field: '{{namespace[assoc]}}position'
    -    }
    -});
    + id_field: 'assoc:variant', + x_axis: { + field: 'assoc:position' + } +});

    Key things to notice are:

      -
    1. The data layer will only see the fields requested by name. Even if a field is present in the API payload, it will not be visible in the data layer unless explicitly referenced in the fields array for that data layer.
    2. -
    3. This layout is generic: the use of namespaces means “given association data from somewhere”. See “using namespaces” below for more details on how to use an abstract layout with a specific dataset (via namespaces).
    4. -
    5. Other sections of the layout (such as x_axis) can reference the fields requested, using the same syntax. But the field must always be requested in the fields array.
    6. +
    7. The data layer will see all of the fields provided by the relevant data sources/adapters. Each field will be prefixed by the “local namespace” for that data (eg if both assoc and ld provide a field called id, both will be present and distinct in the joined data: assoc:id and ld:id)
    8. +
    9. This layout is generic: the use of namespaces means “given association data from somewhere”. See “using namespaces” below.
    10. +
    11. Other sections of the layout (such as x_axis) can reference the fields requested, using the same syntax.
    -

    You will sometimes see fields referenced elsewhere with an additional syntax, like {{namespace[assoc]}}variant|htmlescape. The |htmlescape is a transform that affects value display. The fields array only needs to specify the names of fields; transforms can be applied at any time later.

    -

    No system of notation survives contact with developers

    -

    There are some exceptions to this rule- it is difficult to support every possible combination of data sources from every possible set of API conventions.

    -

    One place where this breaks down is dependent sources- eg, LD information is requested relative to the most significant variant in the association data. Differences in field formatting or nomenclature can sometimes break the ability to find the relevant information that the second data source requires; efforts are made to handle common use cases. These sources gradually become more generic over time based on user feedback and needs.

    -

    The other main exception to the fields mechanism involves API endpoints that return complex nested objects (eg the list of genes in a region, a standard dataset that few people will ever need to customize directly). By notation convention, the default LocusZoom layouts will indicate that special behavior is in effect via a dummy field called all, eg

    -
    { 
    -  fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'] 
    -}
    -
    -

    Explanation: a data layer will not fetch from a source unless the fields array references at least one piece of data from that source. Since the genes source contains special code to bypass fetching explicit fields, the data layer uses a dummy field to trigger the request.

    -
    -

    Most standard data types use the system of exact field names. A more detailed guide is beyond the scope of this tutorial; this behavior is governed by the extractFields method of BaseAdapter. (see: guide to working with data)

    +

    You will sometimes see fields referenced elsewhere with an additional syntax, like assoc:variant|htmlescape. The |htmlescape is a transform that affects value display. Transforms can be applied anywhere that a field value is used.

    +

    Every data layer in the registry will contain an automatically-defined property called _auto_fields, describing the names of all fields expected by this layout object. This is a quick guide for a developer who wants to see a summary of what data is used.

    renameFields: resolving tiny differences in naming

    Sometimes, an existing layout is very close to the format of your data, but there are very small cosmetic differences. For example, your API might send a field variant_name instead of variant.

    In this case, a helper function is provided this will recursively rename every usage of a specified field name in a layout:

    -
    // For abstract layouts
    -layout = LocusZoom.Layouts.renameField(layout, '{{namespace[assoc]}}old_name', '{{namespace[assoc]}}new_name');
    -
    -// For concrete layouts
    -layout = LocusZoom.Layouts.renameField(layout, 'my_assoc:old_name', 'my_assoc:new_name');
    -
    -// To remove a transformation function that is no longer interesting. (must be done in a separate step; otherwise transforms will be preserved after the rename)
    -// The last argument (warn_transforms) suppresses the JS console message that tells you when a rename would affect a field that uses transforms. After all, in this case, that's sort of the point.
    -layout = LocusZoom.Layouts.renameField(layout, 'assoc:pvalue|neg_log10', 'assoc:pvalue', false);
    +
    // For abstract layouts
    +layout = LocusZoom.Layouts.renameField(layout, 'assoc:old_name', 'assoc:new_name');
    +
    +// For concrete layouts
    +layout = LocusZoom.Layouts.renameField(layout, 'my_assoc:old_name', 'my_assoc:new_name');
    +
    +// To remove a transformation function that is no longer interesting. (must be done in a separate step; otherwise transforms will be preserved after the rename)
    +// The last argument (warn_transforms) suppresses the JS console message that tells you when a rename would affect a field that uses transforms. After all, in this case, that's sort of the point.
    +layout = LocusZoom.Layouts.renameField(layout, 'assoc:pvalue|neg_log10', 'assoc:pvalue', false);

    NOTE: Sometimes, the differences in data/field names are more than cosmetic: for example, renaming pvalue|neg_log10 to log_pvalue|neg_log10 would not make sense. This helper method will attempt to warn you if template transformation functions are being used on the field you are changing, so that you can ensure that the resulting layouts uses your data in a way that fits the intended meaning.

    +
    +

    Over time, LocusZoom will become more stringent about what field names it expects to receive. As such, it may make more sense to rename certain fields from the server to match the layout (rather than renaming the layout to match the data). (the _annotateRecords method of a custom adapter can be used for this purpose) Most fields work either way; some, like log_pvalue, are a special case.

    +

    Working with the Registry

    Typically, LocusZoom layouts are loaded via the registry, a set of pre-made reusable layouts. The act of fetching a layout converts it from the abstract definition to one that works with a specific dataset.

    Since the registry just returns JSON-serializable objects, you could create a plot or panel configuration by hand. But this is often tedious, and using the registry will save you from writing many lines of boilerplate code.

    What pieces are available?

    To see the list of pre-defined layouts (as well as any custom ones you have created):

    -
    > LocusZoom.Layouts.list();
    -{plot: Array(4), panel: Array(7), data_layer: Array(9), dashboard: Array(4), dashboard_components: Array(1), tooltip: Array(5) }
    +
    > LocusZoom.Layouts.list();
    +{plot: Array(4), panel: Array(7), data_layer: Array(9), toolbar: Array(4), toolbar_widgets: Array(1), tooltip: Array(5) }

    This will return a top level representation of the available types, showing the available categories. Note that even data layers are composed of smaller building blocks. This lets you use individual parts of a representation (like association tooltips) without committing to the other design choices for a common piece (like the association layer).

    Asking for just the plots shows a list of specific options. Typically, we try to provide example pages that use (most) of the layouts that come with LocusZoom; see the example gallery to preview how these layouts would look.

    -
    > LocusZoom.Layouts.list('plot');
    -(4) ["standard_association", "association_catalog", "standard_phewas", "interval_association"]
    +
    > LocusZoom.Layouts.list('plot');
    +(4) ["standard_association", "association_catalog", "standard_phewas", "interval_association"]

    You may find that the example gallery performs additional customizations on a layout, so this can be a source of ideas. Typically, we try very hard to not make major changes in a layout that is widely in use. Any backwards-incompatible changes will usually be identified in the release notes.

    -

    Abstract vs concrete

    -

    When a layout is first loaded into the registry, it is defined to work in the abstract- given any data. This allows the same layout to be re-used on two different association datasets. The syntax used is {{namespace[assoc]}}variant, where namespaces are replaced by a specific datasource name later on.

    -
    LocusZoom.Layouts.add('data_layer', 'association_pvalues', { // Define a new datalayer
    -    namespace: { 'assoc': 'assoc', 'ld': 'ld' },  // Provides default namespaces, eg look for "assoc" data in a source called "assoc"
    -    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'],
    -});
    -

    It is the act of fetching the layout from the registry that turns it into a concrete one- “find the association data from a particular source”. There are three ways to fetch something, and each behaves in a unique way:

    -
      -
    1. Fetch an existing layout, and tell it where to find the required data. (the third argument, “modifications”, is given an explicit set of namespaces)

      -
      > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { namespace: { assoc: 'my_dataset_1' } } );
      -{
      -    fields: ["my_dataset_1:variant","my_dataset_1:position","my_dataset_1:log_pvalue","my_dataset_1:log_pvalue|logtoscinotation","my_dataset_1:ref_allele","ld:state","ld:isrefvar"]
      -}
    2. -
    3. Fetch an existing layout, and use the “default” data sources. If you follow the examples very closely (eg naming your data source “assoc” and “ld”), this will automatically find the right data.

      -
      > LocusZoom.Layouts.get('data_layer', 'association_pvalues');
      -{
      -    fields: ["assoc:variant", "assoc:position", "assoc:log_pvalue", "assoc:log_pvalue|logtoscinotation", "assoc:ref_allele", "ld:state", "ld:isrefvar"] 
      -}
    4. -
    5. Fetch an existing abstract layout for further modification, and keep it abstract. Note the special unnamespaced: true option, which causes the layout to be returned exactly as it appears in the registry (abstract). This option is used quite a lot in the LZ source code (Layouts.js), because it makes it easy to build a reusable abstract layout (like a panel) out of smaller reusable pieces (like datalayers).

      -
      > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { unnamespaced: true });
      -{
      -    namespace: { assoc: 'assoc', ld: 'ld' },
      -    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'],
      -}
    6. -

    Modifying all (or part) of a layout

    If you are building your own API aimed at use with LocusZoom, then the path of least resistance is to use the same field names as the pre-defined layouts.

    The most straightforward way to modify a layout is to pass just a few overrides. This works will for simple values (like strings), or keys of nested objects:

    Consider an association plot, where the only requested change is to use the right side y-axis (2) instead of the left side y-axis (1, the default). This can be accomplished by adding a key to the third argument of LocusZoom.Layouts.get(...). Note how the other existing options are preserved.

    -
    > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { namespace: { assoc: 'my_dataset_1' }, y_axis: { axis: 2 } } );
    -{ 
    -  y_axis: { axis: 2, field: "my_dataset_1:log_pvalue", floor: 0, upper_buffer: 0.1, min_extent: [0, 10] }
    -}
    +
    > LocusZoom.Layouts.get('data_layer', 'association_pvalues', { namespace: { assoc: 'my_dataset_1' }, y_axis: { axis: 2 } } );
    +{ 
    +  y_axis: { axis: 2, field: "my_dataset_1:log_pvalue", floor: 0, upper_buffer: 0.1, min_extent: [0, 10] }
    +}

    The “modifications” object does not work as well for compound values, like a list, because this behavior is not well defined: changing the 5th element of a list could mean replacement, removal, or minor additions to fields… etc. In practice, this is quite often relevant… because panels and data layers are specified as lists. (order matters)

    -

    For complex scenarios like adding toolbar buttons or overriding the panels/data layers in a plot, you can build your own layout using all or some of the pieces of the layouts registry. One trick that is commonly used in the LocusZoom.js source code is to modify just one part of an existing array field via self-calling functions that immediately return a new, modified object. (this creates the modifications in-place, without leaving any temporary variables around afterwards) Eg, for a toolbar (dashboard) that adds just one extra button to an existing layout:

    -
    {
    -    dashboard: (function () {
    -        var base = LocusZoom.Layouts.get('dashboard', 'standard_panel', { unnamespaced: true });
    -        base.components.push({
    -            type: 'toggle_legend',
    -            position: 'right'
    -        });
    -        return base;
    -    })() // Function calls itself immediately, so "dashboard" is set to the return value
    -}
    +

    For complex scenarios like adding toolbar buttons or overriding the panels/data layers in a plot, you can build your own layout using all or some of the pieces of the layouts registry. One trick that is commonly used in the LocusZoom.js source code is to modify just one part of an existing array field via self-calling functions that immediately return a new, modified object. (this creates the modifications in-place, without leaving any temporary variables around afterwards) Eg, for a toolbar that adds just one extra button to an existing layout:

    +
    {
    +    toolbar: (function () {
    +        var base = LocusZoom.Layouts.get('toolbar', 'standard_panel');
    +        base.widgets.push({
    +            type: 'toggle_legend',
    +            position: 'right'
    +        });
    +        return base;
    +    })() // Function calls itself immediately, so "toolbar" is set to the return value
    +}

    Currently, modifying every level of a deeply nested layout is not an ideal process. Although the above trick (combined with our efforts at backwards compatibility) makes the process possible without copying hundreds of lines of code, we are exploring other, more ergonomic ways to customize layouts in the future.

    TIP: When modifying one option from a list (like changing the label of a toolbar button), it is tempting to address it using simple JavaScript operations, like widgets[0].button_html += 'something'. However, this becomes very hard to read and maintain over time: if someone adds a new button to the start of the list, it will not be obvious that the meaning of button[0] has changed (or what the correct meaning should be). Try to use clear variable names like const display_options = button[0] to convey intent, and override the smallest reusable piece possible. Layouts are defined from the bottom up, not the top down!

    @@ -279,34 +244,34 @@

    Modifying all (or part) of a layoutNested rule example: scalable parameters

    Each key in a layout object corresponds to a set of options supported by the thing that the configuration is intended to control. For example, scatter plots provide simple options that obey exactly one rule (like what to show on the x-axis), but there are also scalable parameters like point_size and point_shape, in which case several rules can be tried in sequence until the first non-null result is found.

    Consider the rules below: in a classic LocusZoom plot, points are colored by LD information, or shown in grey if no LD information is available.

    -
    const data_layer = { 
    -    ...options,
    -    color: [
    -    {
    -        // Name of a function specified in `LocusZoom.ScaleFunctions`
    -        scale_function: 'if',
    -        // The field whose value will be passed to the scale function
    -        field: '{{namespace[ld]}}isrefvar',
    -        // Options that will be passed to the scale function; see documentation for available options
    -        parameters: {
    -            field_value: 1,
    -            then: '#9632b8',
    -        },
    -    },
    -    {
    -        scale_function: 'numerical_bin',
    -        field: '{{namespace[ld]}}state',
    -        parameters: {
    -            breaks: [0, 0.2, 0.4, 0.6, 0.8],
    -            values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'],
    -        },
    -    },
    -    '#B8B8B8',
    -]
    -}
    +
    const data_layer = { 
    +    ...options,
    +    color: [
    +    {
    +        // Name of a function specified in `LocusZoom.ScaleFunctions`
    +        scale_function: 'if',
    +        // The field whose value will be passed to the scale function
    +        field: 'lz_is_ld_refvar',
    +        // Options that will be passed to the scale function; see documentation for available options
    +        parameters: {
    +            field_value: 1,
    +            then: '#9632b8',
    +        },
    +    },
    +    {
    +        scale_function: 'numerical_bin',
    +        field: 'ld:correlation',
    +        parameters: {
    +            breaks: [0, 0.2, 0.4, 0.6, 0.8],
    +            values: ['#357ebd', '#46b8da', '#5cb85c', '#eea236', '#d43f3a'],
    +        },
    +    },
    +    '#B8B8B8',
    +]
    +}

    Common scalable parameters include point size, color, and shape. The full developer documentation marks which parameters are scalable for each data layer rendering type, and describes the options that can be used with each scaling function rule.

    Custom scaling functions may be defined as follows:

    -
    LocusZoom.ScaleFunctions.add('myfunction', (parameters, field_value) => calculated_result_or_null); 
    +
    LocusZoom.ScaleFunctions.add('myfunction', (parameters, field_value) => calculated_result_or_null); 

    Documentation by example

    Composition of smaller pieces is a powerful strategy- but it also means that no single documentation page can explain every feature (because important behavior emerges when two building blocks are combined). As such, examples are a key and explicit part of how LocusZoom usage is documented.

    We encourage you to look at the builtin layouts (via the JS console, or source code) as a guide to “what works”, and the example gallery (with example code) to see what options look like in practice. The full developer documentation enumerates every possible layout configuration option for each plot, panel, data layer rendering type, or rule.

    @@ -318,74 +283,48 @@

    Plotting more than one study

    Using namespaces

    A namespaced layout (usually for panels and below) is one that identifies where to find the relevant data. Due to how separation of concerns works, this requires coordination between the data sources (content) and the layout (presentation).

    Consider the following example, which plots two association studies and a genes track:

    -
    // Other standard sources (genes, LD) omitted for clarity
    -data_sources
    -  .add("assoc_study1", ["AssociationLZ", {url: "/api/association/", params: { source: 1 }}])
    -  .add("assoc_study2", ["AssociationLZ", {url: "/api/association/", params: { source: 2 }}]);
    -
    // This outer call to Layouts.get() will ensure that namespaces are applied, and the returned result is a concrete 
    -//   layout ready for use in drawing a plot with specific data sets. 
    -const plot_layout = LocusZoom.Layouts.get('plot', 'standard_association', { // Override select fields of a pre-made layout 
    -    responsive_resize: true,
    -    panels: [
    -        LocusZoom.Layouts.get('panel', 'association', {
    -            namespace: { assoc: 'assoc_study1' }, // This is the key piece. It says "for this panel, and its child data layers, look for the association data in a datasource called "assoc_study1".
    -            height: 400,
    -            id: 'assoc_study1', // Give each panel a unique ID
    -            title: { text: 'Study 1' },
    -        }),
    -        LocusZoom.Layouts.get('panel', 'association', {
    -            namespace: { assoc: 'assoc_study2' },
    -            height: 400,
    -            id: 'assoc_study2',
    -            title: { text: 'Study 2' },
    -        }),
    -        // Even though genes are part of the original "standard association plot" layout, overriding the panels array means replacing *all* of the panels.
    -        LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true, height: 400 })  // "unnamespaced" when using as a generic building block
    -    ]
    -});
    -

    Namespaces are not only external- they propagate through to how the layer actually sees its data internally. The field names inside the layer are a composite of sourcename:fieldname. For example, this allows the same data layer to work with two pieces of information (like summary stats and LD) even if both API endpoints provide a common field name like id. Namespacing ensures that duplicate field names do not collide.

    -

    From the example above, the second panel (which fetches association data from assoc_study2) converts a “generic” specification like {{namespace[assoc]}}variant into a “concrete” use of one dataset: assoc_study2:variant.

    -
    > var layer_data = Object.keys(plot.panels['assoc_study2'].data_layers['associationpvalues'].data);
    -Object.keys(layer_data[0]); // See the field names used by the data for a single point
    -["assoc_study2:variant", "assoc_study2:position", "assoc_study2:log_pvalue", "assoc_study2:log_pvalue|logtoscinotation", "assoc_study2:ref_allele", "ld:state", "ld:isrefvar"]
    +
    // Other standard sources (genes, LD) omitted for clarity
    +data_sources
    +  .add("assoc_study1", ["AssociationLZ", {url: "/api/association/", source: 1 }])
    +  .add("assoc_study2", ["AssociationLZ", {url: "/api/association/", source: 2 }])
    +  .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]);
    +
    // This outer call to Layouts.get() will ensure that namespaces are applied, and the returned result is a concrete 
    +//   layout ready for use in drawing a plot with specific data sets. 
    +const plot_layout = LocusZoom.Layouts.get('plot', 'standard_association', { // Override select fields of a pre-made layout 
    +    responsive_resize: true,
    +    panels: [
    +        LocusZoom.Layouts.get('panel', 'association', {
    +            namespace: { assoc: 'assoc_study1' }, // This is the key piece. It says "for this panel, and its child data layers, look for the association data in a datasource called "assoc_study1".
    +            height: 400,
    +            id: 'assoc_study1', // Give each panel a unique ID
    +            title: { text: 'Study 1' },
    +        }),
    +        LocusZoom.Layouts.get('panel', 'association', {
    +            namespace: { assoc: 'assoc_study2' },
    +            height: 400,
    +            id: 'assoc_study2',
    +            title: { text: 'Study 2' },
    +        }),
    +        // Even though genes are part of the original "standard association plot" layout, overriding the panels array means replacing *all* of the panels.
    +        LocusZoom.Layouts.get('panel', 'genes', { height: 400 })  // The layout provides a built-in default: "look for gene data in an adapter called gene". In this example, the default matches what sources were defined, so we don't need to override it.
    +    ]
    +});
    +

    Namespaces are the only thing that needs to be changed in order to use a layout with a different source of data. Internally, things are referred to via the “local” name. Eg given { assoc: 'assoc_study2' }, individual fields would be referenced as assoc:some_field, no matter where the data actually came from.

    Adding panels

    The above example demonstrates how to add multiple studies at the time of plot creation. However, sites like the T2D Portal have many datasets, and it can be helpful to let the user interactively choose which other panels to show after first render. New panels can be added dynamically! When doing so, the plot will grow to accommodate the new panel.

    -
    // This creates a new configuration object
    -var extra_panel_layout = LocusZoom.Layouts.get('panel', 'association', {
    -    namespace: { assoc: 'assoc_study3' },
    -    id: 'assoc_study3',
    -    title: { text: 'Study 3' },
    -    y_index: -1 // Special option used by addPanel: inserts this study right before the genes track
    -});
    -
    -// Must add both data sources and panels
    -existing_datasources
    -  .add("assoc_study3", ["AssociationLZ", {url: "/api/association/", params: { source: 3 }}]);
    -
    -const new_panel = existing_plot.addPanel(extra_panel_layout); // Adds the panel and redraws plot
    -

    Common issues

    -

    One of the most common issues in working with namespaced layouts is the difference between abstract and concrete layouts. For example, imagine if the page contained a button to toggle the display of labels on the plot. This button might work by changing the plot layout options, then triggering a re-render.

    -

    Here is how label options would be specified when defining a layout in the registry (abstract), so that labels were present on the very first re-render for any dataset that used this layout. Note that it identifies the key fields using a generic namespace reference:

    -
    const generic_layout_with_special_labels = {
    -    // Other data layer fields omitted for clarity
    -    label: {
    -        text: '{{{{namespace[assoc]}}variant|htmlescape}}',
    -        filters: [ // Only label points if they are above significance threshold
    -            { field: '{{namespace[assoc]}}log_pvalue',  operator: '>', value: 7.301 },
    -        ],
    -        spacing: 6,
    -    }
    -};
    -

    However, once the final layout has been created and used to draw the plot, mutating the layout would require the actual field name (with namespace applied), specific to the panel being changed:

    -
    plot.panels['assoc_study2'].data_layers['associationpvalues'].layout.label = {
    -    text: '{{assoc_study2:variant|htmlescape}}', // Extra outer curly braces around name = Value of field
    -    filters: [ // Only label points if they are above significance threshold
    -        { field: 'assoc_study2:log_pvalue',  operator: '>', value: 7.301 }, // No curly braces: specifies name of field
    -    ],
    -    spacing: 6,
    -};
    -plot.applyState(); // to re-render with labels
    -

    When you are not sure what notation convention to use, check the rest of your layout- the JS console is a very powerful tool, and development is much easier when you can introspect the actual behavior of your code.

    +
    // This creates a new configuration object
    +var extra_panel_layout = LocusZoom.Layouts.get('panel', 'association', {
    +    namespace: { assoc: 'assoc_study3' },
    +    id: 'assoc_study3',
    +    title: { text: 'Study 3' },
    +    y_index: -1 // Special option used by addPanel: inserts this study right before the genes track
    +});
    +
    +// Must add both data sources and panels
    +existing_datasources
    +  .add("assoc_study3", ["AssociationLZ", {url: "/api/association/", source: 3 }]);
    +
    +const new_panel = existing_plot.addPanel(extra_panel_layout); // Adds the panel and redraws plot

    Layouts also control behavior

    In this guide, we have mostly focused on Layouts as a tool for controlling how data is rendered. However, layouts also provide configuration directives to enable powerful behaviors such as zooming, matching, and filtering. See the guide to interactivity for details.

    Where to find more information

    diff --git a/esm/components/data_layer/base.js b/esm/components/data_layer/base.js index 17ce02f6..15d3f334 100644 --- a/esm/components/data_layer/base.js +++ b/esm/components/data_layer/base.js @@ -13,7 +13,7 @@ import * as d3 from 'd3'; import {STATUSES} from '../constants'; import Field from '../../data/field'; import {parseFields} from '../../helpers/display'; -import {deepCopy, merge} from '../../helpers/layouts'; +import {deepCopy, findFields, merge} from '../../helpers/layouts'; import MATCHERS from '../../registry/matchers'; import SCALABLE from '../../registry/scalable'; @@ -52,12 +52,28 @@ import SCALABLE from '../../registry/scalable'; * @property value The target value to compare to */ +/** + * @typedef {object} DataOperation A synchronous function that modifies data returned from adapters, in order to clean up or reformat prior to plotting. + * @property {module:LocusZoom_DataFunctions|'fetch'} type + * @property {String[]} [from] For operations of type "fetch", this is required. By default, it will fill in any items provided in "namespace" (everything specified in namespace triggers an adapter/network request) + * A namespace should be manually specified in this array when there are dependencies (one request depends on the content of what is returned from another namespace). + * Eg, for ld to be fetched after association data, specify "ld(assoc)". Most LocusZoom examples fill in all items, in order to make the examples more clear. + * @property {String} [name] The name of this operation. This only needs to be specified if a data layer performs several operations, and needs to refer to the result of a prior operation. + * Eg, if the retrieved data is combined via several left joins in series: `name: "assoc_plus_ld"` -> feeds into `{name: "final", requires: ["assoc_plus_ld"]}` + * @property {String[]} requires The names of each adapter required. This does not need to specify dependencies, just + * the names of other namespaces (or data operations) whose results must be available before a join can be performed + * @property {String[]} params Any user-defined parameters that should be passed to the particular join function + * (see: {@link module:LocusZoom_DataFunctions} for details). For example, this could specify the left and right key fields for a join function, based on the expected field names used in this data layer: `params: ['assoc:position', 'ld:position2']` + * Separate from this section, data functions will also receive a copy of "plot.state" automatically. + */ + /** * @typedef {object} LegendItem * @property [shape] This is optional (e.g. a legend element could just be a textual label). * Supported values are the standard d3 3.x symbol types (i.e. "circle", "cross", "diamond", "square", - * "triangle-down", and "triangle-up"), as well as "rect" for an arbitrary square/rectangle or line for a path. + * "triangle-down", and "triangle-up"), as well as "rect" for an arbitrary square/rectangle or "line" for a path. + * A special "ribbon" option can be use to draw a series of explicit, numeric-only color stops (a row of colored squares, such as to indicate LD) * @property {string} color The point color (hexadecimal, rgb, etc) * @property {string} label The human-readable label of the legend item * @property {string} [class] The name of a CSS class used to style the point in the legend @@ -66,9 +82,12 @@ import SCALABLE from '../../registry/scalable'; * @property {number} [length] Length (in pixels) for the path rendered as the graphical portion of the legend element * if the value of the shape parameter is "line". * @property {number} [width] Width (in pixels) for the rect rendered as the graphical portion of the legend element if - * the value of the shape parameter is "rect". + * the value of the shape parameter is "rect" or "ribbon". * @property {number} [height] Height (in pixels) for the rect rendered as the graphical portion of the legend element if - * the value of the shape parameter is "rect". + * the value of the shape parameter is "rect" or "ribbon". + * @property {'vertical'|'horizontal'} [orientation='vertical'] For shape "ribbon", specifies whether to draw the ribbon vertically or horizontally. + * @property {Array} [tick_labels] For shape "ribbon", specifies the tick labels that correspond to each colorstop value. Tick labels appear at all box edges: this array should have 1 more item than the number of colorstops. + * @property {String[]} [color_stops] For shape "ribbon", specifies the colors of each box in the row of colored squares. There should be 1 fewer item in color_stops than the number of tick labels. * @property {object} style CSS styles object to be applied to the DOM element representing the graphical portion of * the legend element. */ @@ -78,13 +97,13 @@ import SCALABLE from '../../registry/scalable'; * A basic description of keys expected in all data layer layouts. Not intended to be directly used or modified by an end user. * @memberof module:LocusZoom_DataLayers~BaseDataLayer * @protected - * @type {{type: string, fields: Array, x_axis: {}, y_axis: {}}} */ const default_layout = { id: '', type: '', tag: 'custom_data_type', - fields: [], + namespace: {}, + data_operations: [], id_field: 'id', filters: null, match: {}, @@ -110,12 +129,19 @@ class BaseDataLayer { * layer that shows association scatter plots, anywhere": even if the IDs are different, the tag can be the same. * Most built-in data layers will contain a tag that describes, in human-readable terms, what kind of data is being shown. * (see: {@link LayoutRegistry.mutate_attrs}) - * @param {String[]} layout.fields A list of (namespaced) fields specifying what data is used by the layer. Only - * these fields will be made available to the data layer, and only data sources (namespaces) referred to in - * this array will be fetched. This represents the "contract" between what data is returned and what data is rendered. - * This fields array works in concert with the data retrieval method BaseAdapter.extractFields. * @param {string} [layout.id_field] The datum field used for unique element IDs when addressing DOM elements, mouse - * events, etc. This should be unique to the specified datum. + * events, etc. This should be unique to the specified datum, and persistent across re-renders (because it is + * used to identify where to draw tooltips, eg, if the plot is dragged or zoomed). If no single field uniquely + * identifies all items, a template expression can be used to create an ID from multiple fields instead. (it is + * your job to assure that all of the expected fields are present in every element) + * @param {object} layout.namespace A set of key value pairs representing how to map the local usage of data ("assoc") + * to the globally unique name for something defined in LocusZoom.DataSources. + * Namespaces allow a single layout to be reused to plot many tracks of the same type: "given some form of association data, plot it". + * These pairs take the form of { local_name: global_name }. (and all data layer layouts provide a default) In order to reuse + * a layout with a new provider of data- like plotting two association studies stacked together- + * only the namespace section of the layout needs to be overridden. + * Eg, `LocusZoom.Layouts.get('data_layers', 'association_pvalues', { namespace: { assoc: 'assoc_study_2' }})` + * @param {module:LocusZoom_DataLayers~DataOperation[]} layout.data_operations A set of data operations that will be performed on the data returned from the data adapters specified in `namespace`. (see: {@link module:LocusZoom_DataFunctions}) * @param {module:LocusZoom_DataLayers~FilterOption[]} [layout.filters] If present, restricts the list of data elements to be displayed. Typically, filters * hide elements, but arrange the layer so as to leave the space those elements would have occupied. The exact * details vary from one layer to the next. See the Interactivity Tutorial for details. @@ -167,12 +193,12 @@ class BaseDataLayer { * @private * @member {Boolean} */ - this.initialized = false; + this._initialized = false; /** * @private * @member {Number} */ - this.layout_idx = null; + this._layout_idx = null; /** * The unique identifier for this layer. Should be unique within this panel. @@ -257,13 +283,13 @@ class BaseDataLayer { * @private * @member {String} */ - this.state_id = null; + this._state_id = null; /** * @private * @member {Object} * */ - this.layer_state = null; + this._layer_state = null; // Create a default state (and set any references to the parent as appropriate) this._setDefaultState(); @@ -281,19 +307,25 @@ class BaseDataLayer { * @private * @member {Object} */ - this.tooltips = {}; + this._tooltips = {}; } // Initialize flags for tracking global statuses - this.global_statuses = { + this._global_statuses = { 'highlighted': false, 'selected': false, 'faded': false, 'hidden': false, }; + + // On first load, pre-parse the data specification once, so that it can be used for all other data retrieval + this._data_contract = new Set(); // List of all fields requested by the layout + this._entities = new Map(); + this._dependencies = []; + this.mutateLayout(); // Parse data spec and any other changes that need to reflect the layout } - /****** Public interface: methods for external manipulation */ + /****** Public interface: methods for manipulating the layer from other parts of LZ */ /** * @public @@ -308,9 +340,11 @@ class BaseDataLayer { * @returns {BaseDataLayer} */ moveForward() { - if (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; + const layer_order = this.parent._data_layer_ids_by_z_index; + const current_index = this.layout.z_index; + if (layer_order[current_index + 1]) { + layer_order[current_index] = layer_order[current_index + 1]; + layer_order[current_index + 1] = this.id; this.parent.resortDataLayers(); } return this; @@ -322,9 +356,11 @@ class BaseDataLayer { * @returns {BaseDataLayer} */ moveBack() { - if (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; + const layer_order = this.parent._data_layer_ids_by_z_index; + const current_index = this.layout.z_index; + if (layer_order[current_index - 1]) { + layer_order[current_index] = layer_order[current_index - 1]; + layer_order[current_index - 1] = this.id; this.parent.resortDataLayers(); } return this; @@ -345,10 +381,10 @@ class BaseDataLayer { */ setElementAnnotation (element, key, value) { const id = this.getElementId(element); - if (!this.layer_state.extra_fields[id]) { - this.layer_state.extra_fields[id] = {}; + if (!this._layer_state.extra_fields[id]) { + this._layer_state.extra_fields[id] = {}; } - this.layer_state.extra_fields[id][key] = value; + this._layer_state.extra_fields[id][key] = value; return this; } @@ -363,6 +399,23 @@ class BaseDataLayer { this._filter_func = func; } + /** + * A list of operations that should be run when the layout is mutated + * Typically, these are things done once when a layout is first specified, that would not automatically + * update when the layout was changed. + * @public + */ + mutateLayout() { + // Are we fetching data from external providers? If so, validate that those API calls would meet the expected contract. + if (this.parent_plot) { // Don't run this method if instance isn't mounted to a plot, eg unit tests that don't require requester + const { namespace, data_operations } = this.layout; + this._data_contract = findFields(this.layout, Object.keys(namespace)); + const [entities, dependencies] = this.parent_plot.lzd.config_to_sources(namespace, data_operations, this); + this._entities = entities; + this._dependencies = dependencies; + } + } + /********** Protected methods: useful in subclasses to manipulate data layer behaviors */ /** * Implementation hook for fetching the min and max values of available data. Used to determine axis range, if no other @@ -386,8 +439,12 @@ class BaseDataLayer { /** * Fetch the fully qualified ID to be associated with a specific visual element, based on the data to which that * element is bound. In general this element ID will be unique, allowing it to be addressed directly via selectors. + * + * The ID should also be stable across re-renders, so that tooltips and highlights may be reapplied to that + * element as we switch regions or drag left/right. If the element is not unique along a single field (eg PheWAS data), + * a unique ID can be generated via a template expression like `{{phewas:pheno}}-{{phewas:trait_label}}` * @protected - * @param {Object} element + * @param {Object} element The data associated with a particular element * @returns {String} */ getElementId (element) { @@ -397,11 +454,19 @@ class BaseDataLayer { return element[id_key]; } - const id_field = this.layout.id_field || 'id'; - if (typeof element[id_field] == 'undefined') { + // Two ways to get element ID: field can specify an exact field name, or, we can parse a template expression + const id_field = this.layout.id_field; + let value = element[id_field]; + if (typeof value === 'undefined' && /{{[^{}]*}}/.test(id_field)) { + // No field value was found directly, but if it looks like a template expression, next, try parsing that + // WARNING: In this mode, it doesn't validate that all requested fields from the template are present. Only use this if you trust the data being given to the plot! + value = parseFields(id_field, element, {}); // Not allowed to use annotations b/c IDs should be stable, and annos may be transient + } + if (value === null || value === undefined) { + // Neither exact field nor template options produced an ID throw new Error('Unable to generate element ID'); } - const element_id = element[id_field].toString().replace(/\W/g, ''); + const element_id = value.toString().replace(/\W/g, ''); // Cache ID value for future calls const key = (`${this.getBaseId()}-${element_id}`).replace(/([:.[\],])/g, '_'); @@ -410,11 +475,11 @@ class BaseDataLayer { } /** + * Abstract method. It should be overridden by data layers that implement separate status + * nodes, such as genes or intervals. * Fetch an ID that may bind a data element to a separate visual node for displaying status - * Examples of this might be separate visual nodes to show select/highlight statuses, or - * even a common/shared node to show status across many elements in a set. - * Abstract method. It should be overridden by data layers that implement seperate status - * nodes specifically to the use case of the data layer type. + * Examples of this might be highlighting a gene with a surrounding box to show select/highlight statuses, or + * a group of unrelated intervals (all markings grouped within a category). * @private * @param {String|Object} element * @returns {String|null} @@ -457,23 +522,39 @@ class BaseDataLayer { const broadcast_value = this.parent_plot.state.lz_match_value; // Match functions are allowed to use transform syntax on field values, but not (yet) UI "annotations" const field_resolver = field_to_match ? new Field(field_to_match) : null; + + // Does the data from the API satisfy the list of fields expected by this layout? + // Not every record will have every possible field (example: left joins like assoc + ld). The check is "did + // we see this field at least once in any record at all". + if (this.data.length && this._data_contract.size) { + const fields_unseen = new Set(this._data_contract); + for (let record of this.data) { + Object.keys(record).forEach((field) => fields_unseen.delete(field)); + if (!fields_unseen.size) { + // Once every requested field has been seen in at least one record, no need to look at more records + break; + } + } + if (fields_unseen.size) { + // Current implementation is a soft warning, so that certain "incremental enhancement" features + // (like rsIDs in tooltips) can fail gracefully if the API does not provide the requested info. + // Template syntax like `{{#if fieldname}}` means that throwing an Error is not always the right answer for missing data. + console.debug(`Data layer '${this.getBaseId()}' did not receive all expected fields from retrieved data. Missing fields are: ${[...fields_unseen]} + Common reasons for this error include API payloads with missing fields, or data layer layouts that use two kinds of data and need join logic in "data_operations" + If this field is optional, you can safely ignore this message. Examples include {{#if value}} tags or conditional color rules. +`); + } + } + this.data.forEach((item, i) => { // Basic toHTML() method - return the stringified value in the id_field, if defined. // When this layer receives data, mark whether points match (via a synthetic boolean field) // Any field-based layout directives (color, size, shape) can then be used to control display if (field_to_match && broadcast_value !== null && broadcast_value !== undefined) { - item.lz_is_match = (match_function(field_resolver.resolve(item), broadcast_value)); + item.lz_is_match = match_function(field_resolver.resolve(item), broadcast_value); } - item.toHTML = () => { - const id_field = this.layout.id_field || 'id'; - let html = ''; - if (item[id_field]) { - html = item[id_field].toString(); - } - return html; - }; // Helper methods - return a reference to various plot levels. Useful for interactive tooltips. item.getDataLayer = () => this; item.getPanel = () => this.parent || null; @@ -482,11 +563,6 @@ class BaseDataLayer { const panel = this.parent; return panel ? panel.parent : null; }; - // deselect() method - shortcut method to deselect the element - item.deselect = () => { - const data_layer = this.getDataLayer(); - data_layer.unselectElement(this); // dynamically generated method name. It exists, honest. - }; }); this.applyCustomDataMethods(); return this; @@ -559,7 +635,6 @@ class BaseDataLayer { * @param {('x'|'y')} dimension */ getAxisExtent (dimension) { - if (!['x', 'y'].includes(dimension)) { throw new Error('Invalid dimension identifier'); } @@ -619,7 +694,6 @@ class BaseDataLayer { // No conditions met for generating a valid extent, return an empty array return []; - } /** @@ -838,7 +912,7 @@ class BaseDataLayer { */ getElementAnnotation (element, key) { const id = this.getElementId(element); - const extra = this.layer_state.extra_fields[id]; + const extra = this._layer_state.extra_fields[id]; return key ? (extra && extra[key]) : extra; } @@ -877,8 +951,8 @@ class BaseDataLayer { // Each datalayer tracks two kinds of status: flags for internal state (highlighted, selected, tooltip), // and "extra fields" (annotations like "show a tooltip" that are not determined by the server, but need to // persist across re-render) - const layer_state = { status_flags: {}, extra_fields: {} }; - const status_flags = layer_state.status_flags; + const _layer_state = { status_flags: {}, extra_fields: {} }; + const status_flags = _layer_state.status_flags; STATUSES.adjectives.forEach((status) => { status_flags[status] = status_flags[status] || new Set(); }); @@ -887,11 +961,11 @@ class BaseDataLayer { if (this.parent) { // If layer has a parent, store a reference in the overarching plot.state object - this.state_id = `${this.parent.id}.${this.id}`; + this._state_id = `${this.parent.id}.${this.id}`; this.state = this.parent.state; - this.state[this.state_id] = layer_state; + this.state[this._state_id] = _layer_state; } - this.layer_state = layer_state; + this._layer_state = _layer_state; } /** @@ -963,18 +1037,18 @@ class BaseDataLayer { throw new Error(`DataLayer [${this.id}] layout does not define a tooltip`); } const id = this.getElementId(data); - if (this.tooltips[id]) { + if (this._tooltips[id]) { this.positionTooltip(id); return; } - this.tooltips[id] = { + this._tooltips[id] = { data: data, arrow: null, selector: d3.select(this.parent_plot.svg.node().parentNode).append('div') .attr('class', 'lz-data_layer-tooltip') .attr('id', `${id}-tooltip`), }; - this.layer_state.status_flags['has_tooltip'].add(id); + this._layer_state.status_flags['has_tooltip'].add(id); this.updateTooltip(data); return this; } @@ -991,16 +1065,16 @@ class BaseDataLayer { id = this.getElementId(d); } // Empty the tooltip of all HTML (including its arrow!) - this.tooltips[id].selector.html(''); - this.tooltips[id].arrow = null; + this._tooltips[id].selector.html(''); + this._tooltips[id].arrow = null; // Set the new HTML if (this.layout.tooltip.html) { - this.tooltips[id].selector.html(parseFields(this.layout.tooltip.html, d, this.getElementAnnotation(d))); + this._tooltips[id].selector.html(parseFields(this.layout.tooltip.html, d, this.getElementAnnotation(d))); } // If the layout allows tool tips on this data layer to be closable then add the close button // and add padding to the tooltip to accommodate it if (this.layout.tooltip.closable) { - this.tooltips[id].selector.insert('button', ':first-child') + this._tooltips[id].selector.insert('button', ':first-child') .attr('class', 'lz-tooltip-close-button') .attr('title', 'Close') .text('×') @@ -1009,7 +1083,7 @@ class BaseDataLayer { }); } // Apply data directly to the tool tip for easier retrieval by custom UI elements inside the tool tip - this.tooltips[id].selector.data([d]); + this._tooltips[id].selector.data([d]); // Reposition and draw a new arrow this.positionTooltip(id); return this; @@ -1031,15 +1105,15 @@ class BaseDataLayer { } else { id = this.getElementId(element_or_id); } - if (this.tooltips[id]) { - if (typeof this.tooltips[id].selector == 'object') { - this.tooltips[id].selector.remove(); + if (this._tooltips[id]) { + if (typeof this._tooltips[id].selector == 'object') { + this._tooltips[id].selector.remove(); } - delete this.tooltips[id]; + delete this._tooltips[id]; } // When a tooltip is removed, also remove the reference from the state if (!temporary) { - const tooltip_state = this.layer_state.status_flags['has_tooltip']; + const tooltip_state = this._layer_state.status_flags['has_tooltip']; tooltip_state.delete(id); } return this; @@ -1052,7 +1126,7 @@ class BaseDataLayer { * @returns {BaseDataLayer} */ destroyAllTooltips(temporary = true) { - for (let id in this.tooltips) { + for (let id in this._tooltips) { this.destroyTooltip(id, temporary); } return this; @@ -1073,10 +1147,10 @@ class BaseDataLayer { if (typeof id != 'string') { throw new Error('Unable to position tooltip: id is not a string'); } - if (!this.tooltips[id]) { + if (!this._tooltips[id]) { throw new Error('Unable to position tooltip: id does not point to a valid tooltip'); } - const tooltip = this.tooltips[id]; + const tooltip = this._tooltips[id]; const coords = this._getTooltipPosition(tooltip); if (!coords) { @@ -1095,7 +1169,7 @@ class BaseDataLayer { * @returns {BaseDataLayer} */ positionAllTooltips() { - for (let id in this.tooltips) { + for (let id in this._tooltips) { this.positionTooltip(id); } return this; @@ -1111,7 +1185,8 @@ class BaseDataLayer { * @returns {BaseDataLayer} */ showOrHideTooltip(element, first_time) { - if (typeof this.layout.tooltip != 'object') { + const tooltip_layout = this.layout.tooltip; + if (typeof tooltip_layout != 'object') { return this; } const id = this.getElementId(element); @@ -1162,25 +1237,25 @@ class BaseDataLayer { }; let show_directive = {}; - if (typeof this.layout.tooltip.show == 'string') { - show_directive = { and: [ this.layout.tooltip.show ] }; - } else if (typeof this.layout.tooltip.show == 'object') { - show_directive = this.layout.tooltip.show; + if (typeof tooltip_layout.show == 'string') { + show_directive = { and: [ tooltip_layout.show ] }; + } else if (typeof tooltip_layout.show == 'object') { + show_directive = tooltip_layout.show; } let hide_directive = {}; - if (typeof this.layout.tooltip.hide == 'string') { - hide_directive = { and: [ this.layout.tooltip.hide ] }; - } else if (typeof this.layout.tooltip.hide == 'object') { - hide_directive = this.layout.tooltip.hide; + if (typeof tooltip_layout.hide == 'string') { + hide_directive = { and: [ tooltip_layout.hide ] }; + } else if (typeof tooltip_layout.hide == 'object') { + hide_directive = tooltip_layout.hide; } // Find all the statuses that apply to just this single element - const layer_state = this.layer_state; + const _layer_state = this._layer_state; var status_flags = {}; // {status_name: bool} STATUSES.adjectives.forEach((status) => { const antistatus = `un${status}`; - status_flags[status] = (layer_state.status_flags[status].has(id)); + status_flags[status] = (_layer_state.status_flags[status].has(id)); status_flags[antistatus] = !status_flags[status]; }); @@ -1191,7 +1266,7 @@ class BaseDataLayer { // Most of the tooltip display logic depends on behavior layouts: was point (un)selected, (un)highlighted, etc. // But sometimes, a point is selected, and the user then closes the tooltip. If the panel is re-rendered for // some outside reason (like state change), we must track this in the create/destroy events as tooltip state. - const has_tooltip = (layer_state.status_flags['has_tooltip'].has(id)); + const has_tooltip = (_layer_state.status_flags['has_tooltip'].has(id)); const tooltip_was_closed = first_time ? false : !has_tooltip; if (show_resolved && !tooltip_was_closed && !hide_resolved) { this.createTooltip(element); @@ -1246,12 +1321,12 @@ class BaseDataLayer { } // Track element ID in the proper status state array - const added_status = !this.layer_state.status_flags[status].has(element_id); // On a re-render, existing statuses will be reapplied. + const added_status = !this._layer_state.status_flags[status].has(element_id); // On a re-render, existing statuses will be reapplied. if (active && added_status) { - this.layer_state.status_flags[status].add(element_id); + this._layer_state.status_flags[status].add(element_id); } if (!active && !added_status) { - this.layer_state.status_flags[status].delete(element_id); + this._layer_state.status_flags[status].delete(element_id); } // Trigger tool tip show/hide logic @@ -1274,7 +1349,7 @@ class BaseDataLayer { // The broadcast value can use transforms to "clean up value before sending broadcasting" 'match_requested', { value: new Field(value_to_broadcast).resolve(element), active: active }, - true + true, ); } return this; @@ -1294,7 +1369,7 @@ class BaseDataLayer { if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) { throw new Error('Invalid status'); } - if (typeof this.layer_state.status_flags[status] == 'undefined') { + if (typeof this._layer_state.status_flags[status] == 'undefined') { return this; } if (typeof toggle == 'undefined') { @@ -1305,18 +1380,18 @@ class BaseDataLayer { if (toggle) { this.data.forEach((element) => this.setElementStatus(status, element, true)); } else { - const status_ids = new Set(this.layer_state.status_flags[status]); // copy so that we don't mutate while iterating + const status_ids = new Set(this._layer_state.status_flags[status]); // copy so that we don't mutate while iterating status_ids.forEach((id) => { const element = this.getElementById(id); if (typeof element == 'object' && element !== null) { this.setElementStatus(status, element, false); } }); - this.layer_state.status_flags[status] = new Set(); + this._layer_state.status_flags[status] = new Set(); } // Update global status flag - this.global_statuses[status] = toggle; + this._global_statuses[status] = toggle; return this; } @@ -1395,7 +1470,7 @@ class BaseDataLayer { // Toggle a status case 'toggle': - var current_status_boolean = (self.layer_state.status_flags[behavior.status].has(self.getElementId(element))); + var current_status_boolean = (self._layer_state.status_flags[behavior.status].has(self.getElementId(element))); var exclusive = behavior.exclusive && !current_status_boolean; self.setElementStatus(behavior.status, element, !current_status_boolean, exclusive); @@ -1442,7 +1517,7 @@ class BaseDataLayer { * @private */ applyAllElementStatus () { - const status_flags = this.layer_state.status_flags; + const status_flags = this._layer_state.status_flags; const self = this; for (let property in status_flags) { if (!Object.prototype.hasOwnProperty.call(status_flags, property)) { @@ -1452,7 +1527,7 @@ class BaseDataLayer { try { this.setElementStatus(property, this.getElementById(element_id), true); } catch (e) { - console.warn(`Unable to apply state: ${self.state_id}, ${property}`); + console.warn(`Unable to apply state: ${self._state_id}, ${property}`); console.error(e); } }); @@ -1488,11 +1563,17 @@ class BaseDataLayer { // and then recreated if returning to visibility // Fetch new data. Datalayers are only given access to the final consolidated data from the chain (not headers or raw payloads) - return this.parent_plot.lzd.getData(this.state, this.layout.fields) + return this.parent_plot.lzd.getData(this.state, this._entities, this._dependencies) .then((new_data) => { - this.data = new_data.body; // chain.body from datasources + this.data = new_data; this.applyDataMethods(); - this.initialized = true; + this._initialized = true; + // Allow listeners (like subscribeToData) to see the information associated with a layer + this.parent.emit( + 'data_from_layer', + { layer: this.getBaseId(), content: deepCopy(new_data) }, // TODO: revamp event signature post layer-eventing-mixin + true, + ); }); } } diff --git a/esm/components/data_layer/genes.js b/esm/components/data_layer/genes.js index 88c85da3..14e07f94 100644 --- a/esm/components/data_layer/genes.js +++ b/esm/components/data_layer/genes.js @@ -11,7 +11,7 @@ const default_layout = { // Optionally specify different fill and stroke properties stroke: 'rgb(54, 54, 150)', color: '#363696', - label_font_size: 12, + label_font_size: 15, label_exon_spacing: 3, exon_height: 10, bounding_box_padding: 3, @@ -266,6 +266,7 @@ class Genes extends BaseDataLayer { const boundaries = d3.select(this).selectAll('rect.lz-data_layer-genes.lz-boundary') .data([gene], (d) => `${d.gene_name}_boundary`); + // FIXME: Make gene text font sizes scalable height = 1; boundaries.enter() .append('rect') @@ -309,7 +310,7 @@ class Genes extends BaseDataLayer { }) .attr('y', (d) => ((d.track - 1) * data_layer.getTrackHeight()) + data_layer.layout.bounding_box_padding - + data_layer.layout.label_font_size + + data_layer.layout.label_font_size, ); labels.exit() diff --git a/esm/components/data_layer/highlight_regions.js b/esm/components/data_layer/highlight_regions.js index ac89d47e..9d23c3e3 100644 --- a/esm/components/data_layer/highlight_regions.js +++ b/esm/components/data_layer/highlight_regions.js @@ -56,7 +56,7 @@ class HighlightRegions extends BaseDataLayer { throw new Error('highlight_regions layer does not support mouse events'); } - if (layout.regions && layout.regions.length && layout.fields && layout.fields.length) { + if (layout.regions.length && layout.namespace && Object.keys(layout.namespace).length) { throw new Error('highlight_regions layer can specify "regions" in layout, OR external data "fields", but not both'); } super(...arguments); diff --git a/esm/components/data_layer/line.js b/esm/components/data_layer/line.js index c6189f14..7dc78995 100644 --- a/esm/components/data_layer/line.js +++ b/esm/components/data_layer/line.js @@ -17,6 +17,7 @@ const default_layout = { x_axis: { field: 'x' }, y_axis: { field: 'y', axis: 1 }, hitarea_width: 5, + tooltip: null, }; /********************* @@ -105,7 +106,7 @@ class Line extends BaseDataLayer { if (typeof status == 'undefined' || !STATUSES.adjectives.includes(status)) { throw new Error('Invalid status'); } - if (typeof this.layer_state.status_flags[status] == 'undefined') { + if (typeof this._layer_state.status_flags[status] == 'undefined') { return this; } if (typeof toggle == 'undefined') { @@ -113,12 +114,12 @@ class Line extends BaseDataLayer { } // Update global status flag - this.global_statuses[status] = toggle; + this._global_statuses[status] = toggle; // Apply class to path based on global status flags let path_class = 'lz-data_layer-line'; - Object.keys(this.global_statuses).forEach((global_status) => { - if (this.global_statuses[global_status]) { + Object.keys(this._global_statuses).forEach((global_status) => { + if (this._global_statuses[global_status]) { path_class += ` lz-data_layer-line-${global_status}`; } }); @@ -178,10 +179,6 @@ class OrthogonalLine extends BaseDataLayer { layout.orientation = 'horizontal'; } super(...arguments); - - // Vars for storing the data generated line - /** @member {Array} */ - this.data = []; } getElementId(element) { diff --git a/esm/components/data_layer/scatter.js b/esm/components/data_layer/scatter.js index ecfe78ca..1e0ab1c6 100644 --- a/esm/components/data_layer/scatter.js +++ b/esm/components/data_layer/scatter.js @@ -133,18 +133,18 @@ class Scatter extends BaseDataLayer { }; // Flip any going over the right edge from the right side to the left side // (all labels start on the right side) - data_layer.label_texts.each(function (d, i) { + data_layer._label_texts.each(function (d, i) { const a = this; const da = d3.select(a); const dax = +da.attr('x'); const abound = da.node().getBoundingClientRect(); if (dax + abound.width + spacing > max_x) { - const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null; + const dal = handle_lines ? d3.select(data_layer._label_lines.nodes()[i]) : null; flip(da, dal); } }); // Second pass to flip any others that haven't flipped yet if they collide with another label - data_layer.label_texts.each(function (d, i) { + data_layer._label_texts.each(function (d, i) { const a = this; const da = d3.select(a); if (da.style('text-anchor') === 'end') { @@ -152,8 +152,8 @@ class Scatter extends BaseDataLayer { } let dax = +da.attr('x'); const abound = da.node().getBoundingClientRect(); - const dal = handle_lines ? d3.select(data_layer.label_lines.nodes()[i]) : null; - data_layer.label_texts.each(function () { + const dal = handle_lines ? d3.select(data_layer._label_lines.nodes()[i]) : null; + data_layer._label_texts.each(function () { const b = this; const db = d3.select(b); const bbound = db.node().getBoundingClientRect(); @@ -177,7 +177,7 @@ class Scatter extends BaseDataLayer { // Adapted from thudfactor's fiddle here: https://jsfiddle.net/thudfactor/HdwTH/ // TODO: Make labels also aware of data elements separate_labels() { - this.seperate_iterations++; + this._label_iterations++; const data_layer = this; const alpha = 0.5; if (!this.layout.label) { @@ -186,12 +186,12 @@ class Scatter extends BaseDataLayer { } const spacing = this.layout.label.spacing; let again = false; - data_layer.label_texts.each(function () { + data_layer._label_texts.each(function () { // TODO: O(n2) algorithm; revisit performance? const a = this; const da = d3.select(a); const y1 = da.attr('y'); - data_layer.label_texts.each(function () { + data_layer._label_texts.each(function () { const b = this; // a & b are the same element and don't collide. if (a === b) { @@ -250,14 +250,14 @@ class Scatter extends BaseDataLayer { if (again) { // Adjust lines to follow the labels if (data_layer.layout.label.lines) { - const label_elements = data_layer.label_texts.nodes(); - data_layer.label_lines.attr('y2', (d, i) => { + const label_elements = data_layer._label_texts.nodes(); + data_layer._label_lines.attr('y2', (d, i) => { const label_line = d3.select(label_elements[i]); return label_line.attr('y'); }); } // After ~150 iterations we're probably beyond diminising returns, so stop recursing - if (this.seperate_iterations < 150) { + if (this._label_iterations < 150) { setTimeout(() => { this.separate_labels(); }, 1); @@ -313,20 +313,20 @@ class Scatter extends BaseDataLayer { } // Render label groups - this.label_groups = this.svg.group + this._label_groups = this.svg.group .selectAll(`g.lz-data_layer-${this.layout.type}-label`) .data(label_data, (d) => `${d[this.layout.id_field]}_label`); const style_class = `lz-data_layer-${this.layout.type}-label`; - const groups_enter = this.label_groups.enter() + const groups_enter = this._label_groups.enter() .append('g') .attr('class', style_class); - if (this.label_texts) { - this.label_texts.remove(); + if (this._label_texts) { + this._label_texts.remove(); } - this.label_texts = this.label_groups.merge(groups_enter) + this._label_texts = this._label_groups.merge(groups_enter) .append('text') .text((d) => parseFields(data_layer.layout.label.text || '', d, this.getElementAnnotation(d))) .attr('x', (d) => { @@ -340,10 +340,10 @@ class Scatter extends BaseDataLayer { // Render label lines if (data_layer.layout.label.lines) { - if (this.label_lines) { - this.label_lines.remove(); + if (this._label_lines) { + this._label_lines.remove(); } - this.label_lines = this.label_groups.merge(groups_enter) + this._label_lines = this._label_groups.merge(groups_enter) .append('line') .attr('x1', (d) => d[xcs]) .attr('y1', (d) => d[ycs]) @@ -356,18 +356,18 @@ class Scatter extends BaseDataLayer { .call(applyStyles, data_layer.layout.label.lines.style || {}); } // Remove labels when they're no longer in the filtered data set - this.label_groups.exit() + this._label_groups.exit() .remove(); } else { // If the layout definition has changed (& no longer specifies labels), strip any previously rendered - if (this.label_texts) { - this.label_texts.remove(); + if (this._label_texts) { + this._label_texts.remove(); } - if (this.label_lines) { - this.label_lines.remove(); + if (this._label_lines) { + this._label_lines.remove(); } - if (this.label_groups) { - this.label_groups.remove(); + if (this._label_groups) { + this._label_groups.remove(); } } @@ -402,7 +402,7 @@ class Scatter extends BaseDataLayer { // Apply method to keep labels from overlapping each other if (this.layout.label) { this.flip_labels(); - this.seperate_iterations = 0; + this._label_iterations = 0; this.separate_labels(); } diff --git a/esm/components/legend.js b/esm/components/legend.js index be5d3ed3..7bef5c16 100644 --- a/esm/components/legend.js +++ b/esm/components/legend.js @@ -18,7 +18,7 @@ const default_layout = { width: 10, height: 10, padding: 5, - label_size: 12, + label_size: 14, hidden: false, }; @@ -99,12 +99,13 @@ class Legend { let x = padding; let y = padding; let line_height = 0; - this.parent.data_layer_ids_by_z_index.slice().reverse().forEach((id) => { - if (Array.isArray(this.parent.data_layers[id].layout.legend)) { - this.parent.data_layers[id].layout.legend.forEach((element) => { + this.parent._data_layer_ids_by_z_index.slice().reverse().forEach((id) => { + const layer_legend = this.parent.data_layers[id].layout.legend; + if (Array.isArray(layer_legend)) { + layer_legend.forEach((element) => { const selector = this.elements_group.append('g') .attr('transform', `translate(${x}, ${y})`); - const label_size = +element.label_size || +this.layout.label_size || 12; + const label_size = +element.label_size || +this.layout.label_size; let label_x = 0; let label_y = (label_size / 2) + (padding / 2); line_height = Math.max(line_height, label_size + padding); @@ -135,6 +136,82 @@ class Legend { label_x = width + padding; line_height = Math.max(line_height, height + padding); + } else if (shape === 'ribbon') { + // Color ribbons describe a series of color stops: small boxes of color across a continuous + // scale. Drawn horizontally, or vertically, like: + // [red | orange | yellow | green ] label + // For example, this can be used with the numerical-bin color scale to describe LD color stops in a compact way. + const width = +element.width || 25; + const height = +element.height || width; + const is_horizontal = (element.orientation || 'vertical') === 'horizontal'; + let color_stops = element.color_stops; + + const all_elements = selector.append('g'); + const ribbon_group = all_elements.append('g'); + const axis_group = all_elements.append('g'); + let axis_offset = 0; + if (element.tick_labels) { + let range; + if (is_horizontal) { + range = [0, width * color_stops.length - 1]; // 1 px offset to align tick with inner borders + } else { + range = [height * color_stops.length - 1, 0]; + } + const scale = d3.scaleLinear() + .domain(d3.extent(element.tick_labels)) // Assumes tick labels are always numeric in this mode + .range(range); + const axis = (is_horizontal ? d3.axisTop : d3.axisRight)(scale) + .tickSize(3) + .tickValues(element.tick_labels) + .tickFormat((v) => v); + axis_group + .call(axis) + .attr('class', 'lz-axis'); + let bcr = axis_group.node().getBoundingClientRect(); + axis_offset = bcr.height; + } + if (is_horizontal) { + // Shift axis down (so that tick marks aren't above the origin) + axis_group + .attr('transform', `translate(0, ${axis_offset})`); + // Ribbon appears below axis + ribbon_group + .attr('transform', `translate(0, ${axis_offset})`); + } else { + // Vertical mode: Shift axis ticks to the right of the ribbon + all_elements.attr('transform', 'translate(5, 0)'); + axis_group + .attr('transform', `translate(${width}, 0)`); + } + + if (!is_horizontal) { + // Vertical mode: renders top -> bottom but scale is usually specified low..high + color_stops = color_stops.slice(); + color_stops.reverse(); + } + for (let i = 0; i < color_stops.length; i++) { + const color = color_stops[i]; + const to_next_marking = is_horizontal ? `translate(${width * i}, 0)` : `translate(0, ${height * i})`; + ribbon_group + .append('rect') + .attr('class', element.class || '') + .attr('stroke', 'black') + .attr('transform', to_next_marking) + .attr('stroke-width', 0.5) + .attr('width', width) + .attr('height', height) + .attr('fill', color) + .call(applyStyles, element.style || {}); + } + + // Note: In vertical mode, it's usually easier to put the label above the legend as a separate marker + // This is because the legend element label is drawn last (can't use it's size to position the ribbon, which is drawn first) + if (!is_horizontal && element.label) { + throw new Error('Legend labels not supported for vertical ribbons (use a separate legend item as text instead)'); + } + // This only makes sense for horizontal labels. + label_x = (width * color_stops.length + padding); + label_y += axis_offset; } else if (shape_factory) { // Shape symbol is a recognized d3 type, so we can draw it in the legend (circle, diamond, etc.) const size = +element.size || 40; diff --git a/esm/components/panel.js b/esm/components/panel.js index 11609433..2f36f784 100644 --- a/esm/components/panel.js +++ b/esm/components/panel.js @@ -59,7 +59,7 @@ const default_layout = { */ class Panel { /** - * @param {string} [layout.id=''] An identifier string that must be unique across all panels in the plot + * @param {string} layout.id An identifier string that must be unique across all panels in the plot. Required. * @param {string} [layout.tag='custom_data_type'] Tags have no functional purpose, but they can be used * as a semantic label for what is being displayed in this element. This makes it easy to write custom code like "find every panel * that shows association scatter plots, anywhere": even if the IDs are different, the tag can be the same. @@ -103,7 +103,8 @@ class Panel { * genomic coordinates, eg 23423456 => 23.42 (Mb) * @param {Array} [layout.axes.x.ticks] An array of custom ticks that will override any automatically generated) * @param {string} [layout.axes.y1.label] Label text for the provided axis - * @param {number} [layout.axes.y1.label_offset] + * @param {number} [layout.axes.y1.label_offset] The distance between the axis title and the axis. Use this to prevent + * the title from overlapping with tick mark labels. If there is not enough space for the label, be sure to increase the panel margins (left or right) accordingly. * @param {boolean} [layout.axes.y1.render=false] Whether to render this axis * @param {Array} [layout.axes.y1.ticks] An array of custom ticks that will override any automatically generated) * @param {string} [layout.axes.y2.label] Label text for the provided axis @@ -137,20 +138,8 @@ class Panel { */ this.parent_plot = parent; - // Ensure a valid ID is present. If there is no valid ID then generate one - if (typeof layout.id !== 'string' || !layout.id.length) { - if (!this.parent) { - layout.id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`; - } else { - const generateID = () => { - let id = `p${Math.floor(Math.random() * Math.pow(10, 8))}`; - if (id === null || typeof this.parent.panels[id] != 'undefined') { - id = generateID(); - } - return id; - }; - layout.id = generateID(); - } + if (typeof layout.id !== 'string' || !layout.id) { + throw new Error('Panel layouts must specify "id"'); } else if (this.parent) { if (typeof this.parent.panels[layout.id] !== 'undefined') { throw new Error(`Cannot create panel with id [${layout.id}]; panel with that id already exists`); @@ -166,13 +155,13 @@ class Panel { * @private * @member {Boolean} */ - this.initialized = false; + this._initialized = false; /** * The index of this panel in the parent plot's `layout.panels` * @private * @member {number} * */ - this.layout_idx = null; + this._layout_idx = null; /** * @private * @member {Object} @@ -198,11 +187,11 @@ class Panel { * @private * @member {String} */ - this.state_id = this.id; - this.state[this.state_id] = this.state[this.state_id] || {}; + this._state_id = this.id; + this.state[this._state_id] = this.state[this._state_id] || {}; } else { this.state = null; - this.state_id = null; + this._state_id = null; } /** @@ -215,14 +204,14 @@ class Panel { * @private * @member {String[]} */ - this.data_layer_ids_by_z_index = []; + this._data_layer_ids_by_z_index = []; /** * Track data requests in progress * @member {Promise[]} * @private */ - this.data_promises = []; + this._data_promises = []; /** * @private @@ -277,7 +266,7 @@ class Panel { * @private * @member {number} */ - this.zoom_timeout = null; + this._zoom_timeout = null; /** * Known event hooks that the panel can respond to @@ -285,7 +274,7 @@ class Panel { * @protected * @member {Object} */ - this.event_hooks = {}; + this._event_hooks = {}; // Initialize the layout this.initializeLayout(); @@ -316,11 +305,11 @@ class Panel { if (typeof hook != 'function') { throw new Error('Unable to register event hook, invalid hook function passed'); } - if (!this.event_hooks[event]) { + if (!this._event_hooks[event]) { // We do not validate on known event names, because LZ is allowed to track and emit custom events like "widget button clicked". - this.event_hooks[event] = []; + this._event_hooks[event] = []; } - this.event_hooks[event].push(hook); + this._event_hooks[event].push(hook); return hook; } @@ -332,14 +321,14 @@ class Panel { * @returns {Panel} */ off(event, hook) { - const theseHooks = this.event_hooks[event]; + const theseHooks = this._event_hooks[event]; if (typeof event != 'string' || !Array.isArray(theseHooks)) { throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`); } if (hook === undefined) { // Deregistering all hooks for this event may break basic functionality, and should only be used during // cleanup operations (eg to prevent memory leaks) - this.event_hooks[event] = []; + this._event_hooks[event] = []; } else { const hookMatch = theseHooks.indexOf(hook); if (hookMatch !== -1) { @@ -380,9 +369,9 @@ class Panel { const sourceID = this.getBaseId(); const eventContext = { sourceID: sourceID, target: this, data: eventData || null }; - if (this.event_hooks[event]) { + if (this._event_hooks[event]) { // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound? - this.event_hooks[event].forEach((hookToRun) => { + this._event_hooks[event].forEach((hookToRun) => { // By default, any handlers fired here will see the panel as the value of `this`. If a bound function is // registered as a handler, the previously bound `this` will override anything provided to `call` below. hookToRun.call(this, eventContext); @@ -445,13 +434,12 @@ class Panel { * @returns {BaseDataLayer} */ addDataLayer(layout) { - // Sanity checks if (typeof layout !== 'object' || typeof layout.id !== 'string' || !layout.id.length) { throw new Error('Invalid data layer layout'); } if (typeof this.data_layers[layout.id] !== 'undefined') { - throw new Error(`Cannot create data_layer with id [${layout.id}]; data layer with that id already exists in the panel`); + throw new Error(`Cannot create data_layer with id '${layout.id}'; data layer with that id already exists in the panel`); } if (typeof layout.type !== 'string') { throw new Error('Invalid data layer type'); @@ -470,17 +458,17 @@ class Panel { // If a discrete z_index was set in the layout then adjust other data layer z_index values to accommodate this one if (data_layer.layout.z_index !== null && !isNaN(data_layer.layout.z_index) - && this.data_layer_ids_by_z_index.length > 0) { + && this._data_layer_ids_by_z_index.length > 0) { // Negative z_index values should count backwards from the end, so convert negatives to appropriate values here if (data_layer.layout.z_index < 0) { - data_layer.layout.z_index = Math.max(this.data_layer_ids_by_z_index.length + data_layer.layout.z_index, 0); + data_layer.layout.z_index = Math.max(this._data_layer_ids_by_z_index.length + data_layer.layout.z_index, 0); } - this.data_layer_ids_by_z_index.splice(data_layer.layout.z_index, 0, data_layer.id); - this.data_layer_ids_by_z_index.forEach((dlid, idx) => { + this._data_layer_ids_by_z_index.splice(data_layer.layout.z_index, 0, data_layer.id); + this._data_layer_ids_by_z_index.forEach((dlid, idx) => { this.data_layers[dlid].layout.z_index = idx; }); } else { - const length = this.data_layer_ids_by_z_index.push(data_layer.id); + const length = this._data_layer_ids_by_z_index.push(data_layer.id); this.data_layers[data_layer.id].layout.z_index = length - 1; } @@ -495,7 +483,7 @@ class Panel { if (layout_idx === null) { layout_idx = this.layout.data_layers.push(this.data_layers[data_layer.id].layout) - 1; } - this.data_layers[data_layer.id].layout_idx = layout_idx; + this.data_layers[data_layer.id]._layout_idx = layout_idx; return this.data_layers[data_layer.id]; } @@ -507,30 +495,31 @@ class Panel { * @returns {Panel} */ removeDataLayer(id) { - if (!this.data_layers[id]) { + const target_layer = this.data_layers[id]; + if (!target_layer) { throw new Error(`Unable to remove data layer, ID not found: ${id}`); } // Destroy all tooltips for the data layer - this.data_layers[id].destroyAllTooltips(); + target_layer.destroyAllTooltips(); // Remove the svg container for the data layer if it exists - if (this.data_layers[id].svg.container) { - this.data_layers[id].svg.container.remove(); + if (target_layer.svg.container) { + target_layer.svg.container.remove(); } // Delete the data layer and its presence in the panel layout and state - this.layout.data_layers.splice(this.data_layers[id].layout_idx, 1); - delete this.state[this.data_layers[id].state_id]; + this.layout.data_layers.splice(target_layer._layout_idx, 1); + delete this.state[target_layer._state_id]; delete this.data_layers[id]; // Remove the data_layer id from the z_index array - this.data_layer_ids_by_z_index.splice(this.data_layer_ids_by_z_index.indexOf(id), 1); + this._data_layer_ids_by_z_index.splice(this._data_layer_ids_by_z_index.indexOf(id), 1); // Update layout_idx and layout.z_index values for all remaining data_layers this.applyDataLayerZIndexesToDataLayerLayouts(); this.layout.data_layers.forEach((data_layer_layout, idx) => { - this.data_layers[data_layer_layout.id].layout_idx = idx; + this.data_layers[data_layer_layout.id]._layout_idx = idx; }); return this; @@ -542,7 +531,7 @@ class Panel { * @returns {Panel} */ clearSelections() { - this.data_layer_ids_by_z_index.forEach((id) => { + this._data_layer_ids_by_z_index.forEach((id) => { this.data_layers[id].setAllElementStatus('selected', false); }); return this; @@ -555,7 +544,6 @@ class Panel { * @returns {Panel} */ render() { - // Position the panel container this.svg.container.attr('transform', `translate(${this.layout.origin.x}, ${this.layout.origin.y})`); @@ -564,12 +552,15 @@ class Panel { .attr('width', this.parent_plot.layout.width) .attr('height', this.layout.height); + const { cliparea } = this.layout; + // Set and position the inner border, style if necessary + const { margin } = this.layout; 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)); + .attr('x', margin.left) + .attr('y', margin.top) + .attr('width', this.parent_plot.layout.width - (margin.left + margin.right)) + .attr('height', this.layout.height - (margin.top + margin.bottom)); if (this.layout.inner_border) { this.inner_border .style('stroke-width', 1) @@ -609,41 +600,44 @@ class Panel { // Define default and shifted ranges for all axes const ranges = {}; + const axes_config = this.layout.axes; if (this.x_extent) { const base_x_range = { start: 0, end: this.layout.cliparea.width }; - if (this.layout.axes.x.range) { - base_x_range.start = this.layout.axes.x.range.start || base_x_range.start; - base_x_range.end = this.layout.axes.x.range.end || base_x_range.end; + if (axes_config.x.range) { + base_x_range.start = axes_config.x.range.start || base_x_range.start; + base_x_range.end = axes_config.x.range.end || base_x_range.end; } ranges.x = [base_x_range.start, base_x_range.end]; ranges.x_shifted = [base_x_range.start, base_x_range.end]; } if (this.y1_extent) { - const base_y1_range = { start: this.layout.cliparea.height, end: 0 }; - if (this.layout.axes.y1.range) { - base_y1_range.start = this.layout.axes.y1.range.start || base_y1_range.start; - base_y1_range.end = this.layout.axes.y1.range.end || base_y1_range.end; + const base_y1_range = { start: cliparea.height, end: 0 }; + if (axes_config.y1.range) { + base_y1_range.start = axes_config.y1.range.start || base_y1_range.start; + base_y1_range.end = axes_config.y1.range.end || base_y1_range.end; } ranges.y1 = [base_y1_range.start, base_y1_range.end]; ranges.y1_shifted = [base_y1_range.start, base_y1_range.end]; } if (this.y2_extent) { - const base_y2_range = { start: this.layout.cliparea.height, end: 0 }; - if (this.layout.axes.y2.range) { - base_y2_range.start = this.layout.axes.y2.range.start || base_y2_range.start; - base_y2_range.end = this.layout.axes.y2.range.end || base_y2_range.end; + const base_y2_range = { start: cliparea.height, end: 0 }; + if (axes_config.y2.range) { + base_y2_range.start = axes_config.y2.range.start || base_y2_range.start; + base_y2_range.end = axes_config.y2.range.end || base_y2_range.end; } ranges.y2 = [base_y2_range.start, base_y2_range.end]; ranges.y2_shifted = [base_y2_range.start, base_y2_range.end]; } // Shift ranges based on any drag or zoom interactions currently underway - if (this.parent.interaction.panel_id && (this.parent.interaction.panel_id === this.id || this.parent.interaction.linked_panel_ids.includes(this.id))) { + let { _interaction } = this.parent; + const current_drag = _interaction.dragging; + if (_interaction.panel_id && (_interaction.panel_id === this.id || _interaction.linked_panel_ids.includes(this.id))) { let anchor, scalar = null; - if (this.parent.interaction.zooming && typeof this.x_scale == 'function') { + if (_interaction.zooming && typeof this.x_scale == 'function') { const current_extent_size = Math.abs(this.x_extent[1] - this.x_extent[0]); 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])); - let zoom_factor = this.parent.interaction.zooming.scale; + let zoom_factor = _interaction.zooming.scale; const potential_extent_size = Math.floor(current_scaled_extent_size * (1 / zoom_factor)); if (zoom_factor < 1 && !isNaN(this.parent.layout.max_region_scale)) { zoom_factor = 1 / (Math.min(potential_extent_size, this.parent.layout.max_region_scale) / current_scaled_extent_size); @@ -651,38 +645,38 @@ class Panel { zoom_factor = 1 / (Math.max(potential_extent_size, this.parent.layout.min_region_scale) / current_scaled_extent_size); } const new_extent_size = Math.floor(current_extent_size * zoom_factor); - anchor = this.parent.interaction.zooming.center - this.layout.margin.left - this.layout.origin.x; - const offset_ratio = anchor / this.layout.cliparea.width; + anchor = _interaction.zooming.center - margin.left - this.layout.origin.x; + const offset_ratio = anchor / cliparea.width; 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); ranges.x_shifted = [ this.x_scale(new_x_extent_start), this.x_scale(new_x_extent_start + new_extent_size) ]; - } else if (this.parent.interaction.dragging) { - switch (this.parent.interaction.dragging.method) { + } else if (current_drag) { + switch (current_drag.method) { case 'background': - ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x; - ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x; + ranges.x_shifted[0] = +current_drag.dragged_x; + ranges.x_shifted[1] = cliparea.width + current_drag.dragged_x; break; case 'x_tick': if (d3.event && d3.event.shiftKey) { - ranges.x_shifted[0] = +this.parent.interaction.dragging.dragged_x; - ranges.x_shifted[1] = this.layout.cliparea.width + this.parent.interaction.dragging.dragged_x; + ranges.x_shifted[0] = +current_drag.dragged_x; + ranges.x_shifted[1] = cliparea.width + current_drag.dragged_x; } else { - anchor = this.parent.interaction.dragging.start_x - this.layout.margin.left - this.layout.origin.x; - scalar = constrain(anchor / (anchor + this.parent.interaction.dragging.dragged_x), 3); + anchor = current_drag.start_x - margin.left - this.layout.origin.x; + scalar = constrain(anchor / (anchor + current_drag.dragged_x), 3); ranges.x_shifted[0] = 0; - ranges.x_shifted[1] = Math.max(this.layout.cliparea.width * (1 / scalar), 1); + ranges.x_shifted[1] = Math.max(cliparea.width * (1 / scalar), 1); } break; case 'y1_tick': case 'y2_tick': { - const y_shifted = `y${this.parent.interaction.dragging.method[1]}_shifted`; + const y_shifted = `y${current_drag.method[1]}_shifted`; if (d3.event && d3.event.shiftKey) { - ranges[y_shifted][0] = this.layout.cliparea.height + this.parent.interaction.dragging.dragged_y; - ranges[y_shifted][1] = +this.parent.interaction.dragging.dragged_y; + ranges[y_shifted][0] = cliparea.height + current_drag.dragged_y; + ranges[y_shifted][1] = +current_drag.dragged_y; } else { - anchor = this.layout.cliparea.height - (this.parent.interaction.dragging.start_y - this.layout.margin.top - this.layout.origin.y); - scalar = constrain(anchor / (anchor - this.parent.interaction.dragging.dragged_y), 3); - ranges[y_shifted][0] = this.layout.cliparea.height; - ranges[y_shifted][1] = this.layout.cliparea.height - (this.layout.cliparea.height * (1 / scalar)); + anchor = cliparea.height - (current_drag.start_y - margin.top - this.layout.origin.y); + scalar = constrain(anchor / (anchor - current_drag.dragged_y), 3); + ranges[y_shifted][0] = cliparea.height; + ranges[y_shifted][1] = cliparea.height - (cliparea.height * (1 / scalar)); } } } @@ -734,7 +728,7 @@ class Panel { if (delta === 0) { return; } - this.parent.interaction = { + this.parent._interaction = { panel_id: this.id, linked_panel_ids: this.getLinkedPanelIds('x'), zooming: { @@ -743,14 +737,16 @@ class Panel { }, }; this.render(); - this.parent.interaction.linked_panel_ids.forEach((panel_id) => { + // Redefine b/c might have been changed during call to parent re-render + _interaction = this.parent._interaction; + _interaction.linked_panel_ids.forEach((panel_id) => { this.parent.panels[panel_id].render(); }); - if (this.zoom_timeout !== null) { - clearTimeout(this.zoom_timeout); + if (this._zoom_timeout !== null) { + clearTimeout(this._zoom_timeout); } - this.zoom_timeout = setTimeout(() => { - this.parent.interaction = {}; + this._zoom_timeout = setTimeout(() => { + this.parent._interaction = {}; this.parent.applyState({ start: this.x_extent[0], end: this.x_extent[1] }); }, 500); }; @@ -762,7 +758,7 @@ class Panel { } // Render data layers in order by z-index - this.data_layer_ids_by_z_index.forEach((data_layer_id) => { + this._data_layer_ids_by_z_index.forEach((data_layer_id) => { this.data_layers[data_layer_id].draw().render(); }); @@ -788,7 +784,7 @@ class Panel { * @returns {Panel} */ addBasicLoader(show_immediately = true) { - if (this.layout.show_loading_indicator && this.initialized) { + if (this.layout.show_loading_indicator && this._initialized) { // Prior to LZ 0.13, this function was called only after the plot was first rendered. Now, it is run by default. // Some older pages could thus end up adding a loader twice: to avoid duplicate render events, // short-circuit if a loader is already present after the first render has finished. @@ -812,7 +808,7 @@ class Panel { /************* Private interface: only used internally */ /** @private */ applyDataLayerZIndexesToDataLayerLayouts () { - this.data_layer_ids_by_z_index.forEach((dlid, idx) => { + this._data_layer_ids_by_z_index.forEach((dlid, idx) => { this.data_layers[dlid].layout.z_index = idx; }); } @@ -858,13 +854,14 @@ class Panel { this.y2_range = [this.layout.cliparea.height, 0]; // Initialize panel axes - ['x', 'y1', 'y2'].forEach((axis) => { - if (!Object.keys(this.layout.axes[axis]).length || this.layout.axes[axis].render === false) { + ['x', 'y1', 'y2'].forEach((id) => { + const axis = this.layout.axes[id]; + if (!Object.keys(axis).length || axis.render === false) { // The default layout sets the axis to an empty object, so set its render boolean here - this.layout.axes[axis].render = false; + axis.render = false; } else { - this.layout.axes[axis].render = true; - this.layout.axes[axis].label = this.layout.axes[axis].label || null; + axis.render = true; + axis.label = axis.label || null; } }); @@ -887,21 +884,22 @@ class Panel { * @returns {Panel} */ setDimensions(width, height) { + const layout = this.layout; if (typeof width != 'undefined' && typeof height != 'undefined') { if (!isNaN(width) && width >= 0 && !isNaN(height) && height >= 0) { this.parent.layout.width = Math.round(+width); // Ensure that the requested height satisfies all minimum values - this.layout.height = Math.max(Math.round(+height), this.layout.min_height); + layout.height = Math.max(Math.round(+height), 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); + layout.cliparea.width = Math.max(this.parent_plot.layout.width - (layout.margin.left + layout.margin.right), 0); + layout.cliparea.height = Math.max(layout.height - (layout.margin.top + layout.margin.bottom), 0); if (this.svg.clipRect) { this.svg.clipRect .attr('width', this.parent.layout.width) - .attr('height', this.layout.height); + .attr('height', layout.height); } - if (this.initialized) { + if (this._initialized) { this.render(); this.curtain.update(); this.loader.update(); @@ -928,7 +926,7 @@ class Panel { if (!isNaN(y) && y >= 0) { this.layout.origin.y = Math.max(Math.round(+y), 0); } - if (this.initialized) { + if (this._initialized) { this.render(); } return this; @@ -945,38 +943,39 @@ class Panel { */ setMargin(top, right, bottom, left) { let extra; - if (!isNaN(top) && top >= 0) { - this.layout.margin.top = Math.max(Math.round(+top), 0); + const { cliparea, margin } = this.layout; + if (!isNaN(top) && top >= 0) { + margin.top = Math.max(Math.round(+top), 0); } if (!isNaN(right) && right >= 0) { - this.layout.margin.right = Math.max(Math.round(+right), 0); + margin.right = Math.max(Math.round(+right), 0); } if (!isNaN(bottom) && bottom >= 0) { - this.layout.margin.bottom = Math.max(Math.round(+bottom), 0); + margin.bottom = Math.max(Math.round(+bottom), 0); } if (!isNaN(left) && left >= 0) { - this.layout.margin.left = Math.max(Math.round(+left), 0); + margin.left = Math.max(Math.round(+left), 0); } // If the specified margins are greater than the available width, then shrink the margins. - if (this.layout.margin.top + this.layout.margin.bottom > this.layout.height) { - extra = Math.floor(((this.layout.margin.top + this.layout.margin.bottom) - this.layout.height) / 2); - this.layout.margin.top -= extra; - this.layout.margin.bottom -= extra; + if (margin.top + margin.bottom > this.layout.height) { + extra = Math.floor(((margin.top + margin.bottom) - this.layout.height) / 2); + margin.top -= extra; + margin.bottom -= extra; } - if (this.layout.margin.left + this.layout.margin.right > this.parent_plot.layout.width) { - extra = Math.floor(((this.layout.margin.left + this.layout.margin.right) - this.parent_plot.layout.width) / 2); - this.layout.margin.left -= extra; - this.layout.margin.right -= extra; + if (margin.left + margin.right > this.parent_plot.layout.width) { + extra = Math.floor(((margin.left + margin.right) - this.parent_plot.layout.width) / 2); + margin.left -= extra; + margin.right -= extra; } ['top', 'right', 'bottom', 'left'].forEach((m) => { - this.layout.margin[m] = Math.max(this.layout.margin[m], 0); + margin[m] = Math.max(margin[m], 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; + cliparea.width = Math.max(this.parent_plot.layout.width - (margin.left + margin.right), 0); + cliparea.height = Math.max(this.layout.height - (margin.top + margin.bottom), 0); + cliparea.origin.x = margin.left; + cliparea.origin.y = margin.top; - if (this.initialized) { + if (this._initialized) { this.render(); } return this; @@ -989,7 +988,6 @@ class Panel { * @returns {Panel} */ initialize() { - // Append a container group element to house the main panel group element and the clip path // Position with initial layout parameters const base_id = this.getBaseId(); @@ -1078,7 +1076,7 @@ class Panel { } // Initialize child Data Layers - this.data_layer_ids_by_z_index.forEach((id) => { + this._data_layer_ids_by_z_index.forEach((id) => { this.data_layers[id].initialize(); }); @@ -1110,7 +1108,7 @@ class Panel { */ resortDataLayers() { const sort = []; - this.data_layer_ids_by_z_index.forEach((id) => { + this._data_layer_ids_by_z_index.forEach((id) => { sort.push(this.data_layers[id].layout.z_index); }); this.svg.group @@ -1135,7 +1133,7 @@ class Panel { if (!this.layout.interaction[`${axis}_linked`]) { return linked_panel_ids; } - this.parent.panel_ids_by_y_index.forEach((panel_id) => { + this.parent._panel_ids_by_y_index.forEach((panel_id) => { if (panel_id !== this.id && this.parent.panels[panel_id].layout.interaction[`${axis}_linked`]) { linked_panel_ids.push(panel_id); } @@ -1149,11 +1147,13 @@ class Panel { * @returns {Panel} */ moveUp() { - if (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(); + const { parent } = this; + const y_index = this.layout.y_index; + if (parent._panel_ids_by_y_index[y_index - 1]) { + parent._panel_ids_by_y_index[y_index] = parent._panel_ids_by_y_index[y_index - 1]; + parent._panel_ids_by_y_index[y_index - 1] = this.id; + parent.applyPanelYIndexesToPanelLayouts(); + parent.positionPanels(); } return this; } @@ -1164,9 +1164,10 @@ class Panel { * @returns {Panel} */ moveDown() { - if (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; + const { _panel_ids_by_y_index } = this.parent; + if (_panel_ids_by_y_index[this.layout.y_index + 1]) { + _panel_ids_by_y_index[this.layout.y_index] = _panel_ids_by_y_index[this.layout.y_index + 1]; + _panel_ids_by_y_index[this.layout.y_index + 1] = this.id; this.parent.applyPanelYIndexesToPanelLayouts(); this.parent.positionPanels(); } @@ -1184,23 +1185,23 @@ class Panel { */ reMap() { this.emit('data_requested'); - this.data_promises = []; + this._data_promises = []; // Remove any previous error messages before attempting to load new data this.curtain.hide(); // Trigger reMap on each Data Layer for (let id in this.data_layers) { try { - this.data_promises.push(this.data_layers[id].reMap()); + this._data_promises.push(this.data_layers[id].reMap()); } catch (error) { console.error(error); this.curtain.show(error.message || error); } } // When all finished trigger a render - return Promise.all(this.data_promises) + return Promise.all(this._data_promises) .then(() => { - this.initialized = true; + this._initialized = true; this.render(); this.emit('layout_changed', true); this.emit('data_rendered'); @@ -1217,7 +1218,6 @@ class Panel { * @returns {Panel} */ generateExtents() { - // Reset extents ['x', 'y1', 'y2'].forEach((axis) => { this[`${axis}_extent`] = null; @@ -1225,7 +1225,6 @@ class Panel { // Loop through the data layers for (let id in this.data_layers) { - const data_layer = this.data_layers[id]; // If defined and not decoupled, merge the x extent of the data layer with the panel's x extent @@ -1267,7 +1266,6 @@ class Panel { * * color: string or LocusZoom scalable parameter object */ generateTicks(axis) { - // Parse an explicit 'ticks' attribute in the axis layout if (this.layout.axes[axis].ticks) { const layout = this.layout.axes[axis]; @@ -1287,7 +1285,7 @@ class Panel { // Pass any layer-specific customizations for how ticks are calculated. (styles are overridden separately) const config = { position: baseTickConfig.position }; - const combinedTicks = this.data_layer_ids_by_z_index.reduce((acc, data_layer_id) => { + const combinedTicks = this._data_layer_ids_by_z_index.reduce((acc, data_layer_id) => { const nextLayer = self.data_layers[data_layer_id]; return acc.concat(nextLayer.getTicks(axis, config)); }, []); @@ -1315,7 +1313,6 @@ class Panel { * @returns {Panel} */ renderAxis(axis) { - if (!['x', 'y1', 'y2'].includes(axis)) { throw new Error(`Unable to render axis; invalid axis identifier: ${axis}`); } @@ -1488,7 +1485,7 @@ class Panel { scaleHeightToData(target_height) { target_height = +target_height || null; if (target_height === null) { - this.data_layer_ids_by_z_index.forEach((id) => { + this._data_layer_ids_by_z_index.forEach((id) => { const dh = this.data_layers[id].getAbsoluteDataHeight(); if (+dh) { if (target_height === null) { @@ -1515,7 +1512,7 @@ class Panel { * @param {Boolean} toggle */ setAllElementStatus(status, toggle) { - this.data_layer_ids_by_z_index.forEach((id) => { + this._data_layer_ids_by_z_index.forEach((id) => { this.data_layers[id].setAllElementStatus(status, toggle); }); } diff --git a/esm/components/plot.js b/esm/components/plot.js index ee266be6..a4dcb2e2 100644 --- a/esm/components/plot.js +++ b/esm/components/plot.js @@ -66,6 +66,17 @@ const default_layout = { * @see event:any_lz_event */ +/** + * One particular data layer has completed a request for data. This event is primarily used internally by the `subscribeToData` function, and the syntax may change in the future. + * @event data_from_layer + * @property {object} data + * @property {String} data.layer The fully qualified ID of the layer emitting this event + * @property {Object[]} data.content The data used to draw this layer: an array where each element represents one row/ datum + * element. It reflects all namespaces and data operations used by that layer. + * @see event:any_lz_event + */ + + /** * An action occurred that changed, or could change, the layout. * Many rerendering operations can fire this event and it is somewhat generic: it includes resize, highlight, @@ -219,7 +230,7 @@ class Plot { * @private * @member Boolean} */ - this.initialized = false; + this._initialized = false; /** * @private @@ -256,7 +267,7 @@ class Plot { * @private * @member {String[]} */ - this.panel_ids_by_y_index = []; + this._panel_ids_by_y_index = []; /** * Track update operations (reMap) performed on all child panels, and notify the parent plot when complete @@ -265,7 +276,7 @@ class Plot { * @protected * @member {Promise[]} */ - this.remap_promises = []; + this._remap_promises = []; /** @@ -316,7 +327,7 @@ class Plot { * @protected * @member {Object} */ - this.event_hooks = {}; + this._event_hooks = {}; /** * @callback eventCallback @@ -334,7 +345,7 @@ class Plot { * @member {{panel_id: String, linked_panel_ids: Array, x_linked: *, dragging: *, zooming: *}} * @returns {Plot} */ - this.interaction = {}; + this._interaction = {}; // Initialize the layout this.initializeLayout(); @@ -364,11 +375,11 @@ class Plot { if (typeof hook != 'function') { throw new Error('Unable to register event hook, invalid hook function passed'); } - if (!this.event_hooks[event]) { + if (!this._event_hooks[event]) { // We do not validate on known event names, because LZ is allowed to track and emit custom events like "widget button clicked". - this.event_hooks[event] = []; + this._event_hooks[event] = []; } - this.event_hooks[event].push(hook); + this._event_hooks[event].push(hook); return hook; } @@ -381,14 +392,14 @@ class Plot { * @returns {Plot} */ off(event, hook) { - const theseHooks = this.event_hooks[event]; + const theseHooks = this._event_hooks[event]; if (typeof event != 'string' || !Array.isArray(theseHooks)) { throw new Error(`Unable to remove event hook, invalid event: ${event.toString()}`); } if (hook === undefined) { // Deregistering all hooks for this event may break basic functionality, and should only be used during // cleanup operations (eg to prevent memory leaks) - this.event_hooks[event] = []; + this._event_hooks[event] = []; } else { const hookMatch = theseHooks.indexOf(hook); if (hookMatch !== -1) { @@ -411,10 +422,10 @@ class Plot { emit(event, eventData) { // TODO: there are small differences between the emit implementation between plots and panels. In the future, // DRY this code via mixins, and make sure to keep the interfaces compatible when refactoring. - const these_hooks = this.event_hooks[event]; + const these_hooks = this._event_hooks[event]; if (typeof event != 'string') { throw new Error(`LocusZoom attempted to throw an invalid event: ${event.toString()}`); - } else if (!these_hooks && !this.event_hooks['any_lz_event']) { + } else if (!these_hooks && !this._event_hooks['any_lz_event']) { // If the tree_fall event is emitted in a forest and no one is around to hear it, does it really make a sound? return this; } @@ -468,15 +479,15 @@ class Plot { // If a discrete y_index was set in the layout then adjust other panel y_index values to accommodate this one if (panel.layout.y_index !== null && !isNaN(panel.layout.y_index) - && this.panel_ids_by_y_index.length > 0) { + && this._panel_ids_by_y_index.length > 0) { // Negative y_index values should count backwards from the end, so convert negatives to appropriate values here if (panel.layout.y_index < 0) { - panel.layout.y_index = Math.max(this.panel_ids_by_y_index.length + panel.layout.y_index, 0); + panel.layout.y_index = Math.max(this._panel_ids_by_y_index.length + panel.layout.y_index, 0); } - this.panel_ids_by_y_index.splice(panel.layout.y_index, 0, panel.id); + this._panel_ids_by_y_index.splice(panel.layout.y_index, 0, panel.id); this.applyPanelYIndexesToPanelLayouts(); } else { - const length = this.panel_ids_by_y_index.push(panel.id); + const length = this._panel_ids_by_y_index.push(panel.id); this.panels[panel.id].layout.y_index = length - 1; } @@ -491,10 +502,10 @@ class Plot { if (layout_idx === null) { layout_idx = this.layout.panels.push(this.panels[panel.id].layout) - 1; } - this.panels[panel.id].layout_idx = layout_idx; + this.panels[panel.id]._layout_idx = layout_idx; // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space - if (this.initialized) { + if (this._initialized) { this.positionPanels(); // Initialize and load data into the new panel this.panels[panel.id].initialize(); @@ -531,12 +542,12 @@ class Plot { } panelsList.forEach((pid) => { - this.panels[pid].data_layer_ids_by_z_index.forEach((dlid) => { + this.panels[pid]._data_layer_ids_by_z_index.forEach((dlid) => { const layer = this.panels[pid].data_layers[dlid]; layer.destroyAllTooltips(); - delete layer.layer_state; - delete this.layout.state[layer.state_id]; + delete layer._layer_state; + delete this.layout.state[layer._state_id]; if (mode === 'reset') { layer._setDefaultState(); } @@ -553,42 +564,43 @@ class Plot { * @returns {Plot} */ removePanel(id) { - if (!this.panels[id]) { + const target_panel = this.panels[id]; + if (!target_panel) { throw new Error(`Unable to remove panel, ID not found: ${id}`); } // Hide all panel boundaries - this.panel_boundaries.hide(); + this._panel_boundaries.hide(); // Destroy all tooltips and state vars for all data layers on the panel this.clearPanelData(id); // Remove all panel-level HTML overlay elements - this.panels[id].loader.hide(); - this.panels[id].toolbar.destroy(true); - this.panels[id].curtain.hide(); + target_panel.loader.hide(); + target_panel.toolbar.destroy(true); + target_panel.curtain.hide(); // Remove the svg container for the panel if it exists - if (this.panels[id].svg.container) { - this.panels[id].svg.container.remove(); + if (target_panel.svg.container) { + target_panel.svg.container.remove(); } // Delete the panel and its presence in the plot layout and state - this.layout.panels.splice(this.panels[id].layout_idx, 1); + this.layout.panels.splice(target_panel._layout_idx, 1); delete this.panels[id]; delete this.layout.state[id]; // Update layout_idx values for all remaining panels this.layout.panels.forEach((panel_layout, idx) => { - this.panels[panel_layout.id].layout_idx = idx; + this.panels[panel_layout.id]._layout_idx = idx; }); // Remove the panel id from the y_index array - this.panel_ids_by_y_index.splice(this.panel_ids_by_y_index.indexOf(id), 1); + this._panel_ids_by_y_index.splice(this._panel_ids_by_y_index.indexOf(id), 1); this.applyPanelYIndexesToPanelLayouts(); // Call positionPanels() to keep panels from overlapping and ensure filling all available vertical space - if (this.initialized) { + if (this._initialized) { this.positionPanels(); // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip // positioning. TODO: make this additional call unnecessary. @@ -614,6 +626,8 @@ class Plot { * @callback externalDataCallback * @param {Object} new_data The body resulting from a data request. This represents the same information that would be passed to * a data layer making an equivalent request. + * @param {Object} plot A reference to the plot object. This can be useful for listeners that react to the + * structure of the data, instead of just displaying something. */ /** @@ -631,30 +645,74 @@ class Plot { * * @public * @listens event:data_rendered - * @param {String[]} fields An array of field names and transforms, in the same syntax used by a data layer. - * Different data sources should be prefixed by the namespace name. - * @param {externalDataCallback} success_callback Used defined function that is automatically called any time that - * new data is received by the plot. Receives two arguments: (data, plot). + * @listens event:data_from_layer * @param {Object} [opts] Options + * @param {String} [opts.from_layer=null] The ID string (`panel_id.layer_id`) of a specific data layer to be watched. + * @param {Object} [opts.namespace] An object specifying where to find external data. See data layer documentation for details. + * @param {Object} [opts.data_operations] An array of data operations. If more than one source of data is requested, + * this is usually required in order to specify dependency order and join operations. See data layer documentation for details. * @param {externalErrorCallback} [opts.onerror] User defined function that is automatically called if a problem * occurs during the data request or subsequent callback operations - * @param {boolean} [opts.discrete=false] Normally the callback will subscribe to the combined body from the chain, - * which may not be in a format that matches what the external callback wants to do. If discrete=true, returns the - * uncombined record info + * @param {externalDataCallback} success_callback Used defined function that is automatically called any time that + * new data is received by the plot. Receives two arguments: (data, plot). * @return {function} The newly created event listener, to allow for later cleanup/removal */ - subscribeToData(fields, success_callback, opts) { - opts = opts || {}; + subscribeToData(opts, success_callback) { + const { from_layer, namespace, data_operations, onerror } = opts; // Register an event listener that is notified whenever new data has been rendered - const error_callback = opts.onerror || function (err) { - console.log('An error occurred while acting on an external callback', err); + const error_callback = onerror || function (err) { + console.error('An error occurred while acting on an external callback', err); }; + if (from_layer) { + // Option 1: Subscribe to a data layer. Receive a copy of the exact data it receives; no need to duplicate NS or data operations code in two places. + const base_prefix = `${this.getBaseId()}.`; + // Allow users to provide either `plot.panel.layer`, or `panel.layer`. The latter usually leads to more reusable code. + const layer_target = from_layer.startsWith(base_prefix) ? from_layer : `${base_prefix}${from_layer}`; + + // Ensure that a valid layer exists to watch + let is_valid_layer = false; + for (let p of Object.values(this.panels)) { + is_valid_layer = Object.values(p.data_layers).some((d) => d.getBaseId() === layer_target); + if (is_valid_layer) { + break; + } + } + if (!is_valid_layer) { + throw new Error(`Could not subscribe to unknown data layer ${layer_target}`); + } + + const listener = (eventData) => { + if (eventData.data.layer !== layer_target) { + // Same event name fires for many layers; only fire success cb for the one layer we want + return; + } + try { + success_callback(eventData.data.content, this); + } catch (error) { + error_callback(error); + } + }; + + this.on('data_from_layer', listener); + return listener; + } + + // Second option: subscribe to an explicit list of fields and namespaces. This is useful if the same piece of + // data has to be displayed in multiple ways, eg if we just want an annotation (which is normally visualized + // in connection to some other visualization) + if (!namespace) { + throw new Error("subscribeToData must specify the desired data: either 'from_layer' or 'namespace' option"); + } + + const [entities, dependencies] = this.lzd.config_to_sources(namespace, data_operations); // Does not pass reference to initiator- we don't want external subscribers with the power to mutate the whole plot. const listener = () => { try { - this.lzd.getData(this.state, fields) - .then((new_data) => success_callback(opts.discrete ? new_data.discrete : new_data.body, this)) + // NOTE TO FUTURE SELF: since this event does something async and not tied to a returned promise, unit tests will behave strangely, + // even though this method totally works. Don't spend another hour scratching your head; this is the line to blame. + this.lzd.getData(this.state, entities, dependencies) + .then((new_data) => success_callback(new_data, this)) .catch(error_callback); } catch (error) { // In certain cases, errors are thrown before a promise can be generated, and LZ error display seems to rely on these errors bubbling up @@ -697,13 +755,13 @@ class Plot { // Generate requests for all panels given new state this.emit('data_requested'); - this.remap_promises = []; + this._remap_promises = []; this.loading_data = true; for (let id in this.panels) { - this.remap_promises.push(this.panels[id].reMap()); + this._remap_promises.push(this.panels[id].reMap()); } - return Promise.all(this.remap_promises) + return Promise.all(this._remap_promises) .catch((error) => { console.error(error); this.curtain.show(error.message || error); @@ -714,11 +772,11 @@ class Plot { this.toolbar.update(); // Apply panel-level state values - this.panel_ids_by_y_index.forEach((panel_id) => { + this._panel_ids_by_y_index.forEach((panel_id) => { const panel = this.panels[panel_id]; panel.toolbar.update(); // Apply data-layer-level state values - panel.data_layer_ids_by_z_index.forEach((data_layer_id) => { + panel._data_layer_ids_by_z_index.forEach((data_layer_id) => { panel.data_layers[data_layer_id].applyAllElementStatus(); }); }); @@ -792,12 +850,24 @@ class Plot { // eslint-disable-next-line no-self-assign parent.outerHTML = parent.outerHTML; - this.initialized = false; + this._initialized = false; this.svg = null; this.panels = null; } + /** + * Plots can change how data is displayed by layout mutations. In rare cases, such as swapping from one source of LD to another, + * these layout mutations won't be picked up instantly. This method notifies the plot to recalculate any cached properties, + * like data fetching logic, that might depend on initial layout. It does not trigger a re-render by itself. + * @public + */ + mutateLayout() { + Object.values(this.panels).forEach((panel) => { + Object.values(panel.data_layers).forEach((layer) => layer.mutateLayout()); + }); + } + /******* The private interface: methods only used by LocusZoom internals */ /** * Track whether the target panel can respond to mouse interaction events @@ -807,10 +877,11 @@ class Plot { */ _canInteract(panel_id) { panel_id = panel_id || null; + const { _interaction } = this; if (panel_id) { - return ((typeof this.interaction.panel_id == 'undefined' || this.interaction.panel_id === panel_id) && !this.loading_data); + return ((typeof _interaction.panel_id == 'undefined' || _interaction.panel_id === panel_id) && !this.loading_data); } else { - return !(this.interaction.dragging || this.interaction.zooming || this.loading_data); + return !(_interaction.dragging || _interaction.zooming || this.loading_data); } } @@ -865,7 +936,7 @@ class Plot { * @private */ applyPanelYIndexesToPanelLayouts () { - this.panel_ids_by_y_index.forEach((pid, idx) => { + this._panel_ids_by_y_index.forEach((pid, idx) => { this.panels[pid].layout.y_index = idx; }); } @@ -896,7 +967,6 @@ class Plot { * @returns {Plot} */ initializeLayout() { - // Sanity check layout values if (isNaN(this.layout.width) || this.layout.width <= 0) { throw new Error('Plot layout parameter `width` must be a positive number'); @@ -905,24 +975,10 @@ class Plot { // Backwards compatible check: there was previously a third option. Anything truthy should thus act as "responsive_resize: true" this.layout.responsive_resize = !!this.layout.responsive_resize; - // If this is a responsive layout then set a namespaced/unique onresize event listener on the window - if (this.layout.responsive_resize) { - const resize_listener = () => this.rescaleSVG(); - window.addEventListener('resize', resize_listener); - this.trackExternalListener(window, 'resize', resize_listener); - - // Forcing one additional setDimensions() call after the page is loaded clears up - // any disagreements between the initial layout and the loaded responsive container's size - const load_listener = () => this.setDimensions(); - window.addEventListener('load', load_listener); - this.trackExternalListener(window, 'load', load_listener); - } - // Add panels this.layout.panels.forEach((panel_layout) => { this.addPanel(panel_layout); }); - return this; } @@ -955,7 +1011,7 @@ class Plot { } // Resize/reposition panels to fit, update proportional origins if necessary let y_offset = 0; - this.panel_ids_by_y_index.forEach((panel_id) => { + this._panel_ids_by_y_index.forEach((panel_id) => { const panel = this.panels[panel_id]; const panel_width = this.layout.width; // In this block, we are passing explicit dimensions that might require rescaling all panels at once @@ -981,8 +1037,8 @@ class Plot { } // If the plot has been initialized then trigger some necessary render functions - if (this.initialized) { - this.panel_boundaries.position(); + if (this._initialized) { + this._panel_boundaries.position(); this.toolbar.update(); this.curtain.update(); this.loader.update(); @@ -1007,27 +1063,28 @@ class Plot { // Proportional heights for newly added panels default to null unless explicitly set, so determine appropriate // proportional heights for all panels with a null value from discretely set dimensions. // Likewise handle default nulls for proportional widths, but instead just force a value of 1 (full width) - for (let id in this.panels) { - if (this.panels[id].layout.interaction.x_linked) { - x_linked_margins.left = Math.max(x_linked_margins.left, this.panels[id].layout.margin.left); - x_linked_margins.right = Math.max(x_linked_margins.right, this.panels[id].layout.margin.right); + for (let panel of Object.values(this.panels)) { + if (panel.layout.interaction.x_linked) { + x_linked_margins.left = Math.max(x_linked_margins.left, panel.layout.margin.left); + x_linked_margins.right = Math.max(x_linked_margins.right, panel.layout.margin.right); } } // Update origins on all panels without changing plot-level dimensions yet // Also apply x-linked margins to x-linked panels, updating widths as needed let y_offset = 0; - this.panel_ids_by_y_index.forEach((panel_id) => { + this._panel_ids_by_y_index.forEach((panel_id) => { const panel = this.panels[panel_id]; + const panel_layout = panel.layout; panel.setOrigin(0, y_offset); y_offset += this.panels[panel_id].layout.height; - if (panel.layout.interaction.x_linked) { - const delta = Math.max(x_linked_margins.left - panel.layout.margin.left, 0) - + Math.max(x_linked_margins.right - panel.layout.margin.right, 0); - panel.layout.width += delta; - panel.layout.margin.left = x_linked_margins.left; - panel.layout.margin.right = x_linked_margins.right; - panel.layout.cliparea.origin.x = x_linked_margins.left; + if (panel_layout.interaction.x_linked) { + const delta = Math.max(x_linked_margins.left - panel_layout.margin.left, 0) + + Math.max(x_linked_margins.right - panel_layout.margin.right, 0); + panel_layout.width += delta; + panel_layout.margin.left = x_linked_margins.left; + panel_layout.margin.right = x_linked_margins.right; + panel_layout.cliparea.origin.x = x_linked_margins.left; } }); @@ -1036,11 +1093,11 @@ class Plot { this.setDimensions(); // Set dimensions on all panels using newly set plot-level dimensions and panel-level proportional dimensions - this.panel_ids_by_y_index.forEach((panel_id) => { + this._panel_ids_by_y_index.forEach((panel_id) => { const panel = this.panels[panel_id]; panel.setDimensions( this.layout.width, - panel.layout.height + panel.layout.height, ); }); @@ -1054,10 +1111,34 @@ class Plot { * @returns {Plot} */ initialize() { - // Ensure proper responsive class is present on the containing node if called for if (this.layout.responsive_resize) { d3.select(this.container).classed('lz-container-responsive', true); + + // If this is a responsive layout then set a namespaced/unique onresize event listener on the window + const resize_listener = () => window.requestAnimationFrame(() => this.rescaleSVG()); + + window.addEventListener('resize', resize_listener); + this.trackExternalListener(window, 'resize', resize_listener); + + // Many libraries collapse/hide tab widgets using display:none, which doesn't trigger the resize listener + // High threshold: Don't fire listeners on every 1px change, but allow this to work if the plot position is a bit cockeyed + if (typeof IntersectionObserver !== 'undefined') { // don't do this in old browsers + const options = { root: document.documentElement, threshold: 0.9 }; + const observer = new IntersectionObserver((entries, observer) => { + if (entries.some((entry) => entry.intersectionRatio > 0)) { + this.rescaleSVG(); + } + }, options); + // IntersectionObservers will be cleaned up when DOM node removed; no need to track them for manual cleanup + observer.observe(this.container); + } + + // Forcing one additional setDimensions() call after the page is loaded clears up + // any disagreements between the initial layout and the loaded responsive container's size + const load_listener = () => this.setDimensions(); + window.addEventListener('load', load_listener); + this.trackExternalListener(window, 'load', load_listener); } // Create an element/layer for containing mouse guides @@ -1071,7 +1152,7 @@ class Plot { const mouse_guide_horizontal_svg = mouse_guide_svg.append('rect') .attr('class', 'lz-mouse_guide-horizontal') .attr('y', -1); - this.mouse_guide = { + this._mouse_guide = { svg: mouse_guide_svg, vertical: mouse_guide_vertical_svg, horizontal: mouse_guide_horizontal_svg, @@ -1083,7 +1164,7 @@ class Plot { this.loader = generateLoader.call(this); // Create the panel_boundaries object with show/position/hide methods - this.panel_boundaries = { + this._panel_boundaries = { parent: this, hide_timeout: null, showing: false, @@ -1095,7 +1176,7 @@ class Plot { if (!this.showing && !this.parent.curtain.showing) { this.showing = true; // Loop through all panels to create a horizontal boundary for each - this.parent.panel_ids_by_y_index.forEach((panel_id, panel_idx) => { + this.parent._panel_ids_by_y_index.forEach((panel_id, panel_idx) => { const selector = d3.select(this.parent.svg.node().parentNode).insert('div', '.lz-data_layer-tooltip') .attr('class', 'lz-panel-boundary') .attr('title', 'Resize panel'); @@ -1109,15 +1190,15 @@ class Plot { }); panel_resize_drag.on('drag', () => { // First set the dimensions on the panel we're resizing - const this_panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]]; + const this_panel = this.parent.panels[this.parent._panel_ids_by_y_index[panel_idx]]; const original_panel_height = this_panel.layout.height; this_panel.setDimensions(this.parent.layout.width, this_panel.layout.height + d3.event.dy); const panel_height_change = this_panel.layout.height - original_panel_height; // Next loop through all panels. // Update proportional dimensions for all panels including the one we've resized using discrete heights. // Reposition panels with a greater y-index than this panel to their appropriate new origin. - this.parent.panel_ids_by_y_index.forEach((loop_panel_id, loop_panel_idx) => { - const loop_panel = this.parent.panels[this.parent.panel_ids_by_y_index[loop_panel_idx]]; + this.parent._panel_ids_by_y_index.forEach((loop_panel_id, loop_panel_idx) => { + const loop_panel = this.parent.panels[this.parent._panel_ids_by_y_index[loop_panel_idx]]; if (loop_panel_idx > panel_idx) { loop_panel.setOrigin(loop_panel.layout.origin.x, loop_panel.layout.origin.y + panel_height_change); loop_panel.toolbar.position(); @@ -1128,7 +1209,7 @@ class Plot { this.position(); }); selector.call(panel_resize_drag); - this.parent.panel_boundaries.selectors.push(selector); + this.parent._panel_boundaries.selectors.push(selector); }); // Create a corner boundary / resize element on the bottom-most panel that resizes the entire plot const corner_selector = d3.select(this.parent.svg.node().parentNode) @@ -1154,7 +1235,7 @@ class Plot { this.parent.setDimensions(this.parent.layout.width + d3.event.dx, this.parent._total_height + d3.event.dy); }); corner_selector.call(corner_drag); - this.parent.panel_boundaries.corner_selector = corner_selector; + this.parent._panel_boundaries.corner_selector = corner_selector; } return this.position(); }, @@ -1165,7 +1246,7 @@ class Plot { // Position panel boundaries const plot_page_origin = this.parent._getPageOrigin(); this.selectors.forEach((selector, panel_idx) => { - const panel = this.parent.panels[this.parent.panel_ids_by_y_index[panel_idx]]; + const panel = this.parent.panels[this.parent._panel_ids_by_y_index[panel_idx]]; const panel_page_origin = panel._getPageOrigin(); const left = plot_page_origin.x; const top = panel_page_origin.y + panel.layout.height - 12; @@ -1206,12 +1287,12 @@ class Plot { if (this.layout.panel_boundaries) { d3.select(this.svg.node().parentNode) .on(`mouseover.${this.id}.panel_boundaries`, () => { - clearTimeout(this.panel_boundaries.hide_timeout); - this.panel_boundaries.show(); + 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(); + this._panel_boundaries.hide_timeout = setTimeout(() => { + this._panel_boundaries.hide(); }, 300); }); } @@ -1228,13 +1309,13 @@ class Plot { const namespace = `.${this.id}`; if (this.layout.mouse_guide) { const mouseout_mouse_guide = () => { - this.mouse_guide.vertical.attr('x', -1); - this.mouse_guide.horizontal.attr('y', -1); + this._mouse_guide.vertical.attr('x', -1); + this._mouse_guide.horizontal.attr('y', -1); }; const mousemove_mouse_guide = () => { const coords = d3.mouse(this.svg.node()); - this.mouse_guide.vertical.attr('x', coords[0]); - this.mouse_guide.horizontal.attr('y', coords[1]); + this._mouse_guide.vertical.attr('x', coords[0]); + this._mouse_guide.horizontal.attr('y', coords[1]); }; this.svg .on(`mouseout${namespace}-mouse_guide`, mouseout_mouse_guide) @@ -1245,15 +1326,16 @@ class Plot { this.stopDrag(); }; const mousemove = () => { - if (this.interaction.dragging) { + const { _interaction } = this; + if (_interaction.dragging) { const coords = d3.mouse(this.svg.node()); if (d3.event) { d3.event.preventDefault(); } - this.interaction.dragging.dragged_x = coords[0] - this.interaction.dragging.start_x; - this.interaction.dragging.dragged_y = coords[1] - this.interaction.dragging.start_y; - this.panels[this.interaction.panel_id].render(); - this.interaction.linked_panel_ids.forEach((panel_id) => { + _interaction.dragging.dragged_x = coords[0] - _interaction.dragging.start_x; + _interaction.dragging.dragged_y = coords[1] - _interaction.dragging.start_y; + this.panels[_interaction.panel_id].render(); + _interaction.linked_panel_ids.forEach((panel_id) => { this.panels[panel_id].render(); }); } @@ -1295,7 +1377,7 @@ class Plot { this.applyState({ lz_match_value: to_send }); }); - this.initialized = true; + this._initialized = true; // An extra call to setDimensions with existing discrete dimensions fixes some rounding errors with tooltip // positioning. TODO: make this additional call unnecessary. @@ -1337,7 +1419,7 @@ class Plot { } const coords = d3.mouse(this.svg.node()); - this.interaction = { + this._interaction = { panel_id: panel.id, linked_panel_ids: panel.getLinkedPanelIds(axis), dragging: { @@ -1362,22 +1444,22 @@ class Plot { * @returns {Plot} */ stopDrag() { - - if (!this.interaction.dragging) { + const { _interaction } = this; + if (!_interaction.dragging) { return this; } - if (typeof this.panels[this.interaction.panel_id] != 'object') { - this.interaction = {}; + if (typeof this.panels[_interaction.panel_id] != 'object') { + this._interaction = {}; return this; } - const panel = this.panels[this.interaction.panel_id]; + const panel = this.panels[_interaction.panel_id]; // Helper function to find the appropriate axis layouts on child data layers // Once found, apply the extent as floor/ceiling and remove all other directives // This forces all associated axes to conform to the extent generated by a drag action const overrideAxisLayout = (axis, axis_number, extent) => { - panel.data_layer_ids_by_z_index.forEach((id) => { + panel._data_layer_ids_by_z_index.forEach((id) => { const axis_layout = panel.data_layers[id].layout[`${axis}_axis`]; if (axis_layout.axis === axis_number) { axis_layout.floor = extent[0]; @@ -1390,24 +1472,24 @@ class Plot { }); }; - switch (this.interaction.dragging.method) { + switch (_interaction.dragging.method) { case 'background': case 'x_tick': - if (this.interaction.dragging.dragged_x !== 0) { + if (_interaction.dragging.dragged_x !== 0) { overrideAxisLayout('x', 1, panel.x_extent); this.applyState({ start: panel.x_extent[0], end: panel.x_extent[1] }); } break; case 'y1_tick': case 'y2_tick': - if (this.interaction.dragging.dragged_y !== 0) { - const y_axis_number = parseInt(this.interaction.dragging.method[1]); + if (_interaction.dragging.dragged_y !== 0) { + const y_axis_number = parseInt(_interaction.dragging.method[1]); overrideAxisLayout('y', y_axis_number, panel[`y${y_axis_number}_extent`]); } break; } - this.interaction = {}; + this._interaction = {}; this.svg.style('cursor', null); return this; diff --git a/esm/components/toolbar/index.js b/esm/components/toolbar/index.js index b3f25768..0354dcf0 100644 --- a/esm/components/toolbar/index.js +++ b/esm/components/toolbar/index.js @@ -1,4 +1,4 @@ -import widgets from '../../registry/widgets'; +import WIDGETS from '../../registry/widgets'; import * as d3 from 'd3'; /** @@ -60,21 +60,14 @@ class Toolbar { */ initialize() { // Parse layout to generate widget instances - // In LZ 0.12, `dashboard.components` was renamed to `toolbar.widgets`. Preserve a backwards-compatible alias. - const options = (this.parent.layout.dashboard && this.parent.layout.dashboard.components) || this.parent.layout.toolbar.widgets; + const options = this.parent.layout.toolbar.widgets; if (Array.isArray(options)) { options.forEach((layout) => { - try { - const widget = widgets.create(layout.type, layout, this); - this.widgets.push(widget); - } catch (e) { - console.warn('Failed to create widget'); - console.error(e); - } + this.addWidget(layout); }); } - // Add mouseover event handlers to show/hide panel toolbar + // Add mouseover event handlers to show/hide panel toolbar (plot toolbar will always be shown) if (this.type === 'panel') { d3.select(this.parent.parent.svg.node().parentNode) .on(`mouseover.${this.id}`, () => { @@ -93,6 +86,26 @@ class Toolbar { return this; } + /** + * Add a new widget to the toolbar. + * FIXME: Kludgy to use. In the very rare cases where a widget is added dynamically, the caller will need to: + * - add the widget to plot.layout.toolbar.widgets, AND calling it with the same object reference here. + * - call widget.show() to ensure that the widget is initialized and rendered correctly + * When creating an existing plot defined in advance, neither of these actions is needed and so we don't do this by default. + * @param {Object} layout The layout object describing the desired widget + * @returns {layout.type} + */ + addWidget(layout) { + try { + const widget = WIDGETS.create(layout.type, layout, this); + this.widgets.push(widget); + return widget; + } catch (e) { + console.warn('Failed to create widget'); + console.error(e); + } + } + /** * Whether to persist the toolbar. Returns true if at least one widget should persist, or if the panel is engaged * in an active drag event. @@ -108,7 +121,7 @@ class Toolbar { persist = persist || widget.shouldPersist(); }); // Persist if in a parent drag event - persist = persist || (this.parent_plot.panel_boundaries.dragging || this.parent_plot.interaction.dragging); + persist = persist || (this.parent_plot._panel_boundaries.dragging || this.parent_plot._interaction.dragging); return !!persist; } diff --git a/esm/components/toolbar/widgets.js b/esm/components/toolbar/widgets.js index 32c4b886..eace0a5f 100644 --- a/esm/components/toolbar/widgets.js +++ b/esm/components/toolbar/widgets.js @@ -1142,7 +1142,7 @@ class MovePanelUp extends BaseWidget { class MovePanelDown extends BaseWidget { update () { if (this.button) { - const is_at_bottom = (this.parent_panel.layout.y_index === this.parent_plot.panel_ids_by_y_index.length - 1); + const is_at_bottom = (this.parent_panel.layout.y_index === this.parent_plot._panel_ids_by_y_index.length - 1); this.button.disable(is_at_bottom); return this; } diff --git a/esm/data/adapters.js b/esm/data/adapters.js index deca8120..7f964908 100644 --- a/esm/data/adapters.js +++ b/esm/data/adapters.js @@ -22,8 +22,8 @@ * * ``` * const data_sources = new LocusZoom.DataSources(); - * data_sources.add("trait1", ["AssociationLZ", {url: "http://server.com/api/single/", params: {source: 1}}]); - * data_sources.add("trait2", ["AssociationLZ", {url: "http://server.com/api/single/", params: {source: 2}}]); + * data_sources.add("trait1", ["AssociationLZ", { url: "http://server.com/api/single/", source: 1 }]); + * data_sources.add("trait2", ["AssociationLZ", { url: "http://server.com/api/single/", source: 2 }]); * ``` * * These data sources are then passed to the plot when data is to be rendered: @@ -32,170 +32,188 @@ * @module LocusZoom_Adapters */ -function validateBuildSource(class_name, build, source) { - // Build OR Source, not both - if ((build && source) || !(build || source)) { - throw new Error(`${class_name} must provide a parameter specifying either "build" or "source". It should not specify both.`); - } - // If the build isn't recognized, our APIs can't transparently select a source to match - if (build && !['GRCh37', 'GRCh38'].includes(build)) { - throw new Error(`${class_name} must specify a valid genome build number`); - } -} - +import {BaseUrlAdapter} from './undercomplicate'; -// NOTE: Custom adapaters are annotated with `see` instead of `extend` throughout this file, to avoid clutter in the developer API docs. -// Most people using LZ data sources will never instantiate a class directly and certainly won't be calling internal -// methods, except when implementing a subclass. For most LZ users, it's usually enough to acknowledge that the -// private API methods exist in the base class. +import {parseMarker} from '../helpers/parse'; /** - * Base class for LocusZoom data sources (any). See also: BaseApiAdapter for requests from a remote URL. + * Replaced with the BaseLZAdapter class. * @public + * @deprecated */ class BaseAdapter { - /** - * @param {object} config Configuration options - */ - constructor(config) { - /** - * Whether to enable caching (true for most data adapters) - * @private - * @member {Boolean} - */ - this._enableCache = true; - this._cachedKey = null; - - // Almost all LZ sources are "region based". Cache the region requested and use it to determine whether - // the cache would satisfy the request. - this._cache_pos_start = null; - this._cache_pos_end = null; - - /** - * Whether this adapter type is dependent on previous requests- for example, the LD source cannot annotate - * association data if no data was found for that region. - * @private - * @member {boolean} - */ - this.__dependentSource = false; - - // Parse configuration options - this.parseInit(config); + constructor() { + throw new Error('The "BaseAdapter" and "BaseApiAdapter" classes have been replaced in LocusZoom 0.14. See migration guide for details.'); } +} - /** - * Parse configuration used to create the instance. Many custom sources will override this method to suit their - * needs (eg specific config options, or for sources that do not retrieve data from a URL) - * @protected - * @param {String|Object} config Basic configuration- either a url, or a config object - * @param {String} [config.url] The datasource URL - * @param {String} [config.params] Initial config params for the datasource - */ - parseInit(config) { - /** - * @private - * @member {Object} - */ - this.params = config.params || {}; +/** + * Removed class for LocusZoom data adapters that receive their data over the web. Adds default config parameters + * (and potentially other behavior) that are relevant to URL-based requests. + * @extends module:LocusZoom_Adapters~BaseAdapter + * @deprecated + * @param {string} config.url The URL for the remote dataset. By default, most adapters perform a GET request. + * @inheritDoc + */ +class BaseApiAdapter extends BaseAdapter {} + + +/** + * @extends module:undercomplicate.BaseUrlAdapter + * @inheritDoc + */ +class BaseLZAdapter extends BaseUrlAdapter { + /** + * @param [config.cache_enabled=true] + * @param [config.cache_size=3] + * @param [config.url] + * @param [config.prefix_namespace=true] Whether to modify the API response by prepending namespace to each field name. + * Most adapters will do this by default, so that each field is unambiguously defined based on where it comes from. (this helps to disambiguate two providers that return similar field names, like assoc:variant and catalog:variant) + * Typically, this is only disabled if the response payload is very unusual + * @param {String[]} [config.limit_fields=null] If an API returns far more data than is needed, this can be used to simplify + * the payload by excluding unused fields. This can help to reduce memory usage for really big server responses like LD. + */ + constructor(config = {}) { + if (config.params) { + // Backwards-compat: prevent old sources from breaking in subtle ways because config options are no longer split between two places. + console.warn('Deprecation warning: all options in "config.params" should now be specified as top level keys.'); + Object.assign(config, config.params || {}); + delete config.params; // fields are moved, not just copied in both places; Custom code will need to reflect new reality! + } + super(config); + + // Prefix the namespace for this source to all fieldnames: id -> assoc.id + // This is useful for almost all layers because the layout object says where to find every field, exactly. + // For some very complex data structure- mainly the Genes API payload- the datalayer might want to operate on + // that complex set of fields directly. Disable _prefix_namespace to get field names as they appear + // in the response. (gene_name instead of genes.gene_name) + const { prefix_namespace = true, limit_fields } = config; + this._prefix_namespace = prefix_namespace; + this._limit_fields = limit_fields ? new Set(limit_fields) : false; // Optional and typically only used for very standard datasets like LD or catalog, where API returns >> what is displayed. People want to show their own custom annos for assoc plots pretty often, so the most-often-customized adapters don't specify limit_fields } /** - * A unique identifier that indicates whether cached data is valid for this request. For most sources using GET - * requests to a REST API, this is usually the region requested. Some sources will append additional params to define the request. - * - * This means that to change caching behavior, both the URL and the cache key may need to be updated. However, - * it allows most datasources to skip an extra network request when zooming in. - * @protected - * @param {Object} state Information available in plot.state (chr, start, end). Sometimes used to inject globally - * available information that influences the request being made. - * @param {Object} chain The data chain from previous requests made in a sequence. - * @param fields - * @returns {String} + * Determine how a particular request will be identified in cache. Most LZ requests are region based, + * so the default is a string concatenation of `chr_start_end`. This adapter is "region aware"- if the user + * zooms in, it won't trigger a network request because we alread have the data needed. + * @param options Receives plot.state plus any other request options defined by this source + * @returns {string} + * @public */ - getCacheKey(state, chain, fields) { - // Most region sources, by default, will cache the largest region that satisfies the request: zooming in - // should be satisfied via the cache, but pan or region change operations will cause a network request - - // Some adapters rely on values set in chain.header during the getURL call. (eg, the LD source uses - // this to find the LD refvar) Calling this method is a backwards-compatible way of ensuring that value is set, - // even on a cache hit in which getURL otherwise wouldn't be called. - // Some of the adapters that rely on this behavior are user-defined, hence compatibility hack - this.getURL(state, chain, fields); - - const cache_pos_chr = state.chr; - const {_cache_pos_start, _cache_pos_end} = this; - if (_cache_pos_start && state.start >= _cache_pos_start && _cache_pos_end && state.end <= _cache_pos_end ) { - return `${cache_pos_chr}_${_cache_pos_start}_${_cache_pos_end}`; - } else { - return `${state.chr}_${state.start}_${state.end}`; + _getCacheKey(options) { + // Most LZ adapters are fetching REGION data, and it makes sense to treat zooming as a cache hit by default + let {chr, start, end} = options; // Current view: plot.state + + // Does a prior cache hit qualify as a superset of the ROI? + const superset = this._cache.find(({metadata: md}) => chr === md.chr && start >= md.start && end <= md.end); + if (superset) { + ({ chr, start, end } = superset.metadata); } + + // The default cache key is region-based, and this method only returns the region-based part of the cache hit + // That way, methods that override the key can extend the base value and still get the benefits of region-overlap-check + options._cache_meta = { chr, start, end }; + return `${chr}_${start}_${end}`; } /** - * Stub: build the URL for any requests made by this source. - * @protected - */ - getURL(state, chain, fields) { - return this.url; + * Add the "local namespace" as a prefix for every field returned for this request. Eg if the association api + * returns a field called variant, and the source is referred to as "assoc" within a particular data layer, then + * the returned records will have a field called "assoc:variant" + * + * @param records + * @param options + * @returns {*} + * @public + */ + _postProcessResponse(records, options) { + if (!this._prefix_namespace || !Array.isArray(records)) { + return records; + } + + // Transform fieldnames to include the namespace name as a prefix. For example, a data layer that asks for + // assoc data might see "variant" as "assoc.variant" + const { _limit_fields } = this; + const { _provider_name } = options; + + return records.map((row) => { + return Object.entries(row).reduce( + (acc, [label, value]) => { + // Rename API fields to format `namespace:fieldname`. If an adapter specifies limit_fields, then remove any unused API fields from the final payload. + if (!_limit_fields || _limit_fields.has(label)) { + acc[`${_provider_name}:${label}`] = value; + } + return acc; + }, + {}, + ); + }); } /** - * Perform a network request to fetch data for this source. This is usually the method that is used to override - * when defining how to retrieve data. - * @protected - * @param {Object} state The state of the parent plot - * @param chain - * @param fields - * @returns {Promise} + * Convenience method, manually called in LZ sources that deal with dependent data. + * + * In the last step of fetching data, LZ adds a prefix to each field name. + * This means that operations like "build query based on prior data" can't just ask for "log_pvalue" because + * they are receiving "assoc:log_pvalue" or some such unknown prefix. + * + * This helper lets us use dependent data more easily. Not every adapter needs to use this method. + * + * @param {Object} a_record One record (often the first one in a set of records) + * @param {String} fieldname The desired fieldname, eg "log_pvalue" */ - fetchRequest(state, chain, fields) { - const url = this.getURL(state, chain, fields); - return fetch(url).then((response) => { - if (!response.ok) { - throw new Error(response.statusText); - } - return response.text(); - }); + _findPrefixedKey(a_record, fieldname) { + const suffixer = new RegExp(`:${fieldname}$`); + const match = Object.keys(a_record).find((key) => suffixer.test(key)); + if (!match) { + throw new Error(`Could not locate the required key name: ${fieldname} in dependent data`); + } + return match; } +} + +/** + * The base adapter for the UMich Portaldev API server. This adds a few custom behaviors that handle idiosyncrasies + * of one particular web server. + * @extends module:LocusZoom_Adapters~BaseLZAdapter + * @inheritDoc + */ +class BaseUMAdapter extends BaseLZAdapter { /** - * Gets the data for just this source, typically via a network request (but using cache where possible) - * - * For most use cases, it is better to override `fetchRequest` instead, to avoid bypassing the cache mechanism - * by accident. - * @protected - * @return {Promise} + * @param {Object} config + * @param {String} [config.build] The genome build to be used by all requests for this adapter. (UMich APIs are all genome build aware). "GRCh37" or "GRCh38" */ - getRequest(state, chain, fields) { - let req; - const cacheKey = this.getCacheKey(state, chain, fields); + constructor(config = {}) { + super(config); + // The UM portaldev API accepts an (optional) parameter "genome_build" + this._genome_build = config.genome_build || config.build; + } - if (this._enableCache && typeof(cacheKey) !== 'undefined' && cacheKey === this._cachedKey) { - req = Promise.resolve(this._cachedResponse); // Resolve to the value of the current promise - } else { - req = this.fetchRequest(state, chain, fields); - if (this._enableCache) { - this._cachedKey = cacheKey; - this._cache_pos_start = state.start; - this._cache_pos_end = state.end; - this._cachedResponse = req; - } + _validateBuildSource(build, source) { + // Build OR Source, not both + if ((build && source) || !(build || source)) { + throw new Error(`${this.constructor.name} must provide a parameter specifying either "build" or "source". It should not specify both.`); + } + // If the build isn't recognized, our APIs can't transparently select a source to match + if (build && !['GRCh37', 'GRCh38'].includes(build)) { + throw new Error(`${this.constructor.name} must specify a valid 'genome_build'`); } - return req; } + // Special behavior for the UM portaldev API: col -> row format normalization /** - * Ensure the server response is in a canonical form, an array of one object per record. [ {field: oneval} ]. - * If the server response contains columns, reformats the response from {column1: [], column2: []} to the above. - * - * Does not apply namespacing, transformations, or field extraction. - * - * May be overridden by data adapters that inherently return more complex payloads, or that exist to annotate other - * sources (eg, if the payload provides extra data rather than a series of records). - * @protected - * @param {Object[]|Object} data The original parsed server response + * Some endpoints in the UM portaldev API returns columns of data, rather than rows. Convert the response to record objects, each row of a table being represented as an object of {field:value} pairs. + * @param response_text + * @param options + * @returns {Object[]} + * @public */ - normalizeResponse(data) { + _normalizeResponse(response_text, options) { + let data = super._normalizeResponse(...arguments); + // Most portaldev endpoints (though not all) store the desired response in just one specific part of the payload + data = data.data || data; + if (Array.isArray(data)) { // Already in the desired form return data; @@ -212,7 +230,7 @@ class BaseAdapter { throw new Error(`${this.constructor.name} expects a response in which all arrays of data are the same length`); } - // Go down the rows, and create an object for each record + // Go down the columns, and create an object for each row record const records = []; const fields = Object.keys(data); for (let i = 0; i < N; i++) { @@ -224,568 +242,35 @@ class BaseAdapter { } return records; } - - /** - * Hook to post-process the data returned by this source with new, additional behavior. - * (eg cleaning up API values or performing complex calculations on the returned data) - * - * @protected - * @param {Object[]} records The parsed data from the source (eg standardized api response) - * @param {Object} chain The data chain object. For example, chain.headers may provide useful annotation metadata - * @returns {Object[]|Promise} The modified set of records - */ - annotateData(records, chain) { - // Default behavior: no transformations - return records; - } - - /** - * Clean up the server records for use by datalayers: extract only certain fields, with the specified names. - * Apply per-field transformations as appropriate. - * - * This hook can be overridden, eg to create a source that always returns all records and ignores the "fields" array. - * This is particularly common for sources at the end of a chain- many "dependent" sources do not allow - * cherry-picking individual fields, in which case by **convention** the fields array specifies "last_source_name:all" - * - * @protected - * @param {Object[]} data One record object per element - * @param {String[]} fields The names of fields to extract (as named in the source data). Eg "afield" - * @param {String[]} outnames How to represent the source fields in the output. Eg "namespace:afield|atransform" - * @param {function[]} trans An array of transformation functions (if any). One function per data element, or null. - * @protected - */ - extractFields (data, fields, outnames, trans) { - //intended for an array of objects - // [ {"id":1, "val":5}, {"id":2, "val":10}] - // Since a number of sources exist that do not obey this format, we will provide a convenient pass-through - if (!Array.isArray(data)) { - return data; - } - - if (!data.length) { - // Sometimes there are regions that just don't have data- this should not trigger a missing field error message! - return data; - } - - const fieldFound = []; - for (let k = 0; k < fields.length; k++) { - fieldFound[k] = 0; - } - - const records = data.map(function (item) { - const output_record = {}; - for (let j = 0; j < fields.length; j++) { - let val = item[fields[j]]; - if (typeof val != 'undefined') { - fieldFound[j] = 1; - } - if (trans && trans[j]) { - val = trans[j](val); - } - output_record[outnames[j]] = val; - } - return output_record; - }); - fieldFound.forEach(function(v, i) { - if (!v) { - throw new Error(`field ${fields[i]} not found in response for ${outnames[i]}`); - } - }); - return records; - } - - /** - * Combine records from this source with others in the chain to yield final chain body. - * Handles merging this data with other sources (if applicable). - * - * @protected - * @param {Object[]} data The data That would be returned from this source alone - * @param {Object} chain The data chain built up during previous requests - * @param {String[]} fields - * @param {String[]} outnames - * @param {String[]} trans - * @return {Promise|Object[]} The new chain body - */ - combineChainBody(data, chain, fields, outnames, trans) { - return data; - } - - /** - * Coordinates the work of parsing a response and returning records. This is broken into 4 steps, which may be - * overridden separately for fine-grained control. Each step can return either raw data or a promise. - * - * @see {module:LocusZoom_Adapters~BaseAdapter#normalizeResponse} - * @see {module:LocusZoom_Adapters~BaseAdapter#annotateData} - * @see {module:LocusZoom_Adapters~BaseAdapter#extractFields} - * @see {module:LocusZoom_Adapters~BaseAdapter#combineChainBody} - * @protected - * - * @param {String|Object} resp The raw data associated with the response - * @param {Object} chain The combined parsed response data from this and all other requests made in the chain - * @param {String[]} fields Array of requested field names (as they would appear in the response payload) - * @param {String[]} outnames Array of field names as they will be represented in the data returned by this source, - * including the namespace. This must be an array with the same length as `fields` - * @param {Function[]} trans The collection of transformation functions to be run on selected fields. - * This must be an array with the same length as `fields` - * @returns {Promise} A promise that resolves to an object containing - * request metadata (`headers: {}`), the consolidated data for plotting (`body: []`), and the individual responses that would be - * returned by each source in the chain in isolation (`discrete: {}`) - */ - parseResponse (resp, chain, fields, outnames, trans) { - const source_id = this.source_id || this.constructor.name; - if (!chain.discrete) { - chain.discrete = {}; - } - - const json = typeof resp == 'string' ? JSON.parse(resp) : resp; - - // Perform the 4 steps of parsing the payload and return a combined chain object - return Promise.resolve(this.normalizeResponse(json.data || json)) - .then((standardized) => { - // Perform calculations on the data from just this source - return Promise.resolve(this.annotateData(standardized, chain)); - }).then((data) => { - return Promise.resolve(this.extractFields(data, fields, outnames, trans)); - }).then((one_source_body) => { - // Store a copy of the data that would be returned by parsing this source in isolation (and taking the - // fields array into account). This is useful when we want to re-use the source output in many ways. - chain.discrete[source_id] = one_source_body; - return Promise.resolve(this.combineChainBody(one_source_body, chain, fields, outnames, trans)); - }).then((new_body) => { - return { header: chain.header || {}, discrete: chain.discrete, body: new_body }; - }); - } - - /** - * Fetch the data from the specified data adapter, and apply transformations requested by an external consumer. - * This is the public-facing datasource method that will most be called by the plot, but custom data adapters will - * almost never want to override this method directly- more specific hooks are provided to control individual pieces - * of the request lifecycle. - * - * @private - * @param {Object} state The current "state" of the plot, such as chromosome and start/end positions - * @param {String[]} fields Array of field names that the plot has requested from this data adapter. (without the "namespace" prefix) - * @param {String[]} outnames Array describing how the output data should refer to this field. This represents the - * originally requested field name, including the namespace. This must be an array with the same length as `fields` - * @param {Function[]} trans The collection of transformation functions to be run on selected fields. - * This must be an array with the same length as `fields` - * @returns {function} A callable operation that can be used as part of the data chain - */ - getData(state, fields, outnames, trans) { - if (this.preGetData) { // TODO try to remove this method if at all possible - const pre = this.preGetData(state, fields, outnames, trans); - if (this.pre) { - state = pre.state || state; - fields = pre.fields || fields; - outnames = pre.outnames || outnames; - trans = pre.trans || trans; - } - } - - return (chain) => { - if (this.__dependentSource && chain && chain.body && !chain.body.length) { - // A "dependent" source should not attempt to fire a request if there is no data for it to act on. - // Therefore, it should simply return the previous data chain. - return Promise.resolve(chain); - } - - return this.getRequest(state, chain, fields).then((resp) => { - return this.parseResponse(resp, chain, fields, outnames, trans); - }); - }; - } } -/** - * Base class for LocusZoom data adapters that receive their data over the web. Adds default config parameters - * (and potentially other behavior) that are relevant to URL-based requests. - * @extends module:LocusZoom_Adapters~BaseAdapter - * @param {string} config.url The URL for the remote dataset. By default, most adapters perform a GET request. - * @inheritDoc - */ -class BaseApiAdapter extends BaseAdapter { - parseInit(config) { - super.parseInit(config); - - /** - * @private - * @member {String} - */ - this.url = config.url; - if (!this.url) { - throw new Error('Source not initialized with required URL'); - } - } -} /** * Retrieve Association Data from the LocusZoom/ Portaldev API (or compatible). Defines how to make a request * to a specific REST API. * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter - * @param {string} config.url The base URL for the remote data. - * @param {object} config.params - * @param [config.params.sort=false] Whether to sort the association data (by an assumed field named "position"). This - * is primarily a site-specific workaround for a particular LZ usage; we encourage apis to sort by position before returning - * data to the browser. - * @param [config.params.source] The ID of the GWAS dataset to use for this request, as matching the API backend - */ -class AssociationLZ extends BaseApiAdapter { - preGetData (state, fields, outnames, trans) { - // TODO: Modify internals to see if we can go without this method - const id_field = this.params.id_field || 'id'; - [id_field, 'position'].forEach(function(x) { - if (!fields.includes(x)) { - fields.unshift(x); - outnames.unshift(x); - trans.unshift(null); - } - }); - return {fields: fields, outnames:outnames, trans:trans}; - } - - /** - * Add query parameters to the URL to construct a query for the specified region - */ - getURL (state, chain, fields) { - const analysis = chain.header.analysis || this.params.source || this.params.analysis; // Old usages called this param "analysis" - if (typeof analysis == 'undefined') { - throw new Error('Association source must specify an analysis ID to plot'); - } - return `${this.url}results/?filter=analysis in ${analysis} and chromosome in '${state.chr}' and position ge ${state.start} and position le ${state.end}`; - } - - /** - * Some association sources do not sort their data in a predictable order, which makes it hard to reliably - * align with other sources (such as LD). For performance reasons, sorting is an opt-in argument. - * TODO: Consider more fine grained sorting control in the future. This was added as a very specific - * workaround for the original T2D portal. - * @protected - * @param data - * @return {Object} - */ - normalizeResponse (data) { - data = super.normalizeResponse(data); - if (this.params && this.params.sort && data.length && data[0]['position']) { - data.sort(function (a, b) { - return a['position'] - b['position']; - }); - } - return data; - } -} - -/** - * Fetch linkage disequilibrium information from a UMich LDServer-compatible API, relative to a reference variant. - * If no `plot.state.ldrefvar` is explicitly provided, this source will attempt to find the most significant GWAS - * variant (smallest pvalue or largest neg_log_pvalue) and yse that as the LD reference variant. - * - * This source is designed to connect its results to association data, and therefore depends on association data having - * been loaded by a previous request in the data chain. For custom association APIs, some additional options might - * need to be be specified in order to locate the most significant SNP. Variant IDs of the form `chrom:pos_ref/alt` - * are preferred, but this source will attempt to harmonize other common data formats into something that the LD - * server can understand. + * @see module:LocusZoom_Adapters~BaseUMAdapter + * @inheritDoc * - * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @param {Number} config.source The source ID for the dataset of interest, used to construct the request URL */ -class LDServer extends BaseApiAdapter { - /** - * @param {string} config.url The base URL for the remote data. - * @param {object} config.params - * @param [config.params.build='GRCh37'] The genome build to use when calculating LD relative to a specified reference variant. - * 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. - * @param [config.params.source='1000G'] The name of the reference panel to use, as specified in the LD server instance. - * May be overridden by a global parameter `plot.state.ld_source` to implement widgets that alter LD display. - * @param [config.params.population='ALL'] The sample population used to calculate LD for a specified source; - * population names vary depending on the reference panel and how the server was populated wth data. - * May be overridden by a global parameter `plot.state.ld_pop` to implement widgets that alter LD display. - * @param [config.params.method='rsquare'] The metric used to calculate LD - * @param [config.params.id_field] The association data field that contains variant identifier information. The preferred - * format of LD server is `chrom:pos_ref/alt` and this source will attempt to normalize other common formats. - * This source can auto-detect possible matches for field names containing "variant" or "id" - * @param [config.params.position_field] The association data field that contains variant position information. - * This source can auto-detect possible matches for field names containing "position" or "pos" - * @param [config.params.pvalue_field] The association data field that contains pvalue information. - * This source can auto-detect possible matches for field names containing "pvalue" or "log_pvalue". - * The suggested LD refvar will be the smallest pvalue, or the largest log_pvalue: this source will auto-detect - * the word "log" in order to determine the sign of the comparison. - */ - constructor(config) { +class AssociationLZ extends BaseUMAdapter { + constructor(config = {}) { super(config); - this.__dependentSource = true; - } - - preGetData(state, fields) { - if (fields.length > 1) { - if (fields.length !== 2 || !fields.includes('isrefvar')) { - throw new Error(`LD does not know how to get all fields: ${fields.join(', ')}`); - } - } - } - - findMergeFields(chain) { - // Find the fields (as provided by a previous step in the chain, like an association source) that will be needed to - // combine LD data with existing information - - // Since LD information may be shared across multiple assoc sources with different namespaces, - // we use regex to find columns to join on, rather than requiring exact matches - const exactMatch = function (arr) { - return function () { - const regexes = arguments; - for (let i = 0; i < regexes.length; i++) { - const regex = regexes[i]; - const m = arr.filter(function (x) { - return x.match(regex); - }); - if (m.length) { - return m[0]; - } - } - return null; - }; - }; - let dataFields = { - id: this.params.id_field, - position: this.params.position_field, - pvalue: this.params.pvalue_field, - _names_:null, - }; - if (chain && chain.body && chain.body.length > 0) { - const names = Object.keys(chain.body[0]); - const nameMatch = exactMatch(names); - // Internally, fields are generally prefixed with the name of the source they come from. - // If the user provides an id_field (like `variant`), it should work across data sources (`assoc1:variant`, - // assoc2:variant), but not match fragments of other field names (assoc1:variant_thing) - // Note: these lookups hard-code a couple of common fields that will work based on known APIs in the wild - const id_match = dataFields.id && nameMatch(new RegExp(`${dataFields.id}\\b`)); - dataFields.id = id_match || nameMatch(/\bvariant\b/) || nameMatch(/\bid\b/); - dataFields.position = dataFields.position || nameMatch(/\bposition\b/i, /\bpos\b/i); - dataFields.pvalue = dataFields.pvalue || nameMatch(/\bpvalue\b/i, /\blog_pvalue\b/i); - dataFields._names_ = names; - } - return dataFields; - } - - findRequestedFields (fields, outnames) { - // Assumption: all usages of this source will only ever ask for "isrefvar" or "state". This maps to output names. - let obj = {}; - for (let i = 0; i < fields.length; i++) { - if (fields[i] === 'isrefvar') { - obj.isrefvarin = fields[i]; - obj.isrefvarout = outnames && outnames[i]; - } else { - obj.ldin = fields[i]; - obj.ldout = outnames && outnames[i]; - } - } - return obj; - } - - /** - * The LD API payload does not obey standard format conventions; do not try to transform it. - */ - normalizeResponse (data) { - return data; - } - - /** - * Get the LD reference variant, which by default will be the most significant hit in the assoc results - * This will be used in making the original query to the LD server for pairwise LD information. - * - * This is meant to join a single LD request to any number of association results, and to work with many kinds of API. - * To do this, the datasource looks for fields with special known names such as pvalue, log_pvalue, etc. - * If your API uses different nomenclature, an option must be specified. - * - * @protected - * @returns {String[]} Two strings: 1) the marker id (expected to be in `chr:pos_ref/alt` format) of the reference - * variant, and 2) the marker ID as it appears in the original dataset that we are joining to, so that the exact - * refvar can be marked when plotting the data.. - */ - getRefvar(state, chain, fields) { - let findExtremeValue = function(records, pval_field) { - // Finds the most significant hit (smallest pvalue, or largest -log10p). Will try to auto-detect the appropriate comparison. - pval_field = pval_field || 'log_pvalue'; // The official LZ API returns log_pvalue - const is_log = /log/.test(pval_field); - let cmp; - if (is_log) { - cmp = function(a, b) { - return a > b; - }; - } else { - cmp = function(a, b) { - return a < b; - }; - } - let extremeVal = records[0][pval_field], extremeIdx = 0; - for (let i = 1; i < records.length; i++) { - if (cmp(records[i][pval_field], extremeVal)) { - extremeVal = records[i][pval_field]; - extremeIdx = i; - } - } - return extremeIdx; - }; - - let reqFields = this.findRequestedFields(fields); - let refVar = reqFields.ldin; - if (refVar === 'state') { - refVar = state.ldrefvar || chain.header.ldrefvar || 'best'; - } - if (refVar === 'best') { - if (!chain.body) { - throw new Error('No association data found to find best pvalue'); - } - let keys = this.findMergeFields(chain); - if (!keys.pvalue || !keys.id) { - let columns = ''; - if (!keys.id) { - columns += `${columns.length ? ', ' : ''}id`; - } - if (!keys.pvalue) { - columns += `${columns.length ? ', ' : ''}pvalue`; - } - throw new Error(`Unable to find necessary column(s) for merge: ${columns} (available: ${keys._names_})`); - } - refVar = chain.body[findExtremeValue(chain.body, keys.pvalue)][keys.id]; - } - // Some datasets, notably the Portal, use a different marker format. - // Coerce it into one that will work with the LDServer API. (CHROM:POS_REF/ALT) - const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\d+)[_:|-]?(\w+)?[/_:|-]?([^_]+)?_?(.*)?/; - const match = refVar && refVar.match(REGEX_MARKER); - - if (!match) { - throw new Error('Could not request LD for a missing or incomplete marker format'); - } - const [original, chrom, pos, ref, alt] = match; - // Currently, the LD server only accepts full variant specs; it won't return LD w/o ref+alt. Allowing - // a partial match at most leaves room for potential future features. - let refVar_formatted = `${chrom}:${pos}`; - if (ref && alt) { - refVar_formatted += `_${ref}/${alt}`; - } - - return [refVar_formatted, original]; - } - - /** - * Identify (or guess) the LD reference variant, then add query parameters to the URL to construct a query for the specified region - */ - getURL(state, chain, fields) { - // The LD source/pop can be overridden from plot.state for dynamic layouts - const build = state.genome_build || this.params.build || 'GRCh37'; // This isn't expected to change after the data is plotted. - let source = state.ld_source || this.params.source || '1000G'; - const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL - const method = this.params.method || 'rsquare'; - - if (source === '1000G' && build === 'GRCh38') { - // For build 38 (only), there is a newer/improved 1000G LD panel available that uses WGS data. Auto upgrade by default. - source = '1000G-FRZ09'; - } - - validateBuildSource(this.constructor.name, build, null); // LD doesn't need to validate `source` option - - const [refVar_formatted, refVar_raw] = this.getRefvar(state, chain, fields); - - // Preserve the user-provided variant spec for use when matching to assoc data - chain.header.ldrefvar = refVar_raw; - - return [ - this.url, 'genome_builds/', build, '/references/', source, '/populations/', population, '/variants', - '?correlation=', method, - '&variant=', encodeURIComponent(refVar_formatted), - '&chrom=', encodeURIComponent(state.chr), - '&start=', encodeURIComponent(state.start), - '&stop=', encodeURIComponent(state.end), - ].join(''); - } - - /** - * The LD adapter caches based on region, reference panel, and population name - * @param state - * @param chain - * @param fields - * @return {string} - */ - getCacheKey(state, chain, fields) { - const base = super.getCacheKey(state, chain, fields); - let source = state.ld_source || this.params.source || '1000G'; - const population = state.ld_pop || this.params.population || 'ALL'; // LDServer panels will always have an ALL - const [refVar, _] = this.getRefvar(state, chain, fields); - return `${base}_${refVar}_${source}_${population}`; - } - - /** - * The LD adapter attempts to intelligently match retrieved LD information to a request for association data earlier in the data chain. - * Since each layer only asks for the data needed for that layer, one LD call is sufficient to annotate many separate association tracks. - */ - combineChainBody(data, chain, fields, outnames, trans) { - let keys = this.findMergeFields(chain); - let reqFields = this.findRequestedFields(fields, outnames); - if (!keys.position) { - throw new Error(`Unable to find position field for merge: ${keys._names_}`); - } - const leftJoin = function (left, right, lfield, rfield) { - let i = 0, j = 0; - while (i < left.length && j < right.position2.length) { - if (left[i][keys.position] === right.position2[j]) { - left[i][lfield] = right[rfield][j]; - i++; - j++; - } else if (left[i][keys.position] < right.position2[j]) { - i++; - } else { - j++; - } - } - }; - const tagRefVariant = function (data, refvar, idfield, outrefname, outldname) { - for (let i = 0; i < data.length; i++) { - if (data[i][idfield] && data[i][idfield] === refvar) { - data[i][outrefname] = 1; - data[i][outldname] = 1; // For label/filter purposes, implicitly mark the ref var as LD=1 to itself - } else { - data[i][outrefname] = 0; - } - } - }; - // LD servers vary slightly. Some report corr as "rsquare", others as "correlation" - let corrField = data.rsquare ? 'rsquare' : 'correlation'; - leftJoin(chain.body, data, reqFields.ldout, corrField); - if (reqFields.isrefvarin && chain.header.ldrefvar) { - tagRefVariant(chain.body, chain.header.ldrefvar, keys.id, reqFields.isrefvarout, reqFields.ldout); - } - return chain.body; + // We don't validate the source option because a depressing number of people use AssociationLZ to serve non-dynamic JSON files + const { source } = config; + this._source_id = source; } - /** - * The LDServer API is paginated, but we need all of the data to render a plot. Depaginate and combine where appropriate. - */ - fetchRequest(state, chain, fields) { - let url = this.getURL(state, chain, fields); - let combined = { data: {} }; - let chainRequests = function (url) { - return fetch(url).then().then((response) => { - if (!response.ok) { - throw new Error(response.statusText); - } - return response.text(); - }).then(function(payload) { - payload = JSON.parse(payload); - Object.keys(payload.data).forEach(function (key) { - combined.data[key] = (combined.data[key] || []).concat(payload.data[key]); - }); - if (payload.next) { - return chainRequests(payload.next); - } - return combined; - }); - }; - return chainRequests(url); + _getURL (request_options) { + const {chr, start, end} = request_options; + const base = super._getURL(request_options); + return `${base}results/?filter=analysis in ${this._source_id} and chromosome in '${chr}' and position ge ${start} and position le ${end}`; } } + /** * Fetch GWAS catalog data for a list of known variants, and align the data with previously fetched association data. * There can be more than one claim per variant; this adapter is written to support a visualization in which each @@ -797,161 +282,78 @@ class LDServer extends BaseApiAdapter { * field in association data by looking for the field name `position` or `pos`. * * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter */ -class GwasCatalogLZ extends BaseApiAdapter { +class GwasCatalogLZ extends BaseUMAdapter { /** * @param {string} config.url The base URL for the remote data. - * @param {Object} config.params - * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant. + * @param [config.build] The genome build to use when requesting the specific genomic region. * 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. - * @param {Number} [config.params.source] The ID of the chosen catalog. Most usages should omit this parameter and + * @param {Number} [config.source] The ID of the chosen catalog. Most usages should omit this parameter and * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent EBI GWAS catalog, GRCh37. */ constructor(config) { + if (!config.limit_fields) { + config.limit_fields = ['log_pvalue', 'pos', 'rsid', 'trait', 'variant']; + } super(config); - this.__dependentSource = true; } /** * Add query parameters to the URL to construct a query for the specified region */ - getURL(state, chain, fields) { - // This is intended to be aligned with another source- we will assume they are always ordered by position, asc - // (regardless of the actual match field) - const build = state.genome_build || this.params.build; - const source = this.params.source; - validateBuildSource(this.constructor.name, build, source); + _getURL(request_options) { + const build = request_options.genome_build || this._config.build; + const source = this._config.source; + this._validateBuildSource(build, source); // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build). // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date const source_query = build ? `&build=${build}` : ` and id eq ${source}`; - return `${this.url }?format=objects&sort=pos&filter=chrom eq '${state.chr}' and pos ge ${state.start} and pos le ${state.end}${source_query}`; - } - - findMergeFields(records) { - // Data from previous sources is already namespaced. Find the alignment field by matching. - const knownFields = Object.keys(records); - // Note: All API endoints involved only give results for 1 chromosome at a time; match is implied - const posMatch = knownFields.find(function (item) { - return item.match(/\b(position|pos)\b/i); - }); - - if (!posMatch) { - throw new Error('Could not find data to align with GWAS catalog results'); - } - return { 'pos': posMatch }; - } - extractFields (data, fields, outnames, trans) { - // Skip the "individual field extraction" step; extraction will be handled when building chain body instead - return data; - } - - /** - * Intelligently combine the LD data with the association data used for this data layer. See class description - * for a summary of how this works. - */ - combineChainBody(data, chain, fields, outnames, trans) { - if (!data.length) { - return chain.body; - } - - // TODO: Better reuse options in the future. This source is very specifically tied to the UM PortalDev API, where - // the field name is always "log_pvalue". Relatively few sites will write their own gwas-catalog endpoint. - const decider = 'log_pvalue'; - const decider_out = outnames[fields.indexOf(decider)]; - - function leftJoin(left, right, fields, outnames, trans) { // Add `fields` from `right` to `left` - // Add a synthetic, un-namespaced field to all matching records - const n_matches = left['n_catalog_matches'] || 0; - left['n_catalog_matches'] = n_matches + 1; - if (decider && left[decider_out] && left[decider_out] > right[decider]) { - // There may be more than one GWAS catalog entry for the same SNP. This source is intended for a 1:1 - // annotation scenario, so for now it only joins the catalog entry that has the best -log10 pvalue - return; - } - - for (let j = 0; j < fields.length; j++) { - const fn = fields[j]; - const outn = outnames[j]; - - let val = right[fn]; - if (trans && trans[j]) { - val = trans[j](val); - } - left[outn] = val; - } - } - - const chainNames = this.findMergeFields(chain.body[0]); - const catNames = this.findMergeFields(data[0]); - - var i = 0, j = 0; - while (i < chain.body.length && j < data.length) { - var left = chain.body[i]; - var right = data[j]; - - if (left[chainNames.pos] === right[catNames.pos]) { - // There may be multiple catalog entries for each matching SNP; evaluate match one at a time - leftJoin(left, right, fields, outnames, trans); - j += 1; - } else if (left[chainNames.pos] < right[catNames.pos]) { - i += 1; - } else { - j += 1; - } - } - return chain.body; + const base = super._getURL(request_options); + return `${base}?format=objects&sort=pos&filter=chrom eq '${request_options.chr}' and pos ge ${request_options.start} and pos le ${request_options.end}${source_query}`; } } + /** * Retrieve Gene Data, as fetched from the LocusZoom/Portaldev API server (or compatible format) * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter * @param {string} config.url The base URL for the remote data - * @param {Object} config.params - * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant. + * @param [config.build] The genome build to use * 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. - * @param {Number} [config.params.source] The ID of the chosen gene dataset. Most usages should omit this parameter and + * @param {Number} [config.source] The ID of the chosen gene dataset. Most usages should omit this parameter and * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent GENCODE data, GRCh37. */ -class GeneLZ extends BaseApiAdapter { +class GeneLZ extends BaseUMAdapter { + constructor(config = {}) { + super(config); + + // The UM Genes API has a very complex internal format and the genes layer is written to work with it exactly as given. + // We will avoid transforming or modifying the payload. + this._prefix_namespace = false; + } + /** * Add query parameters to the URL to construct a query for the specified region */ - getURL(state, chain, fields) { - const build = state.genome_build || this.params.build; - let source = this.params.source; - validateBuildSource(this.constructor.name, build, source); + _getURL(request_options) { + const build = request_options.genome_build || this._config.build; + let source = this._config.source; + this._validateBuildSource(build, source); // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build). // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date const source_query = build ? `&build=${build}` : ` and source in ${source}`; - return `${this.url}?filter=chrom eq '${state.chr}' and start le ${state.end} and end ge ${state.start}${source_query}`; - } - - /** - * The UM genes API has a very complex internal data format. Bypass any record parsing, and provide the data layer with - * the exact information returned by the API. (ignoring the fields array in the layout) - * @param data - * @return {Object[]|Object} - */ - normalizeResponse(data) { - return data; - } - /** - * Does not attempt to namespace or modify the fields from the API payload; the payload format is very complex and - * quite coupled with the data rendering implementation. - * Typically, requests to this adapter specify a single dummy field sufficient to trigger the request: `fields:[ 'gene:all' ]` - */ - extractFields(data, fields, outnames, trans) { - return data; + const base = super._getURL(request_options); + return `${base}?filter=chrom eq '${request_options.chr}' and start le ${request_options.end} and end ge ${request_options.start}${source_query}`; } } + /** * Retrieve Gene Constraint Data, as fetched from the gnomAD server (or compatible graphQL api endpoint) * @@ -960,67 +362,55 @@ class GeneLZ extends BaseApiAdapter { * matching on specific assumptions about `gene_name` format. * * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter */ -class GeneConstraintLZ extends BaseApiAdapter { +class GeneConstraintLZ extends BaseLZAdapter { /** * @param {string} config.url The base URL for the remote data - * @param {Object} config.params - * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant. + * @param [config.build] The genome build to use * 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. */ - constructor(config) { + constructor(config = {}) { super(config); - this.__dependentSource = true; + this._prefix_namespace = false; } - /** - * GraphQL API: request details are encoded in the body, not the URL - */ - getURL() { - return this.url; - } - - /** - * The gnomAD API has a very complex internal data format. Bypass any record parsing, and provide the data layer with - * the exact information returned by the API. - */ - normalizeResponse(data) { - return data; - } - - fetchRequest(state, chain, fields) { - const build = state.genome_build || this.params.build; + _buildRequestOptions(state, genes_data) { + const build = state.genome_build || this._config.build; if (!build) { throw new Error(`Adapter ${this.constructor.name} must specify a 'genome_build' option`); } - const unique_gene_names = chain.body.reduce( + const unique_gene_names = new Set(); + for (let gene of genes_data) { // In rare cases, the same gene symbol may appear at multiple positions. (issue #179) We de-duplicate the // gene names to avoid issuing a malformed GraphQL query. - function (acc, gene) { - acc[gene.gene_name] = null; - return acc; - }, - {} - ); - let query = Object.keys(unique_gene_names).map(function (gene_name) { + unique_gene_names.add(gene.gene_name); + } + + state.query = [...unique_gene_names.values()].map(function (gene_name) { // GraphQL alias names must match a specific set of allowed characters: https://stackoverflow.com/a/45757065/1422268 const alias = `_${gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // Each gene symbol is a separate graphQL query, grouped into one request using aliases 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 } } `; }); + state.build = build; + return Object.assign({}, state); + } + _performRequest(options) { + let {query, build} = options; if (!query.length || query.length > 25 || build === 'GRCh38') { // Skip the API request when it would make no sense: // - 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.) - // - Too many genes (gnomAD appears max cost ~25 genes) + // - Too many genes (gnomAD appears to set max cost ~25 genes) // - No genes in region (hence no constraint info) - return Promise.resolve({ data: null }); + return Promise.resolve([]); } - query = `{${query.join(' ')} }`; // GraphQL isn't quite JSON; items are separated by spaces but not commas - const url = this.getURL(state, chain, fields); + + const url = this._getURL(options); + // See: https://graphql.org/learn/serving-over-http/ const body = JSON.stringify({ query: query }); const headers = { 'Content-Type': 'application/json' }; @@ -1036,62 +426,239 @@ class GeneConstraintLZ extends BaseApiAdapter { } /** - * Annotate GENCODE data (from a previous request to the genes adapter) with additional gene constraint data from - * the gnomAD API. See class description for a summary of how this works. + * The gnomAD API has a very complex internal data format. Bypass any record parsing or transform steps. */ - combineChainBody(data, chain, fields, outnames, trans) { - if (!data) { - return chain; + _normalizeResponse(response_text) { + if (typeof response_text !== 'string') { + // If the query short-circuits, we receive an empty list instead of a string + return response_text; } + const data = JSON.parse(response_text); + return data.data; + } +} - chain.body.forEach(function(gene) { - // Find payload keys that match gene names in this response - const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names - const constraint = data[alias] && data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene - if (constraint) { - // Add all fields from constraint data- do not override fields present in the gene source - Object.keys(constraint).forEach(function (key) { - let val = constraint[key]; - if (typeof gene[key] === 'undefined') { - if (typeof val == 'number' && val.toString().includes('.')) { - val = parseFloat(val.toFixed(2)); - } - gene[key] = val; // These two sources are both designed to bypass namespacing - } - }); + +/** + * Fetch linkage disequilibrium information from a UMich LDServer-compatible API, relative to a reference variant. + * If no `plot.state.ldrefvar` is explicitly provided, this source will attempt to find the most significant GWAS + * variant and yse that as the LD reference variant. + * + * THIS ADAPTER EXPECTS TO RECEIVE ASSOCIATION DATA WITH FIELDS `variant` and `log_pvalue`. It may not work correctly + * if this information is not provided. + * + * This source is designed to connect its results to association data, and therefore depends on association data having + * been loaded by a previous request. For custom association APIs, some additional options might + * need to be be specified in order to locate the most significant SNP. Variant IDs of the form `chrom:pos_ref/alt` + * are preferred, but this source will attempt to harmonize other common data formats into something that the LD + * server can understand. + * + * @public + * @see module:LocusZoom_Adapters~BaseUMAdapter + */ +class LDServer extends BaseUMAdapter { + /** + * @param {string} config.url The base URL for the remote data. + * @param [config.build='GRCh37'] The genome build to use when calculating LD relative to a specified reference variant. + * 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. + * @param [config.source='1000G'] The name of the reference panel to use, as specified in the LD server instance. + * May be overridden by a global parameter `plot.state.ld_source` to implement widgets that alter LD display. + * @param [config.population='ALL'] The sample population used to calculate LD for a specified source; + * population names vary depending on the reference panel and how the server was populated wth data. + * May be overridden by a global parameter `plot.state.ld_pop` to implement widgets that alter LD display. + * @param [config.method='rsquare'] The metric used to calculate LD + */ + constructor(config) { + if (!config.limit_fields) { + config.limit_fields = ['variant2', 'position2', 'correlation']; + } + super(config); + } + + __find_ld_refvar(state, assoc_data) { + const assoc_variant_name = this._findPrefixedKey(assoc_data[0], 'variant'); + const assoc_logp_name = this._findPrefixedKey(assoc_data[0], 'log_pvalue'); + + // Determine the reference variant (via user selected OR automatic-per-track) + let refvar; + let best_hit = {}; + if (state.ldrefvar) { + // State/ldrefvar would store the variant in the format used by assoc data, so no need to clean up to match in data + refvar = state.ldrefvar; + best_hit = assoc_data.find((item) => item[assoc_variant_name] === refvar) || {}; + } else { + // find highest log-value and associated var spec + let best_logp = 0; + for (let item of assoc_data) { + const { [assoc_variant_name]: variant, [assoc_logp_name]: log_pvalue} = item; + if (log_pvalue > best_logp) { + best_logp = log_pvalue; + refvar = variant; + best_hit = item; + } } - }); - return chain.body; + } + + // Add a special field that is not part of the assoc or LD data from the server, but has significance for plotting. + // Since we already know the best hit, it's easier to do this here rather than in annotate or join phase. + best_hit.lz_is_ld_refvar = true; + + // Above, we compared the ldrefvar to the assoc data. But for talking to the LD server, + // the variant fields must be normalized to a specific format. All later LD operations will use that format. + const match = parseMarker(refvar, true); + if (!match) { + throw new Error('Could not request LD for a missing or incomplete marker format'); + } + + const [chrom, pos, ref, alt] = match; + // Currently, the LD server only accepts full variant specs; it won't return LD w/o ref+alt. Allowing + // a partial match at most leaves room for potential future features. + refvar = `${chrom}:${pos}`; // FIXME: is this a server request that we can skip? + if (ref && alt) { + refvar += `_${ref}/${alt}`; + } + + const coord = +pos; + // Last step: sanity check the proposed reference variant. Is it inside the view region? If not, we're probably + // remembering a user choice from before user jumped to a new region. LD should be relative to something nearby. + if ((coord && state.ldrefvar && state.chr) && (chrom !== String(state.chr) || coord < state.start || coord > state.end)) { + // Rerun this method, after clearing out the proposed reference variant. NOTE: Adapter call receives a + // *copy* of plot.state, so wiping here doesn't remove the original value. + state.ldrefvar = null; + return this.__find_ld_refvar(state, assoc_data); + } + + // Return the reference variant, in a normalized format suitable for LDServer queries + return refvar; + } + + _buildRequestOptions(state, assoc_data) { + if (!assoc_data) { + throw new Error('LD request must depend on association data'); + } + + // If no state refvar is provided, find the most significant variant in any provided assoc data. + // Assumes that assoc satisfies the "assoc" fields contract, eg has fields variant and log_pvalue + const base = super._buildRequestOptions(...arguments); + if (!assoc_data.length) { + // No variants, so no need to annotate association data with LD! + // NOTE: Revisit. This could have odd cache implications (eg, when joining two assoc datasets to LD, and only the second dataset has data in the region) + base._skip_request = true; + return base; + } + + base.ld_refvar = this.__find_ld_refvar(state, assoc_data); + + // The LD source/pop can be overridden from plot.state, so that user choices can override initial source config + const genome_build = state.genome_build || this._config.build || 'GRCh37'; // This isn't expected to change after the data is plotted. + let ld_source = state.ld_source || this._config.source || '1000G'; + const ld_population = state.ld_pop || this._config.population || 'ALL'; // LDServer panels will always have an ALL + + if (ld_source === '1000G' && genome_build === 'GRCh38') { + // For build 38 (only), there is a newer/improved 1000G LD panel available that uses WGS data. Auto upgrade by default. + ld_source = '1000G-FRZ09'; + } + + this._validateBuildSource(genome_build, null); // LD doesn't need to validate `source` option + return Object.assign({}, base, { genome_build, ld_source, ld_population }); + } + + _getURL(request_options) { + const method = this._config.method || 'rsquare'; + const { + chr, start, end, + ld_refvar, + genome_build, ld_source, ld_population, + } = request_options; + + const base = super._getURL(request_options); + + return [ + base, 'genome_builds/', genome_build, '/references/', ld_source, '/populations/', ld_population, '/variants', + '?correlation=', method, + '&variant=', encodeURIComponent(ld_refvar), + '&chrom=', encodeURIComponent(chr), + '&start=', encodeURIComponent(start), + '&stop=', encodeURIComponent(end), + ].join(''); + } + + _getCacheKey(options) { + // LD is keyed by more than just region; append other parameters to the base cache key + const base = super._getCacheKey(options); + const { ld_refvar, ld_source, ld_population } = options; + return `${base}_${ld_refvar}_${ld_source}_${ld_population}`; + } + + _performRequest(options) { + // Skip request if this one depends on other data, and we are in a region with no data + if (options._skip_request) { + // TODO: A skipped request leads to a cache value; possible edge cases where this could get weird. + return Promise.resolve([]); + } + + const url = this._getURL(options); + + // The UM LDServer uses API pagination; fetch all data by chaining requests when pages are detected + let combined = { data: {} }; + let chainRequests = function (url) { + return fetch(url).then().then((response) => { + if (!response.ok) { + throw new Error(response.statusText); + } + return response.text(); + }).then(function(payload) { + payload = JSON.parse(payload); + Object.keys(payload.data).forEach(function (key) { + combined.data[key] = (combined.data[key] || []).concat(payload.data[key]); + }); + if (payload.next) { + return chainRequests(payload.next); + } + return combined; + }); + }; + return chainRequests(url); } } + /** * Retrieve Recombination Rate Data, as fetched from the LocusZoom API server (or compatible) * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter * @param {string} config.url The base URL for the remote data - * @param {Object} config.params - * @param [config.params.build] The genome build to use when calculating LD relative to a specified reference variant. + * @param [config.build] The genome build to use * 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. - * @param {Number} [config.params.source] The ID of the chosen dataset. Most usages should omit this parameter and + * @param {Number} [config.source] The ID of the chosen dataset. Most usages should omit this parameter and * let LocusZoom choose the newest available dataset to use based on the genome build: defaults to recent HAPMAP recombination rate, GRCh37. */ -class RecombLZ extends BaseApiAdapter { +class RecombLZ extends BaseUMAdapter { + constructor(config) { + if (!config.limit_fields) { + config.limit_fields = ['position', 'recomb_rate']; + } + super(config); + } + /** * Add query parameters to the URL to construct a query for the specified region */ - getURL(state, chain, fields) { - const build = state.genome_build || this.params.build; - let source = this.params.source; - validateBuildSource(this.constructor.SOURCE_NAME, build, source); + _getURL(request_options) { + const build = request_options.genome_build || this._config.build; + let source = this._config.source; + this._validateBuildSource(build, source); // If a build name is provided, it takes precedence (the API will attempt to auto-select newest dataset based on the requested genome build). // Build and source are mutually exclusive, because hard-coded source IDs tend to be out of date const source_query = build ? `&build=${build}` : ` and id in ${source}`; - return `${this.url}?filter=chromosome eq '${state.chr}' and position le ${state.end} and position ge ${state.start}${source_query}`; + + const base = super._getURL(request_options); + return `${base}?filter=chromosome eq '${request_options.chr}' and position le ${request_options.end} and position ge ${request_options.start}${source_query}`; } } + /** * Retrieve static blobs of data as raw JS objects. This does not perform additional parsing, which is required * for some sources (eg it does not know how to join together LD and association data). @@ -1104,38 +671,44 @@ class RecombLZ extends BaseApiAdapter { * * Note: The name is a bit misleading. It receives JS objects, not strings serialized as "json". * @public - * @see module:LocusZoom_Adapters~BaseAdapter - * @param {object} data The data to be returned by this source (subject to namespacing rules) + * @see module:LocusZoom_Adapters~BaseLZAdapter + * @param {object} config.data The data to be returned by this source (subject to namespacing rules) */ -class StaticSource extends BaseAdapter { - parseInit(data) { +class StaticSource extends BaseLZAdapter { + constructor(config = {}) { // Does not receive any config; the only argument is the raw data, embedded when source is created + super(...arguments); + const { data } = config; + if (!data || Array.isArray(config)) { // old usages may provide an array directly instead of as config key + throw new Error("'StaticSource' must provide data as required option 'config.data'"); + } this._data = data; } - getRequest(state, chain, fields) { + _performRequest(options) { return Promise.resolve(this._data); } } + /** * Retrieve PheWAS data retrieved from a LocusZoom/PortalDev compatible API * @public - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter * @param {string} config.url The base URL for the remote data - * @param {Object} config.params - * @param {String[]} config.params.build This datasource expects to be provided the name of the genome build that will - * be used to provide pheWAS results for this position. Note positions may not translate between builds. + * @param {String[]} config.build This datasource expects to be provided the name of the genome build that will + * be used to provide PheWAS results for this position. Note positions may not translate between builds. */ -class PheWASLZ extends BaseApiAdapter { - getURL(state, chain, fields) { - const build = (state.genome_build ? [state.genome_build] : null) || this.params.build; +class PheWASLZ extends BaseUMAdapter { + _getURL(request_options) { + const build = (request_options.genome_build ? [request_options.genome_build] : null) || this._config.build; if (!build || !Array.isArray(build) || !build.length) { - throw new Error(['Adapter', this.constructor.SOURCE_NAME, 'requires that you specify array of one or more desired genome build names'].join(' ')); + throw new Error(['Adapter', this.constructor.name, 'requires that you specify array of one or more desired genome build names'].join(' ')); } + const base = super._getURL(request_options); const url = [ - this.url, - "?filter=variant eq '", encodeURIComponent(state.variant), "'&format=objects&", + base, + "?filter=variant eq '", encodeURIComponent(request_options.variant), "'&format=objects&", build.map(function (item) { return `build=${encodeURIComponent(item)}`; }).join('&'), @@ -1143,108 +716,21 @@ class PheWASLZ extends BaseApiAdapter { return url.join(''); } - getCacheKey(state, chain, fields) { - // This is not a region-based source; it doesn't make sense to cache by a region - return this.getURL(state, chain, fields); - } -} - -/** - * Base class for "connectors"- this is a highly specialized kind of adapter that is rarely used in most LocusZoom - * deployments. This is meant to be subclassed, rather than used directly. - * - * A connector is a data adapter that makes no server requests and caches no data of its own. Instead, it decides how to - * combine data from other sources in the chain. Connectors are useful when we want to request (or calculate) some - * useful piece of information once, but apply it to many different kinds of record types. - * - * Typically, a subclass will implement the field merging logic in `combineChainBody`. - * - * @public - * @see module:LocusZoom_Adapters~BaseAdapter - */ -class ConnectorSource extends BaseAdapter { - /** - * @param {Object} config.params Additional parameters - * @param {Object} config.params.sources Specify how the hard-coded logic should find the data it relies on in the chain, - * as {internal_name: chain_source_id} pairs. This allows writing a reusable connector that does not need to make - * assumptions about what namespaces a source is using. * - */ - constructor(config) { - super(config); - - if (!config || !config.sources) { - throw new Error('Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs'); - } - - /** - * Tells the connector how to find the data it relies on - * - * For example, a connector that applies burden test information to the genes layer might specify: - * {gene_ns: "gene", aggregation_ns: "aggregation"} - * - * @member {Object} - * @private - */ - this._source_name_mapping = config.sources; - - // Validate that this source has been told how to find the required information - const specified_ids = Object.keys(config.sources); - /** @property {String[]} Specifies the sources that must be provided in the original config object */ - - this._getRequiredSources().forEach((k) => { - if (!specified_ids.includes(k)) { - // TODO: Fix constructor.name usage in minified bundles - throw new Error(`Configuration for ${this.constructor.name} must specify a source ID corresponding to ${k}`); - } - }); - } - - // Stub- connectors don't have their own url or data, so the defaults don't make sense - parseInit() {} - - getRequest(state, chain, fields) { - // Connectors do not request their own data by definition, but they *do* depend on other sources having been loaded - // first. This method performs basic validation, and preserves the accumulated body from the chain so far. - Object.keys(this._source_name_mapping).forEach((ns) => { - const chain_source_id = this._source_name_mapping[ns]; - if (chain.discrete && !chain.discrete[chain_source_id]) { - throw new Error(`${this.constructor.name} cannot be used before loading required data for: ${chain_source_id}`); - } - }); - return Promise.resolve(chain.body || []); - } - - parseResponse(data, chain, fields, outnames, trans) { - // A connector source does not update chain.discrete, but it may use it. It bypasses data formatting - // and field selection (both are assumed to have been done already, by the previous sources this draws from) - - // Because of how the chain works, connectors are not very good at applying new transformations or namespacing. - // Typically connectors are called with `connector_name:all` in the fields array. - return Promise.resolve(this.combineChainBody(data, chain, fields, outnames, trans)) - .then(function(new_body) { - return {header: chain.header || {}, discrete: chain.discrete || {}, body: new_body}; - }); - } - - combineChainBody(records, chain) { - // Stub method: specifies how to combine the data - throw new Error('This method must be implemented in a subclass'); - } - - /** - * Helper method since ES6 doesn't support class fields - * @private - */ - _getRequiredSources() { - throw new Error('Must specify an array that identifes the kind of data required by this source'); + _getCacheKey(options) { + // Not a region based source; don't do anything smart for cache check + return this._getURL(options); } } +// Deprecated symbols export { BaseAdapter, BaseApiAdapter }; +// Usually used as a parent class for custom code +export { BaseLZAdapter, BaseUMAdapter }; + +// Usually used as a standalone class export { AssociationLZ, - ConnectorSource, GeneConstraintLZ, GeneLZ, GwasCatalogLZ, diff --git a/esm/data/field.js b/esm/data/field.js index d97ad39a..0fb43c4b 100644 --- a/esm/data/field.js +++ b/esm/data/field.js @@ -1,4 +1,4 @@ -import transforms from '../registry/transforms'; +import TRANSFORMS from '../registry/transforms'; /** * Represents an addressable unit of data from a namespaced datasource, subject to specified value transformations. @@ -15,20 +15,18 @@ import transforms from '../registry/transforms'; */ class Field { constructor(field) { - const parts = /^(?:([^:]+):)?([^:|]*)(\|.+)*$/.exec(field); - /** @member {String} */ - this.full_name = field; - /** @member {String} */ - this.namespace = parts[1] || null; - /** @member {String} */ - this.name = parts[2] || null; - /** @member {Array} */ - this.transformations = []; - - if (typeof parts[3] == 'string' && parts[3].length > 1) { - this.transformations = parts[3].substring(1).split('|'); - this.transformations.forEach((transform, i) => this.transformations[i] = transforms.get(transform)); + // Two scenarios: we are requesting a field by full name, OR there are transforms to apply + // `fieldname` or `namespace:fieldname` followed by `|filter1|filterN` + const field_pattern = /^(?:\w+:\w+|^\w+)(?:\|\w+)*$/; + if (!field_pattern.test(field)) { + throw new Error(`Invalid field specifier: '${field}'`); } + + const [name, ...transforms] = field.split('|'); + + this.full_name = field; // fieldname + transforms + this.field_name = name; // just fieldname + this.transformations = transforms.map((name) => TRANSFORMS.get(name)); } _applyTransformations(val) { @@ -48,15 +46,14 @@ class Field { * @returns {*} */ resolve(data, extra) { + // Four resolutions: a) This is cached, b) this can be calculated from a known field, c) this is a known annotation rather than from an API, d) This field doesn't exist and returns as null if (typeof data[this.full_name] == 'undefined') { // Check for cached result let val = null; - if (typeof (data[`${this.namespace}:${this.name}`]) != 'undefined') { // Fallback: value sans transforms - val = data[`${this.namespace}:${this.name}`]; - } else if (typeof data[this.name] != 'undefined') { // Fallback: value present without namespace - val = data[this.name]; - } else if (extra && typeof extra[this.full_name] != 'undefined') { // Fallback: check annotations - val = extra[this.full_name]; - } // We should really warn if no value found, but many bad layouts exist and this could break compatibility + if (data[this.field_name] !== undefined) { // Fallback: value sans transforms + val = data[this.field_name]; + } else if (extra && extra[this.field_name] !== undefined) { // Fallback: check annotations + val = extra[this.field_name]; + } // Don't warn if no value found, because sometimes only certain rows will have a specific field (esp happens with annotations) data[this.full_name] = this._applyTransformations(val); } return data[this.full_name]; diff --git a/esm/data/requester.js b/esm/data/requester.js index 2e5b5cea..ce842bd6 100644 --- a/esm/data/requester.js +++ b/esm/data/requester.js @@ -1,14 +1,48 @@ -import { TRANSFORMS } from '../registry'; +/** + * @module + * @private + */ +import {getLinkedData} from './undercomplicate'; + +import { DATA_OPS } from '../registry'; + + +class DataOperation { + /** + * Perform a data operation (such as a join) + * @param {String} join_type + * @param initiator The entity that initiated the request for data. Usually, this is the data layer. This argument exists so that a data_operation could do things like auto-define axis labels/ color scheme in response to dynamic data. It has potential for side effects if misused, so use sparingly! + * @param params Optional user/layout parameters to be passed to the data function + */ + constructor(join_type, initiator, params) { + this._callable = DATA_OPS.get(join_type); + this._initiator = initiator; + this._params = params || []; + } + + getData(plot_state, ...dependent_recordsets) { + // Most operations are joins: they receive two pieces of data (eg left + right) + // Other ops are possible, like consolidating just one set of records to best value per key + // Hence all dependencies are passed as first arg: [dep1, dep2, dep3...] + + // Every data operation receives plot_state, reference to the data layer that called it, the input data, & any additional options + const context = {plot_state, data_layer: this._initiator}; + return Promise.resolve(this._callable(context, dependent_recordsets, ...this._params)); + } +} + /** * The Requester manages fetching of data across multiple data sources. It is used internally by LocusZoom data layers. - * It passes state information and ensures that data is formatted in the manner expected by the plot. + * It passes plot.state information to each adapter, and ensures that a series of requests can be performed in a + * designated order. + * + * Each data layer calls the requester object directly, and as such, each data layer has a private view of data: it can + * perform its own calculations, filter results, and apply transforms without influencing other layers. + * (while still respecting a shared cache where appropriate) * * This object is not part of the public interface. It should almost **never** be replaced or modified directly. * - * It is also responsible for constructing a "chain" of dependent requests, by requesting each datasource - * sequentially in the order specified in the datalayer `fields` array. Data sources are only chained within a - * data layer, and only if that layer requests more than one source of data. * @param {DataSources} sources A set of data sources used specifically by this plot instance * @private */ @@ -17,57 +51,108 @@ class Requester { this._sources = sources; } - __split_requests(fields) { - // Given a fields array, return an object specifying what datasource names the data layer should make requests - // to, and how to handle the returned data - var requests = {}; - // Regular expression finds namespace:field|trans - var re = /^(?:([^:]+):)?([^:|]*)(\|.+)*$/; - fields.forEach(function(raw) { - var parts = re.exec(raw); - var ns = parts[1] || 'base'; - var field = parts[2]; - var trans = TRANSFORMS.get(parts[3]); - if (typeof requests[ns] == 'undefined') { - requests[ns] = {outnames:[], fields:[], trans:[]}; + /** + * Parse the data layer configuration when a layer is first created. + * Validate config, and return entities and dependencies in a format usable for data retrieval. + * This is used by data layers, and also other data-retrieval functions (like subscribeToDate). + * + * Inherent assumptions: + * 1. A data layer will always know its data up front, and layout mutations will only affect what is displayed. + * 2. People will be able to add new data adapters (tracks), but if they are removed, the accompanying layers will be + * removed at the same time. Otherwise, the pre-parsed data fetching logic could could preserve a reference to the + * removed adapter. + * @param {Object} namespace_options + * @param {Array} data_operations + * @param {Object|null} initiator The entity that initiated the request (the data layer). Passed to data operations, + * but not adapters. By baking this reference into each data operation, functions can do things like autogenerate + * axis tick marks or color schemes based on dyanmic data. This is an advanced usage and should be handled with care! + * @returns {Array} Map of entities and list of dependencies + */ + config_to_sources(namespace_options = {}, data_operations = [], initiator) { + const entities = new Map(); + const namespace_local_names = Object.keys(namespace_options); + + // 1. Specify how to coordinate data. Precedence: + // a) EXPLICIT fetch logic, + // b) IMPLICIT auto-generate fetch order if there is only one NS, + // c) Throw "spec required" error if > 1, because 2 adapters may need to be fetched in a sequence + let dependency_order = data_operations.find((item) => item.type === 'fetch'); // explicit spec: {fetch, from} + if (!dependency_order) { + dependency_order = { type: 'fetch', from: namespace_local_names }; + data_operations.unshift(dependency_order); + } + + // Validate that all NS items are available to the root requester in DataSources. All layers recognize a + // default value, eg people copying the examples tend to have defined a datasource called "assoc" + const ns_pattern = /^\w+$/; + for (let [local_name, global_name] of Object.entries(namespace_options)) { + if (!ns_pattern.test(local_name)) { + throw new Error(`Invalid namespace name: '${local_name}'. Must contain only alphanumeric characters`); + } + + const source = this._sources.get(global_name); + if (!source) { + throw new Error(`A data layer has requested an item not found in DataSources: data type '${local_name}' from ${global_name}`); + } + entities.set(local_name, source); + + // Note: Dependency spec checker will consider "ld(assoc)" to match a namespace called "ld" + if (!dependency_order.from.find((dep_spec) => dep_spec.split('(')[0] === local_name)) { + // Sometimes, a new piece of data (namespace) will be added to a layer. Often this doesn't have any dependencies, other than adding a new join. + // To make it easier to EXTEND existing layers, by default, we'll push any unknown namespaces to data_ops.fetch + // Thus the default behavior is "fetch all namespaces as though they don't depend on anything. + // If they depend on something, only then does "data_ops[@type=fetch].from" need to be mutated + dependency_order.from.push(local_name); + } + } + + let dependencies = Array.from(dependency_order.from); + + // Now check all joins. Are namespaces valid? Are they requesting known data? + for (let config of data_operations) { + let {type, name, requires, params} = config; + if (type !== 'fetch') { + let namecount = 0; + if (!name) { + name = config.name = `join${namecount}`; + namecount += 1; + } + + if (entities.has(name)) { + throw new Error(`Configuration error: within a layer, join name '${name}' must be unique`); + } + requires.forEach((require_name) => { + if (!entities.has(require_name)) { + throw new Error(`Data operation cannot operate on unknown provider '${require_name}'`); + } + }); + + const task = new DataOperation(type, initiator, params); + entities.set(name, task); + dependencies.push(`${name}(${requires.join(', ')})`); // Dependency resolver uses the form item(depA, depB) } - requests[ns].outnames.push(raw); - requests[ns].fields.push(field); - requests[ns].trans.push(trans); - }); - return requests; + } + return [entities, dependencies]; } /** - * Fetch data, and create a chain that only connects two data sources if they depend on each other - * @param {Object} state The current "state" of the plot, such as chromosome and start/end positions - * @param {String[]} fields The list of data fields specified in the `layout` for a specific data layer + * @param {Object} plot_state Plot state, which will be passed to every adapter. Includes view extent (chr, start, end) + * @param {Map} entities A list of adapter and join tasks. This is created internally from data layer layouts. + * Keys are layer-local namespaces for data types (like assoc), and values are adapter or join task instances + * (things that implement a method getData). + * @param {String[]} dependencies Instructions on what adapters to fetch from, in what order * @returns {Promise} */ - getData(state, fields) { - var requests = this.__split_requests(fields); - // Create an array of functions that, when called, will trigger the request to the specified datasource - var request_handles = Object.keys(requests).map((key) => { - if (!this._sources.get(key)) { - throw new Error(`Datasource for namespace ${key} not found`); - } - return this._sources.get(key).getData( - state, - requests[key].fields, - requests[key].outnames, - requests[key].trans - ); - }); - //assume the fields are requested in dependent order - //TODO: better manage dependencies - var ret = Promise.resolve({header:{}, body: [], discrete: {}}); - for (var i = 0; i < request_handles.length; i++) { - // If a single datalayer uses multiple sources, perform the next request when the previous one completes - ret = ret.then(request_handles[i]); + getData(plot_state, entities, dependencies) { + if (!dependencies.length) { + return Promise.resolve([]); } - return ret; + // The last dependency (usually the last join operation) determines the last thing returned. + return getLinkedData(plot_state, entities, dependencies, true); } } export default Requester; + +export {DataOperation as _JoinTask}; diff --git a/esm/data/undercomplicate/adapter.js b/esm/data/undercomplicate/adapter.js new file mode 100644 index 00000000..4debe5fd --- /dev/null +++ b/esm/data/undercomplicate/adapter.js @@ -0,0 +1,205 @@ +import {LRUCache} from './lru_cache'; +import {clone} from './util'; + +/** + * @param {boolean} [config.cache_enabled=true] Whether to enable the LRU cache, and store a copy of the normalized and parsed response data. + * Turned on by default for most remote requests; turn off if you are using another datastore (like Vuex) or if the response body uses too much memory. + * @param {number} [config.cache_size=3] How many requests to cache. Track-dependent annotations like LD might benefit + * from caching more items, while very large payloads (like, um, TOPMED LD) might benefit from a smaller cache size. + * For most LocusZoom usages, the cache is "region aware": zooming in will use cached data, not a separate request + * @inheritDoc + * @memberOf module:undercomplicate + */ +class BaseAdapter { + constructor(config = {}) { + this._config = config; + const { + // Cache control + cache_enabled = true, + cache_size = 3, + } = config; + this._enable_cache = cache_enabled; + this._cache = new LRUCache(cache_size); + } + + /** + * Build an object with options that control the request. This can take into account both explicit options, and prior data. + * @param {Object} options Any global options passed in via `getData`. Eg, in locuszoom, every request is passed a copy of `plot.state` as the options object, in which case every adapter would expect certain basic information like `chr, start, end` to be available. + * @param {Object[]} dependent_data If the source is called with dependencies, this function will receive one argument with the fully parsed response data from each other source it depends on. Eg, `ld(assoc)` means that the LD adapter would be called with the data from an association request as a function argument. Each dependency is its own argument: there can be 0, 1, 2, ...N arguments. + * @returns {*} An options object containing initial options, plus any calculated values relevant to the request. + * @public + */ + _buildRequestOptions(options, dependent_data) { + // Perform any pre-processing required that may influence the request. Receives an array with the payloads + // for each request that preceded this one in the dependency chain + // This method may optionally take dependent data into account. For many simple adapters, there won't be any dependent data! + return Object.assign({}, options); + } + + /** + * Determine how this request is uniquely identified in cache. Usually this is an exact match for the same key, but it doesn't have to be. + * The LRU cache implements a `find` method, which means that a cache item can optionally be identified by its node + * `metadata` (instead of exact key match). + * This is useful for situations where the user zooms in to a smaller region and wants the original request to + * count as a cache hit. See subclasses for example. + * @param {object} options Request options from `_buildRequestOptions` + * @returns {*} This is often a string concatenating unique values for a compound cache key, like `chr_start_end`. If null, it is treated as a cache miss. + * @public + */ + _getCacheKey(options) { + /* istanbul ignore next */ + if (this._enable_cache) { + throw new Error('Method not implemented'); + } + return null; + } + + /** + * Perform the act of data retrieval (eg from a URL, blob, or JSON entity) + * @param {object} options Request options from `_buildRequestOptions` + * @returns {Promise} + * @public + */ + _performRequest(options) { + /* istanbul ignore next */ + throw new Error('Not implemented'); + } + + /** + * Convert the response format into a list of objects, one per datapoint. Eg split lines of a text file, or parse a blob of json. + * @param {*} response_text The raw response from performRequest, be it text, binary, etc. For most web based APIs, it is assumed to be text, and often JSON. + * @param {Object} options Request options. These are not typically used when normalizing a response, but the object is available. + * @returns {*} A list of objects, each object representing one row of data `{column_name: value_for_row}` + * @public + */ + _normalizeResponse(response_text, options) { + return response_text; + } + + /** + * Perform custom client-side operations on the retrieved data. For example, add calculated fields or + * perform rapid client-side filtering on cached data. Annotations are applied after cache, which means + * that the same network request can be dynamically annotated/filtered in different ways in response to user interactions. + * + * This result is currently not cached, but it may become so in the future as responsibility for dynamic UI + * behavior moves to other layers of the application. + * @param {Object[]} records + * @param {Object} options + * @returns {*} + * @public + */ + _annotateRecords(records, options) { + return records; + } + + /** + * A hook to transform the response after all operations are done. For example, this can be used to prefix fields + * with a namespace unique to the request, like `log_pvalue` -> `assoc:log_pvalue`. (by applying namespace prefixes to field names last, + * annotations and validation can happen on the actual API payload, without having to guess what the fields were renamed to). + * @param records + * @param options + * @public + */ + _postProcessResponse(records, options) { + return records; + } + + /** + * All adapters must implement this method to asynchronously return data. All other methods are simply internal hooks to customize the actual request for data. + * @param {object} options Shared options for this request. In LocusZoom, this is typically a copy of `plot.state`. + * @param {Array[]} dependent_data Zero or more recordsets corresponding to each individual adapter that this one depends on. + * Can be used to build a request that takes into account prior data. + * @returns {Promise<*>} + */ + getData(options = {}, ...dependent_data) { + // Public facing method to define, perform, and process the request + options = this._buildRequestOptions(options, ...dependent_data); + + const cache_key = this._getCacheKey(options); + + // Then retrieval and parse steps: parse + normalize response, annotate + let result; + if (this._enable_cache && this._cache.has(cache_key)) { + result = this._cache.get(cache_key); + } else { + // Cache the promise (to avoid race conditions in conditional fetch). If anything (like `_getCacheKey`) + // sets a special option value called `_cache_meta`, this will be used to annotate the cache entry + // For example, this can be used to decide whether zooming into a view could be satisfied by a cache entry, + // even if the actual cache key wasn't an exact match. (see subclasses for an example; this class is generic) + result = Promise.resolve(this._performRequest(options)) + // Note: we cache the normalized (parsed) response + .then((text) => this._normalizeResponse(text, options)); + this._cache.add(cache_key, result, options._cache_meta); + // We are caching a promise, which means we want to *un*cache a promise that rejects, eg a failed or interrupted request + // Otherwise, temporary failures couldn't be resolved by trying again in a moment + // TODO: In the future, consider providing a way to skip requests (eg, a sentinel value to flag something + // as not cacheable, like "no dependent data means no request... but maybe in another place this is used, there will be different dependent data and a request would make sense") + result.catch((e) => this._cache.remove(cache_key)); + } + + return result + // Return a deep clone of the data, so that there are no shared mutable references to a parsed object in cache + .then((data) => clone(data)) + .then((records) => this._annotateRecords(records, options)) + .then((records) => this._postProcessResponse(records, options)); + } +} + + +/** + * Fetch data over the web, usually from a REST API that returns JSON + * @param {string} config.url The URL to request + * @extends module:undercomplicate.BaseAdapter + * @inheritDoc + * @memberOf module:undercomplicate + */ +class BaseUrlAdapter extends BaseAdapter { + constructor(config = {}) { + super(config); + this._url = config.url; + } + + + /** + * Default cache key is the URL for this request + * @public + */ + _getCacheKey(options) { + return this._getURL(options); + } + + /** + * In many cases, the base url should be modified with query parameters based on request options. + * @param options + * @returns {*} + * @private + */ + _getURL(options) { + return this._url; + } + + _performRequest(options) { + const url = this._getURL(options); + // Many resources will modify the URL to add query or segment parameters. Base method provides option validation. + // (not validating in constructor allows URL adapter to be used as more generic parent class) + if (!this._url) { + throw new Error('Web based resources must specify a resource URL as option "url"'); + } + return fetch(url).then((response) => { + if (!response.ok) { + throw new Error(response.statusText); + } + return response.text(); + }); + } + + _normalizeResponse(response_text, options) { + if (typeof response_text === 'string') { + return JSON.parse(response_text); + } + // Some custom usages will return other datatypes. These would need to be handled by custom normalization logic in a subclass. + return response_text; + } +} + +export { BaseAdapter, BaseUrlAdapter }; diff --git a/esm/data/undercomplicate/index.js b/esm/data/undercomplicate/index.js new file mode 100644 index 00000000..0c1fcae2 --- /dev/null +++ b/esm/data/undercomplicate/index.js @@ -0,0 +1,17 @@ +/** + * The LocusZoom data retrieval library was originally created as a standalone library, mainly for LZ usage. + * It is inlined into the LocusZoom source code, because there are no other places it is really used, and JSDoc references are much easier + * to generate with a package in the same repo. + * + * See individual adapter classes (and their documentation) for helpful guides on what methods are available, and common customizations for LocusZoom use. + * @see module:LocusZoom_Adapters~BaseLZAdapter + * + * @module undercomplicate + * @public + */ +export { BaseAdapter, BaseUrlAdapter } from './adapter'; +export {LRUCache} from './lru_cache'; +export {getLinkedData} from './requests'; + +import * as joins from './joins'; +export {joins}; diff --git a/esm/data/undercomplicate/joins.js b/esm/data/undercomplicate/joins.js new file mode 100644 index 00000000..95475e60 --- /dev/null +++ b/esm/data/undercomplicate/joins.js @@ -0,0 +1,109 @@ +/** + * Very simple client-side data joins. Useful for aligning records from two datasets based on a common key. + */ +import { clone } from './util'; + + +/** + * Simple grouping function, used to identify sets of records for joining. + * + * Used internally by join helpers, exported mainly for unit testing + * @memberOf module:undercomplicate + * @param {object[]} records + * @param {string} group_key + * @returns {Map} + */ +function groupBy(records, group_key) { + const result = new Map(); + for (let item of records) { + const item_group = item[group_key]; + + if (typeof item_group === 'undefined') { + throw new Error(`All records must specify a value for the field "${group_key}"`); + } + if (typeof item_group === 'object') { + // If we can't group this item, then don't (exclude object, array, map, null, etc from grouping keys) + throw new Error('Attempted to group on a field with non-primitive values'); + } + + let group = result.get(item_group); + if (!group) { + group = []; + result.set(item_group, group); + } + group.push(item); + } + return result; +} + + +function _any_match(type, left, right, left_key, right_key) { + // Helper that consolidates logic for all three join types + const right_index = groupBy(right, right_key); + const results = []; + for (let item of left) { + const left_match_value = item[left_key]; + const right_matches = right_index.get(left_match_value) || []; + if (right_matches.length) { + // Record appears on both left and right; equiv to an inner join + results.push(...right_matches.map((right_item) => Object.assign({}, clone(right_item), clone(item)))); + } else if (type !== 'inner') { + // Record appears on left but not right + results.push(clone(item)); + } + } + + if (type === 'outer') { + // Outer join part! We've already added all left-only and left-right matches; all that's left is the items that only appear on right side + const left_index = groupBy(left, left_key); + for (let item of right) { + const right_match_value = item[right_key]; + const left_matches = left_index.get(right_match_value) || []; + if (!left_matches.length) { + results.push(clone(item)); + } + } + } + return results; +} + +/** + * Equivalent to LEFT OUTER JOIN in SQL. Return all left records, joined to matching right data where appropriate. + * @memberOf module:undercomplicate + * @param {Object[]} left The left side recordset + * @param {Object[]} right The right side recordset + * @param {string} left_key The join field in left records + * @param {string} right_key The join field in right records + * @returns {Object[]} + */ +function left_match(left, right, left_key, right_key) { + return _any_match('left', ...arguments); +} + +/** + * Equivalent to INNER JOIN in SQL. Only return record joins if the key field has a match on both left and right. + * @memberOf module:undercomplicate + * @param {object[]} left The left side recordset + * @param {object[]} right The right side recordset + * @param {string} left_key The join field in left records + * @param {string} right_key The join field in right records + * @returns {Object[]} + */ +function inner_match(left, right, left_key, right_key) { + return _any_match('inner', ...arguments); +} + +/** + * Equivalent to FULL OUTER JOIN in SQL. Return records in either recordset, joined where appropriate. + * @memberOf module:undercomplicate + * @param {object[]} left The left side recordset + * @param {object[]} right The right side recordset + * @param {string} left_key The join field in left records + * @param {string} right_key The join field in right records + * @returns {Object[]} + */ +function full_outer_match(left, right, left_key, right_key) { + return _any_match('outer', ...arguments); +} + +export {left_match, inner_match, full_outer_match, groupBy}; diff --git a/esm/data/undercomplicate/lru_cache.js b/esm/data/undercomplicate/lru_cache.js new file mode 100644 index 00000000..5c16cab2 --- /dev/null +++ b/esm/data/undercomplicate/lru_cache.js @@ -0,0 +1,163 @@ +/** + * Implement an LRU Cache + */ + + +class LLNode { + /** + * A single node in the linked list. Users will only need to deal with this class if using "approximate match" (`cache.find()`) + * @memberOf module:undercomplicate + * @param {string} key + * @param {*} value + * @param {object} metadata + * @param {LLNode} prev + * @param {LLNode} next + */ + constructor(key, value, metadata = {}, prev = null, next = null) { + this.key = key; + this.value = value; + this.metadata = metadata; + this.prev = prev; + this.next = next; + } +} + +class LRUCache { + /** + * Least-recently used cache implementation, with "approximate match" semantics + * @memberOf module:undercomplicate + * @param {number} [max_size=3] + */ + constructor(max_size = 3) { + this._max_size = max_size; + this._cur_size = 0; // replace with map.size so we aren't managing manually? + this._store = new Map(); + + // Track LRU state + this._head = null; + this._tail = null; + + // Validate options + if (max_size === null || max_size < 0) { + throw new Error('Cache "max_size" must be >= 0'); + } + } + + /** + * Check key membership without updating LRU + * @param key + * @returns {boolean} + */ + has(key) { + return this._store.has(key); + } + + /** + * Retrieve value from cache (if present) and update LRU cache to say an item was recently used + * @param key + * @returns {null|*} + */ + get(key) { + const cached = this._store.get(key); + if (!cached) { + return null; + } + if (this._head !== cached) { + // Rewrite the cached value to ensure it is head of the list + this.add(key, cached.value); + } + return cached.value; + } + + /** + * Add an item. Forcibly replaces the existing cached value for the same key. + * @param key + * @param value + * @param {Object} [metadata={}) Metadata associated with an item. Metadata can be used for lookups (`cache.find`) to test for a cache hit based on non-exact match + */ + add(key, value, metadata = {}) { + if (this._max_size === 0) { + // Don't cache items if cache has 0 size. + return; + } + + const prior = this._store.get(key); + if (prior) { + this._remove(prior); + } + + const node = new LLNode(key, value, metadata, null, this._head); + + if (this._head) { + this._head.prev = node; + } else { + this._tail = node; + } + + this._head = node; + this._store.set(key, node); + + if (this._max_size >= 0 && this._cur_size >= this._max_size) { + const old = this._tail; + this._tail = this._tail.prev; + this._remove(old); + } + this._cur_size += 1; + } + + + // Cache manipulation methods + clear() { + this._head = null; + this._tail = null; + this._cur_size = 0; + this._store = new Map(); + } + + // Public method, remove by key + remove(key) { + const cached = this._store.get(key); + if (!cached) { + return false; + } + this._remove(cached); + return true; + } + + // Internal implementation, useful when working on list + _remove(node) { + if (node.prev !== null) { + node.prev.next = node.next; + } else { + this._head = node.next; + } + + if (node.next !== null) { + node.next.prev = node.prev; + } else { + this._tail = node.prev; + } + this._store.delete(node.key); + this._cur_size -= 1; + } + + /** + * Find a matching item in the cache, or return null. This is useful for "approximate match" semantics, + * to check if something qualifies as a cache hit despite not having the exact same key. + * (Example: zooming into a region, where the smaller region is a subset of something already cached) + * @param {function} match_callback A function to be used to test the node as a possible match (returns true or false) + * @returns {null|LLNode} + */ + find(match_callback) { + let node = this._head; + while (node) { + const next = node.next; + if (match_callback(node)) { + return node; + } + node = next; + } + } +} + +export { LRUCache }; diff --git a/esm/data/undercomplicate/requests.js b/esm/data/undercomplicate/requests.js new file mode 100644 index 00000000..aaca7424 --- /dev/null +++ b/esm/data/undercomplicate/requests.js @@ -0,0 +1,99 @@ +/** + * Perform a series of requests, respecting order of operations + * @private + */ + +import {Sorter} from '@hapi/topo'; + + +function _parse_declaration(spec) { + // Parse a dependency declaration like `assoc` or `ld(assoc)` or `join(assoc, ld)`. Return node and edges that can be used to build a graph. + const parsed = /^(?\w+)$|((?\w+)+\(\s*(?[^)]+?)\s*\))/.exec(spec); + if (!parsed) { + throw new Error(`Unable to parse dependency specification: ${spec}`); + } + + let {name_alone, name_deps, deps} = parsed.groups; + if (name_alone) { + return [name_alone, []]; + } + + deps = deps.split(/\s*,\s*/); + return [name_deps, deps]; +} + +/** + * Perform a request for data from a set of providers, taking into account dependencies between requests. + * This can be a mix of network requests or other actions (like join tasks), provided that the provider be some + * object that implements a method `instance.getData` + * + * Each data layer in LocusZoom will translate the internal configuration into a format used by this function. + * This function is never called directly in custom user code. In locuszoom, Requester Handles You + * + * TODO Future: It would be great to add a warning if the final element in the DAG does not reference all dependencies. This is a limitation of the current toposort library we use. + * + * @param {object} shared_options Options passed globally to all requests. In LocusZoom, this is often a copy of "plot.state" + * @param {Map} entities A lookup of named entities that implement the method `instance.getData -> Promise` + * @param {String[]} dependencies A description of how to fetch entities, and what they depend on, like `['assoc', 'ld(assoc)']`. + * **Order will be determined by a DAG and the last item in the DAG is all that is returned.** + * @param {boolean} [consolidate=true] Whether to return all results (almost never used), or just the last item in the resolved DAG. + * This can be a pitfall in common usage: if you forget a "join/consolidate" task, the last result may appear to be missing some data. + * @returns {Promise} + */ +function getLinkedData(shared_options, entities, dependencies, consolidate = true) { + if (!dependencies.length) { + return []; + } + + const parsed = dependencies.map((spec) => _parse_declaration(spec)); + const dag = new Map(parsed); + + // Define the order to perform requests in, based on a DAG + const toposort = new Sorter(); + for (let [name, deps] of dag.entries()) { + try { + toposort.add(name, {after: deps, group: name}); + } catch (e) { + throw new Error(`Invalid or possible circular dependency specification for: ${name}`); + } + } + const order = toposort.nodes; + + // Verify that all requested entities exist by name! + const responses = new Map(); + for (let name of order) { + const provider = entities.get(name); + if (!provider) { + throw new Error(`Data has been requested from source '${name}', but no matching source was provided`); + } + + // Each promise should only be triggered when the things it depends on have been resolved + const depends_on = dag.get(name) || []; + const prereq_promises = Promise.all(depends_on.map((name) => responses.get(name))); + + const this_result = prereq_promises.then((prior_results) => { + // Each request will be told the name of the provider that requested it. This can be used during post-processing, + // eg to use the same endpoint adapter twice and label where the fields came from (assoc.id, assoc2.id) + // This has a secondary effect: it ensures that any changes made to "shared" options in one adapter will + // not leak out to others via a mutable shared object reference. + const options = Object.assign({_provider_name: name}, shared_options); + return provider.getData(options, ...prior_results); + }); + responses.set(name, this_result); + } + return Promise.all([...responses.values()]) + .then((all_results) => { + if (consolidate) { + // Some usages- eg fetch + data join tasks- will only require the last response in the sequence + // Consolidate mode is the common use case, since returning a list of responses is not so helpful (depends on order of request, not order specified) + return all_results[all_results.length - 1]; + } + return all_results; + }); +} + + +export {getLinkedData}; + +// For testing only +export {_parse_declaration}; diff --git a/esm/data/undercomplicate/util.js b/esm/data/undercomplicate/util.js new file mode 100644 index 00000000..42e65468 --- /dev/null +++ b/esm/data/undercomplicate/util.js @@ -0,0 +1,19 @@ +/** + * @private + */ + +import justclone from 'just-clone'; + +/** + * The "just-clone" library only really works for objects and arrays. If given a string, it would mess things up quite a lot. + * @param {object} data + * @returns {*} + */ +function clone(data) { + if (typeof data !== 'object') { + return data; + } + return justclone(data); +} + +export { clone }; diff --git a/esm/ext/lz-aggregation-tests.js b/esm/ext/lz-aggregation-tests.js index f4c2bb71..a131fd42 100644 --- a/esm/ext/lz-aggregation-tests.js +++ b/esm/ext/lz-aggregation-tests.js @@ -34,9 +34,7 @@ import {helpers} from 'raremetal.js'; function install (LocusZoom) { - const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter'); - const BaseApiAdapter = LocusZoom.Adapters.get('BaseApiAdapter'); - const ConnectorSource = LocusZoom.Adapters.get('ConnectorSource'); + const BaseUrlAdapter = LocusZoom.Adapters.get('BaseLZAdapter'); /** * Calculates gene or region-based tests based on provided data, using the raremetal.js library. @@ -46,71 +44,82 @@ function install (LocusZoom) { * @see module:ext/lz-aggregation-tests * @private */ - class AggregationTestSourceLZ extends BaseApiAdapter { - getURL(state, chain, fields) { + class AggregationTestSourceLZ extends BaseUrlAdapter { + constructor(config) { + config.prefix_namespace = false; + super(config); + } + + _buildRequestOptions(state) { + const { aggregation_tests = {} } = state; + const { + // eslint-disable-next-line no-unused-vars + genoset_id = null, genoset_build = null, phenoset_build = null, pheno = null, calcs = {}, masks = [], + } = aggregation_tests; + + aggregation_tests.mask_ids = masks.map((item) => item.name); + // Many of these params will be undefined if no tests defined + state.aggregation_tests = aggregation_tests; + return state; + } + + _getURL(options) { // Unlike most sources, calculations may require access to plot state data even after the initial request // This example source REQUIRES that the external UI widget would store the needed test definitions in a plot state // field called `aggregation_tests` (an object {masks: [], calcs: {}) - const required_info = state.aggregation_tests || {}; - - if (!chain.header) { - chain.header = {}; - } - // All of these fields are required in order to use this datasource. TODO: Add validation? - chain.header.aggregation_genoset_id = required_info.genoset_id || null; // Number - chain.header.aggregation_genoset_build = required_info.genoset_build || null; // String - chain.header.aggregation_phenoset_id = required_info.phenoset_id || null; // Number - chain.header.aggregation_pheno = required_info.pheno || null; // String - chain.header.aggregation_calcs = required_info.calcs || {}; // String[] - const mask_data = required_info.masks || []; - chain.header.aggregation_masks = mask_data; // {name:desc}[] - chain.header.aggregation_mask_ids = mask_data.map(function (item) { - return item.name; - }); // Number[] - return this.url; + return this._url; } - getCacheKey(state, chain, fields) { - this.getURL(state, chain, fields); // TODO: This just sets the chain.header fields + _getCacheKey(options) { + const { chr, start, end, aggregation_tests } = options; + const { genoset_id = null, genoset_build = null, phenoset_id = null, pheno = null, mask_ids } = aggregation_tests; + return JSON.stringify({ - chrom: state.chr, - start: state.start, - stop: state.end, - genotypeDataset: chain.header.aggregation_genoset_id, - phenotypeDataset: chain.header.aggregation_phenoset_id, - phenotype: chain.header.aggregation_pheno, + chrom: chr, + start: start, + stop: end, + genotypeDataset: genoset_id, + phenotypeDataset: phenoset_id, + phenotype: pheno, samples: 'ALL', - genomeBuild: chain.header.aggregation_genoset_build, - masks: chain.header.aggregation_mask_ids, + genomeBuild: genoset_build, + masks: mask_ids, }); } - fetchRequest(state, chain, fields) { - const url = this.getURL(state, chain, fields); - const body = this.getCacheKey(state, chain, fields); + _performRequest(options) { + const url = this._getURL(options); + const body = this._getCacheKey(options); // cache key doubles as request body const headers = { 'Content-Type': 'application/json', }; - return fetch(url, {method: 'POST', body: body, headers: headers}).then((response) => { - if (!response.ok) { - throw new Error(response.statusText); - } - return response.text(); - }).then(function (resp) { - const json = typeof resp == 'string' ? JSON.parse(resp) : resp; - if (json.error) { - // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests, - // with a human-readable error description as a key - // For now, this should be treated strictly as an error - throw new Error(json.error); - } - return json; - }); + return fetch(url, {method: 'POST', body: body, headers: headers}) + .then((response) => { + if (!response.ok) { + throw new Error(response.statusText); + } + return response.text(); + }).then((resp) => { + const json = typeof resp == 'string' ? JSON.parse(resp) : resp; + if (json.error) { + // RAREMETAL-server quirk: The API sometimes returns a 200 status code for failed requests, + // with a human-readable error description as a key + // For now, this should be treated strictly as an error + throw new Error(json.error); + } + return json.data; + }); } - annotateData(records, chain) { - // Operate on the calculated results. The result of this method will be added to chain.discrete + _annotateRecords(records, options) { + // The server response gives covariance for a set of masks, but the actual calculations are done separately. + // Eg, several types of aggtests might use the same covariance matrix. + + // TODO In practice, the test calculations are slow. Investigate caching full results (returning all from performRequest), not just covmat. + // This code is largely for demonstration purposes and does not reflect modern best practices possible in LocusZoom (eg sources + dependencies to link together requests) + const { aggregation_tests } = options; + const { calcs = [], mask_ids = [], masks = [] } = aggregation_tests; // In a page using live API data, the UI would only request the masks it needs from the API. // But in our demos, sometimes boilerplate JSON has more masks than the UI asked for. Limit what calcs we run (by @@ -122,19 +131,16 @@ function install (LocusZoom) { return { groups: [], variants: [] }; } - records.groups = records.groups.filter(function (item) { - return item.groupType === 'GENE'; - }); + records.groups = records.groups.filter((item) => item.groupType === 'GENE'); const parsed = helpers.parsePortalJSON(records); let groups = parsed[0]; const variants = parsed[1]; // Some APIs may return more data than we want (eg simple sites that are just serving up premade scorecov json files). // Filter the response to just what the user has chosen to analyze. - groups = groups.byMask(chain.header.aggregation_mask_ids); + groups = groups.byMask(mask_ids); // Determine what calculations to run - const calcs = chain.header.aggregation_calcs; if (!calcs || Object.keys(calcs).length === 0) { // If no calcs have been requested, then return a dummy placeholder immediately return { variants: [], groups: [], results: [] }; @@ -145,11 +151,11 @@ function install (LocusZoom) { .then(function (res) { // Internally, raremetal helpers track how the calculation is done, but not any display-friendly values // We will annotate each mask name (id) with a human-friendly description for later use - const mask_id_to_desc = chain.header.aggregation_masks.reduce(function (acc, val) { + const mask_id_to_desc = masks.reduce((acc, val) => { acc[val.name] = val.description; return acc; }, {}); - res.data.groups.forEach(function (group) { + res.data.groups.forEach((group) => { group.mask_name = mask_id_to_desc[group.mask]; }); return res.data; @@ -159,18 +165,6 @@ function install (LocusZoom) { throw new Error('Failed to calculate aggregation test results'); }); } - - normalizeResponse(data) { - return data; - } - - combineChainBody(records, chain) { - // aggregation tests are a bit unique, in that the data is rarely used directly- instead it is used to annotate many - // other layers in different ways. The calculated result has been added to `chain.discrete`, but will not be returned - // as part of the response body built up by the chain - return chain.body; - } - } /** @@ -180,40 +174,35 @@ function install (LocusZoom) { * @see module:LocusZoom_Adapters * @private */ - class AssocFromAggregationLZ extends BaseAdapter { - constructor(config) { - if (!config || !config.from) { - throw 'Must specify the name of the source that contains association data'; + class AssocFromAggregationLZ extends BaseUrlAdapter { + _buildRequestOptions(state, agg_results) { + // This adapter just reformats an existing payload from cache (maybe this is better as a data_operation instead of an adapter nowadays?) + if (!agg_results) { + throw new Error('Aggregation test results must be provided'); } - super(...arguments); - } - parseInit(config) { - super.parseInit(config); - this._from = config.from; + state._agg_results = agg_results; + return state; } - getRequest(state, chain, fields) { - // Does not actually make a request. Just pick off the specific bundle of data from a known payload structure. - if (chain.discrete && !chain.discrete[this._from]) { - throw `${this.constructor.SOURCE_NAME} cannot be used before loading required data for: ${this._from}`; - } - // Copy the data so that mutations (like sorting) don't affect the original - return Promise.resolve(JSON.parse(JSON.stringify(chain.discrete[this._from]['variants']))); + _performRequest(options) { + return Promise.resolve(options._agg_results['variants']); } - normalizeResponse(data) { + _normalizeResponse(data) { // The payload structure of the association source is slightly different than the one required by association // plots. For example, we need to parse variant names and convert to log_pvalue const REGEX_EPACTS = new RegExp('(?:chr)?(.+):(\\d+)_?(\\w+)?/?([^_]+)?_?(.*)?'); // match API variant strings - return data.map((one_variant) => { - const match = one_variant.variant.match(REGEX_EPACTS); + return data.map((item) => { + const { variant, altFreq, pvalue } = item; + const match = variant.match(REGEX_EPACTS); + const [_, chromosome, position, ref_allele] = match; return { - variant: one_variant.variant, - chromosome: match[1], - position: +match[2], - ref_allele: match[3], - ref_allele_freq: 1 - one_variant.altFreq, - log_pvalue: -Math.log10(one_variant.pvalue), + variant: variant, + chromosome, + position: +position, + ref_allele, + ref_allele_freq: 1 - altFreq, + log_pvalue: -Math.log10(pvalue), }; }).sort((a, b) => { a = a.variant; @@ -230,57 +219,33 @@ function install (LocusZoom) { } } - /** - * A sample connector that aligns calculated aggregation test data with corresponding gene information. Returns a body - * suitable for use with the genes datalayer. - * - * To use this source, one must specify a fields array that calls first the genes source, then a dummy field from - * this source. The output will be to transparently add several new fields to the genes data. - * @see module:ext/lz-aggregation-tests - * @see module:LocusZoom_Adapters - * @private - */ - class GeneAggregationConnectorLZ extends ConnectorSource { - _getRequiredSources() { - return ['gene_ns', 'aggregation_ns']; - } - - combineChainBody(data, chain) { - // The genes layer receives all results, and displays only the best pvalue for each gene - - // Tie the calculated group-test results to genes with a matching name - const aggregation_source_id = this._source_name_mapping['aggregation_ns']; - const gene_source_id = this._source_name_mapping['gene_ns']; - // This connector assumes that genes are the main body of records from the chain, and that aggregation tests are - // a standalone source that has not acted on genes data yet - const aggregationData = chain.discrete[aggregation_source_id]; - const genesData = chain.discrete[gene_source_id]; + const genes_plus_aggregation = (state, [genes_data, aggregation_data]) => { + // Used to highlight genes with significant aggtest results. Unlike a basic left join, it chooses one specific aggtest with the most significant results - const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test - - aggregationData.groups.forEach(function (result) { - if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) { - groupedAggregation[result.group] = []; - } - groupedAggregation[result.group].push(result.pvalue); - }); - - // Annotate any genes that have test results - genesData.forEach(function (gene) { - const gene_id = gene.gene_name; - const tests = groupedAggregation[gene_id]; - if (tests) { - gene.aggregation_best_pvalue = Math.min.apply(null, tests); - } - }); - return genesData; - } - } + // Tie the calculated group-test results to genes with a matching name + const groupedAggregation = {}; // Group together all tests done on that gene- any mask, any test + aggregation_data.groups.forEach(function (result) { + if (!Object.prototype.hasOwnProperty.call(groupedAggregation, result.group)) { + groupedAggregation[result.group] = []; + } + groupedAggregation[result.group].push(result.pvalue); + }); + + // Annotate any genes that have test results + genes_data.forEach((gene) => { + const gene_id = gene.gene_name; + const tests = groupedAggregation[gene_id]; + if (tests) { + gene.aggregation_best_pvalue = Math.min.apply(null, tests); + } + }); + return genes_data; + }; + LocusZoom.DataFunctions.add('gene_plus_aggregation', genes_plus_aggregation); LocusZoom.Adapters.add('AggregationTestSourceLZ', AggregationTestSourceLZ); LocusZoom.Adapters.add('AssocFromAggregationLZ', AssocFromAggregationLZ); - LocusZoom.Adapters.add('GeneAggregationConnectorLZ', GeneAggregationConnectorLZ); } diff --git a/esm/ext/lz-credible-sets.js b/esm/ext/lz-credible-sets.js index 3ba91ab9..5e4bcbef 100644 --- a/esm/ext/lz-credible-sets.js +++ b/esm/ext/lz-credible-sets.js @@ -15,7 +15,6 @@ * ### Loading and usage * The page must incorporate and load all libraries before this file can be used, including: * - LocusZoom - * - gwas-credible-sets (available via NPM or a related CDN) * * To use in an environment without special JS build tooling, simply load the extension file as JS from a CDN (after any dependencies): * ``` @@ -34,7 +33,7 @@ import {marking, scoring} from 'gwas-credible-sets'; function install (LocusZoom) { - const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter'); + const BaseUMAdapter = LocusZoom.Adapters.get('BaseUMAdapter'); /** * (**extension**) Custom data adapter that calculates the 95% credible set based on provided association data. @@ -43,9 +42,8 @@ function install (LocusZoom) { * @alias module:LocusZoom_Adapters~CredibleSetLZ * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions */ - class CredibleSetLZ extends BaseAdapter { + class CredibleSetLZ extends BaseUMAdapter { /** - * @param {String} config.params.fields.log_pvalue The name of the field containing -log10 pvalue information * @param {Number} [config.params.threshold=0.95] The credible set threshold (eg 95%). Will continue selecting SNPs * until the posterior probabilities add up to at least this fraction of the total. * @param {Number} [config.params.significance_threshold=7.301] Do not perform a credible set calculation for this @@ -55,49 +53,45 @@ function install (LocusZoom) { */ constructor(config) { super(...arguments); - this.dependentSource = true; // Don't do calcs for a region with no assoc data - } - - parseInit(config) { - super.parseInit(...arguments); - if (!(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'`); - } - // Set defaults. Default sig threshold is the line of GWAS significance. (as -log10p) - this.params = Object.assign( + this._config = Object.assign( { threshold: 0.95, significance_threshold: 7.301 }, - this.params + this._config, ); + this._prefix_namespace = false; } - getCacheKey (state, chain, fields) { - const threshold = state.credible_set_threshold || this.params.threshold; + _getCacheKey (state) { + const threshold = state.credible_set_threshold || this._config.threshold; return [threshold, state.chr, state.start, state.end].join('_'); } - fetchRequest(state, chain) { - if (!chain.body.length) { + _buildRequestOptions(options, assoc_data) { + const base = super._buildRequestOptions(...arguments); + base._assoc_data = assoc_data; + return base; + } + + _performRequest(options) { + const {_assoc_data} = options; + if (!_assoc_data.length) { // No credible set can be calculated because there is no association data for this region return Promise.resolve([]); } - const self = this; - // The threshold can be overridden dynamically via `plot.state`, or set when the source is created - const threshold = state.credible_set_threshold || this.params.threshold; + const assoc_logp_name = this._findPrefixedKey(_assoc_data[0], 'log_pvalue'); + + const threshold = this._config.threshold; + // Calculate raw bayes factors and posterior probabilities based on information returned from the API - if (typeof chain.body[0][self.params.fields.log_pvalue] === 'undefined') { - throw new Error('Credible set source could not locate the required fields from a previous request.'); - } - const nlogpvals = chain.body.map((item) => item[self.params.fields.log_pvalue]); + const nlogpvals = _assoc_data.map((item) => item[assoc_logp_name]); - if (!nlogpvals.some((val) => val >= self.params.significance_threshold)) { + if (!nlogpvals.some((val) => val >= this._config.significance_threshold)) { // If NO points have evidence of significance, define the credible set to be empty // (rather than make a credible set that we don't think is meaningful) - return Promise.resolve([]); + return Promise.resolve(_assoc_data); } - const credset_data = []; try { const scores = scoring.bayesFactors(nlogpvals); const posteriorProbabilities = scoring.normalizeProbabilities(scores); @@ -108,33 +102,18 @@ function install (LocusZoom) { const credSetScaled = marking.rescaleCredibleSet(credibleSet); const credSetBool = marking.markBoolean(credibleSet); - // Annotate each response record based on credible set membership - for (let i = 0; i < chain.body.length; i++) { - credset_data.push({ - posterior_prob: posteriorProbabilities[i], - contrib_fraction: credSetScaled[i], - is_member: credSetBool[i], - }); + // Annotate each response record based on credible set membership. This has the effect of joining + // credset results to assoc data directly within the adapter (no separate join needed) + for (let i = 0; i < _assoc_data.length; i++) { + _assoc_data[i][`${options._provider_name}:posterior_prob`] = posteriorProbabilities[i]; + _assoc_data[i][`${options._provider_name}:contrib_fraction`] = credSetScaled[i]; + _assoc_data[i][`${options._provider_name}:is_member`] = credSetBool[i]; } } catch (e) { // If the calculation cannot be completed, return the data without annotation fields console.error(e); } - return Promise.resolve(credset_data); - } - - combineChainBody(data, chain, fields, outnames, trans) { - // At this point namespacing has been applied; add the calculated fields for this source to the chain - if (chain.body.length && data.length) { - for (let i = 0; i < data.length; i++) { - const src = data[i]; - const dest = chain.body[i]; - Object.keys(src).forEach(function (attr) { - dest[attr] = src[attr]; - }); - } - } - return chain.body; + return Promise.resolve(_assoc_data); } } @@ -149,8 +128,8 @@ function install (LocusZoom) { */ const association_credible_set_tooltip = function () { // Extend a known tooltip with an extra row of info showing posterior probabilities - const l = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true }); - l.html += '{{#if {{namespace[credset]}}posterior_prob}}
    Posterior probability: {{{{namespace[credset]}}posterior_prob|scinotation|htmlescape}}{{/if}}'; + const l = LocusZoom.Layouts.get('tooltip', 'standard_association'); + l.html += '{{#if credset:posterior_prob}}
    Posterior probability: {{credset:posterior_prob|scinotation|htmlescape}}{{/if}}'; return l; }(); @@ -163,13 +142,12 @@ function install (LocusZoom) { * @see {@link module:ext/lz-credible-sets} for required extension and installation instructions */ const annotation_credible_set_tooltip = { - namespace: { 'assoc': 'assoc', 'credset': 'credset' }, closable: true, show: { or: ['highlighted', 'selected'] }, hide: { and: ['unhighlighted', 'unselected'] }, - html: '{{{{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}}', + html: '{{assoc:variant|htmlescape}}
    ' + + 'P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
    ' + + '{{#if credset:posterior_prob}}
    Posterior probability: {{credset:posterior_prob|scinotation|htmlescape}}{{/if}}', }; LocusZoom.Layouts.add('tooltip', 'annotation_credible_set', annotation_credible_set_tooltip); @@ -182,20 +160,23 @@ function install (LocusZoom) { const association_credible_set_layer = function () { const base = LocusZoom.Layouts.get('data_layer', 'association_pvalues', { - unnamespaced: true, id: 'associationcredibleset', namespace: { 'assoc': 'assoc', 'credset': 'credset', 'ld': 'ld' }, - fill_opacity: 0.7, - tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set', { unnamespaced: true }), - 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', + data_operations: [ + { + type: 'fetch', + from: ['assoc', 'ld(assoc)', 'credset(assoc)'], + }, + { + type: 'left_match', + name: 'credset_plus_ld', + requires: ['credset', 'ld'], // The credible sets demo wasn't fully moved over to the new data operations system, and as such it is a bit weird + params: ['assoc:position', 'ld:position2'], // FIXME: old LZ used position, because it was less sensitive to format. We'd like to match assoc:variant = ld:variant2, but not every assoc source provides variant data in the way we need. This would need to be fixed via special formatting adjustment later. + }, ], - match: { send: '{{namespace[assoc]}}variant', receive: '{{namespace[assoc]}}variant' }, + fill_opacity: 0.7, + tooltip: LocusZoom.Layouts.get('tooltip', 'association_credible_set'), + match: { send: 'assoc:variant', receive: 'assoc:variant' }, }); base.color.unshift({ field: 'lz_is_match', // Special field name whose presence triggers custom rendering @@ -217,11 +198,15 @@ function install (LocusZoom) { */ const annotation_credible_set_layer = { namespace: { 'assoc': 'assoc', 'credset': 'credset' }, + data_operations: [{ + type: 'fetch', + from: ['assoc', 'credset(assoc)'], + }], id: 'annotationcredibleset', type: 'annotation_track', - id_field: '{{namespace[assoc]}}variant', + id_field: 'assoc:variant', x_axis: { - field: '{{namespace[assoc]}}position', + field: 'assoc:position', }, color: [ { @@ -234,11 +219,10 @@ function install (LocusZoom) { }, '#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' }, + match: { send: 'assoc:variant', receive: 'assoc:variant' }, filters: [ // Specify which points to show on the track. Any selection must satisfy ALL filters - { field: '{{namespace[credset]}}is_member', operator: '=', value: true }, + { field: 'credset:is_member', operator: '=', value: true }, ], behaviors: { onmouseover: [ @@ -254,7 +238,7 @@ function install (LocusZoom) { { action: 'toggle', status: 'selected' }, ], }, - tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set', { unnamespaced: true }), + tooltip: LocusZoom.Layouts.get('tooltip', 'annotation_credible_set'), tooltip_positioning: 'top', }; LocusZoom.Layouts.add('data_layer', 'annotation_credible_set', annotation_credible_set_layer); @@ -270,9 +254,9 @@ function install (LocusZoom) { 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 }, + margin: { top: 25, right: 50, bottom: 10, left: 70 }, inner_border: 'rgb(210, 210, 210)', - toolbar: LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar', 'standard_panel'), axes: { x: { extent: 'state', render: false }, }, @@ -282,7 +266,7 @@ function install (LocusZoom) { x_linked: true, }, data_layers: [ - LocusZoom.Layouts.get('data_layer', 'annotation_credible_set', { unnamespaced: true }), + LocusZoom.Layouts.get('data_layer', 'annotation_credible_set'), ], }; LocusZoom.Layouts.add('panel', 'annotation_credible_set', annotation_credible_set); @@ -295,13 +279,11 @@ function install (LocusZoom) { */ const association_credible_set_panel = function () { const l = LocusZoom.Layouts.get('panel', 'association', { - unnamespaced: true, id: 'associationcrediblesets', - namespace: { 'assoc': 'assoc', 'credset': 'credset' }, data_layers: [ - LocusZoom.Layouts.get('data_layer', 'significance', { unnamespaced: true }), - LocusZoom.Layouts.get('data_layer', 'recomb_rate', { unnamespaced: true }), - LocusZoom.Layouts.get('data_layer', 'association_credible_set', { unnamespaced: true }), + LocusZoom.Layouts.get('data_layer', 'significance'), + LocusZoom.Layouts.get('data_layer', 'recomb_rate'), + LocusZoom.Layouts.get('data_layer', 'association_credible_set'), ], }); // Add "display options" button to control how credible set coloring is overlaid on the standard association plot @@ -324,7 +306,7 @@ function install (LocusZoom) { point_shape: 'circle', point_size: 40, color: { - field: '{{namespace[credset]}}is_member', + field: 'credset:is_member', scale_function: 'if', parameters: { field_value: true, @@ -358,7 +340,7 @@ function install (LocusZoom) { point_size: 40, color: [ { - field: '{{namespace[credset]}}contrib_fraction', + field: 'credset:contrib_fraction', scale_function: 'if', parameters: { field_value: 0, @@ -367,7 +349,7 @@ function install (LocusZoom) { }, { scale_function: 'interpolate', - field: '{{namespace[credset]}}contrib_fraction', + field: 'credset:contrib_fraction', parameters: { breaks: [0, 1], values: ['#fafe87', '#9c0000'], @@ -400,7 +382,7 @@ function install (LocusZoom) { }, }, ], - } + }, ); return l; }(); @@ -419,11 +401,11 @@ function install (LocusZoom) { responsive_resize: true, min_region_scale: 20000, max_region_scale: 1000000, - toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'), panels: [ - LocusZoom.Layouts.get('panel', 'association_credible_set', { unnamespaced: true }), - LocusZoom.Layouts.get('panel', 'annotation_credible_set', { unnamespaced: true }), - LocusZoom.Layouts.get('panel', 'genes', { unnamespaced: true }), + LocusZoom.Layouts.get('panel', 'association_credible_set'), + LocusZoom.Layouts.get('panel', 'annotation_credible_set'), + LocusZoom.Layouts.get('panel', 'genes'), ], }; LocusZoom.Layouts.add('plot', 'association_credible_set', association_credible_set_plot); diff --git a/esm/ext/lz-forest-track.js b/esm/ext/lz-forest-track.js index d534b7ae..cdaa37e6 100644 --- a/esm/ext/lz-forest-track.js +++ b/esm/ext/lz-forest-track.js @@ -99,9 +99,9 @@ function install (LocusZoom) { const y_scale = `y${this.layout.y_axis.axis}_scale`; // Generate confidence interval paths if fields are defined - 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)) { + if (this.layout.confidence_intervals && + this.layout.confidence_intervals.start_field && + this.layout.confidence_intervals.end_field) { // Generate a selection for all forest plot confidence intervals const ci_selection = this.svg.group .selectAll('rect.lz-data_layer-forest.lz-data_layer-forest-ci') @@ -121,8 +121,10 @@ function install (LocusZoom) { return `translate(${x}, ${y})`; }; const ci_width = (d) => { - return this.parent[x_scale](d[this.layout.confidence_intervals.end_field]) - - this.parent[x_scale](d[this.layout.confidence_intervals.start_field]); + const {start_field, end_field} = this.layout.confidence_intervals; + const scale = this.parent[x_scale]; + const result = scale(d[end_field]) - scale(d[start_field]); + return Math.max(result, 1); }; const ci_height = 1; // Create confidence interval rect elements @@ -133,7 +135,7 @@ function install (LocusZoom) { .attr('transform', `translate(0, ${isNaN(this.parent.layout.height) ? 0 : this.parent.layout.height})`) .merge(ci_selection) .attr('transform', ci_transform) - .attr('width', ci_width) + .attr('width', ci_width) // Math.max(ci_width, 1)) .attr('height', ci_height); // Remove old elements as needed @@ -210,12 +212,10 @@ function install (LocusZoom) { class CategoryForest extends Forest { _getDataExtent(data, axis_config) { // In a forest plot, the data range is determined by *three* fields (beta + CI start/end) - const ci_config = this.layout.confidence_intervals; - if (ci_config - && this.layout.fields.includes(ci_config.start_field) - && this.layout.fields.includes(ci_config.end_field)) { - const min = (d) => +d[ci_config.start_field]; - const max = (d) => +d[ci_config.end_field]; + const { confidence_intervals } = this.layout; + if (confidence_intervals && confidence_intervals.start_field && confidence_intervals.end_field) { + const min = (d) => +d[confidence_intervals.start_field]; + const max = (d) => +d[confidence_intervals.end_field]; return [d3.min(data, min), d3.max(data, max)]; } diff --git a/esm/ext/lz-intervals-enrichment.js b/esm/ext/lz-intervals-enrichment.js index a3abe606..2e176ba0 100644 --- a/esm/ext/lz-intervals-enrichment.js +++ b/esm/ext/lz-intervals-enrichment.js @@ -157,10 +157,10 @@ function install(LocusZoom) { closable: true, show: { or: ['highlighted', 'selected'] }, hide: { and: ['unhighlighted', 'unselected'] }, - html: `Tissue: {{{{namespace[intervals]}}tissueId|htmlescape}}
    - Range: {{{{namespace[intervals]}}chromosome|htmlescape}}: {{{{namespace[intervals]}}start|htmlescape}}-{{{{namespace[intervals]}}end|htmlescape}}
    - -log10 p: {{{{namespace[intervals]}}pValue|neglog10|scinotation|htmlescape}}
    - Enrichment (n-fold): {{{{namespace[intervals]}}fold|scinotation|htmlescape}}`, + html: `Tissue: {{intervals:tissueId|htmlescape}}
    + Range: {{intervals:chromosome|htmlescape}}: {{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}
    + -log10 p: {{intervals:pValue|neglog10|scinotation|htmlescape}}
    + Enrichment (n-fold): {{intervals:fold|scinotation|htmlescape}}`, }; /** @@ -172,23 +172,22 @@ function install(LocusZoom) { * @see {@link module:ext/lz-intervals-enrichment} for required extension and installation instructions */ const intervals_layer_layout = { - 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', // not a good ID field for overlapping intervals - start_field: '{{namespace[intervals]}}start', - end_field: '{{namespace[intervals]}}end', + namespace: { 'intervals': 'intervals' }, + match: { send: 'intervals:tissueId' }, + id_field: 'intervals:start', // not a good ID field for overlapping intervals + start_field: 'intervals:start', + end_field: 'intervals:end', filters: [ - { field: '{{namespace[intervals]}}ancestry', operator: '=', value: 'EU' }, - { field: '{{namespace[intervals]}}pValue', operator: '<=', value: 0.05 }, - { field: '{{namespace[intervals]}}fold', operator: '>', value: 2.0 }, + { field: 'intervals:ancestry', operator: '=', value: 'EU' }, + { field: 'intervals:pValue', operator: '<=', value: 0.05 }, + { field: 'intervals:fold', operator: '>', value: 2.0 }, ], y_axis: { axis: 1, - field: '{{namespace[intervals]}}fold', // is this used for other than extent generation? + field: 'intervals:fold', // is this used for other than extent generation? floor: 0, upper_buffer: 0.10, min_extent: [0, 10], @@ -196,7 +195,7 @@ function install(LocusZoom) { fill_opacity: 0.5, // Many intervals overlap: show all, even if the ones below can't be clicked color: [ { - field: '{{namespace[intervals]}}tissueId', + field: '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'], @@ -227,19 +226,18 @@ function install(LocusZoom) { 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', + match: { receive: 'intervals:tissueId' }, + start_field: 'intervals:start', + end_field: 'intervals:end', + merge_field: 'intervals:tissueId', filters: [ { field: 'lz_is_match', operator: '=', value: true }, - { field: '{{namespace[intervals]}}ancestry', operator: '=', value: 'EU' }, - { field: '{{namespace[intervals]}}pValue', operator: '<=', value: 0.05 }, - { field: '{{namespace[intervals]}}fold', operator: '>', value: 2.0 }, + { field: 'intervals:ancestry', operator: '=', value: 'EU' }, + { field: 'intervals:pValue', operator: '<=', value: 0.05 }, + { field: 'intervals:fold', operator: '>', value: 2.0 }, ], color: [{ - field: '{{namespace[intervals]}}tissueId', + field: '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'], @@ -259,18 +257,18 @@ function install(LocusZoom) { tag: 'intervals_enrichment', min_height: 250, height: 250, - margin: { top: 35, right: 50, bottom: 40, left: 50 }, + margin: { top: 35, right: 50, bottom: 40, left: 70 }, inner_border: 'rgb(210, 210, 210)', axes: { x: { label: 'Chromosome {{chr}} (Mb)', - label_offset: 32, + label_offset: 34, tick_format: 'region', extent: 'state', }, y1: { label: 'enrichment (n-fold)', - label_offset: 28, + label_offset: 40, }, }, interaction: { @@ -298,10 +296,10 @@ function install(LocusZoom) { responsive_resize: true, min_region_scale: 20000, max_region_scale: 1000000, - toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'), panels: [ function () { - const base = LocusZoom.Layouts.get('panel', 'association', { unnamespaced: true }); + const base = LocusZoom.Layouts.get('panel', 'association'); base.data_layers.unshift(intervals_highlight_layout); return base; }(), diff --git a/esm/ext/lz-intervals-track.js b/esm/ext/lz-intervals-track.js index cfa59847..da8b3600 100644 --- a/esm/ext/lz-intervals-track.js +++ b/esm/ext/lz-intervals-track.js @@ -8,8 +8,10 @@ * * {@link module:LocusZoom_ScaleFunctions~to_rgb} * * {@link module:LocusZoom_DataLayers~intervals} * * {@link module:LocusZoom_Layouts~standard_intervals} + * * {@link module:LocusZoom_Layouts~bed_intervals_layer} * * {@link module:LocusZoom_Layouts~intervals_layer} * * {@link module:LocusZoom_Layouts~intervals} + * * {@link module:LocusZoom_Layouts~bed_intervals} * * {@link module:LocusZoom_Layouts~interval_association} * * ### Loading and usage @@ -43,7 +45,7 @@ const YCE = Symbol.for('lzYCE'); function install (LocusZoom) { - const BaseApiAdapter = LocusZoom.Adapters.get('BaseApiAdapter'); + const BaseUMAdapter = LocusZoom.Adapters.get('BaseUMAdapter'); const _Button = LocusZoom.Widgets.get('_Button'); const _BaseWidget = LocusZoom.Widgets.get('BaseWidget'); @@ -51,15 +53,17 @@ function install (LocusZoom) { * (**extension**) Retrieve Interval Annotation Data (e.g. BED Tracks), as fetched from the LocusZoom API server (or compatible) * @public * @alias module:LocusZoom_Adapters~IntervalLZ - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseUMAdapter * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions * @param {number} config.params.source The numeric ID for a specific dataset as assigned by the API server */ - class IntervalLZ extends BaseApiAdapter { - getURL(state, chain, fields) { - const source = chain.header.bedtracksource || this.params.source; - const query = `?filter=id in ${source} and chromosome eq '${state.chr}' and start le ${state.end} and end ge ${state.start}`; - return `${this.url}${query}`; + class IntervalLZ extends BaseUMAdapter { + _getURL(request_options) { + const source = this._config.source; + const query = `?filter=id in ${source} and chromosome eq '${request_options.chr}' and start le ${request_options.end} and end ge ${request_options.start}`; + + const base = super._getURL(request_options); + return `${base}${query}`; } } @@ -429,7 +433,7 @@ function install (LocusZoom) { .attr('x', 0) .attr('y', (d) => (d * height)) .attr('width', this.parent.layout.cliparea.width) - .attr('height', height - this.layout.track_vertical_spacing); + .attr('height', Math.max(height - this.layout.track_vertical_spacing, 1)); } status_nodes.exit() .remove(); @@ -444,7 +448,7 @@ function install (LocusZoom) { .attr('id', (d) => this.getElementId(d)) .attr('x', (d) => d[XCS]) .attr('y', (d) => d[YCS]) - .attr('width', (d) => d[XCE] - d[XCS]) + .attr('width', (d) => Math.max(d[XCE] - d[XCS], 1)) .attr('height', this.layout.track_height) .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i)) .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i)); @@ -541,10 +545,10 @@ function install (LocusZoom) { // Choose an appropriate color scheme based on the number of items in the track, and whether or not we are // using explicitly provided itemRgb information _makeColorScheme(category_info) { - // If at least one element has an explicit itemRgb, assume the entire dataset has colors + // If at least one element has an explicit itemRgb, assume the entire dataset has colors. BED intervals require rgb triplets,so assume that colors will always be "r,g,b" format. const has_explicit_colors = category_info.find((item) => item[2]); if (has_explicit_colors) { - return category_info.map((item) => item[2]); + return category_info.map((item) => to_rgb({}, item[2])); } // Use a set of color schemes for common 15, 18, or 25 state models, as specified from: @@ -601,16 +605,17 @@ function install (LocusZoom) { * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions */ const intervals_tooltip_layout = { - namespace: { 'intervals': 'intervals' }, closable: false, show: { or: ['highlighted', 'selected'] }, hide: { and: ['unhighlighted', 'unselected'] }, - html: '{{{{namespace[intervals]}}state_name|htmlescape}}
    {{{{namespace[intervals]}}start|htmlescape}}-{{{{namespace[intervals]}}end|htmlescape}}', + html: '{{intervals:state_name|htmlescape}}
    {{intervals:start|htmlescape}}-{{intervals:end|htmlescape}}', }; /** * (**extension**) A data layer with some preconfigured options for intervals display. This example was designed for chromHMM output, - * in which various states are assigned numeric state IDs and (<= as many) text state names + * in which various states are assigned numeric state IDs and (<= as many) text state names. + * + * This layout is deprecated; most usages would be better served by the bed_intervals_layer layout instead. * @alias module:LocusZoom_Layouts~intervals_layer * @type data_layer * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions @@ -620,23 +625,22 @@ function install (LocusZoom) { 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', // FIXME: This is not a good D3 "are these datums redundant" ID for datasets with multiple intervals heavily overlapping - start_field: '{{namespace[intervals]}}start', - end_field: '{{namespace[intervals]}}end', - track_split_field: '{{namespace[intervals]}}state_name', - track_label_field: '{{namespace[intervals]}}state_name', + id_field: '{{intervals:start}}_{{intervals:end}}_{{intervals:state_name}}', + start_field: 'intervals:start', + end_field: 'intervals:end', + track_split_field: 'intervals:state_name', + track_label_field: 'intervals:state_name', split_tracks: false, always_hide_legend: true, color: [ { // If present, an explicit color field will override any other option (and be used to auto-generate legend) - field: '{{namespace[intervals]}}itemRgb', + field: 'intervals:itemRgb', scale_function: 'to_rgb', }, { // TODO: Consider changing this to stable_choice in the future, for more stable coloring - field: '{{namespace[intervals]}}state_name', + field: 'intervals:state_name', scale_function: 'categorical_bin', parameters: { // Placeholder. Empty categories and values will automatically be filled in when new data loads. @@ -664,8 +668,50 @@ function install (LocusZoom) { tooltip: intervals_tooltip_layout, }; + /** - * (**extension**) A panel containing an intervals data layer, eg for BED tracks + * (**extension**) A data layer with some preconfigured options for intervals display. This example was designed for standard BED3+ files and the field names emitted by the LzParsers extension. + * @alias module:LocusZoom_Layouts~bed_intervals_layer + * @type data_layer + * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions + */ + const bed_intervals_layer_layout = LocusZoom.Layouts.merge({ + id_field: '{{intervals:chromStart}}_{{intervals:chromEnd}}_{{intervals:name}}', + start_field: 'intervals:chromStart', + end_field: 'intervals:chromEnd', + track_split_field: 'intervals:name', + track_label_field: 'intervals:name', + split_tracks: true, + always_hide_legend: false, + color: [ + { + // If present, an explicit color field will override any other option (and be used to auto-generate legend) + field: 'intervals:itemRgb', + scale_function: 'to_rgb', + }, + { + // TODO: Consider changing this to stable_choice in the future, for more stable coloring + field: 'intervals:name', + scale_function: 'categorical_bin', + parameters: { + // Placeholder. Empty categories and values will automatically be filled in when new data loads. + categories: [], + values: [], + null_value: '#B8B8B8', + }, + }, + ], + tooltip: LocusZoom.Layouts.merge({ + html: `Group: {{intervals:name|htmlescape}}
    +Region: {{intervals:chromStart|htmlescape}}-{{intervals:chromEnd|htmlescape}} +{{#if intervals:score}}
    +Score: {{intervals:score|htmlescape}}{{/if}}`, + }, intervals_tooltip_layout), + }, intervals_layer_layout); + + + /** + * (**extension**) A panel containing an intervals data layer, eg for BED tracks. This is a legacy layout whose field names were specific to one partner site. * @alias module:LocusZoom_Layouts~intervals * @type panel * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions @@ -675,9 +721,9 @@ function install (LocusZoom) { tag: 'intervals', min_height: 50, height: 50, - margin: { top: 25, right: 150, bottom: 5, left: 50 }, + margin: { top: 25, right: 150, bottom: 5, left: 70 }, toolbar: (function () { - const l = LocusZoom.Layouts.get('toolbar', 'standard_panel', { unnamespaced: true }); + const l = LocusZoom.Layouts.get('toolbar', 'standard_panel'); l.widgets.push({ type: 'toggle_split_tracks', data_layer_id: 'intervals', @@ -700,9 +746,22 @@ function install (LocusZoom) { data_layers: [intervals_layer_layout], }; + /** + * (**extension**) A panel containing an intervals data layer, eg for BED tracks. These field names match those returned by the LzParsers extension. + * @alias module:LocusZoom_Layouts~bed_intervals + * @type panel + * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions + */ + const bed_intervals_panel_layout = LocusZoom.Layouts.merge({ + // Normal BED tracks show the panel legend in collapsed mode! + min_height: 120, + height: 120, + data_layers: [bed_intervals_layer_layout], + }, intervals_panel_layout); + /** * (**extension**) A plot layout that shows association summary statistics, genes, and interval data. This example assumes - * chromHMM data. (see panel layout) + * chromHMM data. (see panel layout) Few people will use the full intervals plot layout directly outside of an example. * @alias module:LocusZoom_Layouts~interval_association * @type plot * @see {@link module:ext/lz-intervals-track} for required extension and installation instructions @@ -713,10 +772,10 @@ function install (LocusZoom) { responsive_resize: true, min_region_scale: 20000, max_region_scale: 1000000, - toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }), + toolbar: LocusZoom.Layouts.get('toolbar', 'standard_association'), panels: [ LocusZoom.Layouts.get('panel', 'association'), - LocusZoom.Layouts.merge({ unnamespaced: true, min_height: 120, height: 120 }, intervals_panel_layout), + LocusZoom.Layouts.merge({ min_height: 120, height: 120 }, intervals_panel_layout), LocusZoom.Layouts.get('panel', 'genes'), ], }; @@ -726,7 +785,9 @@ function install (LocusZoom) { LocusZoom.Layouts.add('tooltip', 'standard_intervals', intervals_tooltip_layout); LocusZoom.Layouts.add('data_layer', 'intervals', intervals_layer_layout); + LocusZoom.Layouts.add('data_layer', 'bed_intervals', bed_intervals_layer_layout); LocusZoom.Layouts.add('panel', 'intervals', intervals_panel_layout); + LocusZoom.Layouts.add('panel', 'bed_intervals', bed_intervals_panel_layout); LocusZoom.Layouts.add('plot', 'interval_association', intervals_plot_layout); LocusZoom.ScaleFunctions.add('to_rgb', to_rgb); diff --git a/esm/ext/lz-parsers/bed.js b/esm/ext/lz-parsers/bed.js new file mode 100644 index 00000000..bd6410bf --- /dev/null +++ b/esm/ext/lz-parsers/bed.js @@ -0,0 +1,114 @@ +/** + * Parse BED-family files, which have 3-12 columns + * https://genome.ucsc.edu/FAQ/FAQformat.html#format1 + */ + +import {normalizeChr} from './utils'; + +/** + * @private + */ +function _bedMissing(value) { + // BED files specify . as the missing/ null value character + if (value === null || value === undefined || value === '.') { + return null; + } + return value; +} + +/** + * @private + */ +function _hasNum(value) { + // Return a number, or null if value marked as missing + value = _bedMissing(value); + return value ? +value : null; +} + +/** + * Parse a BED file, according to the widely used UCSC (quasi-)specification + * + * NOTE: This original version is aimed at tabix region queries, and carries an implicit assumption that data is the + * only thing that will be parsed. It makes no attempt to identify or handle header rows / metadata fields. + * + * @function + * @alias module:ext/lz-parsers~makeBed12Parser + * @param {object} options + * @param {Boolean} options.normalize Whether to normalize the output to the format expected by LocusZoom (eg type coercion + * for numbers, removing chr chromosome prefixes, and using 1-based and inclusive coordinates instead of 0-based disjoint intervals) + * @return function A configured parser function that runs on one line of text from an input file + */ +function makeBed12Parser({normalize = true} = {}) { + /* + * @param {String} line The line of text to be parsed + */ + return (line) => { + const tokens = line.trim().split('\t'); + // The BED file format has 12 standardized columns. 3 are required and 9 are optional. At present, we will not + // attempt to parse any remaining tokens, or nonstandard files that reuse columns with a different meaning. + // https://en.wikipedia.org/wiki/BED_(file_format) + let [ + chrom, + chromStart, + chromEnd, + name, + score, + strand, + thickStart, + thickEnd, + itemRgb, + blockCount, + blockSizes, + blockStarts, + ] = tokens; + + if (!(chrom && chromStart && chromEnd)) { + throw new Error('Sample data must provide all required BED columns'); + } + + strand = _bedMissing(strand); + + if (normalize) { + // Mandatory fields + chrom = normalizeChr(chrom); + chromStart = +chromStart + 1; // BED is 0 based start, but LZ plots start at 1 + chromEnd = +chromEnd; // 0-based positions, intervals exclude end position + + // Optional fields, require checking for blanks + score = _hasNum(score); + thickStart = _hasNum(thickStart); + thickEnd = _hasNum(thickEnd); + + itemRgb = _bedMissing(itemRgb); + + // LocusZoom doesn't use these fields for rendering. Parsing below is theoretical/best-effort. + blockCount = _hasNum(blockCount); + + blockSizes = _bedMissing(blockSizes); + blockSizes = !blockSizes ? null : blockSizes.replace(/,$/, '').split(',').map((value) => +value); // Comma separated list of sizes -> array of integers + + blockStarts = _bedMissing(blockStarts); + blockStarts = !blockStarts ? null : blockStarts.replace(/,$/, '').split(',').map((value) => +value + 1); // Comma separated list of sizes -> array of integers (start positions) + + if (blockSizes && blockStarts && blockCount && (blockSizes.length !== blockCount || blockStarts.length !== blockCount)) { + throw new Error('Block size and start information should provide the same number of items as in blockCount'); + } + } + return { + chrom, + chromStart, + chromEnd, + name, + score, + strand, + thickStart, + thickEnd, + itemRgb, + blockCount, + blockSizes, + blockStarts, + }; + }; +} + +export { makeBed12Parser }; diff --git a/esm/ext/lz-parsers/gwas/parsers.js b/esm/ext/lz-parsers/gwas/parsers.js new file mode 100644 index 00000000..c9f54bef --- /dev/null +++ b/esm/ext/lz-parsers/gwas/parsers.js @@ -0,0 +1,177 @@ +import {parseMarker} from '../../../helpers/parse'; + +import { + MISSING_VALUES, + has, + parseAlleleFrequency, + parsePvalToLog, normalizeChr, +} from '../utils'; + + +/** + * Specify how to parse a GWAS file, given certain column information. + * Outputs an object with fields in portal API format. + * + * All column options must be provided as 1-indexed column IDs (human-friendly argument values) + * @function + * @alias module:ext/lz-parsers~makeGWASParser + * @param options + * @param [options.marker_col] A single identifier that specifies all of chrom, pos, ref, and alt as a single string field. Eg 1:23_A/C + * @param [options.chrom_col] Chromosome + * @param [options.pos_col] Position + * @param [options.ref_col] Reference allele (relative to human reference genome, eg GRCh37 or 38). + * @param [options.alt_col] Alt allele. Some programs specify generic A1/A2 instead; it is the job of the user to identify which columns of this GWAS are ref and alt. + * @param [options.rsid_col] rsID + * @param options.pvalue_col p-value (or -log10p) + * @param [options.beta_col] + * @param [options.stderr_beta_col] + * @param [options.allele_freq_col] Specify allele frequencies directly + * @param [options.allele_count_col] Specify allele frequencies in terms of count and n_samples + * @param [options.n_samples_col] + * @param [options.is_alt_effect=true] Some programs specify beta and frequency information in terms of ref, others alt. Identify effect allele to orient values to the correct allele. + * @param [options.is_neg_log_pvalue=false] + * @param [options.delimiter='\t'] Since this parser is usually used with tabix data, this is rarely changed (tabix does not accept other delimiters) + * @return {function(string)} A parser function that can be called on each line of text with the provided options + */ +function makeGWASParser( + { + // Required fields + marker_col, // Identify the variant: marker OR chrom/pos/ref/alt + chrom_col, + pos_col, + ref_col, + alt_col, + pvalue_col, // pvalue (or log_pvalue; see options below) + // Optional fields + is_neg_log_pvalue = false, + rsid_col, + beta_col, + stderr_beta_col, + allele_freq_col, // Frequency: given directly, OR in terms of counts + allele_count_col, + n_samples_col, + is_alt_effect = true, // whether effect allele is oriented towards alt. We don't support files like METAL, where ref/alt may switch places per line of the file + delimiter = '\t', + }, +) { + // Column IDs should be 1-indexed (human friendly) + if (has(marker_col) && has(chrom_col) && has(pos_col)) { + throw new Error('Must specify either marker OR chr + pos'); + } + if (!(has(marker_col) || (has(chrom_col) && has(pos_col)))) { + throw new Error('Must specify how to locate marker'); + } + + if (has(allele_count_col) && has(allele_freq_col)) { + throw new Error('Allele count and frequency options are mutually exclusive'); + } + if (has(allele_count_col) && !has(n_samples_col)) { + throw new Error('To calculate allele frequency from counts, you must also provide n_samples'); + } + + + return (line) => { + const fields = line.split(delimiter); + let chr; + let pos; + let ref; + let alt; + let rsid = null; + + let freq; + let beta = null; + let stderr_beta = null; + let alt_allele_freq = null; + let allele_count; + let n_samples; + + if (has(marker_col)) { + [chr, pos, ref, alt] = parseMarker(fields[marker_col - 1], false); + } else if (has(chrom_col) && has(pos_col)) { + chr = fields[chrom_col - 1]; + pos = fields[pos_col - 1]; + } else { + throw new Error('Must specify all fields required to identify the variant'); + } + + chr = normalizeChr(chr); + if (chr.startsWith('RS')) { + throw new Error(`Invalid chromosome specified: value "${chr}" is an rsID`); + } + + if (has(ref_col)) { + ref = fields[ref_col - 1]; + } + + if (has(alt_col)) { + alt = fields[alt_col - 1]; + } + + if (has(rsid_col)) { + rsid = fields[rsid_col - 1]; + } + + if (MISSING_VALUES.has(ref)) { + ref = null; + } + if (MISSING_VALUES.has(alt)) { + alt = null; + } + + if (MISSING_VALUES.has(rsid)) { + rsid = null; + } else if (rsid) { + rsid = rsid.toLowerCase(); + if (!rsid.startsWith('rs')) { + rsid = `rs${rsid}`; + } + } + + const log_pval = parsePvalToLog(fields[pvalue_col - 1], is_neg_log_pvalue); + ref = ref || null; + alt = alt || null; + + if (has(allele_freq_col)) { + freq = fields[allele_freq_col - 1]; + } + if (has(allele_count_col)) { + allele_count = fields[allele_count_col - 1]; + n_samples = fields[n_samples_col - 1]; + } + + if (has(beta_col)) { + beta = fields[beta_col - 1]; + beta = MISSING_VALUES.has(beta) ? null : (+beta); + } + + if (has(stderr_beta_col)) { + stderr_beta = fields[stderr_beta_col - 1]; + stderr_beta = MISSING_VALUES.has(stderr_beta) ? null : (+stderr_beta); + } + + if (allele_freq_col || allele_count_col) { + alt_allele_freq = parseAlleleFrequency({ + freq, + allele_count, + n_samples, + is_alt_effect, + }); + } + const ref_alt = (ref && alt) ? `_${ref}/${alt}` : ''; + return { + chromosome: chr, + position: +pos, + ref_allele: ref ? ref.toUpperCase() : null, + alt_allele: alt ? alt.toUpperCase() : null, + variant: `${chr}:${pos}${ref_alt}`, + rsid, + log_pvalue: log_pval, + beta, + stderr_beta, + alt_allele_freq, + }; + }; +} + + +export { makeGWASParser }; diff --git a/esm/ext/lz-parsers/gwas/sniffers.js b/esm/ext/lz-parsers/gwas/sniffers.js new file mode 100644 index 00000000..e89562a2 --- /dev/null +++ b/esm/ext/lz-parsers/gwas/sniffers.js @@ -0,0 +1,269 @@ +/** + * Sniffers: auto detect file format and parsing options for GWAS files. + */ + +import { parseMarker } from '../../../helpers/parse'; +import { MISSING_VALUES, parsePvalToLog, _missingToNull } from '../utils'; + +/** + * @private + */ +function isNumeric(val) { + // Check whether an unparsed string is a numeric value" + if (MISSING_VALUES.has(val)) { + return true; + } + return !Number.isNaN(+val); +} + +function isHeader(row, { comment_char = '#', delimiter = '\t' } = {}) { + // This assumes two basic rules: the line is not a comment, and gwas data is more likely + // to be numeric than headers + return row.startsWith(comment_char) || row.split(delimiter).every((item) => !isNumeric(item)); +} + +/** + * Compute the levenshtein distance between two strings. Useful for finding the single best column + * name that matches a given rule. + * @private + */ +function levenshtein(a, b) { // https://github.com/trekhleb/javascript-algorithms + // Create empty edit distance matrix for all possible modifications of + // substrings of a to substrings of b. + const distanceMatrix = Array(b.length + 1) + .fill(null) + .map(() => Array(a.length + 1) + .fill(null)); + + // Fill the first row of the matrix. + // If this is first row then we're transforming empty string to a. + // In this case the number of transformations equals to size of a substring. + for (let i = 0; i <= a.length; i += 1) { + distanceMatrix[0][i] = i; + } + + // Fill the first column of the matrix. + // If this is first column then we're transforming empty string to b. + // In this case the number of transformations equals to size of b substring. + for (let j = 0; j <= b.length; j += 1) { + distanceMatrix[j][0] = j; + } + + for (let j = 1; j <= b.length; j += 1) { + for (let i = 1; i <= a.length; i += 1) { + const indicator = a[i - 1] === b[j - 1] ? 0 : 1; + distanceMatrix[j][i] = Math.min( + distanceMatrix[j][i - 1] + 1, // deletion + distanceMatrix[j - 1][i] + 1, // insertion + distanceMatrix[j - 1][i - 1] + indicator, // substitution + ); + } + } + return distanceMatrix[b.length][a.length]; +} + +/** + * Return the index of the first column name that meets acceptance criteria + * @private + * @param {String[]} column_synonyms + * @param {String[]}header_names + * @param {Number} threshold Tolerance for fuzzy matching (# edits) + * @return {Number|null} Index of the best matching column, or null if no match possible + */ +function findColumn(column_synonyms, header_names, threshold = 2) { + // Find the column name that best matches + let best_score = threshold + 1; + let best_match = null; + for (let i = 0; i < header_names.length; i++) { + const header = header_names[i]; + if (header === null) { + // If header is empty, don't consider it for a match + // Nulling a header provides a way to exclude something from future searching + continue; // eslint-disable-line no-continue + } + const score = Math.min(...column_synonyms.map((s) => levenshtein(header, s))); + if (score < best_score) { + best_score = score; + best_match = i; + } + } + return best_match; +} + + +/** + * Return parser configuration for pvalues + * + * Returns 1-based column indices, for compatibility with parsers + * @private + * @param header_row + * @param data_rows + * @returns {{}} + */ +function getPvalColumn(header_row, data_rows) { + // TODO: Allow overrides + const LOGPVALUE_FIELDS = ['neg_log_pvalue', 'log_pvalue', 'log_pval', 'logpvalue']; + const PVALUE_FIELDS = ['pvalue', 'p.value', 'p-value', 'pval', 'p_score', 'p', 'p_value']; + + let ps; + const validateP = (col, data, is_log) => { // Validate pvalues + const cleaned_vals = _missingToNull(data.map((row) => row[col])); + try { + ps = cleaned_vals.map((p) => parsePvalToLog(p, is_log)); + } catch (e) { + return false; + } + return ps.every((val) => !Number.isNaN(val)); + }; + + const log_p_col = findColumn(LOGPVALUE_FIELDS, header_row); + const p_col = findColumn(PVALUE_FIELDS, header_row); + + if (log_p_col !== null && validateP(log_p_col, data_rows, true)) { + return { + pvalue_col: log_p_col + 1, + is_neg_log_pvalue: true, + }; + } + if (p_col && validateP(p_col, data_rows, false)) { + return { + pvalue_col: p_col + 1, + is_neg_log_pvalue: false, + }; + } + // Could not auto-determine an appropriate pvalue column + return null; +} + +/** + * @private + */ +function getChromPosRefAltColumns(header_row, data_rows) { + // Returns 1-based column indices, for compatibility with parsers + // Get from either a marker, or 4 separate columns + const MARKER_FIELDS = ['snpid', 'marker', 'markerid', 'snpmarker', 'chr:position']; + const CHR_FIELDS = ['chrom', 'chr', 'chromosome']; + const POS_FIELDS = ['position', 'pos', 'begin', 'beg', 'bp', 'end', 'ps', 'base_pair_location']; + + // TODO: How to handle orienting ref vs effect? + // Order matters: consider ambiguous field names for ref before alt + const REF_FIELDS = ['A1', 'ref', 'reference', 'allele0', 'allele1']; + const ALT_FIELDS = ['A2', 'alt', 'alternate', 'allele1', 'allele2']; + + const first_row = data_rows[0]; + let marker_col = findColumn(MARKER_FIELDS, header_row); + if (marker_col !== null && parseMarker(first_row[marker_col], true)) { + marker_col += 1; + return { marker_col }; + } + + // If single columns were incomplete, attempt to auto detect 4 separate columns. All 4 must + // be found for this function to report a match. + const headers_marked = header_row.slice(); + const find = [ + ['chrom_col', CHR_FIELDS, true], + ['pos_col', POS_FIELDS, true], + ['ref_col', REF_FIELDS, false], + ['alt_col', ALT_FIELDS, false], + ]; + const config = {}; + for (let i = 0; i < find.length; i++) { + const [col_name, choices, is_required] = find[i]; + const col = findColumn(choices, headers_marked); + if (col === null && is_required) { + return null; + } + if (col !== null) { + config[col_name] = col + 1; + // Once a column has been assigned, remove it from consideration + headers_marked[col] = null; + } + } + return config; +} + +/** + * Identify which columns contain effect size (beta) and stderr of the effect size + * @private + * @param {String[]} header_names + * @param {Array[]} data_rows + * @returns {{}} + */ +function getEffectSizeColumns(header_names, data_rows) { + const BETA_FIELDS = ['beta', 'effect_size', 'alt_effsize', 'effect']; + const STDERR_BETA_FIELDS = ['stderr_beta', 'stderr', 'sebeta', 'effect_size_sd', 'se', 'standard_error']; + + function validate_numeric(col, data) { + const cleaned_vals = _missingToNull(data.map((row) => row[col])); + let nums; + try { + nums = cleaned_vals.filter((val) => val !== null).map((val) => +val); + } catch (e) { + return false; + } + return nums.every((val) => !Number.isNaN(val)); + } + + const beta_col = findColumn(BETA_FIELDS, header_names, 0); + const stderr_beta_col = findColumn(STDERR_BETA_FIELDS, header_names, 0); + + const ret = {}; + if (beta_col !== null && validate_numeric(beta_col, data_rows)) { + ret.beta_col = beta_col + 1; + } + if (stderr_beta_col !== null && validate_numeric(stderr_beta_col, data_rows)) { + ret.stderr_beta_col = stderr_beta_col + 1; + } + return ret; +} + +/** + * Attempt to guess the correct parser settings given a set of header rows and a set of data rows + * @private + * @param {String[]} header_row + * @param {String[][]} data_rows + * @param {int} offset Used to convert between 0 and 1-based indexing. + * @return {Object|null} Returns null if a complete configuration could not suggested. + */ +function guessGWAS(header_row, data_rows, offset = 1) { + // 1. Find a specific set of info: marker OR chr/pos/ref/alt ; pvalue OR log_pvalue + // 2. Validate that we will be able to parse the required info: fields present and make sense + // 3. Based on the field names selected, attempt to infer meaning: verify whether log is used, + // and check ref/alt vs effect/noneffect + // 4. Return a parser config object if all tests pass, OR null. + + // Normalize case and remove leading comment marks from line for easier comparison + const headers = header_row.map((item) => (item ? item.toLowerCase() : item)); + headers[0].replace('/^#+/', ''); + // Lists of fields are drawn from Encore (AssocResultReader) and Pheweb (conf_utils.py) + const pval_config = getPvalColumn(headers, data_rows, offset); + if (!pval_config) { + return null; + } + headers[pval_config.pvalue_col - 1] = null; // Remove this column from consideration + const position_config = getChromPosRefAltColumns(headers, data_rows); + if (!position_config) { + return null; + } + // Remove the position config from consideration for future matches + Object.keys(position_config).forEach((key) => { + headers[position_config[key]] = null; + }); + + const beta_config = getEffectSizeColumns(headers, data_rows); + + if (pval_config && position_config) { + return Object.assign({}, pval_config, position_config, beta_config || {}); + } + return null; +} + +export { + // Public members + guessGWAS, + // Symbols exported for testing + isHeader as _isHeader, + getPvalColumn as _getPvalColumn, + findColumn as _findColumn, + levenshtein as _levenshtein, +}; diff --git a/esm/ext/lz-parsers/index.js b/esm/ext/lz-parsers/index.js new file mode 100644 index 00000000..6025f257 --- /dev/null +++ b/esm/ext/lz-parsers/index.js @@ -0,0 +1,101 @@ +/** + * Optional LocusZoom extension: must be included separately, and after LocusZoom has been loaded + * + * This plugin exports helper function, as well as a few optional extra helpers for rendering the plot. The GWAS parsers can be used without registering the plugin. + * + * To use in an environment without special JS build tooling, simply load the extension file as JS from a CDN (after any dependencies): + * ``` + * + * ``` + * + * To use with ES6 modules, import the helper functions and use them with your layout: + * + * ``` + * import { install, makeGWASParser, makeBed12Parser, makePlinkLDParser } from 'locuszoom/esm/ext/lz-parsers'; + * LocusZoom.use(install); + * ``` + * + * ### Features provided + * * {@link module:LocusZoom_Adapters~UserTabixLD} (if the {@link module:ext/lz-tabix-source} extension is loaded first) + * + * @module ext/lz-parsers + */ + +import { makeBed12Parser } from './bed'; +import { makeGWASParser } from './gwas/parsers'; +import { guessGWAS } from './gwas/sniffers'; +import { makePlinkLdParser } from './ld'; + + +// Most of this plugin consists of standalone functions. But we can add a few simple custom classes to the registry that help to use parsed output +function install(LocusZoom) { + if (LocusZoom.Adapters.has('TabixUrlSource')) { + // Custom Tabix adapter depends on another extension being loaded first + const TabixUrlSource = LocusZoom.Adapters.get('TabixUrlSource'); + const LDServer = LocusZoom.Adapters.get('LDServer'); + + /** + * Load user-provided LD from a tabix file, and filter the returned set of records based on a reference variant. (will attempt to choose a reference variant based on the most significant association variant, if no state.ldrefvar is specified) + * @public + * @alias module:LocusZoom_Adapters~UserTabixLD + * @extends module:LocusZoom_Adapters~TabixUrlSource + * @see {@link module:ext/lz-tabix-source} for required extension and installation instructions + * @see {@link module:ext/lz-parsers} for required extension and installation instructions + */ + class UserTabixLD extends TabixUrlSource { + constructor(config) { + if (!config.limit_fields) { + config.limit_fields = ['variant2', 'position2', 'correlation']; + } + super(config); + } + + _buildRequestOptions(state, assoc_data) { + if (!assoc_data) { + throw new Error('LD request must depend on association data'); + } + // If no state refvar is provided, find the most significant variant in any provided assoc data. + // Assumes that assoc satisfies the "assoc" fields contract, eg has fields variant and log_pvalue + const base = super._buildRequestOptions(...arguments); + if (!assoc_data.length) { + base._skip_request = true; + return base; + } + + // NOTE: Reuses a method from another adapter to mix in functionality + base.ld_refvar = LDServer.prototype.__find_ld_refvar(state, assoc_data); + return base; + } + + _performRequest(options) { + // Skip request if this one depends on other data, and we are in a region with no data + if (options._skip_request) { + return Promise.resolve([]); + } + return super._performRequest(options); + } + + _annotateRecords(records, options) { + // A single PLINK LD file could contain several reference variants (SNP_A) in the same region. + // Only show LD relative to the user-selected refvar in this plot. + return records.filter((item) => item['variant1'] === options.ld_refvar); + } + } + + + LocusZoom.Adapters.add('UserTabixLD', UserTabixLD); + } +} + +if (typeof LocusZoom !== 'undefined') { + // Auto-register the plugin when included as a script tag. ES6 module users must register via LocusZoom.use() + // eslint-disable-next-line no-undef + LocusZoom.use(install); +} + +// Support UMD (single symbol export) +const all = { install, makeBed12Parser, makeGWASParser, guessGWAS, makePlinkLdParser }; + +export default all; + +export { install, makeBed12Parser, makeGWASParser, guessGWAS, makePlinkLdParser }; diff --git a/esm/ext/lz-parsers/ld.js b/esm/ext/lz-parsers/ld.js new file mode 100644 index 00000000..c0ebb214 --- /dev/null +++ b/esm/ext/lz-parsers/ld.js @@ -0,0 +1,37 @@ +/** + * Parsers for custom user-specified LD + */ + +import {normalizeChr} from './utils'; +import {normalizeMarker} from '../../helpers/parse'; + +/** + * Parse the output of plink v1.9 R2 calculations relative to one (or a few) target SNPs. + * See: https://www.cog-genomics.org/plink/1.9/ld and + * reformatting commands at https://www.cog-genomics.org/plink/1.9/other + * @function + * @alias module:ext/lz-parsers~makePlinkLdParser + * @param {object} options + * @param {boolean} [options.normalize=true] Normalize fields to expected datatypes and format; if false, returns raw strings as given in the file + * @return {function} A configured parser function that runs on one line of text from an input file + */ +function makePlinkLdParser({normalize = true} = {}) { + return (line) => { + // Sample headers are below: SNP_A and SNP_B are based on ID column of the VCF + // CHR_A BP_A SNP_A CHR_B BP_B SNP_B R2 + let [chromosome1, position1, variant1, chromosome2, position2, variant2, correlation] = line.trim().split('\t'); + if (normalize) { + chromosome1 = normalizeChr(chromosome1); + chromosome2 = normalizeChr(chromosome2); + variant1 = normalizeMarker(variant1); + variant2 = normalizeMarker(variant2); + position1 = +position1; + position2 = +position2; + correlation = +correlation; + } + + return {chromosome1, position1, variant1, chromosome2, position2, variant2, correlation}; + }; +} + +export { makePlinkLdParser }; diff --git a/esm/ext/lz-parsers/utils.js b/esm/ext/lz-parsers/utils.js new file mode 100644 index 00000000..fb32ae7d --- /dev/null +++ b/esm/ext/lz-parsers/utils.js @@ -0,0 +1,132 @@ +/** + * Constant values used by GWAS parser + */ + +/** + * @private + */ +const MISSING_VALUES = new Set(['', '.', 'NA', 'N/A', 'n/a', 'nan', '-nan', 'NaN', '-NaN', 'null', 'NULL', 'None', null]); + +/** + * @private + */ +const REGEX_PVAL = /([\d.-]+)([\sxeE]*)([0-9-]*)/; + + +/** + * Utility helper that checks for the presence of a numeric value (incl 0), + * eg "has column specified" + * @private + * @param num + * @returns {boolean} + */ +function has(num) { + return Number.isInteger(num); +} + +/** + * Convert all missing values to a standardized input form + * Useful for columns like pvalue, where a missing value explicitly allowed + * @private + */ +function missingToNull(values, nulls = MISSING_VALUES, placeholder = null) { + // TODO Make this operate on a single value; cache for efficiency? + return values.map((v) => (nulls.has(v) ? placeholder : v)); +} + +/** + * Normalize chromosome representations + * @private + * @param {String} chromosome + */ +function normalizeChr(chromosome) { + return chromosome.replace(/^chr/g, '').toUpperCase(); +} + +/** + * Parse (and validate) a given number, and return the -log10 pvalue. + * @private + * @param value + * @param {boolean} is_neg_log + * @returns {number|null} The -log10 pvalue + */ +function parsePvalToLog(value, is_neg_log = false) { + // TODO: In future, generalize this for other values prone to underflow + if (value === null) { + return value; + } + const val = +value; + if (is_neg_log) { // Take as is + return val; + } + // Regular pvalue: validate and convert + if (val < 0 || val > 1) { + throw new Error('p value is not in the allowed range'); + } + // 0-values are explicitly allowed and will convert to infinity by design, as they often + // indicate underflow errors in the input data. + if (val === 0) { + // Determine whether underflow is due to the source data, or value conversion + if (value === '0') { + // The source data is bad, so insert an obvious placeholder value + return Infinity; + } + // h/t @welchr: aggressively turn the underflowing string value into -log10 via regex + // Only do this if absolutely necessary, because it is a performance hit + + let [, base, , exponent] = value.match(REGEX_PVAL); + base = +base; + + if (exponent !== '') { + exponent = +exponent; + } else { + exponent = 0; + } + if (base === 0) { + return Infinity; + } + return -(Math.log10(+base) + +exponent); + } + return -Math.log10(val); +} + +/** + * @private + */ +function parseAlleleFrequency({ freq, allele_count, n_samples, is_alt_effect = true }) { + if (freq !== undefined && allele_count !== undefined) { + throw new Error('Frequency and allele count options are mutually exclusive'); + } + + let result; + if (freq === undefined && (MISSING_VALUES.has(allele_count) || MISSING_VALUES.has(n_samples))) { + // Allele count parsing + return null; + } + if (freq === undefined && allele_count !== undefined) { + result = +allele_count / +n_samples / 2; + } else if (MISSING_VALUES.has(freq)) { // Frequency-based parsing + return null; + } else { + result = +freq; + } + + // No matter how the frequency is specified, this stuff is always done + if (result < 0 || result > 1) { + throw new Error('Allele frequency is not in the allowed range'); + } + if (!is_alt_effect) { // Orient the frequency to the alt allele + return 1 - result; + } + return result; +} + +export { + MISSING_VALUES, + missingToNull as _missingToNull, + has, + normalizeChr, + // Exports for unit testing + parseAlleleFrequency, + parsePvalToLog, +}; diff --git a/esm/ext/lz-tabix-source.js b/esm/ext/lz-tabix-source.js index 5246d71d..61f955c7 100644 --- a/esm/ext/lz-tabix-source.js +++ b/esm/ext/lz-tabix-source.js @@ -9,7 +9,6 @@ * The page must incorporate and load all libraries before this file can be used, including: * - Vendor assets * - LocusZoom - * - tabix-reader (available via NPM or a related CDN) * * To use in an environment without special JS build tooling, simply load the extension file as JS from a CDN (after any dependencies): * ``` @@ -32,17 +31,17 @@ * // Tabix performs region queries. If you are fetching interval data (one end outside the edge of the plot), then * // "overfetching" can help to ensure that data partially outside the view region is retrieved * // If you are fetching single-point data like association summary stats, then overfetching is unnecessary - * params: { overfetch: 0.25 } + * overfetch: 0.25 * }]); * ``` * * @module */ -import tabix from 'tabix-reader'; +import { urlReader } from 'tabix-reader'; function install(LocusZoom) { - const BaseAdapter = LocusZoom.Adapters.get('BaseAdapter'); + const BaseLZAdapter = LocusZoom.Adapters.get('BaseLZAdapter'); /** * Loads data from a remote Tabix file (if the file host has been configured with proper @@ -52,32 +51,32 @@ function install(LocusZoom) { * * @alias module:LocusZoom_Adapters~TabixUrlSource * @see {@link module:ext/lz-tabix-source} for required extension and installation instructions - * @see module:LocusZoom_Adapters~BaseApiAdapter + * @see module:LocusZoom_Adapters~BaseLZAdapter * @param {function} config.parser_func A function that parses a single line of text and returns (usually) a * structured object of data fields * @param {string} config.url_data The URL for the bgzipped and tabix-indexed file * @param {string} [config.url_tbi] The URL for the tabix index. Defaults to `url_data` + '.tbi' - * @param {number} [config.params.overfetch = 0] Optionally fetch more data than is required to satisfy the + * @param {Promise} [config.reader] The URL for tabix-reader instance that provides the data. Mutually exclusive with providing a URL. + * Most LocusZoom usages will not pass an external reader. This option exists for websites like LocalZoom that accept + * many file formats and want to perform input validation before creating the plot: "select parser options", etc. + * @param {number} [config.overfetch = 0] Optionally fetch more data than is required to satisfy the * region query. (specified as a fraction of the region size, 0-1). * Useful for sources where interesting features might lie near the edges of the plot, eg BED track intervals. */ - class TabixUrlSource extends BaseAdapter { - parseInit(init) { - if (!init.parser_func || !init.url_data) { + class TabixUrlSource extends BaseLZAdapter { + constructor(config) { + super(config); + if (!config.parser_func || !(config.url_data || config.reader)) { throw new Error('Tabix source is missing required configuration options'); } - this.parser = init.parser_func; - // TODO: In the future, accept a pre-configured reader instance (as an alternative to the URL). Most useful - // for UIs that want to validate the tabix file before adding it to the plot, like LocalZoom. - this.url_data = init.url_data; - this.url_tbi = init.url_tbi || `${this.url_data}.tbi`; + this.parser = config.parser_func; + this.url_data = config.url_data; + this.url_tbi = config.url_tbi || `${this.url_data}.tbi`; // In tabix mode, sometimes we want to fetch a slightly larger region than is displayed, in case a // feature is on the edge of what the tabix query would return. // Specify overfetch in units of % of total region size. ("fetch 10% extra before and after") - const params = init.params || {}; - this.params = params; - this._overfetch = params.overfetch || 0; + this._overfetch = config.overfetch || 0; if (this._overfetch < 0 || this._overfetch > 1) { throw new Error('Overfetch must be specified as a fraction (0-1) of the requested region size'); @@ -85,22 +84,26 @@ function install(LocusZoom) { // Assuming that the `tabix-reader` library has been loaded via a CDN, this will create the reader // Since fetching the index is a remote operation, all reader usages will be via an async interface. - this._reader_promise = tabix.urlReader(this.url_data, this.url_tbi).catch(function () { - throw new Error('Failed to create a tabix reader from the provided URL'); - }); + if (this.url_data) { + this._reader_promise = urlReader(this.url_data, this.url_tbi).catch(function () { + throw new Error('Failed to create a tabix reader from the provided URL'); + }); + } else { + this._reader_promise = Promise.resolve(config.reader); + } } - fetchRequest(state /*, chain, fields */) { + _performRequest(options) { return new Promise((resolve, reject) => { // Ensure that the reader is fully created (and index available), then make a query - const region_start = state.start; - const region_end = state.end; + const region_start = options.start; + const region_end = options.end; const extra_amount = this._overfetch * (region_end - region_start); - const start = state.start - extra_amount; - const end = state.end + extra_amount; + const start = options.start - extra_amount; + const end = options.end + extra_amount; this._reader_promise.then((reader) => { - reader.fetch(state.chr, start, end, function (data, err) { + reader.fetch(options.chr, start, end, function (data, err) { if (err) { reject(new Error('Could not read requested region. This may indicate an error with the .tbi index.')); } @@ -110,9 +113,9 @@ function install(LocusZoom) { }); } - normalizeResponse(data) { + _normalizeResponse(records) { // Parse the data from lines of text to objects - return data.map(this.parser); + return records.map(this.parser); } } diff --git a/esm/ext/lz-widget-addons.js b/esm/ext/lz-widget-addons.js index 0ecf02c0..39c37a2f 100644 --- a/esm/ext/lz-widget-addons.js +++ b/esm/ext/lz-widget-addons.js @@ -226,7 +226,7 @@ function install(LocusZoom) { this.button.menu.setPopulate(() => { this.button.menu.inner_selector.html(''); const table = this.button.menu.inner_selector.append('table'); - this.parent_panel.data_layer_ids_by_z_index.slice().reverse().forEach((id, idx) => { + this.parent_panel._data_layer_ids_by_z_index.slice().reverse().forEach((id, idx) => { const data_layer = this.parent_panel.data_layers[id]; const name = (typeof data_layer.layout.name != 'string') ? data_layer.id : data_layer.layout.name; const row = table.append('tr'); @@ -237,7 +237,7 @@ function install(LocusZoom) { const status_idx = STATUS_ADJECTIVES.indexOf(status_adj); const status_verb = STATUS_VERBS[status_idx]; let html, onclick, highlight; - if (data_layer.global_statuses[status_adj]) { + if (data_layer._global_statuses[status_adj]) { html = STATUS_ANTIVERBS[status_idx]; onclick = `un${status_verb}AllElements`; highlight = '-highlighted'; @@ -257,7 +257,7 @@ function install(LocusZoom) { }); // Sort layer buttons const at_top = (idx === 0); - const at_bottom = (idx === (this.parent_panel.data_layer_ids_by_z_index.length - 1)); + const at_bottom = (idx === (this.parent_panel._data_layer_ids_by_z_index.length - 1)); const td = row.append('td'); td.append('a') .attr('class', `lz-toolbar-button lz-toolbar-button-group-start lz-toolbar-button-${this.layout.color}${at_bottom ? '-disabled' : ''}`) @@ -297,13 +297,13 @@ function install(LocusZoom) { } const covariates_model_tooltip = function () { - const covariates_model_association = LocusZoom.Layouts.get('tooltip', 'standard_association', { unnamespaced: true }); + const covariates_model_association = LocusZoom.Layouts.get('tooltip', 'standard_association'); covariates_model_association.html += 'Condition on Variant
    '; return covariates_model_association; }(); const covariates_model_plot = function () { - const covariates_model_plot_toolbar = LocusZoom.Layouts.get('toolbar', 'standard_association', { unnamespaced: true }); + const covariates_model_plot_toolbar = LocusZoom.Layouts.get('toolbar', 'standard_association'); covariates_model_plot_toolbar.widgets.push({ type: 'covariates_model', button_html: 'Model', diff --git a/esm/helpers/common.js b/esm/helpers/common.js index c80abf50..e0127e06 100644 --- a/esm/helpers/common.js +++ b/esm/helpers/common.js @@ -247,7 +247,7 @@ function debounce(func, delay = 500) { clearTimeout(timer); timer = setTimeout( () => func.apply(this, arguments), - delay + delay, ); }; } diff --git a/esm/helpers/display.js b/esm/helpers/display.js index 91f461ec..6f67afd5 100644 --- a/esm/helpers/display.js +++ b/esm/helpers/display.js @@ -160,7 +160,7 @@ function parseFields(html, data, extra) { // `tokens` is like [token,...] // `token` is like {text: '...'} or {variable: 'foo|bar'} or {condition: 'foo|bar'} or {close: 'if'} const tokens = []; - const regex = /{{(?:(#if )?([A-Za-z0-9_:|]+)|(#else)|(\/if))}}/; + const regex = /{{(?:(#if )?([\w+_:|]+)|(#else)|(\/if))}}/; while (html.length > 0) { const m = regex.exec(html); if (!m) { diff --git a/esm/helpers/layouts.js b/esm/helpers/layouts.js index 3ad87165..e61a1380 100644 --- a/esm/helpers/layouts.js +++ b/esm/helpers/layouts.js @@ -21,52 +21,38 @@ const triangledown = { }; /** - * Apply namespaces to layout, recursively + * Apply shared namespaces to a layout, recursively. + * + * Overriding namespaces can be used to identify where to retrieve data from, but not to add new data sources to a layout. + * For that, a key would have to be added to `layout.namespace` directly. + * + * Detail: This function is a bit magical. Whereas most layouts overrides are copied over verbatim (merging objects and nested keys), applyNamespaces will *only* copy + * over keys that are relevant to that data layer. Eg, if overrides specifies a key called "red_herring", + * an association data layer will ignore that data source entirely, and not copy it into `assoc_layer.namespace`. + * + * Only items under a key called `namespace` are given this special treatment. This allows a single call to `Layouts.get('plot'...)` to specify + * namespace overrides for many layers in one convenient place, without accidentally telling every layer to request all possible data for itself. * @private */ -function applyNamespaces(element, namespace, default_namespace) { - if (namespace) { - if (typeof namespace == 'string') { - namespace = { default: namespace }; - } - } else { - namespace = { default: '' }; +function applyNamespaces(layout, shared_namespaces) { + shared_namespaces = shared_namespaces || {}; + if (!layout || typeof layout !== 'object' || typeof shared_namespaces !== 'object') { + throw new Error('Layout and shared namespaces must be provided as objects'); } - if (typeof element == 'string') { - const re = /\{\{namespace(\[[A-Za-z_0-9]+\]|)\}\}/g; - let match, base, key, resolved_namespace; - const replace = []; - while ((match = re.exec(element)) !== null) { - base = match[0]; - key = match[1].length ? match[1].replace(/(\[|\])/g, '') : null; - resolved_namespace = default_namespace; - if (namespace != null && typeof namespace == 'object' && typeof namespace[key] != 'undefined') { - resolved_namespace = namespace[key] + (namespace[key].length ? ':' : ''); - } - replace.push({ base: base, namespace: resolved_namespace }); - } - for (let r in replace) { - element = element.replace(replace[r].base, replace[r].namespace); - } - } else if (typeof element == 'object' && element != null) { - if (typeof element.namespace != 'undefined') { - const merge_namespace = (typeof element.namespace == 'string') ? { default: element.namespace } : element.namespace; - namespace = merge(namespace, merge_namespace); - } - let namespaced_element, namespaced_property; - for (let property in element) { - if (property === 'namespace') { - continue; - } - namespaced_element = applyNamespaces(element[property], namespace, default_namespace); - namespaced_property = applyNamespaces(property, namespace, default_namespace); - if (property !== namespaced_property) { - delete element[property]; - } - element[namespaced_property] = namespaced_element; + + for (let [field_name, item] of Object.entries(layout)) { + if (field_name === 'namespace') { + Object.keys(item).forEach((requested_ns) => { + const override = shared_namespaces[requested_ns]; + if (override) { + item[requested_ns] = override; + } + }); + } else if (item !== null && (typeof item === 'object')) { + layout[field_name] = applyNamespaces(item, shared_namespaces); } } - return element; + return layout; } /** @@ -118,6 +104,8 @@ function merge(custom_layout, default_layout) { } function deepCopy(item) { + // FIXME: initial attempt to replace this with a more efficient deep clone method caused merge() to break; revisit in future. + // Replacing this with a proper clone would be the key blocker to allowing functions and non-JSON values (like infinity) in layout objects return JSON.parse(JSON.stringify(item)); } @@ -139,6 +127,52 @@ function nameToSymbol(shape) { return d3[factory_name] || null; } + +/** + * Find all references to namespaced fields within a layout object. This is used to validate that a set of provided + * data adapters will actually give all the information required to draw the plot. + * @param {Object} layout + * @param {Array|null} prefixes A list of allowed namespace prefixes. (used to differentiate between real fields, + * and random sentences that match an arbitrary pattern. + * @param {RegExp|null} field_finder On recursive calls, pass the regexp we constructed the first time + * @return {Set} + */ +function findFields(layout, prefixes, field_finder = null) { + const fields = new Set(); + if (!field_finder) { + if (!prefixes.length) { + // A layer that doesn't ask for external data does not need to check if the provider returns expected fields + return fields; + } + const all_ns = prefixes.join('|'); + + // Locates any reference within a template string to to `ns:field`, `{{ns:field}}`, or `{{#if ns:field}}`. + // By knowing the list of allowed NS prefixes, we can be much more confident in avoiding spurious matches + field_finder = new RegExp(`(?:{{)?(?:#if *)?((?:${all_ns}):\\w+)`, 'g'); + } + + for (const value of Object.values(layout)) { + const value_type = typeof value; + let matches = []; + if (value_type === 'string') { + let a_match; + while ((a_match = field_finder.exec(value)) !== null) { + matches.push(a_match[1]); + } + } else if (value !== null && value_type === 'object') { + matches = findFields(value, prefixes, field_finder); + } else { + // Only look for field names in strings or compound values + continue; + } + for (let m of matches) { + fields.add(m); + } + } + return fields; +} + + /** * A utility helper for customizing one part of a pre-made layout. Whenever a primitive value is found (eg string), * replaces *exact match* @@ -166,7 +200,7 @@ function renameField(layout, old_name, new_name, warn_transforms = true) { (acc, key) => { acc[key] = renameField(layout[key], old_name, new_name, warn_transforms); return acc; - }, {} + }, {}, ); } else if (this_type !== 'string') { // Field names are always strings. If the value isn't a string, don't even try to change it. @@ -206,7 +240,7 @@ function mutate_attrs(layout, selector, value_or_callable) { return mutate( layout, selector, - value_or_callable + value_or_callable, ); } @@ -222,4 +256,4 @@ function query_attrs(layout, selector) { return query(layout, selector); } -export { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, renameField }; +export { applyNamespaces, deepCopy, merge, mutate_attrs, query_attrs, nameToSymbol, findFields, renameField }; diff --git a/esm/helpers/parse.js b/esm/helpers/parse.js new file mode 100644 index 00000000..b8dc25c9 --- /dev/null +++ b/esm/helpers/parse.js @@ -0,0 +1,52 @@ +/** + * Parse useful entities + */ + +/** + * @private + */ +const REGEX_MARKER = /^(?:chr)?([a-zA-Z0-9]+?)[_:-](\d+)[_:|-]?(\w+)?[/_:|-]?([^_]+)?_?(.*)?/; + +/** + * Parse a single marker, cleaning up values as necessary + * @private + * @param {String} value + * @param {boolean} test If called in testing mode, do not throw an exception + * @returns {Array} chr, pos, ref, alt (if match found; ref and alt optional) + */ +function parseMarker(value, test = false) { + const match = value && value.match(REGEX_MARKER); + if (match) { + return match.slice(1); + } + if (!test) { + throw new Error(`Could not understand marker format for ${value}. Should be of format chr:pos or chr:pos_ref/alt`); + } else { + return null; + } +} + +/** + * Normalize a provided variant string into the EPACTS-style `chrom:pos_ref/alt` format expected by LocusZoom and the Michigan LD Server + * This allows harmonizing various input data to a consistent format + * @private + * @param {String} variant A string that specifies variant information in one of several common formats (like chr1:99_A/C, 1-99-A-C, 1:99:A:C, etc) + */ +function normalizeMarker(variant) { + const match = parseMarker(variant); + if (!match) { + throw new Error(`Unable to normalize marker format for variant: ${variant}`); + } + const [chrom, pos, ref, alt] = match; + let normalized = `${chrom}:${pos}`; + if (ref && alt) { + normalized += `_${ref}/${alt}`; + } + return normalized; +} + + +export { + parseMarker, + normalizeMarker, +}; diff --git a/esm/helpers/scalable.js b/esm/helpers/scalable.js index bff37d21..16799316 100644 --- a/esm/helpers/scalable.js +++ b/esm/helpers/scalable.js @@ -18,10 +18,10 @@ import * as d3 from 'd3'; * @param {*} parameters.else The value to return if the input value does not match the field value. Optional. If not * defined this scale function will return null (or value of null_value parameter, if defined) when input value fails * to match field_value. - * @param {*} input value + * @param {*} value value */ -const if_value = (parameters, input) => { - if (typeof input == 'undefined' || parameters.field_value !== input) { +const if_value = (parameters, value) => { + if (typeof value == 'undefined' || parameters.field_value !== value) { if (typeof parameters.else != 'undefined') { return parameters.else; } else { @@ -44,17 +44,17 @@ const if_value = (parameters, input) => { * equal length to breaks parameter. Each entry n represents the value to return if the input value is greater than * or equal to break n and less than or equal to break n+1 (or break n+1 doesn't exist). * @param {*} parameters.null_value - * @param {*} input value + * @param {*} value value * @returns {*} */ -const numerical_bin = (parameters, input) => { +const numerical_bin = (parameters, value) => { const breaks = parameters.breaks || []; const values = parameters.values || []; - if (typeof input == 'undefined' || input === null || isNaN(+input)) { + if (typeof value == 'undefined' || value === null || isNaN(+value)) { return (parameters.null_value ? parameters.null_value : null); } const threshold = breaks.reduce(function (prev, curr) { - if (+input < prev || (+input >= prev && +input < curr)) { + if (+value < prev || (+value >= prev && +value < curr)) { return prev; } else { return curr; @@ -91,6 +91,7 @@ const categorical_bin = (parameters, value) => { * choices if the user pans to a region with a different number/order of items. (the same item is assigned a different color) * * See also: stable_choice. + * @function ordinal_cycle * @param {Object} parameters * @param {Array} parameters.values A list of option values * @return {*} @@ -114,6 +115,9 @@ const ordinal_cycle = (parameters, value, index) => { * CAVEAT: Some datasets do not return true datum ids, but instead append synthetic ID fields ("item 1, item2"...) * just to appease D3. This hash function only works if there is a meaningful, stable identifier in the data, * like a category or gene name. + * + * @function stable_choice + * * @param parameters * @param {Array} [parameters.values] A list of options to choose from * @param {Number} [parameters.max_cache_size=500] The maximum number of values to cache. This option is mostly used @@ -167,19 +171,19 @@ let stable_choice = (parameters, value, index) => { * colors, shapes, etc. * @parameters {*} parameters.null_value */ -const interpolate = (parameters, input) => { +const interpolate = (parameters, value) => { var breaks = parameters.breaks || []; var values = parameters.values || []; var nullval = (parameters.null_value ? parameters.null_value : null); if (breaks.length < 2 || breaks.length !== values.length) { return nullval; } - if (typeof input == 'undefined' || input === null || isNaN(+input)) { + if (typeof value == 'undefined' || value === null || isNaN(+value)) { return nullval; } - if (+input <= parameters.breaks[0]) { + if (+value <= parameters.breaks[0]) { return values[0]; - } else if (+input >= parameters.breaks[parameters.breaks.length - 1]) { + } else if (+value >= parameters.breaks[parameters.breaks.length - 1]) { return values[breaks.length - 1]; } else { var upper_idx = null; @@ -187,14 +191,14 @@ const interpolate = (parameters, input) => { if (!idx) { return; } - if (breaks[idx - 1] <= +input && breaks[idx] >= +input) { + if (breaks[idx - 1] <= +value && breaks[idx] >= +value) { upper_idx = idx; } }); if (upper_idx === null) { return nullval; } - const normalized_input = (+input - breaks[upper_idx - 1]) / (breaks[upper_idx] - breaks[upper_idx - 1]); + const normalized_input = (+value - breaks[upper_idx - 1]) / (breaks[upper_idx] - breaks[upper_idx - 1]); if (!isFinite(normalized_input)) { return nullval; } @@ -203,4 +207,51 @@ const interpolate = (parameters, input) => { }; -export { categorical_bin, stable_choice, if_value, interpolate, numerical_bin, ordinal_cycle }; +/** + * Calculate the effect direction based on beta, or the combination of beta and standard error. + * Typically used with phewas plots, to show point shape based on the beta and stderr_beta fields. + * + * @function effect_direction + * @param parameters + * @param parameters.'+' The value to return if the effect direction is positive + * @param parameters.'-' The value to return if the effect direction is positive + * @param parameters.beta_field The name of the field containing beta + * @param parameters.stderr_beta_field The name of the field containing stderr_beta + * @param {Object} input This function should receive the entire datum object, rather than one single field + * @returns {null} + */ +function effect_direction(parameters, input) { + if (input === undefined) { + return null; + } + + const { beta_field, stderr_beta_field, '+': plus_result = null, '-': neg_result = null } = parameters; + + if (!beta_field || !stderr_beta_field) { + throw new Error(`effect_direction must specify how to find required 'beta' and 'stderr_beta' fields`); + } + + const beta_val = input[beta_field]; + const se_val = input[stderr_beta_field]; + + if (beta_val !== undefined) { + if (se_val !== undefined) { + if ((beta_val - 1.96 * se_val) > 0) { + return plus_result; + } else if ((beta_val + 1.96 * se_val) < 0) { + return neg_result || null; + } + } else { + if (beta_val > 0) { + return plus_result; + } else if (beta_val < 0) { + return neg_result; + } + } + } + // Note: The original PheWeb implementation allowed odds ratio in place of beta/se. LZ core is a bit more rigid + // about expected data formats for layouts. + return null; +} + +export { categorical_bin, stable_choice, if_value, interpolate, numerical_bin, ordinal_cycle, effect_direction }; diff --git a/esm/index.js b/esm/index.js index 12019b0f..dcea1ae0 100644 --- a/esm/index.js +++ b/esm/index.js @@ -14,11 +14,12 @@ import { populate } from './helpers/display'; import { ADAPTERS as Adapters, DATA_LAYERS as DataLayers, - WIDGETS as Widgets, + DATA_OPS as DataFunctions, LAYOUTS as Layouts, MATCHERS as MatchFunctions, SCALABLE as ScaleFunctions, TRANSFORMS as TransformationFunctions, + WIDGETS as Widgets, } from './registry'; @@ -30,6 +31,7 @@ const LocusZoom = { // Registries for plugin system Adapters, DataLayers, + DataFunctions, Layouts, MatchFunctions, ScaleFunctions, diff --git a/esm/layouts/index.js b/esm/layouts/index.js index aedf82ce..a9e8f0ef 100644 --- a/esm/layouts/index.js +++ b/esm/layouts/index.js @@ -23,14 +23,13 @@ const LZ_SIG_THRESHOLD_LOGP = 7.301; // -log10(.05/1e6) * Tooltip Layouts */ const standard_association_tooltip = { - namespace: { 'assoc': 'assoc' }, closable: true, show: { or: ['highlighted', 'selected'] }, hide: { and: ['unhighlighted', 'unselected'] }, - html: `{{{{namespace[assoc]}}variant|htmlescape}}
    - P Value: {{{{namespace[assoc]}}log_pvalue|logtoscinotation|htmlescape}}
    - Ref. Allele: {{{{namespace[assoc]}}ref_allele|htmlescape}}
    - {{#if {{namespace[ld]}}isrefvar}}LD Reference Variant{{#else}} + html: `{{assoc:variant|htmlescape}}
    + P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
    + Ref. Allele: {{assoc:ref_allele|htmlescape}}
    + {{#if lz_is_ld_refvar}}LD Reference Variant{{#else}} {{{{namespace[catalog]}}variant|htmlescape}}
    ' + html: '{{catalog:variant|htmlescape}}
    ' + 'Catalog entries: {{n_catalog_matches|htmlescape}}
    ' - + 'Top Trait: {{{{namespace[catalog]}}trait|htmlescape}}
    ' - + 'Top P Value: {{{{namespace[catalog]}}log_pvalue|logtoscinotation}}
    ' + + 'Top Trait: {{catalog:trait|htmlescape}}
    ' + + 'Top P Value: {{catalog:log_pvalue|logtoscinotation}}
    ' // User note: if a different catalog is used, the tooltip will need to be replaced with a different link URL - + 'More:
    GWAS catalog / dbSNP', + + 'More: GWAS catalog / dbSNP', }; const coaccessibility_tooltip = { - namespace: { 'access': 'access' }, closable: true, show: { or: ['highlighted', 'selected'] }, hide: { and: ['unhighlighted', 'unselected'] }, // TODO: Is there a more generic terminology? (eg not every technique is in terms of cis-regulatory element) html: 'Regulatory element
    ' + - '{{{{namespace[access]}}start1|htmlescape}}-{{{{namespace[access]}}end1|htmlescape}}
    ' + + '{{access:start1|htmlescape}}-{{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}}', + '{{access:start2|htmlescape}}-{{access:end2|htmlescape}}
    ' + + '{{#if access:target}}Target: {{access:target|htmlescape}}
    {{/if}}' + + 'Score: {{access:score|htmlescape}}', }; /* @@ -115,22 +112,24 @@ const significance_layer = { * @type data_layer */ const recomb_rate_layer = { - namespace: { 'recomb': 'recomb' }, id: 'recombrate', + namespace: { 'recomb': 'recomb' }, + data_operations: [ + { type: 'fetch', from: ['recomb'] }, + ], 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', + field: 'recomb:position', }, y_axis: { axis: 2, - field: '{{namespace[recomb]}}recomb_rate', + field: 'recomb:recomb_rate', floor: 0, ceiling: 100, }, @@ -143,28 +142,52 @@ const recomb_rate_layer = { */ const association_pvalues_layer = { namespace: { 'assoc': 'assoc', 'ld': 'ld' }, + data_operations: [ + { + type: 'fetch', + from: ['assoc', 'ld(assoc)'], + }, + { + type: 'left_match', + name: 'assoc_plus_ld', + requires: ['assoc', 'ld'], + params: ['assoc:position', 'ld:position2'], // FIXME: old LZ used position, because it was less sensitive to format. We'd like to match assoc:variant = ld:variant2, but not every assoc source provides variant data in the way we need. This would need to be fixed via special formatting adjustment later. + }, + ], 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', + id_field: 'assoc:variant', coalesce: { active: true, }, - point_shape: { - scale_function: 'if', - field: '{{namespace[ld]}}isrefvar', - parameters: { - field_value: 1, - then: 'diamond', - else: 'circle', + point_shape: [ + { + scale_function: 'if', + field: 'lz_is_ld_refvar', + parameters: { + field_value: true, + then: 'diamond', + }, }, - }, + { + // Not every dataset will provide these params + scale_function: 'effect_direction', + parameters: { + '+': 'triangle', + '-': 'triangledown', + // The scale function receives the entire datum object, so it needs to be told where to find individual fields + beta_field: 'assoc:beta', + stderr_beta_field: 'assoc:se', + }, + }, + 'circle', + ], point_size: { scale_function: 'if', - field: '{{namespace[ld]}}isrefvar', + field: 'lz_is_ld_refvar', parameters: { - field_value: 1, + field_value: true, then: 80, else: 40, }, @@ -172,15 +195,15 @@ const association_pvalues_layer = { color: [ { scale_function: 'if', - field: '{{namespace[ld]}}isrefvar', + field: 'lz_is_ld_refvar', parameters: { - field_value: 1, + field_value: true, then: '#9632b8', }, }, { scale_function: 'numerical_bin', - field: '{{namespace[ld]}}state', + field: 'ld:correlation', parameters: { breaks: [0, 0.2, 0.4, 0.6, 0.8], // Derived from Google "Turbo" colormap, breakpoints [0.05, 0.25, 0.45, 0.65, 0.85] @@ -190,22 +213,24 @@ const association_pvalues_layer = { '#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: 'LD (r²)', label_size: 14 }, // We're omitting the refvar symbol for now, but can show it with // shape: 'diamond', color: '#9632b8' + { + shape: 'ribbon', + orientation: 'vertical', + width: 10, + height: 15, + color_stops: ['rgb(70, 54, 153)', 'rgb(38, 188, 225)', 'rgb(110, 254, 104)', 'rgb(248, 195, 42)', 'rgb(219, 61, 17)'], + tick_labels: [0, 0.2, 0.4, 0.6, 0.8, 1.0], + }, ], label: null, z_index: 2, x_axis: { - field: '{{namespace[assoc]}}position', + field: 'assoc:position', }, y_axis: { axis: 1, - field: '{{namespace[assoc]}}log_pvalue', + field: 'assoc:log_pvalue', floor: 0, upper_buffer: 0.10, min_extent: [0, 10], @@ -230,15 +255,18 @@ const association_pvalues_layer = { * @type data_layer */ const coaccessibility_layer = { - 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', + namespace: { 'access': 'access' }, + data_operations: [ + { type: 'fetch', from: ['access'] }, + ], + match: { send: 'access:target', receive: 'access:target' }, + // Note: in the datasets this was tested with, these fields together defined a unique loop. Other datasets might work differently and need a different ID. + id_field: '{{access:start1}}_{{access:end1}}_{{access:start2}}_{{access:end2}}_{{access:score}}_{{access:target}}', filters: [ - { field: '{{namespace[access]}}score', operator: '!=', value: null }, + { field: 'access:score', operator: '!=', value: null }, ], color: [ { @@ -265,12 +293,12 @@ const coaccessibility_layer = { }, ], x_axis: { - field1: '{{namespace[access]}}start1', - field2: '{{namespace[access]}}start2', + field1: 'access:start1', + field2: 'access:start2', }, y_axis: { axis: 1, - field: '{{namespace[access]}}score', + field: 'access:score', upper_buffer: 0.1, min_extent: [0, 1], }, @@ -297,41 +325,63 @@ const association_pvalues_catalog_layer = function () { // Slightly modify an existing layout let base = deepCopy(association_pvalues_layer); base = merge({ id: 'associationpvaluescatalog', fill_opacity: 0.7 }, base); - base.tooltip.html += '{{#if {{namespace[catalog]}}rsid}}
    See hits in GWAS catalog{{/if}}'; + + base.data_operations.push({ + type: 'assoc_to_gwas_catalog', + name: 'assoc_catalog', + requires: ['assoc_plus_ld', 'catalog'], + params: ['assoc:position', 'catalog:pos', 'catalog:log_pvalue'], + }); + + base.tooltip.html += '{{#if catalog:rsid}}
    See hits in GWAS catalog{{/if}}'; base.namespace.catalog = 'catalog'; - base.fields.push('{{namespace[catalog]}}rsid', '{{namespace[catalog]}}trait', '{{namespace[catalog]}}log_pvalue'); return base; }(); + /** * A scatter plot of PheWAS pvalues, with preset field names matching the UM Portaldev API * @name phewas_pvalues * @type data_layer */ const phewas_pvalues_layer = { - namespace: { 'phewas': 'phewas' }, id: 'phewaspvalues', type: 'category_scatter', tag: 'phewas', - point_shape: 'circle', + namespace: { 'phewas': 'phewas' }, + data_operations: [ + { type: 'fetch', from: ['phewas'] }, + ], + point_shape: [ + { + scale_function: 'effect_direction', + parameters: { + '+': 'triangle', + '-': 'triangledown', + // The scale function receives the entire datum object, so it needs to be told where to find individual fields + beta_field: 'phewas:beta', + stderr_beta_field: 'phewas:se', + }, + }, + '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'], + id_field: '{{phewas:trait_group}}_{{phewas:trait_label}}', x_axis: { - field: '{{namespace[phewas]}}x', // Synthetic/derived field added by `category_scatter` layer - category_field: '{{namespace[phewas]}}trait_group', + field: 'lz_auto_x', // Automatically added by the category_scatter layer + category_field: 'phewas:trait_group', lower_buffer: 0.025, upper_buffer: 0.025, }, y_axis: { axis: 1, - field: '{{namespace[phewas]}}log_pvalue', + field: 'phewas:log_pvalue', floor: 0, upper_buffer: 0.15, }, color: [{ - field: '{{namespace[phewas]}}trait_group', + field: 'phewas:trait_group', scale_function: 'categorical_bin', parameters: { categories: [], @@ -344,11 +394,11 @@ const phewas_pvalues_layer = { closable: true, 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(''), + html: `Trait: {{phewas:trait_label|htmlescape}}
    +Trait Category: {{phewas:trait_group|htmlescape}}
    +P-value: {{phewas:log_pvalue|logtoscinotation|htmlescape}} +{{#if phewas:beta|is_numeric}}
    β: {{phewas:beta|scinotation|htmlescape}}
    {{/if}} +{{#if phewas:se|is_numeric}}SE (β): {{phewas:se|scinotation|htmlescape}}{{/if}}`, }, behaviors: { onmouseover: [ @@ -362,7 +412,7 @@ const phewas_pvalues_layer = { ], }, label: { - text: '{{{{namespace[phewas]}}trait_label}}', + text: '{{phewas:trait_label}}', spacing: 6, lines: { style: { @@ -373,7 +423,7 @@ const phewas_pvalues_layer = { }, filters: [ { - field: '{{namespace[phewas]}}log_pvalue', + field: 'phewas:log_pvalue', operator: '>=', value: 20, }, @@ -392,10 +442,20 @@ const phewas_pvalues_layer = { */ const genes_layer = { namespace: { 'gene': 'gene', 'constraint': 'constraint' }, + data_operations: [ + { + type: 'fetch', + from: ['gene', 'constraint(gene)'], + }, + { + name: 'gene_constraint', + type: 'genes_to_gnomad_constraint', + requires: ['gene', 'constraint'], + }, + ], id: 'genes', type: 'genes', tag: 'genes', - fields: ['{{namespace[gene]}}all', '{{namespace[constraint]}}all'], id_field: 'gene_id', behaviors: { onmouseover: [ @@ -446,23 +506,29 @@ const genes_layer_filtered = merge({ const annotation_catalog_layer = { // Identify GWAS hits that are present in the GWAS catalog namespace: { 'assoc': 'assoc', 'catalog': 'catalog' }, + data_operations: [ + { + type: 'fetch', from: ['assoc', 'catalog'], + }, + { + type: 'assoc_to_gwas_catalog', + name: 'assoc_plus_ld', + requires: ['assoc', 'catalog'], + params: ['assoc:position', 'catalog:pos', 'catalog:log_pvalue'], + }, + ], id: 'annotation_catalog', type: 'annotation_track', tag: 'gwascatalog', - id_field: '{{namespace[assoc]}}variant', + id_field: 'assoc:variant', x_axis: { - field: '{{namespace[assoc]}}position', + field: '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: [ // Specify which points to show on the track. Any selection must satisfy ALL filters - { field: '{{namespace[catalog]}}rsid', operator: '!=', value: null }, - { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP }, + { field: 'catalog:rsid', operator: '!=', value: null }, + { field: 'catalog:log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP }, ], behaviors: { onmouseover: [ @@ -656,7 +722,7 @@ const region_nav_plot_toolbar = function () { button_html: '<<', position: 'right', group_position: 'start', - } + }, ); return base; }(); @@ -676,8 +742,8 @@ const association_panel = { id: 'association', tag: 'association', min_height: 200, - height: 225, - margin: { top: 35, right: 50, bottom: 40, left: 50 }, + height: 300, + margin: { top: 35, right: 55, bottom: 40, left: 70 }, inner_border: 'rgb(210, 210, 210)', toolbar: (function () { const base = deepCopy(standard_panel_toolbar); @@ -690,22 +756,22 @@ const association_panel = { axes: { x: { label: 'Chromosome {{chr}} (Mb)', - label_offset: 32, + label_offset: 38, tick_format: 'region', extent: 'state', }, y1: { label: '-log10 p-value', - label_offset: 28, + label_offset: 50, }, y2: { label: 'Recombination Rate (cM/Mb)', - label_offset: 40, + label_offset: 46, }, }, legend: { orientation: 'vertical', - origin: { x: 55, y: 40 }, + origin: { x: 75, y: 40 }, hidden: true, }, interaction: { @@ -732,19 +798,19 @@ const coaccessibility_panel = { tag: 'coaccessibility', min_height: 150, height: 180, - margin: { top: 35, right: 50, bottom: 40, left: 50 }, + margin: { top: 35, right: 55, bottom: 40, left: 70 }, inner_border: 'rgb(210, 210, 210)', toolbar: deepCopy(standard_panel_toolbar), axes: { x: { label: 'Chromosome {{chr}} (Mb)', - label_offset: 32, + label_offset: 38, tick_format: 'region', extent: 'state', }, y1: { label: 'Score', - label_offset: 28, + label_offset: 40, render: false, // We are mainly concerned with the relative magnitudes: hide y axis to avoid clutter. }, }, @@ -768,7 +834,6 @@ const association_catalog_panel = function () { let base = deepCopy(association_panel); base = merge({ id: 'associationcatalog', - namespace: { 'assoc': 'assoc', 'ld': 'ld', 'catalog': 'catalog' }, // Required to resolve display options }, base); base.toolbar.widgets.push({ @@ -788,7 +853,7 @@ const association_catalog_panel = function () { display_name: 'Label catalog traits', // Human readable representation of field name display: { // Specify layout directives that control display of the plot for this option label: { - text: '{{{{namespace[catalog]}}trait}}', + text: '{{catalog:trait}}', spacing: 6, lines: { style: { @@ -800,12 +865,12 @@ const association_catalog_panel = function () { filters: [ // Only label points if they are significant for some trait in the catalog, AND in high LD // with the top hit of interest - { field: '{{namespace[catalog]}}trait', operator: '!=', value: null }, - { field: '{{namespace[catalog]}}log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP }, - { field: '{{namespace[ld]}}state', operator: '>', value: 0.4 }, + { field: 'catalog:trait', operator: '!=', value: null }, + { field: 'catalog:log_pvalue', operator: '>', value: LZ_SIG_THRESHOLD_LOGP }, + { field: 'ld:correlation', operator: '>', value: 0.4 }, ], style: { - 'font-size': '10px', + 'font-size': '12px', 'font-weight': 'bold', 'fill': '#333333', }, @@ -831,7 +896,7 @@ const genes_panel = { tag: 'genes', min_height: 150, height: 225, - margin: { top: 20, right: 50, bottom: 20, left: 50 }, + margin: { top: 20, right: 55, bottom: 20, left: 70 }, axes: {}, interaction: { drag_background_to_pan: true, @@ -846,7 +911,7 @@ const genes_panel = { position: 'right', button_html: 'Resize', }, - deepCopy(gene_selector_menu) + deepCopy(gene_selector_menu), ); return base; })(), @@ -864,7 +929,7 @@ const phewas_panel = { tag: 'phewas', min_height: 300, height: 300, - margin: { top: 20, right: 50, bottom: 120, left: 50 }, + margin: { top: 20, right: 55, bottom: 120, left: 70 }, inner_border: 'rgb(210, 210, 210)', axes: { x: { @@ -880,7 +945,7 @@ const phewas_panel = { }, y1: { label: '-log10 p-value', - label_offset: 28, + label_offset: 50, }, }, data_layers: [ @@ -899,7 +964,7 @@ const annotation_catalog_panel = { tag: 'gwascatalog', min_height: 50, height: 50, - margin: { top: 25, right: 50, bottom: 10, left: 50 }, + margin: { top: 25, right: 55, bottom: 10, left: 70 }, inner_border: 'rgb(210, 210, 210)', toolbar: deepCopy(standard_panel_toolbar), axes: { @@ -973,7 +1038,7 @@ const standard_phewas_plot = { axes: { x: { label: 'Chromosome {{chr}} (Mb)', - label_offset: 32, + label_offset: 38, tick_format: 'region', extent: 'state', }, @@ -1002,7 +1067,7 @@ const coaccessibility_plot = { // This is a companion to the "match" directive in the coaccessibility panel const base = Object.assign( { height: 270 }, - deepCopy(genes_panel) + deepCopy(genes_panel), ); const layer = base.data_layers[0]; layer.match = { send: 'gene_name', receive: 'gene_name' }; diff --git a/esm/registry/data_ops.js b/esm/registry/data_ops.js new file mode 100644 index 00000000..a4faf0b8 --- /dev/null +++ b/esm/registry/data_ops.js @@ -0,0 +1,173 @@ +/** + * "Data operation" functions, with call signature ({plot_state, data_layer}, [recordsetA, recordsetB...], ...params) => combined_results + * + * After data is retrieved from adapters, Data Operations will be run on the resulting data. The most common operation + * is a "join", such as combining association + LD together into a single set of records for plotting. Several join + * functions (that operate by analogy to SQL) are provided built-in. + * + * Other use cases (even if no examples are in the built in code, see unit tests for what is possible): + * 1. Grouping or filtering records; data operations can consider dynamic properties stored in plot.state. + * (in the future, adapters may cache more aggressively; if you want to provide your own code for filtering returned data, + * this is the recommended path to do so) + * 2. Since the context argument also contains a reference to the data layer instance (and thus the parent panel and plot), + * a data operation can modify the layout when new data is received, without having to create a custom data layer class. Eg, + * for datasets where the categories are not known before first render, this could generate automatic x-axis ticks + * (PheWAS), automatic panel legends or color schemes (BED tracks), etc. + * + * Usually, a data operation receives two recordsets (the left and right members of the join, like "assoc" and "ld"). + * In practice, any number of recordsets can be passed to one join function. There are performance penalties to making too many network + * requests when rendering a web page, so in practice, joining too many distinct data entities in this fashion is + * uncommon. (if possible, try to provide your data with fewer adapters/network requests!) + * + * In a few cases, the rules of how to combine datasets are very specific to those two types of data. Some, + * particularly for advanced features, may carry assumptions about field names/ formatting. + * (example: choosing the best EBI GWAS catalog entry for a variant may look for a field called `log_pvalue` instead of `pvalue`, + * or it may match two datasets based on a specific way of identifying the variant) + * + * @module LocusZoom_DataFunctions + */ +import {joins} from '../data/undercomplicate'; + +import {RegistryBase} from './base'; + +/** + * A plugin registry that allows plots to use both pre-defined and user-provided "data join" functions. + * @alias module:LocusZoom~DataFunctions + * @type {module:registry/base~RegistryBase} + */ +const registry = new RegistryBase(); + +function _wrap_join(handle) { + // Validate number of arguments and convert call signature from (context, deps, ...params) to (left, right, ...params). + + // Many of our join functions are implemented with a different number of arguments than what a datafunction + // actually receives. (eg, a join function is generic and doesn't care about "context" information like plot.state) + // This wrapper is simple shared code to handle required validation and conversion stuff. + return (context, deps, ...params) => { + if (deps.length !== 2) { + throw new Error('Join functions must receive exactly two recordsets'); + } + return handle(...deps, ...params); + }; +} + +// Highly specialized join: connect assoc data to GWAS catalog data. This isn't a simple left join, because it tries to +// pick the most significant claim in the catalog for a variant, rather than joining every possible match. +// This is specifically intended for sources that obey the ASSOC and CATALOG fields contracts. +function assoc_to_gwas_catalog(assoc_data, catalog_data, assoc_key, catalog_key, catalog_logp_name) { + if (!assoc_data.length) { + return assoc_data; + } + + // Prepare the genes catalog: group the data by variant, create simplified dataset with top hit for each + const catalog_by_variant = joins.groupBy(catalog_data, catalog_key); + + const catalog_flat = []; // Store only the top significant claim for each catalog variant entry + for (let claims of catalog_by_variant.values()) { + // Find max item within this set of claims, push that to catalog_ + let best = 0; + let best_variant; + for (let item of claims) { + const val = item[catalog_logp_name]; + if ( val >= best) { + best_variant = item; + best = val; + } + } + best_variant.n_catalog_matches = claims.length; + catalog_flat.push(best_variant); + } + return joins.left_match(assoc_data, catalog_flat, assoc_key, catalog_key); +} + +// Highly specialized join: connect gnomAD constraint data to genes data. These are two very nonstandard payloads and need a special function to connect them. +function genes_to_gnomad_constraint(genes_data, constraint_data) { + genes_data.forEach(function(gene) { + // Find payload keys that match gene names in this response + const alias = `_${gene.gene_name.replace(/[^A-Za-z0-9_]/g, '_')}`; // aliases are modified gene names + const constraint = constraint_data[alias] && constraint_data[alias]['gnomad_constraint']; // gnomad API has two ways of specifying missing data for a requested gene + if (constraint) { + // Add all fields from constraint data- do not override fields present in the gene source + Object.keys(constraint).forEach(function (key) { + let val = constraint[key]; + if (typeof gene[key] === 'undefined') { + if (typeof val == 'number' && val.toString().includes('.')) { + val = parseFloat(val.toFixed(2)); + } + gene[key] = val; // These two sources are both designed to bypass namespacing + } + }); + } + }); + return genes_data; +} + + +/** + * Perform a left outer join, based on records where the field values at `left_key` and `right_key` are identical + * + * By analogy with SQL, the result will include all values in the left recordset, annotated (where applicable) with all keys from matching records in the right recordset + * + * @function + * @name left_match + * @param {Object} plot_state + * @param {Array[]} recordsets + * @param {String} left_key + * @params {String} right_key + */ +registry.add('left_match', _wrap_join(joins.left_match)); + +/** + * Perform an inner join, based on records where the field values at `left_key` and `right_key` are identical + * + * By analogy with SQL, the result will include all fields from both recordsets, but only for records where both the left and right keys are defined, and equal. If a record is not in one or both recordsets, it will be excluded from the result. + * + * @function + * @name inner_match + * @param {Object} plot_state + * @param {Array[]} recordsets + * @param {String} left_key + * @params {String} right_key + */ +registry.add('inner_match', _wrap_join(joins.inner_match)); + +/** + * Perform a full outer join, based on records where the field values at `left_key` and `right_key` are identical + * + * By analogy with SQL, the result will include all records from both the left and right recordsets. If there are matching records, then the relevant items will include fields from both records combined into one. + * + * @function + * @name full_outer_match + * @param {Object} plot_state + * @param {Array[]} recordsets + * @param {String} left_key + * @params {String} right_key + */ +registry.add('full_outer_match', _wrap_join(joins.full_outer_match)); + +/** + * A single purpose join function that combines GWAS data with best claim from the EBI GWAS catalog. Essentially this is a left join modified to make further decisions about which records to use. + * + * @function + * @name assoc_to_gwas_catalog + * @param {Object} plot_state + * @param {Array[]} recordsets An array with two items: assoc records, then catalog records + * @param {String} assoc_key The name of the key field in association data, eg variant ID + * @param {String} catalog_key The name of the key field in gwas catalog data, eg variant ID + * @param {String} catalog_log_p_name The name of the "log_pvalue" field in gwas catalog data, used to choose the most significant claim for a given variant + */ +registry.add('assoc_to_gwas_catalog', _wrap_join(assoc_to_gwas_catalog)); + +/** + * A single purpose join function that combines gene data (UM Portaldev API format) with gene constraint data (gnomAD api format). + * + * This acts as a left join that has to perform custom operations to parse two very unusual recordset formats. + * + * @function + * @name genes_to_gnomad_constraint + * @param {Object} plot_state + * @param {Array[]} recordsets An array with two items: UM Portaldev API gene records, then gnomAD gene constraint data + */ +registry.add('genes_to_gnomad_constraint', _wrap_join(genes_to_gnomad_constraint)); + +export default registry; diff --git a/esm/registry/index.js b/esm/registry/index.js index 7db80e43..d0a20b22 100644 --- a/esm/registry/index.js +++ b/esm/registry/index.js @@ -4,6 +4,7 @@ import ADAPTERS from './adapters'; import DATA_LAYERS from './data_layers'; import LAYOUTS from './layouts'; +import DATA_OPS from './data_ops'; import MATCHERS from './matchers'; import SCALABLE from './scalable'; import TRANSFORMS from './transforms'; @@ -13,5 +14,5 @@ export { // Base classes and reusable components ADAPTERS, DATA_LAYERS, LAYOUTS, WIDGETS, // User defined functions for injecting custom behavior into layout directives - MATCHERS, SCALABLE, TRANSFORMS, + DATA_OPS, MATCHERS, SCALABLE, TRANSFORMS, }; diff --git a/esm/registry/layouts.js b/esm/registry/layouts.js index fc4a42bb..6064b18d 100644 --- a/esm/registry/layouts.js +++ b/esm/registry/layouts.js @@ -1,5 +1,5 @@ import {RegistryBase} from './base'; -import {applyNamespaces, deepCopy, mutate_attrs, merge, query_attrs, renameField} from '../helpers/layouts'; +import {applyNamespaces, deepCopy, mutate_attrs, merge, query_attrs, renameField, findFields} from '../helpers/layouts'; import * as layouts from '../layouts'; /** @@ -19,26 +19,23 @@ class LayoutRegistry extends RegistryBase { throw new Error('Must specify both the type and name for the layout desired. See .list() for available options'); } // This is a registry of registries. Fetching an item may apply additional custom behaviors, such as - // applying overrides or using namespaces to convert an abstract layout into a concrete one. + // applying overrides or applying namespaces. let base = super.get(type).get(name); - base = merge(overrides, base); - if (base.unnamespaced) { - delete base.unnamespaced; - return deepCopy(base); - } - let default_namespace = ''; - if (typeof base.namespace == 'string') { - default_namespace = base.namespace; - } else if (typeof base.namespace == 'object' && Object.keys(base.namespace).length) { - if (typeof base.namespace.default != 'undefined') { - default_namespace = base.namespace.default; - } else { - default_namespace = base.namespace[Object.keys(base.namespace)[0]].toString(); - } + + // Most keys are merged directly. Namespaces are handled a little differently, as they act like global overrides. + // (eg ask for plot layout, and modify multiple nested data layers where a particular namespace is referenced) + const custom_namespaces = overrides.namespace; + if (!base.namespace) { + // Iff namespaces are a top level key, we'll allow them to be merged directly with the base layout + // NOTE: The "merge namespace" behavior means that data layers can add new data easily, but this method + // can't be used to remove namespaces when extending something. (you'll need to layout.namespaces = {} separately). + delete overrides.namespace; } - default_namespace += default_namespace.length ? ':' : ''; - const result = applyNamespaces(base, base.namespace, default_namespace); + let result = merge(overrides, base); + if (custom_namespaces) { + result = applyNamespaces(result, custom_namespaces); + } return deepCopy(result); } @@ -63,6 +60,13 @@ class LayoutRegistry extends RegistryBase { } // Ensure that each use of a layout can be modified, by returning a copy is independent const copy = deepCopy(item); + + // Special behavior for datalayers: all registry data layers will attempt to identify the fields requested + // from external sources. This is purely a hint, because not every layout is generated through the registry. + if (type === 'data_layer' && copy.namespace) { + copy._auto_fields = [...findFields(copy, Object.keys(copy.namespace))].sort(); + } + return super.get(type).add(name, copy, override); } diff --git a/esm/registry/transforms.js b/esm/registry/transforms.js index d88b33f5..91635601 100644 --- a/esm/registry/transforms.js +++ b/esm/registry/transforms.js @@ -23,7 +23,7 @@ class TransformationFunctionsRegistry extends RegistryBase { return (value) => { return funcs.reduce( (acc, func) => func(acc), - value + value, ); }; } diff --git a/esm/version.js b/esm/version.js index e105cc40..3a0c7fcc 100644 --- a/esm/version.js +++ b/esm/version.js @@ -1 +1 @@ -export default '0.13.4'; +export default '0.14.0'; diff --git a/examples/coaccessibility.html b/examples/coaccessibility.html index 896eb823..14d01abf 100644 --- a/examples/coaccessibility.html +++ b/examples/coaccessibility.html @@ -13,10 +13,6 @@ - - - @@ -75,18 +71,11 @@
    < return home
    - + - - + + - + LocusZoom.js ~ Aggregation Tests @@ -63,7 +63,7 @@

    LocusZoom.js

    Aggregation Tests Demonstration

    -
    < return home
    +
    < return home

    @@ -196,7 +196,7 @@

    References

    - + - - + + - + - - - + + LocusZoom.js ~ Credible Sets @@ -43,7 +42,7 @@

    LocusZoom.js

    Credible Sets Demonstration

    -
    < return home
    +
    < return home

    @@ -89,23 +88,23 @@

    Top Hits

    data_sources = new LocusZoom.DataSources() .add("assoc", ["AssociationLZ", { url: apiBase + "statistic/single/", - params: { source: 45, id_field: "variant" } + source: 45, }]) - .add("credset", ["CredibleSetLZ", { params: { fields: { log_pvalue: 'assoc:log_pvalue' }, threshold: 0.95, significance_threshold: 7.301 } }]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', build: 'GRCh37', population: 'ALL' } }]) - .add("gene", ["GeneLZ", {url: apiBase + "annotation/genes/", params: { build: 'GRCh37' }}]) - .add("recomb", ["RecombLZ", {url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' }}]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("credset", ["CredibleSetLZ", { threshold: 0.95, significance_threshold: 7.301 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', build: 'GRCh37', population: 'ALL' }]) + .add("gene", ["GeneLZ", {url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("recomb", ["RecombLZ", {url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); /* Define and render the plot */ // Fetch custom layout defined for usage with credible sets - var stateUrlMapping = {chr: "chrom", start: "start", end: "end"}; + var stateUrlMapping = {chr: "chrom", start: "start", end: "end", ldrefvar: 'ld_variant' }; // Fetch initial position from the URL, or use some defaults var initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping); if (!Object.keys(initialState).length) { - initialState = {chr: 16, start: 74947245, end: 75547245}; + initialState = {chr: '16', start: 74947245, end: 75547245}; } layout = LocusZoom.Layouts.get("plot", "association_credible_set", {state: initialState}); diff --git a/examples/credible_sets.png b/examples/ext/credible_sets.png similarity index 100% rename from examples/credible_sets.png rename to examples/ext/credible_sets.png diff --git a/examples/interval_annotations.html b/examples/ext/interval_annotations.html similarity index 82% rename from examples/interval_annotations.html rename to examples/ext/interval_annotations.html index 4bf3fbb4..3673e141 100644 --- a/examples/interval_annotations.html +++ b/examples/ext/interval_annotations.html @@ -7,12 +7,12 @@ - - - + + + - + LocusZoom.js ~ Interval Annotations Example @@ -35,7 +35,7 @@

    LocusZoom.js

    Interval Annotations Example

    -
    < return home
    +
    < return home

    @@ -66,12 +66,12 @@

    Top Hits

    // Define Data Sources var apiBase = "https://portaldev.sph.umich.edu/api/v1/"; var data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", params: { source: 45, id_field: "variant" }}]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', build: 'GRCh37', population: 'ALL' } }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' } }]) - .add("intervals", ["IntervalLZ", { url: apiBase + "annotation/intervals/results/", params: {source: 19} }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", source: 45 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', build: 'GRCh37', population: 'ALL' }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) + .add("intervals", ["IntervalLZ", { url: apiBase + "annotation/intervals/results/", source: 19 }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); // Get the standard assocation plot layout from LocusZoom's built-in layouts layout = LocusZoom.Layouts.get("plot", "interval_association"); @@ -94,10 +94,6 @@

    Top Hits

    } }); - // Remove the itemRgb field from the default layout, because our demo api does not have this information - // (the base layout was defined for the T2D Portal API, which does provide this field) - LocusZoom.Layouts.mutate_attrs(layout, '$..data_layers[?(@.tag === "intervals")].fields', (old_fields) => old_fields.pop() && old_fields); - // This demo is focused on one track (not many), so show the legend. (the intervals track has additional // expand/collapse behavior, so this is controlled in two places instead of one) LocusZoom.Layouts.mutate_attrs(layout, '$..panels[?(@.tag === "intervals")].legend.hidden', false); diff --git a/examples/interval_annotations.png b/examples/ext/interval_annotations.png similarity index 100% rename from examples/interval_annotations.png rename to examples/ext/interval_annotations.png diff --git a/examples/interval_enrichment.html b/examples/ext/interval_enrichment.html similarity index 78% rename from examples/interval_enrichment.html rename to examples/ext/interval_enrichment.html index b5379c94..fa6a40cf 100644 --- a/examples/interval_enrichment.html +++ b/examples/ext/interval_enrichment.html @@ -7,12 +7,12 @@ - - - + + + - + LocusZoom.js ~ Interval Enrichment Example @@ -35,7 +35,7 @@

    LocusZoom.js

    Interval Annotations Example

    -
    < return home
    +
    < return home

    @@ -64,13 +64,13 @@
    < return home
    // Define Data Sources var apiBase = "https://portaldev.sph.umich.edu/api/v1/"; var data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", params: { source: 45, id_field: "variant" }}]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', build: 'GRCh37', population: 'ALL' } }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' } }]) + .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", source: 45 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', build: 'GRCh37', population: 'ALL' }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) // There's no special transformation being done to intervals data- just fetch from a URL - .add("intervals", ["BaseApiAdapter", { url: 'data/intervals_enrichment_simplified.json' }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("intervals", ["BaseLZAdapter", { url: '../data/intervals_enrichment_simplified.json' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); // Get the standard assocation plot layout from LocusZoom's built-in layouts const layout = LocusZoom.Layouts.get("plot", "intervals_association_enrichment"); diff --git a/examples/phewas_forest.html b/examples/ext/phewas_forest.html similarity index 80% rename from examples/phewas_forest.html rename to examples/ext/phewas_forest.html index 6062180f..c8d4e79d 100644 --- a/examples/phewas_forest.html +++ b/examples/ext/phewas_forest.html @@ -7,11 +7,11 @@ - + - + - + LocusZoom.js ~ PheWAS (Forest) Example @@ -34,7 +34,7 @@

    LocusZoom.js

    PheWAS (Forest) Example

    -
    < return home
    +
    < return home

    @@ -55,7 +55,7 @@
    < return home
    // TODO: Write a real data source to fetch and parse data from an API in the future. For now this fetches a // JSON file with a sample payload. var data_sources = new LocusZoom.DataSources() - .add("phewas", ["PheWASLZ", { url: "data/phewas_forest.json", params: { build: ["GRCh37"] } } ]); + .add("phewas", ["PheWASLZ", { url: "../data/phewas_forest.json", build: ["GRCh37"] } ]); // Define a reusable layout, and then retrieve it so that the namespaces get filled in LocusZoom.Layouts.add("plot", "phewas_forest", { @@ -78,7 +78,7 @@
    < return home
    axes: { x: { label: "Beta", - label_offset: 33 + label_offset: 34 }, y2: { ticks: { // Dynamically generated ticks, but specify custom options/styles to be used in every tick @@ -102,7 +102,7 @@
    < return home
    point_shape: "square", point_size: { scale_function: "interpolate", - field: "{{namespace[phewas]}}log_pvalue", + field: 'phewas:log_pvalue', parameters: { breaks: [0, 10], values: [60, 160], @@ -111,7 +111,7 @@
    < return home
    }, color: { scale_function: "interpolate", - field: "{{namespace[phewas]}}log_pvalue", + field: 'phewas:log_pvalue', parameters: { breaks: [0, 10], values: ["#fee8c8","#b30000"], @@ -127,21 +127,20 @@
    < return home
    { shape: "square", class: "lz-data_layer-forest", color: "#d7301f", size: 140, label: "8 - 10" }, { shape: "square", class: "lz-data_layer-forest", color: "#b30000", size: 160, label: "10+" } ], - id_field: "{{namespace[phewas]}}phenotype", - fields: ["{{namespace[phewas]}}phenotype", "{{namespace[phewas]}}log_pvalue", "{{namespace[phewas]}}log_pvalue|logtoscinotation", "{{namespace[phewas]}}beta", "{{namespace[phewas]}}ci_start", "{{namespace[phewas]}}ci_end"], + id_field: 'phewas:phenotype', x_axis: { - field: "{{namespace[phewas]}}beta", + field: 'phewas:beta', lower_buffer: 0.1, upper_buffer: 0.1 }, y_axis: { axis: 2, - category_field: "{{namespace[phewas]}}phenotype", // Labels - field: "{{namespace[phewas]}}y_offset", // Positions (dynamically added) + category_field: 'phewas:phenotype', // Labels + field: 'lz_auto_y_offset', // Positions (dynamically added by category_forest layer) }, confidence_intervals: { - start_field: "{{namespace[phewas]}}ci_start", - end_field: "{{namespace[phewas]}}ci_end" + start_field: 'phewas:ci_start', + end_field: 'phewas:ci_end' }, behaviors: { onmouseover: [ @@ -162,10 +161,10 @@
    < return home
    closable: true, show: { or: ["highlighted", "selected"] }, hide: { and: ["unhighlighted", "unselected"] }, - html: "{{{{namespace[phewas]}}phenotype|htmlescape}}
    " - + "P Value: {{{{namespace[phewas]}}log_pvalue|logtoscinotation|htmlescape}}
    " - + "Odds Ratio: {{{{namespace[phewas]}}beta|htmlescape}}
    " - + "95% Conf. Interval: [ {{{{namespace[phewas]}}ci_start|htmlescape}} {{{{namespace[phewas]}}ci_end|htmlescape}} ]" + html: "{{phewas:phenotype|htmlescape}}
    " + + "P Value: {{phewas:log_pvalue|logtoscinotation|htmlescape}}
    " + + "Odds Ratio: {{phewas:beta|htmlescape}}
    " + + "95% Conf. Interval: [ {{phewas:ci_start|htmlescape}} {{phewas:ci_end|htmlescape}} ]" } }, { diff --git a/examples/phewas_forest.png b/examples/ext/phewas_forest.png similarity index 100% rename from examples/phewas_forest.png rename to examples/ext/phewas_forest.png diff --git a/examples/ext/tabix_tracks.html b/examples/ext/tabix_tracks.html new file mode 100644 index 00000000..377e0c5f --- /dev/null +++ b/examples/ext/tabix_tracks.html @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + LocusZoom.js ~ Tabix Tracks + + + + + + +
    + +

    LocusZoom.js

    + +

    Tabix tracks

    +
    < return home
    + +
    + +

    + LocusZoom.js is able to fetch data directly from tabix files. This is very helpful if you want to render a plot from + your own data, without transforming the files into an intermediate format (like creating JSON files or loading + the data into an API first). This is particularly important for very large datasets, because it allows interactive + region-based queries, without having to transfer the entire dataset to the user's web browser first. + Only the index file is loaded, plus the data needed for a particular region of interest. +

    +

    + LocusZoom provides an extension to help parse tabix data files for several common data formats. Additional + parsers and index types may be supported in the future. Working directly with tabix files is a way to get + started with LocusZoom fast as it does not require building or maintaining a server backend. It is helpful for + sharing small numbers of datasets or in groups that don't want to maintain their own infrastructure. + Typically, larger data sharing portals will not use this approach; as the number of datasets grow, they will + want to run their own web server to support features like searching, complex queries, and harmonizing many + datasets into a single standard format. Tools like PheWeb are + a popular way to handle this sort of use case. +

    +

    + A key feature of LocusZoom is that each track is independent. This means it is very straightforward to define + layouts in which some tracks come from a tabix file (like a BED track), while others are fetched from a remote + web server that handles standard well-known datasets (like genes or 1000G LD). +

    +

    + In this demo, tabix loaders (and built-in file format parsers) are used for association, LD, and BED track data. + Genes and recombination rate are fetched from the UM PortalDev API. View the source code of this page for details. +

    + +
    + +

    Data formatting guidelines

    +

    + Below are some tips on formatting your data files. If you are using a static file storage provider like Amazon + S3 or Google Cloud Storage, note that you may need to configure some additional request headers + before Tabix will work properly. +

    + +

    GWAS Summary statistics

    +

    + There is no single standard for GWAS summary statistics. As such, the LocusZoom.js parser exposes many sets of + options for how to read the data. The general instructions from my.locuszoom.org + are a useful starting point, since the same basic parsing logic is shared across multiple tools. +

    + +

    BED files

    +

    + BED files are a standard format with 3-12 columns of data. + The default LocusZoom panel layout for a BED track will use chromosome, position, line name, and (optionally) color + to draw the plot. Score will be shown as a tooltip field (if present); it may have a different meaning and scale + depending on the contents of your BED file. As with any LocusZoom track, custom layouts can be created to render data in different ways, or to use more or + fewer columns based on the data of interest. +

    + +

    + The following command is helpful for preparing BED files for use in the browser:
    + $ sort -k1,1 -k2,2n input.bed | bgzip > input-sorted.bed.gz && tabix -p bed input-sorted.bed.gz
    + Some BED files will have one or more header rows; in this case, modify the tabix command with: --skip-lines N (where N is the number of headers). +

    + + +

    + Linkage Disequilibrium is an important tool for interpreting LocusZoom.js plots. In order to support viewing any + region, most LocusZoom.js usages take advantage of the Michigan LD server to calculate region-based LD relative + to a particular reference variant, based on the well-known 1000G reference panel. +

    +

    + We recognize that the 1000G reference panel (and its sub-populations) is not suited to all cases, especially for + studies with ancestry-specific results or large numbers of rare variants not represented in a public panel. + For many groups, setting up a private LD Server instance is not an option. + As a fallback, we support parsing a file format derived from PLINK 1.9 `--ld-snp` calculations. Instructions + for preparing these files are provided below. Due to the potential for very large output files, we only + support pre-calculated LD relative to one (or a few) LD reference variants; this means that this feature + requires some advance knowledge of interesting regions in order to be useful. If the user views any + region that is not near a pre-provided reference variant, they will see grey dots indicating the absence of LD information. + We have intentionally restricted the demo so that this limitation is clear. +

    + +
    +
    Preparing genotype files: harmonizing ID formats
    +
    + LocusZoom typically calculates LD relative to a variant by EPACTS-format specifier (chrom:pos_ref/alt). + However, genotype VCF files have no single standard for how variants are identified, which can make it hard to match the requested variant to the actual data. + Some files are not even internally consistent, which makes it hard to write easy copy-and-paste commands that would work widely + across files. Your file can be transformed to match the tutorial assumptions via common tool and the command below:
    + + bcftools annotate -Oz --set-id '%CHROM\:%POS\_%REF\/%ALT' original_vcf.gz > vcfname_epacts_id_format.gz
    + + In some rare cases (such as 1000G phase 3), data preparation errors may result in duplicate entries for the same variant. This can break PLINK. A command such as the one below can be used to find these duplicates:
    + zcat < vcfname_epacts_id_format.gz | cut -f3 | sort | uniq -d
    + They can then be removed using the following command (check the output carefully before using, because reasons for duplicate lines vary widely): +

    + bcftools norm -Oz --rm-dup all vcfname_epacts_id_format.gz > vcfname_epacts_id_format_rmdups.gz +
    + +
    Calculating LD relative to reference variants
    +
    + The command below will calculate LD relative to (several) variants in a 500 kb region centered around each reference variant.
    + plink-1.9 --r2 --vcf vcfname_epacts_id_format.gz --ld-window 499999 --ld-window-kb 500 --ld-window-r2 0.0 --ld-snp-list mysnplist.txt
    + + This command assumes the presence of a file named mysnplist.txt, which contains a series of rows like the example below:
    +
    16:53842908_G/A
    +16:53797908_C/G
    +16:53809247_G/A
    +
    + +
    Preparing the LD output file for use with LocusZoom.js
    +
    + As of this writing, this tutorial assumes a "list of SNPs" feature that requires PLINK 1.9.x (and is not yet available in newer versions). + Unfortunately, PLINK's default output format is not compatible with tabix, for historical reasons. + Transform to a format readable by LocusZoom via the following sequence of commands.
    + cat plink.ld | tail -n+2 | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g' | tr -s ' ' '\t' | sort -k4,4 -k5,5n | bgzip > plink.ld.tab.gz && tabix -s4 -b5 -e5 plink.ld.tab.gz +
    + +
    I don't use PLINK; how should my file be formatted?
    +
    + A custom LD file should be tab-delimited. It should specify a reference variant ("SNP_A") and LD for all others relative to that variant ("SNP_B"). The first two rows will look like the following example, taken from actual PLINK output: +
    CHR_A	BP_A	SNP_A	CHR_B	BP_B	SNP_B	R2
    +22	37470224	22:37470224_T/C	22	37370297	22:37370297_T/C	0.000178517
    + + Note: pre-calculated LD files can easily become very large. We recommend only outputting LD relative to a few target reference variants at a time. +
    +
    + +
    + +
    + +
    +
    + + + + diff --git a/examples/ext/tabix_tracks.png b/examples/ext/tabix_tracks.png new file mode 100644 index 00000000..c11b22bd Binary files /dev/null and b/examples/ext/tabix_tracks.png differ diff --git a/examples/gwas_catalog.html b/examples/gwas_catalog.html index b4fa8f2f..84df8199 100644 --- a/examples/gwas_catalog.html +++ b/examples/gwas_catalog.html @@ -85,22 +85,22 @@

    Top Hits

    */ var apiBase = "//portaldev.sph.umich.edu/api/v1/"; var data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", { url: apiBase + "statistic/single/", params: { source: 45, id_field: "variant" } }]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', population: 'ALL' } }]) + .add("assoc", ["AssociationLZ", { url: apiBase + "statistic/single/", source: 45 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', population: 'ALL' }]) .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/" }]) .add("catalog", ["GwasCatalogLZ", { url: apiBase + 'annotation/gwascatalog/results/' }]) .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/" }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); /* Define and render the plot */ // Fetch custom layout defined for usage with credible sets - var stateUrlMapping = {chr: "chrom", start: "start", end: "end"}; + var stateUrlMapping = {chr: "chrom", start: "start", end: "end", ldrefvar: 'ld_variant' }; // Fetch initial position from the URL, or use some defaults var initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping); if (!Object.keys(initialState).length) { - initialState = { chr: 9, start: 21751670, end: 22351670 }; + initialState = { chr: '9', start: 21751670, end: 22351670 }; } // This example demonstrates using the `state.genome_build` param, which tells LZ annotation sources to // automatically select an appropriate dataset based on a globally specified genome build. diff --git a/examples/js/aggregation-tests-example-page.js b/examples/js/aggregation-tests-example-page.js index a40771f2..426e47f5 100644 --- a/examples/js/aggregation-tests-example-page.js +++ b/examples/js/aggregation-tests-example-page.js @@ -32,6 +32,33 @@ const Observable = function () { // Allow UI elements to monitor changes in a va return handle_value; }; +// Format data in a particular way to look good in the tables on this page +const agg_results_table_format = (state, [agg_data, gene_data]) => { + // Aggregation calcs return very complex data. Parse it here, once, into reusable helper objects. + const parsed = raremetal.helpers.parsePortalJSON(agg_data); + const groups = parsed[0]; + const variants = parsed[1]; + + ///////// + // Post-process this data with any annotations required by data tables on this page + + // The aggregation results use the unique ENSEMBL ID for a gene. The gene source tells us how to connect + // that to a human-friendly gene name (as displayed in the LZ plot) + const _genes_lookup = {}; + gene_data.forEach(function (gene) { + const gene_id = gene.gene_id.split('.')[0]; // Ignore ensembl version on gene ids + _genes_lookup[gene_id] = gene.gene_name; + }); + groups.data.forEach(function (one_result) { + const this_group = groups.getOne(one_result.mask, one_result.group); + // Add synthetic fields that are not part of the raw calculation results + one_result.group_display_name = _genes_lookup[one_result.group] || one_result.group; + one_result.variant_count = this_group.variants.length; + }); + return [groups, variants]; +}; +LocusZoom.DataFunctions.add('agg_results_table_format', agg_results_table_format); + // Make a custom layout object function customizePlotLayout(layout) { // Customize an existing plot layout with the data for aggregation tests @@ -40,12 +67,17 @@ function customizePlotLayout(layout) { // 2. Genes layer must pull from the aggregation source + the aggregation_genes connector if we want to color // the gene track by aggregation test results const assocLayout = layout.panels[0].data_layers[2]; - assocLayout.fields.unshift('aggregation: all'); + assocLayout.namespace['aggregation'] = 'aggregation'; + assocLayout.data_operations[0].from = ['aggregation', 'assoc(aggregation)', 'ld(assoc)']; const genesLayout = layout.panels[1].data_layers[0]; genesLayout.namespace['aggregation'] = 'aggregation'; - genesLayout.namespace['aggregation_genes'] = 'aggregation_genes'; - genesLayout.fields.push('aggregation:all', 'aggregation_genes:all'); + genesLayout.namespace['aggregation'] = 'aggregation'; + genesLayout.data_operations.push({ + type: 'gene_plus_aggregation', + requires: ['gene_constraint', 'aggregation'], + }); + const colorConfig = [ { scale_function: 'if', @@ -192,26 +224,20 @@ function createDisplayWidgets(label_store, context) { .add('aggregation', ['AggregationTestSourceLZ', { url: 'https://portaldev.sph.umich.edu/raremetal/v1/aggregation/covariance' }]) .add('assoc', ['AssocFromAggregationLZ', { // Use a special source that restructures already-fetched data from: 'aggregation', - params: { id_field: 'variant' }, + id_field: 'variant', }]) .add('ld', ['LDServer', { url: 'https://portaldev.sph.umich.edu/ld/', - params: { source: '1000G', build: 'GRCh37', population: 'ALL' }, - }]) - .add('gene', ['GeneLZ', { url: apiBase + 'annotation/genes/', params: { build: 'GRCh37' } }]) - .add('aggregation_genes', ['GeneAggregationConnectorLZ', { - sources: { - aggregation_ns: 'aggregation', - gene_ns: 'gene', - }, + source: '1000G', build: 'GRCh37', population: 'ALL', }]) - .add('recomb', ['RecombLZ', { url: apiBase + 'annotation/recomb/results/', params: { build: 'GRCh37' } }]) + .add('gene', ['GeneLZ', { url: apiBase + 'annotation/genes/', build: 'GRCh37' }]) + .add('recomb', ['RecombLZ', { url: apiBase + 'annotation/recomb/results/', build: 'GRCh37' }]) .add('constraint', ['GeneConstraintLZ', { url: 'https://gnomad.broadinstitute.org/api/', - params: { build: 'GRCh37' }, + build: 'GRCh37', }]); - const stateUrlMapping = { chr: 'chrom', start: 'start', end: 'end' }; + const stateUrlMapping = { chr: 'chrom', start: 'start', end: 'end', ldrefvar: 'ld_variant' }; let initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping); if (!Object.keys(initialState).length) { initialState = { chr: '19', start: 45312079, end: 45512079 }; @@ -326,45 +352,24 @@ function setupWidgetListeners(plot, aggregationTable, variantsTable, resultStora aggregationTable.tableClearFilter(gene_column_name, selected_gene); } }.bind(this)); - plot.subscribeToData( - ['aggregation:all', 'gene:all'], - function (data) { - // chain.discrete provides distinct data from each source - const gene_source_data = data.gene; - const agg_source_data = data.aggregation; - - const results = agg_source_data.results; - - // Aggregation calcs return very complex data. Parse it here, once, into reusable helper objects. - const parsed = raremetal.helpers.parsePortalJSON(agg_source_data); - const groups = parsed[0]; - const variants = parsed[1]; - - ///////// - // Post-process this data with any annotations required by data tables on this page - - // The aggregation results use the unique ENSEMBL ID for a gene. The gene source tells us how to connect - // that to a human-friendly gene name (as displayed in the LZ plot) - const _genes_lookup = {}; - gene_source_data.forEach(function (gene) { - const gene_id = gene.gene_id.split('.')[0]; // Ignore ensembl version on gene ids - _genes_lookup[gene_id] = gene.gene_name; - }); - groups.data.forEach(function (one_result) { - const this_group = groups.getOne(one_result.mask, one_result.group); - // Add synthetic fields that are not part of the raw calculation results - one_result.group_display_name = _genes_lookup[one_result.group] || one_result.group; - one_result.variant_count = this_group.variants.length; - }); - + { + namespace: {'aggregation': 'aggregation', 'gene': 'gene' }, + data_operations: [{ + type: 'agg_results_table_format', + requires: ['aggregation', 'gene'], + }], + }, + (result) => { + // Data ops are designed to return one consolidated stream, so the data op above returns... a tuple + // This is old code and we're not investing heavily in bringing it up to modern spec + const [groups, variants] = result; // When new data has been received (and post-processed), pass it on to any UI elements that use that data resultStorage({ groups: groups, variants: variants, }); - }, - { discrete: true } + } ); // When results are updated, make sure we are not "drilling down" into a calculation that no longer exists diff --git a/examples/locuszoom_standard_association_example.png b/examples/locuszoom_standard_association_example.png new file mode 100644 index 00000000..7b4b29fb Binary files /dev/null and b/examples/locuszoom_standard_association_example.png differ diff --git a/examples/misc/covariates_model.html b/examples/misc/covariates_model.html index 0138d2d6..9c8984a5 100644 --- a/examples/misc/covariates_model.html +++ b/examples/misc/covariates_model.html @@ -67,11 +67,11 @@

    Top Hits

    // Define Data Sources var apiBase = "https://portaldev.sph.umich.edu/api/v1/"; var data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", params: { source: 45, id_field: "variant" }}]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', build: 'GRCh37', population: 'ALL' } }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' } }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", source: 45 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', build: 'GRCh37', population: 'ALL' }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); // Get the standard assocation plot layout from LocusZoom's built-in layouts var mods = { diff --git a/examples/multiple_phenotypes_layered.html b/examples/multiple_phenotypes_layered.html index 4b8193cd..9debe7d7 100644 --- a/examples/multiple_phenotypes_layered.html +++ b/examples/multiple_phenotypes_layered.html @@ -69,9 +69,9 @@

    Top Hits

    // Define base data sources var apiBase = "https://portaldev.sph.umich.edu/api/v1/"; var data_sources = new LocusZoom.DataSources() - .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' } }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); // Build the base layout var association_panel_mods = { @@ -104,9 +104,8 @@

    Top Hits

    { namespace: "cholesterol", title: "Total cholesterol meta-analysis", color: "rgb(53, 126, 189)", study_id: 30 } ]; phenos.forEach(function(pheno){ - data_sources.add(pheno.namespace, ["AssociationLZ", {url: apiBase + "statistic/single/", params: { source: pheno.study_id, id_field: "variant" }}]); + data_sources.add(pheno.namespace, ["AssociationLZ", {url: apiBase + "statistic/single/", source: pheno.study_id }]); var association_data_layer_mods = { - namespace: { "assoc": pheno.namespace }, id: "associationpvalues_" + pheno.namespace, name: pheno.title, point_shape: "circle", @@ -115,18 +114,23 @@

    Top Hits

    legend: [ { shape: "circle", color: pheno.color, size: 40, label: pheno.title, class: "lz-data_layer-scatter" }, ], - fields: [pheno.namespace+":variant", pheno.namespace+":position", pheno.namespace+":log_pvalue", pheno.namespace+":log_pvalue|logtoscinotation", pheno.namespace+":ref_allele"], tooltip: { closable: true, show: { or: ["highlighted", "selected"] }, hide: { and: ["unhighlighted", "unselected"] }, html: "" + pheno.title + "
    " - + "{{" + pheno.namespace + ":variant|htmlescape}}
    " - + "P Value: {{" + pheno.namespace + ":log_pvalue|logtoscinotation|htmlescape}}
    " - + "Ref. Allele: {{" + pheno.namespace + ":ref_allele|htmlescape}}
    " + + "{{assoc:variant|htmlescape}}
    " + + "P Value: {{assoc:log_pvalue|logtoscinotation|htmlescape}}
    " + + "Ref. Allele: {{assoc:ref_allele|htmlescape}}
    " } }; - layout.panels[0].data_layers.push(LocusZoom.Layouts.get("data_layer", "association_pvalues", association_data_layer_mods)); + // Much like subclassing, overrides syntax isn't wel suited to removing things. Since we don't want to show + // LD in this vis, we need to replace "namespace" and "data_operations" manually (if we put namespace in the overrides above, + // it would merge the new namespaces with the old one, and LD would still be there) + const layer_layout = LocusZoom.Layouts.get("data_layer", "association_pvalues", association_data_layer_mods); + layer_layout.namespace = { "assoc": pheno.namespace }; + layer_layout.data_operations = []; + layout.panels[0].data_layers.push(layer_layout); }); // Generate the LocusZoom plot diff --git a/examples/phewas_scatter.html b/examples/phewas_scatter.html index 06e58c42..85870769 100644 --- a/examples/phewas_scatter.html +++ b/examples/phewas_scatter.html @@ -195,19 +195,19 @@

    API (for developers)

    dataSources .add("phewas", ["PheWASLZ", { url: "https://portaldev.sph.umich.edu/" + "api/v1/statistic/phewas/", - params: { build: ["GRCh37"] } + build: ["GRCh37"] }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); } else { apiBase = window.location.origin + window.location.pathname.substr(0, window.location.pathname.lastIndexOf("/") + 1) + "data/"; dataSources .add("phewas", ["PheWASLZ", { url: apiBase + "phewas_" + String(variantChrom) + "_" + String(variantPosition) + "_C-T.json", - params: { build: ["GRCh37"] } + build: ["GRCh37"] }]) - .add("gene", ["GeneLZ", { url: apiBase + "genes_10_114508349-115008349.json", params: { build: 'GRCh37' } }]) - .add("constraint", ["GeneConstraintLZ", { url: apiBase + "gene_constraints_10_114508349-115008349.json", params: { build: 'GRCh37' } }]); + .add("gene", ["GeneLZ", { url: apiBase + "genes_10_114508349-115008349.json", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: apiBase + "gene_constraints_10_114508349-115008349.json", build: 'GRCh37' }]); } // Define the layout @@ -236,17 +236,17 @@

    API (for developers)

    // Modify the tooltips for PheWAS result data layer points to contain more data. The fields in this sample // tooltip are specific to the LZ-Portal API, and are not guaranteed to be in other PheWAS datasources. - LocusZoom.Layouts.mutate_attrs(layout, '$..data_layers[?(@.tag === "phewas")].fields', (fields) => fields.concat(["phewas:pmid", "phewas:description", "phewas:study"])); LocusZoom.Layouts.mutate_attrs(layout, '$..data_layers[?(@.tag === "phewas")].tooltip.html', [ "Trait: {{phewas:trait_label|htmlescape}}
    ", "Trait Category: {{phewas:trait_group|htmlescape}}
    ", - "P-value: {{phewas:log_pvalue|logtoscinotation|htmlescape}}
    ", - + "P-value: {{phewas:log_pvalue|logtoscinotation|htmlescape}}", + "{{#if phewas:beta|is_numeric}}
    β: {{phewas:beta|scinotation|htmlescape}}{{/if}}", + "{{#if phewas:se|is_numeric}}
    SE (β): {{phewas:se|scinotation|htmlescape}}{{/if}}", "{{#if phewas:study}}", - "Study: {{phewas:study|htmlescape}}
    ", + "

    Study: {{phewas:study|htmlescape}}", "{{/if}}", "{{#if phewas:pmid}} {{#if phewas:description}}", - 'Description: {{phewas:description|htmlescape}}', + '
    Description: {{phewas:description|htmlescape}}', "{{/if}} {{/if}}" ].join("")); diff --git a/examples/template.html b/examples/template.html index d1322ae6..f7238f9b 100644 --- a/examples/template.html +++ b/examples/template.html @@ -7,9 +7,9 @@ - - + + LocusZoom.js ~ Template Example ~ Gallery @@ -37,7 +37,7 @@
    < return home

    Template Description

    -
    +

    diff --git a/index.html b/index.html index adbe0373..bf1b7bc6 100644 --- a/index.html +++ b/index.html @@ -56,7 +56,7 @@

    Top Hits

    -

    To see other forms of LocusZoom.js in action take a look at https://my.locuszoom.org or the examples on this page.

    +

    To see other forms of LocusZoom.js in action take a look at https://my.locuszoom.org or the examples on this page. If you are trying to make your own plots but don't want to create a full web server backend, the Tabix Tracks demo provides some useful pointers.


    @@ -76,7 +76,7 @@

    Get LocusZoom.js

    CSS
    - https://cdn.jsdelivr.net/npm/locuszoom@0.13.3/dist/locuszoom.css + https://cdn.jsdelivr.net/npm/locuszoom@0.14.0/dist/locuszoom.css
    All CSS classes are namespaced to avoid collisions. Use <link crossorigin="anonymous" ...> to ensure that saving images works correctly.
    @@ -96,7 +96,7 @@
    Dependencies
    Javascript
    @@ -126,15 +126,15 @@

    Example Plots

    @@ -147,15 +147,15 @@
    PheWAS (Scatter)
    @@ -179,6 +179,13 @@
    Multiple Phenotypes (Layered)
    Multiple Phenotypes (Layered)
    + +

    @@ -202,27 +209,27 @@
    Multiple Phenotypes (Layered)
    if (online) { apiBase = "https://portaldev.sph.umich.edu/api/v1/"; data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", {url: apiBase + "statistic/single/", params: { source: 45, id_field: "variant" }}]) - .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", params: { source: '1000G', build: 'GRCh37', population: 'ALL' } }]) - .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", params: { build: 'GRCh37' } }]) - .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", params: { build: 'GRCh37' } }]) - .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", params: { build: 'GRCh37' } }]); + .add("assoc", ["AssociationLZ", { url: apiBase + "statistic/single/", source: 45 }]) + .add("ld", ["LDServer", { url: "https://portaldev.sph.umich.edu/ld/", source: '1000G', build: 'GRCh37', population: 'ALL' }]) + .add("gene", ["GeneLZ", { url: apiBase + "annotation/genes/", build: 'GRCh37' }]) + .add("recomb", ["RecombLZ", { url: apiBase + "annotation/recomb/results/", build: 'GRCh37' }]) + .add("constraint", ["GeneConstraintLZ", { url: "https://gnomad.broadinstitute.org/api/", build: 'GRCh37' }]); } else { apiBase = window.location.origin + window.location.pathname.substr(0, window.location.pathname.lastIndexOf("/") + 1) + "examples/data/"; data_sources = new LocusZoom.DataSources() - .add("assoc", ["AssociationLZ", {url: apiBase + "assoc_10_114550452-115067678.json?", params: { source: 45, id_field: "variant" }}]) - .add("ld", ["LDServer", { url: apiBase + "ld_10_114550452-115067678.json?" , params: { build: 'GRCh37' }}]) + .add("assoc", ["AssociationLZ", { url: apiBase + "assoc_10_114550452-115067678.json?", source: 45 }]) + .add("ld", ["LDServer", { url: apiBase + "ld_10_114550452-115067678.json?", build: 'GRCh37' }]) .add("gene", ["GeneLZ", { url: apiBase + "genes_10_114550452-115067678.json?", params: { build: 'GRCh37' } }]) .add("recomb", ["RecombLZ", { url: apiBase + "recomb_10_114550452-115067678.json?", params: { build: 'GRCh37' } }]) .add("constraint", ["GeneConstraintLZ", { url: apiBase + "constraint_10_114550452-115067678.json?", params: { build: 'GRCh37' } }]); } // Get the standard association plot layout from LocusZoom's built-in layouts - var stateUrlMapping = {chr: "chrom", start: "start", end: "end"}; + var stateUrlMapping = {chr: "chrom", start: "start", end: "end", ldrefvar: 'ld_variant' }; // Fetch initial position from the URL, or use some defaults var initialState = LzDynamicUrls.paramsFromUrl(stateUrlMapping); if (!Object.keys(initialState).length) { - initialState = {chr: 10, start: 114550452, end: 115067678}; + initialState = {chr: '10', start: 114550452, end: 115067678}; } layout = LocusZoom.Layouts.get("plot", "standard_association", {state: initialState}); diff --git a/package-lock.json b/package-lock.json index e6c5c40c..065a70aa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.13.4", + "version": "0.14.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -8,7 +8,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, "requires": { "@babel/highlight": "^7.12.13" } @@ -296,8 +295,7 @@ "@babel/helper-validator-identifier": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==", - "dev": true + "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" }, "@babel/helper-validator-option": { "version": "7.12.17", @@ -332,7 +330,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.12.13.tgz", "integrity": "sha512-kocDQvIbgMKlWxXe9fof3TQ+gkIPOUSEYhJjqUjvKMez3krV7vbzYCDq39Oj11UAVK7JqPVGQPlgE85dPNlQww==", - "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.12.11", "chalk": "^2.0.0", @@ -343,7 +340,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "requires": { "color-convert": "^1.9.0" } @@ -352,7 +348,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -363,7 +358,6 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "requires": { "has-flag": "^3.0.0" } @@ -371,9 +365,9 @@ } }, "@babel/parser": { - "version": "7.15.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.3.tgz", - "integrity": "sha512-O0L6v/HvqbdJawj0iBEfVQMc3/6WP+AeOsovsIgBFyJaG+W2w7eqvZB7puddATmWuARlm1SX7DwxJ/JJUnDpEA==", + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.12.tgz", + "integrity": "sha512-VfaV15po8RiZssrkPweyvbGVSe4x2y+aciFCgn0n0/SJMR22cwofRV1mtnJQYcSB1wUTaA/X1LnA3es66MCO5A==", "dev": true }, "@babel/plugin-proposal-async-generator-functions": { @@ -1110,19 +1104,18 @@ "dev": true }, "@eslint/eslintrc": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.3.0.tgz", - "integrity": "sha512-1JTKgrOKAHVivSvOYw+sJOunkBjUOvjqWk1DPja7ZFhIS2mX/4EgTT8M7eTK9jrKhL/FvXXEbQwIs3pg1xp3dg==", + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", + "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", "dev": true, "requires": { "ajv": "^6.12.4", "debug": "^4.1.1", "espree": "^7.3.0", - "globals": "^12.1.0", + "globals": "^13.9.0", "ignore": "^4.0.6", "import-fresh": "^3.2.1", "js-yaml": "^3.13.1", - "lodash": "^4.17.20", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" }, @@ -1140,16 +1133,52 @@ } }, "globals": { - "version": "12.4.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz", - "integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==", + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", + "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", "dev": true, "requires": { - "type-fest": "^0.8.1" + "type-fest": "^0.20.2" } + }, + "type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true } } }, + "@hapi/hoek": { + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.2.0.tgz", + "integrity": "sha512-sqKVVVOe5ivCaXDWivIJYVSaEgdQK9ul7a4Kity5Iw7u9+wBAPbX1RMSnLLmp7O4Vzj0WOWwMAJsTL00xwaNug==" + }, + "@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "requires": { + "@hapi/hoek": "^9.0.0" + } + }, + "@humanwhocodes/config-array": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", + "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "dev": true, + "requires": { + "@humanwhocodes/object-schema": "^1.2.0", + "debug": "^4.1.1", + "minimatch": "^3.0.4" + } + }, + "@humanwhocodes/object-schema": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", + "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", + "dev": true + }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -1318,6 +1347,28 @@ "integrity": "sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA==", "dev": true }, + "@types/linkify-it": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.2.tgz", + "integrity": "sha512-HZQYqbiFVWufzCwexrvh694SOim8z2d+xJl5UNamcvQFejLY/2YUtzXHYi3cHdI7PMlS8ejH2slRAOJQ32aNbA==", + "dev": true + }, + "@types/markdown-it": { + "version": "12.2.3", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-12.2.3.tgz", + "integrity": "sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==", + "dev": true, + "requires": { + "@types/linkify-it": "*", + "@types/mdurl": "*" + } + }, + "@types/mdurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-1.0.2.tgz", + "integrity": "sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA==", + "dev": true + }, "@types/minimatch": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", @@ -1610,8 +1661,7 @@ "acorn-jsx": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.1.tgz", - "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==", - "dev": true + "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==" }, "acorn-walk": { "version": "7.2.0", @@ -1633,7 +1683,6 @@ "version": "6.12.3", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.3.tgz", "integrity": "sha512-4K0cK3L1hsqk9xIb2z9vs/XU+PGJZ9PNpJRDS9YLzmNdX6jmVPfamLvTJr0aDAusnHyCHO6MjzlkAsgtqp9teA==", - "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -1653,6 +1702,11 @@ "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==" + }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", @@ -1694,7 +1748,6 @@ "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, "requires": { "sprintf-js": "~1.0.2" } @@ -1942,8 +1995,7 @@ "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "bcrypt-pbkdf": { "version": "1.0.2", @@ -1976,7 +2028,6 @@ "version": "1.1.8", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", - "dev": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -2016,12 +2067,6 @@ "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", @@ -2090,8 +2135,7 @@ "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" }, "camelcase": { "version": "5.3.1", @@ -2099,6 +2143,12 @@ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, + "caniuse-lite": { + "version": "1.0.30001312", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001312.tgz", + "integrity": "sha512-Wiz1Psk2MEK0pX3rUzWaunLTZzqS2JYZFzNKqAiJGiuxIjRPLgV6+VDPOg6lQOUxmDwhTlh198JsTTi8Hzw6aQ==", + "dev": true + }, "caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", @@ -2141,6 +2191,11 @@ "supports-color": "^2.0.0" } }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" + }, "check-error": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", @@ -2188,6 +2243,19 @@ "del": "^4.1.1" } }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.1.tgz", + "integrity": "sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==" + }, "cliui": { "version": "7.0.4", "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", @@ -2200,9 +2268,9 @@ }, "dependencies": { "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "is-fullwidth-code-point": { @@ -2248,7 +2316,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "requires": { "color-name": "1.1.3" } @@ -2256,8 +2323,7 @@ "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "colorette": { "version": "1.2.1", @@ -2288,8 +2354,7 @@ "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "convert-source-map": { "version": "1.7.0", @@ -2646,7 +2711,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, "requires": { "ms": "2.1.2" } @@ -2675,8 +2739,7 @@ "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", - "dev": true + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" }, "default-require-extensions": { "version": "3.0.0", @@ -2738,7 +2801,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, "requires": { "esutils": "^2.0.2" } @@ -2792,9 +2854,9 @@ } }, "entities": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz", - "integrity": "sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==", "dev": true }, "envinfo": { @@ -2833,8 +2895,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "escodegen": { "version": "1.14.3", @@ -2898,29 +2959,32 @@ } }, "eslint": { - "version": "7.20.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.20.0.tgz", - "integrity": "sha512-qGi0CTcOGP2OtCQBgWZlQjcTuP0XkIpYFj25XtRTQSHC+umNnp7UMshr2G8SLsRFYDdAPFeHOsiteadmMH02Yw==", + "version": "7.32.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", + "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", "dev": true, "requires": { "@babel/code-frame": "7.12.11", - "@eslint/eslintrc": "^0.3.0", + "@eslint/eslintrc": "^0.4.3", + "@humanwhocodes/config-array": "^0.5.0", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.0.1", "doctrine": "^3.0.0", "enquirer": "^2.3.5", + "escape-string-regexp": "^4.0.0", "eslint-scope": "^5.1.1", "eslint-utils": "^2.1.0", "eslint-visitor-keys": "^2.0.0", "espree": "^7.3.1", "esquery": "^1.4.0", "esutils": "^2.0.2", - "file-entry-cache": "^6.0.0", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", "functional-red-black-tree": "^1.0.1", - "glob-parent": "^5.0.0", - "globals": "^12.1.0", + "glob-parent": "^5.1.2", + "globals": "^13.6.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", @@ -2928,7 +2992,7 @@ "js-yaml": "^3.13.1", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", - "lodash": "^4.17.20", + "lodash.merge": "^4.6.2", "minimatch": "^3.0.4", "natural-compare": "^1.4.0", "optionator": "^0.9.1", @@ -2937,7 +3001,7 @@ "semver": "^7.2.1", "strip-ansi": "^6.0.0", "strip-json-comments": "^3.1.0", - "table": "^6.0.4", + "table": "^6.0.9", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" }, @@ -2952,9 +3016,9 @@ } }, "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { @@ -2967,9 +3031,9 @@ } }, "chalk": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", - "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { "ansi-styles": "^4.1.0", @@ -2991,13 +3055,19 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, + "escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true + }, "globals": { - "version": "12.4.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz", - "integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==", + "version": "13.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.0.tgz", + "integrity": "sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==", "dev": true, "requires": { - "type-fest": "^0.8.1" + "type-fest": "^0.20.2" } }, "has-flag": { @@ -3007,21 +3077,21 @@ "dev": true }, "semver": { - "version": "7.3.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.4.tgz", - "integrity": "sha512-tCfb2WLjqFAtXn4KEdxIhalnRtoKFN7nAwj0B3ZXCbQloV2tq5eDbcTmT68JJD3nRJq24/XgxtQKFIpQdtvmVw==", + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } }, "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "ansi-regex": "^5.0.1" } }, "supports-color": { @@ -3032,6 +3102,12 @@ "requires": { "has-flag": "^4.0.0" } + }, + "type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true } } }, @@ -3063,9 +3139,9 @@ } }, "eslint-visitor-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz", - "integrity": "sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", + "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", "dev": true }, "eslint-webpack-plugin": { @@ -3150,14 +3226,12 @@ "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, "esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", - "dev": true, "requires": { "estraverse": "^5.1.0" }, @@ -3165,8 +3239,7 @@ "estraverse": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==" } } }, @@ -3174,7 +3247,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, "requires": { "estraverse": "^5.2.0" }, @@ -3182,22 +3254,19 @@ "estraverse": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==" } } }, "estraverse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==" }, "esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "events": { "version": "3.2.0", @@ -3228,6 +3297,16 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true }, + "external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -3237,20 +3316,17 @@ "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "fast-json-stable-stringify": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", - "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", - "dev": true + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" }, "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fastest-levenshtein": { "version": "1.0.12", @@ -3258,6 +3334,14 @@ "integrity": "sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow==", "dev": true }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, "file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -3342,9 +3426,9 @@ } }, "flatted": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.1.1.tgz", - "integrity": "sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz", + "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==", "dev": true }, "foreground-child": { @@ -3394,8 +3478,7 @@ "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { "version": "2.1.3", @@ -3413,8 +3496,7 @@ "functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" }, "gensync": { "version": "1.0.0-beta.2", @@ -3470,7 +3552,6 @@ "version": "7.1.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", - "dev": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -3498,8 +3579,7 @@ "globals": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" }, "globby": { "version": "6.1.0", @@ -3534,6 +3614,11 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", "dev": true }, + "gwas-credible-sets": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/gwas-credible-sets/-/gwas-credible-sets-0.1.0.tgz", + "integrity": "sha512-CQnvmUV/Xg/xAfx0/M0rTUD7uhnhmwsTF7I6/kJeHGRTbx95RQfdBQW2ByNnbL6OcJOnZRpFpJf/P2keWhivhg==" + }, "har-schema": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", @@ -3571,8 +3656,7 @@ "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "has-symbols": { "version": "1.0.1", @@ -3647,14 +3731,12 @@ "ignore": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", - "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==" }, "import-fresh": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, "requires": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -3727,8 +3809,7 @@ "imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" }, "indent-string": { "version": "4.0.0", @@ -3740,7 +3821,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "requires": { "once": "^1.3.0", "wrappy": "1" @@ -3749,8 +3829,68 @@ "inherits": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "inquirer": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.5.2.tgz", + "integrity": "sha512-cntlB5ghuB0iuO65Ovoi8ogLHiWGs/5yNrtUcKjFhSSiVeAIVpD7koaSU9RM8mpXw5YDi9RdYXGQMaOURB7ycQ==", + "requires": { + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^2.0.0", + "lodash": "^4.17.12", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.4.0", + "string-width": "^2.1.0", + "strip-ansi": "^5.1.0", + "through": "^2.3.6" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } + } }, "interpret": { "version": "2.2.0", @@ -3791,8 +3931,7 @@ "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" }, "is-glob": { "version": "4.0.1", @@ -3881,8 +4020,7 @@ "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "isobject": { "version": "3.0.1", @@ -4093,26 +4231,24 @@ "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "js-yaml": { "version": "3.14.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz", "integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==", - "dev": true, "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" } }, "js2xmlparser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz", - "integrity": "sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.2.tgz", + "integrity": "sha512-6n4D8gLlLf1n5mNLQPRfViYzu9RATblzPEtm1SthMX1Pjao0r9YI9nw7ZIfRxQMERS87mcswrg+r/OYrPRX6jA==", "dev": true, "requires": { - "xmlcreate": "^2.0.3" + "xmlcreate": "^2.0.4" } }, "jsbn": { @@ -4122,25 +4258,26 @@ "dev": true }, "jsdoc": { - "version": "3.6.7", - "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.7.tgz", - "integrity": "sha512-sxKt7h0vzCd+3Y81Ey2qinupL6DpRSZJclS04ugHDNmRUXGzqicMJ6iwayhSA0S0DwwX30c5ozyUthr1QKF6uw==", + "version": "3.6.10", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.10.tgz", + "integrity": "sha512-IdQ8ppSo5LKZ9o3M+LKIIK8i00DIe5msDvG3G81Km+1dhy0XrOWD0Ji8H61ElgyEj/O9KRLokgKbAM9XX9CJAg==", "dev": true, "requires": { "@babel/parser": "^7.9.4", + "@types/markdown-it": "^12.2.3", "bluebird": "^3.7.2", "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": "^2.0.3", + "js2xmlparser": "^4.0.2", + "klaw": "^4.0.1", + "markdown-it": "^12.3.2", + "markdown-it-anchor": "^8.4.1", + "marked": "^4.0.10", "mkdirp": "^1.0.4", "requizzle": "^0.2.3", "strip-json-comments": "^3.1.0", "taffydb": "2.6.2", - "underscore": "~1.13.1" + "underscore": "~1.13.2" }, "dependencies": { "escape-string-regexp": { @@ -4203,23 +4340,15 @@ "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", "dev": true }, - "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", - "dev": true - }, "json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" }, "json-stringify-safe": { "version": "5.0.1", @@ -4237,17 +4366,34 @@ } }, "jsprim": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", "dev": true, "requires": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", - "json-schema": "0.2.3", + "json-schema": "0.4.0", "verror": "1.10.0" + }, + "dependencies": { + "json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "dev": true + } } }, + "jszlib": { + "version": "git+https://github.com/dasmoth/jszlib.git#4e562c7b88749f3e1e402737ddef5f96bf0906c6", + "from": "git+https://github.com/dasmoth/jszlib.git#4e562c7" + }, + "just-clone": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/just-clone/-/just-clone-3.2.1.tgz", + "integrity": "sha512-PFotEVrrzAnwuWTUOFquDShWrHnUnhxNrVs1VFqkNfnoH3Sn5XUlDOePYn2Vv5cN8xV2y69jf8qEoQHm7eoLnw==" + }, "just-extend": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.1.0.tgz", @@ -4261,13 +4407,10 @@ "dev": true }, "klaw": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", - "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.9" - } + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-4.0.1.tgz", + "integrity": "sha512-pgsE40/SvC7st04AHiISNewaIMUbY5V/K8b21ekiPiFoYs/EYSdsGa+FJArB1d441uq4Q8zZyIxvAzkGNlBdRw==", + "dev": true }, "klona": { "version": "2.0.4", @@ -4286,9 +4429,9 @@ } }, "linkify-it": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", - "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", + "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", "dev": true, "requires": { "uc.micro": "^1.0.1" @@ -4343,8 +4486,7 @@ "lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, "lodash.debounce": { "version": "4.0.8", @@ -4364,12 +4506,24 @@ "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=", "dev": true }, + "lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, "lodash.sortby": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", "dev": true }, + "lodash.truncate": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", + "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", + "dev": true + }, "log-symbols": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.0.0.tgz", @@ -4456,28 +4610,36 @@ } }, "markdown-it": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz", - "integrity": "sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg==", + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", + "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", "dev": true, "requires": { - "argparse": "^1.0.7", - "entities": "~2.0.0", - "linkify-it": "^2.0.0", + "argparse": "^2.0.1", + "entities": "~2.1.0", + "linkify-it": "^3.0.1", "mdurl": "^1.0.1", "uc.micro": "^1.0.5" + }, + "dependencies": { + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + } } }, "markdown-it-anchor": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz", - "integrity": "sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-8.4.1.tgz", + "integrity": "sha512-sLODeRetZ/61KkKLJElaU3NuU2z7MhXf12Ml1WJMSdwpngeofneCRF+JBbat8HiSqhniOMuTemXMrsI7hA6XyA==", "dev": true }, "marked": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/marked/-/marked-2.1.3.tgz", - "integrity": "sha512-/Q+7MGzaETqifOMWYEA7HVMaZb4XbcRfaOzcSsHZEith83KGlvaSG33u0SKu89Mj5h+T8V2hM+8O45Qc5XTgwA==", + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.0.12.tgz", + "integrity": "sha512-hgibXWrEDNBWgGiK18j/4lkS6ihTe9sxtV4Q1OQppb/0zzyPSzoFANBa5MfsG/zgsWklmNnhm0XACZOH/0HBiQ==", "dev": true }, "mdurl": { @@ -4517,7 +4679,6 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, "requires": { "brace-expansion": "^1.1.7" } @@ -4525,8 +4686,7 @@ "minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "mkdirp": { "version": "1.0.4", @@ -4700,8 +4860,12 @@ "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=" }, "nanoid": { "version": "3.1.20", @@ -4712,8 +4876,7 @@ "natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" }, "neo-async": { "version": "2.6.2", @@ -4721,6 +4884,11 @@ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" + }, "nise": { "version": "1.5.3", "resolved": "https://registry.npmjs.org/nise/-/nise-1.5.3.tgz", @@ -5076,7 +5244,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, "requires": { "wrappy": "1" } @@ -5104,6 +5271,11 @@ "word-wrap": "^1.2.3" } }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" + }, "p-limit": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.0.0.tgz", @@ -5158,7 +5330,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, "requires": { "callsites": "^3.0.0" } @@ -5178,14 +5349,12 @@ "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-is-inside": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", - "dev": true + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=" }, "path-key": { "version": "3.1.1", @@ -5292,8 +5461,7 @@ "progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", - "dev": true + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==" }, "psl": { "version": "1.8.0", @@ -5371,9 +5539,9 @@ } }, "regexpp": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", - "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", + "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", "dev": true }, "regexpu-core": { @@ -5563,8 +5731,31 @@ "resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==" + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "requires": { + "mimic-fn": "^1.0.0" + } + } + } }, "rimraf": { "version": "3.0.2", @@ -5575,11 +5766,24 @@ "glob": "^7.1.3" } }, + "run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==" + }, "rw": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz", "integrity": "sha1-P4Yt+pGrdmsUiF700BEkv9oHT7Q=" }, + "rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "requires": { + "tslib": "^1.9.0" + } + }, "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", @@ -5631,9 +5835,9 @@ }, "dependencies": { "ajv": { - "version": "6.12.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.2.tgz", - "integrity": "sha512-k+V+hzjm5q/Mr8ef/1Y9goCmlsK4I6Sm74teeyGvFk1XrOsbsKLjEdrvny42CZ+a8sXbk8KWpY/bDwS+FLL2UQ==", + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", @@ -5641,20 +5845,13 @@ "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } - }, - "fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true } } }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "serialize-javascript": { "version": "5.0.1", @@ -5698,8 +5895,7 @@ "signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", - "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", - "dev": true + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" }, "sinon": { "version": "6.3.5", @@ -5879,8 +6075,7 @@ "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" }, "sshpk": { "version": "1.16.1", @@ -5915,7 +6110,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dev": true, "requires": { "is-fullwidth-code-point": "^2.0.0", "strip-ansi": "^4.0.0" @@ -5924,14 +6118,12 @@ "ansi-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" }, "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, "requires": { "ansi-regex": "^3.0.0" } @@ -5977,22 +6169,331 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "tabix-reader": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tabix-reader/-/tabix-reader-1.0.1.tgz", + "integrity": "sha512-AtGAUP9yLamN8X6yJqWHZqDlTb2DcEyoBHlNVRrVjyLyshVUVnVi0Fwvl4Ag8n49yGH7YoRYgMemmy5L0pQ6lg==", + "requires": { + "eslint": "^5.16.0", + "jszlib": "git+https://github.com/dasmoth/jszlib.git#4e562c7" + }, + "dependencies": { + "acorn": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.2.tgz", + "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==" + }, + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==" + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "eslint": { + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.16.0.tgz", + "integrity": "sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg==", + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.9.1", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^4.0.3", + "eslint-utils": "^1.3.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^5.0.1", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^11.7.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^6.2.2", + "js-yaml": "^3.13.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.11", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^5.5.1", + "strip-ansi": "^4.0.0", + "strip-json-comments": "^2.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0" + } + }, + "eslint-scope": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", + "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", + "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "requires": { + "eslint-visitor-keys": "^1.1.0" + } + }, + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==" + }, + "espree": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-5.0.1.tgz", + "integrity": "sha512-qWAZcWh4XE/RwzLJejfcofscgMc9CamR6Tn1+XRXNzrvUSSbiAjGOI/fggztjIi7y9VLPqnICMIPiGyr8JaZ0A==", + "requires": { + "acorn": "^6.0.7", + "acorn-jsx": "^5.0.0", + "eslint-visitor-keys": "^1.0.0" + } + }, + "file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "requires": { + "flat-cache": "^2.0.1" + } + }, + "flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "requires": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + } + }, + "flatted": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", + "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==" + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "requires": { + "minimist": "^1.2.5" + } + }, + "optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + } + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=" + }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==" + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "requires": { + "glob": "^7.1.3" + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + } + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "table": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", + "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==", + "requires": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + } + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + } + } + }, "table": { - "version": "6.0.7", - "resolved": "https://registry.npmjs.org/table/-/table-6.0.7.tgz", - "integrity": "sha512-rxZevLGTUzWna/qBLObOe16kB2RTnnbhciwgPbMMlazz1yZGVEgnZK762xyVdVznhqxrfCeBMmMkgOOaPwjH7g==", + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/table/-/table-6.8.0.tgz", + "integrity": "sha512-s/fitrbVeEyHKFa7mFdkuQMWlH1Wgw/yEXMt5xACT4ZpzWFluehAxRtUUQKPuWhaLAWhFcVx6w3oC8VKaUfPGA==", "dev": true, "requires": { - "ajv": "^7.0.2", - "lodash": "^4.17.20", + "ajv": "^8.0.1", + "lodash.truncate": "^4.4.2", "slice-ansi": "^4.0.0", - "string-width": "^4.2.0" + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1" }, "dependencies": { "ajv": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-7.1.1.tgz", - "integrity": "sha512-ga/aqDYnUy/o7vbsRTFhhTsNeXiYb5JWDIcRIeZfwRNCefwjNTVYCGdGSUrEmiu3yDK3vFvNbgJxvrQW4JXrYQ==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.9.0.tgz", + "integrity": "sha512-qOKJyNj/h+OWx7s5DePL6Zu1KeM9jPZhwBqs+7DzP6bGOvqzVCSf0xueYmVuaC/oQ/VtS2zLMLHdQFbkka+XDQ==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", @@ -6002,9 +6503,9 @@ } }, "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "is-fullwidth-code-point": { @@ -6020,23 +6521,23 @@ "dev": true }, "string-width": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", - "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.0" + "strip-ansi": "^6.0.1" } }, "strip-ansi": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", - "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { - "ansi-regex": "^5.0.0" + "ansi-regex": "^5.0.1" } } } @@ -6162,8 +6663,20 @@ "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", - "dev": true + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "requires": { + "os-tmpdir": "~1.0.2" + } }, "to-fast-properties": { "version": "2.0.0", @@ -6194,8 +6707,7 @@ "tslib": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" }, "tunnel-agent": { "version": "0.6.0", @@ -6249,9 +6761,9 @@ "dev": true }, "underscore": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.1.tgz", - "integrity": "sha512-hzSoAVtJF+3ZtiFX0VgfFPHEDRm7Y/QPjGyNo4TVdnDTdft3tr8hEkD25a1jC+TjTuE7tkHGKkhwCgs9dgBB2g==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.2.tgz", + "integrity": "sha512-ekY1NhRzq0B08g4bGuX4wd2jZx5GnKz6mKSqFL4nqBlfyMGiG10gDFhDTMEfYmDL6Jy0FUIZp7wiRB+0BP7J2g==", "dev": true }, "unicode-canonical-property-names-ecmascript": { @@ -6286,7 +6798,6 @@ "version": "4.2.2", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", - "dev": true, "requires": { "punycode": "^2.1.0" }, @@ -6294,8 +6805,7 @@ "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" } } }, @@ -6306,9 +6816,9 @@ "dev": true }, "v8-compile-cache": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz", - "integrity": "sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", + "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", "dev": true }, "verror": { @@ -6583,8 +7093,7 @@ "word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true + "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==" }, "workerpool": { "version": "6.1.0", @@ -6604,9 +7113,9 @@ }, "dependencies": { "ansi-regex": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", - "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { @@ -6664,8 +7173,25 @@ "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "requires": { + "mkdirp": "^0.5.1" + }, + "dependencies": { + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "requires": { + "minimist": "^1.2.5" + } + } + } }, "write-file-atomic": { "version": "3.0.3", @@ -6698,9 +7224,9 @@ "dev": true }, "xmlcreate": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.3.tgz", - "integrity": "sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.4.tgz", + "integrity": "sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg==", "dev": true }, "y18n": { diff --git a/package.json b/package.json index 72a9c4bd..d83237ef 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "locuszoom", - "version": "0.13.4", + "version": "0.14.0", "main": "dist/locuszoom.app.min.js", "module": "esm/index.js", "sideEffects": true, @@ -39,7 +39,11 @@ "docs": "./build_docs.sh" }, "dependencies": { - "d3": "^5.16.0" + "@hapi/topo": "^5.1.0", + "d3": "^5.16.0", + "gwas-credible-sets": "^0.1.0", + "just-clone": "^3.2.1", + "tabix-reader": "^1.0.1" }, "devDependencies": { "@babel/core": "^7.13.1", @@ -49,10 +53,10 @@ "babel-plugin-module-resolver": "^4.1.0", "chai": "^4.3.0", "clean-webpack-plugin": "^3.0.0", - "eslint": "^7.20.0", + "eslint": "^7.32.0", "eslint-webpack-plugin": "^2.5.2", "friendly-errors-webpack-plugin": "^1.7.0", - "jsdoc": "^3.6.7", + "jsdoc": "^3.6.10", "jsdom": "^16.4.0", "jsdom-global": "^3.0.2", "mocha": "^8.3.0", diff --git a/test/unit/components/data_layer/test_highlight_regions.js b/test/unit/components/data_layer/test_highlight_regions.js index 9037d917..255ce77d 100644 --- a/test/unit/components/data_layer/test_highlight_regions.js +++ b/test/unit/components/data_layer/test_highlight_regions.js @@ -11,19 +11,19 @@ describe('highlight_regions data layer', function () { it('must choose to specify data from regions or fields, but not both', function () { const layout = { regions: [{start: 1, end: 12}], - fields: ['mydata:start', 'mydata:end'], + namespace: { 'mydata': 'mydata' }, }; assert.throws( () => DATA_LAYERS.create('highlight_regions', layout), /not both/, - 'Invalid layout options should trigger an error' + 'Invalid layout options should trigger an error', ); }); it('does not allow mouse interaction', function () { assert.throws( () => DATA_LAYERS.create('highlight_regions', { interaction: {}, behaviors: [] }), /mouse events/, - 'Invalid layout options should trigger an error' + 'Invalid layout options should trigger an error', ); }); }); @@ -76,7 +76,7 @@ describe('highlight_regions data layer', function () { }; d3.select('body').append('div').attr('id', 'plot'); const sources = new DataSources() - .add('intervals', ['StaticJSON', [{start: 1, end: 2}]]); + .add('intervals', ['StaticJSON', { data: [{start: 1, end: 2}] }]); this.plot = populate('#plot', sources, layout); }); afterEach(function() { @@ -90,13 +90,17 @@ describe('highlight_regions data layer', function () { }); it('can render data from regions in data source', function () { // Rejigger the original plot layout to work in "datasource mode" - const d_layout = this.plot.panels.p.data_layers.d.layout; - d_layout.start_field = 'intervals:start'; - d_layout.end_field = 'intervals:end'; - d_layout.regions = []; - d_layout.fields = ['intervals:start', 'intervals:end']; + const layer = this.plot.panels.p.data_layers.d; + const d_layout = layer.layout; + Object.assign(d_layout, { + namespace: { intervals: 'intervals'}, + start_field: 'intervals:start', + end_field: 'intervals:end', + regions: [], + }); + layer.mutateLayout(); // Manually tell the layer that data rules have changed for this specific test return this.plot.applyState().then(() => { - assert.equal(this.plot.panels.p.data_layers.d.svg.group.selectAll('rect').size(), 1, 'Layer draws one region as pulled from the datasource'); + assert.equal(layer.svg.group.selectAll('rect').size(), 1, 'Layer draws one region as pulled from the datasource'); }); }); }); diff --git a/test/unit/components/test_datalayer.js b/test/unit/components/test_datalayer.js index bb9a736f..0859d542 100644 --- a/test/unit/components/test_datalayer.js +++ b/test/unit/components/test_datalayer.js @@ -12,6 +12,76 @@ import DataSources from '../../../esm/data'; Test composition of the LocusZoom.Panel object and its base classes */ describe('LocusZoom.DataLayer', function () { + describe('getElementId generates unique IDs for elements', function () { + it('generates unique IDs when id_field is an exact field reference with a value', function () { + const layer = new BaseDataLayer({ id: 'layername', id_field: 'exact_field' }); + let actual = layer.getElementId({ exact_field: 12 }); + assert.equal(actual, 'layername-12', 'Generates ID from exact field value'); + + + assert.throws( + () => layer.getElementId({ not_much_to_go_on: 12 }), + /Unable to generate/, + 'Cannot generate ID field if no value is present for that field', + ); + }); + + it('generates unique IDs when id_field is a valid template expression', function () { + const layer = new BaseDataLayer({ id: 'layername', id_field: 'element_{{some_field}}_{{other_field}}' }); + + let actual = layer.getElementId({ some_field: 'carbon', other_field: '12' }); + assert.equal(actual, 'layername-element_carbon_12', 'Generates ID from template string'); + + layer.layout.id_field = 'partial_{{some_field}}_{{other_field}}'; + actual = layer.getElementId({ some_field: 'carbon' }); + assert.equal(actual, 'layername-partial_carbon_', 'Template values do not warn when some fields are missing (which might be awkward)'); + + layer.layout.id_field = 'neither-template-nor-field'; + assert.throws( + () => layer.getElementId({ some_field: 'carbon', other_field: '12' }), + /Unable to generate/, + 'Not using a field name in the data, and expression is not recognized as a template', + ); + + layer.layout.id_field = ''; + assert.throws( + () => layer.getElementId({ some_field: 'carbon', other_field: '12' }), + /Unable to generate/, + 'An empty template does not evaluate to a useful element ID', + ); + }); + }); + + + describe('data contract parsing and validation', function () { + beforeEach(function () { + const layer = this.layer = new BaseDataLayer({ id: 'something' }); + layer.parent_plot = { state: {} }; + layer._data_contract = new Set(['assoc:variant', 'assoc:rsid']); + }); + + afterEach(function() { + sinon.restore(); + }); + + it('warns if the data received does not match the inferred fields contract', function () { + let spy = sinon.spy(console, 'debug'); + this.layer.data = [{ 'assoc:variant': '1:23_A/B', 'assoc:position': 23 }]; + this.layer.applyDataMethods(); + assert.ok(spy.calledOnce, 'Console.debug was called with data contract errors'); + assert.ok(spy.firstCall.args[0].match(/Missing fields are: assoc:rsid/), 'Developer message identifies the missing fields'); + }); + + it('will treat the fields contract as satisfied if the field is in at least one record of the response', function () { + let spy = sinon.spy(console, 'warn'); + this.layer.data = [ + { 'assoc:variant': '1:23_A/B', 'assoc:position': 23 }, + { 'assoc:variant': '1:24_A/B', 'assoc:position': 24, 'assoc:rsid': 'rsYuppers' }, + ]; + this.layer.applyDataMethods(); + assert.ok(spy.notCalled, 'Console.warn was not called with contract errors'); + }); + }); describe('Z-index sorting', function () { beforeEach(function () { @@ -33,53 +103,56 @@ describe('LocusZoom.DataLayer', function () { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', null, layout); }); + afterEach(function () { d3.select('#plot').remove(); this.plot = null; }); + it('should have a chainable method for moving layers up that stops at the top', function () { - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); this.plot.panels.panel0.data_layers.layerB.moveForward(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); this.plot.panels.panel0.data_layers.layerB.moveForward(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 3); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 2); this.plot.panels.panel0.data_layers.layerB.moveForward().moveForward(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerD', 'layerB']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 3); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 2); }); + it('should have a chainable method for moving layers down that stops at the bottom', function () { - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerB', 'layerC', 'layerD']); this.plot.panels.panel0.data_layers.layerC.moveBack(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerA', 'layerC', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); this.plot.panels.panel0.data_layers.layerC.moveBack(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 0); assert.equal(this.plot.panels.panel0.data_layers.layerD.layout.z_index, 3); this.plot.panels.panel0.data_layers.layerC.moveBack().moveBack(); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); + assert.deepEqual(this.plot.panels.panel0._data_layer_ids_by_z_index, ['layerC', 'layerA', 'layerB', 'layerD']); assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 1); assert.equal(this.plot.panels.panel0.data_layers.layerB.layout.z_index, 2); assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 0); @@ -97,6 +170,7 @@ describe('LocusZoom.DataLayer', function () { assert.equal(datalayer.resolveScalableParameter(this.layout.scale, {}), 17); assert.equal(datalayer.resolveScalableParameter(this.layout.scale, { foo: 'bar' }), 17); }); + it('executes a scale function for the data provided', function () { const datalayer = new BaseDataLayer({ id: 'test' }); const layout = { @@ -113,6 +187,7 @@ describe('LocusZoom.DataLayer', function () { assert.equal(datalayer.resolveScalableParameter(layout.scale, { test: 'manatee' }), null); assert.equal(datalayer.resolveScalableParameter(layout.scale, {}), null); }); + it('can operate in a state-aware manner based on index in data[]', function () { SCALABLE.add('fake', (parameters, input, index) => index); const datalayer = new BaseDataLayer({ id: 'test' }); @@ -124,6 +199,7 @@ describe('LocusZoom.DataLayer', function () { // Clean up/ deregister scale function when done SCALABLE.remove('fake'); }); + it('supports operating on an entire data element in the absence of a specified field', function () { SCALABLE.add('test_effect_direction', function (parameters, input) { if (typeof input == 'undefined') { @@ -155,6 +231,7 @@ describe('LocusZoom.DataLayer', function () { // Clean up/ deregister scale function when done SCALABLE.remove('test_effect_direction'); }); + it('iterates over an array of options until exhausted or a non-null value is found', function () { const datalayer = new BaseDataLayer({ id: 'test' }); const layout = { @@ -183,6 +260,7 @@ describe('LocusZoom.DataLayer', function () { assert.equal(datalayer.resolveScalableParameter(layout.scale, { test: 'witch' }), 'munchkin'); assert.equal(datalayer.resolveScalableParameter(layout.scale, {}), 'munchkin'); }); + it('can resolve based on an annotation field, even when no point data field by that name is present', function () { const layout = { id: 'somelayer', @@ -217,6 +295,7 @@ describe('LocusZoom.DataLayer', function () { datalayer.getAxisExtent('y1'); }); }); + it('generates an accurate extent array for arbitrary data sets', function () { const layout = { id: 'test', @@ -247,6 +326,7 @@ describe('LocusZoom.DataLayer', function () { ]; assert.deepEqual(datalayer.getAxisExtent('x'), [undefined, undefined]); }); + it('applies upper and lower buffers to extents as defined in the layout', function () { let layout = { id: 'test', @@ -286,6 +366,7 @@ describe('LocusZoom.DataLayer', function () { ]; assert.deepEqual(datalayer.getAxisExtent('x'), [-95, 412]); }); + it('applies a minimum extent as defined in the layout', function () { let layout = { id: 'test', @@ -329,6 +410,7 @@ describe('LocusZoom.DataLayer', function () { assert.deepEqual(datalayer.getAxisExtent('x'), [-1.48, 10.74], 'Padding is enforced on both sides when data is close to both boundaries'); }); + it('applies hard floor and ceiling as defined in the layout', function () { let layout = { id: 'test', @@ -375,7 +457,6 @@ describe('LocusZoom.DataLayer', function () { ]; assert.deepEqual(datalayer.getAxisExtent('x'), [4, 6]); }); - }); describe('Layout Parameters', function () { @@ -391,20 +472,23 @@ describe('LocusZoom.DataLayer', function () { }; d3.select('body').append('div').attr('id', 'plot'); }); + afterEach(function () { d3.select('#plot').remove(); delete this.plot; }); + it('should allow for explicitly setting data layer z_index', function () { this.layout.panels[0].data_layers = [ { id: 'd1', type: 'line', z_index: 1 }, { id: 'd2', type: 'line', z_index: 0 }, ]; this.plot = populate('#plot', null, this.layout); - assert.deepEqual(this.plot.panels.p1.data_layer_ids_by_z_index, ['d2', 'd1']); + assert.deepEqual(this.plot.panels.p1._data_layer_ids_by_z_index, ['d2', 'd1']); assert.equal(this.plot.panels.p1.data_layers.d1.layout.z_index, 1); assert.equal(this.plot.panels.p1.data_layers.d2.layout.z_index, 0); }); + it('should allow for explicitly setting data layer z_index with a negative value', function () { this.layout.panels[0].data_layers = [ { id: 'd1', type: 'line' }, @@ -413,7 +497,7 @@ describe('LocusZoom.DataLayer', function () { { id: 'd4', type: 'line', z_index: -1 }, ]; this.plot = populate('#plot', null, this.layout); - assert.deepEqual(this.plot.panels.p1.data_layer_ids_by_z_index, ['d1', 'd2', 'd4', 'd3']); + assert.deepEqual(this.plot.panels.p1._data_layer_ids_by_z_index, ['d1', 'd2', 'd4', 'd3']); assert.equal(this.plot.panels.p1.data_layers.d1.layout.z_index, 0); assert.equal(this.plot.panels.p1.data_layers.d2.layout.z_index, 1); assert.equal(this.plot.panels.p1.data_layers.d3.layout.z_index, 3); @@ -425,15 +509,15 @@ describe('LocusZoom.DataLayer', function () { beforeEach(function () { this.plot = null; const data_sources = new DataSources() - .add('d', ['StaticJSON', [{ id: 'a' }, { id: 'b' }, { id: 'c' }]]); + .add('d', ['StaticJSON', { data: [{ id: 'a' }, { id: 'b' }, { id: 'c' }] }]); const layout = { panels: [ { id: 'p', data_layers: [ { + namespace: { d: 'd' }, id: 'd', - fields: ['d:id'], id_field: 'd:id', type: 'scatter', highlighted: { onmouseover: 'toggle' }, @@ -445,14 +529,16 @@ describe('LocusZoom.DataLayer', function () { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', data_sources, layout); }); + afterEach(function () { d3.select('#plot').remove(); delete this.plot; }); + it('should allow for highlighting and unhighlighting a single element', function () { - return this.plot.lzd.getData({}, ['d:id']) + return this.plot.applyState() .then(() => { - const state_id = this.plot.panels.p.data_layers.d.state_id; + const state_id = this.plot.panels.p.data_layers.d._state_id; const layer_state = this.plot.state[state_id]; const d = this.plot.panels.p.data_layers.d; const a = d.data[0]; @@ -482,24 +568,25 @@ describe('LocusZoom.DataLayer', function () { assert.equal(highlight_flags.size, 0); }); }); + it('should allow for highlighting and unhighlighting all elements', function () { - return this.plot.lzd.getData({}, ['d:id']) + return this.plot.applyState() .then(() => { - const state_id = this.plot.panels.p.data_layers.d.state_id; + const layer = this.plot.panels.p.data_layers.d; + const state_id = layer._state_id; const layer_state = this.plot.state[state_id]; - const d = this.plot.panels.p.data_layers.d; - const a_id = d.getElementId(d.data[0]); - const b_id = d.getElementId(d.data[1]); - const c_id = d.getElementId(d.data[2]); + const a_id = layer.getElementId(layer.data[0]); + const b_id = layer.getElementId(layer.data[1]); + const c_id = layer.getElementId(layer.data[2]); - this.plot.panels.p.data_layers.d.highlightAllElements(); + layer.highlightAllElements(); const highlight_flags = layer_state.status_flags.highlighted; assert.equal(highlight_flags.size, 3); assert.ok(highlight_flags.has(a_id)); assert.ok(highlight_flags.has(b_id)); assert.ok(highlight_flags.has(c_id)); - this.plot.panels.p.data_layers.d.unhighlightAllElements(); + layer.unhighlightAllElements(); assert.equal(layer_state.status_flags.highlighted.size, 0); }); }); @@ -509,7 +596,7 @@ describe('LocusZoom.DataLayer', function () { beforeEach(function () { this.plot = null; const data_sources = new DataSources() - .add('d', ['StaticJSON', [{ id: 'a' }, { id: 'b' }, { id: 'c' }]]); + .add('d', ['StaticJSON', { data: [{ id: 'a' }, { id: 'b' }, { id: 'c' }] }]); const layout = { panels: [ { @@ -517,7 +604,7 @@ describe('LocusZoom.DataLayer', function () { data_layers: [ { id: 'd', - fields: ['d:id'], + namespace: { d: 'd' }, id_field: 'd:id', type: 'scatter', selected: { onclick: 'toggle' }, @@ -529,61 +616,64 @@ describe('LocusZoom.DataLayer', function () { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', data_sources, layout); }); + afterEach(function () { d3.select('#plot').remove(); delete this.plot; }); + it('should allow for selecting and unselecting a single element', function () { - return this.plot.lzd.getData({}, ['d:id']) + return this.plot.applyState() .then(() => { - const state_id = this.plot.panels.p.data_layers.d.state_id; + const layer = this.plot.panels.p.data_layers.d; + const state_id = layer._state_id; const layer_state = this.plot.state[state_id]; - const d = this.plot.panels.p.data_layers.d; - const a = d.data[0]; - const a_id = d.getElementId(a); - const b = d.data[1]; - const c = d.data[2]; - const c_id = d.getElementId(c); + const a = layer.data[0]; + const a_id = layer.getElementId(a); + const b = layer.data[1]; + const c = layer.data[2]; + const c_id = layer.getElementId(c); const selected_flags = layer_state.status_flags.selected; assert.equal(selected_flags.size, 0); - this.plot.panels.p.data_layers.d.selectElement(a); + layer.selectElement(a); assert.equal(selected_flags.size, 1); assert.ok(selected_flags.has(a_id)); - this.plot.panels.p.data_layers.d.unselectElement(a); + layer.unselectElement(a); assert.equal(selected_flags.size, 0); - this.plot.panels.p.data_layers.d.selectElement(c); + layer.selectElement(c); assert.equal(selected_flags.size, 1); assert.ok(selected_flags.has(c_id)); - this.plot.panels.p.data_layers.d.unselectElement(b); + layer.unselectElement(b); assert.equal(selected_flags.size, 1); - this.plot.panels.p.data_layers.d.unselectElement(c); + layer.unselectElement(c); assert.equal(selected_flags.size, 0); }); }); + it('should allow for selecting and unselecting all elements', function () { - return this.plot.lzd.getData({}, ['d:id']) + return this.plot.applyState() .then(() => { - const state_id = this.plot.panels.p.data_layers.d.state_id; + const layer = this.plot.panels.p.data_layers.d; + const state_id = layer._state_id; const layer_state = this.plot.state[state_id]; - const d = this.plot.panels.p.data_layers.d; - const a_id = d.getElementId(d.data[0]); - const b_id = d.getElementId(d.data[1]); - const c_id = d.getElementId(d.data[2]); + const a_id = layer.getElementId(layer.data[0]); + const b_id = layer.getElementId(layer.data[1]); + const c_id = layer.getElementId(layer.data[2]); - this.plot.panels.p.data_layers.d.selectAllElements(); + layer.selectAllElements(); const selected_flags = layer_state.status_flags.selected; assert.equal(selected_flags.size, 3); assert.ok(selected_flags.has(a_id)); assert.ok(selected_flags.has(b_id)); assert.ok(selected_flags.has(c_id)); - this.plot.panels.p.data_layers.d.unselectAllElements(); + layer.unselectAllElements(); assert.equal(layer_state.status_flags.selected.size, 0); }); }); @@ -614,10 +704,12 @@ describe('LocusZoom.DataLayer', function () { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', null, this.layout); }); + afterEach(function () { d3.select('#plot').remove(); delete this.plot; }); + it('should allow for creating and destroying tool tips', function () { this.plot.panels.p.data_layers.d.data = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]; this.plot.panels.p.data_layers.d.positionTooltip = function () { @@ -626,18 +718,19 @@ describe('LocusZoom.DataLayer', function () { const a = this.plot.panels.p.data_layers.d.data[0]; const a_id = this.plot.panels.p.data_layers.d.getElementId(a); const a_id_q = `#${ (`${a_id }-tooltip`).replace(/(:|\.|\[|\]|,)/g, '\\$1')}`; - assert.equal(Object.keys(this.plot.panels.p.data_layers.d.tooltips).length, 0); + assert.equal(Object.keys(this.plot.panels.p.data_layers.d._tooltips).length, 0); this.plot.panels.p.data_layers.d.createTooltip(a); - assert.isObject(this.plot.panels.p.data_layers.d.tooltips[a_id]); - assert.equal(Object.keys(this.plot.panels.p.data_layers.d.tooltips).length, 1); + assert.isObject(this.plot.panels.p.data_layers.d._tooltips[a_id]); + assert.equal(Object.keys(this.plot.panels.p.data_layers.d._tooltips).length, 1); assert.equal(d3.select(a_id_q).empty(), false); this.plot.panels.p.data_layers.d.destroyTooltip(a_id); - assert.equal(Object.keys(this.plot.panels.p.data_layers.d.tooltips).length, 0); - assert.equal(typeof this.plot.panels.p.data_layers.d.tooltips[a_id], 'undefined'); + assert.equal(Object.keys(this.plot.panels.p.data_layers.d._tooltips).length, 0); + assert.equal(typeof this.plot.panels.p.data_layers.d._tooltips[a_id], 'undefined'); assert.equal(d3.select(a_id_q).empty(), true); }); + it('should allow for showing or hiding a tool tip based on layout directives and element status', function () { this.plot.panels.p.data_layers.d.data = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]; this.plot.panels.p.data_layers.d.positionTooltip = function () { @@ -649,36 +742,37 @@ describe('LocusZoom.DataLayer', function () { const b = d.data[1]; const b_id = d.getElementId(b); // Make sure the tooltips object is there - assert.isObject(d.tooltips); + assert.isObject(d._tooltips); // Test highlighted OR selected - assert.isUndefined(d.tooltips[a_id]); + assert.isUndefined(d._tooltips[a_id]); d.highlightElement(a); - assert.isObject(d.tooltips[a_id]); + assert.isObject(d._tooltips[a_id]); d.unhighlightElement(a); - assert.isUndefined(d.tooltips[a_id]); + assert.isUndefined(d._tooltips[a_id]); d.selectElement(a); - assert.isObject(d.tooltips[a_id]); + assert.isObject(d._tooltips[a_id]); d.unselectElement(a); - assert.isUndefined(d.tooltips[a_id]); + assert.isUndefined(d._tooltips[a_id]); // Test highlight AND selected - assert.isUndefined(d.tooltips[b_id]); + assert.isUndefined(d._tooltips[b_id]); d.highlightElement(b); d.selectElement(b); - assert.isObject(d.tooltips[b_id]); + assert.isObject(d._tooltips[b_id]); d.unhighlightElement(b); d.unselectElement(b); - assert.isUndefined(d.tooltips[b_id]); + assert.isUndefined(d._tooltips[b_id]); }); + it('should allow tooltip open/close state to be tracked separately from element selection', function () { // Regression test for zombie tooltips returning after re-render const layer = this.plot.panels.p.data_layers.d; - const status_flags = layer.layer_state.status_flags; + const status_flags = layer._layer_state.status_flags; const item_a = { id: 'a' }; const internal_id = layer.getElementId(item_a); @@ -695,11 +789,11 @@ describe('LocusZoom.DataLayer', function () { layer.setElementStatus('selected', item_a, true, true); const internal_id = layer.getElementId(item_a); - assert.ok(layer.tooltips[internal_id], 'Tooltip created on selection'); + assert.ok(layer._tooltips[internal_id], 'Tooltip created on selection'); assert.ok(status_flags['selected'].has(internal_id), 'Item was initially selected'); layer.destroyTooltip(item_a); - assert.ok(!layer.tooltips[internal_id], 'Tooltip was destroyed by user close event'); + assert.ok(!layer._tooltips[internal_id], 'Tooltip was destroyed by user close event'); assert.ok(status_flags['selected'].has(internal_id), 'Point remains selected after closing tooltip'); assert.ok(!status_flags['has_tooltip'].has(internal_id), 'Tooltip was destroyed by user close event'); @@ -715,7 +809,7 @@ describe('LocusZoom.DataLayer', function () { describe('data element behaviors', function () { beforeEach(function() { const data_sources = new DataSources() - .add('d', ['StaticJSON', [{ id: 'a', x: 1, y: 2 }, { id: 'b', x: 2, y:0 }, { id: 'c', x: 3, y:1 }]]); + .add('d', ['StaticJSON', { data: [{ id: 'a', x: 1, y: 2 }, { id: 'b', x: 2, y:0 }, { id: 'c', x: 3, y:1 }] }]); const layout = { panels: [ @@ -724,8 +818,8 @@ describe('LocusZoom.DataLayer', function () { data_layers: [ { id: 'd', + namespace: { d: 'd'}, type: 'scatter', - fields: ['d:id', 'd:x', 'd:y'], id_field: 'd:id', x_axis: { field: 'd:x' }, y_axis: { field: 'd:y'}, @@ -743,6 +837,7 @@ describe('LocusZoom.DataLayer', function () { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', data_sources, layout); }); + it('can link to an external website', function () { // NOTE: Not all variants of this behavior are tested. This only tests opening links in another window. // This is because JSDom sometimes has issues mocking window.location. @@ -759,6 +854,7 @@ describe('LocusZoom.DataLayer', function () { assert.ok(openStub.calledWith('https://dev.example/a', '_blank'), 'The URL can incorporate parameters from the specified data element'); }); }); + it('applies status-based styles when an item receives mouse events', function () { // Since sequence is important, this test exercises multiple scenarios in a specific order return this.plot.applyState().then(() => { @@ -783,6 +879,7 @@ describe('LocusZoom.DataLayer', function () { assert.notOk(second.node().classList.contains('lz-data_layer-scatter-highlighted'), 'Style is removed on mouseout'); }); }); + it('recognizes keyboard modifiers as distinct events', function () { return this.plot.applyState().then(() => { const openStub = sinon.stub(window, 'open'); @@ -797,6 +894,7 @@ describe('LocusZoom.DataLayer', function () { assert.ok(datapoint.node().classList.contains('lz-data_layer-scatter-selected'), 'Style is applied appropriately'); }); }); + afterEach(function () { sinon.restore(); }); @@ -884,7 +982,9 @@ describe('LocusZoom.DataLayer', function () { beforeEach(function () { this.plot = null; const data_sources = new DataSources() - .add('d', ['StaticJSON', [{ id: 1, a: 12 }, { id: 2, a: 11 }, { id: 3, a: 13 }, { id: 4, a: 15 }, { id: 5, a: 14 }]]); + .add('d', ['StaticJSON', { + data: [{ id: 1, a: 12 }, { id: 2, a: 11 }, { id: 3, a: 13 }, { id: 4, a: 15 }, { id: 5, a: 14 }], + }]); const layout = { panels: [ { @@ -892,7 +992,7 @@ describe('LocusZoom.DataLayer', function () { data_layers: [ { id: 'd', - fields: ['d:id', 'd:a'], + namespace: { d: 'd'}, id_field: 'd:id', type: 'scatter', filters: null, @@ -970,7 +1070,7 @@ describe('LocusZoom.DataLayer', function () { beforeEach(function () { this.plot = null; const data_sources = new DataSources() - .add('d', ['StaticJSON', [{ id: 'a' }, { id: 'b', some_field: true }, { id: 'c' }]]); + .add('d', ['StaticJSON', { data: [{ id: 'a' }, { id: 'b', some_field: true }, { id: 'c' }] }]); const layout = { panels: [ { @@ -978,7 +1078,7 @@ describe('LocusZoom.DataLayer', function () { data_layers: [ { id: 'd', - fields: ['d:id', 'd:some_field'], + namespace: { d: 'd'}, id_field: 'd:id', type: 'scatter', selected: { onclick: 'toggle' }, @@ -1002,7 +1102,7 @@ describe('LocusZoom.DataLayer', function () { data_layer.setElementAnnotation(datum, 'custom_field', 'some_value'); // Find the element annotation for this point via several different ways - assert.equal(data_layer.layer_state.extra_fields['plot_p_d-a']['custom_field'], 'some_value', 'Found in internal storage (as elementID)'); + assert.equal(data_layer._layer_state.extra_fields['plot_p_d-a']['custom_field'], 'some_value', 'Found in internal storage (as elementID)'); assert.equal(data_layer.getElementAnnotation(datum, 'custom_field'), 'some_value', 'Found via helper method (from id_field)'); assert.equal(data_layer.getElementAnnotation({'d:id': 'b'}, 'custom_field'), null, 'If no annotation found, returns null. Annotation does not return actual field values.'); assert.equal(data_layer.getElementAnnotation(datum, 'custom_field'), 'some_value', 'Found via helper method (as data object)'); @@ -1019,16 +1119,16 @@ describe('LocusZoom.DataLayer', function () { it('can use custom markings in layout directives', function () { const self = this; const data_layer = this.plot.panels.p.data_layers.d; - assert.equal(data_layer.label_groups, undefined, 'No labels on first render'); + assert.equal(data_layer._label_groups, undefined, 'No labels on first render'); data_layer.setElementAnnotation({'d:id': 'a'}, 'custom_field', true); return this.plot.applyState().then(function () { - assert.equal(data_layer.label_groups.size(), 1, 'Labels are drawn because of annotations'); + assert.equal(data_layer._label_groups.size(), 1, 'Labels are drawn because of annotations'); // After turning labels on, confirm that we can cycle them off and influence rendering data_layer.setElementAnnotation({'d:id': 'a'}, 'custom_field', false); return self.plot.applyState(); }).then(function () { - assert.equal(data_layer.label_groups.size(), 0, 'Labels are removed because of annotations'); + assert.equal(data_layer._label_groups.size(), 0, 'Labels are removed because of annotations'); }); }); @@ -1039,12 +1139,12 @@ describe('LocusZoom.DataLayer', function () { // Rerender once so the modified layout takes effect return this.plot.applyState().then(function () { - assert.equal(data_layer.label_groups.size(), 1, 'Labels are drawn on first render because field value says to'); + assert.equal(data_layer._label_groups.size(), 1, 'Labels are drawn on first render because field value says to'); // Introduce an annotation that conflicts with the data field from the API data_layer.setElementAnnotation({'d:id': 'b'}, 'd:some_field', false); return self.plot.applyState(); }).then(function () { - assert.equal(data_layer.label_groups.size(), 1, 'Real fields says to label, annotation says no. Real field wins.'); + assert.equal(data_layer._label_groups.size(), 1, 'Real fields says to label, annotation says no. Real field wins.'); }); }); }); diff --git a/test/unit/components/test_panel.js b/test/unit/components/test_panel.js index 8d48cab5..f9208974 100644 --- a/test/unit/components/test_panel.js +++ b/test/unit/components/test_panel.js @@ -2,7 +2,6 @@ import { assert } from 'chai'; import * as d3 from 'd3'; import sinon from 'sinon'; -import {LAYOUTS} from '../../../esm/registry'; import {populate} from '../../../esm/helpers/display'; import Plot from '../../../esm/components/plot'; import Panel from '../../../esm/components/panel'; @@ -13,9 +12,13 @@ describe('Panel', function() { describe('Constructor', function() { beforeEach(function() { d3.select('body').append('div').attr('id', 'plot_id'); - const layout = LAYOUTS.get('plot', 'standard_association'); - layout.state = { chr: '1', start: 1, end: 100000 }; - this.plot = populate('#plot_id', null, layout); + const layout = { + state: {}, + width: 800, + panels: [], + }; + + this.plot = populate('#plot_id', new DataSources(), layout); this.panel = this.plot.panels.association; }); @@ -25,17 +28,11 @@ describe('Panel', function() { this.panel = null; }); - it('should generate an ID if passed a layout that does not define one', function() { - this.plot.addPanel({ 'foo': 'bar' }); - const panel_idx = this.plot.layout.panels.length - 1; - assert.equal(this.plot.layout.panels[panel_idx].foo, 'bar'); - - const panel_layout = this.plot.layout.panels[panel_idx]; - assert.equal(panel_layout.foo, 'bar', 'Layout has the property provided'); - assert.ok(panel_layout.id, 'A panel ID was created'); - - const panel_instance = this.plot.panels[panel_layout.id]; - assert.equal(panel_instance.layout.foo, 'bar', 'Panel instance can access fields on layout object'); + it('should fail if panel layout does not specify an ID', function() { + assert.throws( + () => this.plot.addPanel({ 'foo': 'bar' }), + /must specify "id"/, + ); }); it('should throw an error if adding a panel with an ID that is already used', function() { @@ -49,9 +46,18 @@ describe('Panel', function() { describe('Geometry Methods', function() { beforeEach(function() { d3.select('body').append('div').attr('id', 'plot_id'); - const layout = LAYOUTS.get('plot', 'standard_association'); + + const layout = { + state: {}, + width: 800, + panels: [ + { id: 'association', height: 225, data_layers: [] }, + { id: 'genes', height: 225, data_layers: [] }, + ], + }; + layout.state = { chr: '1', start: 1, end: 100000 }; - this.plot = populate('#plot_id', null, layout); + this.plot = populate('#plot_id', new DataSources(), layout); this.association_panel = this.plot.panels.association; this.genes_panel = this.plot.panels.genes; }); @@ -97,25 +103,26 @@ describe('Panel', function() { it('should allow setting margin, which sets cliparea origin and dimensions', function() { this.association_panel.setMargin(1, 2, 3, 4); - assert.equal(this.association_panel.layout.margin.top, 1); - assert.equal(this.association_panel.layout.margin.right, 2); - assert.equal(this.association_panel.layout.margin.bottom, 3); - assert.equal(this.association_panel.layout.margin.left, 4); - assert.equal(this.association_panel.layout.cliparea.origin.x, 4); - assert.equal(this.association_panel.layout.cliparea.origin.y, 1); - assert.equal(this.association_panel.layout.cliparea.width, this.association_panel.parent.layout.width - (2 + 4)); - assert.equal(this.association_panel.layout.cliparea.height, this.association_panel.layout.height - (1 + 3)); + const layout = this.association_panel.layout; + assert.equal(layout.margin.top, 1); + assert.equal(layout.margin.right, 2); + assert.equal(layout.margin.bottom, 3); + assert.equal(layout.margin.left, 4); + assert.equal(layout.cliparea.origin.x, 4); + assert.equal(layout.cliparea.origin.y, 1); + assert.equal(layout.cliparea.width, this.association_panel.parent.layout.width - (2 + 4)); + assert.equal(layout.cliparea.height, layout.height - (1 + 3)); this.association_panel.setMargin(0, '12', -17, {foo: 'bar'}); - assert.equal(this.association_panel.layout.margin.top, 0); - assert.equal(this.association_panel.layout.margin.right, 12); - assert.equal(this.association_panel.layout.margin.bottom, 3); - assert.equal(this.association_panel.layout.margin.left, 4); - assert.equal(this.association_panel.layout.cliparea.origin.x, 4); - assert.equal(this.association_panel.layout.cliparea.origin.y, 0); + assert.equal(layout.margin.top, 0); + assert.equal(layout.margin.right, 12); + assert.equal(layout.margin.bottom, 3); + assert.equal(layout.margin.left, 4); + assert.equal(layout.cliparea.origin.x, 4); + assert.equal(layout.cliparea.origin.y, 0); - assert.equal(this.association_panel.layout.cliparea.width, this.plot.layout.width - (12 + 4)); - assert.equal(this.association_panel.layout.cliparea.height, this.association_panel.layout.height - (0 + 3)); + assert.equal(layout.cliparea.width, this.plot.layout.width - (12 + 4)); + assert.equal(layout.cliparea.height, layout.height - (0 + 3)); }); it('should prevent margins from overlapping', function() { @@ -128,33 +135,33 @@ describe('Panel', function() { }); it('should have a method for moving panels up that stops at the top', function() { - assert.deepEqual(this.plot.panel_ids_by_y_index, ['association', 'genes']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['association', 'genes']); assert.equal(this.association_panel.layout.y_index, 0); assert.equal(this.genes_panel.layout.y_index, 1); this.genes_panel.moveUp(); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['genes', 'association']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['genes', 'association']); assert.equal(this.association_panel.layout.y_index, 1); assert.equal(this.genes_panel.layout.y_index, 0); this.genes_panel.moveUp(); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['genes', 'association']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['genes', 'association']); assert.equal(this.association_panel.layout.y_index, 1); assert.equal(this.genes_panel.layout.y_index, 0); }); it('should have a method for moving panels down that stops at the bottom', function() { - assert.deepEqual(this.plot.panel_ids_by_y_index, ['association', 'genes']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['association', 'genes']); assert.equal(this.association_panel.layout.y_index, 0); assert.equal(this.genes_panel.layout.y_index, 1); this.association_panel.moveDown(); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['genes', 'association']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['genes', 'association']); assert.equal(this.association_panel.layout.y_index, 1); assert.equal(this.genes_panel.layout.y_index, 0); this.association_panel.moveDown(); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['genes', 'association']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['genes', 'association']); assert.equal(this.association_panel.layout.y_index, 1); assert.equal(this.genes_panel.layout.y_index, 0); }); @@ -178,35 +185,39 @@ describe('Panel', function() { }); it('should have a method for adding data layers', function() { - this.plot.panels.panel0.addDataLayer({ id: 'layerA', type: 'line' }); - this.plot.panels.panel0.addDataLayer({ id: 'layerB', type: 'line' }); - - assert.isObject(this.plot.panels.panel0.data_layers.layerA); - assert.equal(this.plot.panels.panel0.data_layers.layerA.id, 'layerA'); - assert.equal(this.plot.panels.panel0.data_layers.layerA.layout_idx, 0); - assert.isObject(this.plot.panels.panel0.data_layers.layerB); - assert.equal(this.plot.panels.panel0.data_layers.layerB.id, 'layerB'); - assert.equal(this.plot.panels.panel0.data_layers.layerB.layout_idx, 1); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerB']); - assert.equal(typeof this.plot.state[this.plot.panels.panel0.data_layers.layerA.state_id], 'object'); - assert.equal(typeof this.plot.state[this.plot.panels.panel0.data_layers.layerB.state_id], 'object'); + const panel0 = this.plot.panels.panel0; + panel0.addDataLayer({ id: 'layerA', type: 'line' }); + panel0.addDataLayer({ id: 'layerB', type: 'line' }); + + const layerA = panel0.data_layers.layerA; + assert.isObject(layerA); + assert.equal(layerA.id, 'layerA'); + assert.equal(layerA._layout_idx, 0); + const layerB = panel0.data_layers.layerB; + assert.isObject(layerB); + assert.equal(layerB.id, 'layerB'); + assert.equal(layerB._layout_idx, 1); + assert.deepEqual(panel0._data_layer_ids_by_z_index, ['layerA', 'layerB']); + assert.equal(typeof this.plot.state[layerA._state_id], 'object'); + assert.equal(typeof this.plot.state[layerB._state_id], 'object'); }); it('should have a method for removing data layers by id', function() { - this.plot.panels.panel0.addDataLayer({ id: 'layerA', type: 'line' }); - this.plot.panels.panel0.addDataLayer({ id: 'layerB', type: 'line' }); - this.plot.panels.panel0.addDataLayer({ id: 'layerC', type: 'line' }); - const state_id = this.plot.panels.panel0.data_layers.layerB.state_id; - assert.equal(typeof this.plot.panels.panel0.data_layers.layerB, 'object'); + const panel0 = this.plot.panels.panel0; + const layerA = panel0.addDataLayer({ id: 'layerA', type: 'line' }); + const layerB = panel0.addDataLayer({ id: 'layerB', type: 'line' }); + const layerC = panel0.addDataLayer({ id: 'layerC', type: 'line' }); + const state_id = layerB._state_id; + assert.equal(typeof layerB, 'object'); assert.equal(typeof this.plot.state[state_id], 'object'); - this.plot.panels.panel0.removeDataLayer('layerB'); - assert.equal(typeof this.plot.panels.panel0.data_layers.layerB, 'undefined'); + panel0.removeDataLayer('layerB'); + assert.equal(typeof panel0.data_layers.layerB, 'undefined'); assert.equal(typeof this.plot.state[state_id], 'undefined'); - assert.equal(this.plot.panels.panel0.data_layers.layerA.layout_idx, 0); - assert.equal(this.plot.panels.panel0.data_layers.layerC.layout_idx, 1); - assert.equal(this.plot.panels.panel0.data_layers.layerA.layout.z_index, 0); - assert.equal(this.plot.panels.panel0.data_layers.layerC.layout.z_index, 1); - assert.deepEqual(this.plot.panels.panel0.data_layer_ids_by_z_index, ['layerA', 'layerC']); + assert.equal(layerA._layout_idx, 0); + assert.equal(layerC._layout_idx, 1); + assert.equal(layerA.layout.z_index, 0); + assert.equal(layerC.layout.z_index, 1); + assert.deepEqual(panel0._data_layer_ids_by_z_index, ['layerA', 'layerC']); }); }); @@ -310,7 +321,9 @@ describe('Panel', function() { beforeEach(function() { this.plot = null; this.datasources = new DataSources() - .add('static', ['StaticJSON', [{ id: 'a', x: 1, y: 2 }, { id: 'b', x: 3, y: 4 }, { id: 'c', x: 5, y: 6 }] ]); + .add('static', ['StaticJSON', { + data: [{ id: 'a', x: 1, y: 2 }, { id: 'b', x: 3, y: 4 }, { id: 'c', x: 5, y: 6 }], + }]); this.layout = { width: 100, panels: [ @@ -326,7 +339,7 @@ describe('Panel', function() { { id: 'd', type: 'scatter', - fields: ['static:id', 'static:x', 'static:y'], + namespace: { static: 'static' }, id_field: 'static:id', z_index: 0, x_axis: { @@ -388,7 +401,7 @@ describe('Panel', function() { it('should establish background drag interaction handlers when the layout directive is present', function() { this.layout.panels[0].interaction.drag_background_to_pan = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.isDefined(this.plot.panels.p.svg.container.select('.lz-panel-background').node().__on .find((item) => item.type === 'mousedown' && item.name === 'plot.p.interaction.drag.background' )); assert.isDefined(this.plot.svg.node().__on @@ -401,7 +414,7 @@ describe('Panel', function() { it('should establish x tick drag interaction handlers when the layout directives are present', function() { this.layout.panels[0].interaction.drag_x_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.isDefined(this.plot.svg.node().__on .find((item) => item.type === 'mouseup' && item.name === 'plot')); assert.isDefined(this.plot.svg.node().__on @@ -414,7 +427,7 @@ describe('Panel', function() { it('should establish y1 tick drag interaction handlers when the layout directives are present', function() { this.layout.panels[0].interaction.drag_y1_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.isDefined(typeof this.plot.svg.node().__on .find((item) => item.type === 'mouseup' && item.name === 'plot')); assert.isDefined(this.plot.svg.node().__on @@ -427,85 +440,90 @@ describe('Panel', function() { it('should establish a zoom interaction handler on the panel when the layout directive is present', function() { this.layout.panels[0].interaction.scroll_to_zoom = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.isDefined(this.plot.panels.p.svg.container.node().__on .find((item) => item.type === 'wheel' && item.name === 'zoom')); }); }); it.skip('should pan along the x axis when dragging the background', function() { - this.layout.panels[0].interaction.drag_background_to_pan = true; + this.layout.panels[0]._interaction.drag_background_to_pan = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { // Simulate click (mousedown) at [ 50, 50 ] sinon.stub(d3, 'mouse').callsFake(() => [50, 50]); this.plot.loading_data = false; // TODO: Why isn't this already the case? this.plot.panels.p.svg.container.select('.lz-panel-background') .dispatch('mousedown'); - assert.isObject(this.plot.interaction); - assert.equal(this.plot.interaction.panel_id, this.plot.panels.p.id); - assert.isObject(this.plot.interaction.dragging); - assert.equal(this.plot.interaction.dragging.method, 'background'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 50); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + const interaction = this.plot._interaction; + assert.isObject(interaction); + assert.equal(interaction.panel_id, this.plot.panels.p.id); + + const dragging = interaction.dragging; + assert.isObject(dragging); + assert.equal(dragging.method, 'background'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 50); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 0); // Simulate drag (mousemove) to [ 25, 50 ] (x -25) sinon.stub(d3, 'mouse').callsFake(() => [25, 50]); this.plot.svg.node()['__onmousemove.plot'](); - assert.equal(this.plot.interaction.panel_id, this.plot.panels.p.id); - assert.equal(this.plot.interaction.dragging.method, 'background'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 50); - assert.equal(this.plot.interaction.dragging.dragged_x, -25); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + assert.equal(interaction.panel_id, this.plot.panels.p.id); + assert.equal(dragging.method, 'background'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 50); + assert.equal(dragging.dragged_x, -25); + assert.equal(dragging.dragged_y, 0); assert.deepEqual(this.plot.panels.p.x_extent, [2, 6]); // Simulate mouseup at new location this.plot.svg.node()['__onmouseup.plot'](); - assert.deepEqual(this.plot.interaction, {}); + assert.deepEqual(interaction, {}); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.floor, 2); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.ceiling, 6); }); }); it.skip('should scale along the x axis when dragging an x tick', function() { - this.layout.panels[0].interaction.drag_x_ticks_to_scale = true; + this.layout.panels[0]._interaction.drag_x_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { // Simulate click (mousedown) at [ 50, 0 ] (x tick probably doesn't exist there but that's okay) sinon.stub(d3, 'mouse').callsFake(() => [50, 0]); this.plot.panels.p.svg.container.select('.lz-axis.lz-x .tick text') .dispatch('mousedown'); - assert.isObject(this.plot.interaction); - assert.isObject(this.plot.interaction.dragging); - assert.equal(this.plot.interaction.dragging.method, 'x_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 0); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + const interaction = this.plot._interaction; + assert.isObject(interaction); + const dragging = interaction.dragging; + assert.isObject(dragging); + assert.equal(dragging.method, 'x_tick'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 0); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 0); // Simulate drag (mousemove) to [ 25, 0 ] (x -25) sinon.stub(d3, 'mouse').callsFake(() => [25, 50]); this.plot.svg.node()['__onmousemove.plot'](); - assert.equal(this.plot.interaction.dragging.method, 'x_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 0); - assert.equal(this.plot.interaction.dragging.dragged_x, -25); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + assert.equal(dragging.method, 'x_tick'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 0); + assert.equal(dragging.dragged_x, -25); + assert.equal(dragging.dragged_y, 0); assert.deepEqual(this.plot.panels.p.x_extent, [1, 9]); // Simulate mouseup at new location this.plot.svg.node()['__onmouseup.plot'](); - assert.deepEqual(this.plot.interaction, {}); + assert.deepEqual(interaction, {}); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.floor, 1); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.ceiling, 9); }); }); it.skip('should pan along the x axis when shift+dragging an x tick', function() { - this.layout.panels[0].interaction.drag_x_ticks_to_scale = true; + this.layout.panels[0]._interaction.drag_x_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { const event = { shiftKey: true, preventDefault: function () { return null; @@ -515,59 +533,65 @@ describe('Panel', function() { // Simulate shift+click (mousedown) at [ 50, 0 ] (x tick probably doesn't exist there but that's okay) sinon.stub(d3, 'mouse').callsFake(() => [50, 0]); this.plot.panels.p.svg.container.select('.lz-axis.lz-x .tick text').node()['__onmousedown.plot.p.interaction.drag'](event); - assert.isObject(this.plot.interaction); - assert.isObject(this.plot.interaction.dragging); - assert.equal(this.plot.interaction.dragging.method, 'x_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 0); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + + const { _interaction } = this.plot; + assert.isObject(_interaction); + const { dragging } = _interaction; + assert.isObject(dragging); + assert.equal(dragging.method, 'x_tick'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 0); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 0); // Simulate drag (mousemove) to [ 25, 0 ] (x -25) sinon.stub(d3, 'mouse').callsFake(() => [25, 0]); this.plot.svg.node()['__onmousemove.plot'](event); - assert.equal(this.plot.interaction.dragging.method, 'x_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 50); - assert.equal(this.plot.interaction.dragging.start_y, 0); - assert.equal(this.plot.interaction.dragging.dragged_x, -25); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + assert.equal(dragging.method, 'x_tick'); + assert.equal(dragging.start_x, 50); + assert.equal(dragging.start_y, 0); + assert.equal(dragging.dragged_x, -25); + assert.equal(dragging.dragged_y, 0); assert.deepEqual(this.plot.panels.p.x_extent, [2, 6]); // Simulate mouseup at new location this.plot.svg.node()['__onmouseup.plot'](event); - assert.deepEqual(this.plot.interaction, {}); + assert.deepEqual(_interaction, {}); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.floor, 2); assert.equal(this.plot.panels.p.data_layers.d.layout.x_axis.ceiling, 6); }); }); it.skip('should scale along the y1 axis when dragging a y1 tick', function() { - this.layout.panels[0].interaction.drag_y1_ticks_to_scale = true; + this.layout.panels[0]._interaction.drag_y1_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { // Simulate click (mousedown) at [ 0, 25 ] (y1 tick probably doesn't exist there but that's okay) sinon.stub(d3, 'mouse').callsFake(() => [0, 25]); this.plot.panels.p.svg.container.select('.lz-axis.lz-y1 .tick text').node()['__onmousedown.plot.p.interaction.drag'](); - assert.isObject(this.plot.interaction); - assert.isObject(this.plot.interaction.dragging); - assert.equal(this.plot.interaction.dragging.method, 'y1_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 0); - assert.equal(this.plot.interaction.dragging.start_y, 25); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + const { interaction } = this.plot; + assert.isObject(interaction); + + const { dragging } = interaction; + assert.isObject(dragging); + assert.equal(dragging.method, 'y1_tick'); + assert.equal(dragging.start_x, 0); + assert.equal(dragging.start_y, 25); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 0); // Simulate drag (mousemove) to [ 0, 75 ] (x +50) sinon.stub(d3, 'mouse').callsFake(() => [0, 75]); this.plot.svg.node()['__onmousemove.plot'](); - assert.equal(this.plot.interaction.dragging.method, 'y1_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 0); - assert.equal(this.plot.interaction.dragging.start_y, 25); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 50); + assert.equal(dragging.method, 'y1_tick'); + assert.equal(dragging.start_x, 0); + assert.equal(dragging.start_y, 25); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 50); assert.deepEqual(this.plot.panels.p.y1_extent, [2, 14.000000000000004]); // Simulate mouseup at new location this.plot.svg.node()['__onmouseup.plot'](); - assert.deepEqual(this.plot.interaction, {}); + assert.deepEqual(interaction, {}); assert.equal(this.plot.panels.p.data_layers.d.layout.y_axis.floor, 2); assert.equal(this.plot.panels.p.data_layers.d.layout.y_axis.ceiling, 14.000000000000004); }); @@ -576,7 +600,7 @@ describe('Panel', function() { it.skip('should pan along the y axis when shift+dragging a y tick', function() { this.layout.panels[0].interaction.drag_y1_ticks_to_scale = true; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { const event = { shiftKey: true, preventDefault: function () { return null; @@ -586,26 +610,28 @@ describe('Panel', function() { sinon.stub(d3, 'mouse').callsFake(() => [0, 25]); this.plot.panels.p.svg.container.select('.lz-axis.lz-y1 .tick text').node()['__onmousedown.plot.p.interaction.drag'](event); - assert.isObject(this.plot.interaction); - assert.isObject(this.plot.interaction.dragging); - assert.equal(this.plot.interaction.dragging.method, 'y1_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 0); - assert.equal(this.plot.interaction.dragging.start_y, 25); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 0); + const interaction = this.plot.interaction; + assert.isObject(interaction); + const dragging = interaction.dragging; + assert.isObject(dragging); + assert.equal(dragging.method, 'y1_tick'); + assert.equal(dragging.start_x, 0); + assert.equal(dragging.start_y, 25); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 0); // Simulate drag (mousemove) to [ 0, 75 ] (x +50) sinon.stub(d3, 'mouse').callsFake(() => [0, 75]); this.plot.svg.node()['__onmousemove.plot'](event); - assert.equal(this.plot.interaction.dragging.method, 'y1_tick'); - assert.equal(this.plot.interaction.dragging.start_x, 0); - assert.equal(this.plot.interaction.dragging.start_y, 25); - assert.equal(this.plot.interaction.dragging.dragged_x, 0); - assert.equal(this.plot.interaction.dragging.dragged_y, 50); + assert.equal(dragging.method, 'y1_tick'); + assert.equal(dragging.start_x, 0); + assert.equal(dragging.start_y, 25); + assert.equal(dragging.dragged_x, 0); + assert.equal(dragging.dragged_y, 50); assert.deepEqual(this.plot.panels.p.y1_extent, [4, 8]); // Simulate mouseup at new location this.plot.svg.node()['__onmouseup.plot'](event); - assert.deepEqual(this.plot.interaction, {}); + assert.deepEqual(interaction, {}); assert.equal(this.plot.panels.p.data_layers.d.layout.y_axis.floor, 4); assert.equal(this.plot.panels.p.data_layers.d.layout.y_axis.ceiling, 8); }); @@ -664,9 +690,9 @@ describe('Panel', function() { this.plot.on('element_clicked', plot_spy); this.panel.emit('element_clicked', {something: 1}, true); - assert.isUndefined(this.panel.event_hooks['element_clicked'], 'Panel listener is not defined'); - assert.isDefined(this.plot.event_hooks['element_clicked'], 'Plot listener is defined'); - assert.equal(this.plot.event_hooks['element_clicked'].length, 1, 'Plot listener is defined and attached'); + assert.isUndefined(this.panel._event_hooks['element_clicked'], 'Panel listener is not defined'); + assert.isDefined(this.plot._event_hooks['element_clicked'], 'Plot listener is defined'); + assert.equal(this.plot._event_hooks['element_clicked'].length, 1, 'Plot listener is defined and attached'); assert.ok(plot_spy.calledOnce, 'Plot event was bubbled up even though there is no listener on the panel'); }); @@ -721,20 +747,20 @@ describe('Panel', function() { it('allows event listeners to be removed / cleaned up individually', function() { const listener_handle = this.panel.on('element_clicked', function () { }); - assert.equal(this.panel.event_hooks['element_clicked'].length, 1, 'Registered event listener'); + assert.equal(this.panel._event_hooks['element_clicked'].length, 1, 'Registered event listener'); this.panel.off('element_clicked', listener_handle); - assert.equal(this.panel.event_hooks['element_clicked'].length, 0, 'De-registered event listener'); + assert.equal(this.panel._event_hooks['element_clicked'].length, 0, 'De-registered event listener'); }); it('allows event listeners to be removed / cleaned up all at once', function() { // Register two events! this.panel.on('element_clicked', function() {}); this.panel.on('element_clicked', function() {}); - assert.equal(this.panel.event_hooks['element_clicked'].length, 2, 'Registered event listeners'); + assert.equal(this.panel._event_hooks['element_clicked'].length, 2, 'Registered event listeners'); this.panel.off('element_clicked'); - assert.equal(this.panel.event_hooks['element_clicked'].length, 0, 'De-registered event listener'); + assert.equal(this.panel._event_hooks['element_clicked'].length, 0, 'De-registered event listener'); }); it('should scope the value of this to wherever the listener was attached, unless overridden', function() { diff --git a/test/unit/components/test_plot.js b/test/unit/components/test_plot.js index f8d815c1..8696e198 100644 --- a/test/unit/components/test_plot.js +++ b/test/unit/components/test_plot.js @@ -5,11 +5,8 @@ import sinon from 'sinon'; import Plot, {_updateStatePosition} from '../../../esm/components/plot'; import DataSources from '../../../esm/data'; import {populate} from '../../../esm/helpers/display'; -import { LAYOUTS } from '../../../esm/registry'; describe('LocusZoom.Plot', function() { - // Tests - describe('Geometry and Panels', function() { beforeEach(function() { const layout = { @@ -17,18 +14,19 @@ describe('LocusZoom.Plot', function() { panels: [], }; d3.select('body').append('div').attr('id', 'plot'); - this.plot = populate('#plot', null, layout); + this.plot = populate('#plot', new DataSources(), layout); }); afterEach(function() { d3.select('#plot').remove(); delete this.plot; }); + it('should allow for adding arbitrarily many panels', function() { const panelA = this.plot.addPanel({ id: 'panelA', foo: 'bar' }); assert.equal(panelA.id, 'panelA'); assert.equal(this.plot.panels[panelA.id], panelA); assert.equal(this.plot.panels[panelA.id].parent, this.plot); - assert.equal(this.plot.panels[panelA.id].layout_idx, 0); + assert.equal(this.plot.panels[panelA.id]._layout_idx, 0); assert.equal(this.plot.layout.panels.length, 1); assert.equal(this.plot.layout.panels[0].id, panelA.id); assert.equal(this.plot.layout.panels[0].foo, 'bar'); @@ -37,11 +35,12 @@ describe('LocusZoom.Plot', function() { assert.equal(panelB.id, 'panelB'); assert.equal(this.plot.panels[panelB.id], panelB); assert.equal(this.plot.panels[panelB.id].parent, this.plot); - assert.equal(this.plot.panels[panelB.id].layout_idx, 1); + assert.equal(this.plot.panels[panelB.id]._layout_idx, 1); assert.equal(this.plot.layout.panels.length, 2); assert.equal(this.plot.layout.panels[1].id, 'panelB'); assert.equal(this.plot.layout.panels[1].foo, 'baz'); }); + it('should allow for removing panels', function() { const panelA = this.plot.addPanel({ id: 'panelA', foo: 'bar', height: 10 }); const panelB = this.plot.addPanel({ id: 'panelB', foo: 'baz', height: 20 }); @@ -55,10 +54,11 @@ describe('LocusZoom.Plot', function() { assert.doesNotHaveAnyKeys(this.plot.panels, ['panelA']); assert.equal(this.plot.layout.panels.length, 1); assert.equal(this.plot.layout.panels[0].id, 'panelB'); - assert.equal(this.plot.panels[panelB.id].layout_idx, 0); + assert.equal(this.plot.panels[panelB.id]._layout_idx, 0); assert.equal(this.plot._total_height, 20, 'Final height is the space requested by the remaining single panel'); }); + it('should allow setting dimensions', function() { this.plot.setDimensions(563, 681); assert.equal(this.plot.layout.width, 563); @@ -70,6 +70,7 @@ describe('LocusZoom.Plot', function() { this.plot.setDimensions('q', 0); assert.equal(this.plot.layout.width, 563, 'Non-numeric value is ignored'); }); + it('show rescale all panels equally when resizing the plot', function () { assert.equal(this.plot._total_height, 0, 'Empty plot has no height'); @@ -83,6 +84,7 @@ describe('LocusZoom.Plot', function() { assert.equal(panelA.layout.height, 200, 'Panel A doubles in size because plot doubles in size'); assert.equal(panelB.layout.height, 400, 'Panel B doubles in size because plot doubles in size'); }); + it('should rescale all panels and the plot, but only down to the specified minimum size', function () { assert.equal(this.plot._total_height, 0, 'Empty plot has no height'); @@ -96,23 +98,52 @@ describe('LocusZoom.Plot', function() { assert.equal(panelA.layout.height, 50, 'Panel A does not shrink below the minimum size'); assert.equal(panelB.layout.height, 100, 'Panel B does not shrink below the minimum size'); }); + + it.skip('resizes to the full container size when toggling display:none --> visible', function () { + // TODO: JSDOM doesn't implement intersectionobserver, making it hard to unit test this feature without extensive mocking. + const plot = this.plot; + plot.layout.responsive_resize = true; + plot.layout.min_width = 50; + plot.initialize(); + + d3.select('body').style('display', 'none'); + plot.rescaleSVG(); + assert.equal(plot.layout.width, 50, 'When parent element is hidden, plot renders to the minimum dimensions'); + + d3.select('body').style('display', 'block'); + plot.rescaleSVG(); + assert.equal(plot.layout.width, 100, 'When parent element is shown, plot renders to the desired width'); + }); + it('should enforce consistent data layer widths and x-offsets across x-linked panels', function() { const layout = { width: 1000, panels: [ - LAYOUTS.get('panel', 'association', { margin: { left: 200 } }), - LAYOUTS.get('panel', 'association', { id: 'assoc2', margin: { right: 300 } }), + { + id: 'association', + margin: { top: 35, right: 50, bottom: 40, left: 200 }, + interaction: { x_linked: true }, + }, + { + id: 'assoc2', + margin: { top: 35, right: 300, bottom: 40, left: 50 }, + interaction: { x_linked: true }, + }, ], }; - this.plot = populate('#plot', null, layout); - assert.equal(this.plot.layout.panels[0].margin.left, 200); - assert.equal(this.plot.layout.panels[1].margin.left, 200); - assert.equal(this.plot.layout.panels[0].margin.right, 300); - assert.equal(this.plot.layout.panels[1].margin.right, 300); - assert.equal(this.plot.layout.panels[0].cliparea.origin.x, 200); - assert.equal(this.plot.layout.panels[1].cliparea.origin.x, 200); - assert.equal(this.plot.layout.panels[0].origin.x, this.plot.layout.panels[0].origin.x); + this.plot = populate('#plot', new DataSources(), layout); + + const panel0 = this.plot.layout.panels[0]; + const panel1 = this.plot.layout.panels[1]; + + assert.equal(panel0.margin.left, 200); + assert.equal(panel1.margin.left, 200, 'Adjusts second panel to match margins of first'); + assert.equal(panel0.margin.right, 300); + assert.equal(panel1.margin.right, 300); + assert.equal(panel0.cliparea.origin.x, 200); + assert.equal(panel1.cliparea.origin.x, 200); }); + it('should not allow for a non-numerical / non-positive predefined dimensions', function() { assert.throws(() => { populate('#plot', null, { width: 0 }); @@ -127,10 +158,14 @@ describe('LocusZoom.Plot', function() { describe('Mouse Guide Layer', function() { beforeEach(function() { d3.select('body').append('div').attr('id', 'plot'); - const layout = LAYOUTS.get('plot', 'standard_association'); - layout.state = { chr: '1', start: 1, end: 100000 }; - this.plot = populate('#plot', null, layout); + const layout = { + state: {}, + width: 800, + panels: [], + }; + this.plot = populate('#plot', new DataSources(), layout); }); + it('first child should be a mouse guide layer group element', function() { assert.equal(d3.select(this.plot.svg.node().firstChild).attr('id'), 'plot.mouse_guide'); }); @@ -148,6 +183,7 @@ describe('LocusZoom.Plot', function() { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', datasources, layout); }); + it('Should allocate the space requested by the panel, even if less than plot height', function() { const panelA = { id: 'panelA', height: 50 }; this.plot.addPanel(panelA); @@ -158,6 +194,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelA.layout.height, 50); assert.equal(this.plot.panels.panelA.layout.origin.y, 0); }); + it('Should extend the size of the plot if panels are added that expand it, and automatically prevent panels from overlapping vertically', function() { const panelA = { id: 'panelA', height: 60 }; const panelB = { id: 'panelB', height: 60 }; @@ -172,6 +209,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelB.layout.height, 60); assert.equal(this.plot.panels.panelB.layout.origin.y, 60); }); + it('Should resize the plot as panels are removed', function() { const panelA = { id: 'panelA', height: 60 }; const panelB = { id: 'panelB', height: 60 }; @@ -185,6 +223,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelB.layout.height, 60); assert.equal(this.plot.panels.panelB.layout.origin.y, 0); }); + it('Should resize the plot as panels are removed, when panels specify min_height', function() { // Small hack; resize the plot after it was created this.plot.layout.height = 600; @@ -210,6 +249,7 @@ describe('LocusZoom.Plot', function() { // after panel C is removed. assert.equal(this.plot.panels.panelB.layout.origin.y, 300, 'Panel B origin.y matches layout value'); }); + it('Should resize the plot while retaining panel proportions when panel is removed, if plot min_height does not take precedence', function() { // When we remove a panel, we often want the plot to shrink by exactly that size. (so that the bottom // section simply disappears without changing the appearance of the panels that remain) But if plot @@ -236,6 +276,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelB.layout.height, 50, 'Panel B height matches layout (after)'); assert.equal(this.plot.panels.panelB.layout.origin.y, 300, 'Panel B origin.y appears immediately after panel A'); }); + it('Should allow for inserting panels at discrete y indexes', function() { const panelA = { id: 'panelA', height: 60 }; const panelB = { id: 'panelB', height: 61 }; @@ -246,7 +287,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelA.layout.y_index, 0); assert.equal(this.plot.panels.panelB.layout.y_index, 2); assert.equal(this.plot.panels.panelC.layout.y_index, 1); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['panelA', 'panelC', 'panelB']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['panelA', 'panelC', 'panelB']); assert.deepEqual(panelA.height, 60, 'panel A height matches layout value'); assert.deepEqual(panelB.height, 61, 'panel B height matches layout value'); @@ -254,6 +295,7 @@ describe('LocusZoom.Plot', function() { assert.deepEqual(panelA.height + panelB.height + panelC.height, this.plot._total_height, 'Plot height is equal to sum of panels'); }); + it('Should allow for inserting panels at negative discrete y indexes', function() { const panelA = { id: 'panelA', height: 60 }; const panelB = { id: 'panelB', height: 60 }; @@ -270,7 +312,7 @@ describe('LocusZoom.Plot', function() { assert.equal(this.plot.panels.panelC.layout.y_index, 2); assert.equal(this.plot.panels.panelD.layout.y_index, 4); assert.equal(this.plot.panels.panelE.layout.y_index, 3); - assert.deepEqual(this.plot.panel_ids_by_y_index, ['panelA', 'panelB', 'panelC', 'panelE', 'panelD']); + assert.deepEqual(this.plot._panel_ids_by_y_index, ['panelA', 'panelB', 'panelC', 'panelE', 'panelD']); }); }); @@ -284,6 +326,7 @@ describe('LocusZoom.Plot', function() { d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', datasources, layout); }); + it('should show/hide/update on command and track shown status', function() { assert.isFalse(this.plot.curtain.showing); assert.isNull(this.plot.curtain.selector); @@ -300,12 +343,14 @@ describe('LocusZoom.Plot', function() { assert.isNull(this.plot.curtain.selector); assert.isNull(this.plot.curtain.content_selector); }); + it('should have a loader object with show/update/animate/setPercentCompleted/hide methods, a showing boolean, and selectors', function() { assert.isFalse(this.plot.loader.showing); assert.isNull(this.plot.loader.selector); assert.isNull(this.plot.loader.content_selector); assert.isNull(this.plot.loader.progress_selector); }); + it('should show/hide/update on command and track shown status', function() { assert.isFalse(this.plot.loader.showing); assert.isNull(this.plot.loader.selector); @@ -325,6 +370,7 @@ describe('LocusZoom.Plot', function() { assert.isNull(this.plot.loader.content_selector); assert.isNull(this.plot.loader.progress_selector); }); + it('should allow for animating or showing discrete percentages of completion', function() { this.plot.loader.show('test content').animate(); assert.isTrue(this.plot.loader.progress_selector.classed('lz-loader-progress-animated')); @@ -361,28 +407,31 @@ describe('LocusZoom.Plot', function() { this.layout = null; d3.select('#plot').remove(); }); + it('Should apply basic start/end state validation when necessary', function() { this.layout.state = { chr: 1, start: -60, end: 10300050 }; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.equal(this.plot.state.start, 1); assert.equal(this.plot.state.end, 10300050); }); }); + it('Should apply minimum region scale state validation if set in the plot layout', function() { this.layout.min_region_scale = 2000; this.layout.state = { chr: 1, start: 10300000, end: 10300050 }; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.equal(this.plot.state.start, 10299025); assert.equal(this.plot.state.end, 10301025); }); }); + it('Should apply maximum region scale state validation if set in the plot layout', function() { this.layout.max_region_scale = 4000000; this.layout.state = { chr: 1, start: 10300000, end: 15300000 }; this.plot = populate('#plot', this.datasources, this.layout); - return Promise.all(this.plot.remap_promises).then(() => { + return Promise.all(this.plot._remap_promises).then(() => { assert.equal(this.plot.state.start, 10800000); assert.equal(this.plot.state.end, 14800000); }); @@ -392,12 +441,21 @@ describe('LocusZoom.Plot', function() { describe('subscribeToData', function() { beforeEach(function() { const layout = { - panels: [{ id: 'panel0' }], + panels: [ + { id: 'panel0' }, + { + id: 'panel1', + data_layers: [ { id: 'layer1', type: 'line', namespace: { 'first': 'first' } } ], + }, + ], }; this.first_source_data = [ { x: 0, y: false }, { x: 1, y: true } ]; this.data_sources = new DataSources() - .add('first', ['StaticJSON', this.first_source_data ]); + .add('first', ['StaticSource', { + prefix_namespace: false, // Makes it easier to write tests- "data in === data out" + data: this.first_source_data, + }]); d3.select('body').append('div').attr('id', 'plot'); this.plot = populate('#plot', this.data_sources, layout); @@ -408,67 +466,76 @@ describe('LocusZoom.Plot', function() { sinon.restore(); }); - it('allows subscribing to data using a standard limited fields array', function (done) { - const expectedData = [{ 'first:x': 0 }, { 'first:x': 1 }]; + it('requires specifying one of two ways to subscribe', function () { + assert.throws( + () => this.plot.subscribeToData({ useless_option: 'something' }), + /must specify the desired data/, + ); + }); - const dataCallback = sinon.spy(); + it('allows subscribing to the data of a layer by name', function () { + const callbackShort = sinon.spy(); + const callbackLong = sinon.spy(); - this.plot.subscribeToData( - [ 'first:x' ], - dataCallback, - { onerror: done } - ); + const listener = this.plot.subscribeToData({ from_layer: 'panel1.layer1' }, callbackShort); + assert.ok(listener, 'Subscribes to partial path (panel.layer syntax)'); - this.plot.applyState().catch(done); + const listener2 = this.plot.subscribeToData({ from_layer: 'plot.panel1.layer1' }, callbackLong); + assert.ok(listener2, 'Subscribes to full path (plot.panel.layer syntax)'); - // Ugly hack: callback was not recognized at time of promise resolution, and data_rendered may be fired - // more than once during rerender - window.setTimeout(function() { - try { - assert.ok(dataCallback.called, 'Data handler was called'); - assert.ok(dataCallback.calledWith(expectedData), 'Data handler received the expected data'); - done(); - } catch (error) { - done(error); - } - }, 0); + return this.plot.applyState().then(() => { + assert.ok(callbackShort.called, 'panel.layer callback invoked'); + assert.ok(callbackShort.calledWith(this.first_source_data), 'panel.layer callback receives expected data'); + assert.ok(callbackLong.called, 'plot.panel.layer callback invoked'); + assert.ok(callbackLong.calledWith(this.first_source_data), 'plot.panel.layer callback receives expected data'); + }); + }); + + it('warns when subscribing to the data of a layer that does not exist', function () { + assert.throws( + () => this.plot.subscribeToData({ from_layer: 'panel0.layer1' }, () => null), + /unknown data layer/, + 'Warns if requesting an unknown layer', + ); }); - it('allows subscribing to individual (not combined) sources', function (done) { - const expectedData = { first: [{ 'first:x': 0 }, { 'first:x': 1 }] }; + it('allows subscribing to data using namespace syntax', function () { const dataCallback = sinon.spy(); - this.plot.subscribeToData( - [ 'first:x' ], + const listener = this.plot.subscribeToData( + { namespace: { 'first': 'first' } }, dataCallback, - { onerror: done, discrete: true } ); - // Ugly hack: callback was not recognized at time of promise resolution, and data_rendered may be fired - // more than once during rerender - window.setTimeout(function() { - try { - assert.ok(dataCallback.called, 'Data handler was called'); - assert.ok(dataCallback.calledWith(expectedData), 'Data handler received the expected data'); - done(); - } catch (error) { - done(error); - } - }, 0); + assert.ok(listener, 'Listener defined'); + + // When data is manually specified, it calls an async method inside an event hook- no problem in a real + // page, but it makes writing async tests a bit tricksy. + // Force the callback to fire and (pretty much mostly) complete + this.plot.emit('data_rendered'); + + // Technically there's a slight chance of race condition still. Watch for random failures. + return this.plot.applyState().then(() => { + assert.ok(dataCallback.called, 'Data handler was called'); + assert.ok(dataCallback.calledWith(this.first_source_data), 'Data handler received the expected data'); + }); }); it('calls an error callback if a problem occurs while fetching data', function() { - const dataCallback = sinon.spy(); + const dataCallback = () => { + throw new Error('Data callback should not be called'); + }; const errorCallback = sinon.spy(); this.plot.subscribeToData( - [ 'nosource:x' ], + { + from_layer: 'plot.panel1.layer1', + onerror: errorCallback, + }, dataCallback, - { onerror: errorCallback } ); return this.plot.applyState() .then(function() { - assert.ok(dataCallback.notCalled, 'Data callback was not called'); assert.ok(errorCallback.called, 'Error callback was called'); }); }); @@ -478,17 +545,19 @@ describe('LocusZoom.Plot', function() { const errorCallback = sinon.spy(); const listener = this.plot.subscribeToData( - ['nosource:x'], + { + from_layer: 'plot.panel1.layer1', + onerror: errorCallback, + }, dataCallback, - { onerror: errorCallback } ); - this.plot.off('data_rendered', listener); - this.plot.emit('data_rendered'); - assert.equal( - this.plot.event_hooks['data_rendered'].indexOf(listener), - -1, - 'Listener should not be registered' + this.plot.off('data_from_layer', listener); + this.plot.emit('data_from_layer'); + assert.notInclude( + this.plot._event_hooks['data_from_layer'], + listener, + 'Listener should not be registered', ); assert.ok(dataCallback.notCalled, 'listener success callback was not fired'); assert.ok(errorCallback.notCalled, 'listener error callback was not fired'); @@ -552,7 +621,7 @@ describe('LocusZoom.Plot', function() { this.plot = null; const first_source_data = [{ id: 'a', x: 0, y: false }, { id: 'b', x: 1, y: true }]; const data_sources = new DataSources() - .add('s', ['StaticJSON', first_source_data]); + .add('s', ['StaticJSON', { data: first_source_data }]); this.layout = { panels: [ { @@ -562,20 +631,20 @@ describe('LocusZoom.Plot', function() { id: 'd1', id_field: 's:id', type: 'scatter', - fields: ['s:id', 's:x'], + namespace: { s: 's' }, match: { send: 's:x', receive: 's:x' }, }, { id: 'd2', id_field: 's:id', type: 'scatter', - fields: ['s:id', 's:x', 's:y'], + namespace: { s: 's' }, }, { id: 'd3', id_field: 's:id', type: 'scatter', - fields: ['s:id', 's:y'], + namespace: { s: 's' }, match: { receive: 's:y' }, }, ], @@ -658,7 +727,7 @@ describe('LocusZoom.Plot', function() { assert.equal( filtered[0]['s:id'], 'b', - 'This item displayed is the one that satisfies matching rules' + 'This item displayed is the one that satisfies matching rules', ); }); }); @@ -675,6 +744,7 @@ describe('LocusZoom.Plot', function() { assert.equal(stateB.start, 'foo'); assert.equal(stateB.end, 'bar'); }); + it('should enforce no zeros for start and end (if present with chr)', function() { let stateA = { chr: 1, start: 0, end: 123 }; stateA = _updateStatePosition(stateA); @@ -685,6 +755,7 @@ describe('LocusZoom.Plot', function() { assert.equal(stateB.start, 1); assert.equal(stateB.end, 1); }); + it('should enforce no negative values for start and end (if present with chr)', function() { let stateA = { chr: 1, start: -235, end: 123 }; stateA = _updateStatePosition(stateA); @@ -695,12 +766,14 @@ describe('LocusZoom.Plot', function() { assert.equal(stateB.start, 1); assert.equal(stateB.end, 1); }); + it('should enforce no non-integer values for start and end (if present with chr)', function() { let stateA = { chr: 1, start: 1234.4, end: 4567.8 }; stateA = _updateStatePosition(stateA); assert.equal(stateA.start, 1234); assert.equal(stateA.end, 4567); }); + it('should enforce no non-numeric values for start and end (if present with chr)', function() { let stateA = { chr: 1, start: 'foo', end: 324523 }; stateA = _updateStatePosition(stateA); diff --git a/test/unit/components/test_widgets.js b/test/unit/components/test_widgets.js index ed9a3bc4..9d3b44f2 100644 --- a/test/unit/components/test_widgets.js +++ b/test/unit/components/test_widgets.js @@ -41,7 +41,7 @@ describe('Toolbar widgets', function () { describe('Filter fields Widget', function () { beforeEach(function() { const datasources = new DataSources() - .add('d', ['StaticJSON', [{ id: 1, a: 12 }]]); + .add('d', ['StaticJSON', {data: [{ id: 1, a: 12 }] }]); const layout = { panels: [{ id: 'p', @@ -61,7 +61,7 @@ describe('Toolbar widgets', function () { data_layers: [ { id: 'd', - fields: ['d:id', 'd:a'], + namespace: {d: 'd'}, id_field: 'd:id', type: 'scatter', }, @@ -144,7 +144,7 @@ describe('Toolbar widgets', function () { assert.equal( this.widget._getValue(), output, - `Number conversion should convert input ${input} to output ${output}` + `Number conversion should convert input ${input} to output ${output}`, ); }); }); diff --git a/test/unit/data/test_adapters.js b/test/unit/data/test_adapters.js index e3bf2231..c67a7b7a 100644 --- a/test/unit/data/test_adapters.js +++ b/test/unit/data/test_adapters.js @@ -1,359 +1,119 @@ +/** + LocusZoom.js Data Test Suite + Test LocusZoom Data retrieval functionality + */ import { assert } from 'chai'; -import sinon from 'sinon'; import { - AssociationLZ, BaseAdapter, - ConnectorSource, + BaseApiAdapter, + BaseLZAdapter, + BaseUMAdapter, GeneLZ, - GwasCatalogLZ, LDServer, RecombLZ, StaticSource, } from '../../../esm/data/adapters'; -/** - LocusZoom.js Data Test Suite - Test LocusZoom Data access objects - */ -describe('Data adapters', function () { - describe('Base Source Behavior', function () { - describe('Source.getData', function () { - it('dependentSource skips making a request if previous sources did not add data to chain.body', function () { - const source = new BaseAdapter({}); - source.__dependentSource = true; - let requestStub = sinon.stub(source, 'getRequest'); - - const callable = source.getData(); - const noRecordsChain = { body: [] }; - callable(noRecordsChain); - - assert.ok(requestStub.notCalled, 'Request should be skipped'); - }); - - it('dependentSource makes a request if chain.body has data from previous sources', function (done) { - const source = new BaseAdapter({}); - source.__dependentSource = false; - const requestStub = sinon.stub(source, 'getRequest').callsFake(function () { - return Promise.resolve(); - }); - sinon.stub(source, 'parseResponse').callsFake(function () { - // Because this is an async test, `done` will serve as proof that parseResponse was called - done(); - }); - - const callable = source.getData(); - const hasRecordsChain = { body: [{ some: 'data' }] }; - callable(hasRecordsChain); - - assert.ok(requestStub.called, 'Request was made'); - }); - afterEach(function () { - sinon.restore(); - }); +describe('Data adapters', function () { + describe('BaseAdapter (removed)', function () { + it('warns when trying to create instance of (removed) old style adapters', function () { + assert.throws( + () => new BaseAdapter({}), + /have been replaced/, + ); + assert.throws( + () => new BaseApiAdapter({}), + /have been replaced/, + ); }); + }); - describe('Source.getRequest', function () { - it('uses cached data when zooming in', function () { - const source = new BaseAdapter({}); - - const fetchStub = sinon.stub(source, 'fetchRequest').returns(Promise.resolve()); - - let state = { chr: 1, start: 500, end: 1500 }; - let chain = {}; - let fields = []; - const first_key = source.getCacheKey({ chr: 1, start: 500, end: 1500 }); - - // The flags that control cache are set in getRequest (eg, cache miss --> nework request --> update flags) - // Thus the testing plan involves calling getRequest, then checking the expected cache key based on those updated parameters - return source.getRequest(state, chain, fields) - .then(() => { - // Cache hits from the same key - assert.equal( - source.getCacheKey({ chr: 1, start: 750, end: 1250 }), - first_key, - 'Zooming in triggers a cache hit' - ); - assert.equal( - source.getCacheKey({ chr: 1, start: 625, end: 1125 }), - first_key, - 'Panning left inside cached area triggers a cache hit' - ); - assert.equal( - source.getCacheKey({ chr: 1, start: 750, end: 1250 }), - first_key, - 'Panning right inside cached area triggers a cache hit' - ); - - // Prepare for the second request, a cache miss - state = { chr: 1, start: 250, end: 1250 }; - return source.getRequest(state); - }).then(() => { - const second_key = source.getCacheKey(state); - assert.notEqual( - second_key, - first_key, - 'Panning left outside the original zoom area triggers a cache miss' - ); - assert.equal( - second_key, - source.getCacheKey({ chr: 1, start: 400, end: 900 }), - 'After a cache miss, cache hits are relative to the newly fetched data' - ); - - // Slightly weak in that most of the asserts don't actually use getRequest, but... - assert.ok(fetchStub.calledTwice, 'Two fetches triggered by cache miss'); - - assert.notEqual( - source.getCacheKey({ chr: 2, start: 250, end: 1250 }), - second_key, - 'A change in chromosome ALWAYS triggers a cache miss, even if position is the same' - ); - }); - }); + describe('BaseLZAdapter', function () { - afterEach(function () { - sinon.restore(); - }); + class BaseTestClass extends BaseLZAdapter { + _performRequest(options) { + // For fixture purposes, just return some data passed in. Can use this to forcibly test cache hit/miss.. + return options._test_data; + } + } + + it('will merge options nested in config.params into the base options for backwards compat', function () { + const source = new BaseTestClass({ a: 1, params: {b: 2, c: 3, a: 4}}); + assert.deepEqual(source._config, {b: 2, c: 3, a: 4}, 'Options in config.params will be merged, and original .params child will be deleted'); }); - describe('Source.parseResponse', function () { - // Parse response is a wrapper for a set of helper methods. Test them individually, and combined. - afterEach(function () { - sinon.restore(); - }); + it('checks if request can be satisfied using cached data', function () { + const source = new BaseTestClass({ prefix_namespace: false }); + const first_test_data = [{a: 1, b:2}]; + const different_if_cache_hit = [{a: 1, b:2}]; + return source.getData({ chr: '1', start: 100, end: 200, _test_data: first_test_data }) + .then((result) => { + assert.deepEqual(result, first_test_data, 'First request received data passed in'); + return source.getData({ chr: '1', start: 125, end: 175, _test_data: different_if_cache_hit }); + }) + .then((result) => { + assert.deepEqual(result, first_test_data, 'Second request receives cache data for a region that is superset'); + return source.getData({ chr: '1', start: 120, end: 180, _test_data: different_if_cache_hit }); + }).then((result) => { + assert.deepEqual(result, first_test_data, 'A third request shows that the cache is still based on the widest possible region (first request)'); + return source.getData({ chr: '2', start: 120, end: 180, _test_data: different_if_cache_hit }); + }).then((result) => assert.deepEqual(result, different_if_cache_hit, 'Diff region, so not a cache hit')); + }); - describe('Source.normalizeResponse', function () { - it('should create one object per piece of data', function () { - const source = new BaseAdapter({}); - const res = source.normalizeResponse( - { a: [1, 2], b: [3, 4] }); - assert.deepEqual( - res, - [{ a: 1, b: 3 }, { a: 2, b: 4 }], - 'Correct number and union of elements' - ); - }); - - it('should require all columns of data to be of same length', function () { - const source = new BaseAdapter({}); - assert.throws( - function () { - source.normalizeResponse({ a: [1], b: [1, 2], c: [1, 2, 3] }); - }, - /expects a response in which all arrays of data are the same length/ - ); - }); - - it('should return the data unchanged if it is already in the desired shape', function () { - const source = new BaseAdapter({}); - const data = [{ a: 1, b: 3 }, { a: 2, b: 4 }]; - const res = source.normalizeResponse(data); - assert.deepEqual(res, data); - }); - }); + it('prefixes responses with the name of the provider', function () { + const source = new BaseTestClass({}); + return source.getData({ + _provider_name: 'sometest', + _test_data: [{ a: 1, b: 2 }]}, + ).then((result) => assert.deepEqual(result, [{'sometest:a': 1, 'sometest:b': 2}])); + }); - describe('Source.annotateData', function () { - it('should be able to add fields to the returned records', function () { - const custom_class = class extends BaseAdapter { - annotateData(records) { - // Custom hook that adds a field to every parsed record - return records.map(function (item) { - item.force = true; - return item; - }); - } - }; - - // Async test depends on promise - return new custom_class({}).parseResponse([{ a: 1, b: 1 }, { - a: 2, - b: 2, - }], {}, ['a', 'b', 'force'], ['a', 'b', 'force'], []).then(function (records) { - records.body.forEach(function (item) { - assert.ok(item.force, 'Record should have an additional key not in raw server payload'); - }); - }); - }); - - it('should be able to annotate based on info in the body and chain', function () { - const custom_class = class extends BaseAdapter { - annotateData(records, chain) { - return records + chain.header.param; - } - }; - const result = new custom_class({}).annotateData( - 'some data', - { header: { param: ' up the chain' } } - ); - assert.equal(result, 'some data up the chain'); - }); - }); + it('can optionally restrict final payload to a preset list of fields', function () { + const source = new BaseTestClass({ limit_fields: ['b'] }); + return source.getData({ + _provider_name: 'sometest', + _test_data: [{ a: 1, b: 2 }]}, + ).then((result) => assert.deepEqual(result, [{ 'sometest:b': 2}])); + }); - describe('Source.extractFields', function () { - it('extracts the specified fields from each record', function () { - const source = new BaseAdapter({}); - const res = source.extractFields( - [{ 'id': 1, 'val': 5 }, { 'id': 2, 'val': 10 }], - ['id'], ['namespace:id'], [null] - ); - assert.deepEqual(res, [{ 'namespace:id': 1 }, { 'namespace:id': 2 }]); - }); - - it('applies value transformations where appropriate', function () { - const source = new BaseAdapter({}); - const res = source.extractFields( - [{ 'id': 1, 'val': 5 }, { 'id': 2, 'val': 10 }], - ['id', 'val'], ['namespace:id|add1', 'bork:bork'], [function (val) { - return val + 1; - }, null] - ); - // Output fields can be mapped to any arbitrary based on the field->outnames provided - assert.deepEqual(res, [{ 'namespace:id|add1': 2, 'bork:bork': 5 }, { - 'namespace:id|add1': 3, - 'bork:bork': 10, - }]); - }); - - it('throws an error when requesting a field not present in at least one record', function () { - const source = new BaseAdapter({}); - - assert.throws(function () { - source.extractFields( - [{ 'a': 1 }, { 'a': 2 }], - ['b'], ['namespace:b'], [null] - ); - }, /field b not found in response for namespace:b/); - }); - }); + it('has a helper to locate dependent fields that were already namespaced', function () { + const source = new BaseTestClass({}); + const match = source._findPrefixedKey({'sometest:aaa': 1, 'sometest:a': 2, 'sometest:aa': 3}, 'a'); - describe('Source.combineChainBody', function () { - it('returns only the body by default', function () { - const source = new BaseAdapter({}); - - const expectedBody = [{ 'namespace:a': 1 }]; - const res = source.combineChainBody(expectedBody, { header: {}, body: [], discrete: {} }); - - assert.deepEqual(res, expectedBody); - }); - - it('can build a body based on records from all sources in the chain', function () { - const custom_class = class extends BaseAdapter { - combineChainBody(records, chain) { - return records.map(function (item, index) { - return Object.assign({}, item, chain.body[index]); - }); - } - }; - const source = new custom_class({}); - - var records = [{ 'namespace:a': 1 }]; - const res = source.combineChainBody(records, { - header: {}, - body: [{ 'namespace:b': 2 }], - discrete: {}, - }); - - assert.deepEqual(res, [{ 'namespace:a': 1, 'namespace:b': 2 }]); - }); - }); + assert.equal(match, 'sometest:a', 'Found correct key and ignored partial suffixes'); - describe('integration of steps', function () { - it('should interpret a string response as JSON', function () { - const source = new BaseAdapter({}); - - return source.parseResponse('{"a_field": ["val"]}', {}, ['a_field'], ['namespace:a_field'], [null]) - .then(function (chain) { - assert.deepEqual(chain.body, [{ 'namespace:a_field': 'val' }]); - }); - }); - - it('should store annotations in body and chain.discrete where appropriate', function () { - const custom_class = class CustomClass extends BaseAdapter { - annotateData(data) { - return `${data} with annotation`; - } - - normalizeResponse(data) { - return data; - } - - extractFields(data) { - return data; - } - }; - - const result = new custom_class({}).parseResponse({ data: 'a response' }, {}); - return result.then(function (chain) { - assert.deepEqual(chain.discrete, { CustomClass: 'a response with annotation' }, 'Discrete response uses annotations'); - assert.deepEqual(chain.body, 'a response with annotation', 'Combined body uses annotations'); - }); - }); - - it('integrates all methods via promise semantics', function () { - // Returning a promise is optional, but should be supported if a custom subclass chooses to do so - const custom_class = class CustomClass extends BaseAdapter { - normalizeResponse() { - return Promise.resolve([{ a: 1 }]); - } - - annotateData(records) { - return Promise.resolve(records.map(function (item) { - item.b = item.a + 1; - return item; - })); - } - - extractFields(data, fields, outnames, trans) { - const rec = data.map(function (item) { - return { 'bfield': item.b }; - }); - return Promise.resolve(rec); - } - - combineChainBody(records) { - return Promise.resolve(records); - } - }; - - const result = new custom_class({}).parseResponse({}, {}); - const thisBody = [{ bfield: 2 }]; - const expected = { header: {}, discrete: { CustomClass: thisBody }, body: thisBody }; - return result.then(function (final) { - assert.deepEqual(final.body, expected.body, 'Chain produces expected result body'); - assert.deepEqual(final.discrete, expected.discrete, 'The parsed results from this source are also stored in chain.discrete'); - }); - }); - }); + assert.throws( + () => source._findPrefixedKey([{'sometest:aaa': 1 }], 'no_such_key'), + /Could not locate/, + 'Pedantically insists that data match the expected contract', + ); }); }); - describe('Association Data Source', function () { - it('allows normalization + sorting of data', function () { - const source = new AssociationLZ({ - url: 'locuszoom.org', params: { sort: true }, - }); + describe('BaseUMAdapter', function () { + it('normalizes column-based API responses to rows', function () { + const adapter = new BaseUMAdapter({ prefix_namespace: false }); + const result = adapter._normalizeResponse({a: [1], b: [2], c: [3]}); + assert.deepEqual(result, [{ a: 1, b: 2, c: 3 }]); + }); - const sampleData = { position: [2, 1] }; - const expectedData = [{ 'position': 1 }, { 'position': 2 }]; + it('does not try to normalize responses that are already an array', function () { + const adapter = new BaseUMAdapter({ prefix_namespace: false }); + const data = [{ a: 1, b: 2, c: 3 }]; + const result = adapter._normalizeResponse(data); - return source.parseResponse(sampleData, {}, ['position'], ['position'], [null]) - .then(function (resp) { - assert.deepEqual(resp.body, expectedData, 'Results are sorted by position'); - }); + result[0].d = 4; // Mutable reference only works if data is returned as is instead of being reassembled + assert.deepEqual(result, data, 'Data returned as is'); }); - it('usually returns normalized data in the order the data was provided', function () { - const source = new AssociationLZ({ - url: 'locuszoom.org', params: {}, - }); - const sampleData = { position: [2, 1] }; - const expectedData = [{ 'position': 2 }, { 'position': 1 }]; - return source.parseResponse(sampleData, {}, ['position'], ['position'], [null]) - .then(function (resp) { - assert.deepEqual(resp.body, expectedData, 'Order of results matches server response'); - }); + it('warns if trying to normalize a response with arrays of different lengths', function () { + const adapter = new BaseUMAdapter({ prefix_namespace: false }); + assert.throws( + () => adapter._normalizeResponse({ a: [1, 2], b: [3] }), + /same length/, + ); }); }); @@ -363,386 +123,132 @@ describe('Data adapters', function () { const source_name = source_type.name; it('accepts either build or source as config option, but not both', function () { - let source = new source_type({ url: 'www.fake.test', params: { source: 'a', build: 'GRCh37' } }); + let source = new source_type({ url: 'www.fake.test', source: 'a', build: 'GRCh37' }); assert.throws(function () { - source.getURL({}); + source._getURL({}); }, /must provide a parameter specifying either/, `Bad configuration should raise an exception in ${source_type}`); - source = new source_type({ url: 'www.fake.test', params: { source: 'a' } }); - let url = source.getURL({}); + source = new source_type({ url: 'www.fake.test', source: 'a' }); + let url = source._getURL({}); assert.ok(url.match(/ in a/), `Works when specifying source ID for ${source_name}`); source = new source_type({ url: 'www.fake.test' }); - url = source.getURL({ genome_build: 'GRCh37' }); + url = source._getURL({ genome_build: 'GRCh37' }); assert.ok(url.match(/GRCh37/), `Works when specifying build name for ${source_name}`); }); it('gives precedence to state.genome_build over its own config', function () { - const source = new source_type({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - const url = source.getURL({ genome_build: 'GRCh38' }); + const source = new source_type({ url: 'www.fake.test', build: 'GRCh37' }); + const url = source._getURL({ genome_build: 'GRCh38' }); let pattern = /build=GRCh38/; assert.ok(url.match(pattern), `${source_name} produced formed URL: ${url}`); }); it('validates genome build', function () { - const source = new source_type({ url: 'www.fake.test', params: { build: 99 } }); + const source = new source_type({ url: 'www.fake.test', build: 99 }); assert.throws(function () { - source.getURL({}); - }, /must specify a valid genome build number/, `Should validate options for ${source_name}`); + source._getURL({}); + }, /must specify a valid 'genome_build'/, `Should validate options for ${source_name}`); }); }); }); - describe('GwasCatalog Source', function () { - beforeEach(function () { - this.exampleData = [ - { 'chrom': 1, 'pos': 3, 'log_pvalue': 1.3, 'rsid': 'rs3', 'trait': 'arithomania' }, - { 'chrom': 1, 'pos': 4, 'log_pvalue': 1.4, 'rsid': 'rs4', 'trait': 'arithomania' }, - { 'chrom': 1, 'pos': 5, 'log_pvalue': 1.5, 'rsid': 'rs5', 'trait': 'arithomania' }, - { 'chrom': 1, 'pos': 6, 'log_pvalue': 1.6, 'rsid': 'rs6', 'trait': 'arithomania' }, - ]; - this.sampleChain = { - body: [ - { 'assoc:chromosome': 1, 'assoc:position': 2 }, - { 'assoc:chromosome': 1, 'assoc:position': 4 }, - { 'assoc:chromosome': 1, 'assoc:position': 6 }, - ], - }; - }); - - it('will warn if conflicting build and source options are provided', function () { - const source = new GwasCatalogLZ({ url: 'www.fake.test', params: { source: 'fjord' } }); + describe('StaticSource', function () { + it('warns if the `data` key is missing', function () { assert.throws( - () => source.getURL({ genome_build: 'GRCh37' }), - /not specify both/, - 'Warns if conflicting options are used' + () => new StaticSource([]), + /required option/, + ); + assert.throws( + () => new StaticSource({}), + /required option/, ); }); - it('aligns records based on loose position match', function () { - const source = new GwasCatalogLZ({ url: 'www.fake.test', params: { match_type: 'loose' } }); - const res = source.combineChainBody(this.exampleData, this.sampleChain, ['rsid', 'trait'], ['catalog:rsid', 'catalog:trait']); - assert.deepEqual(res, [ - { 'assoc:chromosome': 1, 'assoc:position': 2 }, // No annotations available for this point - { - 'assoc:chromosome': 1, - 'assoc:position': 4, - 'catalog:rsid': 'rs4', - 'catalog:trait': 'arithomania', - 'n_catalog_matches': 1, - }, - { - 'assoc:chromosome': 1, - 'assoc:position': 6, - 'catalog:rsid': 'rs6', - 'catalog:trait': 'arithomania', - 'n_catalog_matches': 1, - }, - ]); - }); - - it('handles the case where the same SNP has more than one catalog entry', function () { - const source = new GwasCatalogLZ({ url: 'www.fake.test' }); - const exampleData = [ - { 'chrom': 1, 'pos': 4, 'log_pvalue': 1.40, 'rsid': 'rs4', 'trait': 'arithomania' }, - { 'chrom': 1, 'pos': 4, 'log_pvalue': 1.41, 'rsid': 'rs4', 'trait': 'graphomania' }, - { 'chrom': 1, 'pos': 6, 'log_pvalue': 1.61, 'rsid': 'rs6', 'trait': 'arithomania' }, - { 'chrom': 1, 'pos': 6, 'log_pvalue': 1.60, 'rsid': 'rs6', 'trait': 'graphomania' }, - ]; - const res = source.combineChainBody(exampleData, this.sampleChain, ['log_pvalue'], ['catalog:log_pvalue']); - assert.deepEqual(res, [ - { 'assoc:chromosome': 1, 'assoc:position': 2 }, // No annotations available for this point - { 'assoc:chromosome': 1, 'assoc:position': 4, 'catalog:log_pvalue': 1.41, 'n_catalog_matches': 2 }, - { 'assoc:chromosome': 1, 'assoc:position': 6, 'catalog:log_pvalue': 1.61, 'n_catalog_matches': 2 }, - ]); - }); - - it('gracefully handles no catalog entries in region', function () { - const source = new GwasCatalogLZ({ url: 'www.fake.test', params: { match_type: 'loose' } }); - const res = source.combineChainBody([], this.sampleChain, ['rsid', 'trait'], ['catalog:rsid', 'catalog:trait']); - assert.deepEqual(res, [ - { 'assoc:chromosome': 1, 'assoc:position': 2 }, - { 'assoc:chromosome': 1, 'assoc:position': 4 }, - { 'assoc:chromosome': 1, 'assoc:position': 6 }, - ]); + it('Returns the exact data provided by the user, regardless of region', function () { + const data = { a: 1, b: 2, c: 3 }; + const source = new StaticSource({ data }); + return source.getData({ chr: 1, start: 2, end: 3}) + .then((result) => { + assert.deepEqual(data, result, 'Returns hard-coded data'); + // Deliberately mutate data, then refetch to ensure that mutations on one request don't pollute shared cache. + data.d = 4; + return source.getData({ chr: 'X', start: 500, end: 1000}); + }) + .then((result) => assert.deepEqual(data, result, 'Returns hard-coded data')); }); }); - describe('LDServer Source', function () { - it('validates the selected build name', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 99 } }); - assert.throws(function () { - source.getURL({}); - }, /must specify a valid genome build number/); + describe('LDServer', function () { + beforeEach(function () { + this._assoc_data = [ + // Deliberately use several variant formats to verify normalization + { 'assoc:variant': '1:23_A/C', 'assoc:log_pvalue': 0.2 }, + { 'assoc:variant': '1:24:A:C', 'assoc:log_pvalue': 125 }, + { 'assoc:variant': '1-25-A-C', 'assoc:log_pvalue': 72 }, + ]; }); - it('will prefer a refvar in plot.state if one is provided', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - const [ref, _] = source.getRefvar( - { ldrefvar: '12:100_A/C' }, - { header: {}, body: [{ id: 'a', pvalue: 0 }] }, - ['ldrefvar', 'state'] - ); - assert.equal(ref, '12:100_A/C'); + it('finds the best variant if none is provided', function () { + const provider = new LDServer({}); + const refvar = provider.__find_ld_refvar({}, this._assoc_data); + assert.equal(refvar, '1:24_A/C', 'Finds variant with max log_pvalue and normalizes spec'); + assert.equal(this._assoc_data[1].lz_is_ld_refvar, true, 'Annotates refvar (best match)'); }); - it('auto-selects the best reference variant (lowest pvalue)', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - const [ref, _] = source.getRefvar( - {}, - { - header: {}, - body: [ - { id: '12:100_A/A', pvalue: 0.5 }, - { id: '12:100_A/B', pvalue: 0.05 }, - { id: '12:100_A/C', pvalue: 0.1 }, - ], - }, - ['isrefvar', 'state'] - ); - assert.equal(ref, '12:100_A/B'); + it('prefers a refvar from plot.state if one is provided', function () { + const provider = new LDServer({}); + const refvar = provider.__find_ld_refvar({ ldrefvar: '1-25-A-C' }, this._assoc_data); + assert.equal(refvar, '1:25_A/C', 'Uses refvar in plot.state and normalizes spec'); + assert.equal(this._assoc_data[2].lz_is_ld_refvar, true, 'Annotates refvar (requested variant)'); }); - it('auto-selects the best reference variant (largest nlog_pvalue)', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - const [ref, _] = source.getRefvar( - {}, - { - header: {}, - body: [ - { id: '12:100_A/A', log_pvalue: 10 }, - { id: '12:100_A/B', log_pvalue: 50 }, - { id: '12:100_A/C', log_pvalue: 7 }, - ], - }, - ['isrefvar', 'state'] - ); - assert.equal(ref, '12:100_A/B'); + it('ignores state.ldrefvar if it refers to a region outside the current view window', function () { + const provider = new LDServer({}); + const refvar = provider.__find_ld_refvar({ chr: 'X', start: 100, end: 200, ldrefvar: 'X-99-A-C' }, this._assoc_data); + assert.equal(refvar, '1:24_A/C', 'Ignores state.ldrefvar because out of range; chooses best refvar instead'); + assert.equal(this._assoc_data[1].lz_is_ld_refvar, true, 'Annotates refvar (best match)'); }); - it('correctly identifies the variant-marker field', function () { - // - const source_default = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - let dataFields = source_default.findMergeFields( - { body: [{ 'assoc:id': 'a', log_pvalue: 10 }] } - ); - assert.equal(dataFields.id, 'assoc:id', 'Uses a default option (ID)'); - - dataFields = source_default.findMergeFields( - { body: [{ 'assoc:variant': 'a', log_pvalue: 10 }] } - ); - assert.equal(dataFields.id, 'assoc:variant', 'Uses a default option (variant name)'); + it('skips the request if no assoc data was present', function () { + const source37 = new LDServer({ url: 'www.fake.test', source: '1000G', build: 'GRCh37' }); - const source_options = new LDServer({ - url: 'www.fake.test', - params: { build: 'GRCh37', id_field: 'marker' }, - }); - dataFields = source_options.findMergeFields( - { body: [{ 'assoc:id': 'a', 'assoc:marker': 'b', log_pvalue: 10 }] } - ); - assert.equal(dataFields.id, 'assoc:marker', 'Uses a provided option (from params.id_field)'); + let request_options = source37._buildRequestOptions({ ldrefvar: '1:2_A/B' }, []); + assert.ok(request_options._skip_request, 'Request is flagged to skip'); - dataFields = source_options.findMergeFields( - { body: [{ 'assoc:onefish': 'a', 'assoc:twofish': 'b', log_pvalue: 10 }] } + assert.throws( + () => source37._buildRequestOptions({ ldrefvar: '1:2_A/B' }, null), + /must depend on/, + 'Warns if the adapter is totally misused (not part of a dependency chain)', ); - assert.equal(dataFields.id, null, 'There is no field matching the requested ID field'); - }); - it('coerces variant formats to one expected by the LD server', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - - const portal_format = '8:117974679:G:A'; - const ldserver_format = '8:117974679_G/A'; - const request_url = source.getURL({ ldrefvar: portal_format }, { - header: {}, - body: [], - }, ['isrefvar', 'state']); - assert.equal( - request_url, - source.getURL({ ldrefvar: ldserver_format }, { header: {}, body: [] }, ['isrefvar', 'state']) + assert.throws( + () => source37._buildRequestOptions({ ldrefvar: '1:2_A/B' }, [{ some_other_data: true, meets_assoc_contract: false }]), + /required key name/, + 'Warns if the adapter is totally misused (not given association data)', ); - assert.ok(request_url.includes(encodeURIComponent(ldserver_format))); - }); - it('coerces variant formats, omitting ref-alt if not provided', function () { - const source = new LDServer({ url: 'www.fake.test', params: { build: 'GRCh37' } }); - const norefvar_topmed = '8-117974679'; - const ldserver_format = '8:117974679'; - const request_url = source.getURL({ ldrefvar: norefvar_topmed }, { - header: {}, - body: [], - }, ['isrefvar', 'state']); - assert.equal( - request_url, - source.getURL({ ldrefvar: ldserver_format }, { header: {}, body: [] }, ['isrefvar', 'state']) - ); - assert.ok(request_url.includes(encodeURIComponent(ldserver_format))); }); it('chooses best 1000G panel for the given build', function () { - const source37 = new LDServer({ url: 'www.fake.test', params: { source: '1000G', build: 'GRCh37' } }); - let request_url = source37.getURL({ ldrefvar: '1:2_A/B' }, { - header: {}, - body: [], - }, ['isrefvar', 'state']); - assert.equal( - request_url, - 'www.fake.testgenome_builds/GRCh37/references/1000G/populations/ALL/variants?correlation=rsquare&variant=1%3A2_A%2FB&chrom=undefined&start=undefined&stop=undefined', - 'Build 37 uses 1000G panel (old)' - ); + const source37 = new LDServer({ url: 'www.fake.test', source: '1000G', build: 'GRCh37' }); + let request_options = source37._buildRequestOptions({ ldrefvar: '1:2_A/B' }, this._assoc_data); + assert.equal(request_options.genome_build, 'GRCh37', 'Build 37 detected'); + assert.equal(request_options.ld_source, '1000G', 'Build 37 uses 1000G panel (old)'); - const source38 = new LDServer({ url: 'www.fake.test', params: { source: '1000G', build: 'GRCh38' } }); - request_url = source38.getURL({ ldrefvar: '1:2_A/B' }, { - header: {}, - body: [], - }, ['isrefvar', 'state']); - assert.equal( - request_url, - 'www.fake.testgenome_builds/GRCh38/references/1000G-FRZ09/populations/ALL/variants?correlation=rsquare&variant=1%3A2_A%2FB&chrom=undefined&start=undefined&stop=undefined', - 'Build 38 uses 1000G panel (upgraded)' - ); - }); - }); + const source38 = new LDServer({ url: 'www.fake.test', source: '1000G', build: 'GRCh38' }); + request_options = source38._buildRequestOptions({ ldrefvar: '1:2_A/B' }, this._assoc_data); - describe('Static Data Source', function () { - beforeEach(function () { - this.data = [ - { x: 0, y: 3, z: 8 }, - { x: 2, y: 7, h: 5 }, - { x: 8, y: 1, q: 6 }, - ]; - this.source = new StaticSource(this.data); - }); - it('should store data passed to the constructor', function () { - assert.deepEqual(this.source._data, this.data); - }); - it('should pass only specifically requested fields and respect namespacing', function () { - return this.source.getData({}, ['x'], ['test:x'], [null])({ - header: {}, - body: [], - discrete: {}, - }).then((data) => { - const expected_data = [{ 'test:x': 0 }, { 'test:x': 2 }, { 'test:x': 8 }]; - assert.hasAllKeys(data, ['header', 'body', 'discrete']); - assert.deepEqual(data.body, expected_data); - }); - }); - it('should pass only specifically requested ', function () { - return this.source.getData({}, ['q'], ['test:q'], [null])({ - header: {}, - body: [], - discrete: {}, - }).then((data) => { - const expected_data = [{ 'test:q': undefined }, { 'test:q': undefined }, { 'test:q': 6 }]; - assert.deepEqual(data.body, expected_data); - }); - }); - }); - - describe('ConnectorSource', function () { - beforeEach(function () { - // Create a source that internally looks for data as "first" from the specified - this.basic_config = { sources: { first: 'a_source', second: 'b_source' } }; - this.basic_source = class test_connector extends ConnectorSource { - combineChainBody(records, chain) { - // A sample method that uses 2 chain sources + an existing body to build an combined response - - // Tell the internal method how to find the actual data it relies on internally, regardless of how - // it is called in the namespaced data chain - const nameFirst = this._source_name_mapping['first']; - const nameSecond = this._source_name_mapping['second']; - - records.forEach(function (item) { - item.a = chain.discrete[nameFirst].a_field; - item.b = chain.discrete[nameSecond].b_field; - }); - return records; - } - - _getRequiredSources() { - return ['first', 'second']; - } - }; + assert.equal(request_options.genome_build, 'GRCh38', 'Build 38 detected'); + assert.equal(request_options.ld_source, '1000G-FRZ09', 'Build 38 uses 1000G panel (upgraded)'); }); - afterEach(function () { - sinon.restore(); - }); - - it('must specify the data it requires from other sources', function () { - const source = class extends ConnectorSource { - _getRequiredSources() { - return []; - } - }; - assert.throws( - function () { - new source(); - }, - /Connectors must specify the data they require as config.sources = {internal_name: chain_source_id}} pairs/ - ); - assert.ok( - new source(this.basic_config), - 'Correctly specifies the namespaces containing data that this connector relies on' - ); - }); - it('must implement a combineChainBody method', function () { - const source = class extends ConnectorSource { - _getRequiredSources() { - return []; - } - }; - assert.throws( - () => { - new source(this.basic_config).combineChainBody(); - }, - /This method must be implemented in a subclass/ - ); - }); - it('should fail if the namespaces it relies on are not present in the chain', function () { - const instance = new this.basic_source(this.basic_config); - assert.throws( - function () { - instance.getRequest({}, { discrete: {} }); - }, - /test_connector cannot be used before loading required data for: a_source/ - ); - }); - it('should not make any network requests', function () { - const instance = new this.basic_source(this.basic_config); - const fetchSpy = sinon.stub(instance, 'fetchRequest'); - - return instance.getRequest({}, { discrete: { a_source: 1, b_source: 2 } }) - .then(function () { - assert.ok(fetchSpy.notCalled, 'No network request was fired'); - }); - }); - it('should not return any new data from getRequest', function () { - const instance = new this.basic_source(this.basic_config); - const expectedBody = { sample: 'response data' }; - return instance.getRequest({}, { discrete: { a_source: 1, b_source: 2 }, body: expectedBody }) - .then(function (records) { - assert.deepEqual(records, expectedBody, 'Should return the previous body'); - }); - }); - it('should build a response by combining data from multiple places', function () { - // Should have access to data in both chain.discrete and chain.body. (connectors don't have their own data) - // Not every source in chain.discrete has to be an array of records- this tests arbitrary blobs of JSON - const rawChain = { a_source: { a_field: 'aaa' }, b_source: { b_field: 'bbb' } }; - const expectedBody = [{ who: 1, a: 'aaa', b: 'bbb' }, { what: 2, a: 'aaa', b: 'bbb' }]; - - const instance = new this.basic_source(this.basic_config); - return instance.getData()( - { - discrete: rawChain, - body: [{ who: 1 }, { what: 2 }], - } - ).then(function (response) { - assert.deepEqual(response.body, expectedBody, 'Response body was correctly annotated'); - assert.deepEqual(response.discrete, rawChain, 'The chain of individual sources was not changed'); - }); + it('validates the selected build name', function () { + const source = new LDServer({ url: 'www.fake.test', build: 99 }); + assert.throws(() => { + source._buildRequestOptions({}, this._assoc_data); + }, /must specify a valid 'genome_build'/); }); }); }); - diff --git a/test/unit/data/test_data_ops.js b/test/unit/data/test_data_ops.js new file mode 100644 index 00000000..ed19fe0f --- /dev/null +++ b/test/unit/data/test_data_ops.js @@ -0,0 +1,130 @@ +/** + * Test custom join logic specific to LZ core code + */ + +import {assert} from 'chai'; + +import {DATA_OPS} from '../../../esm/registry'; + +describe('Data operations', function() { + describe('Common behavior', function () { + it('validates two-argument (join) functions', function () { + const func = DATA_OPS.get('left_match'); + assert.throws( + () => func([1, 2, 3], 'paramA'), + /must receive exactly two recordsets/, + ); + }); + }); + + describe('Custom join operations', function () { + describe('assoc_to_gwas_catalog', function () { + before(function() { + this.func = DATA_OPS.get('assoc_to_gwas_catalog'); + }); + + beforeEach(function () { + this.assoc_data = [ + { 'assoc:chromosome': 1, 'assoc:position': 2 }, + { 'assoc:chromosome': 1, 'assoc:position': 4 }, + { 'assoc:chromosome': 1, 'assoc:position': 6 }, + ]; + this.catalog_data = [ + { 'catalog:chrom': 1, 'catalog:pos': 3, 'catalog:log_pvalue': 1.3, 'catalog:rsid': 'rs3', 'catalog:trait': 'arithomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 4, 'catalog:log_pvalue': 1.4, 'catalog:rsid': 'rs4', 'catalog:trait': 'arithomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 5, 'catalog:log_pvalue': 1.5, 'catalog:rsid': 'rs5', 'catalog:trait': 'arithomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 6, 'catalog:log_pvalue': 1.6, 'catalog:rsid': 'rs6', 'catalog:trait': 'arithomania' }, + ]; + }); + + it('aligns records based on loose position match', function () { + const { func, assoc_data, catalog_data } = this; + const res = func( + {}, + [assoc_data, catalog_data], + 'assoc:position', + 'catalog:pos', + 'catalog:log_pvalue', + ); + + assert.deepEqual(res, [ + { 'assoc:chromosome': 1, 'assoc:position': 2 }, // No annotations available for this point + { + 'assoc:chromosome': 1, + 'assoc:position': 4, + 'catalog:rsid': 'rs4', + 'catalog:trait': 'arithomania', + 'catalog:chrom': 1, + 'catalog:log_pvalue': 1.4, + 'catalog:pos': 4, + 'n_catalog_matches': 1, + }, + { + 'assoc:chromosome': 1, + 'assoc:position': 6, + 'catalog:rsid': 'rs6', + 'catalog:trait': 'arithomania', + 'catalog:chrom': 1, + 'catalog:log_pvalue': 1.6, + 'catalog:pos': 6, + 'n_catalog_matches': 1, + }, + ]); + }); + + it('handles the case where the same SNP has more than one catalog entry', function () { + const { assoc_data, func } = this; + const catalog_data = [ + { 'catalog:chrom': 1, 'catalog:pos': 4, 'catalog:log_pvalue': 1.40, 'catalog:rsid': 'rs4', 'catalog:trait': 'arithomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 4, 'catalog:log_pvalue': 1.41, 'catalog:rsid': 'rs4', 'catalog:trait': 'graphomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 6, 'catalog:log_pvalue': 1.61, 'catalog:rsid': 'rs6', 'catalog:trait': 'arithomania' }, + { 'catalog:chrom': 1, 'catalog:pos': 6, 'catalog:log_pvalue': 1.60, 'catalog:rsid': 'rs6', 'catalog:trait': 'graphomania' }, + ]; + + const res = func( + {}, + [assoc_data, catalog_data], + 'assoc:position', + 'catalog:pos', + 'catalog:log_pvalue', + ); + + assert.deepEqual(res, [ + { 'assoc:chromosome': 1, 'assoc:position': 2 }, // No annotations available for this point + { + 'assoc:chromosome': 1, + 'assoc:position': 4, + 'catalog:chrom': 1, + 'catalog:log_pvalue': 1.41, + 'catalog:pos': 4, + 'catalog:rsid': 'rs4', + 'catalog:trait': 'graphomania', + 'n_catalog_matches': 2, + }, + { + 'assoc:chromosome': 1, + 'assoc:position': 6, + 'catalog:chrom': 1, + 'catalog:log_pvalue': 1.61, + 'catalog:pos': 6, + 'catalog:rsid': 'rs6', + 'catalog:trait': 'arithomania', + 'n_catalog_matches': 2, + }, + ]); + }); + + it('gracefully handles no catalog entries in region', function () { + const { func, assoc_data } = this; + const res = func( + {}, + [assoc_data, []], + 'assoc:position', + 'catalog:pos', + 'catalog:log_pvalue', + ); + assert.deepEqual(res, assoc_data); + }); + }); + }); +}); diff --git a/test/unit/data/test_field.js b/test/unit/data/test_field.js index 64e97eb2..57f163cb 100644 --- a/test/unit/data/test_field.js +++ b/test/unit/data/test_field.js @@ -5,58 +5,53 @@ describe('Field resolver', function () { it('should correctly parse name-only field string into components', function () { const f = new Field('foo'); assert.equal(f.full_name, 'foo'); - assert.equal(f.name, 'foo'); - assert.equal(f.namespace, null); + assert.equal(f.field_name, 'foo'); assert.isArray(f.transformations); assert.equal(f.transformations.length, 0); }); + it('should correctly parse namespaced field string into components', function () { const f = new Field('foo:bar'); assert.equal(f.full_name, 'foo:bar'); - assert.equal(f.name, 'bar'); - assert.equal(f.namespace, 'foo'); + assert.equal(f.field_name, 'foo:bar'); assert.isArray(f.transformations); assert.equal(f.transformations.length, 0); }); + it('should correctly parse namespaced field string with single transformation into components', function () { const f = new Field('foo:bar|scinotation'); assert.equal(f.full_name, 'foo:bar|scinotation'); - assert.equal(f.name, 'bar'); - assert.equal(f.namespace, 'foo'); + assert.equal(f.field_name, 'foo:bar'); assert.isArray(f.transformations); assert.equal(f.transformations.length, 1); assert.isFunction(f.transformations[0]); }); + it('should correctly parse namespaced field string with multiple transformations into components', function () { const f = new Field('foo:bar|scinotation|htmlescape'); assert.equal(f.full_name, 'foo:bar|scinotation|htmlescape'); - assert.equal(f.name, 'bar'); - assert.equal(f.namespace, 'foo'); + assert.equal(f.field_name, 'foo:bar'); assert.isArray(f.transformations); assert.equal(f.transformations.length, 2); assert.isFunction(f.transformations[0]); assert.isFunction(f.transformations[1]); }); + it('should resolve a value when passed a data object', function () { const d = { 'foo:bar': 123 }; const f = new Field('foo:bar'); const v = f.resolve(d); assert.equal(v, 123); }); - it('should resolve to an unnamespaced value if its present and the explicitly namespaced value is not, and cache the value for future lookups', function () { - const d = { 'bar': 123 }; - const f = new Field('foo:bar'); - const v = f.resolve(d); - assert.equal(v, 123); - assert.equal(d['foo:bar'], 123); - }); + it('should use annotations (extra_fields) by exact field name, iff no value is present in point data', function () { - const d = { 'bar': 123, 'foo:my_annotation': 13 }; + const d = { 'foo:bar': 123, 'foo:my_annotation': 13 }; const f = new Field('my_annotation'); const v = f.resolve(d, { 'my_annotation': 12 }); assert.equal(v, 12); }); + it('should apply arbitrarily many transformations in the order defined', function () { const d = { 'foo:bar': 123 }; const f = new Field('foo:bar|neglog10|htmlescape|urlencode'); @@ -64,12 +59,14 @@ describe('Field resolver', function () { assert.equal(v, '-2.0899051114393976'); assert.equal(d['foo:bar|neglog10|htmlescape|urlencode'], '-2.0899051114393976', 'Value is cached for future lookups'); }); + it('should compose two transformations of the same type', function () { const d = { 'foo:pvalue': 10 }; const f = new Field('foo:pvalue|log10|log10'); const v = f.resolve(d); assert.equal(v, 0); }); + it('should compose two different numeric transformations left to right', function () { const d = { 'foo:pvalue': 0.5 }; const f = new Field('foo:pvalue|neglog10|log10'); diff --git a/test/unit/data/test_requester.js b/test/unit/data/test_requester.js new file mode 100644 index 00000000..a4c43f0a --- /dev/null +++ b/test/unit/data/test_requester.js @@ -0,0 +1,234 @@ +import {assert} from 'chai'; + +import Requester, {_JoinTask} from '../../../esm/data/requester'; +import {DATA_OPS} from '../../../esm/registry'; + + +describe('Requester object defines and parses requests', function () { + describe('Layout parsing', function () { + before(function () { + DATA_OPS.add('sumtwo', ( + {plot_state: { state_field = 0 }}, + [left, right], + some_param, + ) => left + right + some_param + state_field); + }); + + after(function () { + DATA_OPS.remove('sumtwo'); + }); + + beforeEach(function () { + this._all_datasources = new Map([ + ['assoc1', { name: 'assoc1', getData: () => Promise.resolve(1) }], + ['someld', { name: 'someld', getData: () => Promise.resolve(2) }], + ['intervals', { name: 'intervals', getData: () => Promise.resolve(['a', 'b', 'c', 'd']) }], + ['assoc2', { name: 'assoc2' }], + ['catalog', { name: 'catalog' }], + ]); + this._requester = new Requester(this._all_datasources); + }); + + it('builds request data from namespaces and join tasks', function () { + // Test name logic + const namespace_options = {'assoc': 'assoc1', 'ld': 'someld'}; + const data_operations = [ + { type: 'fetch', from: ['assoc', 'ld(assoc)'] }, + { + type: 'left_match', + name: 'combined', + requires: ['assoc', 'ld'], + params: ['assoc:variant', 'ld:variant'], + }, + ]; + + const [entities, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + + // Validate names of dependencies are correct + assert.deepEqual(dependencies, ['assoc', 'ld(assoc)', 'combined(assoc, ld)'], 'Dependencies are resolved in expected order'); + + // Validate that correct dependencies were wired up + assert.deepEqual([...entities.keys()], ['assoc', 'ld', 'combined']); + assert.deepEqual(entities.get('assoc').name, 'assoc1'); + assert.deepEqual(entities.get('ld').name, 'someld'); + + assert.instanceOf(entities.get('combined'), _JoinTask, 'A join task was created'); + }); + + it('provides developer friendly error messages', function () { + // Test parse errors: namespaces malformed + assert.throws(() => { + this._requester.config_to_sources({ 'not:allowed': 'whatever' }, []); + }, /Invalid namespace name: 'not:allowed'/); + + assert.throws( + () => { + this._requester.config_to_sources({ 'somenamespace': 'nowhere' }, []); + }, + /not found in DataSources/, + 'Namespace references something not registered in datasource', + ); + + // Test duplicate namespace errors: joins + assert.throws(() => { + this._requester.config_to_sources( + {}, + [ + {name: 'combined', type: 'left_match', requires: []}, + {name: 'combined', type: 'left_match', requires: []}, + ], + ); + }, /join name 'combined' must be unique/); + + assert.throws( + () => { + this._requester.config_to_sources( + {}, + [ + {name: 'combined', type: 'left_match', requires: ['unregistered', 'whatisthis']}, + ], + ); + }, + /cannot operate on unknown provider/, + ); + + }); + + it('performs joins based on layout spec', function () { + const namespace_options = {'assoc': 'assoc1', 'ld': 'someld'}; + const data_operations = [ + { type: 'fetch', from: ['assoc', 'ld(assoc)'] }, + { + type: 'sumtwo', + name: 'combined', + requires: ['assoc', 'ld'], + params: [3], // tests that params get passed, and can be whatever a join function needs + }, + ]; + + const [entities, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + + return this._requester.getData({}, entities, dependencies) + .then((res) => { + assert.equal(res, 6); // 1 + 2 + 3 + }); + }); + + it('passes a copy of plot.state to each data op, and can act on the parameters', function () { + const namespace_options = {'assoc': 'assoc1', 'ld': 'someld'}; + const data_operations = [ + { type: 'fetch', from: ['assoc', 'ld(assoc)'] }, + { + type: 'sumtwo', + name: 'combined', + requires: ['assoc', 'ld'], + params: [3], // tests that params get passed, and can be whatever a join function needs + }, + ]; + + const [entities, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + + return this._requester.getData({ state_field: 20 }, entities, dependencies) + .then((res) => { + assert.equal(res, 26); // 1 + 2 + 3 + 20 + }); + }); + + it('passes a reference to the initiator, allowing it to do things like mutate the data layer layout when data is received', function () { + const namespace_options = {'intervals': 'intervals'}; + DATA_OPS.add('layer_mutator', ({plot_state, data_layer}, [data]) => { + // This sort of operation is very special-purpose and tied to the mock layout and changes we want to see! + data_layer.layout.mock_x_categories = data; + // An operation must always return data in the end. This usage is pretty esoteric, in that it exits solely to create side effects. + return data; + }); + + const data_operations = [ + { type: 'fetch', from: ['intervals'] }, + { + type: 'layer_mutator', + name: 'combined', + requires: ['intervals'], + params: [3], + }, + ]; + + const mock_layer = { + layout: { + mock_x_categories: [], + }, + }; + const [entities, dependencies] = this._requester.config_to_sources(namespace_options, data_operations, mock_layer); + + return this._requester.getData({}, entities, dependencies) + .then((res) => { + assert.deepEqual(mock_layer.layout.mock_x_categories, res, 'In this example, mock categories exactly match returned data'); + }); + }); + + it('tries to auto-generate data_operations[@type=fetch] if not provided', function () { + const namespace_options = { assoc: 'assoc1', catalog: 'catalog', ld: 'someld' }; + let data_operations = []; // no operations, fetch or otherwise + + let [_, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + assert.deepEqual( + data_operations, + [{type: 'fetch', from: ['assoc', 'catalog', 'ld']}], // autogen doesn't specify dependencies, like ld(assoc) + 'Layout data_ops is mutated in place to reference namespaces (no dependencies assumed when auto-specifying)', + ); + + assert.deepEqual(dependencies, ['assoc', 'catalog', 'ld'], 'Dependencies are auto-guessed from namespaces'); + + // Related scenario: no fetch rule defined, but other rules are! + data_operations = [{ type: 'sumtwo', name: 'somejoin', requires: ['assoc', 'ld'], params: [5] }]; + ([_, dependencies] = this._requester.config_to_sources(namespace_options, data_operations)); + assert.deepEqual( + data_operations, + [ + { type: 'fetch', from: ['assoc', 'catalog', 'ld'] }, + { type: 'sumtwo', name: 'somejoin', requires: ['assoc', 'ld'], params: [5] }, + ], + 'Auto-generates fetch rules specifically; leaves other data ops untouched', + ); + assert.deepEqual(dependencies, ['assoc', 'catalog', 'ld', 'somejoin(assoc, ld)'], 'Dependencies are (still) auto-guessed from namespaces'); + }); + + it('attempts to reference all namespaces in data_operations[@type=fetch] at least once', function () { + const namespace_options = {'assoc': 'assoc1', 'catalog': 'catalog'}; + const data_operations = [{ type: 'fetch', from: ['assoc'] }]; // Fetch rules exist, but catalog not referenced! Eg, this could be someone creating a child layout; modifying a nested list is annoying + + const [_, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + assert.deepEqual( + data_operations, + [{type: 'fetch', from: ['assoc', 'catalog']}], + 'Layout data_ops is mutated in place to reference namespaces (no dependencies assumed when auto-specifying)', + ); + assert.deepEqual(dependencies, ['assoc', 'catalog'], 'Dependencies take all namespaces into account'); + }); + + it('autogenerates names for join operations, if none are provided', function () { + const namespace_options = { assoc: 'assoc1', catalog: 'catalog' }; + const data_operations = [ + { type: 'fetch', from: ['assoc', 'catalog'] }, + { type: 'sumtwo', name: 'has_name', requires: ['assoc', 'catalog'], params: [] }, + { type: 'sumtwo', requires: ['assoc', 'has_name'], params: [] }, + ]; + + const [_, dependencies] = this._requester.config_to_sources(namespace_options, data_operations); + assert.deepEqual( + data_operations, + [ + { type: 'fetch', from: ['assoc', 'catalog'] }, + { type: 'sumtwo', name: 'has_name', requires: ['assoc', 'catalog'], params: [] }, + { type: 'sumtwo', name: 'join0', requires: ['assoc', 'has_name'], params: [] }, + ], + 'Layout data_ops is mutated in place to give a name to any join without one', + ); + + assert.deepEqual( + dependencies, + ['assoc', 'catalog', 'has_name(assoc, catalog)', 'join0(assoc, has_name)'], + 'Dependencies reference the auto-generated join names correctly'); + }); + }); +}); diff --git a/test/unit/data/test_sources.js b/test/unit/data/test_sources.js index 37f76d1f..7dc8af39 100644 --- a/test/unit/data/test_sources.js +++ b/test/unit/data/test_sources.js @@ -15,10 +15,10 @@ describe('DataSources object', function() { const data_sources = new DataSources(); const url = 'https://pheweb.org'; data_sources - .add('assoc', ['AssociationLZ', { url, params: {}}]); + .add('assoc', ['AssociationLZ', { url }]); const source = data_sources.get('assoc'); assert.instanceOf(source, AssociationLZ); - assert.equal(url, source.url); + assert.equal(url, source._url); }); it('warns when trying to create a source of unknown type', function () { @@ -29,7 +29,7 @@ describe('DataSources object', function() { }); it('can add source instances directly', function () { - const instance = new AssociationLZ({ url: 'https://pheweb.org', params: {}}); + const instance = new AssociationLZ({ url: 'https://pheweb.org' }); const data_sources = new DataSources(); data_sources .add('assoc', instance); @@ -38,23 +38,23 @@ describe('DataSources object', function() { }); it('should allow chainable adding with a fluent API', function () { - const instance1 = new AssociationLZ({ url: 1, params: {}}); - const instance2 = new AssociationLZ({ url: 2, params: {}}); + const instance1 = new AssociationLZ({ url: 1 }); + const instance2 = new AssociationLZ({ url: 2 }); const data_sources = new DataSources(); data_sources .add('assoc', instance1) .add('assoc2', instance2); - assert.equal(data_sources.get('assoc').url, 1); - assert.equal(data_sources.get('assoc2').url, 2); + assert.equal(data_sources.get('assoc')._url, 1); + assert.equal(data_sources.get('assoc2')._url, 2); }); it('should ensure that all sources are aware of their namespace', function () { const data_sources = new DataSources(); - const instance = new AssociationLZ({ url: 1, params: {}}); + const instance = new AssociationLZ({ url: 1 }); data_sources - .add('assoc', ['AssociationLZ', { url: 1, params: {}}]) + .add('assoc', ['AssociationLZ', { url: 1 }]) .add('assoc2', instance); assert.equal(data_sources.get('assoc').source_id, 'assoc'); diff --git a/test/unit/data/undercomplicate/test_adapters.js b/test/unit/data/undercomplicate/test_adapters.js new file mode 100644 index 00000000..f45c8d4d --- /dev/null +++ b/test/unit/data/undercomplicate/test_adapters.js @@ -0,0 +1,170 @@ +import {assert} from 'chai'; + +import {BaseAdapter, BaseUrlAdapter} from '../../../../esm/data/undercomplicate'; + + +class TestCacheQuirks extends BaseAdapter { + _getCacheKey(options) { + return options.somevalue; + } + + _performRequest(options) { + // Return an object (not a string!) so that cache returns something at risk of being mutated + return Promise.resolve([{ a: 1, b:2, c:3 }]); + } + + _normalizeResponse(records, options) { + // No parsing required + return records; + } + + _annotateRecords(records, options) { + // Mutate the returned object, to confirm it doesn't mutate the contents of cache by shared reference + records.forEach((row) => row.a += 1); + return records; + } +} + +class TestAdapter extends BaseAdapter { + _buildRequestOptions(options, dependent_data) { + const somevalue = (dependent_data ? dependent_data.length : options.somevalue); + return { somevalue }; + } + + _getCacheKey(options) { + return options.somevalue; + } + + _performRequest(options) { + return Promise.resolve('line1\tcol2\nline2\tcol2'); + } + + _normalizeResponse(response_text, options) { + return response_text.split('\n') + .map((row) => { + const [a, b] = row.split('\t'); + return {a, b}; + }); + } + + _annotateRecords(records, options) { + records.forEach((row) => row.c = true); + return records; + } + + _postProcessResponse(records, options) { + return records.map((record) => { + return Object.keys(record).reduce((acc, akey) => { + acc[`prefix.${akey}`] = record[akey]; + return acc; + }, {}); + }); + } +} + + +describe('BaseAdapter', function () { + it('performs a sequence of operations on retrieved data', function () { + const source = new TestAdapter(); + return source.getData() + .then((result) => { + assert.deepEqual(result, [ + {'prefix.a': 'line1', 'prefix.b': 'col2', 'prefix.c': true}, + {'prefix.a': 'line2', 'prefix.b':'col2', 'prefix.c': true}, + ]); + }); + }); + + it('can consider dependent data when performing request', function () { + const source = new TestAdapter(); + const base_options = {somevalue: 12}; + + // First trigger a request that leaves behind a trace of the default options + return source.getData(base_options) + .then((result) => { + assert.ok(source._cache.has(12), 'Uses a cache value as given'); + + // Then trigger a request that leaves behind a trace of using dependent data + return source.getData(base_options, [1, 2, 3]); + }).then((result) => { + assert.ok(source._cache.has(3), 'Uses a cache value calculated from dependent data'); + }); + }); + + it('uses a cache with configurable size', function () { + const source = new TestAdapter({cache_size: 2}); + const requests = [1, 2, 3].map((item) => source.getData({somevalue: item})); + return Promise.all(requests).then(() => { + assert.equal(source._cache._cur_size, 2); + }); + }); + + it('intelligently clones non-string cache entries', function () { + const source = new TestCacheQuirks(); + return source.getData({ somevalue: 1 }) + .then((result) => { + assert.deepEqual(result, [{ a: 2, b:2, c:3 }], 'First cache check returns correct result'); + return source.getData({ somevalue: 1 }); + }) + .then((result) => assert.deepEqual(result, [{ a: 2, b:2, c:3 }], 'Second cache check returns correct result')); + }); + + it('does not mangle string values in cache', function () { + const expected = 'Some string value'; + + class TestStringCache extends BaseAdapter { + _getCacheKey(options) { + return options.somevalue; + } + + _performRequest(options) { + return Promise.resolve(expected); + } + } + + const source = new TestStringCache(); + return source.getData({ somevalue: 1 }) + .then((result) => { + assert.deepEqual(result, expected, 'First value is returned and second cache'); + return source.getData({ somevalue: 1 }); + }) + .then((result) => assert.deepEqual(result, expected, 'Second request returns cache hit, not mangled by cloning process')); + }); + + it('unsets a cached promise if the promise rejects', function () { + let some_counter = 0; + + class TestCacheRejection extends BaseAdapter { + _getCacheKey(options) { + return 'always_same_key'; + } + + _performRequest(options) { + // If we were feeding (failed) response from cache, then every new request would have the same counter value + some_counter += 1; + return Promise.reject(some_counter); + } + } + + const source = new TestCacheRejection(); + return source.getData({}) + .catch((value_from_error) => { + assert.equal(value_from_error, 1, 'First request is counted as 1'); + return source.getData({}); + }).catch((value_from_error) => { + assert.equal(value_from_error, 2, 'Second request is counted as 2 because rejections are removed from cache'); + }); + }); +}); + + + +describe('BaseURLAdapter', function () { + it('Requests throw an error when a URL is not provided', function () { + const source = new BaseUrlAdapter({}); + assert.throws( + () => source._performRequest({}), + /must specify a resource URL/, + ); + }); +}); diff --git a/test/unit/data/undercomplicate/test_cache.js b/test/unit/data/undercomplicate/test_cache.js new file mode 100644 index 00000000..ed6df70c --- /dev/null +++ b/test/unit/data/undercomplicate/test_cache.js @@ -0,0 +1,83 @@ +import {assert} from 'chai'; + +import {LRUCache} from '../../../../esm/data/undercomplicate'; + +describe('LRU cache', function () { + it('restricts max size by evicting old items', function () { + const cache = new LRUCache(3); + ['a', 'b', 'c', 'd', 'e'].forEach((item, index) => cache.add(item, index)); + + assert.equal(cache._cur_size, 3, 'Wrong number of cache entries'); + assert.sameOrderedMembers([...cache._store.keys()], ['c', 'd', 'e'], 'Incorrect cache members'); + }); + + it('does not cache if max size is 0', function () { + const cache = new LRUCache(0); + ['a', 'b', 'c', 'd', 'e'].forEach((item, index) => cache.add(item, index)); + + assert.equal(cache._cur_size, 0, 'No items cached'); + assert.isNull(cache._head, 'No head node'); + assert.isNull(cache._tail, 'No tail node'); + }); + + it('does not support "negative number for infinite cache"', function () { + assert.throws( + () => new LRUCache(-12), + /must be >= 0/, + ); + }); + + it('promotes cache entries by most recently read', function () { + const cache = new LRUCache(3); + ['a', 'b', 'c', 'a'].forEach((item, index) => cache.add(item, index)); + + assert.equal(cache._cur_size, 3, 'Wrong number of cache entries'); + assert.equal(cache._head.key, 'a', 'Last item accessed is at head'); + assert.equal(cache._tail.key, 'b', 'LRU is at tail'); + + cache.get('b'); + assert.equal(cache._head.key, 'b', 'Accessing another item updates head'); + + cache.get('nothing'); + assert.equal(cache._head.key, 'b', 'Uncached values will not affect the LRU order'); + }); + + it('can remove an item by key name', function () { + const cache = new LRUCache(3); + cache.add('some_key', 12); + + let result = cache.remove('some_key'); + assert.ok(result, 'Removing a known item returns true'); + assert.equal(cache._cur_size, 0, 'Item removed from cache'); + + result = cache.remove('never_there'); + assert.notOk(result, 'Removing unknown item returns false'); + assert.equal(cache._cur_size, 0, 'Cache still has zero items'); + + }); + + it('stores metadata along with cache entries', function () { + const cache = new LRUCache(3); + + const meta = {chr: '1', start: 1, end: 100}; + cache.add('something', 12, meta); + + assert.deepEqual(cache._head.metadata, meta); + }); + + it('can search for an item', function () { + const cache = new LRUCache(3); + + cache.add('akey', 12, {chr: '2', start: 15, end: 30}); + cache.add('bkey', 18, {chr: '1', start: 10, end: 20}); + + let found = cache.find((node) => node.value < 10); + assert.equal(found, null, 'Return null when no match found'); + + found = cache.find((node) => node.value > 10); + assert.equal(found.key, 'bkey', 'Return the first match (ordered by most newest cache entry)'); + + found = cache.find(({ metadata}) => metadata.chr === '2' && 16 >= metadata.start && 18 <= metadata.end); + assert.deepEqual(found.key, 'akey', 'A more interesting example: region overlap tested via metadata'); + }); +}); diff --git a/test/unit/data/undercomplicate/test_joins.js b/test/unit/data/undercomplicate/test_joins.js new file mode 100644 index 00000000..bff59d3d --- /dev/null +++ b/test/unit/data/undercomplicate/test_joins.js @@ -0,0 +1,57 @@ +import {assert} from 'chai'; + +import {left_match, inner_match, full_outer_match} from '../../../../esm/data/undercomplicate/joins'; + + +describe('Data Join Helpers', function() { + beforeEach(function () { + this.left_data = [ + { gene_id: 'ENSG00000148737', pval: .05 }, + { gene_id: 'ENSG00000012048', pval: .0005 }, // not on right + ]; + + this.right_data = [ + { gene_id: 'ENSG00000148737', catalog: true }, // 2 matches for 1 item on left + { gene_id: 'ENSG00000148737', catalog: false }, // ' + { gene_id: 'ENSG00000128731', catalog: true }, // Not on left + ]; + }); + + describe('left join helper', function () { + it('takes all records on left, merged with 1 or more records on right', function () { + const expected = [ + { gene_id: 'ENSG00000148737', pval: .05, catalog: true }, + { gene_id: 'ENSG00000148737', pval: .05, catalog: false }, + { gene_id: 'ENSG00000012048', pval: .0005 }, + ]; + + const actual = left_match(this.left_data, this.right_data, 'gene_id', 'gene_id'); + assert.deepEqual(actual, expected); + }); + }); + + describe('inner join helper', function () { + it('takes only records with matches on both left and right', function () { + const expected = [ + { gene_id: 'ENSG00000148737', pval: .05, catalog: true }, + { gene_id: 'ENSG00000148737', pval: .05, catalog: false }, + ]; + const actual = inner_match(this.left_data, this.right_data, 'gene_id', 'gene_id'); + assert.deepEqual(actual, expected); + }); + }); + + describe('full outer join helper', function () { + it('takes all records, matching them where suitable', function () { + const expected = [ + { gene_id: 'ENSG00000148737', pval: .05, catalog: true }, + { gene_id: 'ENSG00000148737', pval: .05, catalog: false }, + { gene_id: 'ENSG00000012048', pval: .0005 }, + { gene_id: 'ENSG00000128731', catalog: true }, + ]; + + const actual = full_outer_match(this.left_data, this.right_data, 'gene_id', 'gene_id'); + assert.deepEqual(actual, expected); + }); + }); +}); diff --git a/test/unit/data/undercomplicate/test_requests.js b/test/unit/data/undercomplicate/test_requests.js new file mode 100644 index 00000000..e817e015 --- /dev/null +++ b/test/unit/data/undercomplicate/test_requests.js @@ -0,0 +1,79 @@ +import {assert} from 'chai'; + +import {_parse_declaration, getLinkedData} from '../../../../esm/data/undercomplicate/requests'; + + +class SequenceFixture { + getData(options, ...prior) { + return prior.reduce((acc, val) => (acc += val), 1); + } +} + +describe('Request helpers', function () { + describe('Dependency parsing syntax', function () { + it('parses requests with and without dependencies', function () { + let result = _parse_declaration('record'); + assert.deepEqual(result, ['record', []]); + + result = _parse_declaration('record(a)'); + assert.deepEqual(result, ['record', ['a']]); + + result = _parse_declaration('record(a, b)'); + assert.deepEqual(result, ['record', ['a', 'b']]); + + result = _parse_declaration('record_12(a, a1)'); + assert.deepEqual(result, ['record_12', ['a', 'a1']]); + }); + + it('rejects invalid syntax', function () { + assert.throws(() => _parse_declaration('dependency.name'), /Unable to parse/); + + assert.throws(() => _parse_declaration('one_dep another_thing'), /Unable to parse/); + }); + }); + + describe('getLinkedData', function () { + it('chains requests together while respecting dependencies', function () { + const entities = new Map(); + const dependencies = ['a', 'b(a)', 'c(a,b)', 'd(c)']; + const shared_state = new SequenceFixture(); + ['a', 'b', 'c', 'd'] + .forEach((key) => entities.set(key, shared_state)); + + // The last result in the chain, by itself, represents a sum of all prior + return getLinkedData({}, entities, dependencies) + .then((result) => assert.equal(result, 5)); + }); + + it('chains requests and can return all values', function () { + const entities = new Map(); + const dependencies = ['a', 'b(a)', 'c(a,b)', 'd(c)']; + const shared_state = new SequenceFixture(); + ['a', 'b', 'c', 'd'] + .forEach((key) => entities.set(key, shared_state)); + + // The last result in the chain, by itself, represents a sum of all prior + return getLinkedData({}, entities, dependencies, false) + .then((result) => assert.deepEqual(result, [1, 2, 4, 5])); + }); + + it('warns if spec references a non-existent provider', function () { + assert.throws( + () => getLinkedData({}, new Map(), ['a']), + /no matching source was provided/, + ); + }); + + it('warns if circular dependencies were declared', function () { + assert.throws( + () => getLinkedData({}, new Map(), ['a(b)', 'b(a)']), + /circular dependency/, + ); + + assert.throws( + () => getLinkedData({}, new Map(), ['a(a)']), + /circular dependency/, + ); + }); + }); +}); diff --git a/test/unit/ext/lz-parsers/gwas/test_parsers.js b/test/unit/ext/lz-parsers/gwas/test_parsers.js new file mode 100644 index 00000000..70f41481 --- /dev/null +++ b/test/unit/ext/lz-parsers/gwas/test_parsers.js @@ -0,0 +1,139 @@ +import { assert } from 'chai'; +import { makeGWASParser } from '../../../../../esm/ext/lz-parsers/gwas/parsers'; + + +describe('GWAS parsing', () => { + describe('Mode selection', () => { + it.skip('Warns if no marker could be identified', () => {}); + }); + + describe('Handles sample data correctly', () => { + it.skip('parses EPACTS data', () => { + // FIXME: Alan notes edge cases that may not be handled yet: + // -when *PVALUE = 0*, it always indicates a variant is very significant (such that it + // underflows R's precision limit), and *should be plotted* + // -when *PVALUE = NA*, it indicates that no test was run for that variant because there + // were too few copies of the alt allele in the sample, and running the test is a waste + // of time since it will never be significant. *These can be safely skipped.*" + }); + + it('parses SAIGE data', () => { + const saige_sample = 'chr1\t76792\tchr1:76792:A:C\tA\tC\t57\t0.00168639048933983\t16900\t0.573681678183941\t0.663806747906141\t1.30193005902619\t0.387461577915637\t0.387461577915637\t1\t2.2694293866027\t2.41152256615949'; + const parser = makeGWASParser({ marker_col: 3, pvalue_col: 12, is_neg_log_pvalue: false }); + const actual = parser(saige_sample); + assert.deepEqual(actual, { + alt_allele: 'C', + chromosome: '1', + log_pvalue: 0.41177135722616476, + position: 76792, + ref_allele: 'A', + variant: '1:76792_A/C', + rsid: null, + beta: null, + stderr_beta: null, + alt_allele_freq: null, + }); + }); + + it('parses RVTESTS data', () => { + const rvtests_sample = '1\t761893\tG\tT\t19292\t2.59624e-05:0.000655308:0\t1:1:0\t0.998289:0.996068:0.998381\t1:1:1\t19258:759:18499\t1:1:0\t0:0:0\t1.33113\t0.268484\t18.4664\t7.12493e-07'; + const parser = makeGWASParser({ + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 16, + is_neg_log_pvalue: false, + alt_allele_freq: null, + }); + const actual = parser(rvtests_sample); + assert.deepEqual(actual, { + alt_allele: 'T', + chromosome: '1', + log_pvalue: 6.147219398093217, + position: 761893, + ref_allele: 'G', + variant: '1:761893_G/T', + rsid: null, + beta: null, + stderr_beta: null, + alt_allele_freq: null, + }); + }); + + it('parses beta and stderr where appropriate', () => { + const line = 'X:12_A/T\t0.1\t0.5\t0.6'; + const parser = makeGWASParser({ + marker_col: 1, + pvalue_col: 2, + beta_col: 3, + stderr_beta_col: 4, + }); + const actual = parser(line); + + assert.deepEqual(actual, { + chromosome: 'X', + position: 12, + ref_allele: 'A', + alt_allele: 'T', + variant: 'X:12_A/T', + rsid: null, + log_pvalue: 1, + beta: 0.5, + stderr_beta: 0.6, + alt_allele_freq: null, + }); + // Also handles missing data for beta + const line2 = 'X:12_A/T\t0.1\t.\t.'; + const actual2 = parser(line2); + assert.equal(actual2.beta, null); + assert.equal(actual2.stderr_beta, null); + }); + + it('ensures that ref and alt are uppercase', () => { + const line = 'X:12\ta\tNA\t0.1'; + const parser = makeGWASParser({ + marker_col: 1, + ref_col: 2, + alt_col: 3, + pvalue_col: 4, + }); + const actual = parser(line); + + assert.deepEqual(actual, { + chromosome: 'X', + position: 12, + ref_allele: 'A', + alt_allele: null, + variant: 'X:12', + rsid: null, + log_pvalue: 1, + beta: null, + stderr_beta: null, + alt_allele_freq: null, + }); + }); + + it('handles rsid in various formats', () => { + const parser = makeGWASParser({ + marker_col: 1, + ref_col: 2, + alt_col: 3, + pvalue_col: 4, + rsid_col: 5, + }); + + const scenarios = [ + ['.', null], + ['14', 'rs14'], + ['RS14', 'rs14'], + ]; + const line = 'X:12\ta\tNA\t0.1\t'; + + scenarios.forEach(([raw, parsed]) => { + const actual = parser(line + raw); + assert.equal(actual.rsid, parsed); + }); + }); + }); +}); diff --git a/test/unit/ext/lz-parsers/gwas/test_sniffers.js b/test/unit/ext/lz-parsers/gwas/test_sniffers.js new file mode 100644 index 00000000..3150740a --- /dev/null +++ b/test/unit/ext/lz-parsers/gwas/test_sniffers.js @@ -0,0 +1,357 @@ +import { assert } from 'chai'; +import { _isHeader, _findColumn, _getPvalColumn, _levenshtein, guessGWAS } from '../../../../../esm/ext/lz-parsers/gwas/sniffers'; + + +describe('Automatic header detection', () => { + it('Correctly identifies various header rules', () => { + assert.isOk(_isHeader('#Comment'), 'Comment lines are headers!'); + assert.isOk(_isHeader('Header\tLabels'), 'Headers tend to be text'); + assert.isNotOk(_isHeader('X\t100'), 'Data has numbers'); + assert.isNotOk(_isHeader('X\t.'), 'Missing data is still data'); + assert.isNotOk(_isHeader('X,100', { delimiter: ',' }), 'Handles data as csv'); + assert.isOk(_isHeader('//100', { comment_char: '//' }), 'Handles different comments'); + }); +}); + + +describe('Levenshtein distance metric', () => { + it('Computes levenshtein distance for sample strings', () => { + const scenarios = [ + ['bob', 'bob', 0], + ['bob', 'bib', 1], + ['alice', 'bob', 5], + ['pvalue', 'p.value', 1], + ['p.value', 'pvalue', 1], + ['pvalue', 'log_pvalue', 4], + ]; + scenarios.forEach((s) => { + const [a, b, score] = s; + const val = _levenshtein(a, b); + assert.equal(score, val, `Incorrect match score for ${a}, ${b}`); + }); + }); +}); + +describe('_findColumn can fuzzy match column names', () => { + const pval_names = ['pvalue', 'p.value', 'pval', 'p_score']; + + it('finds the first header that exactly matches a synonym', () => { + const headers = ['chr', 'pos', 'p.value', 'marker']; + const match = _findColumn(pval_names, headers); + assert.equal(match, 2); + }); + + it('chooses the first exact match when more than one is present', () => { + const headers = ['chr', 'pvalue', 'p.value', 'marker']; + const match = _findColumn(pval_names, headers); + assert.equal(match, 1); + }); + + it('prefers exact matches over fuzzy matches', () => { + const headers = ['chr1', 'pos1', 'pvalues', 'p.value', '1marker']; + const match = _findColumn(pval_names, headers); + assert.equal(match, 3); + }); + + it('finds the first header that closely matches a synonym', () => { + const headers = ['chr', 'pos', 'marker', 'p-value']; + const match = _findColumn(pval_names, headers); + assert.equal(match, 3); + }); + + it('returns null if no good match can be found', () => { + const headers = ['chr', 'pos', 'marker', 'pval_score']; + const match = _findColumn(pval_names, headers); + assert.equal(match, null); + }); + + it('will match based on a configurable threshold', () => { + const headers = ['chr', 'marker', 'pval_score']; + const match = _findColumn(pval_names, headers, 3); + assert.equal(match, 2); + }); + + it('skips headers with a null value', () => { + const headers = ['chr', null, 'marker', 'pval']; + const match = _findColumn(pval_names, headers); + assert.equal(match, 3); + }); +}); + +describe('getPvalColumn', () => { + it('finds logp before p', () => { + const headers = ['logpvalue', 'pval']; + const data_rows = [[0.5, 0.5]]; + + const actual = _getPvalColumn(headers, data_rows); + assert.deepEqual(actual, { pvalue_col: 1, is_neg_log_pvalue: true }); + }); + + it('checks that pvalues are in a realistic range 0..1', () => { + const headers = ['pval']; + const data_rows = [[100]]; + + const actual = _getPvalColumn(headers, data_rows); + assert.deepEqual(actual, null); + }); +}); + +describe('guessGWAS format detection', () => { + it('Returns null if columns could not be identified', () => { + const headers = ['rsid', 'pval']; + const data = [['rs1234', 0.5]]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, null); + }); + + it('handles zorp standard format', () => { + const headers = ['#chrom', 'pos', 'ref', 'alt', 'neg_log_pvalue', 'beta', 'stderr_beta']; + const data = [['1', '762320', 'C', 'T', '0.36947042857317597', '0.5', '0.1']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, { + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 5, + is_neg_log_pvalue: true, + beta_col: 6, + stderr_beta_col: 7, + }); + }); + + it('handles gwas catalog (mostly)', function () { + const headers = ['chromosome', 'base_pair_location', 'effect_allele', 'other_allele', 'odds_ratio', 'ci_lower', 'ci_upper', 'standard_error', 'p_value']; + const data = [['1', '1108138', 'A', 'G', '1.081', '0.8822', '1.325', '0.1038', '0.4517']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, { + // Note: GWAS catalog format uses ambiguous "effect" semantics, so we don't try to capture ref and alt + chrom_col: 1, + pos_col: 2, + pvalue_col: 9, + is_neg_log_pvalue: false, + stderr_beta_col: 8, + }); + }); + + it('handles BOLT-LMM', () => { + // https://data.broadinstitute.org/alkesgroup/BOLT-LMM/#x1-450008.1 + // This sample drawn from: + // ftp://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/ZhuZ_30940143_GCST007609 + // TODO: The official format spec may use other pvalue col names; add tests for that + const headers = ['SNP', 'CHR', 'BP', 'A1', 'A0', 'MAF', 'HWEP', 'INFO', 'BETA', 'SE', 'P']; + const data = [['10:48698435_A_G', '10', '48698435', 'A', 'G', '0.01353', '0.02719', '0.960443', '0.0959329', '0.0941266', '3.3E-01']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, { + marker_col: 1, + pvalue_col: 11, + is_neg_log_pvalue: false, + beta_col: 9, + stderr_beta_col: 10, + }); + }); + + it('handles EPACTS', () => { + // https://genome.sph.umich.edu/wiki/EPACTS#Output_Text_of_All_Test_Statistics + const headers = ['#CHROM', 'BEGIN', 'END', 'MARKER_ID', 'NS', 'AC', 'CALLRATE', 'MAF', 'PVALUE', 'SCORE', 'N.CASE', 'N.CTRL', 'AF.CASE', 'AF.CTRL']; + const data = [['20', '1610894', '1610894', '20:1610894_G/A_Synonymous:SIRPG', '266', '138.64', '1', '0.26061', '6.9939e-05', '3.9765', '145', '121', '0.65177', '0.36476']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, { marker_col: 4, pvalue_col: 9, is_neg_log_pvalue: false }); + }); + + it('handles EMMAX-EPACTS', () => { + // Sample from a file that used multiple tools + const headers = ['#CHROM', 'BEG', 'END', 'MARKER_ID', 'NS', 'AC', 'CALLRATE', 'GENOCNT', 'MAF', 'STAT', 'PVALUE', 'BETA', 'SEBETA', 'R2']; + const data = [['1', '762320', '762320', '1:762320_C/T_rs75333668', '3805', '100.00', '1.00000', '3707/96/2', '0.01314', '0.7942', '0.4271', '0.08034', '0.1012', '0.0001658']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual(actual, { + marker_col: 4, + pvalue_col: 11, + is_neg_log_pvalue: false, + beta_col: 12, + stderr_beta_col: 13, + }); + }); + + it('handles METAL', () => { + const headers = ['#CHROM', 'POS', 'REF', 'ALT', 'N', 'POOLED_ALT_AF', 'DIRECTION_BY_STUDY', 'EFFECT_SIZE', 'EFFECT_SIZE_SD', 'H2', 'PVALUE']; + const data = [['1', '10177', 'A', 'AC', '491984', '0.00511094', '?-????????????????-????+???????????????????????????????????????????????????????????????????-????????????????????????????????????????????????????????????????????????????????', '-0.0257947', '0.028959', '1.61266e-06', '0.373073']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 11, + is_neg_log_pvalue: false, + beta_col: 8, + stderr_beta_col: 9, + }, + ); + }); + + it('handles PLINK', () => { + // Format: https://www.cog-genomics.org/plink2/formats + // Sample: https://github.com/babelomics/babelomics/wiki/plink.assoc + // h/t Josh Weinstock + const headers = ['CHR', 'SNP', 'BP', 'A1', 'F_A', 'F_U', 'A2', 'CHISQ', 'P']; + const data = [['1', 'rs3094315', '742429', 'C', '0.1509', '0.1394', 'T', '0.0759', '0.782', '1.097']]; + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 3, + ref_col: 4, + alt_col: 7, + pvalue_col: 9, + is_neg_log_pvalue: false, + }, + ); + }); + + it('handles RAREMETAL', () => { + const headers = ['#CHROM', 'POS', 'REF', 'ALT', 'N', 'POOLED_ALT_AF', 'DIRECTION_BY_STUDY', 'EFFECT_SIZE', 'EFFECT_SIZE_SD', 'H2', 'PVALUE']; + const data = [['1', '10177', 'A', 'AC', '491984', '0.00511094', '?-????????????????-????+???????????????????????????????????????????????????????????????????-????????????????????????????????????????????????????????????????????????????????', '-0.0257947', '0.028959', '1.61266e-06', '0.373073']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 11, + is_neg_log_pvalue: false, + beta_col: 8, + stderr_beta_col: 9, + }, + ); + }); + + it('handles RAREMETALWORKER', () => { + const headers = ['#CHROM', 'POS', 'REF', 'ALT', 'N_INFORMATIVE', 'FOUNDER_AF', 'ALL_AF', 'INFORMATIVE_ALT_AC', 'CALL_RATE', 'HWE_PVALUE', 'N_REF', 'N_HET', 'N_ALT', 'U_STAT', 'SQRT_V_STAT', 'ALT_EFFSIZE', 'PVALUE']; + const data = [['9', '400066155', 'T', 'C', '432', '0', '0', '0', '1', '1', '432', '0', '0', 'NA', 'NA', 'NA', 'NA']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 17, + is_neg_log_pvalue: false, + beta_col: 16, + }, + ); + }); + + it('handles RVTESTS', () => { + // Courtesy of xyyin and gzajac + const headers = ['CHROM', 'POS', 'REF', 'ALT', 'N_INFORMATIVE', 'AF', 'INFORMATIVE_ALT_AC', 'CALL_RATE', 'HWE_PVALUE', 'N_REF', 'N_HET', 'N_ALT', 'U_STAT', 'SQRT_V_STAT', 'ALT_EFFSIZE', 'PVALUE']; + const data = [['1', '761893', 'G', 'T', '19292', '2.59624e-05:0.000655308:0', '1:1:0', '0.998289:0.996068:0.998381', '1:1:1', '19258:759:18499', '1:1:0', '0:0:0', '1.33113', '0.268484', '18.4664', '7.12493e-07']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 2, + ref_col: 3, + alt_col: 4, + pvalue_col: 16, + is_neg_log_pvalue: false, + beta_col: 15, + }, + ); + }); + + it('handles SAIGE', () => { + // https://github.com/weizhouUMICH/SAIGE/wiki/SAIGE-Hands-On-Practical + const headers = ['CHR', 'POS', 'SNPID', 'Allele1', 'Allele2', 'AC_Allele2', 'AF_Allele2', 'N', 'BETA', 'SE', 'Tstat', 'p.value', 'p.value.NA', 'Is.SPA.converge', 'varT', 'varTstar']; + const data = [['chr1', '76792', 'chr1:76792:A:C', 'A', 'C', '57', '0.00168639048933983', '16900', '0.573681678183941', '0.663806747906141', '1.30193005902619', '0.387461577915637', '0.387461577915637', '1', '2.2694293866027', '2.41152256615949']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + marker_col: 3, + pvalue_col: 12, + is_neg_log_pvalue: false, + beta_col: 9, + stderr_beta_col: 10, + }, + ); + }); + + it('parses a mystery format', () => { + // TODO: Identify the program used and make test more explicit + // FIXME: This test underscores difficulty of reliable ref/alt detection- a1 comes + // before a0, but it might be more valid to switch the order of these columns + const headers = ['chr', 'rs', 'ps', 'n_mis', 'n_obs', 'allele1', 'allele0', 'af', 'beta', 'se', 'p_score']; + const data = [['1', 'rs75333668', '762320', '0', '3610', 'T', 'C', '0.013', '-5.667138e-02', '1.027936e-01', '5.814536e-01']]; + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 1, + pos_col: 3, + ref_col: 6, + alt_col: 7, + pvalue_col: 11, + is_neg_log_pvalue: false, + beta_col: 9, + stderr_beta_col: 10, + }, + ); + }); + + it('handles output of AlisaM pipeline', () => { + const headers = ['MarkerName', 'chr', 'pos', 'ref', 'alt', 'minor.allele', 'maf', 'mac', 'n', 'pvalue', 'SNPID', 'BETA', 'SE', 'ALTFreq', 'SNPMarker']; + const data = [['chr1-281876-AC-A', 'chr1', '281876', 'AC', 'A', 'alt', '0.231428578495979', '1053', '2275', '0.447865946615285', 'rs72502741', '-0.0872936159370696', '0.115014743551501', '0.231428578495979', 'chr1:281876_AC/A']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + chrom_col: 2, + pos_col: 3, + ref_col: 4, + alt_col: 5, + pvalue_col: 10, + is_neg_log_pvalue: false, + beta_col: 12, + stderr_beta_col: 13, + }, + ); + }); + + it('handles whatever diagram was using', () => { + const headers = ['Chr:Position', 'Allele1', 'Allele2', 'Effect', 'StdErr', 'P-value', 'TotalSampleSize']; + const data = [['5:29439275', 'T', 'C', '-0.0003', '0.015', '0.99', '111309']]; + + const actual = guessGWAS(headers, data); + assert.deepEqual( + actual, + { + marker_col: 1, + pvalue_col: 6, + is_neg_log_pvalue: false, + beta_col: 4, + stderr_beta_col: 5, + }, + ); + }); +}); diff --git a/test/unit/ext/lz-parsers/test_bed.js b/test/unit/ext/lz-parsers/test_bed.js new file mode 100644 index 00000000..109162fc --- /dev/null +++ b/test/unit/ext/lz-parsers/test_bed.js @@ -0,0 +1,83 @@ +import { assert } from 'chai'; + +import {makeBed12Parser} from '../../../../esm/ext/lz-parsers/bed'; + + +describe('UCSC-style BED parser', function () { + beforeEach(function () { + this.lines = `chr7 127471196 127472363 Pos1 0 + 127471196 127472363 255,0,0 +chr7 127472363 127473530 Pos2 0 + 127472363 127473530 255,0,0 +chr7 127473530 127474697 Pos3 0 + 127473530 127474697 255,0,0 +chr7 127474697 127475864 Pos4 0 + 127474697 127475864 255,0,0 +chr7 127475864 127477031 Neg1 0 - 127475864 127477031 0,0,255 +chr7 127477031 127478198 Neg2 0 - 127477031 127478198 0,0,255 +chr7 127478198 127479365 Neg3 0 - 127478198 127479365 0,0,255 +chr7 127479365 127480532 Pos5 0 + 127479365 127480532 255,0,0 +chr7 127480532 127481699 Neg4 0 - 127480532 127481699 0,0,255`.split('\n'); + }); + + it('defaults to normalizing the parsed data to match expectations', function () { + const parser = makeBed12Parser({normalize: true}); + const result = parser(this.lines[0]); + const expected = { + 'blockCount': null, + 'blockSizes': null, + 'blockStarts': null, + 'chrom': '7', + 'chromEnd': 127472363, + 'chromStart': 127471197, + 'itemRgb': '255,0,0', + 'name': 'Pos1', + 'score': 0, + 'strand': '+', + 'thickEnd': 127472363, + 'thickStart': 127471196, + }; + assert.deepEqual(result, expected, 'Fields are populated in data object with the expected types'); + }); + + it('warns if required fields are missing', function () { + const parser = makeBed12Parser({normalize: true}); + assert.throws(() => parser('chr12\t51'), /must provide all required/); + }); + + it('returns raw file contents if normalize = false', function () { + const parser = makeBed12Parser({normalize: false}); + const result = parser(this.lines[0]); + const expected = { + 'blockCount': undefined, + 'blockSizes': undefined, + 'blockStarts': undefined, + 'chrom': 'chr7', + 'chromEnd': '127472363', + 'chromStart': '127471196', + 'itemRgb': '255,0,0', + 'name': 'Pos1', + 'score': '0', + 'strand': '+', + 'thickEnd': '127472363', + 'thickStart': '127471196', + }; + assert.deepEqual(result, expected, 'All fields are populated in data object'); + }); + + it('handles additional optional BED fields if they are present', function () { + const parser = makeBed12Parser({normalize: true}); + // The trailing comma in a list-field is part of the UCSC BED examples; weird, but make sure that we handle it! + const a_line = `chr7 127472363 127473530 Pos2 0 + 127472363 127473530 255,0,0 2 567,488, 0,3512`; + const result = parser(a_line); + const extra_expected = { + 'blockCount': 2, + 'blockSizes': [567, 488], + 'blockStarts': [1, 3513], + }; + assert.deepInclude(result, extra_expected, 'Optional fields are parsed and processed correctly'); + }); + + it('performs basic validation of block information', function () { + const parser = makeBed12Parser({normalize: true}); + // Here, blockSizes has 3 items, but blockCounts calls for 2 + const a_line = `chr7 127472363 127473530 Pos2 0 + 127472363 127473530 255,0,0 2 567,488,999 0,3512`; + assert.throws(() => parser(a_line), /same number of items/); + }); +}); diff --git a/test/unit/ext/lz-parsers/test_parser_utils.js b/test/unit/ext/lz-parsers/test_parser_utils.js new file mode 100644 index 00000000..97018fed --- /dev/null +++ b/test/unit/ext/lz-parsers/test_parser_utils.js @@ -0,0 +1,62 @@ +import { assert } from 'chai'; +import { _missingToNull, parseAlleleFrequency, parsePvalToLog } from '../../../../esm/ext/lz-parsers/utils'; + + +describe('missingToNull', () => { + it('converts a range of missing values to null values', () => { + // Every other one should get converted + const values = [0, null, 5, 'n/a', 'bob', '-NaN']; + const result = _missingToNull(values); + assert.deepStrictEqual(result, [0, null, 5, null, 'bob', null]); + }); +}); + +describe('parsePvalToLog', () => { + it('sidesteps language underflow', () => { + const val = '1.93e-780'; + const res = parsePvalToLog(val, false); + assert.equal(res, 779.7144426909922, 'Handled value that would otherwise have underflowed'); + }); + + it('handles underflow that occurred in the source data', () => { + let val = '0'; + let res = parsePvalToLog(val); + assert.equal(res, Infinity, 'Provides a placeholder when the input data underflowed'); + + val = '0.0'; + res = parsePvalToLog(val); + assert.equal(res, Infinity, 'Provides a placeholder when the input data underflowed (slow path)'); + }); +}); + +describe('parseAlleleFrequency', () => { + it('returns freq given frequency', () => { + const res = parseAlleleFrequency({ freq: '0.25', is_alt_effect: true }); + assert.equal(res, 0.25); + }); + + it('returns freq given frequency, and orients to alt', () => { + const res = parseAlleleFrequency({ freq: '0.25', is_alt_effect: false }); + assert.equal(res, 0.75); + }); + + it('handles missing data', () => { + const res = parseAlleleFrequency({ freq: 'NA', is_alt_effect: true }); + assert.equal(res, null); + }); + + it('calculates freq from counts', () => { + const res = parseAlleleFrequency({ allele_count: '25', n_samples: '100' }); + assert.equal(res, 0.125); + }); + + it('calculates freq from counts, and orients to alt', () => { + const res = parseAlleleFrequency({ allele_count: '75', n_samples: '100', is_alt_effect: false }); + assert.equal(res, 0.625); + }); + + it('handles missing data when working with counts', () => { + const res = parseAlleleFrequency({ allele_count: 'NA', n_samples: '100' }); + assert.equal(res, null); + }); +}); diff --git a/test/unit/ext/lz-parsers/test_plink_ld.js b/test/unit/ext/lz-parsers/test_plink_ld.js new file mode 100644 index 00000000..05f3d393 --- /dev/null +++ b/test/unit/ext/lz-parsers/test_plink_ld.js @@ -0,0 +1,41 @@ +import { assert } from 'chai'; +import {makePlinkLdParser} from '../../../../esm/ext/lz-parsers/ld'; + + +describe('LD format parsing', function () { + it('parses PLINK format LD (raw)', function () { + const line = '22\t37470224\t22-37470224-T-C\t22\t37370297\t22-37370297-T-C\t0.000178517'; + const parser = makePlinkLdParser({normalize: false}); + const actual = parser(line); + + const expected = { + chromosome1: '22', + position1: '37470224', + variant1: '22-37470224-T-C', + chromosome2: '22', + position2: '37370297', + variant2: '22-37370297-T-C', + correlation: '0.000178517', + }; + + assert.deepEqual(actual, expected, 'All plink fields parsed as expected'); + }); + + it('normalizes chromosome names and variant formats', function () { + const line = 'chrx\t37470224\t22-37470224\tchr22\t37370297\tchr22:37370297-T-C\t0.000178517'; + const parser = makePlinkLdParser({normalize: true}); + const actual = parser(line); + + const expected = { + chromosome1: 'X', + chromosome2: '22', + correlation: 0.000178517, + position1: 37470224, + position2: 37370297, + variant1: '22:37470224', + variant2: '22:37370297_T/C', + }; + + assert.deepEqual(actual, expected, 'Handles chr prefix, incomplete variants, and normalizes full specifier to EPACTS format (same as LDServer)'); + }); +}); diff --git a/test/unit/ext/test_dynamic-urls.js b/test/unit/ext/test_dynamic-urls.js index fb89e6de..8e539cc6 100644 --- a/test/unit/ext/test_dynamic-urls.js +++ b/test/unit/ext/test_dynamic-urls.js @@ -32,14 +32,14 @@ describe('LzDynamicUrls', function() { const query = '?numeric=1&boolean=false&short_boolean=0&no_value'; const plotData = paramsFromUrl( { numeric: 'numeric', boolean: 'boolean', short_boolean: 'short_boolean', no_value: 'no_value' }, - query + query, ); // Hack: deepStrictEqual behaving oddly in various scenarios; compare types separately assert.deepEqual( plotData, {numeric: '1', boolean: 'false', short_boolean: '0', no_value: ''}, - 'Numeric value deserialized as string' + 'Numeric value deserialized as string', ); assert.ok(typeof plotData['numeric'] === 'string', 'Numeric field represented as string'); diff --git a/test/unit/ext/test_ext_intervals-track.js b/test/unit/ext/test_ext_intervals-track.js index 86da1cc2..f78c6a27 100644 --- a/test/unit/ext/test_ext_intervals-track.js +++ b/test/unit/ext/test_ext_intervals-track.js @@ -27,12 +27,12 @@ describe('Interval annotation track', function () { const layout = LAYOUTS.get('data_layer', 'intervals', { // Unit tests will use the most rigorous form of the track (coloring and separation are determined by // a unique ID that is separate from the label) - track_split_field: '{{namespace[intervals]}}state_id', + track_split_field: 'intervals:state_id', }); const instance = DATA_LAYERS.create('intervals', layout); this.instance = instance; this.color_config = find_color_options(instance._base_layout); - this.color_config.field = '{{namespace[intervals]}}state_id'; + this.color_config.field = 'intervals:state_id'; this.legend_config = instance._base_layout.legend; }); @@ -52,7 +52,7 @@ describe('Interval annotation track', function () { assert.deepEqual( this.color_config, // Note we are comparing base layout (before auto-gen) to dynamic layout (after) - find_color_options(this.instance.layout) + find_color_options(this.instance.layout), ); assert.deepEqual(this.instance.layout.legend, this.instance._base_layout.legend); }); @@ -68,10 +68,10 @@ describe('Interval annotation track', function () { this.instance.data = [ // Interesting property of real data: sometimes two HMM models are assigned the same label. // State id is considered the unambiguous identifier. - { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 1, 'intervals:itemRgb': '#FF0000' }, - { 'intervals:state_name': 'Weak enhancer', 'intervals:state_id': 2, 'intervals:itemRgb': '#00FF00' }, - { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 1, 'intervals:itemRgb': '#FF0000' }, - { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 3, 'intervals:itemRgb': '#0000FF' }, + { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 1, 'intervals:itemRgb': '255,0,0' }, + { 'intervals:state_name': 'Weak enhancer', 'intervals:state_id': 2, 'intervals:itemRgb': '0,255,0' }, + { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 1, 'intervals:itemRgb': '255,0,0' }, + { 'intervals:state_name': 'Strong enhancer', 'intervals:state_id': 3, 'intervals:itemRgb': '0,0,255' }, ]; this.instance._applyLayoutOptions(); @@ -81,15 +81,15 @@ describe('Interval annotation track', function () { const final_legend = this.instance.layout.legend; const final_colors = find_color_options(this.instance.layout); assert.deepEqual(final_colors.parameters.categories, [1, 2, 3], 'Unique categories are generated'); - assert.deepEqual(final_colors.parameters.values, ['#FF0000', '#00FF00', '#0000FF'], 'Unique color options are tracked'); + assert.deepEqual(final_colors.parameters.values, ['rgb(255,0,0)', 'rgb(0,255,0)', 'rgb(0,0,255)'], 'Unique color options are tracked'); assert.deepEqual( final_legend, [ - { color: '#FF0000', 'intervals:state_id': 1, label: 'Strong enhancer', shape: 'rect', 'width': 9 }, - { color: '#00FF00', 'intervals:state_id': 2, label: 'Weak enhancer', shape: 'rect', 'width': 9 }, - { color: '#0000FF', 'intervals:state_id': 3, label: 'Strong enhancer', shape: 'rect', 'width': 9 }, + { color: 'rgb(255,0,0)', 'intervals:state_id': 1, label: 'Strong enhancer', shape: 'rect', 'width': 9 }, + { color: 'rgb(0,255,0)', 'intervals:state_id': 2, label: 'Weak enhancer', shape: 'rect', 'width': 9 }, + { color: 'rgb(0,0,255)', 'intervals:state_id': 3, label: 'Strong enhancer', shape: 'rect', 'width': 9 }, ], - 'Legend items map the correct stateID and colors together' + 'Legend items map the correct stateID and colors together', ); }); @@ -113,7 +113,7 @@ describe('Interval annotation track', function () { assert.deepEqual( final_colors.parameters.values, ['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)'], - 'The smallest preset color scheme that fits data size will be used' + 'The smallest preset color scheme that fits data size will be used', ); assert.deepEqual( final_legend, @@ -122,7 +122,7 @@ describe('Interval annotation track', function () { { color: 'rgb(192,192,192)', 'intervals:state_id': 2, label: 'Weak enhancer', shape: 'rect', 'width': 9 }, { color: 'rgb(128,128,128)', 'intervals:state_id': 3, label: 'Strong enhancer', shape: 'rect', 'width': 9 }, ], - 'Legend items map the correct stateID and colors together' + 'Legend items map the correct stateID and colors together', ); }); }); @@ -131,9 +131,11 @@ describe('Interval annotation track', function () { beforeEach(function() { this.plot = null; const data_sources = new DataSources() - .add('intervals', ['StaticJSON', [ - { start: 100, end: 200, state_id: 'thing1', state_name: 'redfish', itemRgb: '255,0,0' }, - ]]); + .add('intervals', ['StaticJSON', { + data: [ + { start: 100, end: 200, state_id: 'thing1', state_name: 'redfish', itemRgb: '255,0,0' }, + ], + }]); const layout = { panels: [ LAYOUTS.get('panel', 'intervals') ], diff --git a/test/unit/ext/test_tabix-source.js b/test/unit/ext/test_tabix-source.js new file mode 100644 index 00000000..15def0bf --- /dev/null +++ b/test/unit/ext/test_tabix-source.js @@ -0,0 +1,78 @@ +import {assert} from 'chai'; +import sinon from 'sinon'; + +import LocusZoom from 'locuszoom'; +import {ADAPTERS} from '../../../esm/registry'; +import tabix_plugin from '../../../esm/ext/lz-tabix-source'; + +describe('TabixUrlSource', function () { + before(function () { + LocusZoom.use(tabix_plugin); + }); + + function _mock_reader() { + const mock_reader = { fetch: (chr, start, end, callback) => callback(['1\t2', '3\t4']) }; + const spy = sinon.spy(mock_reader, 'fetch'); + return [mock_reader, spy]; + } + + function _line_parser(line) { + const [A, B] = line.split('\t'); + return { A, B }; + } + + it('requires a parser function', function () { + assert.throws( + () => ADAPTERS.create('TabixUrlSource', { url_data: 'ok.tbi' }), + /missing required configuration/, + ); + }); + + it('Checks that overfetch is provided as a fraction', function () { + assert.throws( + () => ADAPTERS.create('TabixUrlSource', { url_data: 'ok.tbi', parser_func: () => 12, overfetch: 99 }), + /fraction/, + ); + }); + + it('accepts a pre-configured external reader instance', function () { + const [reader, _] = _mock_reader(); + + const source = ADAPTERS.create('TabixUrlSource', { + parser_func: _line_parser, + reader: reader, + }); + + assert.ok(source); + }); + + it('overfetches data by the specified fraction', function () { + const [reader, spy] = _mock_reader(); + const source = ADAPTERS.create('TabixUrlSource', { + parser_func: _line_parser, + reader: reader, + overfetch: 0.2, + }); + + return source.getData({ chr: 'X', start: 100, end: 200}).then(() => { + assert.ok(spy.calledWith('X', 80, 220), 'Tabix reader was queried for a wider region of data than the plot view'); + }); + }); + + it('normalizes lines of text and returns parsed results', function () { + const [reader, _] = _mock_reader(); + const source = ADAPTERS.create('TabixUrlSource', { + prefix_namespace: false, + parser_func: _line_parser, + reader: reader, + }); + + return source.getData({ chr: 'X', start: 100, end: 200}).then((records) => { + const expected = [ + { A: '1', B: '2' }, + { A: '3', B: '4' }, + ]; + assert.deepEqual(records, expected, 'Data was retrieved and parsed'); + }); + }); +}); diff --git a/test/unit/helpers/test_display.js b/test/unit/helpers/test_display.js index 9abded34..a38bde36 100644 --- a/test/unit/helpers/test_display.js +++ b/test/unit/helpers/test_display.js @@ -170,12 +170,12 @@ describe('Display and parsing helpers', function () { assert.equal(parseFields(html, data), expected_value); const data2 = { 'fieldA': '', - 'fieldB': '', + 'foo:fieldB': '', }; - const html2 = '{{#if fieldA}}A1
    {{/if}}' - + '{{#if fieldA|derp}}A2
    {{/if}}' - + '{{#if foo:fieldB}}B1
    {{/if}}' - + '{{#if foo:fieldB|derp}}B2
    {{/if}}'; + const html2 = `{{#if fieldA}}A1
    {{/if}}\ +{{#if fieldA|derp}}A2
    {{/if}}\ +{{#if foo:fieldB}}B1
    {{/if}}\ +{{#if foo:fieldB|derp}}B2
    {{/if}}`; const expected_value2 = 'A2
    B2
    '; assert.equal(parseFields(html2, data2), expected_value2); }); diff --git a/test/unit/helpers/test_jsonpath.js b/test/unit/helpers/test_jsonpath.js index 792c5f2a..e0b76e3f 100644 --- a/test/unit/helpers/test_jsonpath.js +++ b/test/unit/helpers/test_jsonpath.js @@ -51,7 +51,7 @@ describe('jsonpath query syntax', function () { assert.throws( () => query(sample_data, '$.panels[@.id !== "a" && @.id === "b"]'), /Cannot parse/, - 'Warns on expression' + 'Warns on expression', ); }); @@ -59,7 +59,7 @@ describe('jsonpath query syntax', function () { assert.throws( () => query(sample_data, '$.panels[1]'), /Cannot parse/, - "Numeric indices are not allowed, because the whole point of this syntax is to write queries that won't break if the order of panels changes later" + "Numeric indices are not allowed, because the whole point of this syntax is to write queries that won't break if the order of panels changes later", ); }); }); diff --git a/test/unit/helpers/test_layouts.js b/test/unit/helpers/test_layouts.js index 727cbc02..4b1cd32a 100644 --- a/test/unit/helpers/test_layouts.js +++ b/test/unit/helpers/test_layouts.js @@ -1,9 +1,73 @@ import {assert} from 'chai'; import sinon from 'sinon'; -import {renameField} from '../../../esm/helpers/layouts'; +import {findFields, renameField} from '../../../esm/helpers/layouts'; describe('Layout helper functions', function () { + describe('findFields', function () { + it('does not try to find requested fields if there are no namespaces declared', function () { + const layout = { + x_field: 'assoc:position', + y_field: 'ld:correlation', + color: 'red', + }; + + const result = [...findFields(layout, [])]; + assert.equal(result.length, 0, 'No fields looked for or found'); + }); + + it('finds simple primitive values', function () { + const namespaces = ['assoc', 'ld']; + const layout = { + x_field: 'assoc:position', + y_field: 'ld:correlation', + label_field_with_filter: 'assoc:variant|htmlescape', + redundant_field: 'assoc:variant', + color: 'red', + spurious: 'X:2500_A/C', + }; + const result = [...findFields(layout, namespaces)]; + assert.sameMembers(result, ['assoc:position', 'assoc:variant', 'ld:correlation'], 'Finds all unique valid field names (and strips filter usages)'); + }); + + it('finds values inside template syntax', function () { + const namespaces = ['assoc']; + const layout = { + y_field: 'ld:correlation', + text: '{{assoc:nearest_gene}} - {{#if assoc:rsid}} { + it('handles various marker formats', () => { + const has_chr_pos = ['chr1:23', 'chrX:23', '1:23', 'X:23']; + const has_chr_pos_refalt = ['chr1:23_A/C', '1:23_A/C', 'chr:1:23:AAAA:G', '1:23_A|C', 'chr1:281876_AC/A']; + const has_chr_pos_refalt_extra = [ + 'chr1:23_A/C_gibberish', '1:23_A/C_gibberish', '1:23_A|C_gibberish', + '1:51873951_G/GT_1:51873951_G/GT', + ]; + + has_chr_pos.forEach((item) => { + const match = parseMarker(item); + assert.ok(match, `Match found for ${item}`); + assert.lengthOf(match.filter((e) => !!e), 2, `Found chr:pos for ${item}`); + }); + has_chr_pos_refalt.forEach((item) => { + const match = parseMarker(item); + assert.ok(match, `Match found for ${item}`); + assert.lengthOf(match.filter((e) => !!e), 4, `Found chr:pos_ref/alt for ${item}`); + }); + has_chr_pos_refalt_extra.forEach((item) => { + const match = parseMarker(item); + assert.ok(match, `Match found for ${item}`); + assert.lengthOf(match.filter((e) => !!e), 5, `Found chr:pos_ref/alt_extra for ${item}`); + }); + + // Pathological edge cases + let match = parseMarker('1:51873951_G/GT_1:51873951_G/GT'); + assert.equal(match[0], '1', 'Found correct chrom'); + assert.equal(match[1], '51873951', 'Found correct pos'); + assert.equal(match[2], 'G', 'Found correct ref'); + assert.equal(match[3], 'GT', 'Found correct alt'); + + match = parseMarker('sentence_goes_here_1:51873951_G/GT', true); + assert.isNotOk(match, 'Marker must be at start of string'); + }); +}); diff --git a/test/unit/helpers/test_render.js b/test/unit/helpers/test_render.js index 6e3f6f0f..1a6f670d 100644 --- a/test/unit/helpers/test_render.js +++ b/test/unit/helpers/test_render.js @@ -43,7 +43,7 @@ describe('Coordinate coalescing', function () { const actual = coalesce_scatter_points( this.sample_data, -Infinity, Infinity, 3, - 0, 1, Infinity + 0, 1, Infinity, ); const expected = _addSymbols([ { x: 1, y: 0.9 }, @@ -61,7 +61,7 @@ describe('Coordinate coalescing', function () { const actual = coalesce_scatter_points( this.sample_data, -Infinity, Infinity, 1, - 0, 1, Infinity + 0, 1, Infinity, ); const expected = _addSymbols([ { x: 0, y: 0.5 }, @@ -82,7 +82,7 @@ describe('Coordinate coalescing', function () { const actual = coalesce_scatter_points( this.sample_data, -Infinity, Infinity, 1.75, // From sample data: verify that x = 0.5 and x = 2 don't combine - 0, 1, Infinity + 0, 1, Infinity, ); const expected = _addSymbols([ { x: 0, y: 0.5 }, @@ -102,7 +102,7 @@ describe('Coordinate coalescing', function () { const actual = coalesce_scatter_points( this.sample_data, -Infinity, Infinity, 3, - 0.0, 1, 0.5 + 0.0, 1, 0.5, ); const expected = _addSymbols([ { x: 1, y: 0.9 }, @@ -126,7 +126,7 @@ describe('Coordinate coalescing', function () { const actual = coalesce_scatter_points( sample_data, -Infinity, Infinity, 3, - 0, 1, Infinity + 0, 1, Infinity, ); assert.deepStrictEqual(actual, sample_data, 'Significant points do not coalesce'); }); diff --git a/test/unit/test_layouts.js b/test/unit/test_layouts.js index 774ea1aa..8cdcc4d7 100644 --- a/test/unit/test_layouts.js +++ b/test/unit/test_layouts.js @@ -1,11 +1,12 @@ import { assert } from 'chai'; -import registry, {_LayoutRegistry} from '../../esm/registry/layouts'; -import {deepCopy, merge} from '../../esm/helpers/layouts'; +import LAYOUTS, {_LayoutRegistry} from '../../esm/registry/layouts'; +import {applyNamespaces, deepCopy, merge} from '../../esm/helpers/layouts'; + describe('_LayoutRegistry', function() { describe('Provides a method to list current layouts by type', function() { it ('No argument: returns an object, keys are layout types and values are arrays of layout names', function() { - const list = registry.list(); + const list = LAYOUTS.list(); assert.isObject(list); assert.hasAllKeys(list, ['plot', 'panel', 'data_layer', 'toolbar', 'toolbar_widgets', 'tooltip']); Object.values(list).forEach((listing) => { @@ -14,8 +15,8 @@ describe('_LayoutRegistry', function() { }); it ('Passed a valid type: returns array of layout names matching that type', function() { - const all = registry.list(); - const just_plots = registry.list('plot'); + const all = LAYOUTS.list(); + const just_plots = LAYOUTS.list('plot'); assert.isArray(just_plots); assert.deepEqual(just_plots, all.plot); @@ -25,13 +26,13 @@ describe('_LayoutRegistry', function() { describe('Provides a method to add new layouts', function() { it ('Requires arguments as (string, string, object) or throws an exception', function() { assert.throws(() => { - registry.add(); + LAYOUTS.add(); }, /must all/); assert.throws(() => { - registry.add('type_only'); + LAYOUTS.add('type_only'); }, /must all/, 'Only type provided'); assert.throws(() => { - registry.add('type', 'name'); + LAYOUTS.add('type', 'name'); }, /must all/, 'Type and name provided, but no item'); }); @@ -46,22 +47,43 @@ describe('_LayoutRegistry', function() { to_add.id = 2; assert.deepEqual(found.id, 1, 'Registry stores a copy: mutating the source object later does not propagate changes'); }); + + it('annotates every new registry item with a best guess of what fields are requested from external providers', function() { + const lookup = new _LayoutRegistry(); + + const base_panel = { id: 'a_panel', red_herring: 'looks_like:a_field' }; + lookup.add('panel', 'not_modified', base_panel); + let actual = lookup.get('panel', 'not_modified'); + assert.deepEqual(actual, base_panel, 'Panel layouts are unchanged'); + + const base_layer = { + id: 'a_layer', + namespace: { assoc: 'assoc', ld: 'ld' }, + x_field: 'assoc:something', + y_field: 'ld:correlation', + red_herring: 'unknown_ns:means_not_field', + label: 'chromosome {{chr}}', + }; + lookup.add('data_layer', 'adds_autofields', base_layer); + actual = lookup.get('data_layer', 'adds_autofields'); + assert.deepEqual(actual._auto_fields, ['assoc:something', 'ld:correlation'], 'Data layers in registry receive an added magic property called _auto_fields'); + }); }); // get() describe('Provides a method to get layout objects', function() { it('Must specify both type and name of the layout desired', function() { assert.throws(() => { - registry.get('plot'); + LAYOUTS.get('plot'); }, /Must specify/, 'Only type specified'); assert.throws(() => { - registry.get('plot', 'nonexistent'); + LAYOUTS.get('plot', 'nonexistent'); }, /not found/, 'Unrecognized type specified'); }); it('Returns layout object when type and name match', function() { - const result = registry.get('panel', 'association'); + const result = LAYOUTS.get('panel', 'association'); assert.equal(result.id, 'association'); }); @@ -123,167 +145,108 @@ describe('_LayoutRegistry', function() { }; lookup.add('test', 'test', base_layout); - assert.deepEqual(lookup.get('test', 'test', mods), expected_layout); + const actual = lookup.get('test', 'test', mods); + assert.deepEqual(actual, expected_layout); + + assert.notDeepEqual(actual, base_layout, 'Overriding the layout does not change the original'); }); - it('Allows for namespacing arbitrary keys and values at all nesting levels', function() { + it('Allows for overriding namespaces', function() { const lookup = new _LayoutRegistry(); - const base_layout = { - scalar_0: 123, - '{{namespace}}scalar_1': 'aardvark', - '{{namespace[dingo]}}scalar_2': '{{namespace[1]}}albacore', - namespace_scalar: '{{namespace}}badger', - namespace_0_scalar: '{{namespace[0]}}crocodile', - namespace_dingo_scalar: '{{namespace[dingo]}}emu', - namespace_1_scalar: '{{namespace[1]}}ferret', - array_of_scalars: [ 4, 5, 6 ], - nested_object: { - property_0: { - scalar_0: 0, - scalar_1: 'grackle', - namespace_scalar: '{{{{namespace}}hog}} and {{{{namespace[1]}}yak}} and {{{{namespace[jackal]}}zebu}}', - namespace_0_scalar: '{{namespace[0]}}iguana', - namespace_jackal_scalar: '{{namespace[jackal]}}kangaroo', - namespace_dingo_scalar: '{{namespace[dingo]}}lemur', - namespace_1_scalar: '{{namespace[1]}}moose', - array: ['nematoad', '{{namespace}}oryx', '{{namespace[1]}}pigeon', '{{namespace[jackal]}}quail'], - object: { - scalar: 'rhea', - array: ['serpent', '{{namespace[0]}}tortoise', '{{namespace[upapa]}}vulture', '{{namespace}}xerus'], - }, + const layout = { + width: 400, + panels: [ + { + data_layers: [ + {id: 'assoc1', namespace: {assoc: 'assoc', ld: 'ld' }}, + {id: 'assoc2', namespace: {assoc: 'assoc', catalog: 'catalog' }}, + ], }, - property_1: false, - property_2: true, - }, + ], }; - - lookup.add('test', 'test', base_layout); - // Explicit directive to NOT apply namespaces: no changes - const unnamespaced_layout = lookup.get('test', 'test', { unnamespaced: true }); - assert.deepEqual(unnamespaced_layout, base_layout); - - // No defined namespaces: drop all namespaces - const no_namespace_layout = lookup.get('test', 'test'); - assert.equal(no_namespace_layout['scalar_1'], 'aardvark'); - assert.equal(no_namespace_layout['scalar_2'], 'albacore'); - assert.equal(no_namespace_layout.namespace_scalar, 'badger'); - assert.equal(no_namespace_layout.namespace_0_scalar, 'crocodile'); - assert.equal(no_namespace_layout.namespace_dingo_scalar, 'emu'); - assert.equal(no_namespace_layout.namespace_1_scalar, 'ferret'); - assert.equal(no_namespace_layout.nested_object.property_0.namespace_scalar, '{{hog}} and {{yak}} and {{zebu}}'); - assert.equal(no_namespace_layout.nested_object.property_0.namespace_0_scalar, 'iguana'); - assert.equal(no_namespace_layout.nested_object.property_0.namespace_jackal_scalar, 'kangaroo'); - assert.equal(no_namespace_layout.nested_object.property_0.namespace_dingo_scalar, 'lemur'); - assert.equal(no_namespace_layout.nested_object.property_0.namespace_1_scalar, 'moose'); - assert.equal(no_namespace_layout.nested_object.property_0.array[1], 'oryx'); - assert.equal(no_namespace_layout.nested_object.property_0.array[2], 'pigeon'); - assert.equal(no_namespace_layout.nested_object.property_0.array[3], 'quail'); - assert.equal(no_namespace_layout.nested_object.property_0.object.array[1], 'tortoise'); - assert.equal(no_namespace_layout.nested_object.property_0.object.array[2], 'vulture'); - assert.equal(no_namespace_layout.nested_object.property_0.object.array[3], 'xerus'); - - // Single namespace string: use in place of all namespace placeholders - const single_namespace_layout = lookup.get('test', 'test', { namespace: 'ns' }); - assert.equal(single_namespace_layout['ns:scalar_1'], 'aardvark'); - assert.equal(single_namespace_layout['ns:scalar_2'], 'ns:albacore'); - assert.equal(single_namespace_layout.namespace_scalar, 'ns:badger'); - assert.equal(single_namespace_layout.namespace_0_scalar, 'ns:crocodile'); - assert.equal(single_namespace_layout.namespace_dingo_scalar, 'ns:emu'); - assert.equal(single_namespace_layout.namespace_1_scalar, 'ns:ferret'); - assert.equal(single_namespace_layout.nested_object.property_0.namespace_scalar, '{{ns:hog}} and {{ns:yak}} and {{ns:zebu}}'); - assert.equal(single_namespace_layout.nested_object.property_0.namespace_0_scalar, 'ns:iguana'); - assert.equal(single_namespace_layout.nested_object.property_0.namespace_jackal_scalar, 'ns:kangaroo'); - assert.equal(single_namespace_layout.nested_object.property_0.namespace_dingo_scalar, 'ns:lemur'); - assert.equal(single_namespace_layout.nested_object.property_0.namespace_1_scalar, 'ns:moose'); - assert.equal(single_namespace_layout.nested_object.property_0.array[1], 'ns:oryx'); - assert.equal(single_namespace_layout.nested_object.property_0.array[2], 'ns:pigeon'); - assert.equal(single_namespace_layout.nested_object.property_0.array[3], 'ns:quail'); - assert.equal(single_namespace_layout.nested_object.property_0.object.array[1], 'ns:tortoise'); - assert.equal(single_namespace_layout.nested_object.property_0.object.array[2], 'ns:vulture'); - assert.equal(single_namespace_layout.nested_object.property_0.object.array[3], 'ns:xerus'); - - // Array of namespaces: replace number-indexed namespace holders, - // resolve {{namespace}} and any named namespaces to {{namespace[0]}}. - const array_namespace_layout = lookup.get('test', 'test', { namespace: ['ns_0', 'ns_1'] }); - assert.equal(array_namespace_layout['ns_0:scalar_1'], 'aardvark'); - assert.equal(array_namespace_layout['ns_0:scalar_2'], 'ns_1:albacore'); - assert.equal(array_namespace_layout.namespace_scalar, 'ns_0:badger'); - assert.equal(array_namespace_layout.namespace_0_scalar, 'ns_0:crocodile'); - assert.equal(array_namespace_layout.namespace_dingo_scalar, 'ns_0:emu'); - assert.equal(array_namespace_layout.namespace_1_scalar, 'ns_1:ferret'); - assert.equal(array_namespace_layout.nested_object.property_0.namespace_scalar, '{{ns_0:hog}} and {{ns_1:yak}} and {{ns_0:zebu}}'); - assert.equal(array_namespace_layout.nested_object.property_0.namespace_0_scalar, 'ns_0:iguana'); - assert.equal(array_namespace_layout.nested_object.property_0.namespace_jackal_scalar, 'ns_0:kangaroo'); - assert.equal(array_namespace_layout.nested_object.property_0.namespace_dingo_scalar, 'ns_0:lemur'); - assert.equal(array_namespace_layout.nested_object.property_0.namespace_1_scalar, 'ns_1:moose'); - assert.equal(array_namespace_layout.nested_object.property_0.array[1], 'ns_0:oryx'); - assert.equal(array_namespace_layout.nested_object.property_0.array[2], 'ns_1:pigeon'); - assert.equal(array_namespace_layout.nested_object.property_0.array[3], 'ns_0:quail'); - assert.equal(array_namespace_layout.nested_object.property_0.object.array[1], 'ns_0:tortoise'); - assert.equal(array_namespace_layout.nested_object.property_0.object.array[2], 'ns_0:vulture'); - assert.equal(array_namespace_layout.nested_object.property_0.object.array[3], 'ns_0:xerus'); - // first defined key to any non-matching namespaces. - const object_namespace_layout = lookup.get('test', 'test', { - namespace: { - dingo: 'ns_dingo', - jackal: 'ns_jackal', - 1: 'ns_1', - 'default': 'ns_default', - }, + lookup.add('plot', 'testfixture', layout); + const modified = lookup.get('plot', 'testfixture', { + namespace: { assoc: 'assoc12', catalog: 'ebi_cat' }, + width: 800, // Add a property during overrides + new_prop: true, }); - assert.equal(object_namespace_layout['ns_default:scalar_1'], 'aardvark'); - assert.equal(object_namespace_layout['ns_dingo:scalar_2'], 'ns_1:albacore'); - assert.equal(object_namespace_layout.namespace_scalar, 'ns_default:badger'); - assert.equal(object_namespace_layout.namespace_0_scalar, 'ns_default:crocodile'); - assert.equal(object_namespace_layout.namespace_dingo_scalar, 'ns_dingo:emu'); - assert.equal(object_namespace_layout.namespace_1_scalar, 'ns_1:ferret'); - assert.equal(object_namespace_layout.nested_object.property_0.namespace_scalar, '{{ns_default:hog}} and {{ns_1:yak}} and {{ns_jackal:zebu}}'); - assert.equal(object_namespace_layout.nested_object.property_0.namespace_0_scalar, 'ns_default:iguana'); - assert.equal(object_namespace_layout.nested_object.property_0.namespace_jackal_scalar, 'ns_jackal:kangaroo'); - assert.equal(object_namespace_layout.nested_object.property_0.namespace_dingo_scalar, 'ns_dingo:lemur'); - assert.equal(object_namespace_layout.nested_object.property_0.namespace_1_scalar, 'ns_1:moose'); - assert.equal(object_namespace_layout.nested_object.property_0.array[1], 'ns_default:oryx'); - assert.equal(object_namespace_layout.nested_object.property_0.array[2], 'ns_1:pigeon'); - assert.equal(object_namespace_layout.nested_object.property_0.array[3], 'ns_jackal:quail'); - assert.equal(object_namespace_layout.nested_object.property_0.object.array[1], 'ns_default:tortoise'); - assert.equal(object_namespace_layout.nested_object.property_0.object.array[2], 'ns_default:vulture'); - assert.equal(object_namespace_layout.nested_object.property_0.object.array[3], 'ns_default:xerus'); + const expected = { + width: 800, + new_prop: true, + panels: [ + { + data_layers: [ + {id: 'assoc1', namespace: {assoc: 'assoc12', ld: 'ld' }}, + {id: 'assoc2', namespace: {assoc: 'assoc12', catalog: 'ebi_cat' }}, + ], + }, + ], + }; + + assert.deepEqual(modified, expected, 'Namespaces are applied to children as part of overrides'); }); + }); +}); - it('Allows for inheriting namespaces', function() { - const lookup = new _LayoutRegistry(); +describe('Layout helpers', function () { + describe('applyNamespaces', function () { + it('warns if layout or namespace-overrides are not objects', function () { + assert.throws( + () => applyNamespaces(null, {}), + /as objects/, + ); + assert.throws( + () => applyNamespaces({}, 42), + /as objects/, + ); + assert.ok(applyNamespaces({}), 'If no namespaced provided, default value is used'); + }); - const layout_0 = { - namespace: { dingo: 'ns_dingo', jackal: 'ns_jackal', default: 'ns_0' }, - '{{namespace[dingo]}}scalar_1': 'aardvark', - '{{namespace[dingo]}}scalar_2': '{{namespace[jackal]}}albacore', - scalar_3: '{{namespace}}badger', + it('Can override namespaces referenced in both a layout and global object', function () { + const base = { + id: 'a_layer', + namespace: { assoc: 'assoc', ld: 'ld', catalog: 'catalog' }, + x_field: 'assoc:position', + y_field: 'ld:correlation', }; - lookup.add('test', 'layout_0', layout_0); - const layout_1 = { - namespace: { ferret: 'ns_ferret', default: 'ns_1' }, - '{{namespace}}scalar_1': 'emu', - '{{namespace[ferret]}}scalar_2': '{{namespace}}kangaroo', - nested_layout: lookup.get('test', 'layout_0', { unnamespaced: true }), + const expected = { + id: 'a_layer', + namespace: { assoc: 'assoc22', ld: 'ld5', catalog: 'catalog' }, + x_field: 'assoc:position', + y_field: 'ld:correlation', }; - lookup.add('test', 'layout_1', layout_1); - const ns_layout_1 = lookup.get('test', 'layout_1', { - namespace: { - dingo: 'ns_dingo_mod', - default: 'ns_mod', - }, - }); - assert.equal(ns_layout_1['ns_mod:scalar_1'], 'emu'); - assert.equal(ns_layout_1['ns_ferret:scalar_2'], 'ns_mod:kangaroo'); - assert.equal(ns_layout_1.nested_layout['ns_dingo_mod:scalar_1'], 'aardvark'); - assert.equal(ns_layout_1.nested_layout['ns_dingo_mod:scalar_2'], 'ns_jackal:albacore'); - assert.equal(ns_layout_1.nested_layout.scalar_3, 'ns_mod:badger'); + + + // Note: a namespace is ONLY copied over if it is relevant to that data layer (other_anno should not appear anywhere) + const actual = applyNamespaces(base, { assoc: 'assoc22', ld: 'ld5', other_anno: 'mything' }); + assert.deepEqual(actual, expected, 'Overrides as appropriate'); + }); + + it('Can override namespaces in all child objects', function () { + const base = { + panels: [{ + data_layers: [ + { id: 'a', x_field: 'assoc:variant', namespace: { assoc: 'assoc', catalog: 'catalog' }}, + { id: 'b', x_field: 'someanno:afield', namespace: { catalog: 'catalog', ld: 'ld', other_thing: 'unused' }}, + ], + }], + }; + + const expected = { + panels: [{ + data_layers: [ + { id: 'a', x_field: 'assoc:variant', namespace: { assoc: 'myassoc', catalog: 'mycat' }}, + { id: 'b', x_field: 'someanno:afield', namespace: { catalog: 'mycat', ld: 'ld5', other_thing: 'unused' }}, + ], + }], + }; + + const actual = applyNamespaces(base, { assoc: 'myassoc', ld: 'ld5', catalog: 'mycat' }); + assert.deepEqual(actual, expected, 'Selectively applies overrides to nested objects'); }); }); -}); -describe('Layout helpers', function () { describe('Provides a method to merge layout objects', function() { beforeEach(function() { this.default_layout = { @@ -306,18 +269,6 @@ describe('Layout helpers', function () { }; }); - it('should throw an exception if either argument is not an object', function() { - assert.throws(() => { - merge(); - }); - assert.throws(() => { - merge({}); - }); - assert.throws(() => { - merge({}, ''); - }); - }); - it('should return the passed default layout if provided an empty layout', function() { const returned_layout = merge({}, this.default_layout); assert.deepEqual(returned_layout, this.default_layout); @@ -382,40 +333,39 @@ describe('Layout helpers', function () { describe('Provides a method to query specific attributes', function () { it('can query a set of values based on a jsonpath selector', function () { - const base = registry.get('plot', 'standard_association'); + const base = LAYOUTS.get('plot', 'standard_association'); base.extra_field = false; const scenarios = [ - ['predicate_filters retrieve only list items where a specific condition is met', '$..color[?(@.scale_function === "if")].field', ['ld:isrefvar']], - ['retrieves a list of scale function names', 'panels[?(@.tag === "association")]..scale_function', [ 'if', 'if', 'if', 'numerical_bin' ]], + ['predicate_filters retrieve only list items where a specific condition is met', '$..color[?(@.scale_function === "if")].field', ['lz_is_ld_refvar']], + ['retrieves a list of scale function names', 'panels[?(@.tag === "association")]..scale_function', [ 'if', 'numerical_bin', 'if', 'effect_direction', 'if' ]], ['fetches dotted field path - one specific axis label', 'panels[?(@.tag === "association")].axes.x.label', [ 'Chromosome {{chr}} (Mb)' ]], ['is able to query and return falsy values', '$.extra_field', [false]], ['returns an empty list if no matches are found', '$.nonexistent', []], ]; for (let [label, selector, expected] of scenarios) { - assert.sameDeepMembers(registry.query_attrs(base, selector), expected, `Scenario '${label}' passed`); + assert.sameDeepMembers(LAYOUTS.query_attrs(base, selector), expected, `Scenario '${label}' passed`); } }); it('can mutate a set of values based on a jsonpath selector', function () { - const base_panel = registry.get('panel', 'association'); - const base_layer = registry.get('data_layer', 'association_pvalues'); - + const base_panel = LAYOUTS.get('panel', 'association'); const scenarios = [ ['set single value to a constant', '$.panels[?(@.tag === "association")].id', 'one', ['one']], ['toggle a boolean false to true', '$.fake_field', true, [true]], ['set many values to a constant', '$..id', 'all', ['all', 'all', 'all', 'all', 'all', 'all']], - ['add items to an array', '$..data_layers[?(@.tag === "association")].fields', (old_value) => old_value.concat(['field1', 'field2']), [base_layer.fields.concat(['field1', 'field2'])]], + ['add items to an array', '$.some_list', (old_value) => old_value.concat(['field1', 'field2']), [['field0', 'field1', 'field2']]], // Two subtly different cases for nested objects (direct query, and as part of filtered list) - ['mutate an object inside an object', '$..panels[?(@.tag === "association")].margin', (old_config) => (old_config.new_field = 10) && old_config, [{bottom: 40, left: 50, right: 50, top: 35, new_field: 10}]], - ['mutate an object inside a list', '$..panels[?(@.tag === "association")]', (old_config) => (old_config.margin.new_field = 10) && old_config, [Object.assign(base_panel, {margin: {bottom: 40, left: 50, right: 50, top: 35, new_field: 10}})]], + ['mutate an object inside an object', '$..panels[?(@.tag === "association")].margin', (old_config) => (old_config.new_field = 10) && old_config, [{bottom: 40, left: 70, right: 55, top: 35, new_field: 10}]], + ['mutate an object inside a list', '$..panels[?(@.tag === "association")]', (old_config) => (old_config.margin.new_field = 10) && old_config, [Object.assign(base_panel, {margin: {bottom: 40, left: 70, right: 55, top: 35, new_field: 10}})]], ]; for (let [label, selector, mutator, expected] of scenarios) { - const base = registry.get('plot', 'standard_association'); + const base = LAYOUTS.get('plot', 'standard_association'); base.fake_field = false; - assert.deepEqual(registry.mutate_attrs(base, selector, mutator), expected, `Scenario '${label}' passed`); + base.some_list = ['field0']; + assert.deepEqual(LAYOUTS.mutate_attrs(base, selector, mutator), expected, `Scenario '${label}' passed`); } }); }); diff --git a/test/unit/test_transforms.js b/test/unit/test_transforms.js index 01fe73f0..ebe7c4ce 100644 --- a/test/unit/test_transforms.js +++ b/test/unit/test_transforms.js @@ -42,7 +42,7 @@ describe('Transformation Functions', function() { it('should escape characters with special meaning in xml, and ignore others', function() { assert.equal( htmlescape(""), - '<script type="application/javascript">alert('yo & ' + `I`)</script>' + '<script type="application/javascript">alert('yo & ' + `I`)</script>', ); }); }); diff --git a/webpack.common.cjs b/webpack.common.cjs index 0f6836a3..5a897992 100644 --- a/webpack.common.cjs +++ b/webpack.common.cjs @@ -12,7 +12,7 @@ const PACKAGE = require('./package.json'); const srcPath = path.resolve(__dirname, 'esm'); const outputPath = path.resolve(__dirname, 'dist'); -const FILENAMES = { +const OUTPUT_FILENAMES = { // For legacy reasons, the filenames that people expect are different than the "library" name LocusZoom: 'locuszoom.app.min.js', LzDynamicUrls: 'ext/lz-dynamic-urls.min.js', @@ -21,6 +21,7 @@ const FILENAMES = { LzIntervalsTrack: 'ext/lz-intervals-track.min.js', LzIntervalsEnrichment: 'ext/lz-intervals-enrichment.min.js', LzCredibleSets: 'ext/lz-credible-sets.min.js', + LzParsers: 'ext/lz-parsers.min.js', LzTabix: 'ext/lz-tabix-source.min.js', LzAggregationTests: 'ext/lz-aggregation-tests.min.js', }; @@ -36,6 +37,7 @@ module.exports = { LzIntervalsTrack: path.resolve(srcPath, 'ext', 'lz-intervals-track.js'), LzIntervalsEnrichment: path.resolve(srcPath, 'ext', 'lz-intervals-enrichment.js'), LzCredibleSets: path.resolve(srcPath, 'ext', 'lz-credible-sets.js'), + LzParsers: path.resolve(srcPath, 'ext', 'lz-parsers/index.js'), LzTabix: path.resolve(srcPath, 'ext', 'lz-tabix-source.js'), LzAggregationTests: path.resolve(srcPath, 'ext', 'lz-aggregation-tests.js'), }, @@ -49,6 +51,7 @@ module.exports = { new ESLintPlugin(), ], resolve: { + symlinks: false, modules: [ 'node_modules', ], @@ -66,7 +69,7 @@ module.exports = { path: outputPath, filename: (data) => { // For backwards compatibility, the filename is different than the chunk name. - const match = FILENAMES[data.chunk.name]; + const match = OUTPUT_FILENAMES[data.chunk.name]; if (!match) { const msg = `Must provide a filename for this chunk: ${data.chunk.name}`; console.error(msg); @@ -80,8 +83,6 @@ module.exports = { externals: { d3: 'd3', locuszoom: 'LocusZoom', - 'gwas-credible-sets': 'gwasCredibleSets', - 'tabix-reader': 'tabix', 'raremetal.js': 'raremetal', }, };