jbrowse-plugin-graphgenomeviewer 4.7.0 → 5.0.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 (65) hide show
  1. package/README.md +7 -1
  2. package/dist/chunks/ChooseWalksDialog-GVQLSGHX.js +2 -0
  3. package/dist/chunks/ChooseWalksDialog-GVQLSGHX.js.map +7 -0
  4. package/dist/chunks/GbzBaseSyntenyAdapter-CKKVHC2R.js +4 -0
  5. package/dist/chunks/GbzBaseSyntenyAdapter-CKKVHC2R.js.map +7 -0
  6. package/dist/chunks/{GraphGenomeView-HZ2EQUOC.js → GraphGenomeView-YYP4IFSI.js} +2 -2
  7. package/dist/chunks/{GraphTrackSettingsDialog-JVPM25GV.js → GraphTrackSettingsDialog-2WPJRAJC.js} +2 -2
  8. package/dist/chunks/LinearGraphDisplay-7YE624D5.js +2 -0
  9. package/dist/chunks/LinearGraphDisplay-7YE624D5.js.map +7 -0
  10. package/dist/chunks/chunk-2H7GDQ3R.js +6 -0
  11. package/dist/chunks/chunk-2H7GDQ3R.js.map +7 -0
  12. package/dist/chunks/chunk-BZOIENU5.js +2 -0
  13. package/dist/chunks/chunk-BZOIENU5.js.map +7 -0
  14. package/dist/chunks/{chunk-UTWFU4X6.js → chunk-H54W6OQQ.js} +2 -2
  15. package/dist/chunks/{chunk-UTWFU4X6.js.map → chunk-H54W6OQQ.js.map} +4 -4
  16. package/dist/chunks/{chunk-F2EPKNTV.js → chunk-O4XV3K35.js} +2 -2
  17. package/dist/chunks/{chunk-F2EPKNTV.js.map → chunk-O4XV3K35.js.map} +4 -4
  18. package/dist/chunks/chunk-SJNG2XK7.js +2 -0
  19. package/dist/chunks/chunk-SJNG2XK7.js.map +7 -0
  20. package/dist/chunks/chunk-WKVVIDCS.js +3 -0
  21. package/dist/chunks/{chunk-KCL5TF5X.js.map → chunk-WKVVIDCS.js.map} +3 -3
  22. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -5
  23. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
  24. package/package.json +3 -3
  25. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.test.ts +36 -2
  26. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.ts +67 -1
  27. package/src/GbzBaseSyntenyAdapter/test_data/fragmented.haplotype-index.db +0 -0
  28. package/src/GbzBaseSyntenyAdapter/test_data/micb-kir3dl1.haplotype-index.db +0 -0
  29. package/src/GbzBaseSyntenyAdapter/test_data/micb-kir3dl1.sampled.haplotype-index.db +0 -0
  30. package/src/GetHaplotypeOverview.ts +77 -0
  31. package/src/GraphGenomeView/components/ChooseWalksDialog.tsx +86 -0
  32. package/src/GraphGenomeView/components/GraphSettingsDialog.tsx +205 -187
  33. package/src/GraphGenomeView/components/TubeMapLegend.test.tsx +29 -0
  34. package/src/GraphGenomeView/components/TubeMapOverlay.tsx +8 -0
  35. package/src/GraphGenomeView/host.ts +6 -0
  36. package/src/GraphGenomeView/model.ts +10 -4224
  37. package/src/GraphGenomeView/pane/fitViews.ts +589 -0
  38. package/src/GraphGenomeView/pane/graphViews.ts +829 -0
  39. package/src/GraphGenomeView/pane/hostViews.ts +193 -0
  40. package/src/GraphGenomeView/pane/launchActions.ts +407 -0
  41. package/src/GraphGenomeView/pane/launchViews.ts +191 -0
  42. package/src/GraphGenomeView/pane/loadActions.ts +701 -0
  43. package/src/GraphGenomeView/pane/paneBase.ts +479 -0
  44. package/src/GraphGenomeView/pane/renderingActions.ts +281 -0
  45. package/src/GraphGenomeView/pane/settingActions.ts +467 -0
  46. package/src/GraphGenomeView/pane/walkRowViews.ts +205 -0
  47. package/src/HaplotypeOverview/HaplotypeOverviewCanvas.tsx +203 -0
  48. package/src/HaplotypeOverview/draw.test.ts +136 -0
  49. package/src/HaplotypeOverview/draw.ts +433 -0
  50. package/src/HaplotypeOverview/model.ts +163 -0
  51. package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +184 -0
  52. package/src/LinearGraphDisplay/components/LinearGraphDisplay.tsx +12 -2
  53. package/src/LinearGraphDisplay/model.ts +107 -3
  54. package/src/gaf/gafFile.ts +2 -0
  55. package/src/index.ts +2 -0
  56. package/src/version.ts +1 -1
  57. package/dist/chunks/GbzBaseSyntenyAdapter-AZBYMDIW.js +0 -8
  58. package/dist/chunks/GbzBaseSyntenyAdapter-AZBYMDIW.js.map +0 -7
  59. package/dist/chunks/LinearGraphDisplay-MJ4ZBJRX.js +0 -2
  60. package/dist/chunks/LinearGraphDisplay-MJ4ZBJRX.js.map +0 -7
  61. package/dist/chunks/chunk-BUXVOMDL.js +0 -2
  62. package/dist/chunks/chunk-BUXVOMDL.js.map +0 -7
  63. package/dist/chunks/chunk-KCL5TF5X.js +0 -3
  64. /package/dist/chunks/{GraphGenomeView-HZ2EQUOC.js.map → GraphGenomeView-YYP4IFSI.js.map} +0 -0
  65. /package/dist/chunks/{GraphTrackSettingsDialog-JVPM25GV.js.map → GraphTrackSettingsDialog-2WPJRAJC.js.map} +0 -0
