jbrowse-plugin-tview 2.0.4 → 2.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 (73) hide show
  1. package/README.md +157 -4
  2. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.d.ts +132 -0
  3. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js +152 -0
  4. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js.map +1 -0
  5. package/dist/LaunchTView/TviewGetPlanRpc/index.d.ts +3 -0
  6. package/dist/LaunchTView/TviewGetPlanRpc/index.js +5 -0
  7. package/dist/LaunchTView/TviewGetPlanRpc/index.js.map +1 -0
  8. package/dist/LaunchTView/align.d.ts +93 -9
  9. package/dist/LaunchTView/align.js +290 -15
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +57 -0
  12. package/dist/LaunchTView/alleles.js +94 -0
  13. package/dist/LaunchTView/alleles.js.map +1 -0
  14. package/dist/LaunchTView/components/ArrayReport.d.ts +10 -0
  15. package/dist/LaunchTView/components/ArrayReport.js +59 -0
  16. package/dist/LaunchTView/components/ArrayReport.js.map +1 -0
  17. package/dist/LaunchTView/components/LaunchTViewDialog.js +74 -37
  18. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +1 -1
  19. package/dist/LaunchTView/fetchTviewPlan.d.ts +20 -13
  20. package/dist/LaunchTView/fetchTviewPlan.js +27 -27
  21. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -1
  22. package/dist/LaunchTView/launchView.d.ts +25 -0
  23. package/dist/LaunchTView/launchView.js +20 -0
  24. package/dist/LaunchTView/launchView.js.map +1 -0
  25. package/dist/LaunchTView/readLayout.d.ts +85 -0
  26. package/dist/LaunchTView/readLayout.js +96 -0
  27. package/dist/LaunchTView/readLayout.js.map +1 -0
  28. package/dist/LaunchTView/repeats.d.ts +68 -0
  29. package/dist/LaunchTView/repeats.js +200 -0
  30. package/dist/LaunchTView/repeats.js.map +1 -0
  31. package/dist/LaunchTView/sampleTree.d.ts +37 -0
  32. package/dist/LaunchTView/sampleTree.js +65 -0
  33. package/dist/LaunchTView/sampleTree.js.map +1 -0
  34. package/dist/LaunchTView/tview.d.ts +67 -44
  35. package/dist/LaunchTView/tview.js +190 -121
  36. package/dist/LaunchTView/tview.js.map +1 -1
  37. package/dist/LaunchTView/useTviewMsa.d.ts +13 -9
  38. package/dist/LaunchTView/useTviewMsa.js +15 -11
  39. package/dist/LaunchTView/useTviewMsa.js.map +1 -1
  40. package/dist/TViewPanel/coords.d.ts +9 -1
  41. package/dist/TViewPanel/coords.js +22 -2
  42. package/dist/TViewPanel/coords.js.map +1 -1
  43. package/dist/TViewPanel/init.d.ts +56 -0
  44. package/dist/TViewPanel/init.js +59 -0
  45. package/dist/TViewPanel/init.js.map +1 -0
  46. package/dist/TViewPanel/model.d.ts +56 -40
  47. package/dist/TViewPanel/model.js +73 -51
  48. package/dist/TViewPanel/model.js.map +1 -1
  49. package/dist/index.js +5 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/jbrowse-plugin-tview.umd.production.min.js +59 -21
  52. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +7 -3
  56. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +264 -0
  57. package/src/LaunchTView/TviewGetPlanRpc/index.ts +14 -0
  58. package/src/LaunchTView/align.ts +343 -17
  59. package/src/LaunchTView/alleles.ts +132 -0
  60. package/src/LaunchTView/components/ArrayReport.tsx +64 -0
  61. package/src/LaunchTView/components/LaunchTViewDialog.tsx +122 -39
  62. package/src/LaunchTView/fetchTviewPlan.ts +42 -42
  63. package/src/LaunchTView/launchView.ts +50 -0
  64. package/src/LaunchTView/readLayout.ts +145 -0
  65. package/src/LaunchTView/repeats.ts +218 -0
  66. package/src/LaunchTView/sampleTree.ts +73 -0
  67. package/src/LaunchTView/tview.ts +259 -157
  68. package/src/LaunchTView/useTviewMsa.ts +20 -17
  69. package/src/TViewPanel/coords.ts +23 -1
  70. package/src/TViewPanel/init.ts +127 -0
  71. package/src/TViewPanel/model.ts +82 -61
  72. package/src/index.ts +5 -1
  73. package/src/version.ts +1 -1
