All files / src/ui InfoPanel.ts

95.21% Statements 338/355
89.05% Branches 122/137
91.66% Functions 22/24
95.21% Lines 338/355

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 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                                                                                                                                      2x 2x 2x 2x 2x 2x 2x 2x                                                                             2x 2x   2x               2x                             2x                 2x 2x   2x   2x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x                   2x 2x 2x                       2x                   2x 2x 2x                 2x 4x 4x 4x                       2x                         2x 8x 8x 8x   2x 45x 45x     4x 4x 4x 1x 3x 4x 4x 4x 4x 45x 37x 37x 37x 4x 4x 40x 4x 45x     2x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x             2x 45x 45x 40x 45x 45x 45x 45x 45x 45x 45x 6x 1x 45x 45x   2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   2x 48x 48x 48x 48x 48x 48x           48x 13x 35x 48x 48x 48x             48x 2x 2x 2x 2x 1x 1x 2x 2x 46x                     48x 34x 34x 34x 14x 48x 48x           48x 48x                         48x 48x 48x   48x 1x 47x 48x 48x 48x       48x 48x 48x 48x 48x 48x                                         2x 33x 33x 10x 58x         10x 10x 10x 10x 10x 10x 10x 33x 33x 33x 33x 33x         33x 33x 33x     33x 33x 33x 33x 33x 33x 33x 33x 33x     33x 33x 33x 10x 10x 10x 33x 10x 10x 10x 10x 10x 10x 10x 10x 90x 90x 90x 90x 10x 10x 10x 1x 9x 33x 8x 2x 33x 33x 33x               2x 10x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 68x 68x 68x 68x 68x   68x 68x 68x 8x 8x 8x 10x           2x       33x 19x 28x 17x 17x 17x 17x 17x 17x 17x 33x 33x 33x 33x 33x 33x         33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x                             2x 33x 33x 33x 33x 33x 33x 33x 33x 1x 32x 33x 33x 33x 33x 2x     10x     10x 10x 8x 10x 8x 8x     10x     10x 10x 8x 10x 3x 3x     10x 10x 10x 10x   10x   10x     1x 1x 1x 1x   715x 715x 715x             715x 715x 715x  
/**
 * The file info panel: attributes, metadata, the unassigned QC statistic, and
 * the performance counters.
 *
 * Three things here are specified rather than chosen.
 *
 * **The unassigned statistic (§7.4).** The fraction of contigs and bins that
 * binning failed to assign is shown once, as a read-only number, phrased as
 * `unassigned: 1,204 contigs (30.1%) · 830 bins (8.3%)`. Both quantities whole
 * on one line, because the line used to pair a count of contigs with a
 * *percentage* of bins and leave the other half of each to a paragraph under it:
 * a reader wanting either number had to assemble it from two sentences in two
 * units. It is a direct diagnostic of binning quality; a metagenomics reader
 * will look for it and a reviewer will expect it. It is a *number, not a view*:
 * it opens nothing, selects nothing, and is not a row in any table. It is the
 * sole exception to `__unbinned__` being invisible, and no code path reaches the
 * reserved genome through it — this panel receives four integers, not an index.
 *
 * **Every block here is a card** (§26.6). The QC statistic was a bare `h4` and
 * the metadata was a bare heading when empty and a `<details>` when not, which
 * made three heading shapes in one column and two of them for one block: a
 * reader comparing two files watched that strip change its typography rather
 * than fill and empty. They are cards now, with the same `cardTitle` and the
 * same fold every other card in every column has, and the stored metadata opens
 * folded because a hundred lines of JSON is not what a reader came to this
 * column for.
 *
 * The §12 read counters and the §6.3 deep-validation control used to live here
 * too. They moved to the status bar: both are glanced at rather than read, and
 * a sidebar block spends permanent vertical space on something a single line
 * can carry.
 *
 * **The record host** is the one part of this panel that changes as you
 * navigate: the `/genomes` or `/contigs` row of whatever heatmap is on screen
 * ({@link RecordCard}). It sits directly under the File card, because those two
 * are what the reader is actually looking at — this file, this genome — while
 * the QC statistic and the stored metadata are consulted once and then ignored.
 * Those two stay last, in that order, wherever the record card is.
 *
 * **The sequences host** sits above it, and on a cooler it is what the record
 * card used to be. A *Chromosome* record described the one sequence already
 * named in the breadcrumb, and it could only ever describe one; the Sequences
 * card lists every chromosome the file has with a tick beside each, so the same
 * strip of panel now says both what is drawn and what else could be — one
 * ticked is that chromosome's block, several are those chromosomes against each
 * other, none is the whole genome. The Chromosomes *table* is untouched: it is
 * the place columns are sorted and read, and this is the place a picture is
 * chosen. A metacool has no host filled here — its unit is the genome, and a
 * list of a hundred thousand contigs is not a picker (see `Session`).
 *
 * **The minimap host** is under it, and it is the same file's sequences drawn
 * rather than listed, with the current view marked on the strip
 * (`ui/MinimapCard.ts`). It is gated on the same fact the Sequences card is —
 * a metagenome's contigs are a texture and not a picture — and it is the one
 * card in this panel that has to be *told* things as the reader navigates, so
 * the session keeps the object and calls its own `update`.
 *
 * The three annotation cards were here too, under the record card. They are now
 * the Annotations column (`SidePanel`): everything in this panel is read, and
 * everything in those is worked on, so the two wanted different amounts of room
 * and different scroll boxes.
 *
 * This panel is the body of the **General** column, and is the only one of the
 * three whose contents it does not own — the shell mounts it there.
 */
 
