jbrowse-plugin-tview 2.2.3 → 3.1.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.
Files changed (110) hide show
  1. package/README.md +325 -106
  2. package/dist/AddHighlightModel/index.js +2 -13
  3. package/dist/AddHighlightModel/index.js.map +1 -1
  4. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.d.ts +44 -64
  5. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js +57 -81
  6. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js.map +1 -1
  7. package/dist/LaunchTView/TviewGetPlanRpc/index.d.ts +1 -1
  8. package/dist/LaunchTView/align.d.ts +11 -17
  9. package/dist/LaunchTView/align.js +190 -150
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +51 -0
  12. package/dist/LaunchTView/alleles.js +213 -0
  13. package/dist/LaunchTView/alleles.js.map +1 -1
  14. package/dist/LaunchTView/fetchTviewPlan.d.ts +5 -37
  15. package/dist/LaunchTView/fetchTviewPlan.js +7 -28
  16. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -1
  17. package/dist/LaunchTView/index.js +45 -16
  18. package/dist/LaunchTView/index.js.map +1 -1
  19. package/dist/LaunchTView/launch.d.ts +50 -0
  20. package/dist/LaunchTView/launch.js +48 -0
  21. package/dist/LaunchTView/launch.js.map +1 -0
  22. package/dist/LaunchTView/launchView.d.ts +3 -8
  23. package/dist/LaunchTView/launchView.js +18 -12
  24. package/dist/LaunchTView/launchView.js.map +1 -1
  25. package/dist/LaunchTView/modifications.d.ts +64 -0
  26. package/dist/LaunchTView/modifications.js +131 -0
  27. package/dist/LaunchTView/modifications.js.map +1 -0
  28. package/dist/LaunchTView/readLayout.d.ts +35 -39
  29. package/dist/LaunchTView/readLayout.js +44 -24
  30. package/dist/LaunchTView/readLayout.js.map +1 -1
  31. package/dist/LaunchTView/repeatStats.d.ts +1 -1
  32. package/dist/LaunchTView/repeatStats.js +6 -21
  33. package/dist/LaunchTView/repeatStats.js.map +1 -1
  34. package/dist/LaunchTView/tview.d.ts +34 -23
  35. package/dist/LaunchTView/tview.js +133 -78
  36. package/dist/LaunchTView/tview.js.map +1 -1
  37. package/dist/TViewPanel/components/TViewPanel.js +9 -4
  38. package/dist/TViewPanel/components/TViewPanel.js.map +1 -1
  39. package/dist/TViewPanel/genome.d.ts +11 -0
  40. package/dist/TViewPanel/genome.js +32 -0
  41. package/dist/TViewPanel/genome.js.map +1 -0
  42. package/dist/TViewPanel/init.d.ts +38 -19
  43. package/dist/TViewPanel/init.js +66 -39
  44. package/dist/TViewPanel/init.js.map +1 -1
  45. package/dist/TViewPanel/initMenu.d.ts +28 -0
  46. package/dist/TViewPanel/initMenu.js +79 -0
  47. package/dist/TViewPanel/initMenu.js.map +1 -0
  48. package/dist/TViewPanel/model.d.ts +1090 -334
  49. package/dist/TViewPanel/model.js +295 -89
  50. package/dist/TViewPanel/model.js.map +1 -1
  51. package/dist/TViewPanel/modifications.d.ts +25 -0
  52. package/dist/TViewPanel/modifications.js +94 -0
  53. package/dist/TViewPanel/modifications.js.map +1 -0
  54. package/dist/index.d.ts +0 -1
  55. package/dist/index.js +0 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/jbrowse-plugin-tview.umd.production.min.js +125 -88
  58. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +8 -8
  62. package/src/AddHighlightModel/index.tsx +8 -14
  63. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +119 -157
  64. package/src/LaunchTView/TviewGetPlanRpc/index.ts +0 -1
  65. package/src/LaunchTView/align.ts +225 -176
  66. package/src/LaunchTView/alleles.ts +272 -0
  67. package/src/LaunchTView/fetchTviewPlan.ts +11 -54
  68. package/src/LaunchTView/index.ts +74 -16
  69. package/src/LaunchTView/launch.ts +98 -0
  70. package/src/LaunchTView/launchView.ts +28 -20
  71. package/src/LaunchTView/modifications.ts +200 -0
  72. package/src/LaunchTView/readLayout.ts +65 -41
  73. package/src/LaunchTView/repeatStats.ts +7 -23
  74. package/src/LaunchTView/tview.ts +165 -91
  75. package/src/TViewPanel/components/TViewPanel.tsx +30 -5
  76. package/src/TViewPanel/genome.ts +41 -0
  77. package/src/TViewPanel/init.ts +104 -51
  78. package/src/TViewPanel/initMenu.ts +126 -0
  79. package/src/TViewPanel/model.ts +346 -97
  80. package/src/TViewPanel/modifications.ts +132 -0
  81. package/src/index.ts +0 -2
  82. package/src/version.ts +1 -1
  83. package/dist/AddHighlightModel/GenomeMouseoverHighlight.d.ts +0 -6
  84. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js +0 -23
  85. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js.map +0 -1
  86. package/dist/AddHighlightModel/HighlightComponents.d.ts +0 -7
  87. package/dist/AddHighlightModel/HighlightComponents.js +0 -11
  88. package/dist/AddHighlightModel/HighlightComponents.js.map +0 -1
  89. package/dist/LaunchTView/components/ArrayReport.d.ts +0 -10
  90. package/dist/LaunchTView/components/ArrayReport.js +0 -59
  91. package/dist/LaunchTView/components/ArrayReport.js.map +0 -1
  92. package/dist/LaunchTView/components/LaunchTViewDialog.d.ts +0 -6
  93. package/dist/LaunchTView/components/LaunchTViewDialog.js +0 -124
  94. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +0 -1
  95. package/dist/LaunchTView/sampleTree.d.ts +0 -37
  96. package/dist/LaunchTView/sampleTree.js +0 -65
  97. package/dist/LaunchTView/sampleTree.js.map +0 -1
  98. package/dist/LaunchTView/useTviewMsa.d.ts +0 -18
  99. package/dist/LaunchTView/useTviewMsa.js +0 -24
  100. package/dist/LaunchTView/useTviewMsa.js.map +0 -1
  101. package/dist/TViewPanel/coords.d.ts +0 -25
  102. package/dist/TViewPanel/coords.js +0 -56
  103. package/dist/TViewPanel/coords.js.map +0 -1
  104. package/src/AddHighlightModel/GenomeMouseoverHighlight.tsx +0 -46
  105. package/src/AddHighlightModel/HighlightComponents.tsx +0 -25
  106. package/src/LaunchTView/components/ArrayReport.tsx +0 -64
  107. package/src/LaunchTView/components/LaunchTViewDialog.tsx +0 -212
  108. package/src/LaunchTView/sampleTree.ts +0 -73
  109. package/src/LaunchTView/useTviewMsa.ts +0 -39
  110. package/src/TViewPanel/coords.ts +0 -65
