### Install and Build Dalliance with Gulp
Source: https://github.com/dasmoth/dalliance/blob/master/README.md
Instructions for setting up the development environment and building Dalliance using Node.js and Gulp. Ensure Node.js and npm are installed before proceeding.
```bash
(sudo?) npm install -g gulp
npm install # Install dependencies
gulp # Build Dalliance
```
--------------------------------
### Browser Constructor Initialization
Source: https://context7.com/dasmoth/dalliance/llms.txt
This example demonstrates how to initialize the Biodalliance Browser object with essential configuration options like the genomic location, coordinate system, and DOM injection target.
```APIDOC
## Browser Constructor — Initializing the Genome Browser
The `Browser` constructor is the entry point. It accepts a configuration object defining the coordinate system, initial view, data sources, and display options. It injects the browser UI into a DOM element identified by `pageName` (default `svgHolder`) or `injectionPoint`.
### Configuration Options:
- **chr** (string) - Required - The initial chromosome to display.
- **viewStart** (integer) - Required - The starting position of the initial view.
- **viewEnd** (integer) - Required - The ending position of the initial view.
- **coordSystem** (object) - Required - Defines the coordinate system.
- **speciesName** (string) - Species name (e.g., 'Human').
- **taxon** (integer) - NCBI Taxonomy ID (e.g., 9606).
- **auth** (string) - Authority for the genome version (e.g., 'GRCh').
- **version** (string) - Genome version (e.g., '38').
- **ucscName** (string) - UCSC genome name (e.g., 'hg38').
- **pageName** (string) - Optional - The ID of the DOM element to inject the browser into (defaults to 'svgHolder').
- **injectionPoint** (DOMElement) - Optional - A DOM element to inject the browser into, alternative to `pageName`.
- **cookieKey** (string) - Optional - A key for saving and restoring the browser's view state.
- **fullScreen** (boolean) - Optional - Whether to make the browser fill the entire window.
- **disablePoweredBy** (boolean) - Optional - Whether to disable the 'Powered by Biodalliance' link.
- **retina** (boolean) - Optional - Enable Retina/HiDPI display support.
- **useFetchWorkers** (boolean) - Optional - Use Web Workers for data fetching.
- **maxWorkers** (integer) - Optional - The maximum number of Web Workers to use.
- **onFirstRender** (function) - Optional - A callback function executed when all tiers have rendered for the first time.
- **sources** (array) - Optional - An array of data source configurations.
### Example Usage:
```html
Loading genome browser...
```
```
--------------------------------
### NPM Module Usage for Dalliance
Source: https://context7.com/dasmoth/dalliance/llms.txt
When using Dalliance via NPM, import necessary components like `Browser` and `registerSourceAdapterFactory`. This example shows registering a custom adapter and creating a browser instance.
```javascript
const dalliance = require('dalliance');
// or: import { Browser, registerSourceAdapterFactory } from 'dalliance';
const { Browser, registerSourceAdapterFactory } = dalliance;
// Register custom adapter
registerSourceAdapterFactory('custom', function(config) {
return {
features: {
fetch: function(chr, min, max, scale, types, pool, cb) {
cb(null, []);
}
}
};
});
// Create browser instance (requires DOM)
const b = new Browser({
chr: '22',
viewStart: 30000000,
viewEnd: 30030000,
injectionPoint: document.getElementById('genome-browser'),
coordSystem: {
speciesName: 'Human', taxon: 9606,
auth: 'GRCh', version: '38', ucscName: 'hg38'
},
sources: [{
name: 'Genome',
twoBitURI: 'http://www.biodalliance.org/datasets/hg38.2bit',
tier_type: 'sequence',
provides_entrypoints: true
}]
});
b.addViewListener(function(chr, min, max) {
console.log('View changed:', chr, min, max);
});
```
--------------------------------
### External Navigation Shortcuts with Browser Links
Source: https://context7.com/dasmoth/dalliance/llms.txt
Configure the `browserLinks` option to add external links to the browser toolbar. Template variables like ${chr}, ${start}, and ${end} are substituted with current view coordinates.
```javascript
var b = new Browser({
chr: '22', viewStart: 30300000, viewEnd: 30500000,
coordSystem: { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: '38', ucscName: 'hg38' },
sources: [/* ... */],
browserLinks: {
Ensembl: 'http://www.ensembl.org/Homo_sapiens/Location/View?r=${chr}:${start}-${end}',
UCSC: 'http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg38&position=chr${chr}:${start}-${end}'
}
});
```
--------------------------------
### browser.addRegionSelectListener(handler)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Registers a callback function that executes when the user selects a genomic region by dragging on the sequence track. The handler receives the chromosome and the start and end coordinates of the selected region.
```APIDOC
## `browser.addRegionSelectListener(handler)` — Region Selection Events
Fires when the user drags on the sequence track to select a genomic region.
### Parameters
- **handler** (function) - The callback function to execute on region selection. It receives `(chr, min, max)`.
- **chr** (string) - The chromosome of the selected region.
- **min** (integer) - The start coordinate of the selected region.
- **max** (integer) - The end coordinate of the selected region.
### Example
```javascript
b.addRegionSelectListener(function(chr, min, max) {
console.log('Selected region: ' + chr + ':' + min + '-' + max);
var length = max - min;
document.getElementById('selectionInfo').textContent =
chr + ':' + min.toLocaleString() + '-' + max.toLocaleString() +
' (' + length.toLocaleString() + ' bp)';
});
```
```
--------------------------------
### Connect to Assembly Hub and Display Genomes
Source: https://github.com/dasmoth/dalliance/blob/master/hubstub.html
Initializes the Dalliance browser, sets up an event listener for a submit button to connect to a hub URL, and displays a list of available genomes. Requires the Dalliance library and DOM manipulation.
```javascript
function init() {
var container = document.getElementById('svgHolder'); // Has the nice property that // it gets nuked when Dalliance starts up....
document.getElementById('submit_button').addEventListener('click', function(ev) {
connectTrackHub(document.getElementById('huburl').value, function(hub, err) {
if (hub) {
container.appendChild(makeElement('p', 'Where do you want to go today?'));
var ge = [];
for (var g in hub.genomes) {
var gg = hub.genomes[g];
var gl = makeElement('li', makeLabelForGenome(gg));
ge.push(gl);
}
container.appendChild(makeElement('ul', ge));
} else {
console.log(err);
}
});
}, false);
}
```
--------------------------------
### Configure Liftover Chains for Coordinate Mapping
Source: https://context7.com/dasmoth/dalliance/llms.txt
Enable on-the-fly coordinate liftover between assemblies using the `chains` option. Each entry maps a key to a Chainset configuration, specifying source and target assemblies.
```javascript
var b = new Browser({
chr: '22', viewStart: 30300000, viewEnd: 30500000,
coordSystem: {
speciesName: 'Human', taxon: 9606,
auth: 'GRCh', version: '38', ucscName: 'hg38'
},
chains: {
hg19ToHg38: new Chainset(
'http://www.derkholm.net:8080/das/hg19ToHg38/',
'GRCh37', // Source assembly name
'GRCh38', // Target assembly name
{
speciesName: 'Human', taxon: 9606,
auth: 'GRCh', version: 37, ucscName: 'hg19'
}
)
},
sources: [
{
name: 'GENCODEv19',
bwgURI: 'http://www.biodalliance.org/datasets/gencode.bb',
mapping: 'hg19ToHg38' // Reference the chain key here
}
]
});
```
--------------------------------
### Configure Multi-Tier Renderer in Dalliance Browser
Source: https://context7.com/dasmoth/dalliance/llms.txt
Set up layered visualizations by configuring a 'multi' tier as a container and 'sub' tiers for individual tracks. Specify offsets and z-indices to control rendering order and position.
```javascript
var b = new Browser({
chr: '1', viewStart: 1000000, viewEnd: 1100000,
coordSystem: { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: '38', ucscName: 'hg38' },
sources: [
// Container multi-tier with grid and quantitative ruler
{
name: 'Multi-tier container',
tier_type: 'qtl',
uri: '',
renderer: 'multi',
multi: {
multi_id: 'layer1',
grid: true,
grid_offset: 0,
grid_spacing: 10,
quant: { min: 0, max: 100 }
}
},
// Sub-tier: gene annotation rendered within the multi-tier
{
name: 'Genes',
desc: 'GENCODE gene structures',
bwgURI: 'http://www.biodalliance.org/datasets/GRCh38/gencode.bb',
stylesheet_uri: 'http://www.biodalliance.org/stylesheets/gencode2.xml',
collapseSuperGroups: true,
renderer: 'sub',
sub: {
multi_id: 'layer1', // Must match the container's multi_id
offset: 0, // Vertical pixel offset from top
z: 1 // z-index for draw ordering
}
},
// Second sub-tier: signal track rendered on top
{
name: 'Signal',
bwgURI: 'http://example.org/signal.bw',
renderer: 'sub',
sub: {
multi_id: 'layer1',
offset: 50,
z: 2
}
}
]
});
```
--------------------------------
### Initialize Biodalliance Browser
Source: https://context7.com/dasmoth/dalliance/llms.txt
Configure and initialize the Biodalliance genome browser. Requires specifying the initial genomic location, coordinate system, and optionally a DOM element for injection, cookie key for state saving, and display options like full screen, retina support, and web workers.
```html
Loading genome browser...
```
--------------------------------
### Configure a Multi-tier Renderer
Source: https://github.com/dasmoth/dalliance/blob/master/docs/renderer.md
This configuration defines a multi-tier with a unique ID, an optional horizontal grid, and a vertical ruler. Only 'multi_id' is mandatory; 'grid' and 'quant' are optional.
```javascript
{
name: 'Multi-tier',
tier_type: 'qtl',
uri: '',
renderer: 'multi',
multi: {
multi_id: "multi_1",
grid: true,
grid_offset: 0,
grid_spacing: 10,
quant: { min: 0, max: 100 }
}
}
```
--------------------------------
### Initialize Dalliance Browser for Human GRCh37
Source: https://github.com/dasmoth/dalliance/blob/master/example-browsers/human37.html
Initializes a Dalliance browser instance with specific genome coordinates, coordinate system, and data sources for human GRCh37. Includes configuration for genome, gene annotations, repeat data, SNPs, CpG islands, and a BWG test track. Also sets up external hubs and enables full-screen mode.
```javascript
var b = new Browser({
chr: '22',
viewStart: 30000000,
viewEnd: 30030000,
cookieKey: 'human-grc_h37',
coordSystem: { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: '37', ucscName: 'hg19' },
chains: {
hg18ToHg19: new Chainset('http://www.derkholm.net:8080/das/hg18ToHg19/', 'NCBI36', 'GRCh37', { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: 36 })
},
sources: [
{name: 'Genome', twoBitURI: 'http://www.biodalliance.org/datasets/hg19.2bit', tier_type: 'sequence', provides_entrypoints: true, pinned: true },
{name: 'GENCODE', bwgURI: 'http://www.biodalliance.org/datasets/gencode.bb', stylesheet_uri: 'http://www.biodalliance.org/stylesheets/gencode.xml', collapseSuperGroups: true, trixURI: 'http://www.biodalliance.org/datasets/geneIndex.ix'},
{name: 'Repeats', desc: 'Repeat annotation from RepeatMasker', bwgURI: 'http://www.biodalliance.org/datasets/repeats.bb', stylesheet_uri: 'http://www.biodalliance.org/stylesheets/bb-repeats.xml', forceReduction: -1},
{name: 'SNPs', tier_type: 'ensembl', species:'human', type: 'variation', disabled: true, featureInfoPlugin: function(f, info) { if (f.id) { info.add('SNP', makeElement('a', f.id, {href: 'http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=' + f.id, target: '_newtab'})); } } },
{name: 'CpG', desc: 'CpG observed/expected ratio', uri: 'http://www.derkholm.net:8080/das/hg19comp/',
quantLeapThreshold: 0.8,
forceReduction: -1,
style: [{type: 'cpgoe', style: {glyph: 'LINEPLOT', FGCOLOR: 'green', HEIGHT: '50', MIN: 0, MAX: 1.2}}]
},
{name: 'BWG test', bwgURI: 'http://www.biodalliance.org/datasets/spermMethylation.bw', stylesheet_uri: 'http://www.ebi.ac.uk/das-srv/genomicdas/das/batman_seq_SP/stylesheet', mapping: 'hg18ToHg19', quantLeapThreshold: 80 },
],
setDocumentTitle: true,
uiPrefix: '../',
fullScreen: true,
hubs: [
'http://www.biodalliance.org/datasets/testhub/hub.txt',
'http://ftp.ebi.ac.uk/pub/databases/ensembl/encode/integration_data_jan2011/hub.txt',
{url: 'http://vizhub.wustl.edu/VizHub/RoadmapReleaseAll.txt', label: 'Roadmap Epigenome'}
]
});
```
--------------------------------
### Configure Dalliance Browser for Mouse GRCm38
Source: https://github.com/dasmoth/dalliance/blob/master/example-browsers/mouse38.html
Initializes the Dalliance browser with specific settings for the GRCm38 mouse genome. Includes coordinate system details, data sources like genome sequence, gene annotations, and repeat data, along with UI preferences.
```javascript
var b = new Browser({
chr: '19',
viewStart: 30000000,
viewEnd: 30100000,
cookieKey: 'mouse38',
coordSystem: { speciesName: 'Mouse', taxon: 10090, auth: 'GRCm', version: 38, ucscName: 'mm10' },
chains: {
mm9ToMm10: new Chainset('http://www.derkholm.net:8080/das/mm9ToMm10/', 'NCBIM37', 'GRCm38', { speciesName: 'Mouse', taxon: 10090, auth: 'NCBIM', version: 37, ucscName: 'mm9' })
},
sources: [
{name: 'Genome', twoBitURI: 'http://www.biodalliance.org/datasets/GRCm38/mm10.2bit', desc: 'Mouse reference genome build GRCm38', tier_type: 'sequence', provides_entrypoints: true},
{name: 'Genes', desc: 'Gene structures from GENCODE M2', bwgURI: 'http://www.biodalliance.org/datasets/GRCm38/gencodeM2.bb', stylesheet_uri: 'http://www.biodalliance.org/stylesheets/gencode.xml', collapseSuperGroups: true, trixURI: 'http://www.biodalliance.org/datasets/GRCm38/gencodeM2.ix'},
{name: 'Repeats', desc: 'Repeat annotation from UCSC', bwgURI: 'http://www.biodalliance.org/datasets/GRCm38/repeats.bb', stylesheet_uri: 'http://www.biodalliance.org/stylesheets/bb-repeats2.xml'}
],
uiPrefix: '../',
fullScreen: true
});
```
--------------------------------
### Initialize Dalliance Browser for Human GRCh38
Source: https://github.com/dasmoth/dalliance/blob/master/example-browsers/human38.html
Instantiates a Dalliance Browser object with specific configurations for the human GRCh38 genome. This includes setting the chromosome, view range, cookie key, coordinate system details, chain mappings, data sources, and browser links.
```javascript
var b = new Browser({
chr: '22',
viewStart: 30300000,
viewEnd: 30500000,
cookieKey: 'human-grc_h38',
coordSystem: { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: '38', ucscName: 'hg38' },
chains: {
hg19ToHg38: new Chainset('http://www.derkholm.net:8080/das/hg19ToHg38/', 'GRCh37', 'GRCh38', { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: 37, ucscName: 'hg19' })
},
sources: [
{name: 'Genome', twoBitURI: 'http://www.biodalliance.org/datasets/hg38.2bit', tier_type: 'sequence'},
{
name: 'GENCODE',
desc: 'Gene structures from GENCODE 20',
bwgURI: 'http://www.biodalliance.org/datasets/GRCh38/gencode.v20.annotation.bb',
stylesheet_uri: 'http://www.biodalliance.org/stylesheets/gencode2.xml',
collapseSuperGroups: true,
trixURI: 'http://www.biodalliance.org/datasets/GRCh38/gencode.v20.annotation.ix'
},
{
name: 'GENCODEv19',
desc: 'Gene structures from GENCODE 19',
bwgURI: 'http://www.biodalliance.org/datasets/gencode.bb',
stylesheet_uri: 'http://www.biodalliance.org/stylesheets/gencode.xml',
collapseSuperGroups: true,
pennant: 'http://genome.ucsc.edu/images/19.jpg',
trixURI: 'http://www.biodalliance.org/datasets/gene-index.ix',
mapping: 'hg19ToHg38'
},
{
name: 'Repeats',
desc: 'Repeat annotation from UCSC',
bwgURI: 'http://www.biodalliance.org/datasets/GRCh38/repeats.bb',
stylesheet_uri: 'http://www.biodalliance.org/stylesheets/bb-repeats2.xml'
},
{
name: 'SNPs',
tier_type: 'ensembl',
species:'human',
type: 'variation',
disabled: true,
featureInfoPlugin: function(f, info) {
if (f.id) {
info.add('SNP', makeElement('a', f.id, {href: 'http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=' + f.id, target: '_newtab'}));
}
}
}
],
prefix: '../',
fullScreen: true,
browserLinks: {
Ensembl: 'http://www.ensembl.org/Homo_sapiens/Location/View?r=${chr}:${start}-${end}',
UCSC: 'http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg19&position=chr${chr}:${start}-${end}',
Sequence: 'http://www.derkholm.net:8080/das/hg19comp/sequence?segment=${chr}:${start},${end}'
},
hubs: [
'http://ngs.sanger.ac.uk/production/ensembl/regulation/hub.txt',
{url: 'http://ftp.ebi.ac.uk/pub/databases/ensembl/encode/integration_data_jan2011/hub.txt', genome: 'hg19', mapping: 'hg19ToHg38'}
]
});
```
--------------------------------
### Dynamically Manage Tracks
Source: https://context7.com/dasmoth/dalliance/llms.txt
Add or remove tracks at runtime using addTier and removeTier. removeTier can target tracks by name or index, and removeAllTiers clears all tracks.
```javascript
// Add a new BigBed track dynamically
b.addTier({
name: 'New Annotation',
bwgURI: 'http://example.org/new_track.bb',
stylesheet_uri: 'http://example.org/style.xml'
}).then(function(tier) {
console.log('Added tier:', tier.dasSource.name);
});
// Remove a track by its source configuration
b.removeTier({ name: 'New Annotation' });
// Remove a track by its index in the tier array
b.removeTier({ index: 2 });
// Remove all tracks
b.removeAllTiers();
```
--------------------------------
### Listen for Track Lifecycle Events
Source: https://context7.com/dasmoth/dalliance/llms.txt
addTierListener registers a callback that fires when tracks are added, removed, reordered, or otherwise changed. The 'status' string indicates the type of change.
```javascript
b.addTierListener(function(status, tier) {
// status values: 'added', 'removed', 'removedAll', 'reordered', 'selected'
if (status === 'added') {
console.log('Track added:', tier.dasSource.name);
} else if (status === 'removed') {
console.log('Track removed:', tier.dasSource.name);
} else if (status === 'reordered') {
var names = b.tiers.map(function(t) { return t.dasSource.name; });
console.log('New order:', names.join(', '));
}
});
```
--------------------------------
### Create Genome Navigation Link
Source: https://github.com/dasmoth/dalliance/blob/master/hubstub.html
Creates a clickable link for a genome that, when clicked, initializes a Dalliance browser instance focused on the genome's default position. This function is used internally by the init function.
```javascript
var AHUB_REGION_REGEXP = /(\d+)-(\d+)/;
function makeLabelForGenome(genome) {
var a = makeElement('a', genome.description);
a.addEventListener('click', function(ev) {
var reg = AHUB_REGION_REGEXP.exec(genome.defaultPos);
var b = new Browser({
chr: reg[1],
viewStart: reg[2]|0,
viewEnd: reg[3]|0,
noPersist: true,
coordSystem: {speciesName: genome.organism, taxon: genome.orderKey|0, auth: '', version: '', ucscName: genome.genome},
sources: [{name: 'Genome', twoBitURI: relativeURL(genome.absURL, genome.twoBitPath), tier_type: 'sequence'}],
hubs: [document.getElementById('huburl').value]
});
b.realInit();
__dalliance = b;
}, false);
return a;
}
```
--------------------------------
### browser.addFeatureHoverListener(handler, opts)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Registers a callback function for feature hover events. Options can be provided to control the hover behavior, such as immediate response or a delayed response.
```APIDOC
## `browser.addFeatureHoverListener(handler, opts)` — Feature Hover Events
Registers a callback for hover events. Use `{immediate: true}` for instant response on mouse-enter, or omit for a debounced 1-second hover.
### Parameters
- **handler** (function) - The callback function to execute on feature hover. It receives `(ev, feature, allHits, tier)`.
- **ev**: The DOM event object.
- **feature**: The hovered feature object (or null if not hovering a feature).
- **allHits**: An array of all feature objects at the hover location.
- **tier**: The tier object containing the feature.
- **opts** (object, optional) - Options for hover behavior.
- **immediate** (boolean, optional) - If `true`, the handler fires instantly on mouse-enter. Defaults to `false` (debounced).
### Example
```javascript
// Immediate hover (fires instantly on mouse-over)
b.addFeatureHoverListener(function(ev, feature, allHits, tier) {
if (feature) {
document.getElementById('tooltip').textContent = feature.label || feature.id || '';
} else {
document.getElementById('tooltip').textContent = '';
}
}, { immediate: true });
// Deferred hover (fires after ~1s of hovering)
b.addFeatureHoverListener(function(ev, feature, allHits, tier) {
if (feature) {
console.log('User is reading feature:', feature.id);
}
});
```
```
--------------------------------
### browser.addTier(conf) / browser.removeTier(conf)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Dynamically adds or removes tracks (tiers) from the browser after initialization. Tracks can be identified for removal by their configuration object, specifically by name or index.
```APIDOC
## `browser.addTier(conf)` / `browser.removeTier(conf)` — Dynamic Track Management
Adds or removes tracks at runtime after the browser has been initialized.
### `addTier(conf)`
Adds a new track to the browser.
#### Parameters
- **conf** (object) - Configuration object for the track. Must include `name`, `bwgURI`, and `stylesheet_uri`.
#### Returns
A Promise that resolves with the added tier object.
### `removeTier(conf)`
Removes a track from the browser.
#### Parameters
- **conf** (object) - Configuration object for removal. Can specify track by `name` or `index`.
- **name** (string) - The name of the track to remove.
- **index** (integer) - The index of the track to remove.
### Example
```javascript
// Add a new BigBed track dynamically
b.addTier({
name: 'New Annotation',
bwgURI: 'http://example.org/new_track.bb',
stylesheet_uri: 'http://example.org/style.xml'
}).then(function(tier) {
console.log('Added tier:', tier.dasSource.name);
});
// Remove a track by its source configuration
b.removeTier({ name: 'New Annotation' });
// Remove a track by its index in the tier array
b.removeTier({ index: 2 });
```
```
--------------------------------
### Configure a Subtier Renderer
Source: https://github.com/dasmoth/dalliance/blob/master/docs/renderer.md
This configuration defines a subtier to be rendered within a specific multi-tier. It includes the multi-tier ID, vertical offset, and z-index for positioning.
```javascript
{
name: 'Genes',
desc: 'Gene structures from GENCODE M2',
bwgURI: 'http://www.biodalliance.org/datasets/GRCm38/gencodeM2.bb',
stylesheet_uri: 'http://localhost:8000/gencode.xml',
collapseSuperGroups: true,
trixURI: 'http://www.biodalliance.org/datasets/GRCm38/gencodeM2.ix',
renderer: 'sub',
sub: {
multi_id: "multi_1",
offset: 100,
z: 2
}
}
```
--------------------------------
### Register Custom Source Adapters in Dalliance
Source: https://context7.com/dasmoth/dalliance/llms.txt
Extend Dalliance with custom data formats using `registerSourceAdapterFactory`. The factory function configures feature fetching and sequence retrieval for the new format.
```javascript
// As a global function (browser-embedded mode)
window.dalliance_registerSourceAdapterFactory('myformat', function(config) {
return {
features: {
fetch: function(chr, min, max, scale, types, pool, callback) {
// Fetch features for this region
myDataFetcher(config.myDataURL, chr, min, max, function(rawData) {
var features = rawData.map(function(d) {
return {
segment: chr,
min: d.start,
max: d.end,
id: d.name,
label: d.label,
score: d.value,
type: 'mytype'
};
});
callback(null, features);
});
}
}
};
});
// Use it in a source configuration
var b = new Browser({
/* coordSystem, chr, etc. */
sources: [{
name: 'My Custom Track',
tier_type: 'myformat',
myDataURL: 'http://example.org/my-data-api'
}]
});
// As an NPM module
const dalliance = require('dalliance');
dalliance.registerSourceAdapterFactory('myformat', factoryFn);
```
--------------------------------
### Handle Feature Hovers
Source: https://context7.com/dasmoth/dalliance/llms.txt
Use addFeatureHoverListener to register callbacks for hover events. The 'immediate' option controls whether the event fires instantly or after a short delay.
```javascript
// Immediate hover (fires instantly on mouse-over)
b.addFeatureHoverListener(function(ev, feature, allHits, tier) {
if (feature) {
document.getElementById('tooltip').textContent = feature.label || feature.id || '';
} else {
document.getElementById('tooltip').textContent = '';
}
}, { immediate: true });
// Deferred hover (fires after ~1s of hovering)
b.addFeatureHoverListener(function(ev, feature, allHits, tier) {
if (feature) {
console.log('User is reading feature:', feature.id);
}
});
```
--------------------------------
### browser.highlightRegion
Source: https://context7.com/dasmoth/dalliance/llms.txt
Draws a translucent colored highlight overlay on a genomic region in all visible tiers. Highlights can be added individually or in bulk, and all highlights can be cleared using `browser.clearHighlights()`.
```APIDOC
## `browser.highlightRegion(chr, min, max)` — Overlaying Highlights
Draws a translucent colored highlight overlay on a genomic region in all visible tiers.
### Parameters
#### Path Parameters
- **chr** (string) - Required - The chromosome identifier.
- **min** (integer) - Required - The start position of the region.
- **max** (integer) - Required - The end position of the region.
### Request Example
```javascript
// Add a highlight
b.highlightRegion('22', 30010000, 30020000);
// Multiple highlights can be added
b.highlightRegion('22', 30025000, 30030000);
// Remove all highlights
b.clearHighlights();
```
### Initialization Options
Custom highlight appearance can be set at initialization:
```javascript
var b = new Browser({
defaultHighlightFill: 'blue', // CSS color string
defaultHighlightAlpha: 0.2, // Opacity 0-1
/* ... */
});
```
```
--------------------------------
### Load UCSC Track Hubs
Source: https://context7.com/dasmoth/dalliance/llms.txt
Configure the browser to load tracks from UCSC Track Hubs using the `hubs` option. This can be an array of URLs or configuration objects specifying hub details and optional liftover mappings.
```javascript
var b = new Browser({
chr: '22', viewStart: 30000000, viewEnd: 30030000,
coordSystem: { speciesName: 'Human', taxon: 9606, auth: 'GRCh', version: '37', ucscName: 'hg19' },
sources: [/* ... */],
hubs: [
// Simple string URL
'http://www.biodalliance.org/datasets/testhub/hub.txt',
// Object with explicit genome and optional liftover mapping
{
url: 'http://ftp.ebi.ac.uk/pub/databases/ensembl/encode/integration_data_jan2011/hub.txt',
genome: 'hg19',
mapping: 'hg19ToHg38',
label: 'ENCODE Jan 2011'
},
// Named hub with label override
{ url: 'http://vizhub.wustl.edu/VizHub/RoadmapReleaseAll.txt', label: 'Roadmap Epigenome' }
]
});
```
--------------------------------
### browser.setLocation(chr, min, max, callback)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Navigates the browser to a specified genomic region. It automatically handles chromosome name aliasing (with or without 'chr' prefix) and ensures the coordinates are within the chromosome boundaries. An optional callback function can be provided to handle errors or confirm navigation.
```APIDOC
## `browser.setLocation(chr, min, max, callback)` — Programmatic Navigation
Navigates the browser to the specified genomic region. Handles chromosome name aliasing (with/without "chr" prefix) and clamping to chromosome boundaries.
### Parameters
- **chr** (string) - The chromosome name.
- **min** (integer) - The minimum genomic coordinate.
- **max** (integer) - The maximum genomic coordinate.
- **callback** (function, optional) - A function to be called after navigation, receiving an error object if navigation failed.
### Example
```javascript
var b = new Browser({ /* ... */ });
// Navigate to a specific region with a callback
b.setLocation('22', 29000000, 30000000, function(err) {
if (err) {
console.error('Navigation failed:', err);
} else {
console.log('Now viewing chr22:29000000-30000000');
}
});
// Navigate without 'chr' prefix (auto-resolved)
b.setLocation('chr7', 117120000, 117310000);
```
```
--------------------------------
### browser.addTierListener(handler)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Registers a callback function that is triggered when tracks are added, removed, reordered, or their status changes within the browser. The handler receives the status of the change and the affected tier object.
```APIDOC
## `browser.addTierListener(handler)` — Track Lifecycle Events
Fires when tracks are added, removed, reordered, or otherwise changed. The `status` string indicates the type of change.
### Parameters
- **handler** (function) - The callback function to execute on tier changes. It receives `(status, tier)`.
- **status** (string) - Indicates the type of change: 'added', 'removed', 'removedAll', 'reordered', 'selected'.
- **tier** (object) - The tier object affected by the change.
### Example
```javascript
b.addTierListener(function(status, tier) {
// status values: 'added', 'removed', 'removedAll', 'reordered', 'selected'
if (status === 'added') {
console.log('Track added:', tier.dasSource.name);
} else if (status === 'removed') {
console.log('Track removed:', tier.dasSource.name);
} else if (status === 'reordered') {
var names = b.tiers.map(function(t) { return t.dasSource.name; });
console.log('New order:', names.join(', '));
}
});
```
```
--------------------------------
### Handle Feature Clicks
Source: https://context7.com/dasmoth/dalliance/llms.txt
Register a callback with addFeatureListener to execute code when a user clicks on a genomic feature. Returning true from the handler prevents the default popup.
```javascript
b.addFeatureListener(function(ev, feature, allHits, tier) {
console.log('Clicked feature:', feature.id || feature.label);
console.log(' Location: ' + feature.segment + ':' + feature.min + '-' + feature.max);
console.log(' Score:', feature.score);
console.log(' Type:', feature.type);
console.log(' In tier:', tier.dasSource.name);
// Return true to prevent the default popup from showing
return true;
});
// Remove a listener
b.removeFeatureListener(myHandler);
```
--------------------------------
### registerSourceAdapterFactory
Source: https://context7.com/dasmoth/dalliance/llms.txt
Allows for the registration of custom data format adapters. A factory function is provided, which receives a source configuration and must return source objects for features and/or sequences.
```APIDOC
## `registerSourceAdapterFactory(formatName, factoryFn)` — Registering New Data Types
Use `registerSourceAdapterFactory` to add support for custom data formats. The factory function receives the source configuration and must return an object with `features` and/or `sequence` source objects.
### Parameters
#### Path Parameters
- **formatName** (string) - Required - The name of the custom format.
- **factoryFn** (function) - Required - The factory function that creates the source objects.
- The factory function receives a `config` object.
- It must return an object with `features` and/or `sequence` properties.
- `features`: An object with a `fetch` method.
- `fetch(chr, min, max, scale, types, pool, callback)`: Fetches features for a given region.
- `sequence`: An object with a `fetch` method.
- `fetch(chr, min, max, callback)`: Fetches sequence data for a given region.
### Request Example (Global Function)
```javascript
// As a global function (browser-embedded mode)
window.dalliance_registerSourceAdapterFactory('myformat', function(config) {
return {
features: {
fetch: function(chr, min, max, scale, types, pool, callback) {
// Fetch features for this region
myDataFetcher(config.myDataURL, chr, min, max, function(rawData) {
var features = rawData.map(function(d) {
return {
segment: chr,
min: d.start,
max: d.end,
id: d.name,
label: d.label,
score: d.value,
type: 'mytype'
};
});
callback(null, features);
});
}
}
};
});
// Use it in a source configuration
var b = new Browser({
/* coordSystem, chr, etc. */
sources: [{
name: 'My Custom Track',
tier_type: 'myformat',
myDataURL: 'http://example.org/my-data-api'
}]
});
```
### Request Example (NPM Module)
```javascript
// As an NPM module
const dalliance = require('dalliance');
dalliance.registerSourceAdapterFactory('myformat', factoryFn);
```
```
--------------------------------
### Highlight Genomic Regions in Dalliance Browser
Source: https://context7.com/dasmoth/dalliance/llms.txt
Use `highlightRegion` to draw colored overlays on genomic regions. Call `clearHighlights` to remove all overlays. Customize default highlight appearance during browser initialization.
```javascript
// Add a highlight
b.highlightRegion('22', 30010000, 30020000);
// Multiple highlights can be added
b.highlightRegion('22', 30025000, 30030000);
// Remove all highlights
b.clearHighlights();
// Customize highlight appearance at initialization
var b = new Browser({
defaultHighlightFill: 'blue', // CSS color string
defaultHighlightAlpha: 0.2, // Opacity 0-1
/* ... */
});
```
--------------------------------
### browser.addViewListener(handler)
Source: https://context7.com/dasmoth/dalliance/llms.txt
Registers a callback function that is invoked whenever the visible genomic region changes due to panning, zooming, or switching chromosomes. This is useful for synchronizing external UI elements or updating linked views.
```APIDOC
## `browser.addViewListener(handler)` — Viewport Change Events
Fires whenever the visible genomic region changes (pan, zoom, or chromosome change). Useful for syncing external UI elements.
### Parameters
- **handler** (function) - The callback function to execute on view change. It receives `(chr, minFloor, maxFloor, zoomSliderValue, zoomDict, minExact, maxExact)`.
- **chr**: The current chromosome name.
- **minFloor**: The minimum visible coordinate (floored).
- **maxFloor**: The maximum visible coordinate (floored).
- **zoomSliderValue**: The current value of the zoom slider.
- **zoomDict**: An object containing zoom-related information.
- **minExact**: The exact minimum visible coordinate.
- **maxExact**: The exact maximum visible coordinate.
### Example
```javascript
b.addViewListener(function(chr, minFloor, maxFloor, zoomSliderValue, zoomDict, minExact, maxExact) {
// Update an Ensembl link
var ensLink = document.getElementById('enslink');
ensLink.href = 'http://www.ensembl.org/Homo_sapiens/Location/View?r=' +
chr + ':' + minFloor + '-' + maxFloor;
// Log zoom state
console.log('View: ' + chr + ':' + minFloor + '-' + maxFloor);
console.log(' Zoom: ' + zoomDict.current + ' (snap: ' + zoomDict.isSnapZooming + ')');
});
// To remove a listener:
// var myViewHandler = function(...) { ... };
// b.addViewListener(myViewHandler);
// b.removeViewListener(myViewHandler);
```
```
--------------------------------
### Listen for Region Selection
Source: https://context7.com/dasmoth/dalliance/llms.txt
addRegionSelectListener registers a callback that fires when the user drags on the sequence track to select a genomic region. The callback receives the chromosome, minimum, and maximum coordinates of the selection.
```javascript
b.addRegionSelectListener(function(chr, min, max) {
console.log('Selected region: ' + chr + ':' + min + '-' + max);
var length = max - min;
document.getElementById('selectionInfo').textContent =
chr + ':' + min.toLocaleString() + '-' + max.toLocaleString() +
' (' + length.toLocaleString() + ' bp)';
});
```
--------------------------------
### Navigate to Genomic Region
Source: https://context7.com/dasmoth/dalliance/llms.txt
Use setLocation to navigate to a specific genomic region. It handles chromosome name aliasing and boundary clamping. setCenterLocation can be used to center on a position while preserving the current zoom level.
```javascript
var b = new Browser({ /* ... */ });
// Navigate to a specific region
b.setLocation('22', 29000000, 30000000, function(err) {
if (err) {
console.error('Navigation failed:', err);
} else {
console.log('Now viewing chr22:29000000-30000000');
}
});
// Navigate without 'chr' prefix (auto-resolved)
b.setLocation('chr7', 117120000, 117310000);
// Center on a position, preserving current zoom level
b.setCenterLocation('22', 30015000);
```
--------------------------------
### Listen for Viewport Changes
Source: https://context7.com/dasmoth/dalliance/llms.txt
addViewListener registers a callback that fires whenever the visible genomic region changes due to panning, zooming, or chromosome changes. This is useful for syncing external UI elements.
```javascript
b.addViewListener(function(chr, minFloor, maxFloor, zoomSliderValue, zoomDict, minExact, maxExact) {
// Update an Ensembl link
var ensLink = document.getElementById('enslink');
ensLink.href = 'http://www.ensembl.org/Homo_sapiens/Location/View?r=' +
chr + ':' + minFloor + '-' + maxFloor;
// Log zoom state
console.log('View: ' + chr + ':' + minFloor + '-' + maxFloor);
console.log(' Zoom: ' + zoomDict.current + ' (snap: ' + zoomDict.isSnapZooming + ')');
});
// Remove listener
b.removeViewListener(myViewHandler);
```