import type { OpenResult } from '../worker/protocol'
import { convergenceOf, libraryComplexity, writePairtoolsStats, type PairStats } from '../pairs/stats'
import { devFeature } from '../state/devFeatures'
import { button, el, fmt } from './dom'
import { downloadBlob } from './export'
import { resolutionLabel } from '../units'
import { cardTitle, foldable, icon, iconButton, startFolded } from './icons'
import { cisChart, decayChart, slotOfType, typeSegments, typesBar } from './pairsCharts'
import { recordCard, type RecordSpec } from './RecordCard'
 
/**
 * Which map the File card describes, in a deck (§16.5).
 *
 * `own`: the session's own file — or its two, while it compares — named as the
 * map it is. `other`: a starred companion's, whose facts arrive once its panel
 * has opened the file (`info` is `null` until then).
 */
export type FileShown =
  | { kind: 'own'; name: string; starred: boolean }
  | { kind: 'other'; name: string; info: OpenResult | null }
 
export interface InfoPanelProps {
  info: OpenResult
  /**
   * Close one of the two open files.
   *
   * Offered only while there are two: the button is what makes the comparison
   * reversible from where it is described, and `1` promotes the second file to
   * the first rather than closing the session — the map that remains is a
   * perfectly ordinary one-file map.
   */
  onCloseFile?(which: 1 | 2): void
}
 
/**
 * There is deliberately no "close the map" button here any more.
 *
 * It used to sit on the single File card, and it was the only way out of the
 * matrix — a one-way door, in the panel that *describes* the file rather than
 * the one that lists what is drawn. Both maps now have a row of their own in
 * the Annotations column's Contact maps card, each with the same eye a track
 * carries and an × beside it, so putting the matrix down and letting go of it
 * are two visibly different acts in the place a reader already goes to decide
 * what is on screen. General says what the file *is*; it does not decide
 * whether it is drawn.
 */
 
