All files / src/ui mapPick.ts

100% Statements 78/78
95.12% Branches 39/41
92.85% Functions 13/14
100% Lines 78/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                          2x 2x 2x   31x 31x 31x                             2x 4x 4x                 2x   31x 31x       31x 4x 4x 31x     2x 35x 35x                 2x 12x 11x 11x 11x 11x   2x 6x 4x 4x 4x 4x               2x 7x 7x 7x 7x 7x     2x 27x 27x   2x 147x 147x 147x                   2x 50x 9x 9x 9x 9x 9x                                 2x       6x 5x 5x                                                                                                                                                                               2x 22x 22x 22x 22x 22x 22x 22x 22x 18x     20x 18x 22x 22x 63x 29x 29x 22x 1x 1x 1x 21x 21x  
/**
 * A locus the reader pointed at on the map, for a form that asked them to.
 *
 * All that survives of the virtual 4C **lane** (§8.9), which is gone. That lane
 * was a whole feature: shift-drag on the map created a track, the track lived in
 * a store the panel borrowed because a `.metacool` has none, it renamed itself
 * from the anchor until the reader renamed it, and it drew a profile of whatever
 * block happened to be loaded. Every one of those things the **4C task** now does
 * better — it reads the file rather than the picture, it produces a track that is
 * a track like any other, and its result is a record with a provenance line. A
 * second, dimmer version of the same answer, appearing without being asked for,
 * was the thing worth removing.
 *
 * What was worth keeping is one sentence: *the reader can point at a locus*.
 *
 * ## Arming, and why it is a mode
 *
 * The gesture that used to name an anchor — shift-drag — is now a 1D zoom, so a
 * pick has to be asked for. The 4C task's **Pick on map** button arms this
 * module; while it is armed the next drag on a map names a locus instead of
 * doing whatever it would have done, and then it disarms itself.
 *
 * A mode on a map is a thing to be careful with, and the two rules that make
 * this one safe are both here rather than in the map: it disarms after **one**
 * pick, so a reader cannot leave it on by accident, and it disarms on Escape,
 * because the way out of a mode has to be the way out of every other mode in
 * this app. The map's own job is only to ask {@link isArmed} before it decides
 * what a drag means.
 */
 
import type { ManualPoint, ManualSpan } from '../annotations/manual'
 
/** A locus, in the shape the map reports and a form reads. */
export interface PickedLocus {
  /** Sequence name, as the file spells it — or a genome's, when {@link whole}. */
  contig: string
  /** 0-based, half-open — cooler's convention, and the reader's. */
  start: number
  end: number
  /**
   * The **whole named unit**, with no span inside it.
   *
   * What a pick on an axis of genomes can honestly report. A genome × genome
   * map has one cell per MAG and no base pair anywhere in it (§8.4), so the
   * answer to "where did they point" is a name and not a coordinate — and a
   * name is exactly what every range grammar here already accepts for a whole
   * sequence or a whole genome. Written out as the bare name by
   * {@link locusText}, so the form's box holds something the reader could have
   * typed.
   */
  whole?: boolean
}
 
let armed = false
let picked: PickedLocus | null = null
const listeners = new Set<() => void>()
 
function announce(): void {
  for (const listener of listeners) listener()
}
 
/**
 * Escape, on the window rather than on the map.
 *
 * The mode is armed from a button in a side panel, so the focus at the moment
 * the reader changes their mind is very often not on the plot — and a way out
 * that only works if you first click the thing you were trying not to click is
 * not a way out.
 *
 * Exported because it is the *rule*, and the rule is worth a test: the wiring
 * below needs a DOM and this does not. It stops nothing — Escape closes menus
 * and cancels drags elsewhere in the app, and one press putting away everything
 * it can is what a reader expects of it.
 */
export function pickKeyDown(event: { key: string }): void {
  if (event.key === 'Escape') disarmPick()
}
 
/**
 * Listen only while armed, so a session that never picks carries no listener.
 *
 * Capturing, so the press is seen before a focused control can swallow it. The
 * guard is for the workers and the tests, which have no `window`.
 */
/** One instance, module-wide: `removeEventListener` matches by identity. */
const escapeListener = (event: Event): void => pickKeyDown(event as KeyboardEvent)
 
function watchEscape(on: boolean): void {
  const scope = globalThis as {
    addEventListener?: typeof addEventListener
    removeEventListener?: typeof removeEventListener
  }
  if (scope.addEventListener === undefined || scope.removeEventListener === undefined) return
  if (on) scope.addEventListener('keydown', escapeListener, true)
  else scope.removeEventListener('keydown', escapeListener, true)
}
 
/** Whether the next drag on a map should name a locus rather than act. */
export function isArmed(): boolean {
  return armed
}
 
/**
 * Ask for the next drag.
 *
 * Idempotent, so a second press of an already-lit button is not a toggle by
 * accident — {@link disarmPick} is how it is turned off, and the button calls
 * that when it is pressed while lit.
 */
export function armPick(): void {
  if (armed) return
  armed = true
  watchEscape(true)
  announce()
}
 
export function disarmPick(): void {
  if (!armed) return
  armed = false
  watchEscape(false)
  announce()
}
 
/**
 * A drag named a locus. Records it and disarms.
 *
 * One pick per arming, deliberately: a reader who armed the button to answer one
 * question should not find the next three drags answering it again.
 */
export function pickLocus(at: PickedLocus): void {
  picked = at
  armed = false
  watchEscape(false)
  announce()
}
 
/** The last locus picked, or `null`. */
export function lastPick(): PickedLocus | null {
  return picked
}
 
export function subscribePick(listener: () => void): () => void {
  listeners.add(listener)
  return () => listeners.delete(listener)
}
 
