MST patterns
JBrowse uses @jbrowse/mobx-state-tree, an internal ESM fork of
MobX-State-Tree. The public API matches
upstream MST, so the upstream documentation applies.
The sections below cover the MST idioms JBrowse relies on: driving side-effects
with autorun, composing models from mixins, types.frozen, volatile state,
and using self over this in views.
autorun inside useEffect
Drive a side-effect from MST observables in a React component. The autorun's
disposer goes in the useEffect cleanup, and every observable read inside
becomes a dependency without going in the dep array:
useEffect(() => {
const dispose = autorun(() => {
const xJ = snp2 && model.locusViewportX(snp2.refName, snp2.start)
const xI = snp1 && model.locusViewportX(snp1.refName, snp1.start)
view.setVolatileGuides(
xJ !== undefined && xI !== undefined ? [{ xPos: xJ }, { xPos: xI }] : [],
)
})
return () => {
dispose()
view.setVolatileGuides([])
}
}, [snp1, snp2, model, view])Prefer autorun over reaction for side-effects: it runs immediately and
tracks dependencies automatically. Use reaction only to separate the tracked
expression from the effect.
To read an observable inside an autorun without making it a dependency, wrap
it in untracked(). The dotplot's geometry build tracks the zoom and reads the
pan offset untracked:
// GPU precision anchor: the viewport-start cumBp per axis at build time.
// Read offsetPx untracked so panning alone doesn't rebuild geometry
// (pan is a uniform-only update on the GPU); a zoom changes bpPerPx,
// which IS tracked, so the base is recaptured near the view on zoom.
// Whole bp, so an integer coordinate minus it stays exact in Float32
// out to 2^24 bp.
// eslint-disable-next-line no-restricted-syntax -- effect input: the geometry build consumes the pan offset, zoom is the decision
const { baseH, baseV } = untracked(() => ({
baseH: Math.round(hview.offsetPx * hview.bpPerPx),
baseV: Math.round(vview.offsetPx * vview.bpPerPx),
}))The dotplot's fetch takes the split further, and it is the pattern to copy for
any expensive effect: fold every input that should trigger it into one computed
(currentFetchKey), track only that, and read the raw values inside
untracked. Tracking the underlying observables individually would refire the
worker fetch on every pan frame for an identical result.
untracked above is deliberate. MST actions also run untracked, so moving
an autorun's body into one leaves the autorun with no dependencies at all. It
fires exactly once, never again, and nothing throws or warns.
Factoring the body out into an action is easy to reach for, because it looks
like the obvious way to reuse it — from a menu item, or from a flush-on-teardown
path that wants the same work on demand. The fix is to duplicate the reads in
the autorun and say why in a comment; RegionTooLargeMixin's byte gate is the
worked example.
self.someAction(getSnapshot(self)) also tracks, but only because the snapshot
is taken in the argument list, before the action is entered. Move that read
inside the action and the dependency disappears with it.
Model composition
types.compose(name, ...types) layers mixins onto a base model. It takes the
name and every part up front — there is no .compose() method on a model type,
so the mixins cannot be chained on one at a time the way .views() and
.actions() are. LinearMafDisplay layers its mixins onto BaseDisplay, with
the three parts every linear display shares nested as one, since a compose of
more than eleven parts erases every prop rather than failing:
.compose(
'LinearMafDisplay',
types.compose(
BaseDisplay,
TrackHeightMixin(),
MultiRegionDisplayMixin(),
),
StoredHoverMixin<MafRowHover>((a, b) => a.name === b.name),
CoarseTierMixin<MafRegionPayload<MafSummaryRecord[]>>(),
LegendMixin(),
ColorWritesMixin(),
TreeSidebarMixin<MafRow>(),
ContextMenuMixin<MafContextMenuInfo>(),
ScoreScaleMixin(COVERAGE_Y_PATHS),
types.model({
/**
* #property
*/
type: types.literal('LinearMafDisplay'),
/**
* #property
*/
configuration: ConfigurationReference(configSchema),
}),
).views() / .actions() / .volatile() chain onto the result of that one
call.
Mixins are factory functions returning a model type, not classes, so the same mixin can be composed at different positions in the chain without inheritance.
Keep the main model chain in one file. Splitting .views() or .actions()
across files obscures the composition order and which views depend on which.
Chaining multiple .views() blocks
self inside a .views() block is typed with everything the model had
before that block. So a later block reaches an earlier block's getters on
self, and that is the reason to split. LinearMarkDisplay puts its typed
conf getter in a separate block so every getter after it can read self.conf:
.views(self => ({
/**
* #getter
* the config typed off the concrete schema
*/
get conf(): LinearMarkDisplayConfig {
return self.configuration
},
}))Use multiple blocks when a getter depends on another getter, making the dependency explicit through ordering.
types.frozen
Use types.frozen() for data that is:
- Large and doesn't need deep reactivity (e.g., an array of 10k feature objects)
- Stored as a plain JSON value and hydrated lazily into MST nodes on first access
sortRowsBy: types.maybe(types.frozen<RowSortSpec>()),types.frozen<T>() takes the shape as a type parameter and stores a plain
value. Wrap it in types.maybe or types.optional the same as any other type —
frozen is about what MST does with the value, not about whether it is present.
Frozen values are compared by reference; MST does not track fields inside them.
For reactive access to a field inside a frozen value, copy it out into a regular
MST property or a .volatile() field.
To make a field a dependency of an autorun without using its value, void it —
for a frozen field that means the autorun fires when the whole value is
replaced, without enumerating its properties. The shared fetch skeleton (which
every fetch outside the per-region and global display families runs on, Hi-C's
file-header read among them) does it to a counter so the retry button re-runs
the fetch:
() => {
// the pure "go again" signal, read unconditionally above every gate so a
// Retry click re-runs the body even when nothing else moved
const reloadEpoch = self.reloadCounter
// Tracked for the same reason as the counter, but this one closes the
// gate below, so a run that returned before the counter read would drop
// the one observable that can reopen the gate, and a Cancel could not be
// undone by Retry. Order, not just position: counter first, then this,
// then the gates.
const canceled = self.fetchCanceled === true
// Above the gate, not only above `prepare`: teardown mutates the
// observables this body reads before the disposers run, and every `gate`
// but the breakpoint view's reaches the containing view or track through a
// parent walk (`host.initialized`, `isMinimized`, `getContainingView`),
// which throws once the node has left the tree. This catches the destroyed
// node; the detached-and-still-alive window (ADR-069) is covered only by
// the walk's own cache. Nothing is reported for a dead node — there is no
// Retry button left to be dead, and the check would read three more
// members of the destroyed node to decide it.
if (!isAlive(self)) {
return false
}
if (canceled || gate?.() === false) {
noteFetchAutorunRun?.('gated')
return false
}
const args = prepare()
if (args === undefined) {
noteFetchAutorunRun?.('declined')
return false
}
// The freshness gate, and the reload that overrides it. The epoch is
// stamped at ISSUE where the key is stamped at commit: a fetch that fails
// leaves nothing current, so this gate is open anyway on the next run and
// consuming the retry here is safe, and a reload landing
// mid-flight is handled by the re-run the counter read above already
// guarantees.
if (held !== undefined && held(args) && reloadEpoch === issuedEpoch) {
noteFetchAutorunRun?.('declined')
return false
}
issuedEpoch = reloadEpoch
noteFetchAutorunRun?.('fetched')
// `run` is called synchronously, so its prefix down to its first await
// executes in this derivation; `FetchPhases.run` promises those reads are
// untracked, and unlike the MST flow the LGV side uses, nothing
// here makes it so. Whatever the run needs tracked belongs in `prepare`.
// eslint-disable-next-line no-restricted-syntax -- effect input: run's prefix reads are the fetch's, prepare is the trigger list
untracked(() => {
void runFetchOnce(self, rotation.begin(), args, {
run,
commit: commitAndStamp,
setError,
onBegin,
onEnd,
})
})
// arms the debounce; the runs that bail above return false and stay on
// the leading edge, so the first real fetch is immediate while a
// zoom/pan refetch debounces
return true
},Give every autorun a name as that one does; MobX shows the name when you debug
which effect refired.
self over this in .views()
self over this is a typing rule, not a runtime one. self and
self-via-this are the same object at runtime, and both dispatch to a later
block's override; what differs is what TypeScript can see:
selfis typed with everything the model had before the block. It reaches earlier blocks, the properties, and the volatiles — and cannot see a sibling in the same block.thisinside the returned object literal is typed as that literal. It reaches same-block siblings and nothing else.
Prefer self.X, and reach for this.X only for a sibling defined in the same
block. LinearVariantDisplay's variantGenotypeRowViews reads both in one
expression:
/**
* #getter
* Whether a circular view's ring hosts the display (`hostHeight`).
* The ring samples one canvas of its strip, the records band's.
*/
get inRing(): boolean {
return self.hostHeight !== undefined
},
/**
* #getter
* Whether the VCF has genotype rows to draw or hide, whatever hosts the
* display: it lists samples, more than one or one whose row somebody
* asked for. True until the sample listing lands.
*/
get hasSampleRows(): boolean {
const sampleCount = self.adapterSamples?.length
return !(
sampleCount === 0 ||
(sampleCount === 1 && !self.genotypesShowWritten)
)
},
/**
* #getter
* Whether the records band is the display, every record the filter
* admits, sized by `heightMode` and lettered as a feature track: a VCF
* with no samples, a one-sample call set whose row nobody asked for,
* or a ring, which draws one canvas and so the records alone.
*/
get recordsOnly(): boolean {
return !this.hasSampleRows || this.inRing
},
/**
* #getter
* Whether genotype rows draw: `genotypes.show`, on a VCF with samples.
* Hidden, the rows take no height and the records band is the track.
*/
get drawsGenotypeRows(): boolean {
return self.showGenotypes && !this.recordsOnly
},Note recordsOnly's explicit : boolean return type. A getter read through
this has to be annotated — without it TypeScript has to infer the literal's
type from a member that refers to the literal, and gives up with a
circular-reference error. That annotation is the cost of a same-block this
read, and the reason splitting into another block is usually tidier.
If you need to extend a parent view in a subclass, destructure the super version
off self outside the returned object, before redefining it. Reading it
inside would find your own override and recurse. LinearMafDisplay appending to
the inherited track menu:
.views(self => {
const { trackMenuItems: superTrackMenuItems } = self
return {
/**
* #method
*/
trackMenuItems() {
return [
...superTrackMenuItems(),
...buildMafTrackMenuItems(self),
...editPlotMenuItems(self, getCoverageMenuItems(self)),
...mafLaunchMenuItems({
session: getSession(self),
model: self,
view: containingLgv(self),
pluginManager: getEnv(self).pluginManager,
}),
]
},
}
})Volatile state
Use .volatile(() => ({ … })) for state that should not be persisted in
snapshots — loading flags, hover and menu state that a reload should reset.
Fetched data is not one: it is held in the foundation's per-region store and a
display reads it back through a getter. The feature display's block, in full:
/**
* #volatile
*/
featureIdUnderMouse: undefined as string | undefined,
/**
* #volatile
*/
subfeatureIdUnderMouse: undefined as string | undefined,
/**
* #volatile
* the hover tooltip's rows, each rendered as a separate element — see
* hoverTooltipRows for why this is a list and not one HTML string
*/
mouseoverExtraInformation: undefined as string[] | undefined,
/**
* #volatile
* genomic base currently hovered in a feature sequence dialog opened
* from this display, read by the LGV crosshair overlay
*/
sequenceHoverPosition: undefined as SequenceHoverPosition | undefined,
/**
* #volatile
*/
onScreenIdsMemo: createMembershipMemo(),undefined as T | undefined is the idiom for a volatile whose type MST cannot
infer from its initial value.
Observable maps (.map<K, V>()) give reactive key-level tracking: an autorun
reading map.get(key) re-fires only when that key changes, not on every map
write.
See also
- Developer guide: Data fetching pipeline
- Developer guide: Configuration schema
- Developer guide: Custom view types