export class InfoPanel {
  readonly el: HTMLElement
  /** Empty on a table view; `:empty` in the stylesheet is what hides it. */
  private readonly recordHost = el('div', { class: 'record-host' })
  /**
   * The Sequences card, on a file whose chromosomes are a picker.
   *
   * A host rather than a card built here, because the list arrives with the
   * `/chroms` read and the ticks are the session's — this panel describes the
   * file, and which sequences are drawn is a fact about the *view*.
   */
  private readonly sequenceHost = el('div', { class: 'sequence-host' })
  /**
   * The Genome minimap's slot, under the Sequences card.
   *
   * A host for the same reason the one above it is: the *card* is the session's
   * — it is built from the assembly and it has to be told where the reader is on
   * every navigation — while this panel only says where in the column it goes.
   * Directly under Sequences because the two answer one question between them:
   * that card is the list of sequences and this one is the picture of them, with
   * the current view marked on it (`ui/MinimapCard.ts`).
   *
   * Empty on a metagenome, and the session applies that gate with `suitsMinimap`
   * — the same rule that withholds the Sequences card and the browser's bar.
   * `.minimap-host:empty` is what keeps an absent card from spending a gap.
   */
  private readonly minimapHost = el('div', { class: 'minimap-host' })
  /**
   * The File card(s). One while one file is open, two while two are.
   *
   * A host rather than a fixed card, because the second file arrives and leaves
   * without the rest of this panel changing: the QC statistic and the metadata
   * below describe the *first* file whichever way, since that is the file whose
   * genomes and attributes every other view is about.
   */
  private readonly fileHost = el('div', { class: 'file-host' })
  private compare: OpenResult | null = null
  /** The map the card is about while a deck is up; `null` with no deck. */
  private shown: FileShown | null = null
 
  constructor(private readonly props: InfoPanelProps) {
    this.el = el(
      'aside',
      { class: 'info-panel' },
      this.fileHost,
      this.sequenceHost,
      this.minimapHost,
      this.recordHost,
      this.pairsBlock(),
      this.unassignedBlock(),
      this.metadataBlock(),
    )
    this.paintFiles()
  }
 
  /**
   * Hang the Sequences card under the File card, or take it away.
   *
   * Called once per file, with the card the session built: rebuilding it on
   * every navigation would throw away the filter text and the scroll position of
   * a list a reader is working their way down, and the ticks follow the view on
   * their own (`SequenceSelection`).
   */
  setSequences(card: HTMLElement | null): void {
    this.sequenceHost.replaceChildren(...(card === null ? [] : [card]))
  }
 
  /**
   * Hang the Genome minimap under the Sequences card, or take it away.
   *
   * Called once per file, with the card the session built — and then the card is
   * *kept*: it owns a `ResizeObserver`, a text-scale subscription and a drag in
   * flight, and where the reader is arrives through its own `update`, so
   * replacing it on every navigation would throw all four away to redraw one
   * highlight. `null` withdraws it, which is what a metagenome gets
   * (`suitsMinimap`) and what a session with no assembly gets.
   */
  setMinimap(card: HTMLElement | null): void {
    this.minimapHost.replaceChildren(...(card === null ? [] : [card]))
  }
 
  /**
   * Show the table row(s) behind the current view, or nothing at all.
   *
   * Called on every render, including with `[]`: a genome card left standing
   * over the genomes table would describe a heatmap that is no longer there.
   */
  setRecords(records: RecordSpec[]): void {
    this.recordHost.replaceChildren(...records.map(recordCard))
  }
 
  /**
   * Adopt, or drop, the second file.
   *
   * The heading is the tell: one file is *File*, two are *File 1* and *File 2*,
   * and the numbers are the triangles — 1 above the diagonal, 2 below it. The
   * mark beside each name says which without a legend.
   */
  setCompare(info: OpenResult | null): void {
    this.compare = info
    this.paintFiles()
  }
 