/**
 * Forget everything, on the way into a different file.
 *
 * A locus names a sequence, and the same name in another file is another place —
 * so carrying one across would hand a task coordinates from somewhere the reader
 * never pointed at. The arming goes too: a mode entered against one file has no
 * meaning against the next.
 */
export function resetPick(): void {
  if (!armed && picked === null) return
  armed = false
  picked = null
  watchEscape(false)
  announce()
}
 
/**
 * `chrIV:500001-510000` — the format every tool in this field takes.
 *
 * **No thousands separators**, which is the difference between a string that
 * pastes into samtools, bedtools, IGV and this app's own locus boxes and one
 * that only looks right. The app's *display* format is the same locus with its
 * digits grouped (§26.1) — the hyphen is the same in both, an en dash being
 * this app's mark for a range of *values* rather than for a locus — and that
 * one is for reading; this one is for pasting, and the two must not be
 * confused.
 *
 * One-based inclusive, because that is what the format means: the interval here
 * is half-open and 0-based, as everything internal is, and the `+1` is the
 * conversion rather than an off-by-one.
 */
export function locusText(at: PickedLocus): string {
  // A whole unit is its name and nothing else: a genome has no coordinate
  // system of its own to write a span in, and `contig:1-0` would be a range
  // nothing accepts.
  if (at.whole === true) return at.contig
  return `${at.contig}:${at.start + 1}-${at.end}`
}
 
// ---------------------------------------------------------------------------
// Arming several maps at once
// ---------------------------------------------------------------------------
 
/** Anything that can be put into a picking mode — a map, or a deck of them. */
export interface Armable<H> {
  armPicking(handlers: H, onEnd: () => void): () => void
}
 
/**
 * What a picking mode reports, and — by which of these is present — what the
 * form is asking the reader to do.
 *
 * Two gestures rather than one, because the marks are not all one shape. A line
 * and an arrowhead are each *a place*, and the gesture for a place is a click. A
 * rectangle is *an extent*, and the gesture for an extent is a drag: pressing at
 * one corner and letting go at the other is what a hand does to draw a box, and
 * asking for two clicks instead made the reader hold a corner in their head
 * between them with nothing on the picture to show it.
 *
 * The panel reads which is present and arms accordingly — `box` turns drawing
 * on, where a plain drag draws a marquee instead of panning.
 */
export interface PickHandlers {
  /** A click, as one locus per axis. */
  point?: (at: PickedPlace) => void
  /** A drag, as one stretch per axis. */
  box?: (at: { rows: ManualSpan; cols: ManualSpan }) => void
}
 
/**
 * The place a click landed on, as a coordinate on each axis.
 *
 * Both axes, always, because a mark is a two-axis object and the *form* is what
 * decides which of them it means — a vertical rule wants the column, a
 * horizontal one the row, an arrowhead both. A surface that reported one would
 * be a surface whose answer only half the card could use.
 *
 * A **1D surface reports the same coordinate twice**, and says so with
 * {@link oneAxis}. That is not a stand-in for a missing number: a genome browser
 * has one axis, so the place a click names on it is the point of the map's
 * diagonal at that coordinate, where the row and the column genuinely are the
 * same base pair. Everything downstream then works unchanged — a box drawn on a
 * track comes out as the on-diagonal square, an arrowhead as the on-diagonal
 * cell — and only the line form has a decision left to make, which is what the
 * flag is for.
 */
export interface PickedPlace {
  /** Where it sits on the row axis. */
  rows: ManualPoint
  /** Where it sits on the column axis. */
  cols: ManualPoint
  /**
   * The surface has a single axis, so {@link rows} and {@link cols} are one
   * coordinate reported twice.
   *
   * Stated rather than inferred from `rows` equalling `cols`: a click on a map's
   * own diagonal reports two equal coordinates as well, and a card that read
   * *that* as "this came off a track" would quietly change what the map's
   * gestures mean — which is the one thing this flag must not do. Absent means a
   * surface with two axes, which is every map.
   */
  oneAxis?: boolean
}
 
/**
 * Put every map on screen into one picking mode.
 *
 * A mark is a coordinate and a companion is a map, so a deck of five pictures is
 * five places a reader may reasonably point at. The marks already *appear* on
 * all of them — they live in one store every panel draws from — and this is the
 * half that lets them be put there.
 *
 * What this is really for is making N modes behave as one. Each map ends its own
 * mode on Escape or when it is torn down, and each reports that by calling the
 * `onEnd` it was armed with; a reader who disarmed the panel they were looking
 * at and left the other four swallowing clicks they meant as navigation would
 * have a map that had silently stopped answering. So every target is armed with
 * the *same* ending, and that ending disarms all of them and reports upward
 * exactly once, however it was reached.
 *
 * Returns the same ending, for the card that armed the mode to put its button
 * back. `onEnd` is called immediately, and the returned function does nothing,
 * when there is no map to arm at all — which is the race where a view was torn
 * down between a button being enabled and being pressed.
 */
export function armAll<H>(
  targets: ReadonlyArray<Armable<H> | null | undefined>,
  handlers: H,
  onEnd: () => void,
): () => void {
  const cancels: Array<() => void> = []
  let ended = false
  const finish = (): void => {
    if (ended) return
    ended = true
    // Taken first: cancelling a target calls back in here through its own
    // `onEnd`, and the list must not be walked while it is emptying.
    for (const cancel of cancels.splice(0, cancels.length)) cancel()
    onEnd()
  }
  for (const target of targets) {
    if (target === null || target === undefined) continue
    cancels.push(target.armPicking(handlers, finish))
  }
  if (cancels.length === 0) {
    onEnd()
    return () => {}
  }
  return finish
}