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 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 | 2x 2x 2x 2x 2x 2x 2x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 2x 90x 90x 90x 90x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 1x 1x 90x 90x 90x 90x 90x 2x 2x 2x 2x 6x 6x 6x 6x 2x 90x 90x 90x 90x 90x 6x 6x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 2x 23x 23x 23x 23x 23x 23x 23x 2x 2x 87x 87x 2x 20x 20x 2x 2x 2x 2x 2x 2x 6x 6x 27x 18x 27x 6x 6x 6x 2x 129x 129x 2x 481x 481x 481x 481x 2x 90x 41x 41x 41x 90x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 334x 16x 16x 16x 16x 16x 16x 16x 16x 17x 17x 16x 16x 1x 1x 1x 1x 16x 16x 16x 16x 318x 318x 318x 334x 334x 334x 199x 119x 334x 334x 334x 1x 1x 1x 318x 318x 318x 22x 22x 20x 22x 22x 318x 318x 318x 318x 90x 2x 10x 5x 2x 2x 2x 2x 5x 5x 5x 5x 10x 10x 10x 2x 100x 405x 405x 405x 405x 376x 9x 405x 100x 2x 126x 126x 36x 36x 126x 126x 2x 59x 59x 59x 59x 59x 59x 59x 2x 126x 126x 442x 442x 24x 224x 1x 1x 1x 442x 442x 22x 22x 126x 1x 1x 1x 1x 1x 1x 126x 126x 2x 126x 126x 126x 1x 1x 9x 75x 9x 9x 9x 9x 9x 75x 45x 45x 45x 45x 9x 9x 68x 5x 5x 68x 6x 9x 9x 9x 9x 126x 2x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x 2x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 2x 284x 284x 284x 2x 270x 123x 219x 270x 270x 270x 2x 270x 270x 270x 270x 270x 270x 270x 3x 3x 3x 3x 3x 3x 3x 270x 1x 1x 270x 391x 391x 391x 391x 270x 22x 22x 22x 270x 1122x 1122x 270x 2x 391x 391x 391x 391x 391x 391x 391x 160x 160x 22x 22x 22x 160x 160x 160x 391x 1329x 18x 18x 18x 1329x 1263x 1263x 1263x 1263x 1263x 1263x 1263x 48x 48x 48x 48x 2x 2x 48x 48x 48x 391x 5x 5x 4x 391x 391x 391x 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 5x 5x 5x 5x 5x 1x 1x 18x 18x 18x 2x 1122x 1122x 1122x 1122x 1122x 1122x 487x 487x 487x 1122x 3790x 3790x 3790x 119x 119x 119x 119x 119x 119x 119x 3790x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 3623x 3790x 3790x 3790x 1122x 1122x 2x 8x 8x 2x 24x 24x 24x 24x 24x 2x 21x 21x 21x 21x 21x 10x 10x 21x 1x 1x 21x 21x 21x 1x 1x 21x 2x 2x 21x 4x 4x 21x 3x 1x 1x 1x 3x 21x 21x 14x 14x 14x 14x 14x 14x 14x 21x 12x 12x 12x 14x 21x 2x 2719x 2719x 2719x 1292x 1292x 2x 2x 25x 25x 4x 4x 4x 4x 4x 21x 25x 25x 25x 25x 17x 26x 23x 26x 13x 26x 1x 26x 1x 26x 1x 26x 5x 26x 2x 26x 26x 17x 2x 26x 26x 3x 3x 3x 3x 1x 1x 3x 26x 3x 3x 3x 20x 20x 20x 30x 30x 30x | /**
* A sortable, filterable, virtualised table.
*
* Shared by the genomes table (§5.1) and the contigs table (§9). Virtualisation
* is not a nicety: the reference file has 4,395 genomes and 154,468 contigs, and
* 154 k rows of DOM is several seconds of layout before anything appears.
* Only the rows in view (plus a small overscan) exist as elements; the rest is
* a spacer of the right height.
*
* The filter grammar deliberately follows the shape of `metacooler`'s own
* `--filter`: one comparison per box, ANDed across boxes, and **a missing value
* never matches** — including under a negated comparison — because a filter
* selects rows it can positively vouch for.
*/
import { icon } from './icons'
import { clear, debounce, el } from './dom'
export type ColumnKind = 'string' | 'number'
/**
* A column whose cells are tick boxes rather than text.
*
* The leading `selectable` column is *the* selection — which rows the view is
* about — and there is only ever one of it. This is a different thing: a
* **declaration written against a row**, of which a table may carry several and
* none of which is what the ticked set means. §8.15's *this sequence is
* circular* is the first, and it is why the two are not one mechanism: a reader
* who ticks four chromosomes to draw them and declares one of them circular has
* said two unrelated things about the same rows.
*
* The column keeps a `value` like any other, so it sorts and filters and the
* search box reaches it — a hundred thousand contigs with three circular ones in
* them is exactly the table where *show me the ticked ones* has to be typeable.
*/
export interface ColumnToggle {
/** Whether this row's box is ticked, asked at every paint. */
checked(row: number): boolean
/** The reader ticked or unticked it. */
onToggle(row: number, on: boolean): void
/** The box's own tooltip, which names the row it is about. */
title?(row: number): string
}
/**
* A column whose cells are boxes the reader types into.
*
* The same kind of thing as a {@link ColumnToggle} — a declaration written
* against a row and kept outside the table — for a declaration that is a value
* rather than a yes or a no. §8.15's replication origin is the first: a number
* the Origin and terminus task writes and a reader corrects. The box shows what
* is declared, and, greyed while it is empty, what stands in for it. The
* column's `value` is still what it sorts and filters on.
*/
export interface ColumnEdit {
/** What the box holds for a row, asked at every paint; `''` for nothing declared. */
text(row: number): string
/** What stands in, greyed, while the box is empty. */
placeholder?(row: number): string
/**
* The reader committed — Enter, or leaving the box — and `''` is clearing it.
*
* @returns `null` where the text was taken, else why not: the box goes back
* to what it held and says so on its tooltip, rather than keeping a value
* that is not the one in force.
*/
commit(row: number, text: string): string | null
/** The box's own tooltip, which names the row it is about. */
title?(row: number): string
}
export interface ColumnDef {
/** Stable key; also the filter box's identity. */
key: string
label: string
kind: ColumnKind
/** Cell value for a source row index. `undefined` means missing. */
value(row: number): string | number | undefined
/** Display string; defaults to a formatted `value`. */
format?(value: string | number | undefined, row: number): string
/** Header tooltip — where the density column's "not a contact count" lives. */
title?: string
/**
* This column came in **with** the file rather than out of the format, and the
* table says so where it starts.
*
* A CheckM table joined into a metacool brings a `Length` of its own, so the
* header read `name length contigs bins Length GC-content …`: two columns of
* identical numbers, told apart by a capital letter. §5.1 forbids dropping the
* joined one and {@link GenomesTable}'s labels answer half of it in a tooltip
* — this is the other half, and it is the same mark the record card draws as
* *joined in with the file*: a rule down the side of the first of them, so the
* two halves of the header are visibly two halves.
*/
joined?: boolean
/** CSS grid track for this column. */
width?: string
align?: 'left' | 'right'
/** Draw this column's cells as tick boxes; see {@link ColumnToggle}. */
toggle?: ColumnToggle
/** Draw this column's cells as boxes to type into; see {@link ColumnEdit}. */
edit?: ColumnEdit
}
export interface VirtualTableOptions {
columns: ColumnDef[]
/** Source row indices, in the order the file wrote them. */
rows: number[]
rowHeight?: number
/** Activating a row (click or Enter). */
onOpen(row: number): void
/** Called whenever the checked set changes. */
onSelect?(rows: number[]): void
/**
* Show the leading checkbox column, and let any number of rows be ticked.
*
* It used to be `maxSelection: 2`, because the only thing a selection could
* do was open the pair view and a third tick had to drop the oldest. A
* selection is now a picture of however many rows are in it, so the cap has
* no meaning and its silent eviction would be a bug.
*/
selectable?: boolean
/** Columns the free-text box searches; defaults to every string column. */
searchKeys?: string[]
searchPlaceholder?: string
emptyMessage?: string
/**
* Save and restore the filter/sort/search state across navigation.
*
* The table calls `save` whenever the state changes and reads `initial` once
* at construction. It lives outside the table because *where* to keep it (per
* file, per scope) is the caller's question — see `state/UiMemory`.
*/
persistence?: {
initial: TableUiState | null
save(state: TableUiState): void
}
}
/** The user-typed table state that survives leaving the view and coming back. */
export interface TableUiState {
filters: Record<string, string>
search: string
sortKey: string | null
sortDir: 1 | -1
}
type Predicate = (row: number) => boolean
/**
* What a {@link ColumnToggle}'s filter stores when it is on.
*
* A sentinel rather than a boolean beside the map, because the filter state is
* what {@link TableUiState} persists and restoring a session written by an older
* build must not turn a text expression into a tick. Nothing a reader can type
* spells it.
*/
const TOGGLE_ONLY = ' only'
const OVERSCAN = 6
/**
* One collator for every string comparison in every table.
*
* `String.prototype.localeCompare` constructs a collator per call. Hoisting it
* is the single largest win in the sort, and `numeric: true` also gives
* `NODE_2` before `NODE_10`, which is what a reader of contig names expects.
*/
const COLLATOR = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
export class VirtualTable {
readonly el: HTMLElement
private readonly options: Required<Pick<VirtualTableOptions, 'rowHeight'>> & VirtualTableOptions
private readonly filters = new Map<string, string>()
private readonly selected = new Set<number>()
private readonly pool: HTMLElement[] = []
/** Source row indices, in the order the file wrote them. Fixed at construction. */
private readonly source: number[]
private visible: number[] = []
/** Memoised sort order; see {@link sorted}. */
private sortCache: { key: string; dir: 1 | -1; order: number[] } | null = null
/**
* Position of {@link active} within {@link visible}.
*
* Kept rather than searched for: `visible.indexOf(active)` is 154,468
* comparisons per keypress on the reference file, at the key-repeat rate.
*/
private activePosition = -1
private persistTimer: ReturnType<typeof setTimeout> | undefined
private readonly onResize: () => void
/** Cached sticky-header height; a geometry read per keypress otherwise. */
private headHeightCache = -1
/** Lowercased search haystacks, per column key; see {@link lowercased}. */
private readonly searchCache = new Map<string, Map<number, string>>()
private sortKey: string | null = null
private sortDir: 1 | -1 = 1
private search = ''
private active = -1
private readonly viewport: HTMLElement
/** Intrinsic-width wrapper inside the scroller; keeps header and rows aligned. */
private readonly grid: HTMLElement
/** Sticky header block, whose height offsets every row coordinate. */
private readonly head: HTMLElement
private readonly body: HTMLElement
private readonly header: HTMLElement
private readonly filterRow: HTMLElement
private readonly status: HTMLElement
private readonly toolbar: HTMLElement
/** The filter field, so `/` can reach it — see {@link focusSearch}. */
private readonly searchBox: HTMLInputElement
/** `clear filters`, held so {@link recompute} can grey it when there are none. */
private readonly reset: HTMLButtonElement
/**
* The box in the filter row's gutter: tick, or untick, everything showing.
*
* Built unconditionally and mounted only when the table is selectable, so
* {@link syncHeadCheck} has one thing to write to rather than a lookup that
* may find nothing.
*/
private readonly headCheck = el('input', {
class: 'checkbox tf-check-box',
type: 'checkbox',
})
constructor(options: VirtualTableOptions) {
this.options = { rowHeight: 28, ...options }
this.source = options.rows
// Restored state is untrusted: it may have been written by an older build
// against a file whose columns have since changed, so every field is
// validated rather than assigned.
const saved = options.persistence?.initial ?? null
if (saved !== null) {
const known = new Set(options.columns.map((column) => column.key))
for (const [key, value] of Object.entries(saved.filters ?? {})) {
if (known.has(key) && typeof value === 'string' && value !== '') this.filters.set(key, value)
}
if (typeof saved.search === 'string') this.search = saved.search.trim().toLowerCase()
if (typeof saved.sortKey === 'string' && known.has(saved.sortKey)) {
this.sortKey = saved.sortKey
this.sortDir = saved.sortDir === -1 ? -1 : 1
}
}
const template = this.gridTemplate()
this.status = el('span', { class: 'table-status' })
const searchBox = el('input', {
class: 'search',
type: 'search',
// `filter`, not `search`: this box narrows the rows under it as it is
// typed in, and `search` is the word the command palette and a store's
// full-text box use for the other thing (§26.4).
placeholder: options.searchPlaceholder ?? 'filter names…',
})
this.searchBox = searchBox
searchBox.value = this.search
searchBox.addEventListener(
'input',
debounce(() => {
this.search = searchBox.value.trim().toLowerCase()
this.recompute()
}, 120),
)
const reset = el('button', { class: 'btn btn-quiet', text: 'clear filters', type: 'button' })
// Greyed with nothing to clear, exactly as `clear selection` beside it is
// with nothing ticked. It used to stay live, so two quiet buttons sharing a
// verb followed two different rules and a reader looked for the filter the
// live one was offering to clear.
this.reset = reset
reset.addEventListener('click', () => {
this.filters.clear()
this.search = ''
searchBox.value = ''
// `.tf-input` rather than every input in the row: the row also holds the
// select-everything-showing box, and blanking that would be clearing a
// *selection* from a button that says it clears filters.
for (const input of this.filterRow.querySelectorAll('.tf-input')) {
if (!(input instanceof HTMLInputElement)) continue
input.value = ''
input.classList.remove('active')
}
this.recompute()
})
this.toolbar = el('div', { class: 'table-toolbar' }, searchBox, this.status, reset)
this.headCheck.title =
'Tick every row the filters are showing, or untick them if they all are. ' +
'Rows a filter is hiding are left alone.'
this.headCheck.addEventListener('click', (event) => {
// The header is inside the scroller and the filter row sits over the
// columns; a press here is about the selection and nothing else.
event.stopPropagation()
this.toggleVisible()
})
this.header = el('div', { class: 'thead-row', style: { gridTemplateColumns: template } })
this.filterRow = el('div', { class: 'tfilter-row', style: { gridTemplateColumns: template } })
this.buildHeader()
this.paintSortArrows()
this.body = el('div', { class: 'tbody' })
this.head = el('div', { class: 'thead' }, this.header, this.filterRow)
// The header lives *inside* the scroller, sticky to its top.
//
// With the header outside it, a horizontal scroll moved the rows and left
// the headings behind, so the columns you scrolled to see were unlabelled —
// which is the one moment you need the labels. One scroll container makes
// horizontal movement shared and vertical stickiness automatic; `.tgrid`
// carries the intrinsic width so both stay aligned when the columns
// overflow.
this.grid = el(
'div',
{ class: 'tgrid' },
this.head,
this.body,
)
this.viewport = el(
'div',
{ class: 'tviewport', attrs: { tabindex: '0', role: 'grid' } },
this.grid,
)
this.viewport.addEventListener('scroll', () => this.paint())
// The header can re-wrap at a different width, which is the one thing that
// changes its height without going through `recompute`.
this.onResize = () => {
this.headHeightCache = -1
}
window.addEventListener?.('resize', this.onResize)
this.viewport.addEventListener('keydown', (event) => this.onKeyDown(event))
this.el = el('div', { class: 'table' }, this.toolbar, this.viewport)
this.recompute()
// The viewport has no height until it is in the document; repaint once the
// browser has laid it out so the first screen is not blank.
requestAnimationFrame(() => this.paint())
}
/**
* Release the resize listener and write out any pending filter state.
*
* The flush is the point: {@link persistLater} coalesces a burst of typing
* into one `sessionStorage` write, and a user who types a filter and
* immediately clicks a row would otherwise leave before it landed and come
* back to an unfiltered table.
*/
destroy(): void {
window.removeEventListener?.('resize', this.onResize)
if (this.persistTimer !== undefined) {
clearTimeout(this.persistTimer)
this.persistTimer = undefined
this.persist()
}
}
/**
* Put the caret in the filter field — the `/` key.
*
* A table's box is a filter rather than a place to type a coordinate, but it
* is the same gesture and the same question: *where is the thing I am after*.
* One key for both is what makes it worth having.
*/
focusSearch(): void {
this.searchBox.focus()
this.searchBox.select()
}
/** Extra controls placed in the toolbar by the owning view. */
addToolbarItem(node: HTMLElement): void {
this.toolbar.appendChild(node)
}
get selection(): number[] {
return [...this.selected]
}
clearSelection(): void {
this.selected.clear()
this.options.onSelect?.([])
this.paint()
}
/**
* Tick or untick everything the reader can currently see — the filtered,
* searched set, and never the whole file.
*
* That is what makes the control worth having: filter to completeness above
* 90, then take all of them. Rows a filter is hiding are left exactly as they
* were, in both directions, because the box sits in the header of the column
* it applies to and what that column is showing is what it can honestly speak
* for. Emptying the selection outright is a different question and has its own
* button beside the table.
*
* The direction is decided by what is on screen, which is the behaviour every
* header checkbox has: all of them ticked means the press unticks, anything
* less means it ticks the rest.
*/
toggleVisible(): void {
const all = this.allVisibleSelected()
for (const row of this.visible) {
if (all) this.selected.delete(row)
else this.selected.add(row)
}
this.options.onSelect?.([...this.selected])
this.paint()
}
/** `true` when every visible row is ticked — and there is one to tick. */
private allVisibleSelected(): boolean {
return this.visible.length > 0 && this.visible.every((row) => this.selected.has(row))
}
private gridTemplate(): string {
const tracks = this.options.columns.map((column) => column.width ?? 'minmax(6rem, 1fr)')
if (this.options.selectable === true) tracks.unshift('2rem')
return tracks.join(' ')
}
private buildHeader(): void {
if (this.options.selectable === true) {
this.header.appendChild(el('div', { class: 'th th-check', text: '' }))
// In the **filter** row, not the label row, and that is where it belongs:
// it selects what the filters left, so it sits on the line the filters are
// on, in the gutter directly above the boxes it ticks. In the label row it
// would have read as a heading for the column of checkboxes — a thing to
// sort by — which is what a box in a `<th>` looks like.
this.filterRow.appendChild(el('div', { class: 'tf tf-check' }, this.headCheck))
}
for (const column of this.options.columns) {
const label = el('span', { text: column.label })
const arrow = el('span', { class: 'sort-arrow', text: '' })
const cell = el(
'div',
{
class: `th${column.align === 'right' ? ' num' : ''}${column.joined === true ? ' is-joined' : ''}`,
title: column.title ?? column.label,
attrs: { role: 'columnheader' },
},
label,
arrow,
)
cell.addEventListener('click', () => this.toggleSort(column.key))
this.header.appendChild(cell)
// A toggle column filters by *being ticked*, so its filter is not a text
// expression: `contains` in a column two rem wide is a control nobody can
// type in, and the only question anybody asks of a column of ticks is
// "show me the ticked ones".
//
// **A named toggle rather than a second bare checkbox**, and that is the
// correction. It was a box of exactly the class and size of the one in the
// gutter at the other end of the same row — and that one *ticks every row
// showing*, so on the Chromosomes table two identical glyphs on one line
// meant two different verbs, told apart only by hovering. A reader who
// ticked the right-hand one expecting to declare all sixteen chromosomes
// circular emptied the table instead. Lit when it is narrowing, like every
// other toggle in the application (§26.3), so the row it filters is
// visibly a filter and the gutter keeps the only checkbox on the line.
if (column.toggle !== undefined) {
const only = el('button', {
class: 'btn btn-quiet btn-toggle tf-only',
type: 'button',
text: 'ticked',
title: `Show only the rows ticked under ${column.label}`,
attrs: { 'aria-pressed': 'false' },
}) as HTMLButtonElement
const sync = (on: boolean): void => {
only.setAttribute('aria-pressed', on ? 'true' : 'false')
}
sync(this.filters.get(column.key) === TOGGLE_ONLY)
only.addEventListener('click', () => {
const on = only.getAttribute('aria-pressed') !== 'true'
sync(on)
if (on) this.filters.set(column.key, TOGGLE_ONLY)
else this.filters.delete(column.key)
this.recompute()
})
this.filterRow.appendChild(el('div', { class: 'tf tf-only-cell' }, only))
continue
}
const input = el('input', {
class: 'tf-input',
type: 'text',
// What the box *does*, in both columns. It said `contains` under a text
// column and `>0` under a numeric one — one box naming an operation and
// the next showing an expression to type, and `>0` under a completeness
// score, where every value already is, reads as a filter that has been
// applied. The grammar stays in the tooltip, which is where a grammar
// belongs.
placeholder: column.kind === 'number' ? 'compare' : 'contains',
title:
column.kind === 'number'
? 'Numeric filter: >x, >=x, <x, <=x, =x, !=x, or a..b. Missing values never match.'
: 'Text filter: substring, /regex/, or !substring. Missing values never match.',
})
const restored = this.filters.get(column.key)
if (restored !== undefined) {
input.value = restored
input.classList.add('active')
}
input.addEventListener(
'input',
debounce(() => {
const value = input.value.trim()
if (value === '') this.filters.delete(column.key)
else this.filters.set(column.key, value)
input.classList.toggle('active', value !== '')
this.recompute()
}, 150),
)
this.filterRow.appendChild(el('div', { class: 'tf' }, input))
}
}
private toggleSort(key: string): void {
if (this.sortKey === key) {
if (this.sortDir === 1) this.sortDir = -1
else {
this.sortKey = null
this.sortDir = 1
}
} else {
this.sortKey = key
this.sortDir = 1
}
this.paintSortArrows()
this.recompute()
}
/** Reflect `sortKey`/`sortDir` in the header, including a restored sort. */
private paintSortArrows(): void {
for (const [index, cell] of [...this.header.querySelectorAll('.th')].entries()) {
const offset = this.options.selectable === true ? 1 : 0
const column = this.options.columns[index - offset]
const arrow = cell.querySelector('.sort-arrow')
if (arrow === null || column === undefined) continue
if (this.sortKey !== column.key) arrow.replaceChildren()
else arrow.replaceChildren(icon(this.sortDir === 1 ? 'chevron-up' : 'chevron-down', { size: 13 }))
}
}
/** Queue a {@link persist}, coalescing a burst of typing into one write. */
private persistLater(): void {
if (this.persistTimer !== undefined) clearTimeout(this.persistTimer)
this.persistTimer = setTimeout(() => {
this.persistTimer = undefined
this.persist()
}, 500)
}
/** Hand the user-typed state to the caller's store, if there is one. */
private persist(): void {
this.options.persistence?.save({
filters: Object.fromEntries(this.filters),
search: this.search,
sortKey: this.sortKey,
sortDir: this.sortDir,
})
}
private predicates(): Predicate[] {
const list: Predicate[] = []
for (const column of this.options.columns) {
const expression = this.filters.get(column.key)
if (expression === undefined) continue
const toggle = column.toggle
if (toggle !== undefined) {
if (expression === TOGGLE_ONLY) list.push((row) => toggle.checked(row))
continue
}
const test = column.kind === 'number' ? numberFilter(expression) : stringFilter(expression)
if (test === null) continue
list.push((row) => test(column.value(row)))
}
if (this.search !== '') {
const keys = this.options.searchKeys ?? this.options.columns.filter((c) => c.kind === 'string').map((c) => c.key)
const columns = this.options.columns.filter((column) => keys.includes(column.key))
const needle = this.search
// Lowercased once per column, not once per row per keystroke: 154,468
// fresh strings per recompute, at up to eight recomputes a second while
// typing, is ~31 MB/s of garbage for a comparison that never changes.
const haystacks = columns.map((column) => this.lowercased(column))
list.push((row) => haystacks.some((byRow) => byRow.get(row)?.includes(needle) === true))
}
return list
}
/**
* The source rows in sort order, computed once per (column, direction).
*
* Two things were wrong with sorting inside `recompute`. It ran on **every
* debounced keystroke** — typing an eight-character prefix with a name sort
* active re-sorted eight times — and it sorted through the comparator, which
* called `column.value(row)` twice per comparison and `localeCompare` once.
* For 154,468 contigs that is ~2.7 M comparisons: 5.3 M closure calls and
* 2.7 M collations, on the main thread, per keystroke.
*
* Decorate-sort-undecorate fixes the first half: the keys are extracted once,
* `n` calls instead of `2n log n`. A single shared `Intl.Collator` fixes the
* second — `String.prototype.localeCompare` builds a collator per call, which
* is where most of the time went. And caching the result by sort key fixes the
* third, so filtering is a stable pass over an order that already exists.
*/
private sorted(): number[] {
const key = this.sortKey
if (key === null) return this.source
if (this.sortCache !== null && this.sortCache.key === key && this.sortCache.dir === this.sortDir) {
return this.sortCache.order
}
const column = this.options.columns.find((c) => c.key === key)
if (column === undefined) return this.source
const dir = this.sortDir
const numeric = column.kind === 'number'
const n = this.source.length
// One pass for the values, so `value()` is called once per row.
const values: Array<string | number | undefined> = new Array<string | number | undefined>(n)
const missing = new Uint8Array(n)
for (let i = 0; i < n; i++) {
const v = column.value(this.source[i])
values[i] = v
// Missing sorts last regardless of direction: a blank taxonomy is not
// "smaller" than a filled one, it is absent.
missing[i] = v === undefined || (numeric && Number.isNaN(v as number)) ? 1 : 0
}
const order = Array.from({ length: n }, (_, i) => i)
order.sort((a, b) => {
if (missing[a] !== 0 || missing[b] !== 0) {
return missing[a] !== 0 && missing[b] !== 0 ? 0 : missing[a] !== 0 ? 1 : -1
}
if (numeric) return ((values[a] as number) - (values[b] as number)) * dir
return COLLATOR.compare(String(values[a]), String(values[b])) * dir
})
const rows = order.map((i) => this.source[i])
this.sortCache = { key, dir, order: rows }
return rows
}
/** A column's values, lowercased, built once per column and kept. */
private lowercased(column: ColumnDef): Map<number, string> {
let cached = this.searchCache.get(column.key)
if (cached === undefined) {
cached = new Map<number, string>()
for (const row of this.source) {
const value = column.value(row)
if (value !== undefined) cached.set(row, String(value).toLowerCase())
}
this.searchCache.set(column.key, cached)
}
return cached
}
private recompute(): void {
const tests = this.predicates()
// Filtering a sorted array preserves its order, so the sort happens once
// per column click rather than once per keystroke.
this.headHeightCache = -1
const ordered = this.sorted()
this.visible = tests.length === 0 ? [...ordered] : ordered.filter((row) => tests.every((t) => t(row)))
const total = this.source.length
const shown = this.visible.length
this.status.textContent = shown === total ? `${total.toLocaleString()} rows` : `${shown.toLocaleString()} of ${total.toLocaleString()} rows`
// Here rather than at each place a filter changes, so a set restored from
// persistence arrives with the button already live.
this.reset.disabled = this.filters.size === 0 && this.search === ''
// Debounced separately and more slowly than the filter it follows:
// `JSON.stringify` plus a synchronous `sessionStorage.setItem` is not
// something to do eight times a second while someone types, and nothing
// reads it until the view is left.
this.persistLater()
// The body reserves the full height of the virtual row set; only the rows
// in view exist as elements.
this.body.style.height = `${this.visible.length * this.options.rowHeight}px`
this.viewport.scrollTop = 0
// The active row's *position* is meaningless in a different visible set —
// and so is the row itself once a filter has taken it away. Keeping it would
// leave Enter opening, and the space bar ticking, a row that is no longer on
// screen: a keypress aimed at the list the reader can see, answered with one
// they cannot.
this.activePosition = this.active < 0 ? -1 : this.visible.indexOf(this.active)
if (this.activePosition < 0) this.active = -1
this.paint()
}
/**
* Height of the sticky header, cached.
*
* Constant while the user scrolls and keys around, and re-read only when the
* filter row could have changed shape — so a keypress does not force a layout.
*/
private headHeight(): number {
if (this.headHeightCache < 0) this.headHeightCache = this.head.offsetHeight
return this.headHeightCache
}
/**
* The header box against what is on screen: ticked, part-ticked, or empty.
*
* `indeterminate` for a partial selection, because "some of these" is a third
* state and drawing it as either of the other two is a lie a reader acts on —
* an empty box over four ticked rows reads as "nothing is selected".
*/
private syncHeadCheck(): void {
if (this.options.selectable !== true) return
const all = this.allVisibleSelected()
const some = !all && this.visible.some((row) => this.selected.has(row))
this.headCheck.checked = all
this.headCheck.indeterminate = some
}
private paint(): void {
this.syncHeadCheck()
const { rowHeight } = this.options
const height = this.viewport.clientHeight || 400
// The sticky header scrolls with the content, so it occupies the first
// `head.offsetHeight` pixels of `scrollTop`; row 0 begins after it.
const scrolled = Math.max(0, this.viewport.scrollTop - this.headHeight())
const first = Math.max(0, Math.floor(scrolled / rowHeight) - OVERSCAN)
const count = Math.min(this.visible.length - first, Math.ceil(height / rowHeight) + 2 * OVERSCAN)
if (this.visible.length === 0) {
clear(this.body)
this.pool.length = 0
this.body.appendChild(
el('div', { class: 'tempty', text: this.options.emptyMessage ?? 'No rows match these filters.' }),
)
return
}
if (this.body.firstChild instanceof HTMLElement && this.body.firstChild.classList.contains('tempty')) {
clear(this.body)
}
while (this.pool.length < count) {
const row = this.buildRow()
this.pool.push(row)
this.body.appendChild(row)
}
while (this.pool.length > count) {
const row = this.pool.pop()
row?.remove()
}
for (let i = 0; i < count; i++) {
this.fillRow(this.pool[i], this.visible[first + i], (first + i) * rowHeight)
}
}
private buildRow(): HTMLElement {
const template = this.gridTemplate()
const row = el('div', {
class: 'tr',
style: { gridTemplateColumns: template, height: `${this.options.rowHeight}px` },
attrs: { role: 'row' },
})
if (this.options.selectable === true) {
const check = el('input', { class: 'tcheck', type: 'checkbox' })
check.addEventListener('click', (event) => {
event.stopPropagation()
const index = Number(row.dataset.row)
this.toggleSelection(index)
})
row.appendChild(el('div', { class: 'td td-check' }, check))
}
for (const column of this.options.columns) {
if (column.edit !== undefined) {
row.appendChild(this.editCell(row, column.edit))
continue
}
if (column.toggle === undefined) {
row.appendChild(
el('div', {
class: `td${column.align === 'right' ? ' num' : ''}${column.joined === true ? ' is-joined' : ''}`,
}),
)
continue
}
// A box rather than a word, and its own `click` stopped before the row's:
// the row opens the sequence, and a reader declaring one circular is not
// asking to be taken there.
const box = el('input', { class: 'tcheck', type: 'checkbox' })
const toggle = column.toggle
box.addEventListener('click', (event) => event.stopPropagation())
box.addEventListener('change', () => {
const index = Number(row.dataset.row)
if (Number.isFinite(index)) toggle.onToggle(index, box.checked)
})
row.appendChild(el('div', { class: 'td td-check' }, box))
}
row.addEventListener('click', (event) => {
const index = Number(row.dataset.row)
if (event.ctrlKey || event.metaKey) this.toggleSelection(index)
else this.options.onOpen(index)
})
return row
}
/**
* A box to type a row's value into.
*
* Its clicks and its keys are stopped before the row's: a click into the box
* is not a request to open the sequence, and a key typed in it is neither the
* table's arrow navigation nor any of the application's one-key commands.
* Enter commits, Escape puts back what the box held, and leaving it commits.
*/
private editCell(row: HTMLElement, edit: ColumnEdit): HTMLElement {
const box = el('input', {
class: 'input tedit',
type: 'text',
attrs: { spellcheck: 'false', autocomplete: 'off', inputmode: 'numeric' },
})
const index = (): number => Number(row.dataset.row)
box.addEventListener('click', (event) => event.stopPropagation())
box.addEventListener('keydown', (event) => {
event.stopPropagation()
if (event.key === 'Enter') box.blur()
if (event.key === 'Escape') {
const at = index()
if (Number.isFinite(at)) box.value = edit.text(at)
box.blur()
}
})
box.addEventListener('change', () => {
const at = index()
if (!Number.isFinite(at)) return
const refused = edit.commit(at, box.value.trim())
box.classList.toggle('is-refused', refused !== null)
if (refused === null) return
box.value = edit.text(at)
box.title = refused
})
return el('div', { class: 'td td-edit' }, box)
}
private fillRow(node: HTMLElement, row: number, top: number): void {
node.dataset.row = String(row)
node.style.transform = `translateY(${top}px)`
node.classList.toggle('selected', this.selected.has(row))
node.classList.toggle('active', this.active === row)
const offset = this.options.selectable === true ? 1 : 0
if (offset === 1) {
const check = node.children[0]?.firstChild
if (check instanceof HTMLInputElement) check.checked = this.selected.has(row)
}
this.options.columns.forEach((column, index) => {
const cell = node.children[index + offset]
if (!(cell instanceof HTMLElement)) return
if (column.toggle !== undefined) {
const box = cell.firstChild
if (box instanceof HTMLInputElement) {
box.checked = column.toggle.checked(row)
box.title = column.toggle.title?.(row) ?? column.label
}
return
}
if (column.edit !== undefined) {
const box = cell.firstChild
if (box instanceof HTMLInputElement) {
box.placeholder = column.edit.placeholder?.(row) ?? ''
box.setAttribute('aria-label', column.edit.title?.(row) ?? column.label)
// Not while the reader is typing in it: a repaint — a scroll, another
// row's change — would put back what they are halfway through replacing.
if (document.activeElement !== box) {
box.value = column.edit.text(row)
box.title = column.edit.title?.(row) ?? column.label
box.classList.remove('is-refused')
}
}
return
}
const value = column.value(row)
const text = column.format ? column.format(value, row) : defaultFormat(value)
cell.textContent = text
cell.title = text
})
}
/**
* Redraw the rows in view, for a {@link ColumnToggle} something else changed.
*
* The declaration behind a toggle column lives outside this table — it is the
* session's, and the same fact is drawn in two other places — so a tick set
* from elsewhere has to reach the boxes somehow. Only the rows that exist are
* touched; the rest are built from the same `checked` when they scroll in.
*/
repaint(): void {
this.paint()
}
private toggleSelection(row: number): void {
if (this.selected.has(row)) this.selected.delete(row)
else this.selected.add(row)
this.options.onSelect?.([...this.selected])
this.paint()
}
private onKeyDown(event: KeyboardEvent): void {
if (this.visible.length === 0) return
// `activePosition` rather than `visible.indexOf(this.active)`: the linear
// scan was 154,468 comparisons per keypress at reference scale, repeated at
// the key-repeat rate.
const position = this.activePosition
let next = position
switch (event.key) {
case 'ArrowDown':
next = position + 1
break
case 'ArrowUp':
next = position - 1
break
case 'PageDown':
next = position + 10
break
case 'PageUp':
next = position - 10
break
case 'Home':
next = 0
break
case 'End':
next = this.visible.length - 1
break
case 'Enter':
if (this.active >= 0) this.options.onOpen(this.active)
return
case ' ':
if (this.active >= 0 && this.options.selectable === true) {
event.preventDefault()
this.toggleSelection(this.active)
}
return
default:
return
}
event.preventDefault()
next = Math.min(Math.max(next, 0), this.visible.length - 1)
this.activePosition = next
this.active = this.visible[next]
// Row coordinates are relative to the body, which starts below the sticky
// header; scroll positions are relative to the scroller. Hence the offset,
// and hence keeping the row clear of the header rather than under it.
const headHeight = this.headHeight()
const top = next * this.options.rowHeight + headHeight
const bottom = top + this.options.rowHeight
if (top - headHeight < this.viewport.scrollTop) this.viewport.scrollTop = top - headHeight
else if (bottom > this.viewport.scrollTop + this.viewport.clientHeight) {
this.viewport.scrollTop = bottom - this.viewport.clientHeight
}
this.paint()
}
}
function defaultFormat(value: string | number | undefined): string {
if (value === undefined) return ''
if (typeof value === 'number') return Number.isFinite(value) ? value.toLocaleString() : ''
return value
}
/**
* A number as this box accepts one: digits, a decimal point, and an exponent
* whose sign may be either.
*
* The sign of the exponent is the whole reason this is written out rather than
* left as a character class. It used to be `-?[\d.eE+]+`, which has no `-` in
* it past the first character — so `1e-5` did not parse, `>1e-5` compiled to
* `null`, and the column came back *unfiltered* rather than reporting anything.
* A density is the column a reader most often filters, and a density is written
* in exactly that form.
*/
const NUMBER = String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?`
/**
* Compile a numeric filter box. Returns `null` for an expression that does not
* parse, which leaves the column unfiltered rather than emptying the table
* while the user is still typing `>`.
*/
export function numberFilter(expression: string): ((value: string | number | undefined) => boolean) | null {
const range = new RegExp(`^(${NUMBER})\\.\\.(${NUMBER})$`).exec(expression)
if (range !== null) {
const lo = Number(range[1])
const hi = Number(range[2])
if (Number.isNaN(lo) || Number.isNaN(hi)) return null
return (value) => isNumber(value) && value >= lo && value <= hi
}
const comparison = new RegExp(`^(>=|<=|!=|>|<|=)?\\s*(${NUMBER})$`).exec(expression)
if (comparison === null) return null
const operator = comparison[1] ?? '='
const bound = Number(comparison[2])
if (Number.isNaN(bound)) return null
return (value) => {
if (!isNumber(value)) return false
switch (operator) {
case '>':
return value > bound
case '>=':
return value >= bound
case '<':
return value < bound
case '<=':
return value <= bound
case '!=':
return value !== bound
default:
return value === bound
}
}
}
/** Compile a text filter box: `/regex/`, `!substring`, or a plain substring. */
export function stringFilter(expression: string): ((value: string | number | undefined) => boolean) | null {
const regex = /^\/(.*)\/([a-z]*)$/.exec(expression)
if (regex !== null) {
try {
const compiled = new RegExp(regex[1], regex[2].includes('i') ? regex[2] : `${regex[2]}i`)
return (value) => value !== undefined && compiled.test(String(value))
} catch {
return null
}
}
if (expression.startsWith('!')) {
const needle = expression.slice(1).toLowerCase()
// Missing still fails: a filter selects rows it can vouch for, even negated.
return (value) => value !== undefined && !String(value).toLowerCase().includes(needle)
}
const needle = expression.toLowerCase()
return (value) => value !== undefined && String(value).toLowerCase().includes(needle)
}
function isNumber(value: string | number | undefined): value is number {
return typeof value === 'number' && !Number.isNaN(value)
}
|