  /**
   * Re-read the open file's facts.
   *
   * Almost everything on this card is fixed for the life of an open file —
   * a bin size does not change while it is open — so the panel is painted once
   * and left. One thing does: an `.scool`'s cell set, which the reader changes
   * by ticking boxes, and with it the pixel count the card reports and the whole
   * -file gate forecasts from. Left unpainted, the panel went on saying *all
   * 3,882* over a map summed from two.
   */
  refresh(info: OpenResult): void {
    this.props.info = info
    this.paintFiles()
  }
 
  /**
   * Follow the star (§16.5): describe the starred map's file, and say under the
   * heading which map that is — as the Aesthetics column's *Map* card does, and
   * for the same reason. A deck is several files, and a card headed *File*
   * that went on describing the first of them after the star had moved to
   * another was a card about a map the reader had just said they were not
   * looking at. `null` takes the line away, for a session with no deck.
   */
  setShown(shown: FileShown | null): void {
    this.shown = shown
    this.paintFiles()
  }
 
  private paintFiles(): void {
    const shown = this.shown
    if (shown?.kind === 'other') {
      // A companion's one file. The comparison is the *first* map's two
      // triangles, and neither of them is the starred map's.
      this.fileHost.replaceChildren(
        this.singleCard(
          shown.info === null
            ? el('p', { class: 'clip-note', text: 'Its file’s facts are here once it has opened.' })
            : this.fileTable(shown.info),
        ),
      )
      return
    }
    if (this.compare === null) {
      this.fileHost.replaceChildren(this.singleCard(this.fileTable(this.props.info)))
      return
    }
    const first = this.fileCard(1, this.props.info)
    const line = this.forLine()
    if (line !== null) first.querySelector('.card-head')?.after(line)
    this.fileHost.replaceChildren(first, this.fileCard(2, this.compare))
  }
 
  /** The one File card: its heading, the line naming its map in a deck, and `body`. */
  private singleCard(body: HTMLElement): HTMLElement {
    const line = this.forLine()
    return el(
      'div',
      { class: 'card' },
      foldable(
        el(
          'h3',
          { class: 'file-head card-head' },
          icon('file', { size: 13 }),
          el('span', { class: 'file-name', text: 'File' }),
        ),
        'File',
      ),
      ...(line === null ? [] : [line]),
      body,
    )
  }
 
  /**
   * The map this card describes, named, with the star it carries — the Map
   * card's own line (`MatrixPanel.setCardFor`), so the two columns say the same
   * thing the same way. Nothing with no deck: one map needs no name.
   */
  private forLine(): HTMLElement | null {
    const shown = this.shown
    if (shown === null) return null
    const starred = shown.kind === 'other' || shown.starred
    const line = el(
      'p',
      { class: 'map-card-for file-card-for' },
      icon('star', { size: 12, class: starred ? 'map-card-star is-on' : 'map-card-star' }),
      el('span', { text: shown.name }),
    )
    line.title = starred
      ? `The file of ${shown.name}, the starred map. Star another map to read its file here.`
      : `The file of ${shown.name}, the session’s own map. Star a map to read its file here.`
    return line
  }
 
  private fileCard(which: 1 | 2, info: OpenResult): HTMLElement {
    const close = this.props.onCloseFile
    return el(
      'div',
      { class: 'card card-file' },
      foldable(
        el(
          'h3',
          { class: 'file-head card-head' },
          el('span', {
            class: `compare-mark ${which === 1 ? 'compare-upper' : 'compare-lower'}`,
            text: which === 1 ? '◥' : '◣',
            title: which === 1 ? 'Upper-right triangle' : 'Lower-left triangle',
          }),
          el('span', { class: 'file-name', text: `File ${which}` }),
          ...(close === undefined
            ? []
            : [
                iconButton(
                  'x',
                  which === 1
                    ? 'Close this file. The other takes its place and the map goes back to one.'
                    : 'Close this file and go back to one map.',
                  () => close(which),
                  { class: 'btn btn-icon btn-close', size: 13 },
                ),
              ]),
        ),
        `File ${which}`,
      ),
      this.fileTable(info),
    )
  }
 