@@ -1,5 +1,10 @@
1
1
  import { alignInsertionSite } from './align'
2
- import { buildArrayBlocks, reanchorInsertions } from './alleles'
2
+ import {
3
+ buildArrayBlocks,
4
+ mergeInsertionSites,
5
+ normalizeInsertions,
6
+ reanchorInsertions,
7
+ } from './alleles'
3
8
  import {
4
9
  ABSENT,
5
10
  SPANNED_GAP,
@@ -9,10 +14,10 @@ import {
9
14
  parseRead,
10
15
  } from './readLayout'
11
16
  import { findReferenceArrays, mergeArrays } from './repeats'
12
- import { newickSafe } from './sampleTree'
13
17
 
14
18
  import type { ArrayBlock } from './alleles'
15
19
  import type { AlignmentFeature, ReadLayout } from './readLayout'
20
+ import type { Highlight, RowDataInput } from 'react-msaview'
16
21
 
17
22
  export type { AlignmentFeature, ReadLayout } from './readLayout'
18
23
  export { clipInsertions, parseCigar, parseRead } from './readLayout'
@@ -168,6 +173,26 @@ function arrayContaining(arrays: ArrayBlock[], pos: number) {
168
173
  return arrays.find(a => a.start < pos && pos < a.end)
169
174
  }
170
175
 
176
+ /**
177
+ * The reference positions a row is walked over, from inclusive to exclusive. A
178
+ * trailing insertion is keyed one past the last position the read spans, so
179
+ * that slot is in it.
180
+ */
181
+ export function rowSpan(read: ReadLayout, layout: ColumnLayout) {
182
+ const { start, end, arrays } = layout
183
+ const lastPos = read.start + read.refChars.length
184
+ const from = Math.max(start, read.start)
185
+ const to = Math.min(end, lastPos + 1)
186
+ // a row that begins or ends inside an array does not span it, so it gets no
187
+ // block; snapping past the block keeps the walk from emitting part of one
188
+ const startsInside = arrayContaining(arrays, from)
189
+ const endsInside = arrayContaining(arrays, to)
190
+ return {
191
+ from: startsInside ? Math.min(end, startsInside.end) : from,
192
+ to: endsInside ? endsInside.start : to,
193
+ }
194
+ }
195
+
171
196
  /**
172
197
  * Lays a single row out across the whole region. Rows are typically a tiny
173
198
  * fraction of the region, so the columns on either side are filled in one shot
@@ -177,22 +202,10 @@ function arrayContaining(arrays: ArrayBlock[], pos: number) {
177
202
  * `refChars` between them.
178
203
  */
179
204
  export function renderRow(read: ReadLayout, layout: ColumnLayout) {
180
- const { start, end, insWidths, arrays, offsets, totalColumns } = layout
205
+ const { start, insWidths, offsets, totalColumns } = layout
181
206
  const { arrayByStart, breaks } = layout
182
- // a trailing insertion is keyed one past the last position the read spans
183
207
  const lastPos = read.start + read.refChars.length
184
- let from = Math.max(start, read.start)
185
- let to = Math.min(end, lastPos + 1)
186
- // a row that begins or ends inside an array does not span it, so it gets no
187
- // block; snapping past the block keeps the walk from emitting part of one
188
- const startsInside = arrayContaining(arrays, from)
189
- if (startsInside) {
190
- from = Math.min(end, startsInside.end)
191
- }
192
- const endsInside = arrayContaining(arrays, to)
193
- if (endsInside) {
194
- to = endsInside.start
195
- }
208
+ const { from, to } = rowSpan(read, layout)
196
209
  if (to <= from) {
197
210
  return ABSENT.repeat(totalColumns)
198
211
  }
@@ -224,81 +237,40 @@ export function renderRow(read: ReadLayout, layout: ColumnLayout) {
224
237
  continue
225
238
  }
226
239
  const refChar = pos < lastPos ? read.refChars[pos - read.start]! : ABSENT
227
- // a read that is not really here pads the insertion the same way it pads
228
- // the reference column, so an intron reads as one absence
229
- const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP
230
240
  const ins = read.insertions.get(pos) ?? ''
241
+ // insertion columns sit between pos - 1 and pos, so a read that is absent
242
+ // on either side, an intron or its own first base, does not span them
243
+ const spans =
244
+ ins !== '' ||
245
+ (refChar !== ABSENT &&
246
+ pos > read.start &&
247
+ read.refChars[pos - read.start - 1] !== ABSENT)
248
+ const pad = spans ? SPANNED_GAP : ABSENT
231
249
  ret += ins + pad.repeat(insWidths.get(pos)! - ins.length) + refChar
232
250
  pos++
233
251
  }
234
252
  return ret + ABSENT.repeat(totalColumns - offsets[to - start]!)
235
253
  }