@@ -1,4 +1,4 @@
1
- import React from 'react'
1
+ import React, { useState } from 'react'
2
2
 
3
3
  import { getConf } from '@jbrowse/core/configuration'
4
4
  import { Dialog, ErrorMessage } from '@jbrowse/core/ui'
@@ -7,15 +7,42 @@ import {
7
7
  getContainingView,
8
8
  getSession,
9
9
  } from '@jbrowse/core/util'
10
- import { Button, DialogActions, DialogContent } from '@mui/material'
10
+ import {
11
+ Button,
12
+ Checkbox,
13
+ DialogActions,
14
+ DialogContent,
15
+ FormControlLabel,
16
+ Typography,
17
+ } from '@mui/material'
11
18
 
12
- import { MAX_BP, MAX_CELLS } from '../limits'
13
- import { renderTviewMsa } from '../tview'
19
+ import ArrayReport from './ArrayReport'
20
+ import { MAX_BP } from '../limits'
14
21
  import { useTviewMsa } from '../useTviewMsa'
15
22
 
23
+ import type { TviewInit } from '../../TViewPanel/init'
16
24
  import type { AbstractTrackModel } from '@jbrowse/core/util'
17
25
  import type { LinearGenomeViewModel } from '@jbrowse/plugin-linear-genome-view'
18
26
 