  private fileTable(info: OpenResult): HTMLElement {
    const rows: Array<[string, string]> = [
      ['uri', info.uri],
      ['layout', info.layout.kind],
      ['source', info.sourceKind === 'local' ? `local file (${fmt.bytes(info.sourceBytes)})` : `remote (${fmt.bytes(info.sourceBytes)})`],
      ['bin size', info.binsize === null ? '—' : resolutionLabel(info.binsize)],
      ['bin type', String(info.info['bin-type'] ?? '—')],
      // `genome-then-length` is the multi-genome format's word for its contig
      // order, and a `.hic`, a `.pairs` and a HiC-Pro pair are given it only so
      // they read as one; while that format is a dev feature that is off
      // (§29), the row names a concept the page does not offer, so it is not
      // drawn.
      ...(devFeature('metacool')
        ? ([['ordering', String(info.info['ordering'] ?? '—')]] as Array<[string, string]>)
        : []),
      ['storage mode', String(info.info['storage-mode'] ?? '—')],
      ['assembly', String(info.info['assembly'] ?? '—')],
      ['format', `${String(info.info['format'] ?? '—')} v${String(info.info['format-version'] ?? '?')}`],
      // **Which of a `.hic`'s vectors the balanced map is drawn with** (§3.6).
      // The reader chooses the file's best — SCALE, then KR and its kin, then
      // the coverage ones — and the choice was made silently: a reader of
      // somebody else's file could not tell a KR picture from a VC one. Named
      // here, beside the format it belongs to, and named as missing where the
      // rung open has none, since *balanced* is then not on offer.
      ...(info.info['format'] === 'HIC'
        ? ([
            [
              'normalisation',
              typeof info.info['hic-normalisation'] === 'string'
                ? info.info['hic-normalisation']
                : 'none at this resolution',
            ],
          ] as Array<[string, string]>)
        : []),
      // A cooler has no genome layer, and a row reading "genomes 0" invites the
      // question of where they went. It is the contigs — cooler's chroms — that
      // this file is made of.
      //
      // `__unbinned__` is not one of them (§7.4, §8.5). `nGenomes` counts it,
      // because it occupies genome index 0 and every lookup downstream has to
      // know that; the genomes *table* under this card does not list it, so
      // printing the raw count put a 49th organism in a card sitting a hand's
      // width above a table saying 48 rows. The QC line below is the one place
      // it is counted.
      ...(info.hasGenomes
        ? ([
            ['genomes', fmt.int(info.nGenomes - (info.unassigned === null ? 0 : 1))],
          ] as Array<[string, string]>)
        : []),
      [info.hasGenomes ? 'contigs' : 'chromosomes', fmt.int(info.nContigs)],
      ['bins', fmt.int(info.nBins)],
      // Two rows for an scool where every other file has none: how many cells
      // it holds, and how many of them the picture on screen is made of. The
      // second is the one that matters — a map summed from four cells and a map
      // summed from four thousand look like different experiments, and this is
      // the panel that says which one is being read.
      ...(info.cells.length === 0
        ? []
        : ([
            ['cells', fmt.int(info.cells.length)],
            [
              'cells summed',
              info.activeCells.length === info.cells.length
                ? `all ${fmt.int(info.cells.length)}`
                : fmt.int(info.activeCells.length),
            ],
          ] as Array<[string, string]>)),
      // An scool's root declares no pixel count — it has no pixels of its own —
      // so the honest number is the selected cells', which is also the one the
      // whole-file gate forecasts from.
      [
        'non-zero pixels',
        info.cellNnz !== null
          ? fmt.int(info.cellNnz)
          : info.info['nnz'] === null || info.info['nnz'] === undefined
            ? '—'
            : fmt.int(Number(info.info['nnz'])),
      ],
      ['sum', info.info['sum'] === null || info.info['sum'] === undefined ? '—' : fmt.int(Number(info.info['sum']))],
    ]
    // One line a row, scrolled sideways rather than wrapped: a URI broken over
    // eight lines, and `storage mode` over two, made the card three times as
    // tall as its facts and split words a reader copies out of it.
    return el(
      'div',
      { class: 'file-scroll' },
      el('div', { class: 'kv kv-nowrap' }, ...rows.flatMap(([key, value]) => keyValue(key, value))),
    )
  }
 
