-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathindex.tsx
1219 lines (1135 loc) · 37.9 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getConf, AnyConfigurationModel } from '@jbrowse/core/configuration'
import { BaseViewModel } from '@jbrowse/core/pluggableElementTypes/models'
import { Region } from '@jbrowse/core/util/types'
import { ElementId, Region as MUIRegion } from '@jbrowse/core/util/types/mst'
import { MenuItem, ReturnToImportFormDialog } from '@jbrowse/core/ui'
import {
assembleLocString,
clamp,
findLastIndex,
getContainingView,
getSession,
isViewContainer,
isSessionModelWithWidgets,
measureText,
parseLocString,
springAnimate,
} from '@jbrowse/core/util'
import BaseResult from '@jbrowse/core/TextSearch/BaseResults'
import { BlockSet, BaseBlock } from '@jbrowse/core/util/blockTypes'
import calculateDynamicBlocks from '@jbrowse/core/util/calculateDynamicBlocks'
import calculateStaticBlocks from '@jbrowse/core/util/calculateStaticBlocks'
import { getParentRenderProps } from '@jbrowse/core/util/tracks'
import { transaction, autorun } from 'mobx'
import {
addDisposer,
cast,
getSnapshot,
getRoot,
resolveIdentifier,
types,
Instance,
} from 'mobx-state-tree'
import Base1DView from '@jbrowse/core/util/Base1DViewModel'
import { moveTo, pxToBp, bpToPx } from '@jbrowse/core/util/Base1DUtils'
import { saveAs } from 'file-saver'
import clone from 'clone'
import PluginManager from '@jbrowse/core/PluginManager'
// icons
import { TrackSelector as TrackSelectorIcon } from '@jbrowse/core/ui/Icons'
import SyncAltIcon from '@mui/icons-material/SyncAlt'
import VisibilityIcon from '@mui/icons-material/Visibility'
import LabelIcon from '@mui/icons-material/Label'
import FolderOpenIcon from '@mui/icons-material/FolderOpen'
import PhotoCameraIcon from '@mui/icons-material/PhotoCamera'
import ZoomInIcon from '@mui/icons-material/ZoomIn'
import MenuOpenIcon from '@mui/icons-material/MenuOpen'
// locals
import { renderToSvg } from './components/LinearGenomeViewSvg'
import RefNameAutocomplete from './components/RefNameAutocomplete'
import SearchBox from './components/SearchBox'
import ExportSvgDlg from './components/ExportSvgDialog'
export interface BpOffset {
refName?: string
index: number
offset: number
start?: number
end?: number
coord?: number
reversed?: boolean
assemblyName?: string
oob?: boolean
}
export interface ExportSvgOptions {
rasterizeLayers?: boolean
filename?: string
}
function calculateVisibleLocStrings(contentBlocks: BaseBlock[]) {
if (!contentBlocks.length) {
return ''
}
const isSingleAssemblyName = contentBlocks.every(
block => block.assemblyName === contentBlocks[0].assemblyName,
)
const locs = contentBlocks.map(block =>
assembleLocString({
...block,
start: Math.round(block.start),
end: Math.round(block.end),
assemblyName: isSingleAssemblyName ? undefined : block.assemblyName,
}),
)
return locs.join(' ')
}
export interface NavLocation {
refName: string
start?: number
end?: number
assemblyName?: string
}
export const HEADER_BAR_HEIGHT = 48
export const HEADER_OVERVIEW_HEIGHT = 20
export const SCALE_BAR_HEIGHT = 17
export const RESIZE_HANDLE_HEIGHT = 3
export const INTER_REGION_PADDING_WIDTH = 2
export const SPACING = 7
export const WIDGET_HEIGHT = 32
function localStorageGetItem(item: string) {
return typeof localStorage !== 'undefined'
? localStorage.getItem(item)
: undefined
}
export function stateModelFactory(pluginManager: PluginManager) {
return types
.compose(
BaseViewModel,
types.model('LinearGenomeView', {
id: ElementId,
type: types.literal('LinearGenomeView'),
offsetPx: 0,
bpPerPx: 1,
displayedRegions: types.array(MUIRegion),
// we use an array for the tracks because the tracks are displayed in a
// specific order that we need to keep.
tracks: types.array(
pluginManager.pluggableMstType('track', 'stateModel'),
),
hideHeader: false,
hideHeaderOverview: false,
hideNoTracksActive: false,
trackSelectorType: types.optional(
types.enumeration(['hierarchical']),
'hierarchical',
),
trackLabels: types.optional(
types.string,
() => localStorageGetItem('lgv-trackLabels') || 'overlapping',
),
showCenterLine: types.optional(types.boolean, () => {
const setting = localStorageGetItem('lgv-showCenterLine')
return setting !== undefined && setting !== null ? !!+setting : false
}),
showCytobandsSetting: types.optional(types.boolean, () => {
const setting = localStorageGetItem('lgv-showCytobands')
return setting !== undefined && setting !== null ? !!+setting : true
}),
showGridlines: true,
}),
)
.volatile(() => ({
volatileWidth: undefined as number | undefined,
minimumBlockWidth: 3,
draggingTrackId: undefined as undefined | string,
volatileError: undefined as undefined | Error,
// array of callbacks to run after the next set of the displayedRegions,
// which is basically like an onLoad
afterDisplayedRegionsSetCallbacks: [] as Function[],
scaleFactor: 1,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
trackRefs: {} as { [key: string]: any },
coarseDynamicBlocks: [] as BaseBlock[],
coarseTotalBp: 0,
leftOffset: undefined as undefined | BpOffset,
rightOffset: undefined as undefined | BpOffset,
searchResults: undefined as undefined | BaseResult[],
searchQuery: undefined as undefined | string,
seqDialogDisplayed: false,
}))
.views(self => ({
get width(): number {
if (self.volatileWidth === undefined) {
throw new Error(
'width undefined, make sure to check for model.initialized',
)
}
return self.volatileWidth
},
get interRegionPaddingWidth() {
return INTER_REGION_PADDING_WIDTH
},
get assemblyNames() {
return [
...new Set(self.displayedRegions.map(region => region.assemblyName)),
]
},
}))
.views(self => ({
get assemblyErrors() {
const { assemblyManager } = getSession(self)
const { assemblyNames } = self
return assemblyNames
.map(a => assemblyManager.get(a)?.error)
.filter(f => !!f)
.join(', ')
},
get assembliesInitialized() {
const { assemblyManager } = getSession(self)
const { assemblyNames } = self
return assemblyNames.every(a => assemblyManager.get(a)?.initialized)
},
get initialized() {
return self.volatileWidth !== undefined && this.assembliesInitialized
},
get hasDisplayedRegions() {
return self.displayedRegions.length > 0
},
get isSearchDialogDisplayed() {
return self.searchResults !== undefined
},
get scaleBarHeight() {
return SCALE_BAR_HEIGHT + RESIZE_HANDLE_HEIGHT
},
get headerHeight() {
if (self.hideHeader) {
return 0
}
if (self.hideHeaderOverview) {
return HEADER_BAR_HEIGHT
}
return HEADER_BAR_HEIGHT + HEADER_OVERVIEW_HEIGHT
},
get trackHeights() {
return self.tracks
.map(t => t.displays[0].height)
.reduce((a, b) => a + b, 0)
},
get trackHeightsWithResizeHandles() {
return this.trackHeights + self.tracks.length * RESIZE_HANDLE_HEIGHT
},
get height() {
return (
this.trackHeightsWithResizeHandles +
this.headerHeight +
this.scaleBarHeight
)
},
get totalBp() {
return self.displayedRegions.reduce((a, b) => a + b.end - b.start, 0)
},
get maxBpPerPx() {
return this.totalBp / (self.width * 0.9)
},
get minBpPerPx() {
return 1 / 50
},
get error() {
return self.volatileError || this.assemblyErrors
},
get maxOffset() {
// objectively determined to keep the linear genome on the main screen
const leftPadding = 10
return this.displayedRegionsTotalPx - leftPadding
},
get minOffset() {
// objectively determined to keep the linear genome on the main screen
const rightPadding = 30
return -self.width + rightPadding
},
get displayedRegionsTotalPx() {
return this.totalBp / self.bpPerPx
},
renderProps() {
return {
...getParentRenderProps(self),
bpPerPx: self.bpPerPx,
highResolutionScaling: getConf(
getSession(self),
'highResolutionScaling',
),
}
},
searchScope(assemblyName: string) {
return {
assemblyName,
includeAggregateIndexes: true,
tracks: self.tracks,
}
},
getTrack(id: string) {
return self.tracks.find(t => t.configuration.trackId === id)
},
rankSearchResults(results: BaseResult[]) {
// order of rank
const openTrackIds = self.tracks.map(
track => track.configuration.trackId,
)
results.forEach(result => {
if (openTrackIds.includes(result.trackId)) {
result.updateScore(result.getScore() + 1)
}
})
return results
},
// modifies view menu action onClick to apply to all tracks of same type
rewriteOnClicks(trackType: string, viewMenuActions: MenuItem[]) {
viewMenuActions.forEach(action => {
// go to lowest level menu
if ('subMenu' in action) {
this.rewriteOnClicks(trackType, action.subMenu)
}
if ('onClick' in action) {
const holdOnClick = action.onClick
action.onClick = (...args: unknown[]) => {
self.tracks.forEach(track => {
if (track.type === trackType) {
holdOnClick.apply(track, [track, ...args])
}
})
}
}
})
},
get trackTypeActions() {
const allActions: Map<string, MenuItem[]> = new Map()
self.tracks.forEach(track => {
const trackInMap = allActions.get(track.type)
if (!trackInMap) {
const viewMenuActions = clone(track.viewMenuActions)
this.rewriteOnClicks(track.type, viewMenuActions)
allActions.set(track.type, viewMenuActions)
}
})
return allActions
},
}))
.actions(self => ({
setShowCytobands(flag: boolean) {
self.showCytobandsSetting = flag
localStorage.setItem('lgv-showCytobands', `${+flag}`)
},
setWidth(newWidth: number) {
self.volatileWidth = newWidth
},
setError(error: Error | undefined) {
self.volatileError = error
},
toggleHeader() {
self.hideHeader = !self.hideHeader
},
toggleHeaderOverview() {
self.hideHeaderOverview = !self.hideHeaderOverview
},
toggleNoTracksActive() {
self.hideNoTracksActive = !self.hideNoTracksActive
},
toggleShowGridlines() {
self.showGridlines = !self.showGridlines
},
scrollTo(offsetPx: number) {
const newOffsetPx = clamp(offsetPx, self.minOffset, self.maxOffset)
self.offsetPx = newOffsetPx
return newOffsetPx
},
zoomTo(bpPerPx: number) {
const newBpPerPx = clamp(bpPerPx, self.minBpPerPx, self.maxBpPerPx)
if (newBpPerPx === self.bpPerPx) {
return newBpPerPx
}
const oldBpPerPx = self.bpPerPx
self.bpPerPx = newBpPerPx
if (Math.abs(oldBpPerPx - newBpPerPx) < 0.000001) {
console.warn('zoomTo bpPerPx rounding error')
return oldBpPerPx
}
// tweak the offset so that the center of the view remains at the same coordinate
const viewWidth = self.width
this.scrollTo(
Math.round(
((self.offsetPx + viewWidth / 2) * oldBpPerPx) / newBpPerPx -
viewWidth / 2,
),
)
return newBpPerPx
},
setOffsets(left: undefined | BpOffset, right: undefined | BpOffset) {
// sets offsets used in the get sequence dialog
self.leftOffset = left
self.rightOffset = right
},
setSearchResults(
results: BaseResult[] | undefined,
query: string | undefined,
) {
self.searchResults = results
self.searchQuery = query
},
setSequenceDialogOpen(open: boolean) {
self.seqDialogDisplayed = open
},
setNewView(bpPerPx: number, offsetPx: number) {
this.zoomTo(bpPerPx)
this.scrollTo(offsetPx)
},
horizontallyFlip() {
self.displayedRegions = cast(
self.displayedRegions
.slice()
.reverse()
.map(region => ({ ...region, reversed: !region.reversed })),
)
this.scrollTo(self.totalBp / self.bpPerPx - self.offsetPx - self.width)
},
showTrack(
trackId: string,
initialSnapshot = {},
displayInitialSnapshot = {},
) {
const schema = pluginManager.pluggableConfigSchemaType('track')
const conf = resolveIdentifier(schema, getRoot(self), trackId)
if (!conf) {
throw new Error(`Could not resolve identifier "${trackId}"`)
}
const trackType = pluginManager.getTrackType(conf?.type)
if (!trackType) {
throw new Error(`Unknown track type ${conf.type}`)
}
const viewType = pluginManager.getViewType(self.type)
const supportedDisplays = viewType.displayTypes.map(d => d.name)
const displayConf = conf.displays.find((d: AnyConfigurationModel) =>
supportedDisplays.includes(d.type),
)
if (!displayConf) {
throw new Error(
`Could not find a compatible display for view type ${self.type}`,
)
}
const t = self.tracks.filter(t => t.configuration === conf)
if (t.length === 0) {
const track = trackType.stateModel.create({
...initialSnapshot,
type: conf.type,
configuration: conf,
displays: [
{
type: displayConf.type,
configuration: displayConf,
...displayInitialSnapshot,
},
],
})
self.tracks.push(track)
return track
}
return t[0]
},
hideTrack(trackId: string) {
const schema = pluginManager.pluggableConfigSchemaType('track')
const conf = resolveIdentifier(schema, getRoot(self), trackId)
const t = self.tracks.filter(t => t.configuration === conf)
transaction(() => t.forEach(t => self.tracks.remove(t)))
return t.length
},
}))
.actions(self => ({
moveTrack(movingId: string, targetId: string) {
const oldIndex = self.tracks.findIndex(track => track.id === movingId)
if (oldIndex === -1) {
throw new Error(`Track ID ${movingId} not found`)
}
const newIndex = self.tracks.findIndex(track => track.id === targetId)
if (newIndex === -1) {
throw new Error(`Track ID ${targetId} not found`)
}
const track = getSnapshot(self.tracks[oldIndex])
self.tracks.splice(oldIndex, 1)
self.tracks.splice(newIndex, 0, track)
},
closeView() {
const parent = getContainingView(self)
if (parent) {
// I am embedded in a some other view
if (isViewContainer(parent)) {
parent.removeView(self)
}
} else {
// I am part of a session
getSession(self).removeView(self)
}
},
toggleTrack(trackId: string) {
// if we have any tracks with that configuration, turn them off
const hiddenCount = self.hideTrack(trackId)
// if none had that configuration, turn one on
if (!hiddenCount) {
self.showTrack(trackId)
}
},
setTrackLabels(setting: 'overlapping' | 'offset' | 'hidden') {
self.trackLabels = setting
localStorage.setItem('lgv-trackLabels', setting)
},
toggleCenterLine() {
self.showCenterLine = !self.showCenterLine
localStorage.setItem('lgv-showCenterLine', `${+self.showCenterLine}`)
},
setDisplayedRegions(regions: Region[]) {
self.displayedRegions = cast(regions)
self.zoomTo(self.bpPerPx)
},
activateTrackSelector() {
if (self.trackSelectorType === 'hierarchical') {
const session = getSession(self)
if (isSessionModelWithWidgets(session)) {
const selector = session.addWidget(
'HierarchicalTrackSelectorWidget',
'hierarchicalTrackSelector',
{ view: self },
)
session.showWidget(selector)
return selector
}
}
throw new Error(`invalid track selector type ${self.trackSelectorType}`)
},
/**
* Helper method for the fetchSequence.
* Retrieves the corresponding regions that were selected by the rubberband
*
* @param leftOffset - `object as {start, end, index, offset}`, offset = start of user drag
* @param rightOffset - `object as {start, end, index, offset}`, offset = end of user drag
* @returns array of Region[]
*/
getSelectedRegions(leftOffset?: BpOffset, rightOffset?: BpOffset) {
const snap = getSnapshot(self)
const simView = Base1DView.create({
// xref https://github.com/mobxjs/mobx-state-tree/issues/1524 for Omit
...(snap as Omit<typeof self, symbol>),
interRegionPaddingWidth: self.interRegionPaddingWidth,
})
simView.setVolatileWidth(self.width)
simView.moveTo(leftOffset, rightOffset)
return simView.dynamicBlocks.contentBlocks.map(region => ({
...region,
start: Math.floor(region.start),
end: Math.ceil(region.end),
}))
},
// schedule something to be run after the next time displayedRegions is set
afterDisplayedRegionsSet(cb: Function) {
self.afterDisplayedRegionsSetCallbacks.push(cb)
},
horizontalScroll(distance: number) {
const oldOffsetPx = self.offsetPx
// newOffsetPx is the actual offset after the scroll is clamped
const newOffsetPx = self.scrollTo(self.offsetPx + distance)
return newOffsetPx - oldOffsetPx
},
center() {
const centerBp = self.totalBp / 2
const centerPx = centerBp / self.bpPerPx
self.scrollTo(Math.round(centerPx - self.width / 2))
},
showAllRegions() {
self.zoomTo(self.maxBpPerPx)
this.center()
},
showAllRegionsInAssembly(assemblyName?: string) {
const session = getSession(self)
const { assemblyManager } = session
if (!assemblyName) {
const assemblyNames = [
...new Set(
self.displayedRegions.map(region => region.assemblyName),
),
]
if (assemblyNames.length > 1) {
session.notify(
`Can't perform this with multiple assemblies currently`,
)
return
}
;[assemblyName] = assemblyNames
}
const assembly = assemblyManager.get(assemblyName)
if (assembly) {
const { regions } = assembly
if (regions) {
this.setDisplayedRegions(regions)
self.zoomTo(self.maxBpPerPx)
this.center()
}
}
},
setDraggingTrackId(idx?: string) {
self.draggingTrackId = idx
},
setScaleFactor(factor: number) {
self.scaleFactor = factor
},
}))
.actions(self => {
let cancelLastAnimation = () => {}
function slide(viewWidths: number) {
const [animate, cancelAnimation] = springAnimate(
self.offsetPx,
self.offsetPx + self.width * viewWidths,
self.scrollTo,
)
cancelLastAnimation()
cancelLastAnimation = cancelAnimation
animate()
}
return { slide }
})
.actions(self => {
let cancelLastAnimation = () => {}
function zoom(targetBpPerPx: number) {
self.zoomTo(self.bpPerPx)
if (
// already zoomed all the way in
(targetBpPerPx < self.bpPerPx && self.bpPerPx === self.minBpPerPx) ||
// already zoomed all the way out
(targetBpPerPx > self.bpPerPx && self.bpPerPx === self.maxBpPerPx)
) {
return
}
const factor = self.bpPerPx / targetBpPerPx
const [animate, cancelAnimation] = springAnimate(
1,
factor,
self.setScaleFactor,
() => {
self.zoomTo(targetBpPerPx)
self.setScaleFactor(1)
},
)
cancelLastAnimation()
cancelLastAnimation = cancelAnimation
animate()
}
return { zoom }
})
.views(self => ({
get canShowCytobands() {
return self.displayedRegions.length === 1 && this.anyCytobandsExist
},
get showCytobands() {
return this.canShowCytobands && self.showCytobandsSetting
},
get anyCytobandsExist() {
const { assemblyManager } = getSession(self)
const { assemblyNames } = self
return assemblyNames.some(
asm => assemblyManager.get(asm)?.cytobands?.length,
)
},
get cytobandOffset() {
return this.showCytobands
? measureText(self.displayedRegions[0].refName, 12) + 15
: 0
},
}))
.views(self => ({
menuItems(): MenuItem[] {
const { canShowCytobands, showCytobands } = self
const menuItems: MenuItem[] = [
{
label: 'Return to import form',
onClick: () => {
getSession(self).queueDialog(handleClose => [
ReturnToImportFormDialog,
{ model: self, handleClose },
])
},
icon: FolderOpenIcon,
},
{
label: 'Export SVG',
icon: PhotoCameraIcon,
onClick: () => {
getSession(self).queueDialog(handleClose => [
ExportSvgDlg,
{ model: self, handleClose },
])
},
},
{
label: 'Open track selector',
onClick: self.activateTrackSelector,
icon: TrackSelectorIcon,
},
{
label: 'Horizontally flip',
icon: SyncAltIcon,
onClick: self.horizontallyFlip,
},
{ type: 'divider' },
{
label: 'Show all regions in assembly',
icon: VisibilityIcon,
onClick: self.showAllRegionsInAssembly,
},
{
label: 'Show center line',
icon: VisibilityIcon,
type: 'checkbox',
checked: self.showCenterLine,
onClick: self.toggleCenterLine,
},
{
label: 'Show header',
icon: VisibilityIcon,
type: 'checkbox',
checked: !self.hideHeader,
onClick: self.toggleHeader,
},
{
label: 'Show header overview',
icon: VisibilityIcon,
type: 'checkbox',
checked: !self.hideHeaderOverview,
onClick: self.toggleHeaderOverview,
disabled: self.hideHeader,
},
{
label: 'Show no tracks active button',
icon: VisibilityIcon,
type: 'checkbox',
checked: !self.hideNoTracksActive,
onClick: self.toggleNoTracksActive,
},
{
label: 'Show gridlines',
icon: VisibilityIcon,
type: 'checkbox',
checked: self.showGridlines,
onClick: self.toggleShowGridlines,
},
{
label: 'Track labels',
icon: LabelIcon,
subMenu: [
{
label: 'Overlapping',
icon: VisibilityIcon,
type: 'radio',
checked: self.trackLabels === 'overlapping',
onClick: () => self.setTrackLabels('overlapping'),
},
{
label: 'Offset',
icon: VisibilityIcon,
type: 'radio',
checked: self.trackLabels === 'offset',
onClick: () => self.setTrackLabels('offset'),
},
{
label: 'Hidden',
icon: VisibilityIcon,
type: 'radio',
checked: self.trackLabels === 'hidden',
onClick: () => self.setTrackLabels('hidden'),
},
],
},
...(canShowCytobands
? [
{
label: showCytobands ? 'Hide ideogram' : 'Show ideograms',
onClick: () => {
self.setShowCytobands(!showCytobands)
},
},
]
: []),
]
// add track's view level menu options
for (const [key, value] of self.trackTypeActions.entries()) {
if (value.length) {
menuItems.push(
{ type: 'divider' },
{ type: 'subHeader', label: key },
)
value.forEach(action => {
menuItems.push(action)
})
}
}
return menuItems
},
}))
.views(self => {
let currentlyCalculatedStaticBlocks: BlockSet | undefined
let stringifiedCurrentlyCalculatedStaticBlocks = ''
return {
get staticBlocks() {
const ret = calculateStaticBlocks(self)
const sret = JSON.stringify(ret)
if (stringifiedCurrentlyCalculatedStaticBlocks !== sret) {
currentlyCalculatedStaticBlocks = ret
stringifiedCurrentlyCalculatedStaticBlocks = sret
}
return currentlyCalculatedStaticBlocks as BlockSet
},
get dynamicBlocks() {
return calculateDynamicBlocks(self)
},
get roundedDynamicBlocks() {
return this.dynamicBlocks.contentBlocks.map(block => {
return {
...block,
start: Math.floor(block.start),
end: Math.ceil(block.end),
}
})
},
get visibleLocStrings() {
return calculateVisibleLocStrings(this.dynamicBlocks.contentBlocks)
},
get coarseVisibleLocStrings() {
return calculateVisibleLocStrings(self.coarseDynamicBlocks)
},
}
})
.actions(self => ({
// this "clears the view" and makes the view return to the import form
clearView() {
self.setDisplayedRegions([])
self.tracks.clear()
// it is necessary to run these after setting displayed regions empty
// or else model.offsetPx gets set to Infinity and breaks
// mobx-state-tree snapshot
self.scrollTo(0)
self.zoomTo(10)
},
setCoarseDynamicBlocks(blocks: BlockSet) {
self.coarseDynamicBlocks = blocks.contentBlocks
self.coarseTotalBp = blocks.totalBp
},
afterAttach() {
addDisposer(
self,
autorun(
() => {
if (self.initialized) {
this.setCoarseDynamicBlocks(self.dynamicBlocks)
}
},
{ delay: 150 },
),
)
},
}))
.actions(self => ({
async exportSvg(opts: ExportSvgOptions = {}) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const html = await renderToSvg(self as any, opts)
const blob = new Blob([html], { type: 'image/svg+xml' })
saveAs(blob, opts.filename || 'image.svg')
},
/**
* offset is the base-pair-offset in the displayed region, index is the index of the
* displayed region in the linear genome view
*
* @param start - object as `{start, end, offset, index}`
* @param end - object as `{start, end, offset, index}`
*/
moveTo(start?: BpOffset, end?: BpOffset) {
moveTo(self, start, end)
},
navToLocString(locString: string, optAssemblyName?: string) {
const { assemblyNames } = self
const { assemblyManager } = getSession(self)
const { isValidRefName } = assemblyManager
const assemblyName = optAssemblyName || assemblyNames[0]
let parsedLocStrings
const inputs = locString
.split(/(\s+)/)
.map(f => f.trim())
.filter(f => !!f)
// first try interpreting as a whitespace-separated sequence of
// multiple locstrings
try {
parsedLocStrings = inputs.map(l =>
parseLocString(l, ref => isValidRefName(ref, assemblyName)),
)
} catch (e) {
// if this fails, try interpreting as a whitespace-separated refname,
// start, end if start and end are integer inputs
const [refName, start, end] = inputs
if (
`${e}`.match(/Unknown reference sequence/) &&
Number.isInteger(+start) &&
Number.isInteger(+end)
) {
parsedLocStrings = [
parseLocString(refName + ':' + start + '..' + end, ref =>
isValidRefName(ref, assemblyName),
),
]
} else {
throw e
}
}
const locations = parsedLocStrings?.map(region => {
const asmName = region.assemblyName || assemblyName
const asm = assemblyManager.get(asmName)
const { refName } = region
if (!asm) {
throw new Error(`assembly ${asmName} not found`)
}
const { regions } = asm
if (!regions) {
throw new Error(`regions not loaded yet for ${asmName}`)
}
const canonicalRefName = asm.getCanonicalRefName(region.refName)
if (!canonicalRefName) {
throw new Error(`Could not find refName ${refName} in ${asm.name}`)
}
const parentRegion = regions.find(
region => region.refName === canonicalRefName,
)
if (!parentRegion) {
throw new Error(`Could not find refName ${refName} in ${asmName}`)
}
return {
...region,
assemblyName: asmName,
parentRegion,
}
})
if (locations.length === 1) {
const loc = locations[0]
self.setDisplayedRegions([
{ reversed: loc.reversed, ...loc.parentRegion },
])
const { start, end, parentRegion } = loc
this.navTo({
...loc,
start: clamp(start ?? 0, 0, parentRegion.end),
end: clamp(end ?? parentRegion.end, 0, parentRegion.end),
})
} else {
self.setDisplayedRegions(
// @ts-ignore
locations.map(r => (r.start === undefined ? r.parentRegion : r)),