@@ -0,0 +1,701 @@
1
+ import {
2
+ BUBBLE_KIND_NAMES,
3
+ bubbleSegmentIds,
4
+ classifyBubble,
5
+ } from '@jbrowse/bandage-core/bubbles/classifyBubble'
6
+ import { bubbleSubgraph } from '@jbrowse/bandage-core/bubbles/popBubble'
7
+ import { trimToWindow } from '@jbrowse/bandage-core/layout/trimToWindow'
8
+ import { layoutModeByValue } from '@jbrowse/bandage-core/layoutModes'
9
+ import {
10
+ anchorFromPaths,
11
+ chooseReferencePath,
12
+ } from '@jbrowse/bandage-core/pathAnchoring'
13
+ import {
14
+ engineKey,
15
+ forceLayout,
16
+ loadGraph,
17
+ } from '@jbrowse/bandage-core/pipeline'
18
+ import { assemblyWalk } from '@jbrowse/bandage-core/reference'
19
+ import { coarsenTubeMap } from '@jbrowse/bandage-core/tubeMap/coarsen'
20
+ import { readConfObject } from '@jbrowse/core/configuration'
21
+ import {
22
+ getRpcSessionId,
23
+ getSession,
24
+ statusMessageText,
25
+ } from '@jbrowse/core/util'
26
+ import { openLocation } from '@jbrowse/core/util/io'
27
+ import { flow, isAlive } from '@jbrowse/mobx-state-tree'
28
+
29
+ import {
30
+ TUBE_MAP_MODES,
31
+ bubblePrefix,
32
+ forceLayoutsOf,
33
+ remember,
34
+ } from './paneBase'
35
+ import { withSettingActions } from './settingActions'
36
+ import { namesReads } from '../../GetGraphReads'
37
+ import { locLabel } from '../../launchFromGraph/contributors'
38
+ import { geneModelsFrom } from '../genes/geneFeatures'
39
+ import { repeatArraysFrom } from '../repeats/repeatFeatures'
40
+
41
+ import type { SubgraphCutOptions, SubgraphRegion } from '../../GetSubgraph'
42
+ import type { GafReads } from '../../gaf/gafFile'
43
+ import type { MinigraphBubble } from '@jbrowse/bandage-core/bubbles/bubbleLine'
44
+ import type { GeneModel } from '@jbrowse/bandage-core/genes/genePins'
45
+ import type { EngineRequest } from '@jbrowse/bandage-core/pipeline'
46
+ import type { Graph, LayoutResult } from '@jbrowse/bandage-core/types'
47
+ import type { Feature } from '@jbrowse/core/util'
48
+ import type { FileLocation } from '@jbrowse/core/util/types'
49
+
50
+ export const withLoadActions = withSettingActions.actions(self => {
51
+ let loadController: AbortController | undefined
52
+
53
+ function callEngine(request: EngineRequest) {
54
+ const { rpcManager } = getSession(self)
55
+ return rpcManager.call(getRpcSessionId(self), 'GraphComputeLayout', {
56
+ ...request,
57
+ signal: loadController?.signal,
58
+ // A StatusCallback takes an RpcStatus, not a string — it may be a
59
+ // bare label, a phase, or a phase that threw. `statusMessageText` is
60
+ // core's reader for the human-facing line.
61
+ statusCallback: status => {
62
+ self.setStatusMessage(statusMessageText(status) ?? '')
63
+ },
64
+ }) as Promise<{ result: LayoutResult; duration: number }>
65
+ }
66
+
67
+ // The engine's inputs, and only those: the graph, plus what `callLayout`
68
+ // puts in `options`. The reference path is there because the seeds are a
69
+ // function of it; the colour scheme and the anchored modes' own settings
70
+ // are absent because none of them reaches the engine.
71
+ function forceLayoutKey(graph: Graph) {
72
+ return engineKey(graph, {
73
+ quality: self.layoutQuality,
74
+ linearLayout: self.linearLayout,
75
+ bubbleSpread: self.bubbleSpread,
76
+ })
77
+ }
78
+
79
+ // Single dispatch point for every layout mode. A mode that returns a
80
+ // result computed it locally; one that returns undefined can't draw this
81
+ // graph and hands off to the remote FMMM engine, which is also how
82
+ // 'force' is expressed. See LAYOUT_MODES.
83
+ function* computeLayout(graph: Graph) {
84
+ const start = performance.now()
85
+ const tubeMap = TUBE_MAP_MODES.has(self.chosenLayoutMode)
86
+ // a tube map draws the window; the cut's context is for walk rows
87
+ const region = self.graphRegion
88
+ const drawn = tubeMap && region ? trimToWindow(graph, region) : graph
89
+ // reads are placed by the cut's segment names, which a fold renames
90
+ const coarse =
91
+ tubeMap && self.tubeMapFold > 0 && !drawn.reads
92
+ ? coarsenTubeMap(drawn, self.tubeMapFold)
93
+ : undefined
94
+ const local = layoutModeByValue(self.chosenLayoutMode).run(
95
+ coarse?.graph ?? drawn,
96
+ self.graphRegion,
97
+ self.host ? self.layoutResult?.sampleRows : undefined,
98
+ )
99
+ if (local) {
100
+ const result =
101
+ coarse && local.tubeMap
102
+ ? { ...local, tubeMap: { ...local.tubeMap, coarse } }
103
+ : local
104
+ return { result, duration: performance.now() - start }
105
+ }
106
+ const cache = forceLayoutsOf(graph)
107
+ const key = forceLayoutKey(graph)
108
+ const hit = cache.get(key)
109
+ if (hit) {
110
+ return { result: hit, duration: performance.now() - start }
111
+ }
112
+ const oriented = (yield forceLayout(
113
+ graph,
114
+ {
115
+ quality: self.layoutQuality,
116
+ linearLayout: self.linearLayout,
117
+ bubbleSpread: self.bubbleSpread,
118
+ },
119
+ callEngine,
120
+ )) as { result: LayoutResult; duration: number }
121
+ // Under the key read BEFORE the call: the settings that produced this
122
+ // drawing are not necessarily the ones on screen now, and filing it
123
+ // under the current ones would serve it up as a layout it is not.
124
+ remember(cache, key, oriented.result)
125
+ return oriented
126
+ }
127
+
128
+ // Which layout request is the live one. A layout is async and nothing in
129
+ // the UI waits for it, so several are routinely in flight: every control
130
+ // in the settings dialog fires `recomputeLayout` on change, and a force
131
+ // layout takes seconds where an anchored one is instant.
132
+ //
133
+ // The graph identity below is not enough to order them, because the
134
+ // competing requests are usually layouts of the SAME graph. Left to
135
+ // resolve order the last one to FINISH won rather than the last one
136
+ // asked for, so switching away from a slow force layout — to an anchored
137
+ // mode, a cheaper bubble spread, a lower quality — drew the abandoned
138
+ // one over the top of the chosen one seconds later, with the dropdown
139
+ // still naming the choice that was discarded.
140
+ let liveRequest = 0
141
+ // a haplotype's genes by track and contig span, kept across cuts
142
+ const walkGeneCache = new Map<string, GeneModel[]>()
143
+
144
+ // Applied under a guard because a layout is async and the user can load a
145
+ // different graph, or ask for a different layout of it, while one is in
146
+ // flight; the stale result must not land.
147
+ function* layoutInto(graph: Graph) {
148
+ const request = ++liveRequest
149
+ const isLive = () => self.graph === graph && request === liveRequest
150
+ const signal = loadController?.signal
151
+ let computed
152
+ try {
153
+ computed = yield* computeLayout(graph)
154
+ } catch (e) {
155
+ // A discarded layout's failure is not the user's problem: the drawing
156
+ // they asked for is on screen or on its way, and raising a banner
157
+ // over it reports a graph as broken because a setting they moved on
158
+ // from could not be drawn. An aborted one was discarded by the load
159
+ // that replaced it, even when the graph is still the same object.
160
+ if (!isLive() || signal?.aborted) {
161
+ return false
162
+ }
163
+ throw e
164
+ }
165
+ const live = isLive()
166
+ if (live) {
167
+ self.layoutResult = computed.result
168
+ self.setLayoutMs(computed.duration)
169
+ }
170
+ return live
171
+ }
172
+
173
+ // The walk a path graph's track puts on the region's assembly: the one
174
+ // that names it, else the one chooseReferencePath infers
175
+ function loadedReference(graph: Graph, region: SubgraphRegion) {
176
+ const paths = graph.anchorPaths
177
+ return graph.anchoredBy === 'paths' && paths
178
+ ? (
179
+ assemblyWalk(graph, self.assemblySpellings(region.assemblyName)) ??
180
+ chooseReferencePath(paths, region.assemblyName)
181
+ )?.name
182
+ : undefined
183
+ }
184
+
185
+ // `keepSelection` for a re-cut of the same source: node ids survive one
186
+ // where edge indexes do not, so the selection is found again by id.
187
+ // `readsOf` fetches the reads over the parsed graph before its one
188
+ // layout, since the tube map lays them out with the paths.
189
+ function* parseAndLayout(
190
+ text: string,
191
+ name: string,
192
+ region: SubgraphRegion | undefined,
193
+ keepSelection = false,
194
+ readsOf?: (graph: Graph) => Promise<GafReads>,
195
+ ) {
196
+ const signal = loadController?.signal
197
+ self.setStatusMessage('Parsing GFA')
198
+ const parsed = loadGraph(text, name, {
199
+ referencePath: self.referencePath || region?.assemblyName,
200
+ maxNodes: self.maxGraphNodes,
201
+ })
202
+ const loaded = region ? loadedReference(parsed, region) : undefined
203
+ const graph =
204
+ !self.referencePath &&
205
+ loaded !== undefined &&
206
+ loaded !== parsed.referencePath
207
+ ? anchorFromPaths(parsed, loaded)
208
+ : parsed
209
+ if (readsOf) {
210
+ self.setStatusMessage('Reading alignments')
211
+ try {
212
+ const { records, total } = (yield readsOf(graph)) as GafReads
213
+ graph.reads = records
214
+ self.readsShown = { shown: records.length, total }
215
+ } catch (e) {
216
+ if (signal?.aborted) {
217
+ return
218
+ }
219
+ console.warn('[GraphGenomeView] no reads for this graph', e)
220
+ self.readsShown = undefined
221
+ }
222
+ if (signal?.aborted) {
223
+ return
224
+ }
225
+ } else {
226
+ self.readsShown = undefined
227
+ }
228
+ const selected = keepSelection ? self.selectedNode : null
229
+ self.graph = graph
230
+ self.graphRegion = region
231
+ self.loadedReferencePath = loaded
232
+ self.indexBubbles = undefined
233
+ self.geneFeatures = undefined
234
+ self.walkGeneFeatures = undefined
235
+ walkGeneCache.clear()
236
+ self.repeatArrays = undefined
237
+ self.popStack = []
238
+ // hoveredEdge is an index into graph.edges and hoveredNode/selectedNode
239
+ // are ids, so all three address the graph being replaced here. Carrying
240
+ // them over points the tooltip and the highlight at whatever now happens
241
+ // to sit at that index.
242
+ self.clearInteractionState()
243
+ if (selected !== null && self.nodeById?.has(selected)) {
244
+ self.selectedNode = selected
245
+ }
246
+ self.setStatusMessage('Computing layout')
247
+ yield* layoutInto(graph)
248
+ }
249
+
250
+ // Which load is the live one, for the reason liveRequest orders layouts:
251
+ // every change in the settings dialog re-cuts, a remote cut takes seconds,
252
+ // and the last one to finish is not the last one asked for.
253
+ let liveLoad = 0
254
+
255
+ function beginLoad() {
256
+ const load = ++liveLoad
257
+ loadController?.abort()
258
+ loadController = new AbortController()
259
+ self.loadCanceled = false
260
+ return {
261
+ isLive: () => load === liveLoad,
262
+ signal: loadController.signal,
263
+ }
264
+ }
265
+
266
+ // The bubble index that the hosted HPRC build keeps beside its segments,
267
+ // `<prefix>.bubbles.bed.gz`, read through the bubble adapter over the same
268
+ // window. A graph whose source has no such file, the ordinary case for a
269
+ // graph of one's own, keeps its derived bubbles, so a failure here is not
270
+ // the graph's problem. A coarse cut reads none: its nodes are the
271
+ // bubbles, and the index over its window can run to a chromosome's rows.
272
+ function* loadBubbles(
273
+ adapterConfig: Record<string, unknown>,
274
+ region: SubgraphRegion,
275
+ isLive: () => boolean,
276
+ ) {
277
+ // The track config arrives as written, so the prefix is either the
278
+ // `uri` shorthand or the segments location it expands to.
279
+ const prefix = bubblePrefix(adapterConfig)
280
+ if (adapterConfig.type !== 'RgfaTabixAdapter' || prefix === undefined) {
281
+ return
282
+ }
283
+ try {
284
+ const features = (yield getSession(self).rpcManager.call(
285
+ getRpcSessionId(self),
286
+ 'CoreGetFeatures',
287
+ {
288
+ adapterConfig: {
289
+ type: 'MinigraphBubbleAdapter',
290
+ uri: `${prefix}.bubbles.bed.gz`,
291
+ baseUri: adapterConfig.baseUri,
292
+ assemblyNameToPanSN: adapterConfig.assemblyNameToPanSN,
293
+ },
294
+ regions: [region],
295
+ },
296
+ )) as Feature[]
297
+ if (isLive()) {
298
+ self.indexBubbles = features.map(f => ({
299
+ refName: region.refName,
300
+ start: f.get('start'),
301
+ end: f.get('end'),
302
+ segmentCount: f.get('segmentCount') as number,
303
+ pathCount: (f.get('pathCount') as number | undefined) ?? 0,
304
+ inversion: f.get('inversion') as boolean,
305
+ shortestAlleleLength: f.get('shortestAlleleLength') as number,
306
+ longestAlleleLength: f.get('longestAlleleLength') as number,
307
+ segments: f.get('segments') as string,
308
+ shortestAllele: undefined,
309
+ longestAllele: undefined,
310
+ }))
311
+ }
312
+ } catch (e) {
313
+ console.warn('[GraphGenomeView] no bubble index for this graph', e)
314
+ }
315
+ }
316
+
317
+ // A session track's features over the cut. Undefined when the session
318
+ // has no such track or the read fails: an annotation is never the
319
+ // graph's problem.
320
+ function* trackFeatures(
321
+ trackId: string | undefined,
322
+ region: SubgraphRegion,
323
+ what: string,
324
+ ) {
325
+ const session = getSession(self)
326
+ const config = trackId
327
+ ? session.tracks.find(t => t.trackId === trackId)
328
+ : undefined
329
+ if (!config) {
330
+ return undefined
331
+ }
332
+ try {
333
+ return (yield session.rpcManager.call(
334
+ getRpcSessionId(self),
335
+ 'CoreGetFeatures',
336
+ {
337
+ adapterConfig: readConfObject(config, 'adapter'),
338
+ regions: [region],
339
+ },
340
+ )) as Feature[]
341
+ } catch (e) {
342
+ console.warn(`[GraphGenomeView] no ${what} for this graph`, e)
343
+ return undefined
344
+ }
345
+ }
346
+
347
+ // The genes over the cut, from the session's annotation track for the
348
+ // assembly, so the backbone can carry its exons and names.
349
+ function* loadGenes(region: SubgraphRegion, isLive: () => boolean) {
350
+ const features = yield* trackFeatures(
351
+ self.geneTrack?.trackId,
352
+ region,
353
+ 'genes',
354
+ )
355
+ if (features && isLive()) {
356
+ self.geneFeatures = geneModelsFrom(features)
357
+ }
358
+ }
359
+
360
+ // The tandem repeat arrays over the cut, from the session's repeat
361
+ // track, for the walk rows to measure between and tile by.
362
+ function* loadRepeats(region: SubgraphRegion, isLive: () => boolean) {
363
+ const features = yield* trackFeatures(
364
+ self.repeatTrack?.trackId,
365
+ region,
366
+ 'repeats',
367
+ )
368
+ if (features && isLive()) {
369
+ self.repeatArrays = repeatArraysFrom(features)
370
+ }
371
+ }
372
+
373
+ // Raises `isLoading` before any fetch, so a view waiting on a remote file
374
+ // shows its loading state instead of the import form. Text already in
375
+ // hand is parsed without yielding first. `region` is the window a
376
+ // declared file was stated beside, which the parse anchors on.
377
+ function* loadWholeGFA(
378
+ name: string,
379
+ source: string | ((signal: AbortSignal) => Promise<string>),
380
+ region?: SubgraphRegion,
381
+ ) {
382
+ const { isLive, signal } = beginLoad()
383
+ self.isLoading = true
384
+ self.error = undefined
385
+ try {
386
+ const text =
387
+ typeof source === 'string' ? source : ((yield source(signal)) as string)
388
+ if (isLive()) {
389
+ yield* parseAndLayout(text, name, region)
390
+ }
391
+ } catch (e) {
392
+ if (isLive()) {
393
+ console.error('[GraphGenomeView.loadWholeGFA]', e)
394
+ self.error = e
395
+ }
396
+ } finally {
397
+ if (isLive()) {
398
+ self.finishLoading()
399
+ }
400
+ }
401
+ return isLive()
402
+ }
403
+
404
+ function abortLoad() {
405
+ loadController?.abort()
406
+ loadController = undefined
407
+ liveLoad++
408
+ liveRequest++
409
+ }
410
+
411
+ // The graph and everything derived from it, dropped; any load in
412
+ // flight ends too, or it would land its graph afterwards
413
+ function dropGraph() {
414
+ abortLoad()
415
+ self.graph = undefined
416
+ self.graphRegion = undefined
417
+ self.loadedReferencePath = undefined
418
+ self.layoutResult = undefined
419
+ self.indexBubbles = undefined
420
+ self.geneFeatures = undefined
421
+ self.walkGeneFeatures = undefined
422
+ walkGeneCache.clear()
423
+ self.repeatArrays = undefined
424
+ self.readsShown = undefined
425
+ self.popStack = []
426
+ self.error = undefined
427
+ self.isLoading = false
428
+ self.loadCanceled = false
429
+ self.statusMessage = ''
430
+ self.clearInteractionState()
431
+ self.clearPerfMetrics()
432
+ }
433
+
434
+ return {
435
+ // back to the import form
436
+ clearGraph() {
437
+ dropGraph()
438
+ },
439
+ // The user's stop before anything is drawn. The source stays, so a
440
+ // retry can load it again.
441
+ cancelLoad() {
442
+ if (self.canCancelLoad) {
443
+ dropGraph()
444
+ self.loadCanceled = true
445
+ }
446
+ },
447
+ // The user's stop, leaving whatever is drawn under it
448
+ stopLoad() {
449
+ abortLoad()
450
+ self.isLoading = false
451
+ self.statusMessage = ''
452
+ self.loadCanceled = true
453
+ },
454
+ beforeDestroy() {
455
+ abortLoad()
456
+ },
457
+ loadGFA: flow(function* (text: string, name = 'Imported GFA') {
458
+ yield* loadWholeGFA(name, text)
459
+ }),
460
+ loadGFAFromLocation: flow(function* (
461
+ location: FileLocation,
462
+ region?: SubgraphRegion,
463
+ ) {
464
+ self.setStatusMessage('Fetching GFA')
465
+ const live = yield* loadWholeGFA(
466
+ 'uri' in location ? (location.uri.split('/').pop() ?? 'GFA') : 'GFA',
467
+ signal => openLocation(location).readFile({ encoding: 'utf8', signal }),
468
+ region,
469
+ )
470
+ if (region && live && self.graph) {
471
+ yield* loadRepeats(region, () => self.graphRegion === region)
472
+ }
473
+ }),
474
+ // One cut of a region, laid out with the annotations over it. Whether
475
+ // the region may be cut is the caller's call; overlapping cuts are
476
+ // ordered by liveLoad, so the latest one lands.
477
+ cutSubgraph: flow(function* (
478
+ adapterConfig: Record<string, unknown>,
479
+ region: SubgraphRegion,
480
+ opts: SubgraphCutOptions = {},
481
+ ) {
482
+ const { isLive, signal } = beginLoad()
483
+ self.isLoading = true
484
+ self.error = undefined
485
+ self.setStatusMessage('Fetching subgraph')
486
+ try {
487
+ const fetchStart = performance.now()
488
+ const gfaText = (yield getSession(self).rpcManager.call(
489
+ getRpcSessionId(self),
490
+ 'GetSubgraph',
491
+ { adapterConfig, region, opts, signal },
492
+ )) as string
493
+ if (!isLive()) {
494
+ return
495
+ }
496
+ self.setFetchMs(performance.now() - fetchStart)
497
+ if (!gfaText) {
498
+ throw new Error(
499
+ 'Adapter returned no GFA — region may be outside indexed data or the adapter does not implement getSubgraph',
500
+ )
501
+ }
502
+ yield* parseAndLayout(
503
+ gfaText,
504
+ locLabel(region),
505
+ region,
506
+ true,
507
+ namesReads(adapterConfig)
508
+ ? graph =>
509
+ getSession(self).rpcManager.call(
510
+ getRpcSessionId(self),
511
+ 'GetGraphReads',
512
+ {
513
+ adapterConfig,
514
+ nodeNames: graph.nodes.map(n => n.name),
515
+ signal,
516
+ },
517
+ )
518
+ : undefined,
519
+ )
520
+ if (!isLive()) {
521
+ return
522
+ }
523
+ // Independent remote reads, each landing as it arrives. A coarse
524
+ // cut reads no bubble index: its nodes are the bubbles, and the
525
+ // index over its window can run to a chromosome's rows.
526
+ self.setStatusMessage('Reading annotations')
527
+ yield Promise.all([
528
+ opts.tier === 'coarse'
529
+ ? undefined
530
+ : flow(loadBubbles)(adapterConfig, region, isLive),
531
+ flow(loadGenes)(region, isLive),
532
+ flow(loadRepeats)(region, isLive),
533
+ ])
534
+ } catch (e) {
535
+ if (isLive()) {
536
+ console.error('[GraphGenomeView.cutSubgraph]', e)
537
+ self.error = e
538
+ }
539
+ } finally {
540
+ if (isLive()) {
541
+ self.finishLoading()
542
+ }
543
+ }
544
+ }),
545
+ // Re-read one annotation track alone, for a track change. The graph,
546
+ // its layout and any open bubble stay as they are. Live only while the
547
+ // track it read is still the one chosen, so a slow read cannot land
548
+ // over the pick that followed it.
549
+ reloadRepeats: flow(function* () {
550
+ const region = self.graphRegion
551
+ const trackId = self.repeatTrack?.trackId
552
+ if (region) {
553
+ yield* loadRepeats(
554
+ region,
555
+ () =>
556
+ self.graphRegion === region &&
557
+ self.repeatTrack?.trackId === trackId,
558
+ )
559
+ }
560
+ }),
561
+ // The walk rows' genes, each row's from its haplotype's assembly. A
562
+ // row's genes are its own contig's, so they take the row's name for
563
+ // their contig, whatever the track calls it.
564
+ loadWalkGenes: flow(function* () {
565
+ const reads = self.walkGeneReads?.reads ?? []
566
+ const key = JSON.stringify(reads)
567
+ const graph = self.graph
568
+ const fetched = new Map<string, GeneModel[]>()
569
+ yield Promise.all(
570
+ reads.map(({ row, trackId, region }) =>
571
+ flow(function* () {
572
+ const cacheKey = `${trackId} ${region.refName}:${region.start}-${region.end}`
573
+ let genes = walkGeneCache.get(cacheKey)
574
+ if (!genes) {
575
+ const features = yield* trackFeatures(
576
+ trackId,
577
+ region,
578
+ 'haplotype genes',
579
+ )
580
+ if (!features) {
581
+ return
582
+ }
583
+ genes = geneModelsFrom(features).map(g => ({
584
+ ...g,
585
+ refName: region.refName,
586
+ }))
587
+ walkGeneCache.set(cacheKey, genes)
588
+ }
589
+ fetched.set(row, genes)
590
+ })(),
591
+ ),
592
+ )
593
+ if (
594
+ isAlive(self) &&
595
+ self.graph === graph &&
596
+ JSON.stringify(self.walkGeneReads?.reads ?? []) === key
597
+ ) {
598
+ self.walkGeneFeatures = reads.length ? fetched : undefined
599
+ }
600
+ }),
601
+ reloadGenes: flow(function* () {
602
+ walkGeneCache.clear()
603
+ const region = self.graphRegion
604
+ const trackId = self.geneTrack?.trackId
605
+ if (region) {
606
+ yield* loadGenes(
607
+ region,
608
+ () =>
609
+ self.graphRegion === region && self.geneTrack?.trackId === trackId,
610
+ )
611
+ }
612
+ }),
613
+ // Open one bubble: the graph becomes the segments the bubble row names,
614
+ // drawn in the layout the reader is in. The graph it came from stays
615
+ // behind it, one click away, and the popped graph gets its own derived
616
+ // bubbles, so a superbubble opens progressively.
617
+ popBubble: flow(function* (bubble: MinigraphBubble) {
618
+ const graph = self.graph
619
+ if (!graph) {
620
+ return
621
+ }
622
+ const sub = bubbleSubgraph(graph, bubbleSegmentIds(bubble))
623
+ if (sub.nodes.length === 0) {
624
+ getSession(self).notify(
625
+ 'None of the segments of this bubble are in the cut; widen the graph context to open it',
626
+ 'info',
627
+ )
628
+ return
629
+ }
630
+ const { isLive } = beginLoad()
631
+ self.popStack = [
632
+ ...self.popStack,
633
+ {
634
+ graph,
635
+ layoutMode: self.chosenLayoutMode,
636
+ label: graph.name,
637
+ indexBubbles: self.indexBubbles,
638
+ },
639
+ ]
640
+ self.indexBubbles = undefined
641
+ const label = `${BUBBLE_KIND_NAMES[classifyBubble(bubble, self.repeatArrays).kind]} at ${bubble.refName}:${bubble.start.toLocaleString()}`
642
+ self.graph = { ...sub, name: label }
643
+ self.clearInteractionState()
644
+ self.viewportOwner = 'fit'
645
+ self.isLoading = true
646
+ try {
647
+ if (yield* layoutInto(self.graph)) {
648
+ self.finishLoading()
649
+ }
650
+ } catch (e) {
651
+ if (isLive()) {
652
+ self.error = e
653
+ self.finishLoading()
654
+ }
655
+ }
656
+ }),
657
+ unpopBubble: flow(function* () {
658
+ const from = self.poppedFrom
659
+ if (!from) {
660
+ return
661
+ }
662
+ self.popStack = self.popStack.slice(0, -1)
663
+ self.graph = from.graph
664
+ self.layoutMode = from.layoutMode
665
+ self.indexBubbles = from.indexBubbles
666
+ self.clearInteractionState()
667
+ self.viewportOwner = 'fit'
668
+ self.isLoading = true
669
+ try {
670
+ if (yield* layoutInto(from.graph)) {
671
+ self.finishLoading()
672
+ }
673
+ } catch (e) {
674
+ self.error = e
675
+ self.finishLoading()
676
+ }
677
+ }),
678
+ recomputeLayout: flow(function* () {
679
+ const graph = self.graph
680
+ if (!graph) {
681
+ return
682
+ }
683
+ self.isLoading = true
684
+ self.setStatusMessage('Computing layout')
685
+
686
+ try {
687
+ // A superseded request leaves the spinner to the request that
688
+ // replaced it: clearing it here reports "done" while the layout the
689
+ // user actually asked for is still being computed, which is the
690
+ // common case when a cheap choice follows an expensive one.
691
+ if (yield* layoutInto(graph)) {
692
+ self.finishLoading()
693
+ }
694
+ } catch (e) {
695
+ console.error('[GraphGenomeView.recomputeLayout]', e)
696
+ self.error = e
697
+ self.finishLoading()
698
+ }
699
+ }),
700
+ }
701
+ })