  /**
   * What `pairtools stats` says of the records a `.pairs` import read (§3.7).
   *
   * Only on a map imported from one: every number here is about records, which
   * no other container keeps, and the import counted them in the pass that
   * binned the map (`pairs/stats.ts`). The rows are the ones a reader judges a
   * library by — how much of it mapped, how much was duplicated, how much is
   * cis and how far it reaches — each as a count and as the share pairtools
   * and MultiQC give it, so the number here is the number in their reports.
   * The rest of what pairtools counts is in the file the button writes, in its
   * own format, rather than in forty more rows.
   *
   * Three small charts sit among the rows, each under the rows it pictures
   * (`ui/pairsCharts.ts`): the pair types as one bar under *duplicates*, with
   * the chips as its key; cis past each distance as columns under the last of
   * those rows; and P(s) by orientation under *strands meet*, with the point
   * it names marked. Each is left out where the file has nothing to draw — no
   * `pair_type` column, no cis pair, no strands — rather than drawn empty.
   */
  private pairsBlock(): HTMLElement | null {
    const stats = this.props.info.pairs?.stats ?? null
    if (stats === null) return null
    const share = (part: number, whole: number): string =>
      whole > 0 ? `${fmt.int(part)} · ${fmt.pct(part / whole)}` : fmt.int(part)
    // Each share's denominator is pairtools': of every record for the first
    // three, of the mapped for the duplicates, and of the unique mapped — the
    // `total_nodups` every `frac_cis` is over — for the rest. Said on the key,
    // so the value stays a count and a percentage a narrow column can hold.
    const rows: Array<[string, string, string]> = [
      ['records', fmt.int(stats.total), 'Every record in the file.'],
      ['mapped', share(stats.totalMapped, stats.total), 'Both sides mapped, of every record.'],
      ['one side', share(stats.totalSingleSidedMapped, stats.total), 'One side mapped, of every record.'],
      ['unmapped', share(stats.totalUnmapped, stats.total), 'Neither side mapped, of every record.'],
      [
        'duplicates',
        stats.pairTypeColumn ? share(stats.totalDups, stats.totalMapped) : 'not marked',
        'Pairs typed DD, of the mapped.',
      ],
      ['cis', share(stats.cis, stats.totalNodups), 'Both sides on one sequence, of the unique mapped pairs.'],
      ['trans', share(stats.trans, stats.totalNodups), 'On two sequences, of the unique mapped pairs.'],
      // The shares past 1, 2, 4, 10, 20 and 40 kb are the chart under these
      // two rows, each column labelled with its share and its exact count on
      // hover: six rows of the same numbers above it made the card twice the
      // height for nothing a reader could not already read off the columns.
      ['library size', libraryText(stats), 'Distinct molecules, estimated from the duplicates as pairtools does.'],
      ['strands meet', convergenceText(stats), convergenceTitle(stats)],
    ]
    // A word beside the mark, because what it saves is a format with a name a
    // reader looks for — the file MultiQC and `pairtools stats --merge` read.
    const save = button(
      'save .stats',
      () => void downloadBlob(new Blob([writePairtoolsStats(stats)], { type: 'text/plain' }), statsName(this.props.info.uri)),
      {
        class: 'btn btn-small pairs-stats-save',
        title: 'Save every count as pairtools writes them: a .stats file MultiQC and `pairtools stats --merge` read.',
      },
    )
    save.prepend(icon('download', { size: 13 }))
    // Each chart under the last row it pictures, across both of the table's
    // columns, so the rows on either side of it keep one key column.
    const after = new Map<string, HTMLElement>()
    const types = this.pairTypesBlock(stats)
    if (types !== null) after.set('duplicates', types)
    const cis = cisChart(stats)
    if (cis !== null) after.set('trans', cis)
    const decay = decayChart(stats)
    if (decay !== null) after.set('strands meet', decay)
    return el(
      'div',
      { class: 'card pairs-stats' },
      cardTitle('Pairs statistics', 'library'),
      el(
        'div',
        { class: 'kv pairs-stats-table' },
        ...rows.flatMap(([key, value, title]) => {
          const [k, v] = keyValue(key, value)
          k.title = title
          const chart = after.get(key)
          return chart === undefined ? [k, v] : [k, v, chart]
        }),
      ),
      ...(stats.scoped
        ? [el('p', { class: 'hint', text: 'Counted over the sequences the index let the import read, not the whole file.' })]
        : []),
      ...(stats.pairTypeColumn
        ? []
        : [el('p', { class: 'hint', text: 'This file has no pair_type column, so no record is counted as a duplicate.' })]),
      el('div', { class: 'pairs-stats-actions' }, save),
    )
  }
 