236
254
 
237
- // A defline is truncated at its first space (msa-parsers' FastaMSA), so the
238
- // count is joined on. `labelsAlignRight` puts it flush against the sequence.
239
- const COPY_COUNT_SEPARATOR = '|'
240
-
241
255
  /**
242
- * What a row is called on screen. The one place `label` falls back to `name`,
243
- * so the defline and the tree leaf cannot disagree about it — react-msaview
244
- * joins them by string, and a row the tree names differently renders blank.
256
+ * The reference row's name, and the sample its row table entry gives it. Not
257
+ * the sequence's own name: react-msaview prints a row's residues as
258
+ * `<row>:<index>`, and `chr4:25` would read as a genome coordinate when it is an
259
+ * index into the window.
245
260
  */
246
- export function rowLabel(read: ReadLayout) {
247
- return read.label ?? read.name
248
- }
249
-
250
- /**
251
- * Rows ordered longest-allele-first and labelled with their copy count.
252
- *
253
- * Copy number is the measurement at a tandem array, and reading it off where a
254
- * row runs out is the thing the unit-per-block layout exists to avoid, so it is
255
- * stated in the label. Ordering by it puts the alleles in a ladder, which is
256
- * what makes one row's array comparable to the next at a glance. Rows that do
257
- * not span the array keep genomic order, below the ones that do; the reference
258
- * stays on top whatever its allele, since it is what the columns are named
259
- * after rather than one of the observations.
260
- */
261
- export function labelAndOrderByCopies(
262
- reads: ReadLayout[],
263
- array: ArrayBlock,
264
- referenceName?: string,
265
- ) {
266
- const rank = (read: ReadLayout) => (read.name === referenceName ? 1 : 0)
267
- return reads
268
- .map(read => ({ read, copies: array.copiesByName.get(read.name) }))
269
- .sort((a, b) => {
270
- const byRef = rank(b.read) - rank(a.read)
271
- if (byRef) {
272
- return byRef
273
- }
274
- if (a.copies === undefined || b.copies === undefined) {
275
- return a.copies === b.copies
276
- ? byStart(a.read, b.read)
277
- : a.copies === undefined
278
- ? 1
279
- : -1
280
- }
281
- return b.copies - a.copies || byStart(a.read, b.read)
282
- })
283
- .map(({ read, copies }) =>
284
- copies === undefined
285
- ? read
286
- : { ...read, label: `${read.name}${COPY_COUNT_SEPARATOR}n=${copies}` },
287
- )
288
- }
261
+ export const REFERENCE = 'reference'
289
262
 
