diff --git a/app/globals.css b/app/globals.css index ed8e9b48..7d16ac8e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -104,7 +104,9 @@ /* a form control's edge (checkbox, radio, text field, select): dark enough that an unchecked box reads as one rather than as disabled; --line is for dividers */ --control-line: light-dark(#9aa7b0, #4f5f69); - --line: light-dark(#dde4e8, #2a353c); --code-bg: light-dark(#f1f5f7, #1a242a); --mark: light-dark(#b25e09, #e0a35c); --mark-soft: light-dark(#fbf0e2, #35270f); + --line: light-dark(#dde4e8, #2a353c); --code-bg: light-dark(#f1f5f7, #1a242a); + /* a table's alternate rows, as the portal's study-view tables (#f9f9f9 every other row) */ + --row-stripe: light-dark(#f9f9f9, #1b2329); --mark: light-dark(#b25e09, #e0a35c); --mark-soft: light-dark(#fbf0e2, #35270f); --ok: light-dark(#2e7d32, #7bc47f); --ok-soft: light-dark(#e6f2e6, #17301a); --err: light-dark(#b3261e, #f2b8b5); --err-soft: light-dark(#fbeae9, #3a2323); /* the NEW mark's text (app/lab/new-mark.tsx) */ --new: light-dark(#ea580c, #fb923c); @@ -222,31 +224,51 @@ pre { .note { font-size: var(--t-sm); color: var(--muted); margin-top: 0.5rem; } .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 1.4rem; } @media (max-width: 880px) { .two-col { grid-template-columns: 1fr; } } -/* Explore: one facet (or gene table, or study breakdown) per tile, packed as many to a - row as fit — the portal's own study-view density, instead of a couple of full-width - columns each stacking every facet vertically. `auto-fill` + a fixed min width is what - makes it collapse to one column on a phone without a media query: below ~280px+gap - there is only room for one track. Each tile keeps its own `.card` look; `.vallist` - already caps its own height and scrolls (see its own comment), so no facet makes its row - tall. The tiles in a row share its height, so the grid reads as rows rather than a ragged - edge; the reading order stays left to right. */ -.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 0.8rem; align-items: stretch; } +/* Explore's grid, as the portal's (STS-LY-1, app/lab/explore-grid.tsx): react-grid-layout places + each card in 195 × 170 px cells 5 px apart, the grid centred at its own width. Each card fills its + cells and scrolls within them, so no card sets another's size. The loading placeholders take the + same cells. */ +.svgridbox { width: 100%; display: flex; justify-content: flex-start; } +.svgrid { flex: none; } +.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(188px, 1fr)); grid-auto-rows: 170px; gap: 7px; padding: 7px 0; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } .nosamples p + p { margin-top: 0.6rem; } -.facetgrid > .card { margin-bottom: 0; min-width: 0; } -/* A tile whose body is a scrolling list fills the height its row gives it: the list's flex-basis - of 0 keeps its rows out of the row's height (its min-height is the least it shows), and it - grows into whatever height a taller neighbour sets, so no tile ends in empty space. */ -.facetgrid > .card:has(> .vallist, > .generows, > .sbrows) { display: flex; flex-direction: column; } -.facetgrid > .card > :is(.vallist, .generows, .sbrows) { flex: 1 1 0; max-height: none; } -.facetgrid > .card > .vallist { min-height: var(--vallist-h); } -.facetgrid > .card > :is(.generows, .sbrows) { min-height: 20rem; } -/* Studies and data types are dense multi-column rows (see .sbrow/.dtrow's own - grid-template-columns) that read as cramped at one tile's width. */ -.facetgrid > .card.wide { grid-column: span 2; } -/* Explore's card order is the portal's priorities (cardOrders, lib/study-view-config.ts), set by - app/lab/page.tsx as a style per card rather than by the order the page builds them in */ -@media (max-width: 620px) { .facetgrid > .card.wide { grid-column: span 1; } } +.svcell > .card { height: 100%; margin: 0; min-width: 0; overflow: auto; box-sizing: border-box; padding: 4px 6px; border-radius: var(--r-md, 4px); position: relative; } +/* A card whose body is a scrolling list gives the list the card's height below its title */ +.svcell > .card:has(> .vallist, > .generows, > .sbrows) { display: flex; flex-direction: column; overflow: hidden; } +.svcell > .card > :is(.vallist, .generows, .sbrows) { flex: 1 1 0; min-height: 0; max-height: none; } +/* A card's header, as the portal's (STS-HD-1…3): one line at the card's top, ruled underneath edge to edge. The title is its + name only, bold and centred over the card's whole width, a long one cut with an ellipsis (the whole + of it, and what it counts, in its tooltip). The controls sit on the same line at the top right: the + ☰ menu in the corner, any others (.cardctl) to its left. The title keeps as clear of them on its + left as on its right, so it stays centred. */ +.svcell :is(.facettitle, .xc-title) { + display: block; height: 20px; line-height: 20px; padding: 0 26px; margin: 0; + font-size: var(--t-md); font-weight: 600; color: var(--ink); text-transform: none; letter-spacing: 0; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; min-width: 0; +} +.svcell > .card:has(.cardctl) :is(.facettitle, .xc-title) { padding: 0 50px; } +.svcell .xc-head { display: block; } +/* the header: 28 px and a rule under it, across the card's padding; the buttons (top 4 px, 20 px) sit centred in it */ +.svcell > .card > :is(.facettitle, .xc-head) { + margin: -4px -6px 4px; height: 29px; flex: none; border-bottom: 1px solid var(--line); +} +.svcell > .card > .facettitle { line-height: 28px; padding: 0 26px; } +.svcell > .card:has(.cardctl) > .facettitle { padding: 0 50px; } +.svcell > .card > .xc-head { padding: 4px 6px; } +.svcell > .card[data-shape=pie] > .facettitle { margin: -4px 0 0; } +.svcell > .card .chartgear { position: absolute; top: 4px; right: 4px; width: 20px; height: 20px; min-width: 0; padding: 0; } +.svcell .cardctl { position: absolute; top: 4px; right: 26px; height: 20px; display: flex; align-items: center; gap: 2px; } +.svcell .cardctl :is(.charticon, .titleicon) { width: 20px; height: 20px; min-width: 0; padding: 0; display: inline-flex; align-items: center; justify-content: center; } +.svcell :is(.chartgear, .charticon, .titleicon) svg { width: 14px; height: 14px; } +/* a card's header buttons show while the pointer is over it, a button in it has focus, or its menu is open */ +@media (hover: hover) { + .svcell > .card :is(.chartgear, .cardctl) { opacity: 0; transition: opacity 0.12s; } + .svcell:hover > .card :is(.chartgear, .cardctl), .svcell > .card:focus-within :is(.chartgear, .cardctl), + .svcell > .card .chartgear[aria-expanded=true], .svcell > .card .chartgear[data-state=open] { opacity: 1; } +} +.svcell .titleicon { border: 0; background: none; color: var(--muted); cursor: pointer; } +.svcell .titleicon[aria-pressed=true] { color: var(--accent-ink); } .chk { display: flex; gap: 0.4rem; align-items: center; } .chk input { width: auto; } .qdesc { @@ -300,7 +322,7 @@ pre { .skeleton { background: var(--line); border-radius: var(--r-md); animation: skeleton-pulse 1.3s ease-in-out infinite; } .skeleton-cohort { flex: 1 1 18rem; max-width: 26rem; height: 4.6rem; } .skeleton-counts { display: inline-block; vertical-align: middle; width: 15rem; height: 0.9em; border-radius: var(--r-sm); } -.skeleton-facet { height: 13rem; } +.skeleton-facet { height: 100%; } .skeleton-view { height: 16rem; margin-bottom: 1rem; } /* under a view's toolbar the figure stands where the drawing will be, as far below it as the drawing */ .viewtb + .skeleton-view { margin-top: var(--s3); } @@ -448,9 +470,8 @@ main.analysis-main { max-width: min(132rem, 100%); } /* Explore: per-study breakdown rows */ .sbrow { display: grid; - /* fixed tracks: every row is its own grid, so shared widths must be explicit - or the proportion bars would not be comparable between rows */ - grid-template-columns: calc(0.75rem + 2px) minmax(9rem, 1.6fr) 5.5rem minmax(4rem, 1fr) 3.2rem 5rem; + /* fixed tracks: every row is its own grid, so shared widths must be explicit */ + grid-template-columns: calc(0.75rem + 2px) minmax(9rem, 1.6fr) 5.5rem 3.2rem 5rem; gap: 0 0.6rem; align-items: center; padding: 0.22rem 0; border-top: 1px solid var(--line); font-size: var(--t-md); @@ -458,8 +479,6 @@ main.analysis-main { max-width: min(132rem, 100%); } .sbrows { max-height: 20rem; overflow-y: auto; overscroll-behavior: contain; } .sbrow .mono { font-family: "IBM Plex Mono", monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sbrow .inst { color: var(--accent-ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: var(--t-sm); } -.sbrow .bar { display: block; height: 8px; background: var(--line); border-radius: var(--r-sm); overflow: hidden; } -.sbrow .bar i { display: block; height: 100%; min-width: 2px; background: var(--accent-ink); opacity: 0.8; } .sbrow .pct { text-align: right; font-variant-numeric: tabular-nums; } .sbrow .n { text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; } @@ -500,9 +519,6 @@ main.analysis-main { max-width: min(132rem, 100%); } .generow .cnatag { font-size: var(--t-xs); padding: 0.05rem 0.2rem; border-radius: 3px; text-align: center; } .generow .cnatag.amp { background: #e41a1c22; color: #b3131a; } .generow .cnatag.del { background: #2166ac22; color: #1b4f86; } -/* a data type's bar: the same frame as a clinical value's (.valrow .vbar) */ -.generow .gbar { height: 8px; background: var(--card); border: 1px solid var(--line); border-radius: 2px; overflow: hidden; } -.generow .gbar i { display: block; height: 100%; min-width: 2px; background: var(--accent); } .generow .gcount { text-align: right; font-variant-numeric: tabular-nums; font-size: var(--t-sm); } /* Explore: numeric clinical histograms (cBioPortal study-view bins): a y axis of counts beside @@ -538,30 +554,26 @@ main.analysis-main { max-width: min(132rem, 100%); } flex: 1 1 0; min-width: 10px; text-align: left; white-space: nowrap; overflow: visible; font-size: var(--t-xs); color: var(--muted); font-variant-numeric: tabular-nums; } +/* in a grid card the histogram fills the room under the title: the bars take what the tick row leaves */ +.svcell > .card:has(> .histowrap) { display: flex; flex-direction: column; } +.svcell > .card > .histowrap { --histo-ticks-h: 14px; flex: 1 1 0; min-height: 0; align-items: stretch; } +.svcell .histo-main { display: flex; flex-direction: column; } +.svcell .histo { flex: 1 1 0; min-height: 0; height: auto; } +.svcell .histo-y { height: auto; margin-bottom: var(--histo-ticks-h); } +.svcell .histo-ticks { flex: none; height: var(--histo-ticks-h); } /* Explore: categorical clinical facets as pie charts (portal study-view style) */ -.piewrap { display: flex; gap: 0.6rem; align-items: center; margin-top: 0.3rem; } -.pie { width: 72px; height: 72px; flex: 0 0 72px; } -.pie .slice { cursor: pointer; stroke: var(--card); stroke-width: 1; } -.pie .slice:hover { opacity: 0.82; } -.pie .slice.on { stroke: var(--ink); stroke-width: 2; } -.pielegend { display: flex; flex-wrap: wrap; gap: 0.15rem 0.5rem; flex: 1; min-width: 0; } -.pikey { - display: inline-flex; align-items: center; gap: 0.3rem; max-width: 100%; - background: none; border: none; padding: 0.06rem 0.2rem; border-radius: var(--r-sm); - font: inherit; font-size: var(--t-md); color: var(--ink); cursor: pointer; -} -.pikey:hover { background: var(--code-bg); } -/* Selected, not just hovered: a flat accent tint, not a boxed outline — a - bordered, rounded pill sitting inside a plain legend read as clutter. */ -.pikey.on { background: var(--accent-soft); font-weight: 600; } -.pikey.on .pname { color: var(--accent-ink); } -.pikey .swatch { width: 9px; height: 9px; border-radius: 2px; flex: 0 0 9px; } -.pikey .pname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 11rem; } -.pikey .pn { color: var(--muted); font-variant-numeric: tabular-nums; } +/* a pie fills its 1 × 1 card below the title, as the portal's (STS-PIE-2); its values are a table in the hover popover */ +.svcell > .card[data-shape=pie] { padding: 4px 0 0; display: flex; flex-direction: column; overflow: hidden; } +.svcell > .card[data-shape=pie] > .facettitle { flex: none; } +.svcell > .card[data-shape=pie] > span { display: flex; flex: 1 1 0; min-height: 0; } +.pie { display: block; width: 100%; height: 100%; } +.pie .slice { cursor: pointer; } +.pie .slice:hover path { opacity: 0.82; } +.pietable .vallist { max-height: 150px; } /* Explore: data-types rows */ -.generow.dtrow { grid-template-columns: calc(0.75rem + 2px) minmax(6rem, 1fr) minmax(6rem, 1.4fr) minmax(3rem, 1.2fr) 4.5rem 3.5rem; } +.generow.dtrow { grid-template-columns: calc(0.75rem + 2px) minmax(6rem, 1fr) minmax(6rem, 1.4fr) 3.5rem 3.5rem; } .generow.dtrow.is-static { cursor: default; } .generow.dtrow.is-static:hover { background: none; } /* Selected, not just hovered: a flat accent tint flush with the row above and @@ -572,21 +584,19 @@ main.analysis-main { max-width: min(132rem, 100%); } /* Explore: high-cardinality categorical facets as a ranked list (portal table) */ .vallist { - /* checkbox · name · bar · count · share, shared by the rows and their header */ - --valrow-cols: calc(0.75rem + 2px) 1fr 2.25rem minmax(3.5rem, auto) 3.25rem; + /* checkbox · name · count · share, shared by the rows and their header */ + --valrow-cols: calc(0.75rem + 2px) 1fr minmax(3.5rem, auto) 3.25rem; margin-top: 0.25rem; /* every value is present; the list scrolls rather than being trimmed */ max-height: var(--vallist-h); overflow-y: auto; overscroll-behavior: contain; } -/* checkbox · name · a second count in place of the bar · count · share */ +/* checkbox · name · a second count · count · share */ .vallist.withextra { --valrow-cols: calc(0.75rem + 2px) 1fr minmax(2.5rem, auto) minmax(2.5rem, auto) 3.25rem; } .vallist.withextra .valhead > span:nth-child(3) { text-align: right; } .vlistfoot { display: block; margin-top: var(--s1); } .valrow { - /* name · a thin proportion rule · count · share — the bar is a hint at - relative size, deliberately small so the label and the number stay the - content. Declare a column for EVERY child: adding the share without one - wrapped it to a second line under each value. */ + /* name · count · share. Declare a column for EVERY child, or the extra + child wraps to a second line under each value. */ display: grid; grid-template-columns: var(--valrow-cols); gap: 0 0.6rem; align-items: center; width: 100%; /* the portal's table row (STS-TBL-7): 25 px whatever the font, as VALROW_H in pick-list.tsx */ @@ -597,7 +607,7 @@ main.analysis-main { max-width: min(132rem, 100%); } .valrow:hover { background: var(--code-bg); } /* the portal's table header: # and Freq over their columns */ .valhead { display: grid; grid-template-columns: var(--valrow-cols); gap: 0 0.6rem; width: 100%; height: 22px; box-sizing: border-box; align-items: center; font-size: var(--t-xs); font-weight: 600; color: var(--muted); } -.valhead > span:nth-child(n + 4) { text-align: right; } +.valhead > span:nth-child(n + 3) { text-align: right; } /* the search box and Select all / Deselect all under a list that scrolls */ .vsearch { display: flex; align-items: center; gap: var(--s1); margin-top: var(--s1); } /* Selected, not just hovered: a flat accent tint flush with the row above and @@ -605,10 +615,6 @@ main.analysis-main { max-width: min(132rem, 100%); } .valrow.on { background: var(--accent-soft); border-radius: 0; } .valrow.on .vname { color: var(--accent-ink); font-weight: 600; } .valrow .vname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -/* A bordered 8px track, solid fill, no track tint and no hover-opacity trick: a hint at relative - size, not a chart. */ -.valrow .vbar { height: 8px; background: var(--card); border: 1px solid var(--line); border-radius: 2px; overflow: hidden; } -.valrow .vbar i { display: block; height: 100%; min-width: 2px; background: var(--accent); } .valrow .vn { text-align: right; font-variant-numeric: tabular-nums; color: var(--muted); } /* Explore's lists (app/lab/pick-list.tsx): only the rows in view are mounted, each placed at its @@ -619,6 +625,12 @@ main.analysis-main { max-width: min(132rem, 100%); } .vrows { position: relative; width: 100%; } .vrow { position: absolute; top: 0; left: 0; width: 100%; } .vrow[data-index="0"] > .generow, .vrow[data-index="0"] > .sbrow { border-top: none; } +/* the Study View's tables as the portal's: every other row striped (its row index, since only the + rows in view are mounted), the scrolling box ruled above and below */ +:is(.svcell, .pietable) .vrow[data-odd] { background: var(--row-stripe); } +:is(.svcell, .pietable) .vallist:not(:has(> .vrows)) > .valrow:nth-child(even) { background: var(--row-stripe); } +:is(.svcell, .pietable) .vrow > :is(.generow, .sbrow) { border-top: none; } +:is(.svcell, .pietable) :is(.vallist, .generows, .sbrows) { border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); } .sbrow { cursor: pointer; } .valrow, .generow, .sbrow { margin: 0; } /* The checkbox's track (the first of each row's grid) is a little narrower than the 1rem box, which @@ -691,9 +703,7 @@ main.analysis-main { max-width: min(132rem, 100%); } /* a chart's title as the portal's (STS-HD-1): one line, centred, a long one cut with an ellipsis (the whole of it is in the tooltip); padded on both sides alike so the chart menu, placed over the card's corner, neither covers it nor pulls it off centre */ -.facetgrid > .card > .facettitle { text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 1.75rem; } /* what the chart counts, on a line of its own under the title, so a long title never hides it */ -.facetgrid > .card > .facettitle > .meta { display: block; font-weight: 400; overflow: hidden; text-overflow: ellipsis; } /* ---------------- view-card tables (app/lab/kinds/.tsx) ---------------- */ .vscroll { overflow-x: auto; } @@ -1213,9 +1223,7 @@ details.cohortpick .gearmenu-items { min-width: 22rem; max-width: 30rem; gap: 0; .cpick-foot { margin: var(--s1) var(--s3) 0; padding-top: var(--s1); border-top: 1px solid var(--line); font-size: var(--t-sm); color: var(--muted); } /* an Explore chart's "⋯" menu: pinned to the card's corner, like a cohort box's */ -.facetgrid > .card { position: relative; } -.facetgrid > .card > div:first-child { padding-right: 1.8rem; } -.facetgrid > .card .chartgear { position: absolute; top: 0.45rem; right: 0.5rem; } +.svcell > .card { position: relative; } .partrename { border: none; background: none; padding: 0; font: inherit; color: inherit; cursor: text; text-align: left; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .partrename:hover { text-decoration: underline dotted; } .partrenameinput { font: inherit; height: 1.45rem; width: 100%; box-sizing: border-box; padding: 0 var(--s1); } @@ -1612,6 +1620,13 @@ td.camp-links { flex-direction: column; align-items: flex-start; gap: var(--s1); .xc-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--s2); } .xc-title { font-size: var(--t-md); font-weight: 600; } .xc-body { position: relative; min-height: 12rem; } +/* in a grid card the chart fills the room under the title (app/lab/figure.tsx DrawAtSize, the density's own measure) */ +.svcell > .card.xc-card { display: flex; flex-direction: column; } +.svcell > .card.xc-card > .xc-head { flex: none; } +.svcell > .card.xc-card > .xc-body { flex: 1 1 0; min-height: 0; overflow: hidden; } +.svcell .xc-body > :is(.figsize, .xc-dens) { height: 100%; } +.figsize { width: 100%; height: 100%; overflow: hidden; } +.figsize > svg { display: block; } .xc-wait { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: var(--s2); background: color-mix(in srgb, var(--card) 70%, transparent); color: var(--muted); font-size: var(--t-sm); } /* the Clinical Data tab's table scrolls within the window, as the portal's (STV-CD-5: max height 100vh − 220px) */ [data-tab="clinical-data"] .tv-scroll { max-height: calc(100vh - 220px); overflow: auto; } diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index 4bc6be57..6842aeaf 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -5,18 +5,20 @@ // same ones an analysis would report. A density is a filter: drag a rectangle over it to add both // axes' ranges to the selection. import { useEffect, useRef, useState } from "react"; +import { RotateCcw } from "lucide-react"; +import { cardRank, type GridCard } from "./explore-grid.tsx"; +import { chartCells, kmPlotTitle } from "../../lib/study-view-layout.ts"; import { api } from "./api.ts"; -import { Choice } from "../_ui/choice.tsx"; import { Button } from "../_ui/button"; -import { useWidth } from "./figure.tsx"; +import { useSize } from "./figure.tsx"; import { linear, axisLeft, axisBottom, leftAxisWidth, bottomAxisHeight } from "../../lib/svg-kit.ts"; -import { fmtInt } from "../../lib/chart/format.ts"; -import type { CohortDef } from "../../lib/types.ts"; +import { fmtCompactTick, fmtInt } from "../../lib/chart/format.ts"; +import type { CohortDef, KmCurve } from "../../lib/types.ts"; import type { PlotCell } from "../../lib/plot.ts"; import { ChartMenu } from "./partitions.tsx"; import { caseFileAction, densityFigureSvg, figureActions, standaloneSvg } from "./chart-files.ts"; import { chartFileName } from "../../lib/study-view-download.ts"; -import { survivalSvg } from "../../lib/views/survival/figure.ts"; +import { curveSummary, survivalSvg } from "../../lib/views/survival/figure.ts"; import { PORTAL_STUDY_VIEW_KM } from "../../lib/chart/style.ts"; import { FGA, MUTATION_COUNT, correlationLines, densityAxes, densityPairKey, densityAxisLabel, densityColors, densityGradient, densitySelection, densityTip, @@ -55,8 +57,29 @@ interface Props { type PlotData = { shape: string; n: number; extent?: { x0: number; x1: number; y0: number; y1: number }; grid?: [number, number]; bins?: PlotCell[]; stats?: { pearson: number | null; spearman: number | null }; coverage?: { total: number; nx: number; ny: number } }; -export function ExploreCharts({ studies, selection, draft, attrs, endpoints, addClauses, km, density = true, pairs = [], onRemovePair, onClearDensity }: Props) { +/** + * The survival chart and the density charts as grid cards. The survival chart is one card with an + * endpoint picker (kept on purpose, 2026-11-13), drawn at 2 × 2 where the portal draws a 1 × 1 tile + * per endpoint. + */ +export function exploreChartCards(props: Props): GridCard[] { + const { attrs, density = true, pairs = [], onRemovePair, onClearDensity, studies, draft, selection, addClauses } = props; const nameOf = (a: string) => attrs.find((x) => x.attribute === a)?.displayName || DENSITY_NAMES[a] || a; + // the default Mutation Count vs FGA chart (unless unchecked), then the reader's X vs Y charts (STS-SC-1) + // the same rule the filter bar reads to hide a drag's pills (STV-FB-3b) + const shown = densityChartsShown(attrs.map((a) => a.attribute), density, pairs); + return [ + ...(props.endpoints && props.endpoints.length ? [{ key: "survival", ...cardRank('[data-chart="survival"]'), ...chartCells("density"), node: }] : []), + ...shown.map(({ pair, added }): GridCard => ({ + key: "density:" + densityPairKey(pair), ...(added ? { name: nameOf(pair.x) + " vs " + nameOf(pair.y) } : cardRank('[data-chart="mutcount-fga"]')), + ...chartCells("density"), + node: onRemovePair(pair) : undefined} onClear={onClearDensity ? () => onClearDensity(pair) : undefined} />, + })), + ]; +} + +function SurvivalCard({ studies, selection, draft, endpoints, km, attrs }: Props) { const [endpoint, setEndpoint] = useState("OS"); const ep = endpoints && endpoints.length ? (endpoints.includes(endpoint) ? endpoint : endpoints[0]) : null; const [res, setRes] = useState<{ key: string; curves?: unknown[]; error?: string } | null>(null); @@ -84,28 +107,26 @@ export function ExploreCharts({ studies, selection, draft, attrs, endpoints, add return () => ac.abort(); }, [key]); // eslint-disable-line react-hooks/exhaustive-deps - // the default Mutation Count vs FGA chart (unless unchecked), then the reader's X vs Y charts (STS-SC-1) - // the same rule the filter bar reads to hide a drag's pills (STV-FB-3b) - const shown = densityChartsShown(attrs.map((a) => a.attribute), density, pairs); const stale = loading || !res || res.key !== key; return <> {ep && (
- {ep === "OS" ? "Overall survival" : ep + " survival"} of the selection - {kmPlotTitle(attrs.find((a) => a.attribute === ep + "_STATUS")?.displayName || ep + " Status")} + 1 ? [{ label: "Endpoint", title: "the outcome the curve follows", + sub: endpoints.map((x) => ({ label: x, checked: x === ep, title: "follow " + x, onClick: () => setEndpoint(x) })) }] : []), + { label: "Download", title: "save this chart as a file", sub: [caseFileAction("Data", { kind: "survival", status: ep + "_STATUS", months: ep + "_MONTHS" }, chartFileName((ep === "OS" ? "Overall" : ep) + " survival", "data"), selection, (update) => setFileError((cur) => update(cur))), ...figureActions((ep === "OS" ? "Overall" : ep) + " survival", () => { const curves = res?.curves; return curves && curves.length ? standaloneSvg(survivalSvg({ kind: "survival", curves } as never, { width: 480, theme: "light" }, PORTAL_STUDY_VIEW_KM)) : null; }, (message) => setFileError(message))] }]} /> - {endpoints && endpoints.length > 1 && ( - [x, x] as const)} /> - )}
-
+ {/* the curve's median, patients and events in its tooltip, where the portal's small KM chart keeps its legend (STS-KM-3) */} +
c.cohort + ": " + curveSummary(c)).join("\n") : undefined}> {res && res.curves && (res.curves.length ? km(res.curves) :

no patient in the selection has a {ep} time and status

)} {res && res.error &&

{res.error}

} {fileError &&

{fileError}

} @@ -113,10 +134,6 @@ export function ExploreCharts({ studies, selection, draft, attrs, endpoints, add
)} - {shown.map(({ pair, added }) => ( - onRemovePair(pair) : undefined} onClear={onClearDensity ? () => onClearDensity(pair) : undefined} /> - ))} ; } @@ -169,11 +186,10 @@ function DensityCard({ pair, added, studies, draft, selection, addClauses, nameO return (
- {title} - {plot && plot.coverage && plot.coverage.total > plot.n - ? fmtInt(plot.n) + " of " + fmtInt(plot.coverage.total) + " samples have both · " : ""}{held ? "selected: " + heldText : "drag a box to filter"} - {held && onClear && } + plot.n + ? fmtInt(plot.n) + " of " + fmtInt(plot.coverage.total) + " samples have both · " : "") + (held ? "selected: " + heldText : "drag a box to filter")}>{title} + {held && onClear && } saveDensity(swapDensity(dset)) }, ...(["x", "y"] as const).filter((k) => logOffered(axes[k].attribute)).map((k) => ({ @@ -207,9 +223,11 @@ function Density({ data, axes, names, figure, held, onSelect }: { data: PlotData /** set to draw the chart as a file */ figure: React.MutableRefObject<(() => string | null) | null>; onSelect: (box: { x0: number; x1: number; y0: number; y1: number }, span: { x: number; y: number }) => void }) { - const { ref, width } = useWidth(260); + // the box's size: in a grid card, the room under the title, which the chart fills + const { ref, size } = useSize(); + const width = size?.width ?? null; const LEGEND_W = 92; - const W = Math.max(200, (width ?? 340) - LEGEND_W), H = Math.round(Math.max(200, Math.min(300, W * 0.72))); + const W = Math.max(200, (width ?? 340) - LEGEND_W), H = size && size.height >= 160 ? size.height : Math.round(Math.max(200, Math.min(300, W * 0.72))); const [gx, gy] = data.grid!; // the engine's log axis is log2(1 + v); the portal draws ln(1 + v) const show = (v: number, log: boolean) => log ? lnFromEngine(v) : v; @@ -217,12 +235,15 @@ function Density({ data, axes, names, figure, held, onSelect }: { data: PlotData y0: show(data.extent!.y0, axes.y.log), y1: show(data.extent!.y1, axes.y.log) }; const xName = names.x, yName = names.y; const xTitle = densityAxisLabel(xName, axes.x.log), yTitle = densityAxisLabel(yName, axes.y.log); - const ys0 = linear(e.y0, e.y1, 0, 1, { nice: false, count: 8 }); - const L = 6 + leftAxisWidth(ys0, yTitle), R = 8, T = 8, B = bottomAxisHeight(xTitle) + 2, PW = W - L - R, PH = H - T - B; - const ys = linear(e.y0, e.y1, T + PH, T, { nice: false, count: 8 }); - const xs = linear(e.x0, e.x1, L, L + PW, { nice: false, count: 8 }); + // about five ticks an axis, thousands as "10K": the labels take little of the card from the plot + const TICKS = 5; + const ys0 = linear(e.y0, e.y1, 0, 1, { nice: false, count: TICKS }); + const yFmt = (v: number) => fmtCompactTick(v, ys0.fmt); + const L = 6 + leftAxisWidth(ys0, yTitle, yFmt), R = 8, T = 8, B = bottomAxisHeight(xTitle) + 2, PW = W - L - R, PH = H - T - B; + const ys = linear(e.y0, e.y1, T + PH, T, { nice: false, count: TICKS }); + const xs = linear(e.x0, e.x1, L, L + PW, { nice: false, count: TICKS }); const pal = { ink: "var(--ink)", muted: "var(--muted)", line: "var(--line)" }; - const axesSvg = axisLeft(ys, L, pal, { title: yTitle }) + axisBottom(xs, T + PH, pal, { title: xTitle, minX: 0, maxX: W }); + const axesSvg = axisLeft(ys, L, pal, { title: yTitle, fmt: (v) => fmtCompactTick(v, ys.fmt) }) + axisBottom(xs, T + PH, pal, { title: xTitle, minX: 0, maxX: W, fmt: (v) => fmtCompactTick(v, xs.fmt) }); const bins = data.bins || []; const { color, legend } = densityColors(bins.map((b) => b.n)); const lines = correlationLines({ pearson: data.stats?.pearson ?? null, spearman: data.stats?.spearman ?? null }, bins.reduce((a, b) => a + b.n, 0)); diff --git a/app/lab/explore-grid.tsx b/app/lab/explore-grid.tsx new file mode 100644 index 00000000..45c1c03e --- /dev/null +++ b/app/lab/explore-grid.tsx @@ -0,0 +1,48 @@ +"use client"; +/** + * The Study View's chart grid, laid out as the portal's (STS-LY-1…3) with the portal's own grid + * library, react-grid-layout: cells of about 195 × 170 px 7 px apart, as many columns as fill the + * page's width, flush with both its sides, + * each card a whole number of cells by its kind, placed in priority order into the first free spot. + * Cards keep their places: no drag and no resize (decided against, 2026-11-13). + */ +import { useMemo, type ReactNode } from "react"; +import ReactGridLayout, { useContainerWidth } from "react-grid-layout"; +import { absoluteStrategy, verticalCompactor } from "react-grid-layout/core"; +import "react-grid-layout/css/styles.css"; +import { CARD_PRIORITY } from "../../lib/study-view-config.ts"; +import { GRID_CELL, findSpotLayout, gridCols, orderCards, type CardSpec } from "../../lib/study-view-layout.ts"; + +/** a card on the grid: its place in the layout (`lib/study-view-layout.ts`) and what it draws */ +export type GridCard = CardSpec & { node: ReactNode }; + +/** the portal's rank and name for a card that is not a clinical attribute's (STS-LY-8), by its card's selector */ +export function cardRank(selector: string): { name: string; priority: number } { + const r = CARD_PRIORITY.find((c) => c.selector === selector); + if (!r) throw new Error("no rank for " + selector); + return { name: r.name, priority: r.priority }; +} + +const MARGIN: [number, number] = [GRID_CELL.margin, GRID_CELL.margin]; +/** no padding at the grid's sides, the gap above and below it */ +const PADDING: [number, number] = [0, GRID_CELL.margin]; + +export function StudyViewGrid({ cards }: { cards: GridCard[] }) { + // the grid fills its box's width; the columns stretch or squeeze a little to fill it + const { width, containerRef, mounted } = useContainerWidth({ measureBeforeMount: true }); + const cols = gridCols(width); + const ordered = useMemo(() => orderCards(cards), [cards]); + const layout = useMemo(() => findSpotLayout(ordered, cols), [ordered, cols]); + return ( +
+ {mounted && ( + + {ordered.map((c) =>
{c.node}
)} +
+ )} +
+ ); +} diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index cbd97b43..aa55d485 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -15,13 +15,18 @@ import { isCustomAttr } from "../../lib/custom-data-names.ts"; import { CAT_COLORS } from "./view-chrome.tsx"; import { useWidth } from "./figure.tsx"; import { textWidth } from "../../lib/chart/text.ts"; -import { fmtInt, fmtNum, fmtPct, portalBinRange, portalFreq, portalLogTick, portalSelectedInfo } from "../../lib/chart/format.ts"; +import { fmtInt, fmtNum, fmtPct, portalBinRange, portalFreq, portalLogTick, portalPieCount, portalSelectedInfo } from "../../lib/chart/format.ts"; import { countAxis } from "../../lib/chart/scale.ts"; import { naturalOrder } from "../../lib/ordinal.ts"; import { barFigureSvg, pieFigureSvg, type FigureBar, type PieSlice } from "../../lib/study-view-figures.ts"; import { caseFileAction, figureActions, runCaseFile } from "./chart-files.ts"; import { caseFileName } from "../../lib/study-view-case-files.ts"; import { chartOffered } from "../../lib/study-view-config.ts"; +import { chartCells } from "../../lib/study-view-layout.ts"; +import { PIE_AREA, PIE_LIFT, PIE_SELECTED_STROKE, PIE_UNSELECTED, pieLabelFits, pieRadius } from "../../lib/study-view-pie.ts"; +import { HoverPopover } from "../_ui/hover-popover.tsx"; +import { textOn } from "../../lib/chart/style.ts"; +import { cardRank, type GridCard } from "./explore-grid.tsx"; import { violinPairKey, violinTitle } from "../../lib/study-view-violin.ts"; import { addChartLines, assayTabs, bulkButtons, genomicChartLines, xVsYAttributes, xVsYButton, SPECIAL_CHART_KEYS, specialChartsShown, geneTabView, columnsMenuTabs } from "../../lib/study-view-add-chart.ts"; import { StudyHeader } from "./explore-study-header.tsx"; @@ -41,7 +46,6 @@ import { DEFAULT_CLINICAL_CHARTS, SHOW_DERIVED_FACETS, type ExploreState, type G import { LINE_TYPE } from "../../lib/treatment-lines.ts"; import { Dna, Download, Filter, LoaderCircle, Save, Search, Tag, Users, X } from "lucide-react"; import { Button } from "../_ui/button"; -import { CHIP } from "../_ui/toolbar.ts"; import { GearMenu } from "../_ui/gear-menu.tsx"; import { Checkbox } from "../_ui/checkbox"; import { Input } from "../_ui/input"; @@ -570,7 +574,6 @@ export function DerivedFacets({ ctx }: { ctx: ExploreCtx }) {
{explore.derived.map(d => { - const max = Math.max(...d.buckets.map(b => b.n), 1); const dEventType = (d as any).eventType as string | undefined; const dLineGap = (d as any).lineGap as number | undefined; const picked = (b: { gte?: number; lt?: number }) => { @@ -601,7 +604,6 @@ export function DerivedFacets({ ctx }: { ctx: ExploreCtx }) { ...(dEventType ? { eventType: dEventType } : {}), ...(dLineGap != null ? { lineGap: dLineGap } : {}), range: { ...(b.gte != null ? { gte: b.gte } : {}), ...(b.lt != null ? { lt: b.lt } : {}) } })}> {b.label} - {b.n.toLocaleString()} ))} @@ -615,8 +617,6 @@ export function DerivedFacets({ ctx }: { ctx: ExploreCtx }) { ; } -/** rows a value list shows before it scrolls (`.vallist`'s max-height) */ -const VALLIST_ROWS = 9; /** * A facet's histogram, as the portal's bar chart: a y axis of integer counts, one bar per bin (the @@ -822,6 +822,9 @@ function compareNumeric(label: string, singleStudy: boolean, working: boolean, q ] }; } +/** a pie slice's count label, in px (STS-PIE-3) */ +const PIE_LABEL_SIZE = 11; + /** a value list's key for its NA row, which no value can spell */ const NA_KEY = "\u0000NA"; @@ -836,13 +839,15 @@ function binClause(attribute: string, b: any): Clause { const binLabel = (b: any): string => b.value != null ? b.value : b.special === "<=" ? "≤" + fmtNum(b.end) : b.special === ">" ? ">" + fmtNum(b.start) : b.start === b.end ? fmtNum(b.start) : fmtNum(b.start) + "–" + fmtNum(b.end); -export function ClinicalFacets({ ctx }: { ctx: ExploreCtx }) { - const { visibleClinical } = ctx; +/** the clinical charts shown, by the portal's priority: a numeric one a bar chart, a categorical one a pie or a table of its values */ +export function clinicalCards(ctx: ExploreCtx): GridCard[] { const explore = ctx.explore!; - return <> - {(visibleClinical(explore.clinical as never) as unknown as typeof explore.clinical) - .map((c) => )} - ; + return (ctx.visibleClinical(explore.clinical as never) as unknown as typeof explore.clinical).map((c) => ({ + key: "attr:" + c.per + "|" + c.attribute, name: c.displayName || c.attribute, priority: c.priority ?? 0, + ...(c.kind === "num" ? chartCells("bar") : PIE_ATTRIBUTES.has(c.attribute) ? chartCells("pie") + : chartCells("list", c.values.length + (c.na ? 1 : 0))), + node: , + })); } /* data-attr / data-shape make the facet identifiable from outside @@ -870,15 +875,9 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin : (c.bins || []).reduce((n: number, b: any) => n + b.count, 0); const unit = c.per === "sample" ? " samples" : " patients"; return ( -
- {isCustomAttr(c.attribute) && custom} - {c.displayName || c.attribute}{" "} - - {(c.per === "sample" ? "sample-level · " : "") + shown.toLocaleString() + unit} - {disj ? " · not narrowed by its own filter" : ""} - +
+ {c.displayName || c.attribute} {(() => { const label = c.displayName || c.attribute; const chart: ChartKey = { kind: "clinical", attribute: c.attribute }; @@ -935,7 +934,8 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin const values: any[] = [...naturalOrder(c.values, (v: any) => String(v.v)), ...(c.na ? [{ v: "NA", n: c.na, isNa: true }] : [])]; const total = values.reduce((n: number, v: any) => n + v.n, 0) || 1; let acc = 0; - const R = 34, CX = 36, CY = 36; + // the pie fills its 1 × 1 cell as the portal's (STS-PIE-2) + const R = pieRadius(PIE_AREA.w, PIE_AREA.h), CX = PIE_AREA.w / 2, CY = PIE_AREA.h / 2 - PIE_LIFT; const arcs = values.map((v: any, i: number) => { const frac = v.n / total, a0 = acc * 2 * Math.PI - Math.PI / 2; acc += frac; @@ -947,11 +947,11 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin const path = frac >= 0.999 ? "M " + CX + " " + (CY - R) + " A " + R + " " + R + " 0 1 1 " + (CX - 0.01) + " " + (CY - R) + " Z" : "M " + CX + " " + CY + " L " + x0 + " " + y0 + " A " + R + " " + R + " 0 " + large + " 1 " + x1 + " " + y1 + " Z"; - return { v, path, color: v.isNa ? PORTAL_NA : CAT_COLORS[i % CAT_COLORS.length], frac }; + const mid = (a0 + a1) / 2; + return { v, path, color: v.isNa ? PORTAL_NA : CAT_COLORS[i % CAT_COLORS.length], frac, lx: CX + R * 0.62 * Math.cos(mid), ly: CY + R * 0.62 * Math.sin(mid) }; }); - if (asList) { - const byKey = new Map(values.map((v: any) => [String(v.v), v])); - return (<> + const byKey = new Map(values.map((v: any) => [String(v.v), v])); + const table = ( c.values.length ? { shown: c.values.length, of: c.distinct! } : undefined} hint={"keep the cases whose " + (c.displayName || c.attribute) + " is any of the checked values"} rows={values.map((v: any) => ({ key: v.isNa ? NA_KEY : String(v.v), name: String(v.v), n: v.n, total, on: isSel(v), muted: v.isNa, solo: v.isNa, @@ -961,36 +961,40 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin if (keys.includes(NA_KEY)) { toggleNaValue(c.attribute); return; } const vs = keys.map((k) => byKey.get(k).v); addClause(vs.length === 1 ? clause(byKey.get(keys[0])) : { kind: "clinical", attribute: c.attribute, values: vs }); - }} /> + }} />); + if (asList) { + return (<> + {table} {(c.distinct ?? 0) > c.values.length ? ( - showing {c.values.length.toLocaleString()} of {c.distinct!.toLocaleString()} values{c.values.length > VALLIST_ROWS ? " · scroll for more" : ""} + showing {c.values.length.toLocaleString()} of {c.distinct!.toLocaleString()} values - ) : c.values.length > VALLIST_ROWS && ( - {c.values.length.toLocaleString()} values · scroll for more - )} + ) : null} ); } + // while the chart has a filter, the values it leaves out are grey (STS-PIE-7) + const filtered = values.some(isSel); + // the chart's values as a table in the hover popover, where the portal shows its pie's (STS-PIE-5) return ( -
- - {arcs.map((a: any, i: number) => ( - pick(a.v)} - data-tip={a.v.v + " — " + a.v.n.toLocaleString() + " (" + portalFreq(100 * a.frac) + ")"} /> - ))} - -
- {arcs.map((a: any, i: number) => ( - - ))} -
-
+ + {arcs.map((a: any, i: number) => { + const off = filtered && !isSel(a.v); + const fill = off ? PIE_UNSELECTED.fill : a.color; + const label = portalPieCount(a.v.n); + return ( + pick(a.v)} data-tip={a.v.v + ":" + a.v.n}> + + {pieLabelFits(a.frac, R, textWidth(label, PIE_LABEL_SIZE)) && ( + {label} + )} + + ); + })} + }> + {table} + ); })()} {c.kind === "num" && c.bins && c.bins.length > 1 && (() => { @@ -1029,11 +1033,6 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin ); })()} - {c.kind === "num" &&
- min {fmtNum(c.min)} · median {fmtNum(c.median)} · max {fmtNum(c.max)} - - -
} {binsOpen && c.kind === "num" && setChartBins(c.attribute, { ...binSet, bins: b })} onClose={() => setBinsOpen(false)} />}
@@ -1194,13 +1193,16 @@ function AssayChartPicker({ ctx, assayType }: { ctx: ExploreCtx; assayType: stri * the portal's generic-assay frequency tables (STS-OT-5): a row per (entity, value), its cases and * Freq of every selected case; arm-level CNA and LOH tables show altered categories until asked */ -export function AssayFreqTables({ ctx }: { ctx: ExploreCtx }) { +export function assayFreqCards(ctx: ExploreCtx): GridCard[] { + return (ctx.explore!.assayFreqTables || []).map((t) => ({ key: "assayfreq:" + t.profileType, name: "Frequency Table: " + t.name, + ...chartCells("table"), node: })); +} + +/** the frequency tables left undrawn, said above the grid */ +export function AssayFreqTablesMore({ ctx }: { ctx: ExploreCtx }) { const more = ctx.explore!.assayFreqTablesNotShown || []; - return <> - {(ctx.explore!.assayFreqTables || []).map((t) => )} - {more.length > 0 &&

- {ASSAY_FREQ_TABLE_LIMIT} frequency tables are drawn at most; not drawn: {more.join(", ")}.

} - ; + return more.length > 0 ?

+ {ASSAY_FREQ_TABLE_LIMIT} frequency tables are drawn at most; not drawn: {more.join(", ")}.

: null; } function AssayFreqTable({ t, ctx }: { t: NonNullable["assayFreqTables"]>[number]; ctx: ExploreCtx }) { @@ -1219,13 +1221,13 @@ function AssayFreqTable({ t, ctx }: { t: NonNullable -
+
Frequency Table: {t.name} - {t.unit}-level · Freq of {fmtInt(t.total)} {noun}{t.disjunctive ? " · counted without its own filter" : ""} + {curated && }
- {curated && } {without.length > 0 &&

Not held by {without.join(", ")}: counted in Freq, but its rows cannot filter {without.length === 1 ? "it" : "them"}.

} {peers.length > 0 &&

Not counted: {peers.join(", ")} (a peer's {peers.length === 1 ? "study" : "studies"}, whose counts are not shared).

} {rows.length ? - {(ctx.explore!.assayFacets || []).map((f) => )} - ; +/** the generic-assay entities the reader charted, in the order added: a bar chart, or a table of values */ +export function assayCards(ctx: ExploreCtx): GridCard[] { + return (ctx.explore!.assayFacets || []).map((f) => ({ key: "assay:" + f.profileType + "|" + f.entity, name: f.entity, + ...(f.kind === "num" ? chartCells("bar") : chartCells("list", (f.values || []).length)), node: })); } function AssayFacet({ f, ctx }: { f: NonNullable["assayFacets"]>[number]; ctx: ExploreCtx }) { @@ -1265,8 +1267,8 @@ function AssayFacet({ f, ctx }: { f: NonNullable b.count > 0).map((b) => ({ name: armLabel(short + " " + binText(b)), where: { ...base, ...assayBinWhere(b) } as Leaf })); return (
-
- {title} +
+ {title} compareAction((f.values || []).map((v) => ({ ...valueArm(v.v), n: v.n })), checked.map(valueArm), "value of " + title, (arms) => compareItems(chart, arms, t), t)) : forBoth((t) => compareNumeric(title, exStudies.length === 1, splittingBy === title, (q) => compareQuantiles({ assay: { profileType: f.profileType, entity: f.entity } }, q, title, t), @@ -1275,10 +1277,9 @@ function AssayFacet({ f, ctx }: { f: NonNullable ({ count: b.count, tick: b.special === "<=" ? "≤" + fmtNum(b.end!) : b.special === ">" ? ">" + fmtNum(b.start!) : fmtNum(b.start!) })), f.total > f.measured ? "NA " + fmtInt(f.total - f.measured) : null), ctx.setExMsg) }] : []), ...(f.kind === "cat" && f.values && f.unit ? [summaryDownload(title, f.unit, f.values.map((v) => ({ value: v.v, count: v.n })), f.total - f.measured, f.distinct, ctx.setExMsg)] : [])]} /> - +
- {noun} · {fmtInt(f.measured)} of {fmtInt(f.total)} with a value{f.disjunctive ? " · counted without its own filter" : ""}{why} {f.error &&

{f.error}

} {f.kind === "cat" && f.values && ( ); })()} - {f.kind === "num" && f.median != null &&
- min {fmtNum(f.min!)} · median {fmtNum(f.median)} · max {fmtNum(f.max!)} - {clickable && <> - - - } -
}
); } -export function GeneFacets({ ctx }: { ctx: ExploreCtx }) { +/** the gene status charts the reader added, one per gene and profile: a table of the gene's states */ +export function geneFacetCards(ctx: ExploreCtx): GridCard[] { const { addClauses, geneStatesClauses } = ctx; const explore = ctx.explore!; - return <> - {(explore.geneFacets || []).filter((f) => (ctx.geneKinds[f.gene] || []).includes(f.type)).map(f => { + return (explore.geneFacets || []).filter((f) => (ctx.geneKinds[f.gene] || []).includes(f.type)).map((f): GridCard => { const apply = (states: string[]) => geneStatesClauses(f.gene, f.type, states); // the copy-number levels the portal draws: none at 0 (the drivers-only chart keeps its fixed rows) const states = f.type === "CNA" && !explore.drivers ? f.states.filter((st) => st.n > 0) : f.states; - return ( -
-
+ return { key: "gene:" + f.gene + "|" + f.type, name: geneChartName(f.gene, f.type), ...chartCells("list", states.length), node: ( +
+
{geneChartName(f.gene, f.type)} - sample-level · {f.total.toLocaleString()} samples ({ value: st.label, count: st.n })), 0, undefined, ctx.setExMsg, undefined, undefined, // the file writes the portal's codes (SD14); the figure, the names on screen @@ -1355,19 +1348,18 @@ export function GeneFacets({ ctx }: { ctx: ExploreCtx }) {

) : null}
- ); - })} - ; + ) }; + }); } /** * the portal's treatment tables (STS-OT-6), when a selected study has treatments: patients per * agent, and samples per agent taken before or after it; the checked rows filter (Union) */ -export function TreatmentTables({ ctx }: { ctx: ExploreCtx }) { +export function treatmentCards(ctx: ExploreCtx): GridCard[] { const { addClauses, parseDraft } = ctx; const t = ctx.explore!.treatments; - if (!t) return null; + if (!t) return []; const draft = parseDraft(); const leftOut = t.leftOut &&

Not counted: {t.leftOut.join(", ")}, held by a peer whose federation API has no treatment counts. @@ -1376,7 +1368,7 @@ export function TreatmentTables({ ctx }: { ctx: ExploreCtx }) { const on = new Set(appliedTreatmentKeys(draft, level)); return (

-
{title}{meta}
+
{title}
{leftOut} {rows.length ? ); }; - return <> - {table("patient", "Treatment per Patient", fmtInt(t.totalPatients) + " patients treated", "patients treated", - t.patients.map((r) => ({ key: r.agent, name: r.agent, n: r.n, title: r.agent + " — " + fmtInt(r.n) + " patients treated" })))} - {table("sample", "Treatment per Sample (pre/post)", fmtInt(t.totalSamples) + " samples with a time", "samples acquired before treatment or after/on treatment", + return [ + { key: "treatments:patient", ...cardRank('[data-treatments="patient"]'), ...chartCells("table"), node: table("patient", "Treatment per Patient", fmtInt(t.totalPatients) + " patients treated", "patients treated", + t.patients.map((r) => ({ key: r.agent, name: r.agent, n: r.n, title: r.agent + " — " + fmtInt(r.n) + " patients treated" }))) }, + { key: "treatments:sample", ...cardRank('[data-treatments="sample"]'), ...chartCells("table"), node: table("sample", "Treatment per Sample (pre/post)", fmtInt(t.totalSamples) + " samples with a time", "samples acquired before treatment or after/on treatment", sampleTreatmentOrder(t.samples).map((r) => ({ key: sampleTreatmentKey(r.agent, r.time), name: r.agent, extra: r.time, n: r.n, - title: r.agent + " — " + fmtInt(r.n) + " samples taken " + (r.time === "Pre" ? "before" : "after") + " the first treatment with it" })))} - ; + title: r.agent + " — " + fmtInt(r.n) + " samples taken " + (r.time === "Pre" ? "before" : "after") + " the first treatment with it" }))) }, + ]; } /** * each gene charted by mutation type: the portal's Mutation Type Counts table (STS-OT-3), # Mut, * # and Freq of the selected samples; the checked types filter to samples with any of them */ -export function MutationTypeFacets({ ctx }: { ctx: ExploreCtx }) { +export function mutationTypeCards(ctx: ExploreCtx): GridCard[] { const { addClauses, parseDraft } = ctx; - return <> - {(ctx.explore!.mutationTypeFacets || []).map((f) => { + return (ctx.explore!.mutationTypeFacets || []).map((f): GridCard => { const applied = appliedMutationTypes(parseDraft(), f.gene), on = new Set(applied.types); const counted = !f.leftOut || f.total > 0; - return ( -
-
+ return { key: "mutationtypes:" + f.gene, name: f.gene + ": mutation types", ...chartCells("table"), node: ( +
+
{f.gene}: mutation types - {counted && sample-level · Freq of {f.total.toLocaleString()} samples{f.disjunctive ? " · counted without its own filter" : ""}}
{applied.excluded > 0 &&

{applied.excluded === 1 ? "A filter excludes" : applied.excluded + " filters exclude"} {f.gene} mutation types; this table is counted without {applied.excluded === 1 ? "it" : "them"}. @@ -1427,12 +1417,23 @@ export function MutationTypeFacets({ ctx }: { ctx: ExploreCtx }) { onApply={(types) => { const r = mutationTypesClause(f.gene, types); if ("clauses" in r) addClauses(r.clauses); }} /> ) :

No {f.gene} mutation in the selected samples.

}
- ); - })} - ; + ) }; + }); +} + +/** the Cancer Studies table, for more than one study */ +export function studyCards(ctx: ExploreCtx): GridCard[] { + return (ctx.explore!.studyBreakdown || []).length && ctx.exStudies.length > 1 + ? [{ key: "studies", ...cardRank('[data-chart="studies"]'), ...chartCells("table"), node: }] : []; +} + +/** the Data Types table, unless unchecked in Add chart */ +export function dataTypesCards(ctx: ExploreCtx): GridCard[] { + return ctx.chartChecked("genomic|datatypes") && (ctx.explore!.dataTypes || []).length + ? [{ key: "datatypes", ...cardRank('[data-chart="datatypes"]'), ...chartCells("table"), node: }] : []; } -export function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { +function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { const { exStudies, setExploreStudies } = ctx; const explore = ctx.explore!; const picks = usePicks(); @@ -1443,14 +1444,13 @@ export function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { const total = rows.reduce((n, r) => n + r.n, 0) || 1; return (
-

Cancer Studies — {explore.draftCount != null ? "the draft's" : "the selection's"} samples across the {exStudies.length} selected studies

+
Cancer Studies
r.study} estimate={26} className="sbrows"> {(r) => ( {r.study} {r.instance !== "a" ? "⧉ " + r.instanceLabel : ""} - {fmtPct(100 * r.n / total)} {r.n.toLocaleString()} @@ -1473,7 +1473,7 @@ const PROFILED_TYPE: Record = { /** where the browser keeps the Data types table's Union / Intersection choice */ const DATA_TYPES_OP_KEY = "cbiolab.explore.dataTypesOp"; -export function DataTypes({ ctx }: { ctx: ExploreCtx }) { +function DataTypes({ ctx }: { ctx: ExploreCtx }) { const { addClause, addClauses, parseDraft } = ctx; const explore = ctx.explore!; const picks = usePicks(); @@ -1491,7 +1491,6 @@ export function DataTypes({ ctx }: { ctx: ExploreCtx }) { if (!rows.length) return null; const d = parseDraft(); const selected = (t: string) => !!(d && d.all.some((cl: any) => cl.kind === "profiled" && cl.type === t)); - const max = Math.max(...rows.map((x) => x.n), 1); const samples = explore.totals?.samples ?? 0; const typeOf = new Map(rows.map((dt) => [dt.profile, PROFILED_TYPE[dt.alterationType]])); const types = (profiles: string[]) => [...new Set(profiles.map((p) => typeOf.get(p)).filter(Boolean))] as string[]; @@ -1500,7 +1499,7 @@ export function DataTypes({ ctx }: { ctx: ExploreCtx }) { const refusal = op === "intersection" && n > 1 ? intersectionRefusal(filters, n, "kind of data") : null; return (
-

Data types — samples with each kind of molecular data

+
Data Types
dt.profile} estimate={26} className="generows"> {(dt) => { const t = PROFILED_TYPE[dt.alterationType]; @@ -1509,7 +1508,6 @@ export function DataTypes({ ctx }: { ctx: ExploreCtx }) { title={t ? "require " + t + " data (profiled clause)" : "no membership filter for this data type in the DSL — shown for completeness"}> {dt.profile} {dt.label} - {dt.n.toLocaleString()} {portalFreq(samples ? 100 * dt.n / samples : NaN)} @@ -1530,9 +1528,12 @@ export function DataTypes({ ctx }: { ctx: ExploreCtx }) { ); } -export function AlteredGenes({ ctx }: { ctx: ExploreCtx }) { - // each table unless unchecked in Add chart's Genomic tab - return <>{(["mutated", "cna", "sv"] as const).filter((kind) => ctx.chartChecked("genomic|" + kind)).map((kind) => )}; +/** the Mutated, CNA and SV gene tables: each one with genes, unless unchecked in Add chart's Genomic tab */ +export function geneTableCards(ctx: ExploreCtx): GridCard[] { + const e = ctx.explore!; + const rows = { mutated: e.mutatedGenes, cna: e.cnaGenes, sv: e.svGenes }; + return (["mutated", "cna", "sv"] as const).filter((kind) => ctx.chartChecked("genomic|" + kind) && (rows[kind] || []).length) + .map((kind) => ({ key: "genetable:" + kind, ...cardRank('[data-genetable="' + kind + '"]'), ...chartCells("table"), node: })); } /** a gene table row's height in px: one line of --t-md plus the row's padding */ @@ -1590,14 +1591,9 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore const rowKey = (g: any) => g.gene + (g.cna ?? ""); const byKey = new Map(all.map((g: any) => [rowKey(g), g])); return ( -
-
-

{title}

- {drivers && OncoKB drivers} - - setGeneFilter({ ...geneFilter, [kind]: e.target.value })} /> +
+
+ {title} {(() => { const chart: ChartKey = { kind: "genes", specs: (kind === "mutated" ? ["MUT"] : kind === "cna" ? ["AMP", "HOMDEL"] : ["FUSION"]).map((c) => ": " + callOql(c)) }; const checked = picks.picked.map((k) => byKey.get(k)).filter(Boolean); @@ -1660,9 +1656,12 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore ); }} - {needle - ? rows.length.toLocaleString() + " of " + all.length.toLocaleString() + " genes match" - : all.length.toLocaleString() + " genes"} + {/* the search box in the card's footer, as every chart's (STS-TBL-3) */} +
+ setGeneFilter({ ...geneFilter, [kind]: e.target.value })} /> +
{(() => { const n = picks.picked.length; const refusal = op === "intersection" && n > 1 ? intersectionRefusal(draftClauses.length, n) : null; @@ -1710,7 +1709,7 @@ function SpecialCharts({ ctx }: { ctx: ExploreCtx }) { ); } -export function EventsAndCaseLists({ ctx }: { ctx: ExploreCtx }) { +export function specialCards(ctx: ExploreCtx): GridCard[] { const { addClause, parseDraft, chartChecked } = ctx; const explore = ctx.explore!; const leaves = ((parseDraft()?.all) || []).flatMap((c: any) => Array.isArray(c?.any) ? c.any : [c]); @@ -1719,23 +1718,22 @@ export function EventsAndCaseLists({ ctx }: { ctx: ExploreCtx }) { // the portal shows these only when added (Case Lists also while one is filtered on): STS-OT-2, STS-OT-7 const shown = specialChartsShown(chartChecked, leaves, explore.events.length > 0); const anyOf = (ls: any[]) => { if (ls.length) addClause(ls.length === 1 ? ls[0] : { any: ls }); }; - return <> - {shown.events &&
-

Timeline Events Availability

+ return [ + ...(shown.events ? [{ key: "events", ...cardRank('[data-special="events"]'), ...chartCells("table"), node:
+
Timeline Events Availability
limitRefusal(types.length, ANY_LEAF_LIMIT, "alternatives")} rows={explore.events.map((e) => ({ key: e.type, name: e.type, n: e.n, total: explore.totals?.patients, on: eventOn(e.type), title: e.n.toLocaleString() + " of " + (explore.totals?.patients ?? 0).toLocaleString() + " selected patients with a " + e.type + " event" }))} onApply={(types) => anyOf(types.map((t) => ({ kind: "event", a: { eventType: t }, rel: { type: "NONE" } })))} /> -
} - {shown.caseLists &&
-

Case Lists

+
}] : []), + ...(shown.caseLists ? [{ key: "caselists", ...cardRank('[data-special="caselists"]'), ...chartCells("table"), node:
+
Case Lists
limitRefusal(ids.length, ANY_LEAF_LIMIT, "alternatives")} rows={explore.caseLists.map((l) => ({ key: l.id, name: l.name, n: l.n, total: explore.totals?.samples, on: listOn(l.id), title: l.id + " — " + l.n.toLocaleString() + " of " + (explore.totals?.samples ?? 0).toLocaleString() + " selected samples" }))} onApply={(ids) => anyOf(ids.map((id) => ({ kind: "caseList", id })))} /> -

Profiles here: {(explore.profiles || []).join(", ") || "none"}{explore.gaProfiles && explore.gaProfiles.length ? " · assays: " + explore.gaProfiles.join(", ") : ""} · facet counts {explore.draftCount != null ? "narrowed to your draft" : "study-wide"} · {explore.stats.ms}ms

-
} - ; +
}] : []), + ]; } diff --git a/app/lab/explore-violin.tsx b/app/lab/explore-violin.tsx index c04bd9da..cc415c26 100644 --- a/app/lab/explore-violin.tsx +++ b/app/lab/explore-violin.tsx @@ -66,8 +66,7 @@ export function ViolinCard({ facet, nameOf, selected, onToggle, onRemove }: { return (
- {title} - sample-level + {title} setLog(!log) }] : []), { label: "Show Violin Plot", checked: showViolin, title: "draw each category's distribution", onClick: () => setShowViolin(!showViolin) }, diff --git a/app/lab/figure.tsx b/app/lab/figure.tsx index 5cc1ca5d..94c0bc21 100644 --- a/app/lab/figure.tsx +++ b/app/lab/figure.tsx @@ -28,6 +28,37 @@ export function useWidth(min = MIN_FIGURE_W) { return { ref, width }; } +/** the box's width and height, in 8px steps, followed as it resizes (null before the first measure) */ +export function useSize() { + const ref = useRef(null); + const [size, setSize] = useState<{ width: number; height: number } | null>(null); + useLayoutEffect(() => { + const el = ref.current; + if (!el) return; + const measure = () => { + const width = Math.floor(el.clientWidth / 8) * 8, height = Math.floor(el.clientHeight / 8) * 8; + setSize((cur) => cur && cur.width === width && cur.height === height ? cur : { width, height }); + }; + measure(); + const ro = new ResizeObserver(measure); + ro.observe(el); + return () => ro.disconnect(); + }, []); + return { ref, size }; +} + +/** + * A figure function drawn to fill its box, width and height: the box takes its size from the page + * (a grid card's room under its title), never from the figure, so drawing does not resize it. + */ +export function DrawAtSize({ draw, deps }: { draw: (width: number, height: number) => string | null; deps: unknown[] }) { + const { ref, size } = useSize(); + // eslint-disable-next-line react-hooks/exhaustive-deps -- `deps` are the drawing's inputs, named by the caller + const svg = useMemo(() => size && size.width > 0 && size.height > 0 ? draw(size.width, size.height) : null, [size, ...deps]); + // the renderer escapes every label it writes (lib/chart/esc.ts) + return
; +} + /** * SVG markup laid out at `width` (lib/svg-kit.ts frame()), shown 1:1, scrolling when wider than its box; * with `topScroll`, a second scrollbar above it, kept in step, for a figure taller than the screen diff --git a/app/lab/page.tsx b/app/lab/page.tsx index 299a0625..0690cd13 100644 --- a/app/lab/page.tsx +++ b/app/lab/page.tsx @@ -3,7 +3,9 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { currentLinkUrlMax, linkParams, writeSearch } from "../_links/link-state.ts"; import { TAB_PARAM, readFilters, readTab, writeTab, type StudyViewTab } from "../../lib/study-view-url.ts"; import { useLinkParams } from "../_links/use-link.ts"; -import { ExploreCharts } from "./explore-charts"; +import { exploreChartCards } from "./explore-charts"; +import { StudyViewGrid } from "./explore-grid.tsx"; +import { chartCells } from "../../lib/study-view-layout.ts"; import { geneChartCount } from "../../lib/study-view-add-chart.ts"; import { ViolinCard } from "./explore-violin"; import { violinPairKey } from "../../lib/study-view-violin.ts"; @@ -35,12 +37,11 @@ import { api } from "./api.ts"; import { useSavedArtifacts } from "./use-saved.ts"; import { useSaved, useSavedActions } from "../_saved/saved-context.tsx"; import { ExamplesTab } from "./examples-tab.tsx"; -import { DrawAtWidth } from "./figure.tsx"; +import { DrawAtSize } from "./figure.tsx"; import { survivalSvg } from "../../lib/views/survival/figure.ts"; import { PORTAL_STUDY_VIEW_KM } from "../../lib/chart/style.ts"; import { GenesDialog, CustomDataWarning, CohortColumn, DocDialog, ViewColumn, type AnalysisCtx } from "./analysis-sections.tsx"; -import { StudyPicker, ExploreBar, AddChartDialog, DerivedFacets, ClinicalFacets, GeneFacets, MutationTypeFacets, AssayFacets, AssayFreqTables, TreatmentTables, StudyBreakdown, DataTypes, AlteredGenes, EventsAndCaseLists, type ExploreCtx } from "./explore-sections.tsx"; -import { cardOrders } from "../../lib/study-view-config.ts"; +import { StudyPicker, ExploreBar, AddChartDialog, DerivedFacets, clinicalCards, geneFacetCards, mutationTypeCards, assayCards, assayFreqCards, AssayFreqTablesMore, treatmentCards, studyCards, dataTypesCards, geneTableCards, specialCards, type ExploreCtx } from "./explore-sections.tsx"; import { CohortEditDialog, WorkspaceDialog } from "./dialogs.tsx"; import { useViewOptions } from "./use-view-options.ts"; import { useViewEdits } from "./use-view-edits.ts"; @@ -659,40 +660,37 @@ export default function AnalysisPage() {
)} {explore && explore.draftCount !== 0 && <> - {/* every card's place by the portal's priorities, clinical and other kinds together (STS-LY-3) */} - -
- tabSelection} draft={parseDraft()} - attrs={explore.clinical || []} - endpoints={(() => { + + {/* every card in the portal's grid, by its priorities, clinical and other kinds together (STS-LY-1…3) */} + tabSelection, draft: parseDraft(), + attrs: explore.clinical || [], + endpoints: (() => { // an endpoint is a _MONTHS with its _STATUS, the survival view's own convention const names = new Set((explore.clinical || []).map((c: any) => c.attribute)); const eps = [...names].filter((a) => /_MONTHS$/.test(a) && names.has(a.replace(/_MONTHS$/, "_STATUS"))).map((a) => a.replace(/_MONTHS$/, "")); return eps.sort((a, b) => (a === "OS" ? -1 : b === "OS" ? 1 : a.localeCompare(b))); - })()} - addClauses={exploreState.addDensitySelection} km={(curves) => survivalSvg({ kind: "survival", curves: curves as any }, { width }, PORTAL_STUDY_VIEW_KM)} deps={[curves]} />} - density={exploreState.chartChecked("genomic|density")} pairs={exploreState.xyCharts} onRemovePair={exploreState.removeXyChart} - onClearDensity={exploreState.clearDensitySelection} /> - {(explore.violinFacets || []).filter((f) => exploreState.violinCharts.some((p) => violinPairKey(p) === violinPairKey(f))).map((f) => ( - survivalSvg({ kind: "survival", curves: (curves as any[]).map((c) => ({ ...c, atRisk: undefined })) as any }, { width }, PORTAL_STUDY_VIEW_KM, true, height)} deps={[curves]} />, + density: exploreState.chartChecked("genomic|density"), pairs: exploreState.xyCharts, onRemovePair: exploreState.removeXyChart, + onClearDensity: exploreState.clearDensitySelection }), + ...(explore.violinFacets || []).filter((f) => exploreState.violinCharts.some((p) => violinPairKey(p) === violinPairKey(f))).map((f) => ({ + key: "violin:" + violinPairKey(f), name: violinPairKey(f), ...chartCells("violin"), + node: (explore.clinical || []).find((c: any) => c.attribute === a)?.displayName || a} - onToggle={(v) => exploreState.togglePieValue(f.categorical, v)} onRemove={() => exploreState.removeViolinChart(f)} /> - ))} - - {/* Charted genes (added from "+ Add chart" > Gene status) — one tile per - gene per alteration type, the same tile shape a clinical attribute gets, - so a chart you configured actually reaches this grid rather than only - living inside the dialog that configured it. */} - - - - - - - {exploreState.chartChecked("genomic|datatypes") && } - - -
+ onToggle={(v) => exploreState.togglePieValue(f.categorical, v)} onRemove={() => exploreState.removeViolinChart(f)} /> })), + ...clinicalCards(exploreCtx), + ...geneFacetCards(exploreCtx), + ...mutationTypeCards(exploreCtx), + ...assayCards(exploreCtx), + ...assayFreqCards(exploreCtx), + ...treatmentCards(exploreCtx), + ...studyCards(exploreCtx), + ...dataTypesCards(exploreCtx), + ...geneTableCards(exploreCtx), + ...specialCards(exploreCtx), + ]} /> }
} diff --git a/app/lab/partitions.tsx b/app/lab/partitions.tsx index c27faad9..3ed2d5b2 100644 --- a/app/lab/partitions.tsx +++ b/app/lab/partitions.tsx @@ -248,7 +248,7 @@ export function ChartMenu({ actions, label }: { actions: ChartAction[]; label: s return ( - + {actions.map((a) => )} diff --git a/app/lab/pick-list.tsx b/app/lab/pick-list.tsx index 620e253f..bd2ea345 100644 --- a/app/lab/pick-list.tsx +++ b/app/lab/pick-list.tsx @@ -47,7 +47,7 @@ export function VirtualRows({ items, rowKey, estimate, className, header, chi {header &&
{header}
}
{v.getVirtualItems().map((r) => ( -
+
{children(items[r.index], r.index)}
))} @@ -143,15 +143,13 @@ export function ValueList({ rows, onApply, why, hint, picks: shared, pct = fmtPc const bulk = listBulk(shown, picks.picked); const keys = useMemo(() => new Set(rows.map((r) => r.key)), [rows]); const live = picks.picked.filter((k) => keys.has(k)); - const max = Math.max(...rows.map((r) => r.n), 1); return <> r.key} estimate={VALROW_H} className={"vallist" + (extra ? " withextra" : "")} - header={}> + header={}> {(r) => ( {r.name} - {extra ? {typeof r.extra === "string" ? r.extra : fmtInt(r.extra ?? 0)} - : } + {extra && {typeof r.extra === "string" ? r.extra : fmtInt(r.extra ?? 0)}} {r.n.toLocaleString()} {r.share} diff --git a/lib/chart/format.ts b/lib/chart/format.ts index f2325f8f..5123fddd 100644 --- a/lib/chart/format.ts +++ b/lib/chart/format.ts @@ -17,6 +17,20 @@ export function fmtNum(n: number, sig = 3): string { return minus(trimZeros(n.toPrecision(sig))); } +/** + * An axis tick where room is short: from a thousand up, at most one decimal and K, M or B + * (10000 → "10K", 2500 → "2.5K", 1200000 → "1.2M"); below, as `below` writes it (the scale's own + * tick format, so 0.25 keeps its decimals). + */ +export function fmtCompactTick(v: number, below: (v: number) => string = fmtNum): string { + const a = Math.abs(v); + if (!(a >= 1e3) || !Number.isFinite(v)) return below(v); + // the smallest unit whose one-decimal value stays under 1000, so 999,999 reads "1M", not "1000K" + const units = [["K", 1e3], ["M", 1e6], ["B", 1e9]] as const; + const [u, d] = units.find(([, d]) => Math.round(a / d * 10) < 10000) ?? units[2]; + return minus(trimZeros((v / d).toFixed(1))) + u; +} + /** a percentage given as 0–100: one decimal, "<0.1%" for a sliver, never "0%" for something */ export function fmtPct(pct: number, decimals = 1): string { if (!Number.isFinite(pct)) return "–"; @@ -53,6 +67,16 @@ export function portalFreq(pct: number): string { return pct >= 0.1 ? pct.toFixed(1) + "%" : "<0.1%"; } +/** + * A pie slice's count, as cbioportal.org labels it (numeral `0.[0]a`, k and m upper-cased, + * STS-PIE-3): 312 → "312", 1,234 → "1.2K", 1,000 → "1K", 1,500,000 → "1.5M". + */ +export function portalPieCount(n: number): string { + const unit = Math.abs(n) >= 1e9 ? ["B", 1e9] as const : Math.abs(n) >= 1e6 ? ["M", 1e6] as const : Math.abs(n) >= 1e3 ? ["K", 1e3] as const : ["", 1] as const; + const v = Math.round((n / unit[1]) * 10) / 10; + return (Number.isInteger(v) ? String(v) : v.toFixed(1)) + unit[0]; +} + /** * An oncoprint track's altered percent, `100 * (altered / profiled)` as the portal computes it, as * its gutter and gap labels show it: OncoprintUtils percentAltered writes one decimal below 3% diff --git a/lib/study-view-config.ts b/lib/study-view-config.ts index 585b1db6..4094bc5b 100644 --- a/lib/study-view-config.ts +++ b/lib/study-view-config.ts @@ -72,7 +72,8 @@ export function chartBinSettings(all: Record | undefined, a /** * The portal's priorities for the charts that are not clinical attributes (`StudyViewConfig.ts` - * 131-170, STS-LY-8), by the selector of their card on Explore's grid. + * 131-170, STS-LY-8), by the selector of their card on Explore's grid; the grid orders by them + * (`orderCards`, lib/study-view-layout.ts). */ export const CARD_PRIORITY: readonly { selector: string; name: string; priority: number }[] = [ { selector: '[data-chart="datatypes"]', name: "Data Types", priority: 1000 }, // GENOMIC_PROFILES_SAMPLE_COUNT @@ -88,19 +89,5 @@ export const CARD_PRIORITY: readonly { selector: string; name: string; priority: { selector: '[data-chart="studies"]', name: "Cancer Studies", priority: 70 }, ]; -/** - * Every card's place on the grid, as the portal lays a page out on first load (STS-LY-3): by - * priority, highest first, then by name A–Z, clinical charts and the other kinds together. Each is - * a CSS `order`, negative so a card not ranked here (a chart the reader added: a gene, an assay - * entity) comes after them all, as the portal puts newly added charts last. - */ -export function cardOrders(clinical: { per: string; attribute: string; displayName?: string; priority?: number }[]): { selector: string; order: number }[] { - const cards = [ - ...clinical.map((c) => ({ selector: '[data-attr="' + (c.per + "|" + c.attribute).replace(/["\\]/g, "\\$&") + '"]', name: c.displayName || c.attribute, priority: c.priority ?? 0 })), - ...CARD_PRIORITY, - ].sort((a, b) => b.priority - a.priority || a.name.localeCompare(b.name)); - return cards.map((c, i) => ({ selector: c.selector, order: i - cards.length })); -} - /** whether Add chart offers an attribute: priority 0 is offered but hidden by default; below 0 it is dropped entirely (STS-LY-8) */ export const chartOffered = (priority: number | undefined): boolean => (priority ?? 0) >= 0; diff --git a/lib/study-view-layout.ts b/lib/study-view-layout.ts new file mode 100644 index 00000000..f633beb0 --- /dev/null +++ b/lib/study-view-layout.ts @@ -0,0 +1,95 @@ +/** + * The Study View's grid as the portal lays it out (STS-LY-1…3): cells of about 195 × 170 px with 7 px + * between them (the portal's 5, and 2 more), as many columns as fill the width, each chart a whole number of cells by its + * kind, placed in priority order into the first free spot (`calculateLayout` / `findSpot`, + * `StudyViewUtils.tsx`). + */ + +/** one cell, as the portal's (`StudyViewConfig.ts` layout), and the gap between cells and above and + * below the grid: 7 px, the portal's 5 and 2 more by the user's choice (2026-11-24) */ +export const GRID_CELL = { w: 195, h: 170, margin: 7 } as const; + +/** the narrowest a column may be stretched or squeezed to, filling the width */ +const MIN_CELL_W = 175; + +/** + * The columns for a grid `width` px wide, flush with both its sides (the user's choice, 2026-11-24): + * the count whose columns, stretched or squeezed to fill the width, come closest to the portal's + * 195 px, never under 175 px; at least one. + */ +export function gridCols(width: number): number { + const { w, margin } = GRID_CELL; + let cols = Math.max(1, Math.round((width + margin) / (w + margin))); + while (cols > 1 && cellWidth(width, cols) < MIN_CELL_W) cols--; + return cols; +} + +/** a column's width when `cols` of them, 7 px apart, fill `width` */ +export const cellWidth = (width: number, cols: number): number => (width - (cols - 1) * GRID_CELL.margin) / cols; + +/** what a card draws, as far as its size goes (STS-LY-2) */ +export type CardKind = + | "pie" // a categorical chart drawn as a pie + | "survival" + | "bar" // a numeric chart's histogram + | "list" // a categorical chart drawn as a table of values (the portal's pie-as-table) + | "table" // gene, treatment, frequency, case-list, data-type and study tables + | "density" + | "violin"; + +/** + * A card's size in cells, w × h, as the portal's defaults: a pie or survival chart 1×1, a bar + * chart 2×1, a table, the density and the violin 2×2; a categorical chart drawn as a table is + * 2×1 up to 4 rows and 2×2 past that (`StudyViewPageStore.ts:9152-9167`). + */ +export function chartCells(kind: CardKind, rows = 0): { w: number; h: number } { + switch (kind) { + case "pie": case "survival": return { w: 1, h: 1 }; + case "bar": return { w: 2, h: 1 }; + case "list": return rows <= 4 ? { w: 2, h: 1 } : { w: 2, h: 2 }; + default: return { w: 2, h: 2 }; + } +} + +/** a card to lay out: its key, its size in cells, and its rank (`priority` absent: a chart the reader added) */ +export type CardSpec = { key: string; w: number; h: number; name: string; priority?: number }; + +/** + * The portal's first-load order (STS-LY-3): the ranked cards by priority, highest first, then by + * name A–Z; then the cards the reader added, in the order they were added. + */ +export function orderCards(cards: T[]): T[] { + const ranked = cards.filter((c) => c.priority != null).sort((a, b) => b.priority! - a.priority! || a.name.localeCompare(b.name)); + return [...ranked, ...cards.filter((c) => c.priority == null)]; +} + +/** + * Each card, in order, in the first spot it fits: rows top to bottom, then left to right + * (`findSpot`). A card wider than the grid is narrowed to it. + */ +export function findSpotLayout(cards: { key: string; w: number; h: number }[], cols: number): { i: string; x: number; y: number; w: number; h: number }[] { + const taken: boolean[][] = []; + const free = (x: number, y: number, w: number, h: number) => { + for (let r = y; r < y + h; r++) for (let c = x; c < x + w; c++) if (taken[r]?.[c]) return false; + return true; + }; + return cards.map(({ key, w: w0, h }) => { + const w = Math.min(w0, cols); + let y = 0; + for (;; y++) { + for (let x = 0; x + w <= cols; x++) { + if (!free(x, y, w, h)) continue; + for (let r = y; r < y + h; r++) { taken[r] ??= []; for (let c = x; c < x + w; c++) taken[r][c] = true; } + return { i: key, x, y, w, h }; + } + } + }); +} + +/** + * A survival chart's title, as the portal's (STS-KM-1): "KM Plot: " + its status attribute's name + * without "status" or "survival" + " (months)", e.g. "KM Plot: Overall (months)". + */ +export function kmPlotTitle(statusName: string): string { + return "KM Plot: " + statusName.replace(/\b(status|survival)\b/gi, " ").replace(/\s+/g, " ").trim() + " (months)"; +} diff --git a/lib/study-view-pie.ts b/lib/study-view-pie.ts new file mode 100644 index 00000000..618c7bd6 --- /dev/null +++ b/lib/study-view-pie.ts @@ -0,0 +1,27 @@ +/** + * The Study View's pie chart as the portal draws it (STS-PIE-2, STS-PIE-3, STS-PIE-7): its size in + * its cell, which slices carry their count, and how a filtered chart greys the values it leaves out. + */ +import { GRID_CELL } from "./study-view-layout.ts"; + +/** a 1 × 1 card's chart area: the cell less its border, and less the 20 px header in height */ +export const PIE_AREA = { w: GRID_CELL.w - 2, h: GRID_CELL.h - 20 } as const; + +/** the pie's radius: min(w, h) / 2 − 20 */ +export const pieRadius = (w: number, h: number): number => Math.min(w, h) / 2 - 20; + +/** the pie is drawn 12 px above the area's centre */ +export const PIE_LIFT = 12; + +/** + * Whether a slice shows its count: always past a quarter of the pie; a smaller one only where the + * label fits, |tan(π·ratio/2)|·(r/5)·2 ≥ the label's width. + */ +export function pieLabelFits(ratio: number, radius: number, labelWidth: number): boolean { + return ratio > 0.25 || Math.abs(Math.tan((Math.PI * ratio) / 2)) * (radius / 5) * 2 >= labelWidth; +} + +/** an unselected value while the chart has a filter: grey at half opacity (selected ones keep their colour) */ +export const PIE_UNSELECTED = { fill: "#D3D3D3", opacity: 0.5 } as const; +/** a selected value's outline while the chart has a filter */ +export const PIE_SELECTED_STROKE = { color: "#cccccc", width: 3 } as const; diff --git a/lib/views/survival/figure.ts b/lib/views/survival/figure.ts index 9d26a2f1..307ccc76 100644 --- a/lib/views/survival/figure.ts +++ b/lib/views/survival/figure.ts @@ -12,15 +12,23 @@ import { seriesStyle, fmtInt, fmtMonths, fmtNum, label, textWidth, esc, FS, SW, type SvgOpts } from "../../svg-kit.ts"; -/** `single`: one colour for every curve, where a page draws one group as the portal does (the Study View's #2986E2) */ -export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: string): string { +/** + * `single`: one colour for every curve, where a page draws one group as the portal does (the Study + * View's #2986E2). `plotOnly`: the axes and curves alone, no legend, tests or caption, as the Study + * View's small KM chart draws them (STS-KM-3: its legend is in the tooltip; `curveSummary` writes it). + * `height`, with `plotOnly`: the figure's whole height, the plot taking what its x axis leaves, so + * the chart fills its card. + */ +export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: string, plotOnly = false, height?: number): string { const styleOf = (i: number) => single ? { color: single, dash: "" } : seriesStyle(i); const p = palette(o.theme), W = Math.max(360, o.width || 720); const curves = (v.curves || []) as KmCurve[]; const incidence = v.display === "incidence"; const { tMax, step } = survivalAxis(curves, { cutoffMonths: v.cutoffMonths, tickMonths: v.tickMonths }); - const T = 12, R = 16, PLOT = plotHeight(W); + const xTitle = "Months" + (v.anchoredTo ? " from " + v.anchoredTo : ""); + const T = 12, R = 16, below = bottomAxisHeight(xTitle) + 10; + const PLOT = plotOnly && height ? Math.max(60, height - T - below) : plotHeight(W); const yTitle = incidence ? "Cumulative incidence" : "Survival probability"; const ys = linear(0, 1, T + PLOT, T, { nice: false }); ys.ticks = [0, 0.25, 0.5, 0.75, 1]; @@ -33,7 +41,6 @@ export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: s const xs = linear(0, tMax, L, W - R, { nice: false }); xs.ticks = []; for (let t = 0; t <= tMax + 1e-9; t += step) xs.ticks.push(t); - const xTitle = "Months" + (v.anchoredTo ? " from " + v.anchoredTo : ""); const out: string[] = []; out.push(axisLeft(ys, L, p, { title: yTitle, gridTo: W - R, fmt: yFmt })); @@ -48,13 +55,11 @@ export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: s (st.dash ? ` stroke-dasharray="${st.dash}"` : "") + ` stroke-linejoin="round"/>`); }); - let y = T + PLOT + bottomAxisHeight(xTitle) + 10; + let y = T + PLOT + below; + if (plotOnly) return frame(W, y, out.join(""), p.bg, false, (incidence ? "Cumulative incidence" : "Kaplan–Meier") + " — " + curves.map((c) => c.cohort).join(", ")); if (risk) { const rt = riskTable(curves, xs, y, W, L, nameW, p, styleOf); out.push(rt.svg); y += rt.height + 8; } const items = curves.map((c, i) => ({ - label: c.cohort, color: styleOf(i).color, dash: styleOf(i).dash, kind: "line" as const, - detail: !c.n ? "no patients with data" : (incidence ? "50% incidence by " + (c.median == null ? "not reached" : fmtMonths(c.median)) - : "median " + (c.median == null ? "not reached" : portalMedianCi(c.median, c.medianCi?.lo ?? null, c.medianCi?.hi ?? null) + " mo")) + - " · n = " + fmtInt(c.n) + " · " + fmtInt(c.events) + " events" + label: c.cohort, color: styleOf(i).color, dash: styleOf(i).dash, kind: "line" as const, detail: curveSummary(c, incidence), })); const lg = legend(items, 8, y, W - 16, p, { grid: true }); out.push(lg.svg); @@ -70,6 +75,13 @@ export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: s return frame(W, y + cap.height + 8, out.join(""), p.bg, false, (incidence ? "Cumulative incidence" : "Kaplan–Meier") + " — " + curves.map((c) => c.cohort).join(", ")); } +/** a curve's legend line: its median (or 50% incidence) with its interval, its patients and its events */ +export function curveSummary(c: KmCurve, incidence = false): string { + return !c.n ? "no patients with data" : (incidence ? "50% incidence by " + (c.median == null ? "not reached" : fmtMonths(c.median)) + : "median " + (c.median == null ? "not reached" : portalMedianCi(c.median, c.medianCi?.lo ?? null, c.medianCi?.hi ?? null) + " mo")) + + " · n = " + fmtInt(c.n) + " · " + fmtInt(c.events) + " events"; +} + /** the tests, in words: the one the reader asked for and, where studies were pooled, the other */ function statLines(v: DrawnResultOf<"survival">): string[] { const lines: string[] = []; diff --git a/package-lock.json b/package-lock.json index bc989ea5..bc3ef450 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "radix-ui": "^1.8.1", "react": "^19", "react-dom": "^19", + "react-grid-layout": "2.3.0", "sharp": "^0.35.3", "streamdown": "^2.7.0", "svg2pdf.js": "^2.9.0", @@ -7834,6 +7835,12 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "license": "MIT" }, + "node_modules/fast-equals": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-4.0.3.tgz", + "integrity": "sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg==", + "license": "MIT" + }, "node_modules/fast-glob": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", @@ -8908,7 +8915,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, "license": "MIT" }, "node_modules/jscpd": { @@ -9554,6 +9560,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -11607,6 +11625,17 @@ "node": ">=6" } }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, "node_modules/property-information": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", @@ -11850,6 +11879,44 @@ "react": "^19.2.8" } }, + "node_modules/react-draggable": { + "version": "4.7.2", + "resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-4.7.2.tgz", + "integrity": "sha512-pmqDx72EqhMGoJe/x42ZO2wJ9TIz7qJ5OPnFu6lVWWznEuJumlSjR+J0V4tNyDFhUo6dVvv56FeiTqN+arTgnw==", + "license": "MIT", + "dependencies": { + "clsx": "^2.1.1", + "prop-types": "^15.8.1" + }, + "peerDependencies": { + "react": ">= 16.3.0", + "react-dom": ">= 16.3.0" + } + }, + "node_modules/react-grid-layout": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/react-grid-layout/-/react-grid-layout-2.3.0.tgz", + "integrity": "sha512-4ofzuR/MlYchp+ixDUVBxH6ybaw+JH51M+rpf675ik/++4Dn0Kax/Vf2Gv/7Z++mV1ZC7mY9UV2sRRycjGjKXQ==", + "license": "MIT", + "dependencies": { + "clsx": "^2.1.1", + "fast-equals": "^4.0.3", + "prop-types": "^15.8.1", + "react-draggable": "^4.4.6", + "react-resizable": "^3.2.0", + "resize-observer-polyfill": "^1.5.1" + }, + "peerDependencies": { + "react": ">= 16.3.0", + "react-dom": ">= 16.3.0" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, "node_modules/react-remove-scroll": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", @@ -11897,6 +11964,20 @@ } } }, + "node_modules/react-resizable": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/react-resizable/-/react-resizable-3.2.0.tgz", + "integrity": "sha512-3NKQ0SLZV7rs3LQHeXlOzDSRQfFrkX6TVet77/Qk03zqiZyee37b7N8/gwDJAA8UUjRz7PdWCCy49hcso45SMQ==", + "license": "MIT", + "dependencies": { + "prop-types": "15.x", + "react-draggable": "^4.5.0" + }, + "peerDependencies": { + "react": ">= 16.3", + "react-dom": ">= 16.3" + } + }, "node_modules/react-style-singleton": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", @@ -12106,6 +12187,12 @@ "node": ">=0.10.0" } }, + "node_modules/resize-observer-polyfill": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz", + "integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==", + "license": "MIT" + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", diff --git a/package.json b/package.json index 9d95fbab..de7d34c1 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,7 @@ "radix-ui": "^1.8.1", "react": "^19", "react-dom": "^19", + "react-grid-layout": "2.3.0", "sharp": "^0.35.3", "streamdown": "^2.7.0", "svg2pdf.js": "^2.9.0", diff --git a/test/compact-tick-format.test.ts b/test/compact-tick-format.test.ts new file mode 100644 index 00000000..b3a3e6c6 --- /dev/null +++ b/test/compact-tick-format.test.ts @@ -0,0 +1,15 @@ +// An axis tick where room is short (lib/chart/format.ts fmtCompactTick): thousands as K, M, B. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { fmtCompactTick } from "../lib/chart/format.ts"; + +test("fmtCompactTick: K, M, B from a thousand, one decimal at most; below that the scale's own format", () => { + const cases: [number, string][] = [ + [0, "0"], [999, "999"], [1000, "1K"], [2000, "2K"], [2500, "2.5K"], [10000, "10K"], [12345, "12.3K"], + [999_999, "1M"], [999_400, "999.4K"], [1_000_000, "1M"], [1_200_000, "1.2M"], [3e9, "3B"], [-4000, "−4K"], + ]; + for (const [v, want] of cases) assert.equal(fmtCompactTick(v), want, String(v)); + // below a thousand, the formatter it is given + assert.equal(fmtCompactTick(0.2, (v) => v.toString() + "!"), "0.2!"); + assert.equal(fmtCompactTick(5000, () => "unused"), "5K"); +}); diff --git a/test/e2e/explore.cjs b/test/e2e/explore.cjs index 32ff6833..420f1633 100644 --- a/test/e2e/explore.cjs +++ b/test/e2e/explore.cjs @@ -43,22 +43,14 @@ async function explore({ ok, BASE, page, browser }) { scrolls: l.scrollHeight > l.clientHeight + 2, capped: [...l.querySelectorAll("span")].some(s2 => /showing .* of .* values/.test(s2.textContent || "")) })).sort((a, b) => b.rows - a.rows)[0]; - return { lists: lists.length, big, bars: document.querySelectorAll(".vbar").length }; + return { lists: lists.length, big, bars: document.querySelectorAll(".vbar, .gbar, .sbrow .bar").length }; }); ok("categorical values are shown in full, scrolled rather than trimmed", !!vals.big && vals.big.rows > 20 && vals.big.scrolls, vals.big ? vals.big.rows + " values in the largest list, scrolls=" + vals.big.scrolls + (vals.big.capped ? ", cap disclosed" : "") : "no value lists"); - // the proportion rules are a hint, not a chart — guard against them growing - const barBox = await page.evaluate(() => { - const b2 = document.querySelector(".valrow .vbar"); - if (!b2) return null; - const r = b2.getBoundingClientRect(); - return { h: Math.round(r.height), w: Math.round(r.width) }; - }); - // 8px + a 1px border each side: a hint at relative size, not a chart - ok("value bars stay small", !!vals.bars && !!barBox && barBox.h <= 10 && barBox.w <= 80, - barBox ? vals.bars + " bars, " + barBox.w + "x" + barBox.h + "px" : "no bars found"); + // the Study View's lists draw no bar per row + ok("value lists draw no bar per row", vals.bars === 0, vals.bars + " row bars"); // The grid draws the checked attributes of "+ Add chart" > Clinical, and until the // reader changes them those are cBioPortal's default: the first 20 with a priority @@ -110,7 +102,7 @@ async function explore({ ok, BASE, page, browser }) { await page.waitForSelector("[data-attr]", { timeout: 120000 }); await page.waitForTimeout(1500); const before = await facetShapes(); - const key = page.locator(".pielegend .pikey").first(); + const key = page.locator(".pie .slice").first(); if (await key.count()) { await key.click(); await page.waitForTimeout(6000); @@ -307,7 +299,7 @@ async function explore({ ok, BASE, page, browser }) { const before = await top(); await page.locator(".driverchoice").click(); await page.getByRole("option", { name: "Alterations: OncoKB drivers only" }).click(); - await page.waitForFunction(() => /OncoKB drivers/.test(document.querySelector("[data-genetable=mutated]")?.textContent || ""), null, { timeout: 240000 }); + await page.locator("[data-genetable=mutated][data-drivers]").waitFor({ timeout: 240000 }); const after = await top(), url = new URL(page.url()).searchParams.get("drivers"); const egfr = table.locator(".generow", { has: page.locator(".gname", { hasText: /^EGFR$/ }) }).first(); const counted = Number((await egfr.locator(".gnum").nth(1).innerText()).replace(/,/g, "")); @@ -489,7 +481,7 @@ async function explore({ ok, BASE, page, browser }) { let dtDetail = "", dtOk = false; try { await page.goto(BASE + "/lab?tab=explore&study=luad_tcga_pan_can_atlas_2018", { waitUntil: "domcontentloaded" }); - const card = page.locator(".card", { has: page.locator("h2", { hasText: "Data types" }) }); + const card = page.locator("[data-chart=datatypes]"); await card.locator(".dtrow").first().waitFor({ timeout: 240000 }); const rows = await card.locator(".dtrow").evaluateAll((els) => els.map((e) => [...e.querySelectorAll(".gcount")].map((s) => s.textContent.trim()))); const top = Number(rows[0][0].replace(/,/g, "")); @@ -615,7 +607,7 @@ async function explore({ ok, BASE, page, browser }) { const filtered = () => page.evaluate(() => /patients match/.test(document.querySelector(".exbar")?.textContent || "")); await drag(); await page.waitForFunction(() => /patients match/.test(document.querySelector(".exbar")?.textContent || ""), null, { timeout: 240000 }); - const meta = (await card.locator(".meta").first().innerText()).trim(); + const meta = ((await card.locator(".xc-title").getAttribute("data-tip")) || "").trim(); const pills = (await page.locator(".svpills").innerText().catch(() => "")).replace(/\s+/g, " "); const draggedFilters = await filtered(); await card.locator("[data-chart-reset]").click(); @@ -697,13 +689,13 @@ async function explore({ ok, BASE, page, browser }) { const counts = (await pt.locator(".valrow .vn").allInnerTexts()).map((t) => Number(t.replace(/,/g, ""))); const ordered = counts.every((n, i) => i === 0 || counts[i - 1] >= n); const pick = (await pt.locator(".valrow .vname").allInnerTexts())[0]; - const before = (await st.locator(".facettitle").textContent()).trim(); // as the wait below reads it + const before = (await st.locator(".facettitle").getAttribute("data-tip")) || ""; // as the wait below reads it await pt.locator(".valrow").first().click(); await pt.getByRole("button", { name: "Apply filter" }).click(); await page.waitForFunction((a) => document.body.innerText.includes("treated with " + a), pick, { timeout: 240000 }); - await page.waitForFunction((b) => (document.querySelector("[data-treatments='sample'] .facettitle")?.textContent || "").trim() !== b, before, { timeout: 240000 }); + await page.waitForFunction((b) => (document.querySelector("[data-treatments='sample'] .facettitle")?.getAttribute("data-tip") || "") !== b, before, { timeout: 240000 }); const pinned = await pt.locator(".valrow.on .vname").allInnerTexts(); - const after = (await st.locator(".facettitle").textContent()).trim(); + const after = (await st.locator(".facettitle").getAttribute("data-tip")) || ""; txDetail = JSON.stringify({ rows: counts.length, pick, pinned, before, after }); txOk = counts.length > 1 && ordered && pinned.length === 1 && pinned[0] === pick && after !== before; } catch (e) { txDetail = String(e.message).split("\n")[0]; } diff --git a/test/study-view-chart-files.test.ts b/test/study-view-chart-files.test.ts index 22a27718..93cc3f65 100644 --- a/test/study-view-chart-files.test.ts +++ b/test/study-view-chart-files.test.ts @@ -57,3 +57,12 @@ test("STS-KM-2: the Study View's curve in the portal's #2986E2, its risk-table k const plain = survivalSvg({ kind: "survival", curves: [curve] } as never, { width: 480, theme: "light" }); assert.ok(strokes(plain).every((c) => c === SERIES[0])); }); + +test("survivalSvg plot-only at a height: the figure is that tall, whatever its width", () => { + const curve: KmCurve = { cohort: "Selected", points: [{ t: 0, s: 1 } as never, { t: 40, s: 0.5 } as never], median: 40, n: 10, events: 5, tLast: 40 }; + const tall = (svg: string) => Number(/viewBox="0 0 [\d.]+ ([\d.]+)"/.exec(svg)?.[1]); + for (const h of [220, 300]) assert.equal(tall(survivalSvg({ kind: "survival", curves: [curve] } as never, { width: 381 }, PORTAL_STUDY_VIEW_KM, true, h)), h); + // without plotOnly the height is ignored: the full figure keeps its own + const full = survivalSvg({ kind: "survival", curves: [curve] } as never, { width: 381 }, PORTAL_STUDY_VIEW_KM, false); + assert.equal(tall(survivalSvg({ kind: "survival", curves: [curve] } as never, { width: 381 }, PORTAL_STUDY_VIEW_KM, false, 220)), tall(full)); +}); diff --git a/test/study-view-config.test.ts b/test/study-view-config.test.ts index 25c489cb..86a753c9 100644 --- a/test/study-view-config.test.ts +++ b/test/study-view-config.test.ts @@ -3,7 +3,8 @@ // with a priority above 0 in priority then name order, less the charts with a single value. import { test, describe } from "node:test"; import assert from "node:assert/strict"; -import { chartBinSettings, chartPriority, chartOrder, defaultChartKeys, shouldShowChart, DEFAULT_CLINICAL_CHARTS, cardOrders, chartOffered } from "../lib/study-view-config.ts"; +import { chartBinSettings, chartPriority, chartOrder, defaultChartKeys, shouldShowChart, DEFAULT_CLINICAL_CHARTS, CARD_PRIORITY, chartOffered } from "../lib/study-view-config.ts"; +import { orderCards } from "../lib/study-view-layout.ts"; test("the portal's table replaces a priority of exactly 1, and only that", () => { assert.equal(chartPriority("SEX", 1), 9); @@ -66,22 +67,21 @@ describe("a chart's starting bins (initialBins)", () => { // STS-LY-3, STS-LY-8: one order for every card, clinical and other kinds together test("cards are placed by the portal's priorities, then name; a chart not ranked comes after them all", () => { const clinical = [ - { per: "patient", attribute: "AGE", displayName: "Diagnosis Age", priority: 9 }, - { per: "sample", attribute: "CANCER_TYPE_DETAILED", displayName: "Cancer Type Detailed", priority: 2000 }, - { per: "patient", attribute: "SEX", displayName: "Sex", priority: 9 }, - { per: "sample", attribute: "MUTATION_COUNT", displayName: "Mutation Count", priority: 30 }, + { key: '[data-attr="patient|AGE"]', name: "Diagnosis Age", priority: 9 }, + { key: '[data-attr="sample|CANCER_TYPE_DETAILED"]', name: "Cancer Type Detailed", priority: 2000 }, + { key: '[data-attr="patient|SEX"]', name: "Sex", priority: 9 }, + { key: '[data-attr="sample|MUTATION_COUNT"]', name: "Mutation Count", priority: 30 }, ]; - const order = cardOrders(clinical); - const rank = (sel: string) => order.findIndex((o) => o.selector === sel); + const cards = [{ key: "added", name: "A gene chart" }, ...clinical, ...CARD_PRIORITY.map((c) => ({ key: c.selector, name: c.name, priority: c.priority }))] + .map((c) => ({ ...c, w: 1, h: 1 })); + const order = orderCards(cards).map((c) => c.key); const seq = ['[data-attr="sample|CANCER_TYPE_DETAILED"]', '[data-special="caselists"]', '[data-chart="datatypes"]', '[data-chart="survival"]', '[data-chart="mutcount-fga"]', '[data-genetable="mutated"]', '[data-genetable="sv"]', '[data-genetable="cna"]', '[data-chart="studies"]', '[data-attr="sample|MUTATION_COUNT"]', '[data-attr="patient|AGE"]', '[data-attr="patient|SEX"]']; // 2000, then the two 1000s by name (Case Lists, Data Types), survival 400, density 200, the gene // tables 90 / 85 / 80 (SV before CNA), studies 70, then the 30 and the two 9s by name - assert.deepEqual(seq.map(rank), [...seq.map(rank)].sort((a, b) => a - b), "in the portal's order"); - assert.ok(order.every((o) => o.order < 0), "an unranked card (order 0) comes after every ranked one"); - assert.equal(new Set(order.map((o) => o.order)).size, order.length); - assert.equal(cardOrders([{ per: "patient", attribute: 'A"B', priority: 1 }]).find((o) => o.selector.includes("A"))!.selector, '[data-attr="patient|A\\"B"]', "a quote in an id is escaped"); + assert.deepEqual(seq.map((k) => order.indexOf(k)), [...seq.map((k) => order.indexOf(k))].sort((x, y) => x - y), "in the portal's order"); + assert.equal(order[order.length - 1], "added", "an unranked card comes after every ranked one"); }); test("Add chart drops an attribute of priority below 0, and offers 0 (hidden by default)", () => { diff --git a/test/study-view-layout.test.ts b/test/study-view-layout.test.ts new file mode 100644 index 00000000..3e7936c0 --- /dev/null +++ b/test/study-view-layout.test.ts @@ -0,0 +1,72 @@ +// The Study View grid (STS-LY-1…3), from docs/legacy-spec/30-study-summary.md §1. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { GRID_CELL, cellWidth, chartCells, findSpotLayout, gridCols, kmPlotTitle, orderCards } from "../lib/study-view-layout.ts"; + +test("LY-1: a 195 × 170 cell, 7 px apart (the portal's 5, and 2 more)", () => { + assert.deepEqual(GRID_CELL, { w: 195, h: 170, margin: 7 }); + assert.equal(Math.round(cellWidth(1395, 7)), 193); // 7 columns, 6 gaps of 7, fill 1395 + assert.equal(cellWidth(195, 1), 195); +}); + +test("LY-1: the columns that fill the width with cells closest to 195 px, never under 175, at least one", () => { + const cases: [number, number][] = [ + [1395, 7], // a 1440 px window: 193 px cells (6 would be 226) + [1555, 8], // 1600: 188.4 (7 would be 216) + [1407, 7], // 195 exactly + [1205, 6], // 195 exactly + [1306, 7], // 6.5 cells' worth rounds up to 7 at 180.6; ties go up + [1305, 6], // just under the half: 6 at 211.7 + [500, 2], // round gives 2.5→3 at 162, under 175: 2 at 246.5 + [195, 1], [100, 1], [0, 1], + ]; + for (const [w, cols] of cases) assert.equal(gridCols(w), cols, w + " px"); + for (const w of [400, 700, 1000, 1395, 1900, 2500]) assert.ok(cellWidth(w, gridCols(w)) >= 175 || gridCols(w) === 1, w + " px"); +}); + +test("LY-2: each kind's default size", () => { + assert.deepEqual(chartCells("pie"), { w: 1, h: 1 }); + assert.deepEqual(chartCells("survival"), { w: 1, h: 1 }); + assert.deepEqual(chartCells("bar"), { w: 2, h: 1 }); + assert.deepEqual(chartCells("table"), { w: 2, h: 2 }); + assert.deepEqual(chartCells("density"), { w: 2, h: 2 }); + assert.deepEqual(chartCells("violin"), { w: 2, h: 2 }); + // Cancer Type Detailed: 3 rows 395 × 170, 6+ rows 395 × 345 + assert.deepEqual(chartCells("list", 3), { w: 2, h: 1 }); + assert.deepEqual(chartCells("list", 4), { w: 2, h: 1 }); + assert.deepEqual(chartCells("list", 5), { w: 2, h: 2 }); +}); + +test("LY-3: by priority, then name; the reader's charts last, as added", () => { + const cards = [ + { key: "added2", w: 1, h: 1, name: "B" }, { key: "age", w: 2, h: 1, name: "Diagnosis Age", priority: 9 }, + { key: "added1", w: 1, h: 1, name: "A" }, { key: "sex", w: 1, h: 1, name: "Sex", priority: 9 }, + { key: "ct", w: 2, h: 2, name: "Cancer Type", priority: 3000 }, + ]; + assert.deepEqual(orderCards(cards).map((c) => c.key), ["ct", "age", "sex", "added2", "added1"]); +}); + +test("LY-3: each card in the first free spot, rows top-down then left-right", () => { + const layout = findSpotLayout([ + { key: "a", w: 2, h: 2 }, { key: "b", w: 2, h: 1 }, { key: "c", w: 1, h: 1 }, { key: "d", w: 2, h: 2 }, { key: "e", w: 1, h: 1 }, + ], 5); + assert.deepEqual(layout, [ + { i: "a", x: 0, y: 0, w: 2, h: 2 }, + { i: "b", x: 2, y: 0, w: 2, h: 1 }, + { i: "c", x: 4, y: 0, w: 1, h: 1 }, + { i: "d", x: 2, y: 1, w: 2, h: 2 }, // the first row with room for 2 × 2 + { i: "e", x: 4, y: 1, w: 1, h: 1 }, // back-fills the hole beside it + ]); +}); + +test("LY-3: a card wider than the grid is narrowed to it", () => { + assert.deepEqual(findSpotLayout([{ key: "t", w: 2, h: 2 }, { key: "p", w: 1, h: 1 }], 1), + [{ i: "t", x: 0, y: 0, w: 1, h: 2 }, { i: "p", x: 0, y: 2, w: 1, h: 1 }]); +}); + +test("KM-1: a survival chart's title from its status attribute's name", () => { + assert.equal(kmPlotTitle("Overall Survival Status"), "KM Plot: Overall (months)"); + assert.equal(kmPlotTitle("Disease Free Status"), "KM Plot: Disease Free (months)"); + assert.equal(kmPlotTitle("Disease-specific Survival status"), "KM Plot: Disease-specific (months)"); + assert.equal(kmPlotTitle("Progression Free Status"), "KM Plot: Progression Free (months)"); +}); diff --git a/test/study-view-pie.test.ts b/test/study-view-pie.test.ts new file mode 100644 index 00000000..2329e5eb --- /dev/null +++ b/test/study-view-pie.test.ts @@ -0,0 +1,32 @@ +// The Study View pie (STS-PIE-2, STS-PIE-3, STS-PIE-7), from docs/legacy-spec/30-study-summary.md §3. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { PIE_AREA, PIE_UNSELECTED, pieLabelFits, pieRadius } from "../lib/study-view-pie.ts"; +import { portalPieCount } from "../lib/chart/format.ts"; + +test("PIE-2: a 1 × 1 card's pie, radius min(w, h) / 2 − 20", () => { + assert.deepEqual(PIE_AREA, { w: 193, h: 150 }); + assert.equal(pieRadius(PIE_AREA.w, PIE_AREA.h), 55); +}); + +test("PIE-3: a slice past a quarter always shows its count; a smaller one only where it fits", () => { + assert.equal(pieLabelFits(0.26, 55, 500), true); + assert.equal(pieLabelFits(0.25, 55, 500), false, "a quarter exactly is held to the fit"); + // tan(π·0.1/2)·(55/5)·2 = 3.48 px: no room for a label + assert.equal(pieLabelFits(0.1, 55, 10), false); + // tan(π·0.2/2)·22 = 7.15 + assert.equal(pieLabelFits(0.2, 55, 7), true); + assert.equal(pieLabelFits(0.2, 55, 8), false); +}); + +test("PIE-3: the count as numeral 0.[0]a, upper-cased", () => { + assert.equal(portalPieCount(312), "312"); + assert.equal(portalPieCount(1234), "1.2K"); + assert.equal(portalPieCount(1000), "1K"); + assert.equal(portalPieCount(1500000), "1.5M"); + assert.equal(portalPieCount(0), "0"); +}); + +test("PIE-7: values left out of the chart's filter are grey at half opacity", () => { + assert.deepEqual(PIE_UNSELECTED, { fill: "#D3D3D3", opacity: 0.5 }); +});