  /**
   * The pair types: one bar of every record by its type, and a chip a type
   * under it, so a line breaks between two types and never inside one. The
   * chips are the bar's key — each carries its segment's swatch, the folded
   * types all the neutral one — so the bar needs no legend of its own.
   */
  private pairTypesBlock(stats: PairStats): HTMLElement | null {
    if (stats.pairTypes.length === 0) return null
    const segments = typeSegments(stats)
    const bar = typesBar(stats)
    return el(
      'div',
      { class: 'pairs-stats-chart pairs-stats-types-block' },
      el('div', { class: 'pairs-stats-caption', text: 'pair types' }),
      bar,
      el(
        'p',
        { class: 'pairs-stats-types', title: 'Every pair type in the file, the most common first.' },
        ...stats.pairTypes.map(([type, count]) => {
          const slot = slotOfType(segments, type)
          return el(
            'span',
            { class: 'pairs-stats-type' },
            ...(bar === null
              ? []
              : [el('span', { class: `pairs-stats-swatch ${slot === 0 ? 'is-other' : `is-s${slot}`}`, attrs: { 'aria-hidden': 'true' } })]),
            `${type} ${fmt.int(count)}`,
          )
        }),
      ),
    )
  }
 
  /**
   * The single retained `__unbinned__` number, labelled as a QC statistic and
   * not as a genome.
   */
  private unassignedBlock(): HTMLElement | null {
    // A cooler was never binned, so there is no binning to report on — clean or
    // otherwise. Saying "every contig was assigned to a bin" about a file with
    // no bins is a false statement, not a reassuring one.
    if (!this.props.info.hasGenomes) return null
    const stats = this.props.info.unassigned
    if (stats === null) {
      return el(
        'div',
        { class: 'card qc qc-clean' },
        cardTitle('Binning QC', 'info'),
        el('p', { text: 'This file has no __unbinned__ genome: every contig was assigned to a bin.' }),
      )
    }
    const contigFraction = stats.totalContigs === 0 ? 0 : stats.contigs / stats.totalContigs
    const binFraction = stats.totalBins === 0 ? 0 : stats.bins / stats.totalBins
    return el(
      'div',
      { class: 'card qc' },
      cardTitle('Binning QC', 'info'),
      // Each quantity whole: a count, and what share of its own total that is.
      // The hint under it is one clause, because the two sentences it used to
      // carry were a disclaimer — *cannot be displayed*, *a diagnostic only* —
      // and a reader acts on neither; what they act on is the number.
      el('p', {
        class: 'qc-stat',
        text:
          `unassigned: ${fmt.int(stats.contigs)} contigs (${fmt.pct(contigFraction)}) · ` +
          `${fmt.int(stats.bins)} bins (${fmt.pct(binFraction)})`,
      }),
      el('p', {
        class: 'hint',
        text: '__unbinned__ is not a genome and is never drawn; a diagnostic of binning quality.',
      }),
    )
  }
 