290
263
  export interface TviewPlan {
291
264
  reads: ReadLayout[]
265
+ /** the row each feature became, parallel to the features planned */
266
+ featureNames: string[]
292
267
  layout: ColumnLayout
293
- insertionWidths: [number, number][]
294
- /** [start, end, width] per array block, to rebuild the column mapping */
295
- arraySpans: [number, number, number][]
296
268
  region: { refName: string; start: number; end: number }
297
269
  /** rows x columns, i.e. how big the alignment renderTviewMsa builds will be */
298
270
  cellCount: number
299
271
  /** tandem arrays the reference carries here, left to right */
300
272
  arrays: ArrayBlock[]
301
- /** the array the rows are ordered and labelled by, when there is one */
273
+ /** the array the rows are ordered by, when there is one */
302
274
  subject?: ArrayBlock
303
275
  /** name of the reference row, when the reference sequence was available */
304
276
  referenceName?: string
@@ -336,7 +308,7 @@ export function planTviewMsa({
336
308
  sequence,
337
309
  sampleOf,
338
310
  }: PlanArgs): TviewPlan {
339
- const names = getReadNames(features, sampleOf)
311
+ const names = getReadNames(features, [REFERENCE])
340
312
  const parsed = features
341
313
  .map((f, i) => parseRead(f, names[i]!, sampleOf?.(i)))
342
314
  .sort(byStart)
@@ -344,10 +316,11 @@ export function planTviewMsa({
344
316
  // The reference is laid out as a row like any other, which is what lets it be
345
317
  // one of the alleles an array block squares up rather than a thing the block
346
318
  // has to be compared against afterwards.
347
- const referenceName = sequence ? newickSafe(refName) : undefined
319
+ const referenceName = sequence ? REFERENCE : undefined
348
320
  const referenceRead: ReadLayout | undefined = sequence
349
321
  ? {
350
- name: referenceName!,
322
+ name: REFERENCE,
323
+ sample: REFERENCE,
351
324
  start,
352
325
  refChars: sequence.toUpperCase(),
353
326
  insertions: new Map(),
@@ -368,7 +341,17 @@ export function planTviewMsa({
368
341
  const intervals = sequence
369
342
  ? mergeArrays(findReferenceArrays(sequence, start))
370
343
  : []
371
- const anchored = reanchorInsertions(clipped, intervals)
344
+ const normalized = normalizeInsertions(
345
+ reanchorInsertions(clipped, intervals),
346
+ intervals,
347
+ start,
348
+ )
349
+ const anchored = referenceRead
350
+ ? mergeInsertionSites(normalized, intervals, {
351
+ seq: referenceRead.refChars,
352
+ start,
353
+ })
354
+ : normalized
372
355
  const arrays = buildArrayBlocks(anchored, intervals)
373
356
  const ownedByArray = new Set<number>()
374
357
  for (const array of arrays) {
@@ -387,39 +370,130 @@ export function planTviewMsa({
387
370
  best && alleleSpread(best) >= alleleSpread(array) ? best : array,
388
371
  undefined,
389
372
  )
390
- const reads = subject
391
- ? labelAndOrderByCopies(aligned, subject, referenceName)
392
- : aligned
393
-
394
- const insWidths = maxInsertionWidths(reads, ownedByArray)
373
+ const insWidths = maxInsertionWidths(aligned, ownedByArray)
395
374
  const layout = buildColumnLayout(start, end, insWidths, arrays)
396
375
 
397
376
  return {
398
- reads,
377
+ reads: aligned,
378
+ featureNames: names,
399
379
  layout,
400
- insertionWidths: [...insWidths.entries()].sort((a, b) => a[0] - b[0]),
401
- arraySpans: arrays.map(a => [a.start, a.end, a.width]),
402
380
  region: { refName, start, end },
403
- cellCount: reads.length * layout.totalColumns,
381
+ cellCount: aligned.length * layout.totalColumns,
404
382
  arrays,
405
383
  subject,
406
384
  referenceName,
407
385
  samples: [
408
- ...new Set(parsed.map(r => r.sample).filter(s => s !== undefined)),
386
+ ...new Set(
387
+ features.map((_, i) => sampleOf?.(i)).filter(s => s !== undefined),
388
+ ),
409
389
  ],
410
390
  }
411
391
  }
412
392
 
413
- export function renderTviewMsa({ reads, layout }: TviewPlan) {
414
- return reads.map(r => `>${rowLabel(r)}\n${renderRow(r, layout)}\n`).join('')
393
+ export function renderRows({ reads, layout }: TviewPlan) {
394
+ return reads.map(r => renderRow(r, layout))
395
+ }
396
+
397
+ export function toFasta({ reads }: TviewPlan, rows: string[]) {
398
+ return reads.map((r, i) => `>${r.name}\n${rows[i]}\n`).join('')
399
+ }
400
+
401
+ export function renderTviewMsa(plan: TviewPlan) {
402
+ return toFasta(plan, renderRows(plan))
403
+ }
404
+
405
+ /**
406
+ * What each row is, keyed by its name: the sample it came from and, where there
407
+ * is a subject array, the copies it carries there and their length in bp.
408
+ */
409
+ export function planRowData({ reads, subject }: TviewPlan): RowDataInput {
410
+ return Object.fromEntries(
411
+ reads.map(({ name, sample }) => {
412
+ const copies = subject?.copiesByName.get(name)
413
+ const alleleBp = subject?.lengthByName.get(name)
414
+ return [
415
+ name,
416
+ {
417
+ ...(sample === undefined ? {} : { sample }),
418
+ ...(copies === undefined ? {} : { copies }),
419
+ ...(alleleBp === undefined ? {} : { alleleBp }),
420
+ },
421
+ ]
422
+ }),
423
+ )
424
+ }
425
+
426
+ /** the value most of `values` share, the larger of two equally common */
427
+ function commonest(values: number[]) {
428
+ const counts = new Map<number, number>()
429
+ for (const value of values) {
430
+ counts.set(value, (counts.get(value) ?? 0) + 1)
431
+ }
432
+ return [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0])[0]![0]
433
+ }
434
+
435
+ // A bracket is kept in the session and drawn in one strip, and a noisy window
436
+ // has an insertion site every few bases, so only the sites carrying the most
437
+ // inserted sequence are marked.
438
+ const MAX_INSERTION_BRACKETS = 100
439
+
440
+ /**
441
+ * A bracket over the runs of columns that are not one reference base: the
442
+ * insertion sites, and each array block. Columns are the file's, 1-based.
443
+ */
444
+ export function planHighlights({
445
+ reads,
446
+ layout,
447
+ region,
448
+ referenceName,
449
+ }: TviewPlan): Highlight[] {
450
+ const { start, offsets, insWidths, arrays } = layout
451
+ const n = (x: number) => x.toLocaleString('en-US')
452
+ const column = (pos: number) => offsets[pos - start]! + 1
453
+ const lengthsAt = new Map<number, number[]>()
454
+ for (const read of reads) {
455
+ for (const [pos, ins] of read.insertions) {
456
+ const lengths = lengthsAt.get(pos) ?? []
457
+ lengths.push(ins.replaceAll(SPANNED_GAP, '').length)
458
+ lengthsAt.set(pos, lengths)
459
+ }
460
+ }
461
+ const insertedBases = (pos: number) =>
462
+ (lengthsAt.get(pos) ?? []).reduce((a, b) => a + b, 0)
463
+ const insertions = [...insWidths]
464
+ .filter(([, width]) => width > 0)
465
+ .sort((a, b) => insertedBases(b[0]) - insertedBases(a[0]) || a[0] - b[0])
466
+ .slice(0, MAX_INSERTION_BRACKETS)
467
+ .map(([pos, width]) => ({
468
+ start: column(pos),
469
+ end: column(pos) + width - 1,
470
+ label: `+${commonest(lengthsAt.get(pos) ?? [width])}bp after ${region.refName}:${n(pos)}`,
471
+ }))
472
+ const blocks = arrays.map(array => {
473
+ const copies = referenceName
474
+ ? array.copiesByName.get(referenceName)
475
+ : undefined
476
+ return {
477
+ start: column(array.start),
478
+ end: column(array.start) + array.width - 1,
479
+ label:
480
+ copies === undefined
481
+ ? `(${array.unit})n`
482
+ : `(${array.unit})x${copies} in the reference`,
483
+ }
484
+ })
485
+ return [...insertions, ...blocks]
486
+ .sort((a, b) => a.start - b.start)
487
+ .map((h): Highlight => ({ ...h, mark: 'bracket' }))
415
488
  }
416
489
 
417
490
  export function buildTviewMsa(args: PlanArgs) {
418
491
  const plan = planTviewMsa(args)
419
492
  return {
420
493
  msa: renderTviewMsa(plan),
421
- insertionWidths: plan.insertionWidths,
422
- arraySpans: plan.arraySpans,
494
+ rowData: planRowData(plan),
495
+ highlights: planHighlights(plan),
496
+ insertionWidths: [...plan.layout.insWidths].sort((a, b) => a[0] - b[0]),
423
497
  region: plan.region,
424
498
  arrays: plan.arrays,
425
499
  subject: plan.subject,
@@ -1,20 +1,45 @@
1
1
  import React from 'react'
2
2
 
3
+ import { ErrorMessage, LoadingEllipses } from '@jbrowse/core/ui'
4
+ import { Button, Typography } from '@mui/material'
3
5
  import { observer } from 'mobx-react'
4
6
  import { MSAView } from 'react-msaview'
5
7
 
6
8
  import type { JBrowsePluginTViewModel } from '../model'
7
- import type { MsaViewModel } from 'react-msaview'
9
+
10
+ const padded = { padding: 20 }
8
11
 
9
12
  const TViewPanel = observer(function TViewPanel2({
10
13
  model,
11
14
  }: {
12
15
  model: JBrowsePluginTViewModel
13
16
  }) {
14
- // react-msaview types its model prop with type: 'MsaView' baked in, but a
15
- // JBrowse view model's `type` must equal its registered view type name. That
16
- // literal is the only difference, and the MSA renderer never reads it.
17
- return <MSAView model={model as unknown as MsaViewModel} />
17
+ const state = model.viewState
18
+ return state.kind === 'alignment' ? (
19
+ <MSAView model={model} />
20
+ ) : (
21
+ <div style={padded}>
22
+ {state.kind === 'loading' ? (
23
+ <LoadingEllipses variant="h6" message={state.message} />
24
+ ) : state.kind === 'notice' ? (
25
+ <Typography>{state.message}</Typography>
26
+ ) : (
27
+ <>
28
+ <ErrorMessage error={state.error} />
29
+ {state.retry ? (
30
+ <Button
31
+ variant="contained"
32
+ onClick={() => {
33
+ model.retryLoad()
34
+ }}
35
+ >
36
+ Retry
37
+ </Button>
38
+ ) : null}
39
+ </>
40
+ )}
41
+ </div>
42
+ )
18
43
  })
19
44
 
20
45
  export default TViewPanel
@@ -0,0 +1,41 @@
1
+ export interface HoverPosition {
2
+ /** 1-based */
3
+ coord: number
4
+ refName: string
5
+ /** the genome view the cursor is in, where the host says */
6
+ viewId?: string
7
+ }
8
+
9
+ /** the base a genome view's cursor is over, from `session.hovered` */
10
+ export function hoverPosition(hovered: unknown): HoverPosition | undefined {
11
+ const hover = !!hovered && typeof hovered === 'object' ? hovered : undefined
12
+ const pos =
13
+ hover && 'hoverPosition' in hover ? hover.hoverPosition : undefined
14
+ const viewId =
15
+ hover && 'viewId' in hover && typeof hover.viewId === 'string'
16
+ ? hover.viewId
17
+ : undefined
18
+ return !!pos &&
19
+ typeof pos === 'object' &&
20
+ 'coord' in pos &&
21
+ typeof pos.coord === 'number' &&
22
+ 'refName' in pos &&
23
+ typeof pos.refName === 'string'
24
+ ? { coord: pos.coord, refName: pos.refName, viewId }
25
+ : undefined
26
+ }
27
+
28
+ /** how many entries of an ascending index are below `value` */
29
+ export function lowerBound(index: ArrayLike<number>, value: number) {
30
+ let lo = 0
31
+ let hi = index.length
32
+ while (lo < hi) {
33
+ const mid = (lo + hi) >>> 1
34
+ if (index[mid]! < value) {
35
+ lo = mid + 1
36
+ } else {
37
+ hi = mid
38
+ }
39
+ }
40
+ return lo
41
+ }
@@ -1,9 +1,9 @@
1
- import { readConfObject } from '@jbrowse/core/configuration'
2
1
  import { parseLocString } from '@jbrowse/core/util'
2
+ import { getTrackName } from '@jbrowse/core/util/tracks'
3
3
 
4
- import { findTrackConf } from '../LaunchTView/fetchTviewPlan'
4
+ import { MAX_BP } from '../LaunchTView/limits'
5
5
 
6
- import type { TviewSource } from '../LaunchTView/fetchTviewPlan'
6
+ import type { FetchRegion, TviewSource } from '../LaunchTView/fetchTviewPlan'
7
7
  import type { AbstractSessionModel } from '@jbrowse/core/util'
8
8
 
9
9
  /**
@@ -23,15 +23,14 @@ export type TviewTrackInit = string | { trackId: string; sample?: string }
23
23
  * - A session can **author** a tview. `{ type: 'TView', init: { … } }` in a
24
24
  * defaultSession opens one with no click path — as does the flat form of the
25
25
  * same keys in a session spec URL, which is what makes a repeat locus a link.
26
- * - There is one code path. Launching from the track menu, restoring a saved
27
- * session and following a link all end up applying the same blob, so the
28
- * launch dialog does not build the view — it names it.
26
+ * - There is one code path. Launching from a menu, restoring a saved session
27
+ * and following a link all end up applying the same blob, and changing what
28
+ * the view shows from its own menu is replacing that blob.
29
29
  *
30
30
  * Unlike LinearGenomeView's, this init is **kept, not cleared**. What it
31
- * resolves to is a multiple alignment held as one string, which react-msaview
32
- * drops from snapshots past 50kb and has no file to reload from; the blob is
33
- * both smaller than what it produces and the only durable statement of what the
34
- * view is.
31
+ * resolves to — the alignment and its row table — is kept out of snapshots and
32
+ * rebuilt from it on restore, so the blob is the only durable statement of what
33
+ * the view is.
35
34
  */
36
35
  export interface TviewInit {
37
36
  /** assembly the locus and the tracks belong to */
@@ -42,33 +41,76 @@ export interface TviewInit {
42
41
  tracks: TviewTrackInit[]
43
42
  }
44
43
 
45
- // Derived from the interface so it cannot drift: the Record requires exactly one
46
- // entry per key, so adding a field without listing it here is a compile error
47
- // rather than a key that silently reads as a view prop.
48
- const initKeyMap: Record<keyof TviewInit, true> = {
49
- assembly: true,
50
- loc: true,
51
- tracks: true,
44
+ export type RegionCheck =
45
+ | { region: FetchRegion; error?: undefined }
46
+ | { region?: undefined; error: string }
47
+
48
+ /** the slice of a loaded assembly that a locstring is resolved against */
49
+ export interface LocAssembly {
50
+ name: string
51
+ isValidRefName: (refName: string) => boolean
52
+ getCanonicalRefName2: (refName: string) => string
53
+ getRegionForRefName: (
54
+ refName: string,
55
+ ) => { start: number; end: number } | undefined
52
56
  }
53
- export const initKeys = new Set<string>(Object.keys(initKeyMap))
54
57
 
55
- /** the region `init.loc` names, or undefined until the assembly can parse it */
56
- export function initRegion(session: AbstractSessionModel, init: TviewInit) {
57
- const { assemblyManager } = session
58
- if (!assemblyManager.get(init.assembly)?.initialized) {
59
- return undefined
60
- }
61
- const parsed = parseLocString(init.loc, refName =>
62
- assemblyManager.isValidRefName(refName, init.assembly),
63
- )
64
- return {
65
- assemblyName: init.assembly,
66
- refName: parsed.refName,
67
- start: parsed.start ?? 0,
68
- end: parsed.end ?? 0,
58
+ function errorText(e: unknown) {
59
+ return e instanceof Error ? e.message : String(e)
60
+ }
61
+
62
+ /**
63
+ * The region `loc` names on `assembly`, under the assembly's own name for the
64
+ * sequence and clamped to it, or why there is none: a locstring that does not
65
+ * parse, a region off the end of the contig, or one wider than {@link MAX_BP}.
66
+ * A bare refName means the whole contig, and is held to the same limit.
67
+ */
68
+ export function checkRegion(assembly: LocAssembly, loc: string): RegionCheck {
69
+ try {
70
+ const parsed = parseLocString(loc, refName =>
71
+ assembly.isValidRefName(refName),
72
+ )
73
+ const refName = assembly.getCanonicalRefName2(parsed.refName)
74
+ const contig = assembly.getRegionForRefName(refName)
75
+ return contig
76
+ ? clampToContig({
77
+ assemblyName: assembly.name,
78
+ refName,
79
+ start: Math.max(contig.start, parsed.start ?? contig.start),
80
+ end: Math.min(contig.end, parsed.end ?? contig.end),
81
+ loc,
82
+ contigLength: contig.end,
83
+ })
84
+ : { error: `${assembly.name} has no sequence named ${refName}` }
85
+ } catch (e) {
86
+ return { error: errorText(e) }
69
87
  }
70
88
  }
71
89
 
90
+ function clampToContig({
91
+ loc,
92
+ contigLength,
93
+ ...region
94
+ }: FetchRegion & { loc: string; contigLength: number }): RegionCheck {
95
+ const width = region.end - region.start
96
+ const n = (x: number) => x.toLocaleString('en-US')
97
+ return width <= 0
98
+ ? {
99
+ error: `${loc} lies outside ${region.refName}, which is ${n(contigLength)}bp`,
100
+ }
101
+ : width > MAX_BP
102
+ ? {
103
+ error: `Region is ${n(width)}bp, wider than the ${n(MAX_BP)}bp limit`,
104
+ }
105
+ : { region }
106
+ }
107
+
108
+ /** {@link checkRegion} for `init`, or undefined until its assembly has loaded */
109
+ export function initRegion(session: AbstractSessionModel, init: TviewInit) {
110
+ const assembly = session.assemblyManager.get(init.assembly)
111
+ return assembly?.initialized ? checkRegion(assembly, init.loc) : undefined
112
+ }
113
+
72
114
  /**
73
115
  * One entry of `init.tracks`, resolved against the session.
74
116
  *
@@ -76,38 +118,47 @@ export function initRegion(session: AbstractSessionModel, init: TviewInit) {
76
118
  * — what the init asked for, what the track config is called, or the trackId —
77
119
  * is settled once, at the point where all three are in hand, so nothing
78
120
  * downstream has to ask again. `||` rather than `??` on purpose: a track
79
- * configured with `name: ''` should fall through to its id, not label a clade
121
+ * configured with `name: ''` should fall through to its id, not label a band
80
122
  * with an empty string.
81
123
  */
82
124
  interface ResolvedTrack {
83
125
  trackId: string
84
- adapterConfig: unknown
126
+ adapterConfig: Record<string, unknown>
85
127
  sample: string
86
128
  }
87
129
 
130
+ export function entryTrackId(entry: TviewTrackInit) {
131
+ return typeof entry === 'string' ? entry : entry.trackId
132
+ }
133
+
88
134
  function resolveTrack(
89
135
  session: AbstractSessionModel,
90
136
  entry: TviewTrackInit,
91
137
  ): ResolvedTrack | undefined {
92
- const { trackId, sample } =
93
- typeof entry === 'string' ? { trackId: entry, sample: undefined } : entry
94
- const conf = findTrackConf(session, trackId)
138
+ const trackId = entryTrackId(entry)
139
+ const sample = typeof entry === 'string' ? undefined : entry.sample
140
+ const conf = session.getTrackById(trackId)
95
141
  return conf
96
142
  ? {
97
143
  trackId,
98
- adapterConfig: readConfObject(conf, 'adapter'),
99
- sample: sample || (readConfObject(conf, 'name') as string) || trackId,
144
+ adapterConfig: conf.adapter as Record<string, unknown>,
145
+ sample: sample || getTrackName(conf, session) || trackId,
100
146
  }
101
147
  : undefined
102
148
  }
103
149
 
150
+ /** what rows from `entry` are grouped under, or its trackId if no track has it */
151
+ export function trackLabel(
152
+ session: AbstractSessionModel,
153
+ entry: TviewTrackInit,
154
+ ) {
155
+ return resolveTrack(session, entry)?.sample ?? entryTrackId(entry)
156
+ }
157
+
104
158
  /**
105
159
  * The sources `init.tracks` names, or undefined until every one of them
106
160
  * resolves. All or nothing: a partial set comes back with samples missing and
107
161
  * nothing on screen says any were.
108
- *
109
- * Whether the names are *used* is decided here and only here — one file's rows
110
- * need no prefix, and would gain a tree of one clade drawn beside a list.
111
162
  */
112
163
  export function initSources(
113
164
  session: AbstractSessionModel,
@@ -115,13 +166,15 @@ export function initSources(
115
166
  ): TviewSource[] | undefined {
116
167
  const resolved = init.tracks.map(entry => resolveTrack(session, entry))
117
168
  const found = resolved.filter(t => t !== undefined)
118
- if (found.length !== init.tracks.length) {
119
- return undefined
120
- }
121
- const labelled = found.length > 1
122
- return found.map(track => ({
123
- trackId: track.trackId,
124
- adapterConfig: track.adapterConfig,
125
- sample: labelled ? track.sample : undefined,
126
- }))
169
+ return found.length === init.tracks.length ? found : undefined
170
+ }
171
+
172
+ /** the trackIds `init.tracks` names that this session has no track for */
173
+ export function missingTrackIds(
174
+ session: AbstractSessionModel,
175
+ init: TviewInit,
176
+ ) {
177
+ return init.tracks
178
+ .map(entryTrackId)
179
+ .filter(trackId => !session.getTrackById(trackId))
127
180
  }