igv 3.6.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/igv.esm.js CHANGED
@@ -8447,7 +8447,7 @@ function regExpEscape(s) {
8447
8447
  function isGoogleURL(url) {
8448
8448
  return (url.includes("googleapis") && !url.includes("urlshortener")) ||
8449
8449
  isGoogleStorageURL(url) ||
8450
- isGoogleDriveURL(url);
8450
+ isGoogleDriveURL$1(url);
8451
8451
  }
8452
8452
 
8453
8453
  function isGoogleStorageURL(url) {
@@ -8457,7 +8457,7 @@ function isGoogleURL(url) {
8457
8457
  url.startsWith("https://storage.googleapis.com");
8458
8458
  }
8459
8459
 
8460
- function isGoogleDriveURL(url) {
8460
+ function isGoogleDriveURL$1(url) {
8461
8461
  return url.startsWith("https://www.googleapis.com/drive/v3/files");
8462
8462
  }
8463
8463
 
@@ -8610,7 +8610,7 @@ async function getAccessToken(scope) {
8610
8610
  // })
8611
8611
 
8612
8612
  function getScopeForURL(url) {
8613
- if (isGoogleDriveURL(url)) {
8613
+ if (isGoogleDriveURL$1(url)) {
8614
8614
  return "https://www.googleapis.com/auth/drive.file"
8615
8615
  } else if (isGoogleStorageURL(url)) {
8616
8616
  return "https://www.googleapis.com/auth/devstorage.read_only"
@@ -8829,7 +8829,7 @@ class IGVXhr {
8829
8829
  return buffer
8830
8830
  }
8831
8831
  } else {
8832
- if (isGoogleDriveURL(url) || url.startsWith("https://www.dropbox.com")) {
8832
+ if (isGoogleDriveURL$1(url) || url.startsWith("https://www.dropbox.com")) {
8833
8833
  return this.googleThrottle.add(async () => {
8834
8834
  return this._loadURL(url, options)
8835
8835
  })
@@ -8853,7 +8853,7 @@ class IGVXhr {
8853
8853
  options = options || {};
8854
8854
 
8855
8855
  let oauthToken;
8856
- if (isGoogleDriveURL(url)) {
8856
+ if (isGoogleDriveURL$1(url)) {
8857
8857
  // Google drive urls always require oAuth
8858
8858
  oauthToken = await getAccessToken("https://www.googleapis.com/auth/drive.file");
8859
8859
  } else {
@@ -8872,7 +8872,7 @@ class IGVXhr {
8872
8872
  }
8873
8873
  url = addApiKey(url);
8874
8874
 
8875
- if (isGoogleDriveURL(url)) {
8875
+ if (isGoogleDriveURL$1(url)) {
8876
8876
  addTeamDrive(url);
8877
8877
  }
8878
8878
 
@@ -12402,7 +12402,7 @@ for (let p of pairs) {
12402
12402
  complements.set(p2.toLowerCase(), p1.toLowerCase());
12403
12403
  }
12404
12404
 
12405
- function complementBase(base) {
12405
+ function complementBase$1(base) {
12406
12406
  return complements.has(base) ? complements.get(base) : base
12407
12407
  }
12408
12408
 
@@ -16987,6 +16987,35 @@ function findFeatureAfterCenter(featureList, center, direction = true) {
16987
16987
  return sortedList[low]
16988
16988
  }
16989
16989
 
16990
+ /**
16991
+ * Utilities for detecting problematic resources (local files, Google Drive URLs)
16992
+ * that cannot be reliably loaded when a session is shared or restored.
16993
+ */
16994
+
16995
+ /**
16996
+ * Check if an object is a local File instance
16997
+ * @param {*} obj - The object to check
16998
+ * @returns {boolean} True if the object is a File instance
16999
+ */
17000
+ function isLocalFile(obj) {
17001
+ return obj instanceof File
17002
+ }
17003
+
17004
+ /**
17005
+ * Check if a URL is a Google Drive URL
17006
+ * Google Drive URLs require authentication and will not work when shared.
17007
+ *
17008
+ * @param {string|*} url - The URL to check
17009
+ * @returns {boolean} True if the URL is a Google Drive URL
17010
+ */
17011
+ function isGoogleDriveURL(url) {
17012
+ if (typeof url !== 'string') {
17013
+ return false
17014
+ }
17015
+ // Match both googleapis.com/drive and drive.google.com URLs
17016
+ return url.includes('googleapis.com/drive') || url.includes('drive.google.com')
17017
+ }
17018
+
16990
17019
  const fixColor = (colorString) => {
16991
17020
  if (isString$3(colorString)) {
16992
17021
  return (colorString.indexOf(",") > 0 && !(colorString.startsWith("rgb(") || colorString.startsWith("rgba("))) ?
@@ -17611,7 +17640,20 @@ class TrackBase {
17611
17640
  }
17612
17641
  }
17613
17642
 
17614
- static localFileInspection(config) {
17643
+ /**
17644
+ * Prepare a track configuration for session serialization by identifying and marking
17645
+ * problematic resources (local files).
17646
+ *
17647
+ * Local files are converted to {file: filename} or {indexFile: filename}
17648
+ * Google Drive URLs are kept in the url/indexURL fields as-is and detected when loading
17649
+ *
17650
+ * This allows the configuration to be serialized while preserving information
17651
+ * about resources that cannot be automatically loaded when the session is restored.
17652
+ *
17653
+ * @param {Object} config - Track configuration to prepare
17654
+ * @returns {Object} Cleaned configuration with problematic resources marked
17655
+ */
17656
+ static prepareConfigForSession(config) {
17615
17657
 
17616
17658
  const cooked = Object.assign({}, config);
17617
17659
  const lut =
@@ -17620,8 +17662,9 @@ class TrackBase {
17620
17662
  indexURL: 'indexFile'
17621
17663
  };
17622
17664
 
17665
+ // Check for local File objects and convert to filename strings
17623
17666
  for (const key of ['url', 'indexURL']) {
17624
- if (cooked[key] && cooked[key] instanceof File) {
17667
+ if (cooked[key] && isLocalFile(cooked[key])) {
17625
17668
  cooked[lut[key]] = cooked[key].name;
17626
17669
  delete cooked[key];
17627
17670
  }
@@ -17631,8 +17674,6 @@ class TrackBase {
17631
17674
  }
17632
17675
 
17633
17676
  // Methods to support filtering api
17634
-
17635
-
17636
17677
  set filter(f) {
17637
17678
  this._filter = f;
17638
17679
  this.trackView.repaintViews();
@@ -35100,14 +35141,21 @@ function getExonPhase(exon) {
35100
35141
  return (3 - exon.readingFrame) % 3
35101
35142
  }
35102
35143
 
35103
- function getEonStart(exon) {
35144
+ function getCodingStart(exon) {
35104
35145
  return exon.cdStart || exon.start
35105
35146
  }
35106
35147
 
35107
- function getExonEnd(exon) {
35148
+ function getCodingEnd(exon) {
35108
35149
  return exon.cdEnd || exon.end
35109
35150
  }
35110
35151
 
35152
+ function getCodingLength(exon) {
35153
+ if (exon.utr) return 0
35154
+ const start = exon.cdStart || exon.start;
35155
+ const end = exon.cdEnd || exon.end;
35156
+ return end - start
35157
+ }
35158
+
35111
35159
  const aminoAcidSequenceRenderThreshold = 0.25;
35112
35160
 
35113
35161
  /**
@@ -35356,8 +35404,8 @@ function renderAminoAcidSequence(ctx, strand, leftExon, exon, riteExon, bpStart,
35356
35404
  };
35357
35405
 
35358
35406
  const phase = getExonPhase(exon);
35359
- let ss = getEonStart(exon);
35360
- let ee = getExonEnd(exon);
35407
+ let ss = getCodingStart(exon);
35408
+ let ee = getCodingEnd(exon);
35361
35409
 
35362
35410
  let bpTripletStart;
35363
35411
  let bpTripletEnd;
@@ -35526,7 +35574,7 @@ function getAminoAcidLetterWithExonGap(strand, phase, phaseExtentStart, phaseExt
35526
35574
  return undefined
35527
35575
  }
35528
35576
 
35529
- [ss, ee] = [getExonEnd(leftExon) - (3 - phase), getExonEnd(leftExon)];
35577
+ [ss, ee] = [getCodingEnd(leftExon) - (3 - phase), getCodingEnd(leftExon)];
35530
35578
  stringA = sequenceInterval.getSequence(ss, ee);
35531
35579
 
35532
35580
  if (!stringA) {
@@ -35545,7 +35593,7 @@ function getAminoAcidLetterWithExonGap(strand, phase, phaseExtentStart, phaseExt
35545
35593
  }
35546
35594
 
35547
35595
  const ritePhase = getExonPhase(riteExon);
35548
- const riteStart = getEonStart(riteExon);
35596
+ const riteStart = getCodingStart(riteExon);
35549
35597
  stringB = sequenceInterval.getSequence(riteStart, riteStart + ritePhase);
35550
35598
 
35551
35599
  if (!stringB) {
@@ -35565,7 +35613,7 @@ function getAminoAcidLetterWithExonGap(strand, phase, phaseExtentStart, phaseExt
35565
35613
  return undefined
35566
35614
  }
35567
35615
 
35568
- [ss, ee] = [getEonStart(riteExon), getEonStart(riteExon) + (3 - phase)];
35616
+ [ss, ee] = [getCodingStart(riteExon), getCodingStart(riteExon) + (3 - phase)];
35569
35617
  stringB = sequenceInterval.getSequence(ss, ee);
35570
35618
 
35571
35619
  if (!stringB) {
@@ -35585,7 +35633,7 @@ function getAminoAcidLetterWithExonGap(strand, phase, phaseExtentStart, phaseExt
35585
35633
  }
35586
35634
 
35587
35635
  const leftPhase = getExonPhase(leftExon);
35588
- const leftEnd = getExonEnd(leftExon);
35636
+ const leftEnd = getCodingEnd(leftExon);
35589
35637
  stringA = sequenceInterval.getSequence(leftEnd - leftPhase, leftEnd);
35590
35638
 
35591
35639
  if (!stringA) {
@@ -39013,7 +39061,7 @@ class TrackDbHub {
39013
39061
 
39014
39062
  const isContainer = (s.hasOwnProperty("superTrack") && !s.hasOwnProperty("bigDataUrl")) ||
39015
39063
  s.hasOwnProperty("compositeTrack") || s.hasOwnProperty("view") ||
39016
- (s.hasOwnProperty("container") && s.getOwnProperty("container").equals("multiWig"));
39064
+ (s.hasOwnProperty("container") && (s.getOwnProperty("container") === "multiWig"));
39017
39065
 
39018
39066
  // Find parent, if any. "group" containers can be implicit, all other types should be explicitly
39019
39067
  // defined before their children
@@ -40789,9 +40837,9 @@ class TrackViewport extends Viewport {
40789
40837
 
40790
40838
  if (typeof this.trackView.track.popupData === "function") {
40791
40839
 
40792
- popupTimerID = setTimeout(() => {
40840
+ popupTimerID = setTimeout(async () => {
40793
40841
 
40794
- const content = this.handleTrackClick(event);
40842
+ const content = await this.handleTrackClick(event);
40795
40843
  if (content) {
40796
40844
 
40797
40845
  if (false === event.shiftKey) {
@@ -40956,7 +41004,7 @@ class TrackViewport extends Viewport {
40956
41004
 
40957
41005
  }
40958
41006
 
40959
- handleTrackClick(event) {
41007
+ async handleTrackClick(event) {
40960
41008
 
40961
41009
  const clickState = this.createClickState(event);
40962
41010
 
@@ -40965,7 +41013,7 @@ class TrackViewport extends Viewport {
40965
41013
  }
40966
41014
 
40967
41015
  let track = this.trackView.track;
40968
- const dataList = track.popupData(clickState);
41016
+ const dataList = await track.popupData(clickState);
40969
41017
 
40970
41018
  const popupClickHandlerResult = this.browser.fireEvent('trackclick', [track, dataList, clickState.genomicLocation]);
40971
41019
 
@@ -47435,7 +47483,7 @@ class BaseModificationKey {
47435
47483
  this.base = base;
47436
47484
  this.strand = strand;
47437
47485
  this.modification = modification;
47438
- this.canonicalBase = this.strand === '+' ? this.base : complementBase(this.base);
47486
+ this.canonicalBase = this.strand === '+' ? this.base : complementBase$1(this.base);
47439
47487
  }
47440
47488
 
47441
47489
  getCanonicalBase() {
@@ -47485,7 +47533,7 @@ class BaseModificationSet {
47485
47533
  this.modification = modification;
47486
47534
  this.strand = strand;
47487
47535
  this.likelihoods = likelihoods;
47488
- this.canonicalBase = this.strand == '+' ? this.base : complementBase(this.base);
47536
+ this.canonicalBase = this.strand == '+' ? this.base : complementBase$1(this.base);
47489
47537
  this.key = BaseModificationKey.getKey(base, strand, modification);
47490
47538
  }
47491
47539
 
@@ -48918,6 +48966,818 @@ function computeLengthOnReference(cigarString) {
48918
48966
  return len
48919
48967
  }
48920
48968
 
48969
+ // Lazy import to avoid circular dependency
48970
+
48971
+ /**
48972
+ * Search for a feature by name across various data sources
48973
+ * This module is separate to avoid circular dependencies between search.js and hgvs.js
48974
+ */
48975
+
48976
+ const DEFAULT_SEARCH_CONFIG = {
48977
+ timeout: 5000,
48978
+ type: "plain",
48979
+ url: 'https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$',
48980
+ coords: 0
48981
+ };
48982
+
48983
+ /**
48984
+ * Search for a feature by name in MANE transcripts, searchable tracks, and web services
48985
+ * @param {Object} browser - The IGV browser instance
48986
+ * @param {string} name - The feature name to search for
48987
+ * @returns {Promise<Object|undefined>} The found feature or undefined
48988
+ */
48989
+ async function searchFeatures(browser, name) {
48990
+
48991
+ const searchConfig = browser.searchConfig || DEFAULT_SEARCH_CONFIG;
48992
+ let feature;
48993
+
48994
+ name = name.toUpperCase();
48995
+
48996
+ // Search MANE transcripts first, if available
48997
+ feature = await browser.genome.getManeTranscript(name);
48998
+ if (feature) {
48999
+ return feature
49000
+ }
49001
+
49002
+ const searchableTracks = browser.tracks.filter(t => t.searchable);
49003
+ for (let track of searchableTracks) {
49004
+ const feature = await track.search(name);
49005
+ if (feature) {
49006
+ return feature
49007
+ }
49008
+ }
49009
+
49010
+ // If still not found try webservice, if enabled
49011
+ if (browser.config && false !== browser.config.search) {
49012
+ try {
49013
+ feature = await searchWebService(browser, name, searchConfig);
49014
+ return feature // Might be undefined
49015
+ } catch (error) {
49016
+ console.log("Search service not available " + error);
49017
+ }
49018
+ }
49019
+
49020
+ }
49021
+
49022
+ /**
49023
+ * Search for a feature using a web service
49024
+ * @param {Object} browser - The IGV browser instance
49025
+ * @param {string} locus - The locus to search for
49026
+ * @param {Object} searchConfig - Search configuration
49027
+ * @returns {Promise<Object|undefined>} The search result
49028
+ */
49029
+ async function searchWebService(browser, locus, searchConfig) {
49030
+
49031
+ let path = searchConfig.url.replace("$FEATURE$", locus.toUpperCase());
49032
+ if (path.indexOf("$GENOME$") > -1) {
49033
+ path = path.replace("$GENOME$", (browser.genome.id ? browser.genome.id : "hg19"));
49034
+ }
49035
+ const options = searchConfig.timeout ? {timeout: searchConfig.timeout} : undefined;
49036
+ const result = await igvxhr.loadString(path, options);
49037
+
49038
+ return await processSearchResult(browser, result, searchConfig)
49039
+ }
49040
+
49041
+ /**
49042
+ * Process search results from web service
49043
+ * @param {Object} browser - The IGV browser instance
49044
+ * @param {string} result - The raw result from the web service
49045
+ * @param {Object} searchConfig - Search configuration
49046
+ * @returns {Promise<Object|undefined>} The processed search result
49047
+ */
49048
+ async function processSearchResult(browser, result, searchConfig) {
49049
+
49050
+ let results;
49051
+
49052
+ if ('plain' === searchConfig.type) {
49053
+ results = await parseSearchResults(browser, result);
49054
+ } else {
49055
+ results = JSON.parse(result);
49056
+ }
49057
+
49058
+ if (searchConfig.resultsField) {
49059
+ results = results[searchConfig.resultsField];
49060
+ }
49061
+
49062
+ if (!results || 0 === results.length) {
49063
+ return undefined
49064
+
49065
+ } else {
49066
+
49067
+ const chromosomeField = searchConfig.chromosomeField || "chromosome";
49068
+ const startField = searchConfig.startField || "start";
49069
+ const endField = searchConfig.endField || "end";
49070
+ const coords = searchConfig.coords || 1;
49071
+
49072
+
49073
+ let result;
49074
+ if (Array.isArray(results)) {
49075
+ // Ignoring all but first result for now
49076
+ // TODO -- present all and let user select if results.length > 1
49077
+ result = results[0];
49078
+ } else {
49079
+ // When processing search results from Ensembl REST API
49080
+ // Example: https://rest.ensembl.org/lookup/symbol/macaca_fascicularis/BRCA2?content-type=application/json
49081
+ result = results;
49082
+ }
49083
+
49084
+ if (!(result.hasOwnProperty(chromosomeField) && (result.hasOwnProperty(startField)))) {
49085
+ console.error("Search service results must include chromosome and start fields: " + result);
49086
+ }
49087
+
49088
+ const chr = result[chromosomeField];
49089
+ let start = result[startField] - coords;
49090
+ let end = result[endField];
49091
+ if (undefined === end) {
49092
+ end = start + 1;
49093
+ }
49094
+
49095
+ const locusObject = {chr, start, end};
49096
+
49097
+ // Some GTEX hacks
49098
+ if (searchConfig.geneField && searchConfig.snpField) {
49099
+ const name = result[searchConfig.geneField] || result[searchConfig.snpField]; // Should never have both
49100
+ if (name) locusObject.name = name.toUpperCase();
49101
+ }
49102
+
49103
+ return locusObject
49104
+ }
49105
+ }
49106
+
49107
+ /**
49108
+ * Parse the igv line-oriented (non json) search results.
49109
+ * NOTE: currently, and probably permanently, this will always be a single line
49110
+ * Example
49111
+ * EGFR chr7:55,086,724-55,275,031 refseq
49112
+ *
49113
+ * @param {Object} browser - The IGV browser instance
49114
+ * @param {string} data - The raw search result data
49115
+ * @returns {Array} Array of parsed search results
49116
+ */
49117
+ async function parseSearchResults(browser, data) {
49118
+
49119
+ const results = [];
49120
+ const lines = splitLines$3(data);
49121
+
49122
+ for (let line of lines) {
49123
+
49124
+ const tokens = line.split("\t");
49125
+
49126
+ if (tokens.length >= 3) {
49127
+ const locusTokens = tokens[1].split(":");
49128
+ const rangeTokens = locusTokens[1].split("-");
49129
+ results.push({
49130
+ chromosome: browser.genome.getChromosomeName(locusTokens[0].trim()),
49131
+ start: parseInt(rangeTokens[0].replace(/,/g, '')),
49132
+ end: parseInt(rangeTokens[1].replace(/,/g, '')),
49133
+ name: tokens[0].toUpperCase()
49134
+ });
49135
+ }
49136
+ }
49137
+
49138
+ return results
49139
+
49140
+ }
49141
+
49142
+ const log = console;
49143
+
49144
+ function isValidHGVS(notation) {
49145
+ if (!notation) return false
49146
+ // We only need to validate that we can parse the notation in the search method.
49147
+ // Check for basic structure: <accession>:g.<position> or <accession>:c.<position> or <accession>:p.<position>
49148
+ // We don't validate the variant details since we only need the position for searching.
49149
+
49150
+ // Genomic: g.\d+ (with optional range and anything after)
49151
+ const genomic = "g\\.\\d+.*";
49152
+ // Coding: c. followed by optional -, *, then digits, with optional intronic offset and anything after
49153
+ const coding = "c\\.[-*]?\\d+.*";
49154
+ // Non-coding: n. followed by optional leading '-' then digits, anything after
49155
+ const nonCoding = "n\\.-?\\d+.*";
49156
+ // Protein: p. followed by optional AA letters, digits, with optional range and anything after
49157
+ const protein = "p\\.[A-Za-z*]*\\d+.*";
49158
+ // Optional gene symbol in parentheses immediately after accession
49159
+ const accessionWithOptionalGene = "^[A-Za-z0-9_.]+(?:\\([^)]+\\))?";
49160
+
49161
+ const pattern = new RegExp(accessionWithOptionalGene + ":(?:" + genomic + "|" + coding + "|" + nonCoding + "|" + protein + ")$");
49162
+ return pattern.test(notation)
49163
+ }
49164
+
49165
+ /**
49166
+ * Searches for the given HGVS notation in the provided genome.
49167
+ * Returns a SearchResult with the corresponding chromosome and position if found,
49168
+ * otherwise returns null.
49169
+ */
49170
+ async function search$1(hgvs, browser) {
49171
+
49172
+ if (!isValidHGVS(hgvs)) {
49173
+ return null
49174
+ }
49175
+
49176
+ const genome = browser.genome;
49177
+
49178
+ // Determine type and extract accession and position
49179
+ const idxG = hgvs.indexOf(":g.");
49180
+ const idxC = hgvs.indexOf(":c.");
49181
+ const idxP = hgvs.indexOf(":p.");
49182
+ const idxN = hgvs.indexOf(":n.");
49183
+ let type;
49184
+ let idx;
49185
+ if (idxG >= 0) {
49186
+ type = "g";
49187
+ idx = idxG;
49188
+ } else if (idxC >= 0) {
49189
+ type = "c";
49190
+ idx = idxC;
49191
+ } else if (idxN >= 0) {
49192
+ type = "n";
49193
+ idx = idxN;
49194
+ } else if (idxP >= 0) {
49195
+ type = "p";
49196
+ idx = idxP;
49197
+ } else {
49198
+ return null
49199
+ }
49200
+ let accession = hgvs.substring(0, idx);
49201
+ // Strip optional trailing gene symbol in parentheses, e.g., "NM_000302.3(PLOD1)" -> "NM_000302.3"
49202
+ if (accession.endsWith(")")) {
49203
+ const openIdx = accession.lastIndexOf('(');
49204
+ if (openIdx > 0) {
49205
+ accession = accession.substring(0, openIdx);
49206
+ }
49207
+ }
49208
+ const positionPart = hgvs.substring(idx + 3); // skip ':g.' or ':c.' or ':p.'
49209
+
49210
+ if (type === "g") {
49211
+ if (!positionPart) return null
49212
+ // Match genomic positions including:
49213
+ // - Simple position: 123
49214
+ // - Range: 123_456
49215
+ // - Uncertain positions: 123_? or ?_456 or (123_456)
49216
+ // Extract just the numeric positions, ignoring variant notation after
49217
+ const match = positionPart.match(/^\(?(\d+)(?:_(\d+|\?))?/);
49218
+ if (!match) return null
49219
+ const start = parseInt(match[1], 10);
49220
+ const endGroup = match[2];
49221
+ // If end is '?' or undefined, use start as end
49222
+ const end = (endGroup && endGroup !== '?') ? parseInt(endGroup, 10) : start;
49223
+ const aliasRecord = await genome.getAliasRecord(accession);
49224
+ const chr = aliasRecord ? aliasRecord.chr : accession;
49225
+ return {chr, start: start - 1, end: end}
49226
+
49227
+ } else if (type === "p") {
49228
+
49229
+ // Protein notation not supported for search currently. The code below is ported from Java and kept for
49230
+ // future reference.
49231
+ return null
49232
+
49233
+ // // Protein position mapping: map codon(s) to genomic span.
49234
+ // const transcript = await getTranscript(browser, accession)
49235
+ // if (!transcript) return null
49236
+ //
49237
+ // const proteinPart = positionPart
49238
+ // const pm = proteinPart.match(/^[A-Za-z*]{0,3}(\d+)(?:_[A-Za-z*]{0,3}(\d+))?/)
49239
+ // if (!pm) return null
49240
+ // let p1 = parseInt(pm[1], 10)
49241
+ // const p2Str = pm[2]
49242
+ // let p2 = p1
49243
+ // if (p2Str) {
49244
+ // p2 = parseInt(p2Str, 10)
49245
+ // }
49246
+ //
49247
+ // const codon1 = transcript.getCodon(genome, transcript.chr, p1)
49248
+ // if (!codon1 || !codon1.isGenomePositionsSet()) return null
49249
+ // let start1 = Math.min(...codon1.getGenomePositions())
49250
+ // let end1 = Math.max(...codon1.getGenomePositions())
49251
+ //
49252
+ // let regionStart = start1
49253
+ // let regionEnd = end1
49254
+ // if (p2 !== p1) {
49255
+ // const codon2 = transcript.getCodon(genome, transcript.chr, p2)
49256
+ // if (!codon2 || !codon2.isGenomePositionsSet()) return null
49257
+ // let start2 = Math.min(...codon2.getGenomePositions())
49258
+ // let end2 = Math.max(...codon2.getGenomePositions())
49259
+ // regionStart = Math.min(start1, start2)
49260
+ // regionEnd = Math.max(end1, end2)
49261
+ // }
49262
+ // const halfOpenEnd = regionEnd + 1
49263
+ // return {chr: transcript.chr, start: regionStart, end: halfOpenEnd}
49264
+
49265
+ } else if (type === "n") {
49266
+
49267
+ // Non-coding transcript mapping: n.123 or n.-123 maps relative to transcript start
49268
+ const transcript = await getTranscript(browser, accession);
49269
+ if (!transcript) return null
49270
+
49271
+ // Parse signed position with optional range and intronic offset (e.g., n.123, n.123_456, n.-7080_-1781, n.123+5)
49272
+ const matcher = positionPart.match(/^(-?\d+)(?:_(-?\d+))?([+-]\d+)?/);
49273
+ if (!matcher) return null
49274
+
49275
+ const t1 = parseInt(matcher[1], 10);
49276
+ const t2Str = matcher[2];
49277
+ const t2 = t2Str != null ? parseInt(t2Str, 10) : t1;
49278
+
49279
+ // Map both transcript positions to genomic
49280
+ let g1 = transcriptPositionToGenomicPosition(transcript, t1);
49281
+ let g2 = transcriptPositionToGenomicPosition(transcript, t2);
49282
+ if (g1 <= 0 || g2 <= 0) return null
49283
+
49284
+ // Apply intronic offset (if any) to BOTH endpoints, strand-aware
49285
+ const offsetStr = matcher[3];
49286
+ if (offsetStr) {
49287
+ let offset = parseInt(offsetStr, 10);
49288
+ if (transcript.strand === '-') offset = -offset;
49289
+ g1 += offset;
49290
+ g2 += offset;
49291
+ }
49292
+
49293
+ // Normalize to genomic span regardless of strand
49294
+ const regionStart = Math.min(g1, g2);
49295
+ const regionEndInclusive = Math.max(g1, g2);
49296
+ const halfOpenEnd = regionEndInclusive + 1;
49297
+ return {chr: transcript.chr, start: regionStart, end: halfOpenEnd}
49298
+
49299
+ } else { // "c"
49300
+
49301
+ const transcript = await getTranscript(browser, accession);
49302
+ if (transcript) {
49303
+ // UTR 5' c.-N with optional range and intronic offset (e.g., c.-211_-215 or c.-211-1058C>G)
49304
+ const utr5Matcher = positionPart.match(/^-(\d+)(?:_-(\d+))?([+-]\d+)?/);
49305
+ if (utr5Matcher) {
49306
+ const n1 = parseInt(utr5Matcher[1], 10);
49307
+ const n2Str = utr5Matcher[2];
49308
+ const n2 = n2Str != null ? parseInt(n2Str, 10) : null;
49309
+ const firstCodingGenomic = codingToGenomePosition(transcript, 1);
49310
+ if (firstCodingGenomic > 0) {
49311
+ let g1 = transcript.strand === '+' ? (firstCodingGenomic - n1) : (firstCodingGenomic + n1);
49312
+ let g2 = g1;
49313
+ if (n2 != null) {
49314
+ g2 = transcript.strand === '+' ? (firstCodingGenomic - n2) : (firstCodingGenomic + n2);
49315
+ }
49316
+ // Apply intronic offset (single value) to both ends if present
49317
+ const offsetStr = utr5Matcher[3];
49318
+ if (offsetStr) {
49319
+ let offset = parseInt(offsetStr, 10);
49320
+ if (transcript.strand === '-') offset = -offset;
49321
+ g1 += offset;
49322
+ g2 += offset;
49323
+ }
49324
+ const start = Math.min(g1, g2);
49325
+ const endInclusive = Math.max(g1, g2);
49326
+ const endExclusive = endInclusive + 1;
49327
+ return {resultType: "LOCUS", chr: transcript.chr, start, end: endExclusive}
49328
+ }
49329
+ return null
49330
+ }
49331
+
49332
+ // UTR 3' c.*N with optional range and intronic offset (e.g., c.*526_*529delATCA or c.*123+45)
49333
+ const utr3Matcher = positionPart.match(/^\*(\d+)(?:_\*(\d+))?([+-]\d+)?/);
49334
+ if (utr3Matcher) {
49335
+ const n1 = parseInt(utr3Matcher[1], 10);
49336
+ const n2Str = utr3Matcher[2];
49337
+ const n2 = n2Str != null ? parseInt(n2Str, 10) : null;
49338
+ let codingLen = 0;
49339
+ if (transcript.exons) {
49340
+ for (const exon of transcript.exons) {
49341
+ codingLen += getCodingLength(exon);
49342
+ }
49343
+ }
49344
+ if (codingLen > 0) {
49345
+ const lastCodingGenomic = codingToGenomePosition(transcript, codingLen);
49346
+ if (lastCodingGenomic > 0) {
49347
+ let g1 = transcript.strand === '+' ? (lastCodingGenomic + n1) : (lastCodingGenomic - n1);
49348
+ let g2 = g1;
49349
+ if (n2 != null) {
49350
+ g2 = transcript.strand === '+' ? (lastCodingGenomic + n2) : (lastCodingGenomic - n2);
49351
+ }
49352
+ // Apply intronic offset (single value) to both ends if present
49353
+ const offsetStr = utr3Matcher[3];
49354
+ if (offsetStr) {
49355
+ let offset = parseInt(offsetStr, 10);
49356
+ if (transcript.strand === '-') offset = -offset;
49357
+ g1 += offset;
49358
+ g2 += offset;
49359
+ }
49360
+ const start = Math.min(g1, g2);
49361
+ const endInclusive = Math.max(g1, g2);
49362
+ const endExclusive = endInclusive + 1;
49363
+ return {resultType: "LOCUS", chr: transcript.chr, start, end: endExclusive}
49364
+ }
49365
+ }
49366
+ return null
49367
+ }
49368
+
49369
+ // CDS position with optional range
49370
+ // First parse endpoints c.X(_Y)? ignoring intronic offsets
49371
+ const cpos = positionPart.match(/^(\d+)(?:_(\d+))?/);
49372
+ if (!cpos) return null
49373
+ const c1 = parseInt(cpos[1], 10);
49374
+ const c2Str = cpos[2];
49375
+ const c2 = c2Str != null ? parseInt(c2Str, 10) : c1;
49376
+
49377
+ // Map both coding positions to genomic
49378
+ let g1 = codingToGenomePosition(transcript, c1);
49379
+ let g2 = codingToGenomePosition(transcript, c2);
49380
+ if (g1 <= 0 || g2 <= 0) return null
49381
+
49382
+ // Now parse optional intronic offsets for each endpoint separately
49383
+ // Patterns like: 123+5 or 123-2 at the beginning, optionally followed by _ and second with offset
49384
+ const offs = positionPart.match(/^(\d+)([+-]\d+)?(?:_(\d+)([+-]\d+)?)?/);
49385
+ if (offs) {
49386
+ const off1Str = offs[2];
49387
+ const off2Str = offs[4];
49388
+ if (off1Str) {
49389
+ let off1 = parseInt(off1Str, 10);
49390
+ if (transcript.strand === '-') off1 = -off1;
49391
+ g1 += off1;
49392
+ }
49393
+ if (off2Str) {
49394
+ let off2 = parseInt(off2Str, 10);
49395
+ if (transcript.strand === '-') off2 = -off2;
49396
+ g2 += off2;
49397
+ }
49398
+ }
49399
+
49400
+ // If there is no explicit second coding position, ensure single-site locus
49401
+ if (c2Str == null) {
49402
+ g2 = g1;
49403
+ }
49404
+
49405
+ const start = Math.min(g1, g2);
49406
+ const endInclusive = Math.max(g1, g2);
49407
+ const endExclusive = endInclusive + 1;
49408
+ return {chr: transcript.chr, start, end: endExclusive}
49409
+ }
49410
+ return null
49411
+ }
49412
+
49413
+ }
49414
+
49415
+ async function getTranscript(browser, accession) {
49416
+ return searchFeatures(browser, accession)
49417
+ }
49418
+
49419
+ /**
49420
+ * Convert a transcript position (1-based, from transcription start) to genomic position
49421
+ * for non-coding transcripts. Walks through exons to find the genomic coordinate.
49422
+ */
49423
+ function transcriptPositionToGenomicPosition(transcript, transcriptPos) {
49424
+ // Handle positions upstream of transcript start (negative n. values)
49425
+ if (transcriptPos <= 0) {
49426
+ const d = Math.abs(transcriptPos);
49427
+ return transcript.strand === '+' ? (transcript.getStart() - d) : (transcript.getEnd() + d)
49428
+ }
49429
+
49430
+ const exons = transcript.exons;
49431
+ if (!exons || exons.length === 0) {
49432
+ // No exons, treat as simple feature
49433
+ if (transcript.strand === '+') {
49434
+ return transcript.getStart() + transcriptPos - 1
49435
+ } else {
49436
+ return transcript.getEnd() - transcriptPos + 1
49437
+ }
49438
+ }
49439
+
49440
+ const positive = transcript.strand === '+';
49441
+ let accumulatedLength = 0;
49442
+
49443
+ // Sort exons appropriately based on strand
49444
+ const sortedExons = exons.slice();
49445
+ if (!positive) {
49446
+ sortedExons.sort((e1, e2) => e2.getStart() - e1.getStart());
49447
+ } else {
49448
+ sortedExons.sort((e1, e2) => e1.getStart() - e2.getStart());
49449
+ }
49450
+
49451
+ for (const exon of sortedExons) {
49452
+ const exonLength = exon.getEnd() - exon.getStart();
49453
+ if (accumulatedLength + exonLength >= transcriptPos) {
49454
+ // Position is in this exon
49455
+ const offsetInExon = transcriptPos - accumulatedLength - 1;
49456
+ if (positive) {
49457
+ return exon.getStart() + offsetInExon
49458
+ } else {
49459
+ return exon.getEnd() - offsetInExon - 1
49460
+ }
49461
+ }
49462
+ accumulatedLength += exonLength;
49463
+ }
49464
+
49465
+ // Position beyond transcript end
49466
+ return -1
49467
+ }
49468
+
49469
+ /**
49470
+ * Translate a 1-based coding position to a 0-based genomic position. Supports HGVS parsing
49471
+ *
49472
+ * @param codingPosition 1-based coding position
49473
+ * @return 0-based genomic position, or -1 if not found.
49474
+ */
49475
+ function codingToGenomePosition(feature, codingPosition) {
49476
+ if (codingPosition <= 0) {
49477
+ return -1
49478
+ }
49479
+ const cdna = codingPosition - 1; // Convert to 0-based
49480
+
49481
+ const exons = feature.exons;
49482
+ if (!exons) {
49483
+ return -1
49484
+ }
49485
+
49486
+ const strand = feature.strand;
49487
+ // if (strand === 'NONE') {
49488
+ // throw new Error("Cannot translate from coding position on an unstranded feature.")
49489
+ // }
49490
+ const positive = strand === '+';
49491
+
49492
+ let codingLength = 0;
49493
+ for (let i = 0; i < exons.length; i++) {
49494
+ const exon = positive ? exons[i] : exons[exons.length - 1 - i];
49495
+ const exonCodingLength = getCodingLength(exon);
49496
+ if (codingLength + exonCodingLength > cdna) {
49497
+ const cdnaOffset = cdna - codingLength;
49498
+ if (positive) {
49499
+ return getCodingStart(exon) + cdnaOffset
49500
+ } else {
49501
+ return getCodingEnd(exon) - 1 - cdnaOffset
49502
+ }
49503
+ }
49504
+ codingLength += exonCodingLength;
49505
+ }
49506
+
49507
+ return -1
49508
+ }
49509
+
49510
+ /**
49511
+ * Returns genomic HGVS notation: <RefSeqAccession>:g.<position>
49512
+ * Example: NC_000001.11:g.1234567
49513
+ */
49514
+ async function getHGVSPosition(genome, chr, position) {
49515
+ try {
49516
+ const aliasRecord = await genome.getAliasRecord(chr);
49517
+ let accession = null;
49518
+
49519
+ if (aliasRecord) {
49520
+ for (const alias of Object.values(aliasRecord)) {
49521
+ if (alias.startsWith("NC_") || alias.startsWith("NT_") || alias.startsWith("NW_") ||
49522
+ alias.startsWith("NG_") || alias.startsWith("NM_") || alias.startsWith("NR_") ||
49523
+ alias.startsWith("NP_")) {
49524
+ accession = alias;
49525
+ break
49526
+ }
49527
+ }
49528
+ }
49529
+
49530
+ if (!accession) {
49531
+ accession = chr;
49532
+ }
49533
+
49534
+ return `${accession}:g.${position}`
49535
+ } catch (e) {
49536
+ log.error("Error getting HGVS position", e);
49537
+ return null
49538
+ }
49539
+ }
49540
+
49541
+ /**
49542
+ * Returns HGVS annotation for the position, for ref and alt bases. If a MANE transcript is available that is
49543
+ * used with coding notation (c.), otherwise genome position is used with genomic notation (g.).
49544
+ * Example: NM_000302.3:c.1234A>G or NM_000302.3:c.123+5T>C (intronic) or NC_000001.11:g.1234567G>A
49545
+ *
49546
+ * @param genome The genome
49547
+ * @param chr The chromosome name
49548
+ * @param position The genomic position (0-based)
49549
+ * @param reference The reference base (single-character string)
49550
+ * @param alternate The alternate base (single-character string)
49551
+ * @return {Promise<string|null>} HGVS notation string, or null if error
49552
+ */
49553
+ async function createHGVSAnnotation(genome, chr, position, reference, alternate) {
49554
+
49555
+ try {
49556
+ const transcript = await genome.getManeTranscriptAt(chr, position);
49557
+
49558
+ if (transcript && transcript.exons) {
49559
+
49560
+ // Ensure bases are uppercase
49561
+ reference = reference.toUpperCase();
49562
+ alternate = alternate.toUpperCase();
49563
+
49564
+ if (transcript.strand === '-') {
49565
+ reference = complementBase(reference);
49566
+ alternate = complementBase(alternate);
49567
+ }
49568
+
49569
+
49570
+ let positionString = "";
49571
+
49572
+ let transcriptName = transcript.name;
49573
+ for (const key of Object.keys(transcript)) {
49574
+ const value = transcript[key];
49575
+ if (typeof value === 'string' && (value.startsWith("NM_") || value.startsWith("NR_"))) {
49576
+ transcriptName = value;
49577
+ break
49578
+ }
49579
+ }
49580
+
49581
+ if (transcriptName) {
49582
+ // Check if position is within an exon (coding or non-coding)
49583
+ let positionIsInExon = false;
49584
+ for (const exon of transcript.exons) {
49585
+ if (position >= exon.start && position < exon.end) {
49586
+ positionIsInExon = true;
49587
+ break
49588
+ }
49589
+ }
49590
+
49591
+ const positive = transcript.strand === '+';
49592
+
49593
+ if (positionIsInExon) {
49594
+ // Try to convert to coding position
49595
+ const codingPosition = genomeToCodingPosition(position, positive, transcript.exons);
49596
+
49597
+ if (codingPosition >= 0) {
49598
+ // Position is in a coding region, return c. notation (1-based)
49599
+ positionString = `${transcriptName}:c.${codingPosition + 1}`;
49600
+ } else {
49601
+ // Position is in an exon but not coding - check if in UTR
49602
+ const firstCodingPos = codingToGenomePosition(transcript, 1);
49603
+ if (firstCodingPos > 0) {
49604
+ // Calculate total coding length
49605
+ let codingLen = 0;
49606
+ for (const exon of transcript.exons) {
49607
+ codingLen += getCodingLength(exon);
49608
+ }
49609
+ const lastCodingPos = codingToGenomePosition(transcript, codingLen);
49610
+
49611
+ // Check if in 5' UTR
49612
+ if ((positive && position < firstCodingPos) || (!positive && position > firstCodingPos)) {
49613
+ const distance = Math.abs(position - firstCodingPos);
49614
+ positionString = `${transcriptName}:c.-${distance}`;
49615
+ }
49616
+ // Check if in 3' UTR
49617
+ else if ((positive && position >= lastCodingPos) || (!positive && position <= lastCodingPos)) {
49618
+ const distance = Math.abs(position - lastCodingPos) + 1;
49619
+ positionString = `${transcriptName}:c.*${distance}`;
49620
+ }
49621
+ }
49622
+ }
49623
+ } else {
49624
+ // Position is intronic - find nearest exon boundary
49625
+ // For HGVS, we reference the last coding base in the nearest exon
49626
+ let nearestExonEdge = -1;
49627
+ let nearestCodingPos = -1;
49628
+ let minDistance = Number.MAX_SAFE_INTEGER;
49629
+
49630
+ for (const exon of transcript.exons) {
49631
+ if (getCodingLength(exon) === 0) continue // Skip non-coding exons
49632
+
49633
+ // Check distance to the last coding base at the start side of the exon
49634
+ // exon.start is 0-based inclusive
49635
+ const distToStart = Math.abs(position - exon.start);
49636
+ if (distToStart > 0 && distToStart < minDistance) {
49637
+ minDistance = distToStart;
49638
+ nearestExonEdge = exon.start;
49639
+ // Get coding position of first base in this exon
49640
+ nearestCodingPos = genomeToCodingPosition(getCodingStart(exon), positive, transcript.exons);
49641
+ }
49642
+
49643
+ // Check distance to the last coding base at the end side of the exon
49644
+ // exon.end is 0-based exclusive, so last base is at end-1
49645
+ const distToEnd = Math.abs(position - (exon.end - 1));
49646
+ if (distToEnd > 0 && distToEnd < minDistance) {
49647
+ minDistance = distToEnd;
49648
+ nearestExonEdge = exon.end - 1;
49649
+ // Get coding position of last base in this exon
49650
+ nearestCodingPos = genomeToCodingPosition(getCodingEnd(exon) - 1, positive, transcript.exons);
49651
+ }
49652
+ }
49653
+
49654
+ if (nearestCodingPos >= 0) {
49655
+ // Calculate offset: positive = downstream of exon, negative = upstream of exon
49656
+ let offset = position - nearestExonEdge;
49657
+ // For positive strand: + means to the right, - means to the left
49658
+ // For negative strand: + means to the left (genomically), - means to the right
49659
+ // But in HGVS, the sign is relative to transcript direction, so we need to flip for negative strand
49660
+ if (!positive) {
49661
+ offset = -offset;
49662
+ }
49663
+ const sign = offset >= 0 ? "+" : "";
49664
+ positionString = `${transcriptName}:c.${nearestCodingPos + 1}${sign}${offset}`;
49665
+ }
49666
+ }
49667
+ }
49668
+
49669
+ return positionString + reference + ">" + alternate
49670
+ }
49671
+
49672
+ // Fallback to genomic notation
49673
+ const aliasRecord = await genome.getAliasRecord(chr);
49674
+ let accession = chr;
49675
+
49676
+ if (aliasRecord) {
49677
+ for (const alias of Object.values(aliasRecord)) {
49678
+ if (alias.startsWith("NC_") || alias.startsWith("NT_") || alias.startsWith("NW_") ||
49679
+ alias.startsWith("NG_") || alias.startsWith("NM_") || alias.startsWith("NR_") ||
49680
+ alias.startsWith("NP_")) {
49681
+ accession = alias;
49682
+ break
49683
+ }
49684
+ }
49685
+ }
49686
+
49687
+ // HGVS genomic coordinate is 1-based; position parameter is 0-based
49688
+ return `${accession}:g.${position + 1}${reference}>${alternate}`
49689
+ } catch (e) {
49690
+ log.error("Error creating HGVS annotation", e);
49691
+ return null
49692
+ }
49693
+ }
49694
+
49695
+ // Helper function to complement a base (string)
49696
+ function complementBase(base) {
49697
+ const complementMap = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' };
49698
+ return complementMap[base] || base
49699
+ }
49700
+
49701
+ function genomeToCodingPosition(genomePosition, positive, exons) {
49702
+
49703
+ if (exons) {
49704
+
49705
+ /*
49706
+ We loop over all exons, either from the beginning or the end.
49707
+ Increment position only on coding regions.
49708
+ */
49709
+
49710
+ let codingOffset = 0;
49711
+
49712
+ for (let exnum = 0; exnum < exons.length; exnum++) {
49713
+
49714
+ const exon = positive ? exons[exnum] : exons[exons.length - 1 - exnum];
49715
+
49716
+ if (exon.start <= genomePosition && exon.end > genomePosition) {
49717
+ const delta = positive
49718
+ ? genomePosition - getCodingStart(exon)
49719
+ : getCodingEnd(exon) - genomePosition - 1;
49720
+ return codingOffset + delta
49721
+ }
49722
+
49723
+ codingOffset += getCodingLength(exon);
49724
+ }
49725
+ }
49726
+ return -1
49727
+ }
49728
+
49729
+
49730
+
49731
+ const HGVS = {
49732
+ isValidHGVS,
49733
+ search: search$1,
49734
+ getHGVSPosition,
49735
+ createHGVSAnnotation
49736
+ };
49737
+
49738
+ /**
49739
+ * ClinVar utilities for searching and retrieving ClinVar variation information
49740
+ */
49741
+
49742
+ /**
49743
+ * Get the ClinVar URL for the given HGVS notation
49744
+ * @param {string} hgvsNotation - The HGVS notation string to search for
49745
+ * @return {Promise<string|null>} The ClinVar variation URL, or null if not found or error occurs
49746
+ */
49747
+ async function getClinVarURL(hgvsNotation) {
49748
+ try {
49749
+ const encodedHgvs = encodeURIComponent(hgvsNotation);
49750
+ const esearchUrl = `https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?` +
49751
+ `db=clinvar&term=${encodedHgvs}&retmode=json`;
49752
+
49753
+ const response = await fetch(esearchUrl);
49754
+
49755
+ if (!response.ok) {
49756
+ console.error(`HTTP error! status: ${response.status}`);
49757
+ return null
49758
+ }
49759
+
49760
+ // Parse JSON response to get the first ClinVar accession
49761
+ const json = await response.json();
49762
+ const esearchResult = json.esearchresult;
49763
+
49764
+ if (esearchResult.count > 0) {
49765
+ const uid = esearchResult.idlist[0];
49766
+ return `https://www.ncbi.nlm.nih.gov/clinvar/variation/${uid}/`
49767
+ } else {
49768
+ return null
49769
+ }
49770
+
49771
+ } catch (e) {
49772
+ console.error("Error fetching ClinVar URL", e);
49773
+ return null
49774
+ }
49775
+ }
49776
+
49777
+ const ClinVar = {
49778
+ getClinVarURL
49779
+ };
49780
+
48921
49781
  const READ_PAIRED_FLAG = 0x1;
48922
49782
  const PROPER_PAIR_FLAG = 0x2;
48923
49783
  const READ_UNMAPPED_FLAG = 0x4;
@@ -49052,13 +49912,22 @@ class BamAlignment {
49052
49912
  return (genomicLocation >= s && genomicLocation <= (s + l))
49053
49913
  }
49054
49914
 
49055
- popupData(genomicLocation, hiddenTags, showTags) {
49915
+ /**
49916
+ * Return data to show in the popup. Elements are either strings (for raw HTML) or
49917
+ * objects with name, value, borderTop properties.
49918
+ *
49919
+ * @param genomicLocation - 0-based genomic location
49920
+ * @param hiddenTags - Set of bam tags to hide
49921
+ * @param showTags - Set of bam tags to show (overrides hide/show rules)
49922
+ * @returns {*[]}
49923
+ */
49924
+ async popupData(genomicLocation, hiddenTags, showTags, refBase, genome) {
49056
49925
 
49057
49926
  // if the user clicks on a base next to an insertion, show just the
49058
49927
  // inserted bases in a popup (like in desktop IGV).
49059
49928
  const nameValues = [];
49060
49929
 
49061
- // Consert genomic location to int
49930
+ // Convert genomic location to int
49062
49931
  genomicLocation = Math.floor(genomicLocation);
49063
49932
 
49064
49933
  if (this.insertions) {
@@ -49077,6 +49946,26 @@ class BamAlignment {
49077
49946
 
49078
49947
  nameValues.push({name: 'Read Name', value: this.readName});
49079
49948
 
49949
+
49950
+ // HGVS annotations for variants, and ClinVar links if available
49951
+ const readBase = this.readBaseAt(genomicLocation);
49952
+ if (refBase) {
49953
+ if (readBase && readBase !== refBase && readBase !== '*') {
49954
+ const hgvsNotation = await HGVS.createHGVSAnnotation(genome, this.chr, genomicLocation, refBase, readBase);
49955
+ if (hgvsNotation) {
49956
+ const clinVarURL = await ClinVar.getClinVarURL(hgvsNotation);
49957
+ if (clinVarURL) {
49958
+ nameValues.push({
49959
+ name: 'ClinVar',
49960
+ value: `<a href='${clinVarURL}' target='_blank'>${hgvsNotation}</a>`
49961
+ });
49962
+ } else {
49963
+ nameValues.push({name: 'HGVS', value: hgvsNotation});
49964
+ }
49965
+ }
49966
+ }
49967
+ }
49968
+
49080
49969
  // Sample
49081
49970
  // Read group
49082
49971
  nameValues.push('<hr/>');
@@ -49152,7 +50041,7 @@ class BamAlignment {
49152
50041
 
49153
50042
  nameValues.push('<hr/>');
49154
50043
  nameValues.push({name: 'Genomic Location: ', value: numberFormatter$1(1 + genomicLocation)});
49155
- nameValues.push({name: 'Read Base:', value: this.readBaseAt(genomicLocation)});
50044
+ nameValues.push({name: 'Read Base:', value: readBase});
49156
50045
  nameValues.push({name: 'Base Quality:', value: this.readBaseQualityAt(genomicLocation)});
49157
50046
 
49158
50047
  const bmSets = this.getBaseModificationSets();
@@ -51357,8 +52246,8 @@ class BamSource {
51357
52246
  if (alignmentContainer.hasAlignments) {
51358
52247
  const sequence = await genome.getSequence(chr, alignmentContainer.start, alignmentContainer.end);
51359
52248
  if (sequence) {
51360
- alignmentContainer.coverageMap.refSeq = sequence; // TODO -- fix this
51361
- alignmentContainer.sequence = sequence; // TODO -- fix this
52249
+ alignmentContainer.coverageMap.refSeq = sequence;
52250
+ alignmentContainer.sequence = sequence;
51362
52251
  return alignmentContainer
51363
52252
  } else {
51364
52253
  console.error("No sequence for: " + chr + ":" + alignmentContainer.start + "-" + alignmentContainer.end);
@@ -53679,7 +54568,7 @@ class AlignmentTrack extends TrackBase {
53679
54568
  highlightColor: undefined,
53680
54569
  minTLEN: undefined,
53681
54570
  maxTLEN: undefined,
53682
- tagColorPallete: "Set1",
54571
+ tagColorPallete: "Set1"
53683
54572
  }
53684
54573
 
53685
54574
  _colorTables = new Map()
@@ -54029,7 +54918,7 @@ class AlignmentTrack extends TrackBase {
54029
54918
 
54030
54919
  IGVGraphics.strokeLine(ctx, sPixel, yStrokedLine, ePixel, yStrokedLine, {
54031
54920
  strokeStyle: color,
54032
- lineWidth: 2,
54921
+ lineWidth: 2
54033
54922
  });
54034
54923
 
54035
54924
  // Add gap width as text like Java IGV if it fits nicely and is a multi-base gap
@@ -54038,7 +54927,7 @@ class AlignmentTrack extends TrackBase {
54038
54927
  IGVGraphics.fillRect(ctx, textStart - 1, y - 1, gapTextWidth + 2, 12, {fillStyle: "white"});
54039
54928
  IGVGraphics.fillText(ctx, gapLenText, textStart, y + 10, {
54040
54929
  'font': 'normal 10px monospace',
54041
- 'fillStyle': this.deletionTextColor,
54930
+ 'fillStyle': this.deletionTextColor
54042
54931
  });
54043
54932
  }
54044
54933
  }
@@ -54081,7 +54970,7 @@ class AlignmentTrack extends TrackBase {
54081
54970
  if (this.showInsertionText && insertionBlock.len > 1 && basePixelWidth > textPixelWidth) {
54082
54971
  IGVGraphics.fillText(ctx, insertLenText, xBlockStart + 1, y + 10, {
54083
54972
  'font': 'normal 10px monospace',
54084
- 'fillStyle': this.insertionTextColor,
54973
+ 'fillStyle': this.insertionTextColor
54085
54974
  });
54086
54975
  }
54087
54976
  lastXBlockStart = xBlockStart;
@@ -54251,7 +55140,7 @@ class AlignmentTrack extends TrackBase {
54251
55140
  height: alignmentHeight
54252
55141
  },
54253
55142
  baseColor,
54254
- readChar,
55143
+ readChar
54255
55144
  });
54256
55145
  }
54257
55146
 
@@ -54261,13 +55150,28 @@ class AlignmentTrack extends TrackBase {
54261
55150
  return blockBasesToDraw
54262
55151
  }
54263
55152
  }
55153
+ }
54264
55154
 
54265
- };
54266
-
54267
- popupData(clickState) {
55155
+ async popupData(clickState) {
54268
55156
  const clickedObject = this.getClickedObject(clickState);
54269
- return clickedObject?.popupData(clickState.genomicLocation, this.hiddenTags, this.showTags)
54270
- };
55157
+ if (clickedObject) {
55158
+
55159
+ // Determine reference base at clicked position, used for HGVS notation
55160
+ let refBase;
55161
+ if (clickedObject.chr) {
55162
+ const viewport = clickState.viewport;
55163
+ const alignmentContainer = viewport.cachedFeatures;
55164
+ const coverageMap = alignmentContainer?.coverageMap;
55165
+ const refseq = coverageMap?.refSeq;
55166
+ if (refseq) {
55167
+ const genomicLocation = Math.floor(clickState.genomicLocation);
55168
+ refBase = refseq.charAt(genomicLocation - coverageMap.bpStart).toUpperCase();
55169
+ }
55170
+ }
55171
+
55172
+ return clickedObject.popupData(clickState.genomicLocation, this.hiddenTags, this.showTags, refBase, this.browser.genome)
55173
+ }
55174
+ }
54271
55175
 
54272
55176
  /**
54273
55177
  * Return menu items for the AlignmentTrack
@@ -55040,7 +55944,7 @@ class AlignmentTrack extends TrackBase {
55040
55944
  this.colorTable = new PaletteColorTable(this.tagColorPallete);
55041
55945
  }
55042
55946
  color = this.colorTable.getColor(tagValue);
55043
-
55947
+
55044
55948
  }
55045
55949
  break
55046
55950
  }
@@ -55197,7 +56101,7 @@ function drawModifications(ctx,
55197
56101
 
55198
56102
 
55199
56103
  const base = key.base;
55200
- const compl = complementBase(base);
56104
+ const compl = complementBase$1(base);
55201
56105
 
55202
56106
  const modifiable = coverageMap.getCount(pos, base) + coverageMap.getCount(pos, compl);
55203
56107
  const detectable = modificationCounts.simplexModifications.has(key.modification) ?
@@ -55230,7 +56134,7 @@ function drawModifications(ctx,
55230
56134
 
55231
56135
  const DEFAULT_COVERAGE_COLOR = "rgb(150, 150, 150)";
55232
56136
 
55233
- class CoverageTrack {
56137
+ class CoverageTrack {
55234
56138
 
55235
56139
 
55236
56140
  constructor(config, parent) {
@@ -55242,7 +56146,7 @@ class CoverageTrack {
55242
56146
  this.top = 0;
55243
56147
 
55244
56148
  this.autoscale = config.autoscale || config.max === undefined;
55245
- if(config.coverageColor) {
56149
+ if (config.coverageColor) {
55246
56150
  this.color = config.coverageColor;
55247
56151
  }
55248
56152
 
@@ -55259,11 +56163,15 @@ class CoverageTrack {
55259
56163
  return this.parent.coverageTrackHeight
55260
56164
  }
55261
56165
 
56166
+ get browser() {
56167
+ return this.parent.browser
56168
+ }
56169
+
55262
56170
  draw(options) {
55263
56171
 
55264
56172
  const pixelTop = options.pixelTop;
55265
56173
  pixelTop + options.pixelHeight;
55266
- const nucleotideColors = this.parent.browser.nucleotideColors;
56174
+ const nucleotideColors = this.browser.nucleotideColors;
55267
56175
 
55268
56176
  if (pixelTop > this.height) {
55269
56177
  return //scrolled out of view
@@ -55297,7 +56205,8 @@ class CoverageTrack {
55297
56205
  fillStyle: color,
55298
56206
  strokeStyle: color
55299
56207
  });
55300
- const w = Math.max(1, 1.0 / bpPerPixel);
56208
+
56209
+ const w = Math.max(1, 1.0 / bpPerPixel);
55301
56210
  for (let i = 0, len = coverageMap.coverage.length; i < len; i++) {
55302
56211
 
55303
56212
  const bp = (coverageMap.bpStart + i);
@@ -55366,8 +56275,9 @@ class CoverageTrack {
55366
56275
  const coverageMap = features.coverageMap;
55367
56276
  const coverageMapIndex = Math.floor(genomicLocation - coverageMap.bpStart);
55368
56277
  const coverage = coverageMap.coverage[coverageMapIndex];
55369
- if(coverage) {
56278
+ if (coverage) {
55370
56279
  return {
56280
+ reference: coverageMap.refSeq ? coverageMap.refSeq.charAt(coverageMapIndex).toUpperCase() : undefined,
55371
56281
  coverage: coverage,
55372
56282
  baseModCounts: features.baseModCounts,
55373
56283
  hoverText: () => coverageMap.coverage[coverageMapIndex].hoverText()
@@ -55375,60 +56285,64 @@ class CoverageTrack {
55375
56285
  }
55376
56286
  }
55377
56287
 
55378
- popupData(clickState) {
56288
+ async popupData(clickState) {
55379
56289
 
55380
56290
  const nameValues = [];
55381
56291
 
55382
- const {coverage, baseModCounts} = this.getClickedObject(clickState);
56292
+ const {reference, coverage, baseModCounts} = this.getClickedObject(clickState);
55383
56293
  if (coverage) {
55384
56294
  const genomicLocation = Math.floor(clickState.genomicLocation);
55385
56295
  const referenceFrame = clickState.viewport.referenceFrame;
55386
56296
 
55387
56297
  nameValues.push(referenceFrame.chr + ":" + numberFormatter$1(1 + genomicLocation));
55388
-
55389
56298
  nameValues.push({name: 'Total Count', value: coverage.total});
56299
+ nameValues.push('<HR/>');
55390
56300
 
55391
56301
  // A
55392
- let tmp = coverage.posA + coverage.negA;
55393
- if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posA + "+, " + coverage.negA + "- )";
55394
- nameValues.push({name: 'A', value: tmp});
55395
-
55396
- // C
55397
- tmp = coverage.posC + coverage.negC;
55398
- if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posC + "+, " + coverage.negC + "- )";
55399
- nameValues.push({name: 'C', value: tmp});
55400
-
55401
- // G
55402
- tmp = coverage.posG + coverage.negG;
55403
- if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posG + "+, " + coverage.negG + "- )";
55404
- nameValues.push({name: 'G', value: tmp});
55405
-
55406
- // T
55407
- tmp = coverage.posT + coverage.negT;
55408
- if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posT + "+, " + coverage.negT + "- )";
55409
- nameValues.push({name: 'T', value: tmp});
55410
-
55411
- // N
55412
- tmp = coverage.posN + coverage.negN;
55413
- if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posN + "+, " + coverage.negN + "- )";
55414
- nameValues.push({name: 'N', value: tmp});
56302
+ for (let b of ['A', 'C', 'G', 'T', 'N']) {
56303
+ let tmp = coverage[`pos${b}`] + coverage[`neg${b}`];
56304
+ tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage[`pos${b}`] + "+, " + coverage[`neg${b}`] + "- )";
56305
+ nameValues.push({name: b, value: tmp});
56306
+ }
55415
56307
 
55416
- nameValues.push('<HR/>');
55417
- nameValues.push({name: 'DEL', value: coverage.del.toString()});
55418
- nameValues.push({name: 'INS', value: coverage.ins.toString()});
56308
+ if (coverage.del > 0) nameValues.push({name: 'DEL', value: coverage.del.toString()});
56309
+ if (coverage.ins > 0) nameValues.push({name: 'INS', value: coverage.ins.toString()});
55419
56310
 
55420
- if(baseModCounts) {
56311
+ if (baseModCounts) {
55421
56312
  nameValues.push('<hr/>');
55422
56313
  nameValues.push(...baseModCounts.popupData(genomicLocation, this.parent.colorBy));
55423
56314
 
55424
56315
  }
55425
56316
 
55426
- }
56317
+ // HGVS annotations for variants, and ClinVar links if available
56318
+ if (reference) {
56319
+ let first = true;
56320
+ for (let b of ['A', 'C', 'G', 'T']) {
56321
+ let count = coverage[`pos${b}`] + coverage[`neg${b}`];
56322
+ if (count > 0 && reference !== b) {
56323
+ if (first) {
56324
+ nameValues.push('<hr/>');
56325
+ first = false;
56326
+ }
56327
+ const hgvsNotation = await HGVS.createHGVSAnnotation(this.browser.genome, referenceFrame.chr, genomicLocation, reference, b);
56328
+ const clinVarURL = await ClinVar.getClinVarURL(hgvsNotation);
56329
+ if (clinVarURL) {
56330
+ nameValues.push({
56331
+ name: 'ClinVar',
56332
+ value: `<a href='${clinVarURL}' target='_blank'>${hgvsNotation}</a>`
56333
+ });
56334
+ } else {
56335
+ nameValues.push({name: 'HGVS', value: hgvsNotation});
56336
+ }
56337
+ }
56338
+ }
56339
+ }
55427
56340
 
55428
- return nameValues
55429
56341
 
55430
- }
56342
+ return nameValues
55431
56343
 
56344
+ }
56345
+ }
55432
56346
  }
55433
56347
 
55434
56348
  class BAMTrack extends TrackBase {
@@ -72360,39 +73274,6 @@ const SV_COLOR_TABLE = new ColorTable({
72360
73274
  '*': '#002eff'
72361
73275
  });
72362
73276
 
72363
- const DEFAULT_SEARCH_CONFIG = {
72364
- timeout: 5000,
72365
- type: "plain",
72366
- url: 'https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$',
72367
- coords: 0
72368
- };
72369
-
72370
- async function searchFeatures(browser, name) {
72371
-
72372
- const searchConfig = browser.searchConfig || DEFAULT_SEARCH_CONFIG;
72373
- let feature;
72374
-
72375
- name = name.toUpperCase();
72376
- const searchableTracks = browser.tracks.filter(t => t.searchable);
72377
- for (let track of searchableTracks) {
72378
- const feature = await track.search(name);
72379
- if (feature) {
72380
- return feature
72381
- }
72382
- }
72383
-
72384
- // If still not found try webservice, if enabled
72385
- if (browser.config && false !== browser.config.search) {
72386
- try {
72387
- feature = await searchWebService(browser, name, searchConfig);
72388
- return feature // Might be undefined
72389
- } catch (error) {
72390
- console.log("Search service not available " + error);
72391
- }
72392
- }
72393
-
72394
- }
72395
-
72396
73277
  /**
72397
73278
  * Return an object representing the locus of the given string. Object is of the form
72398
73279
  * {
@@ -72419,6 +73300,13 @@ async function search(browser, string) {
72419
73300
 
72420
73301
  const searchForLocus = async (locus) => {
72421
73302
 
73303
+ if (HGVS.isValidHGVS(locus)) {
73304
+ const hgvsResult = await HGVS.search(locus, browser);
73305
+ if (hgvsResult) {
73306
+ return hgvsResult
73307
+ }
73308
+ }
73309
+
72422
73310
  if (locus.trim().toLowerCase() === "all" || locus === "*") {
72423
73311
  if (browser.genome.wholeGenomeView) {
72424
73312
  const wgChr = browser.genome.getChromosome("all");
@@ -72444,12 +73332,12 @@ async function search(browser, string) {
72444
73332
 
72445
73333
  // Not a locus string, search track annotations
72446
73334
  const feature = await searchFeatures(browser, locus);
72447
- if(feature) {
73335
+ if (feature) {
72448
73336
  locusObject = {
72449
73337
  chr: feature.chr,
72450
73338
  start: feature.start,
72451
73339
  end: feature.end,
72452
- name: (feature.name || locus).toUpperCase(),
73340
+ name: (feature.name || locus).toUpperCase()
72453
73341
 
72454
73342
  };
72455
73343
  }
@@ -72574,110 +73462,6 @@ function parseLocusString(locus, isSoftclipped = false) {
72574
73462
 
72575
73463
  }
72576
73464
 
72577
- async function searchWebService(browser, locus, searchConfig) {
72578
-
72579
- let path = searchConfig.url.replace("$FEATURE$", locus.toUpperCase());
72580
- if (path.indexOf("$GENOME$") > -1) {
72581
- path = path.replace("$GENOME$", (browser.genome.id ? browser.genome.id : "hg19"));
72582
- }
72583
- const options = searchConfig.timeout ? {timeout: searchConfig.timeout} : undefined;
72584
- const result = await igvxhr.loadString(path, options);
72585
-
72586
- return processSearchResult(browser, result, searchConfig)
72587
- }
72588
-
72589
- function processSearchResult(browser, result, searchConfig) {
72590
-
72591
- let results;
72592
-
72593
- if ('plain' === searchConfig.type) {
72594
- results = parseSearchResults(browser, result);
72595
- } else {
72596
- results = JSON.parse(result);
72597
- }
72598
-
72599
- if (searchConfig.resultsField) {
72600
- results = results[searchConfig.resultsField];
72601
- }
72602
-
72603
- if (!results || 0 === results.length) {
72604
- return undefined
72605
-
72606
- } else {
72607
-
72608
- const chromosomeField = searchConfig.chromosomeField || "chromosome";
72609
- const startField = searchConfig.startField || "start";
72610
- const endField = searchConfig.endField || "end";
72611
- const coords = searchConfig.coords || 1;
72612
-
72613
-
72614
- let result;
72615
- if (Array.isArray(results)) {
72616
- // Ignoring all but first result for now
72617
- // TODO -- present all and let user select if results.length > 1
72618
- result = results[0];
72619
- } else {
72620
- // When processing search results from Ensembl REST API
72621
- // Example: https://rest.ensembl.org/lookup/symbol/macaca_fascicularis/BRCA2?content-type=application/json
72622
- result = results;
72623
- }
72624
-
72625
- if (!(result.hasOwnProperty(chromosomeField) && (result.hasOwnProperty(startField)))) {
72626
- console.error("Search service results must include chromosome and start fields: " + result);
72627
- }
72628
-
72629
- const chr = result[chromosomeField];
72630
- let start = result[startField] - coords;
72631
- let end = result[endField];
72632
- if (undefined === end) {
72633
- end = start + 1;
72634
- }
72635
-
72636
- const locusObject = {chr, start, end};
72637
-
72638
- // Some GTEX hacks
72639
- result.type ? result.type : "gene";
72640
- if (searchConfig.geneField && searchConfig.snpField) {
72641
- const name = result[searchConfig.geneField] || result[searchConfig.snpField]; // Should never have both
72642
- if (name) locusObject.name = name.toUpperCase();
72643
- }
72644
-
72645
- return locusObject
72646
- }
72647
- }
72648
-
72649
- /**
72650
- * Parse the igv line-oriented (non json) search results.
72651
- * NOTE: currently, and probably permanently, this will always be a single line
72652
- * Example
72653
- * EGFR chr7:55,086,724-55,275,031 refseq
72654
- *
72655
- */
72656
- function parseSearchResults(browser, data) {
72657
-
72658
- const results = [];
72659
- const lines = splitLines$3(data);
72660
-
72661
- for (let line of lines) {
72662
-
72663
- const tokens = line.split("\t");
72664
-
72665
- if (tokens.length >= 3) {
72666
- const locusTokens = tokens[1].split(":");
72667
- const rangeTokens = locusTokens[1].split("-");
72668
- results.push({
72669
- chromosome: browser.genome.getChromosomeName(locusTokens[0].trim()),
72670
- start: parseInt(rangeTokens[0].replace(/,/g, '')),
72671
- end: parseInt(rangeTokens[1].replace(/,/g, '')),
72672
- name: tokens[0].toUpperCase()
72673
- });
72674
- }
72675
- }
72676
-
72677
- return results
72678
-
72679
- }
72680
-
72681
73465
  class QTLTrack extends TrackBase {
72682
73466
 
72683
73467
  constructor(config, browser) {
@@ -75693,7 +76477,7 @@ function createReferenceFrameList(loci, genome, browserFlanking, minimumBases, v
75693
76477
  })
75694
76478
  }
75695
76479
 
75696
- const _version = "3.6.0";
76480
+ const _version = "3.7.0";
75697
76481
  function version() {
75698
76482
  return _version
75699
76483
  }
@@ -78705,7 +79489,7 @@ class Genome {
78705
79489
  this.sequence = await loadSequence(config, this.browser);
78706
79490
 
78707
79491
  // Load cytobands. This is optional but required to support the ideogram. Only needed for whole genome view
78708
- if(false !== config.showIdeogram && false !== config.wholeGenomeView) {
79492
+ if (false !== config.showIdeogram && false !== config.wholeGenomeView) {
78709
79493
  if (config.cytobandURL) {
78710
79494
  this.cytobandSource = new CytobandFile(config.cytobandURL, Object.assign({}, config));
78711
79495
  } else if (config.cytobandBbURL) {
@@ -78713,8 +79497,8 @@ class Genome {
78713
79497
  }
78714
79498
  }
78715
79499
 
78716
- // Search for chromosomes, that is an array of chromosome objects containing name and length. This is
78717
- // optional but required to support whole genome view.
79500
+ // Search for chromosomes, that is an array of chromosome objects containing name and length. This is
79501
+ // optional but required to support whole genome view.
78718
79502
  if (this.sequence.chromosomes) {
78719
79503
  this.chromosomes = this.sequence.chromosomes;
78720
79504
  } else if (config.chromSizesURL) {
@@ -78750,7 +79534,7 @@ class Genome {
78750
79534
  // Trim to remove non-existent chromosomes
78751
79535
  await this.chromAlias.preload(this.#wgChromosomeNames);
78752
79536
  this.#wgChromosomeNames =
78753
- this.#wgChromosomeNames.map(c => this.getChromosomeName(c)).filter(c => this.chromosomes.has(c));
79537
+ this.#wgChromosomeNames.map(c => this.getChromosomeName(c)).filter(c => this.chromosomes.has(c));
78754
79538
  } else {
78755
79539
  this.#wgChromosomeNames = trimSmallChromosomes(this.chromosomes);
78756
79540
  await this.chromAlias.preload(this.#wgChromosomeNames);
@@ -78994,6 +79778,75 @@ class Genome {
78994
79778
  getHubURLs() {
78995
79779
  return this.config.hubs
78996
79780
  }
79781
+
79782
+ /**
79783
+ * Return the Mane transcript with the given name, or null if not found. We also check the refseq historical
79784
+ * db if available for backward compatibility. This is only available for hg38.
79785
+ * @param {string} name - The name of the Mane transcript to search for.
79786
+ * @return {Promise<Object|null>} A Promise resolving to the Mane transcript object if found, or null otherwise.
79787
+ */
79788
+ async getManeTranscript(name) {
79789
+
79790
+ if (!this.maneFeatureSource && this.config.maneBbURL) {
79791
+ this.loadManeFeatureSource();
79792
+ }
79793
+ if (this.maneFeatureSource) {
79794
+ const feature = await this.maneFeatureSource.search(name);
79795
+ if (feature) {
79796
+ return feature
79797
+ }
79798
+ }
79799
+ if (!this.rsDBFeatureSource && this.config.rsdbURL) {
79800
+ this.rsDBFeatureSource = new BWSource({url: this.config.rsdbURL}, this);
79801
+ }
79802
+ if (this.rsDBFeatureSource) {
79803
+ const feature = await this.rsDBFeatureSource.search(name);
79804
+ if (feature) {
79805
+ return feature
79806
+ }
79807
+ }
79808
+ return null
79809
+ }
79810
+
79811
+ /**
79812
+ * Return the Mane transcript overlapping the given position, or null if none found.
79813
+ *
79814
+ * @param chr Chromosome name (e.g., "chr1", "chrX") in which to search for the transcript.
79815
+ * @param position Genomic position (0-based coordinate) to check for overlap with a Mane transcript.
79816
+ * @return {Promise<*|null>} The feature representing the Mane transcript overlapping the specified position, or null if none is found.
79817
+ */
79818
+ async getManeTranscriptAt(chr, position) {
79819
+ if (!this.maneFeatureSource && this.config.maneBbURL) {
79820
+ this.loadManeFeatureSource();
79821
+ }
79822
+ if (this.maneFeatureSource) {
79823
+ try {
79824
+ const start = position;
79825
+ const end = position + 1;
79826
+ const features = await this.maneFeatureSource.getFeatures({chr, start, end});
79827
+ if (features) {
79828
+ for (const feature of features) {
79829
+ if (feature.start <= position && feature.end >= position) {
79830
+ return feature
79831
+ }
79832
+ }
79833
+ }
79834
+ } catch (e) {
79835
+ console.error("Error fetching MANE transcript", e);
79836
+ }
79837
+ }
79838
+ return null
79839
+ }
79840
+
79841
+ loadManeFeatureSource() {
79842
+ if (this.config.maneBbURL != null) {
79843
+ const bbConfig = {url: this.config.maneBbURL};
79844
+ if (this.config.maneTrixURL) {
79845
+ bbConfig.trixURL = this.config.maneTrixURL;
79846
+ }
79847
+ this.maneFeatureSource = new BWSource(bbConfig, this);
79848
+ }
79849
+ }
78997
79850
  }
78998
79851
 
78999
79852
  /**
@@ -79811,10 +80664,7 @@ class Browser {
79811
80664
 
79812
80665
  let session;
79813
80666
  if (options.url || options.file) {
79814
- session = await Browser.loadSessionFile(options, this.config);
79815
- // if (options.parentApp``) {
79816
- // session.parentApp = options.parentApp
79817
- // }
80667
+ session = await Browser.loadSessionFile(options);
79818
80668
  } else {
79819
80669
  session = options;
79820
80670
  }
@@ -79828,7 +80678,7 @@ class Browser {
79828
80678
  * @param options
79829
80679
  * @returns {Promise<*|XMLSession>}
79830
80680
  */
79831
- static async loadSessionFile(options, defaults) {
80681
+ static async loadSessionFile(options) {
79832
80682
 
79833
80683
  const urlOrFile = options.url || options.file;
79834
80684
 
@@ -79857,7 +80707,7 @@ class Browser {
79857
80707
  config = await igvxhr.loadJson(urlOrFile);
79858
80708
  }
79859
80709
  }
79860
- setDefaults(config, defaults);
80710
+
79861
80711
  return config
79862
80712
  }
79863
80713
 
@@ -79868,6 +80718,9 @@ class Browser {
79868
80718
  */
79869
80719
  async loadSessionObject(session) {
79870
80720
 
80721
+ // Capture current configuration options that might be missing from session
80722
+ setDefaults(session, this.config);
80723
+
79871
80724
  // prepare to load a new session, discarding DOM and state
79872
80725
  this.cleanHouseForSession();
79873
80726
  this.config = session;
@@ -79972,16 +80825,19 @@ class Browser {
79972
80825
 
79973
80826
  // Sample info
79974
80827
  const localSampleInfoFiles = [];
80828
+ const googleDriveSampleInfoFiles = [];
79975
80829
  if (session.sampleinfo) {
79976
80830
  const sampleInfoArray = Array.isArray(session.sampleinfo) ? session.sampleinfo : [session.sampleinfo];
79977
80831
  for (const sampleInfoConfig of sampleInfoArray) {
79978
- // The "file" property is recorded in the session when a local file is referenced. It can't be used
79979
- // on reloading, its only purpose is to present an alert to the user. This could also be used
79980
- // to prompt the user to load the file manually, but we don't currently do that.
79981
80832
  if (sampleInfoConfig.file) {
79982
80833
  localSampleInfoFiles.push(sampleInfoConfig.file);
79983
80834
  } else {
79984
- await this.sampleInfo.loadSampleInfo(sampleInfoConfig);
80835
+ const googleDriveItem = this.#createGoogleDriveItemIfPresent(sampleInfoConfig, 'Sample info', 'url', 'filename', 'Google Drive file');
80836
+ if (googleDriveItem) {
80837
+ googleDriveSampleInfoFiles.push(googleDriveItem);
80838
+ } else {
80839
+ await this.sampleInfo.loadSampleInfo(sampleInfoConfig);
80840
+ }
79985
80841
  }
79986
80842
  }
79987
80843
  }
@@ -79996,22 +80852,40 @@ class Browser {
79996
80852
  trackConfigurations.push({type: "sequence", order: defaultSequenceTrackOrder, removable: false});
79997
80853
  }
79998
80854
 
79999
- const localTrackFileNames = trackConfigurations.filter((config) => undefined !== config.file).map(({file}) => file);
80855
+ // Extract problematic resources from track configurations
80856
+ const { localFileItems, googleDriveItems } = this.#extractProblematicResources(
80857
+ trackConfigurations,
80858
+ localSampleInfoFiles,
80859
+ googleDriveSampleInfoFiles
80860
+ );
80000
80861
 
80001
- const localIndexFileNames = trackConfigurations.filter((config) => undefined !== config.indexFile).map(({indexFile}) => indexFile);
80002
- if (localIndexFileNames.length > 0) {
80003
- localTrackFileNames.push(...localIndexFileNames);
80004
- }
80862
+ // Display warning if problematic resources are found
80863
+ if (localFileItems.length > 0 || googleDriveItems.length > 0) {
80864
+ let message = 'Local and Google Drive files cannot be loaded from a saved session. The following file(s) will not be restored with this session.\n\n';
80005
80865
 
80006
- if (localSampleInfoFiles.length > 0) {
80007
- localTrackFileNames.push(...localSampleInfoFiles);
80008
- }
80866
+ // Add local file items
80867
+ for (const item of localFileItems) {
80868
+ message += `Local file name: ${item.fileName}\n`;
80869
+ message += `Track name: ${item.trackName}\n\n`;
80870
+
80871
+ }
80872
+
80873
+ // Add Google Drive items
80874
+ for (const item of googleDriveItems) {
80875
+ message += `Google Drive file name: ${item.fileName}\n`;
80876
+ message += `Track name: ${item.trackName}\n\n`;
80877
+
80878
+ }
80009
80879
 
80010
- if (localTrackFileNames.length > 0) {
80011
- alert(`Local files cannot be loaded automatically.\nThis session contains references to these local files:\n${localTrackFileNames.map(str => ` ${str}`).join('\n')}`);
80880
+ alert(message);
80012
80881
  }
80013
80882
 
80014
- const nonLocalTrackConfigurations = trackConfigurations.filter((config) => undefined === config.file);
80883
+ const nonLocalTrackConfigurations = trackConfigurations.filter((config) =>
80884
+ undefined === config.file &&
80885
+ undefined === config.indexFile &&
80886
+ // Filter out tracks with Google Drive URLs in url/indexURL fields
80887
+ !(config.url && isGoogleDriveURL(config.url)) &&
80888
+ !(config.indexURL && isGoogleDriveURL(config.indexURL)));
80015
80889
 
80016
80890
  // Maintain track order unless explicitly set
80017
80891
  let trackOrder = 1;
@@ -80907,7 +81781,7 @@ class Browser {
80907
81781
  }
80908
81782
 
80909
81783
  minimumBases() {
80910
- return this.config.minimumBases
81784
+ return this.config.minimumBases ?? 40
80911
81785
  }
80912
81786
 
80913
81787
  // Zoom in by a factor of 2, keeping the same center location
@@ -81278,11 +82152,6 @@ class Browser {
81278
82152
  }
81279
82153
 
81280
82154
  json["reference"] = this.genome.toJSON();
81281
- if (json.reference.fastaURL instanceof File) { // Test specifically for File. Other types of File-like objects might be savable) {
81282
- throw new Error(`Error. Sessions cannot include local file references ${json.reference.fastaURL.name}.`)
81283
- } else if (json.reference.indexURL instanceof File) { // Test specifically for File. Other types of File-like objects might be savable) {
81284
- throw new Error(`Error. Sessions cannot include local file references ${json.reference.indexURL.name}.`)
81285
- }
81286
82155
 
81287
82156
  // Build locus array (multi-locus view). Use the first track to extract the loci, any track could be used.
81288
82157
  const locus = [];
@@ -81323,9 +82192,9 @@ class Browser {
81323
82192
 
81324
82193
  let config;
81325
82194
  if (typeof track.getState === "function") {
81326
- config = TrackBase.localFileInspection(track.getState());
82195
+ config = TrackBase.prepareConfigForSession(track.getState());
81327
82196
  } else if (track.config) {
81328
- config = TrackBase.localFileInspection(track.config);
82197
+ config = TrackBase.prepareConfigForSession(track.config);
81329
82198
  }
81330
82199
 
81331
82200
  if (config) {
@@ -81356,37 +82225,214 @@ class Browser {
81356
82225
 
81357
82226
  json["tracks"] = trackJson;
81358
82227
 
81359
- const localFileDetections = [];
81360
- for (const json of trackJson) {
81361
- for (const key of Object.keys(json)) {
81362
- if ('file' === key || 'indexFile' === key) {
81363
- localFileDetections.push(json[key]);
81364
- }
82228
+ // Sample info
82229
+ if (this.config.sampleinfo) {
82230
+ json["sampleinfo"] = this.config.sampleinfo;
82231
+ }
82232
+
82233
+ // Validate reference genome and warn about problematic resources
82234
+ this._validateAndWarnResources(json);
82235
+
82236
+ return json
82237
+ }
82238
+
82239
+ /**
82240
+ * Get a display identifier for a Google Drive file.
82241
+ * Returns the provided filename if available, otherwise falls back to a default string.
82242
+ * Note: Filenames should always be present in saved sessions since Google Drive files
82243
+ * can only be added when the user is authenticated.
82244
+ *
82245
+ * @param {string|undefined} filename - The filename property from the config (e.g., config.filename or config.indexFilename)
82246
+ * @param {string} defaultFallback - Default identifier to use if filename is not provided
82247
+ * @returns {string} A display identifier (filename or fallback string)
82248
+ * @private
82249
+ */
82250
+ #getGoogleDriveDisplayName(filename, defaultFallback = 'Google Drive file') {
82251
+ return filename || defaultFallback
82252
+ }
82253
+
82254
+ /**
82255
+ * Check if a config has a Google Drive URL and create a Google Drive item if found.
82256
+ *
82257
+ * @param {Object} config - Track configuration object
82258
+ * @param {string} trackName - Name of the track
82259
+ * @param {string} urlField - Field name to check ('url' or 'indexURL')
82260
+ * @param {string} filenameField - Field name for filename ('filename' or 'indexFilename')
82261
+ * @param {string} defaultFileName - Default filename if not found
82262
+ * @returns {Object|null} Google Drive item object or null if not a Google Drive URL
82263
+ * @private
82264
+ */
82265
+ #createGoogleDriveItemIfPresent(config, trackName, urlField, filenameField, defaultFileName) {
82266
+ const url = config[urlField];
82267
+ if (url && isGoogleDriveURL(url)) {
82268
+ const fileName = this.#getGoogleDriveDisplayName(config[filenameField], defaultFileName);
82269
+ return {
82270
+ trackName: trackName,
82271
+ fileName: fileName
81365
82272
  }
81366
82273
  }
82274
+ return null
82275
+ }
81367
82276
 
81368
- // Sample info
81369
- const localSampleInfoFileDetections = [];
81370
- if (this.config.sampleinfo) {
82277
+ /**
82278
+ * Extract Google Drive items from a track configuration (checks both url and indexURL).
82279
+ *
82280
+ * @param {Object} config - Track configuration object
82281
+ * @returns {Array} Array of Google Drive items found in this config
82282
+ * @private
82283
+ */
82284
+ #extractGoogleDriveItemsFromConfig(config) {
82285
+ const items = [];
82286
+ const trackName = config.name || 'Unnamed track';
81371
82287
 
81372
- json["sampleinfo"] = this.config.sampleinfo;
82288
+ // Check main file URL
82289
+ const mainItem = this.#createGoogleDriveItemIfPresent(config, trackName, 'url', 'filename', 'Google Drive file');
82290
+ if (mainItem) {
82291
+ items.push(mainItem);
82292
+ }
82293
+
82294
+ // Check index file URL
82295
+ const indexItem = this.#createGoogleDriveItemIfPresent(config, `${trackName} index`, 'indexURL', 'indexFilename', 'Google Drive index file');
82296
+ if (indexItem) {
82297
+ items.push(indexItem);
82298
+ }
82299
+
82300
+ return items
82301
+ }
82302
+
82303
+ /**
82304
+ * Extract problematic resources (local files and Google Drive files) from track configurations.
82305
+ * Google Drive files are detected by checking if the url/indexURL fields contain Google Drive URLs,
82306
+ * using the isGoogleDriveURL helper function from sessionResourceValidator.
82307
+ *
82308
+ * @param {Array} trackConfigurations - Array of track configuration objects
82309
+ * @param {Array} localSampleInfoFiles - Array of local sample info filenames
82310
+ * @param {Array} googleDriveSampleInfoFiles - Array of Google Drive sample info items (objects with trackName and fileName)
82311
+ * @returns {{localFileItems: Array, googleDriveItems: Array}} Object containing arrays of problematic resources
82312
+ * @private
82313
+ */
82314
+ #extractProblematicResources(trackConfigurations, localSampleInfoFiles = [], googleDriveSampleInfoFiles = []) {
82315
+ const localFileItems = [];
82316
+ const googleDriveItems = [];
82317
+
82318
+ // Collect local files from track configurations
82319
+ for (const config of trackConfigurations) {
82320
+ const trackName = config.name || 'Unnamed track';
82321
+ if (config.file) {
82322
+ localFileItems.push({
82323
+ trackName: trackName,
82324
+ fileName: config.file
82325
+ });
82326
+ }
82327
+ if (config.indexFile) {
82328
+ localFileItems.push({
82329
+ trackName: `${trackName} index`,
82330
+ fileName: config.indexFile
82331
+ });
82332
+ }
82333
+ }
82334
+
82335
+ // Add sample info local files
82336
+ for (const fileName of localSampleInfoFiles) {
82337
+ localFileItems.push({
82338
+ trackName: 'Sample info',
82339
+ fileName: fileName
82340
+ });
82341
+ }
82342
+
82343
+ // Collect Google Drive files by checking if url/indexURL fields contain Google Drive URLs
82344
+ for (const config of trackConfigurations) {
82345
+ const items = this.#extractGoogleDriveItemsFromConfig(config);
82346
+ googleDriveItems.push(...items);
82347
+ }
82348
+
82349
+ // Add sample info Google Drive files
82350
+ googleDriveItems.push(...googleDriveSampleInfoFiles);
82351
+
82352
+ return { localFileItems, googleDriveItems }
82353
+ }
82354
+
82355
+ /**
82356
+ * Validate reference genome and warn about problematic resources in the session.
82357
+ *
82358
+ * Reference genome: Throws error if local files or Google Drive URLs are detected
82359
+ * Tracks/Sample Info: Shows warning if local files or Google Drive URLs are detected
82360
+ *
82361
+ * @param {Object} json - The session JSON object
82362
+ * @private
82363
+ */
82364
+ _validateAndWarnResources(json) {
82365
+ // 1. Validate reference genome (blocking errors)
82366
+ const refErrors = [];
82367
+
82368
+ if (json.reference.fastaURL) {
82369
+ if (isLocalFile(json.reference.fastaURL)) {
82370
+ refErrors.push(`Local file: ${json.reference.fastaURL.name}`);
82371
+ } else if (isGoogleDriveURL(json.reference.fastaURL)) {
82372
+ refErrors.push(`Google Drive URL: ${json.reference.fastaURL}`);
82373
+ }
82374
+ }
82375
+
82376
+ if (json.reference.indexURL) {
82377
+ if (isLocalFile(json.reference.indexURL)) {
82378
+ refErrors.push(`Local file: ${json.reference.indexURL.name}`);
82379
+ } else if (isGoogleDriveURL(json.reference.indexURL)) {
82380
+ refErrors.push(`Google Drive URL: ${json.reference.indexURL}`);
82381
+ }
82382
+ }
82383
+
82384
+ if (refErrors.length > 0) {
82385
+ throw new Error(
82386
+ `Error: Sessions cannot include the following resources in the reference genome:\n` +
82387
+ refErrors.map(err => ` - ${err}`).join('\n') + '\n' +
82388
+ `These resources require local access or authentication and will not work when the session is shared.`
82389
+ )
82390
+ }
82391
+
82392
+ // 2. Collect warnings from tracks and sample info
82393
+ const localSampleInfoFiles = [];
82394
+ const googleDriveSampleInfoFiles = [];
81373
82395
 
82396
+ // Check sample info
82397
+ if (this.config.sampleinfo) {
81374
82398
  for (const path of this.sampleInfo.sampleInfoFiles) {
81375
- const config = TrackBase.localFileInspection({url: path});
82399
+ const config = TrackBase.prepareConfigForSession({url: path});
81376
82400
  if (config.file) {
81377
- localSampleInfoFileDetections.push(config.file);
82401
+ localSampleInfoFiles.push(config.file);
82402
+ }
82403
+ // Check if the url field contains a Google Drive URL
82404
+ const googleDriveItem = this.#createGoogleDriveItemIfPresent(config, 'Sample info', 'url', 'filename', 'Google Drive file');
82405
+ if (googleDriveItem) {
82406
+ googleDriveSampleInfoFiles.push(googleDriveItem);
81378
82407
  }
81379
- }
81380
- if (localSampleInfoFileDetections.length > 0) {
81381
- localFileDetections.push(...localSampleInfoFileDetections);
81382
82408
  }
81383
82409
  }
81384
82410
 
81385
- if (localFileDetections.length > 0) {
81386
- alert(`This session includes reference(s) to local file(s):\n${localFileDetections.map(str => ` ${str}`).join('\n')}\nLocal files cannot be loaded automatically when a saved session is restored.`);
81387
- }
82411
+ // Extract problematic resources from tracks
82412
+ const { localFileItems, googleDriveItems } = this.#extractProblematicResources(
82413
+ json.tracks || [],
82414
+ localSampleInfoFiles,
82415
+ googleDriveSampleInfoFiles
82416
+ );
81388
82417
 
81389
- return json
82418
+ // 3. Display consolidated warning if any issues found
82419
+ if (localFileItems.length > 0 || googleDriveItems.length > 0) {
82420
+ let message = 'Local and Google Drive files cannot be loaded automatically when a saved session is restored. This session saves references to the following file(s) that will not be restored.\n\n';
82421
+
82422
+ // Add local file items
82423
+ for (const item of localFileItems) {
82424
+ message += `Local file name: ${item.fileName}\n`;
82425
+ message += `Track name: ${item.trackName}\n\n`;
82426
+ }
82427
+
82428
+ // Add Google Drive items
82429
+ for (const item of googleDriveItems) {
82430
+ message += `Google Drive file name: ${item.fileName}\n`;
82431
+ message += `Track name: ${item.trackName}\n\n`;
82432
+ }
82433
+
82434
+ alert(message);
82435
+ }
81390
82436
  }
81391
82437
 
81392
82438
  compressedSession() {
@@ -81890,6 +82936,281 @@ toggleTrackLabels(trackViews, isVisible) {
81890
82936
  }
81891
82937
  }
81892
82938
 
82939
+ /**
82940
+ * Handles incoming messages from the WebSocket connection. Performs requested actions on the IGV browser instance
82941
+ * and returns a response message.
82942
+ *
82943
+ * @param json
82944
+ * @param browser
82945
+ * @returns {Promise<{uniqueID, message: string, status: string}>}
82946
+ */
82947
+
82948
+
82949
+ async function handleMessage(json, browser) {
82950
+
82951
+ const returnMsg = {uniqueID: json.uniqueID, status: 'ok'};
82952
+
82953
+ try {
82954
+ let tracks;
82955
+ const {type, args} = json;
82956
+ switch (type.toLowerCase()) {
82957
+
82958
+ case "goto":
82959
+ case "search":
82960
+ const term = args.locus || args.term;
82961
+ const found = await browser.search(term);
82962
+ if (found) {
82963
+ returnMsg.message = `Locus ${term} found and navigated to successfully`;
82964
+ } else {
82965
+ returnMsg.message = `Locus ${term} not found`;
82966
+ returnMsg.status = 'warning';
82967
+ }
82968
+ break
82969
+
82970
+ case "currentloci":
82971
+ returnMsg.data = browser.currentLoci();
82972
+ returnMsg.message = `Retrieved current loci successfully`;
82973
+ break
82974
+
82975
+ case "visibilityChange":
82976
+ returnMsg.message = await browser.visibilityChange();
82977
+ break
82978
+
82979
+ case "tojson":
82980
+ returnMsg.data = browser.toJSON();
82981
+ returnMsg.message = `Session serialized to JSON successfully`;
82982
+ break
82983
+
82984
+ case "compressedsession":
82985
+ returnMsg.data = browser.compressedSession();
82986
+ returnMsg.message = `Session serialized and compressed successfully`;
82987
+ break
82988
+
82989
+ case "tosvg":
82990
+ returnMsg.data = browser.toSVG();
82991
+ returnMsg.message = `Session exported to SVG successfully`;
82992
+ break
82993
+
82994
+ case "removetrackbyname": {
82995
+ let {trackName} = args;
82996
+ if(trackName) {
82997
+ tracks = browser.findTracks(t => trackName ? t.name === trackName : true);
82998
+ if (tracks) {
82999
+ tracks.forEach(t => browser.removeTrack(t));
83000
+ returnMsg.message = `Removed track(s) ${trackName} for ${tracks.length} track(s)`;
83001
+ } else {
83002
+ returnMsg.message = `No tracks found matching name ${trackName}`;
83003
+ returnMsg.status = 'warning';
83004
+ }
83005
+ } else {
83006
+ returnMsg.message = `No track name provided`;
83007
+ returnMsg.status = 'warning';
83008
+ }
83009
+ break
83010
+ }
83011
+
83012
+ case "loadsampleinfo": {
83013
+ browser.loadSampleInfo(args);
83014
+ returnMsg.message = `Sample info loaded successfully`;
83015
+ break
83016
+ }
83017
+
83018
+ case "discardsampleinfo":
83019
+ browser.discardSampleInfo();
83020
+ returnMsg.message = `Sample info discarded successfully`;
83021
+ break
83022
+
83023
+ case "loadroi":
83024
+ browser.loadROI(args);
83025
+ returnMsg.message = `ROI loaded successfully`;
83026
+ break
83027
+
83028
+ case "clearrois":
83029
+ browser.clearROIs();
83030
+ returnMsg.message = `ROIs cleared successfully`;
83031
+ break
83032
+
83033
+ case "getuserdefinedrois":
83034
+ const rois = await browser.getUserDefinedROIs();
83035
+ returnMsg.data = rois;
83036
+ returnMsg.message = `Retrieved ${rois.length} user-defined ROIs successfully`;
83037
+ break
83038
+
83039
+ case 'loadtrack': {
83040
+ const {url, indexURL} = args;
83041
+ const track = await browser.loadTrack({url, indexURL});
83042
+ returnMsg.message = `Track ${track.name} loaded successfully`;
83043
+ break
83044
+ }
83045
+
83046
+ case "genome":
83047
+ const id = args.id;
83048
+ await browser.loadGenome(id);
83049
+ returnMsg.message = `Genome ${id} loaded successfully`;
83050
+ break
83051
+
83052
+ case "loadsession":
83053
+ const url = args.url;
83054
+ await browser.loadSession({url});
83055
+ returnMsg.message = `Session loaded successfully from ${url}`;
83056
+ break
83057
+
83058
+ case "zoomin":
83059
+ await browser.zoomIn();
83060
+ returnMsg.message = `Zoomed in successfully`;
83061
+ break
83062
+
83063
+ case "zoomout":
83064
+ await browser.zoomOut();
83065
+ returnMsg.message = `Zoomed out successfully`;
83066
+ break
83067
+
83068
+ case "setcolor":
83069
+
83070
+ let {color, trackName} = args;
83071
+
83072
+ if (color.includes(",") && !color.startsWith("rgb(")) {
83073
+ // Convert "R,G,B" to "rgb(R,G,B)"
83074
+ color = `rgb(${color})`;
83075
+ }
83076
+
83077
+ tracks = browser.findTracks(t => trackName ? t.name === trackName : true);
83078
+ if (tracks) {
83079
+ tracks.forEach(t => t.color = color);
83080
+ browser.repaintViews();
83081
+ returnMsg.message = `Set color to ${color} for ${tracks.length} track(s)`;
83082
+ } else {
83083
+ returnMsg.message = `No tracks found matching name ${trackName}`;
83084
+ returnMsg.status = 'warning';
83085
+ }
83086
+ break
83087
+
83088
+ case "renametrack":
83089
+
83090
+ const {currentName, newName} = args;
83091
+
83092
+ tracks = browser.findTracks(t => currentName === t.name);
83093
+ if (tracks && tracks.length > 0) {
83094
+ tracks.forEach(t => {
83095
+ t.name = newName;
83096
+ browser.fireEvent('tracknamechange', [t]);
83097
+ });
83098
+ returnMsg.message = `Renamed ${tracks.length} track(s) from ${currentName} to ${newName}`;
83099
+ } else {
83100
+ returnMsg.message = `No track found with name ${currentName}`;
83101
+ returnMsg.status = 'warning';
83102
+ }
83103
+ break
83104
+
83105
+ default:
83106
+ returnMsg.message = `Unrecognized message type: ${type}`;
83107
+ returnMsg.status = 'error';
83108
+ }
83109
+ } catch (err) {
83110
+ returnMsg.message = err?.message || String(err);
83111
+ returnMsg.status = 'error';
83112
+ }
83113
+
83114
+ return returnMsg
83115
+ }
83116
+
83117
+ /**
83118
+ * Create a WebSocket client that connects to a server and handles messages. The client attempts to connect to a
83119
+ * WebSocketServer upon creation. If the connection is not successful or lost, it will attempt to reconnect with an
83120
+ * exponential backoff strategy. Incoming messages are expected to be JSON formatted and are processed by the
83121
+ * handleMessage function. Messages encompass a subset of the igv.js API
83122
+ *
83123
+ * This client was created to interact with an MCP server, but could be used for other purposes.
83124
+ *
83125
+ * @param host Host for the WebSocket server
83126
+ * @param port Port for the WebSocket server
83127
+ * @param browser The igv.js browser instance
83128
+ */
83129
+
83130
+ function createWebSocketClient(host, port, browser) {
83131
+
83132
+ let socket;
83133
+ let retryInterval = 1000; // Initial retry interval in ms
83134
+ const maxRetryInterval = 10000; // Maximum retry interval in ms
83135
+ let reconnectTimer;
83136
+ let intentionalClose = false; // Flag to prevent reconnection on intentional close
83137
+
83138
+ function connect() {
83139
+
83140
+ const isLocal = host === 'localhost' || host === '127.0.0.1';
83141
+ const protocol = window.location.protocol === 'https:' && !isLocal ? 'wss:' : 'ws:';
83142
+ socket = new WebSocket(`${protocol}//${host}:${port}`);
83143
+
83144
+ // helper to safely send
83145
+ const sendJSON = (obj) => {
83146
+ if (socket.readyState === WebSocket.OPEN) {
83147
+ socket.send(JSON.stringify(obj));
83148
+ }
83149
+ };
83150
+
83151
+ socket.addEventListener('open', function (event) {
83152
+ retryInterval = 1000; // Reset retry interval on successful connection
83153
+ sendJSON({message: 'Hello from browser client'});
83154
+ });
83155
+
83156
+ // Listen for incoming messages
83157
+ socket.addEventListener('message', async function (event) {
83158
+ try {
83159
+ const json = JSON.parse(event.data);
83160
+
83161
+ if("close" === json.type) {
83162
+ intentionalClose = true;
83163
+ clearTimeout(reconnectTimer);
83164
+ if (socket && socket.readyState === WebSocket.OPEN) {
83165
+ socket.close();
83166
+ }
83167
+ return
83168
+ }
83169
+
83170
+ const returnMsg = await handleMessage(json, browser);
83171
+ sendJSON(returnMsg);
83172
+
83173
+ } catch (e) {
83174
+ if (e instanceof SyntaxError) {
83175
+ console.warn('Received non-JSON message from server:', event.data);
83176
+ } else {
83177
+ console.error('Error handling message:', e);
83178
+ sendJSON({
83179
+ status: 'error',
83180
+ message: `Error handling message: ${e.message || e.toString()}`
83181
+ });
83182
+ }
83183
+ }
83184
+ });
83185
+
83186
+ socket.addEventListener('error', function (event) {
83187
+ console.error('WebSocket error:', event);
83188
+ // The 'close' event will fire immediately after 'error', triggering the reconnect logic.
83189
+ });
83190
+
83191
+ socket.addEventListener('close', function (event) {
83192
+ if (intentionalClose) {
83193
+ console.log('WebSocket closed intentionally. Not reconnecting.');
83194
+ return
83195
+ }
83196
+ console.log('Disconnected from server. Retrying in ' + (retryInterval / 1000) + ' seconds.');
83197
+ clearTimeout(reconnectTimer);
83198
+ reconnectTimer = setTimeout(connect, retryInterval);
83199
+ // Increase retry interval for next time, up to a max
83200
+ retryInterval = Math.min(maxRetryInterval, retryInterval * 2);
83201
+ });
83202
+ }
83203
+
83204
+ connect(); // Initial connection attempt
83205
+
83206
+ window.addEventListener('beforeunload', function (event) {
83207
+ clearTimeout(reconnectTimer); // Don't try to reconnect when page is closing
83208
+ if (socket && socket.readyState === WebSocket.OPEN) {
83209
+ socket.close();
83210
+ }
83211
+ });
83212
+ }
83213
+
81893
83214
  let allBrowsers = [];
81894
83215
 
81895
83216
  /**
@@ -81947,8 +83268,13 @@ async function createBrowser(parentDiv, config) {
81947
83268
 
81948
83269
  browser.navbar.navbarDidResize();
81949
83270
 
81950
- return browser
83271
+ if(config.enableWebSocket) {
83272
+ const host = config.webSocketHost || "localhost";
83273
+ const port = config.webSocketPort || 60141;
83274
+ createWebSocketClient(host, port, browser);
83275
+ }
81951
83276
 
83277
+ return browser
81952
83278
  }
81953
83279
 
81954
83280
  function removeBrowser(browser) {
@@ -82141,7 +83467,8 @@ var index = {
82141
83467
  loadSessionFile: Browser.loadSessionFile,
82142
83468
  loadHub,
82143
83469
  uncompressSession: Browser.uncompressSession,
82144
- createIcon
83470
+ createIcon,
83471
+ createWebSocketClient
82145
83472
  };
82146
83473
 
82147
83474
  export { index as default };