  /**
   * What the file stored about itself, in the column's own shape.
   *
   * One card in both states, headed like every other card here, and *folded*
   * when there is JSON in it. It was two shapes before — an uppercase iconed
   * heading with a hint under it when the file stored nothing, a bare `▶
   * Metadata` disclosure when it stored something — so the absence of metadata
   * was announced more loudly than its presence, and a reader moving between a
   * cooler and a metacool saw one strip of this column change its typography.
   * Folded rather than open because this block is consulted once and then
   * ignored (see the header): the fold is the card's own, so the chevron says
   * which way it will go and one press opens it.
   */
  private metadataBlock(): HTMLElement {
    const metadata = this.props.info.metadata
    const stored = metadata !== null && Object.keys(metadata).length > 0
    const head = cardTitle('Metadata', 'info')
    const card = el(
      'div',
      { class: 'card' },
      head,
      stored
        ? el('pre', { class: 'json', text: JSON.stringify(metadata, null, 2) })
        : el('p', { class: 'hint', text: 'No metadata was stored in this file.' }),
    )
    if (stored) startFolded(card)
    return card
  }
}
 
/** pairtools' library estimate, in molecules, or what it means where it is not a number. */
function libraryText(stats: PairStats): string {
  // Estimated from the duplicates, so not at all from a file that marks none,
  // and without bound from one that marks none duplicated — pairtools' `nan`.
  if (!stats.pairTypeColumn) return 'not estimated'
  if (stats.totalDups === 0 && stats.totalMapped > 0) return 'unbounded'
  const size = libraryComplexity(stats.totalMapped, stats.totalDups)
  if (!(size > 0)) return '—'
  return `${fmt.int(Math.round(size))} molecules`
}
 
/** Where the four orientations converge, as pairtools finds it. */
function convergenceText(stats: PairStats): string {
  // Nothing to compare — no strands in the file, or no cis pair — is not
  // agreement everywhere.
  const counted = Object.values(stats.distFreq).some((counts) => counts.some((count) => count > 0))
  if (!counted) return '—'
  const convergence = convergenceOf(stats)
  if (convergence.distance === null) return 'everywhere'
  return `past ${resolutionLabel(convergence.distance)}`
}
 
/** What {@link convergenceText} measured, and which orientation strayed furthest. */
function convergenceTitle(stats: PairStats): string {
  const { strands } = convergenceOf(stats)
  return (
    'The separation past which the four strand orientations each stay within 5% of their mean, ' +
    'as pairtools finds it' +
    (strands === null ? '.' : `; ${strands} strays furthest.`)
  )
}
 
/** `sample.pairs.gz` → `sample.stats`, as pairtools names its own. */
function statsName(uri: string): string {
  const name = uri.split('::')[0].split(/[?#]/)[0].split('/').pop() ?? 'pairs'
  return `${name.replace(/\.pairs(am)?(\.b?gz)?$/i, '') || 'pairs'}.stats`
}
 
function keyValue(key: string, value: string): HTMLElement[] {
  return [
    el('div', { class: 'k', text: key }),
    // A long value **wraps** rather than being cut: the panel is where a reader
    // goes to read the identity of what is on screen whole, and the card's
    // sideways scroll was the promise this made and never kept — a URL chopped
    // at `http://127.0.0.1:5` with no ellipsis and no scrollbar drawn reads as a
    // rendering fault rather than as a long path. The `title` stays for the
    // reader who would rather hover than read three lines.
    el('div', { class: 'v', text: value, title: value }),
  ]
}