27
+ // how much of the alignment the default column width aims to put on screen
28
+ const FIT_WIDTH_PX = 3000
29
+
30
+ function trackLabel(track: AbstractTrackModel) {
31
+ return (
32
+ (getConf(track, 'name') as string) || (getConf(track, 'trackId') as string)
33
+ )
34
+ }
35
+
36
+ /** every alignments track open in the same view, the launching one first */
37
+ function peerTracks(view: LinearGenomeViewModel, model: AbstractTrackModel) {
38
+ const alignments = view.tracks.filter(track =>
39
+ track.displays.some(
40
+ (display: { type: string }) => display.type === 'LinearAlignmentsDisplay',
41
+ ),
42
+ ) as AbstractTrackModel[]
43
+ return [model, ...alignments.filter(t => t.id !== model.id)]
44
+ }
45
+
19
46
  export default function LaunchTViewDialog({
20
47
  handleClose,
21
48
  model,
@@ -26,8 +53,6 @@ export default function LaunchTViewDialog({
26
53
  const view = getContainingView(model) as LinearGenomeViewModel
27
54
  const session = getSession(model)
28
55
  const block = view.dynamicBlocks.contentBlocks[0]
29
- // assemblyName is required: the RPC uses it to map the view's refName onto
30
- // whatever the file calls that sequence (refNameAliases)
31
56
  const region = block
32
57
  ? {
33
58
  assemblyName: block.assemblyName,
@@ -39,16 +64,42 @@ export default function LaunchTViewDialog({
39
64
  const width = region ? region.end - region.start : 0
40
65
  const tooWide = width > MAX_BP
41
66
 
67
+ const candidates = peerTracks(view, model)
68
+ // the launching track is always in; the others are opt-in, because pulling
69
+ // every open pileup into one alignment is a much bigger fetch than the menu
70
+ // item that got here suggests
71
+ const [extra, setExtra] = useState<string[]>([])
72
+ const chosen = candidates.filter(
73
+ t => t.id === model.id || extra.includes(t.id),
74
+ )
75
+
76
+ // The dialog's whole output. Everything below either previews what this
77
+ // resolves to or hands it to a view, so what the button opens is the same
78
+ // blob a session could have been authored with.
79
+ const init: TviewInit | undefined = region
80
+ ? {
81
+ assembly: region.assemblyName,
82
+ loc: assembleLocString(region),
83
+ tracks: chosen.map(t => ({
84
+ trackId: getConf(t, 'trackId') as string,
85
+ sample: trackLabel(t),
86
+ })),
87
+ }
88
+ : undefined
89
+
42
90
  const { data, error, isLoading } = useTviewMsa({
43
- model,
44
- region: tooWide ? undefined : region,
91
+ session,
92
+ init: tooWide ? undefined : init,
45
93
  })
46
- const displayName = region ? assembleLocString(region) : 'Unknown'
47
- const tooLarge = !!data && data.plan.cellCount > MAX_CELLS
48
- // lets the view rebuild itself after a session reload
49
- const msaSource = region
50
- ? { trackId: getConf(model, 'trackId'), assemblyName: region.assemblyName }
51
- : undefined
94
+
95
+ // 10 is comfortable for an ordinary pileup, but an unrolled tandem array runs
96
+ // to hundreds of columns and at 10 almost none of it is on screen at once.
97
+ // Fits the alignment to roughly two screen-widths; a no-op for the narrow
98
+ // regions that already fitted.
99
+ const totalColumns = data?.columnCount ?? 0
100
+ const colWidth = totalColumns
101
+ ? Math.max(1, Math.min(10, Math.floor(FIT_WIDTH_PX / totalColumns)))
102
+ : 10
52
103
 
53
104
  return (
54
105
  <Dialog
@@ -60,53 +111,85 @@ export default function LaunchTViewDialog({
60
111
  open
61
112
  >
62
113
  <DialogContent>
63
- <div>
114
+ <Typography>
64
115
  Create a view similar to "samtools tview" for the reads in the current
65
- region: {displayName}
66
- </div>
67
- {tooWide ? (
116
+ region: {init?.loc ?? 'Unknown'}
117
+ </Typography>
118
+ {candidates.length > 1 ? (
68
119
  <div>
120
+ <Typography variant="subtitle2">
121
+ Include reads from other alignment tracks in this view
122
+ </Typography>
123
+ {candidates.slice(1).map(track => (
124
+ <FormControlLabel
125
+ key={track.id}
126
+ control={
127
+ <Checkbox
128
+ checked={extra.includes(track.id)}
129
+ onChange={event => {
130
+ setExtra(
131
+ event.target.checked
132
+ ? [...extra, track.id]
133
+ : extra.filter(id => id !== track.id),
134
+ )
135
+ }}
136
+ />
137
+ }
138
+ label={trackLabel(track)}
139
+ />
140
+ ))}
141
+ </div>
142
+ ) : null}
143
+ {tooWide ? (
144
+ <Typography>
69
145
  Region is {width.toLocaleString('en-US')}bp, wider than the{' '}
70
146
  {MAX_BP.toLocaleString('en-US')}bp limit. Zoom in and try again.
71
- </div>
147
+ </Typography>
72
148
  ) : error ? (
73
149
  <ErrorMessage error={error} />
74
150
  ) : isLoading ? (
75
- <div>Loading...</div>
76
- ) : tooLarge ? (
77
- <div>
78
- {data.rowCount.toLocaleString('en-US')} reads over{' '}
79
- {data.plan.layout.totalColumns.toLocaleString('en-US')} columns is{' '}
80
- {data.plan.cellCount.toLocaleString('en-US')} cells, above the{' '}
81
- {MAX_CELLS.toLocaleString('en-US')} limit. Zoom in and try again.
82
- </div>
151
+ <Typography>Loading...</Typography>
152
+ ) : data?.tooLarge ? (
153
+ <Typography>
154
+ {data.rowCount.toLocaleString('en-US')} rows over{' '}
155
+ {data.columnCount.toLocaleString('en-US')} columns is{' '}
156
+ {data.cellCount.toLocaleString('en-US')} cells, which is too large
157
+ to render. Zoom in and try again.
158
+ </Typography>
83
159
  ) : data ? (
84
- <div>{data.rowCount} reads with sequence data found</div>
160
+ <>
161
+ <Typography>
162
+ {data.rowCount} rows
163
+ {data.referenceName
164
+ ? ' (the reference plus every read with sequence)'
165
+ : ' of reads with sequence data'}
166
+ {data.samples.length > 1
167
+ ? `, from ${data.samples.length} tracks`
168
+ : ''}
169
+ </Typography>
170
+ <ArrayReport data={data} />
171
+ </>
85
172
  ) : (
86
- <div>No region is currently visible.</div>
173
+ <Typography>No region is currently visible.</Typography>
87
174
  )}
88
175
  </DialogContent>
89
176
  <DialogActions>
90
177
  <Button
91
178
  variant="contained"
92
179
  color="primary"
93
- disabled={!data?.rowCount || tooLarge}
180
+ disabled={!data?.msa || !init}
94
181
  onClick={() => {
95
- if (data && !tooLarge) {
182
+ if (init) {
96
183
  session.addView('TView', {
97
184
  type: 'TView',
98
- displayName,
99
- colWidth: 10,
185
+ displayName: init.loc,
186
+ init,
187
+ colWidth,
100
188
  rowHeight: 12,
101
189
  labelsAlignRight: true,
102
190
  colorSchemeName: 'jbrowse_dna',
191
+ drawTree: init.tracks.length > 1,
103
192
  connectedViewId: view.id,
104
- msaRegion: data.plan.region,
105
- insertionWidths: data.plan.insertionWidths,
106
- msaSource,
107
- data: {
108
- msa: renderTviewMsa(data.plan),
109
- },
110
193
  })
111
194
  }
112
195
  handleClose()
@@ -1,14 +1,10 @@
1
- import { getConf, readConfObject } from '@jbrowse/core/configuration'
2
- import { getRpcSessionId } from '@jbrowse/core/util/tracks'
1
+ import { readConfObject } from '@jbrowse/core/configuration'
3
2
 
4
- import { planTviewMsa } from './tview'
3
+ import { MAX_CELLS } from './limits'
5
4
 
5
+ import type { TviewPlanResult } from './TviewGetPlanRpc'
6
6
  import type { AnyConfigurationModel } from '@jbrowse/core/configuration'
7
- import type {
8
- AbstractSessionModel,
9
- AbstractTrackModel,
10
- Feature,
11
- } from '@jbrowse/core/util'
7
+ import type { AbstractSessionModel } from '@jbrowse/core/util'
12
8
 
13
9
  /** the RPC needs assemblyName to resolve refNameAliases for the file */
14
10
  export interface FetchRegion {
@@ -18,17 +14,12 @@ export interface FetchRegion {
18
14
  end: number
19
15
  }
20
16
 
21
- /** what CoreGetFeatures needs, reachable from a live track or from its config */
17
+ /** one track's worth of rows, and the name they are grouped under */
22
18
  export interface TviewSource {
23
19
  adapterConfig: unknown
24
- rpcSessionId: string
25
- }
26
-
27
- export function sourceFromTrack(track: AbstractTrackModel): TviewSource {
28
- return {
29
- adapterConfig: getConf(track, 'adapter'),
30
- rpcSessionId: getRpcSessionId(track),
31
- }
20
+ /** the label rows from this file carry; omitted when there is only one */
21
+ sample?: string
22
+ trackId: string
32
23
  }
33
24
 
34
25
  /**
@@ -57,39 +48,48 @@ export function findTrackConf(session: SessionTrackLookup, trackId: string) {
57
48
  }
58
49
 
59
50
  /**
60
- * A rebuild runs from the track's config rather than a track model, so it works
61
- * whether or not the track is still open anywhere in the session.
51
+ * The assembly's own sequence adapter, which is what makes the reference a row
52
+ * and, through it, makes an array an interval rather than an insertion. An
53
+ * assembly that cannot supply one still works: the alignment is then reads only
54
+ * and no array is reported, which is the pre-reference behaviour.
62
55
  */
63
- export function sourceFromConfig(conf: AnyConfigurationModel): TviewSource {
64
- return {
65
- adapterConfig: readConfObject(conf, 'adapter'),
66
- rpcSessionId: `tview-${readConfObject(conf, 'trackId')}`,
67
- }
56
+ export function sequenceAdapterConfig(
57
+ session: AbstractSessionModel,
58
+ assemblyName: string,
59
+ ) {
60
+ const assembly = session.assemblyManager.get(assemblyName)
61
+ const conf = assembly?.configuration
62
+ return conf
63
+ ? (readConfObject(conf, ['sequence', 'adapter']) as
64
+ Record<string, unknown> | undefined)
65
+ : undefined
68
66
  }
69
67
 
68
+ /**
69
+ * One RPC per launch, however many files it draws from. The session id is
70
+ * shared across the sources so the worker keeps one adapter cache for the view
71
+ * rather than one per file.
72
+ */
70
73
  export async function fetchTviewPlan({
71
74
  session,
72
- source,
75
+ sources,
73
76
  region,
77
+ maxCells = MAX_CELLS,
74
78
  }: {
75
79
  session: AbstractSessionModel
76
- source: TviewSource
80
+ sources: TviewSource[]
77
81
  region: FetchRegion
82
+ maxCells?: number
78
83
  }) {
79
- const { adapterConfig, rpcSessionId } = source
80
- const feats = (await session.rpcManager.call(
81
- rpcSessionId,
82
- 'CoreGetFeatures',
83
- {
84
- adapterConfig,
85
- sessionId: rpcSessionId,
86
- regions: [region],
87
- },
88
- )) as Feature[]
89
- const features = feats.filter(f => !!f.get('seq'))
90
- // only planned, not rendered: a caller may cancel, or find it too large
91
- return {
92
- plan: planTviewMsa({ features, ...region }),
93
- rowCount: features.length,
94
- }
84
+ const rpcSessionId = `tview-${sources.map(s => s.trackId).join(',')}`
85
+ return (await session.rpcManager.call(rpcSessionId, 'TviewGetPlan', {
86
+ sessionId: rpcSessionId,
87
+ sources: sources.map(s => ({
88
+ adapterConfig: s.adapterConfig,
89
+ sample: s.sample,
90
+ })),
91
+ sequenceAdapterConfig: sequenceAdapterConfig(session, region.assemblyName),
92
+ region,
93
+ maxCells,
94
+ })) as TviewPlanResult
95
95
  }
@@ -0,0 +1,50 @@
1
+ import { initKeys } from '../TViewPanel/init'
2
+
3
+ import type { TviewInit } from '../TViewPanel/init'
4
+ import type PluginManager from '@jbrowse/core/PluginManager'
5
+ import type { AbstractSessionModel } from '@jbrowse/core/util'
6
+
7
+ /**
8
+ * `LaunchView-TView`, so a session spec URL can open one.
9
+ *
10
+ * The two ways of writing a view are not the same shape, and JBrowse's spec
11
+ * loader says so out loud: a spec view is **flat arguments** to this launcher,
12
+ * while a config or defaultSession view is MST state, where anything needing
13
+ * resolution on load lives under the view's own `init`. So the spec
14
+ *
15
+ * { type: 'TView', assembly: 'hg19', loc: 'chrX:1..2', tracks: ['HG002'] }
16
+ *
17
+ * and the config
18
+ *
19
+ * { type: 'TView', init: { assembly: 'hg19', loc: '…', tracks: […] } }
20
+ *
21
+ * are the same view, and this is the one line between them. Splitting on
22
+ * `initKeys` rather than listing the pass-through props means every react-msaview
23
+ * view prop — colWidth, rowHeight, colorSchemeName, the ones added next — rides
24
+ * along without being enumerated here.
25
+ */
26
+ export type LaunchTViewArgs = { session: AbstractSessionModel } & Record<
27
+ string,
28
+ unknown
29
+ >
30
+
31
+ export default function LaunchTViewF(pluginManager: PluginManager) {
32
+ /** #extensionPoint LaunchView-TView | async | Programmatically launch a tview */
33
+ pluginManager.addToExtensionPoint(
34
+ 'LaunchView-TView',
35
+ (args: LaunchTViewArgs) => {
36
+ const { session, ...spec } = args
37
+ const init: Record<string, unknown> = {}
38
+ const viewProps: Record<string, unknown> = {}
39
+ for (const [key, value] of Object.entries(spec)) {
40
+ ;(initKeys.has(key) ? init : viewProps)[key] = value
41
+ }
42
+ session.addView('TView', {
43
+ type: 'TView',
44
+ ...viewProps,
45
+ init: init as unknown as TviewInit,
46
+ })
47
+ return args
48
+ },
49
+ )
50
+ }
@@ -0,0 +1,145 @@
1
+ import { newickSafe } from './sampleTree'
2
+
3
+ /** the subset of an @jbrowse/core Feature that the layout reads */
4
+ export interface AlignmentFeature {
5
+ get: (key: string) => any
6
+ }
7
+
8
+ /**
9
+ * Only '-' and '.' are treated as gaps by react-msaview (anything else counts
10
+ * as a base in the conservation track and column stats), so the two of them
11
+ * carry the whole vocabulary for "no base here". They are split by meaning:
12
+ *
13
+ * - SPANNED_GAP: the read covers this reference position but aligns no base to
14
+ * it, i.e. a deletion, or padding in an insertion column
15
+ * - ABSENT: the read is not here at all, i.e. outside its bounds, or skipping
16
+ * over the position through an N (an intron, not a deleted allele)
17
+ */
18
+ export const SPANNED_GAP = '-'
19
+ export const ABSENT = '.'
20
+
21
+ export interface ReadLayout {
22
+ /**
23
+ * Identity. Every per-row lookup is keyed by this — the array blocks, the
24
+ * tree — so it is fixed once, here, and nothing downstream rewrites it.
25
+ */
26
+ name: string
27
+ /**
28
+ * What the row is called on screen, when that is not just its name. Kept
29
+ * apart from `name` because the copy-number label is added after the array
30
+ * blocks are built and keyed: renaming in place instead left every labelled
31
+ * row unable to find its own block, and the block fell back to gaps — a row
32
+ * that silently loses its sequence while keeping its label.
33
+ */
34
+ label?: string
35
+ /**
36
+ * The sample the row belongs to, when several were loaded at once. Already
37
+ * Newick-safe, and the same string the row's own name is prefixed with, so
38
+ * the clade label and its leaves agree.
39
+ */
40
+ sample?: string
41
+ start: number
42
+ /** one char per reference position consumed: the aligned base, or a gap */
43
+ refChars: string
44
+ /** reference position -> bases inserted immediately before that position */
45
+ insertions: Map<number, string>
46
+ }
47
+
48
+ const cigarRegex = /([MIDNSHPX=])/
49
+
50
+ export const byStart = (a: ReadLayout, b: ReadLayout) => a.start - b.start
51
+
52
+ export function parseCigar(cigar: string) {
53
+ return cigar.split(cigarRegex).slice(0, -1)
54
+ }
55
+
56
+ export function parseRead(
57
+ feature: AlignmentFeature,
58
+ name: string,
59
+ sample?: string,
60
+ ): ReadLayout {
61
+ const seq = feature.get('seq') as string
62
+ const ops = parseCigar(feature.get('CIGAR') as string)
63
+ const start = feature.get('start')
64
+ const insertions = new Map<number, string>()
65
+ let refChars = ''
66
+ let seqOffset = 0
67
+
68
+ for (let i = 0; i < ops.length; i += 2) {
69
+ const len = +ops[i]!
70
+ const op = ops[i + 1]!
71
+ if (op === 'S') {
72
+ seqOffset += len
73
+ } else if (op === 'I') {
74
+ // consecutive I ops (e.g. 3M2I3I3M) land on the same reference position
75
+ const pos = start + refChars.length
76
+ const prev = insertions.get(pos) ?? ''
77
+ insertions.set(pos, prev + seq.slice(seqOffset, seqOffset + len))
78
+ seqOffset += len
79
+ } else if (op === 'D') {
80
+ refChars += SPANNED_GAP.repeat(len)
81
+ } else if (op === 'N') {
82
+ refChars += ABSENT.repeat(len)
83
+ } else if (op === 'M' || op === 'X' || op === '=') {
84
+ refChars += seq.slice(seqOffset, seqOffset + len)
85
+ seqOffset += len
86
+ }
87
+ // H and P consume neither the read sequence nor the reference
88
+ }
89
+ // sanitized here, the same way getReadNames sanitizes the prefix it builds
90
+ // from it, so the clade label and the leaves inside it are one string
91
+ return {
92
+ name,
93
+ sample: sample === undefined ? undefined : newickSafe(sample),
94
+ start,
95
+ refChars,
96
+ insertions,
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Reads are fetched by overlap, so they carry insertions on either side of the
102
+ * region. Those get no columns and are never rendered, so dropping them keeps
103
+ * the pairwise alignment below off the wasted sites entirely.
104
+ */
105
+ export function clipInsertions(
106
+ reads: ReadLayout[],
107
+ start: number,
108
+ end: number,
109
+ ) {
110
+ return reads.map(read => ({
111
+ ...read,
112
+ insertions: new Map(
113
+ [...read.insertions].filter(([pos]) => pos >= start && pos < end),
114
+ ),
115
+ }))
116
+ }
117
+
118
+ function mateSuffix(flags: number | undefined) {
119
+ return flags === undefined || !(flags & 1) ? '' : flags & 64 ? '/1' : '/2'
120
+ }
121
+
122
+ /**
123
+ * MSA rows are keyed by name, so mates and duplicate names need disambiguating.
124
+ * With several samples loaded at once the same read name can also arrive twice
125
+ * from two files, which the sample prefix separates before the counter has to.
126
+ *
127
+ * The name is made Newick-safe here rather than where the tree is written,
128
+ * because the tree names the same rows the FASTA does and the two have to agree
129
+ * exactly. '|' separates the parts because ':' opens a branch length.
130
+ */
131
+ export function getReadNames(
132
+ features: AlignmentFeature[],
133
+ sampleOf?: (index: number) => string | undefined,
134
+ ) {
135
+ const counts = new Map<string, number>()
136
+ return features.map((f, i) => {
137
+ const sample = sampleOf?.(i)
138
+ const prefix = sample ? `${newickSafe(sample)}|` : ''
139
+ const name = newickSafe(String(f.get('name')))
140
+ const base = `${prefix}${name}${mateSuffix(f.get('flags'))}`
141
+ const n = (counts.get(base) ?? 0) + 1
142
+ counts.set(base, n)
143
+ return n === 1 ? base : `${base}_${n}`
144
+ })
145
+ }