From cf98f932e14fdeb79b628e750b6e6ff6553f9f8a Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Fri, 20 Nov 2026 16:29:08 +0000 Subject: [PATCH 01/17] =?UTF-8?q?Study=20View:=20the=20portal's=20grid,=20?= =?UTF-8?q?with=20its=20own=20library=20(react-grid-layout):=20195=20?= =?UTF-8?q?=C3=97=20170=20cells,=20each=20chart=20a=20whole=20number=20of?= =?UTF-8?q?=20them=20(STS-LY-1=E2=80=A63)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every card on Explore's Summary is placed as the portal places it: cells of 195 × 170 px, 5 px apart, floor((window − 40) / 200) columns, the grid centred at cols·195 + (cols+1)·5. Each card takes the portal's default size for its kind (a pie 1×1, a bar chart 2×1, a table, density or violin 2×2, a table of values 2×1 up to 4 rows), and goes in priority order into the first free spot (findSpot), the reader's added charts last. No drag or resize. The survival card stays one card with an endpoint picker, at 2×2. Categorical charts drawn as value lists take the portal's pie-as-table size. Draft: not to be merged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 46 +++++------- app/lab/explore-charts.tsx | 32 ++++++--- app/lab/explore-grid.tsx | 58 ++++++++++++++++ app/lab/explore-sections.tsx | 123 +++++++++++++++++++-------------- app/lab/page.tsx | 61 ++++++++-------- lib/study-view-config.ts | 17 +---- lib/study-view-layout.ts | 76 ++++++++++++++++++++ package-lock.json | 89 +++++++++++++++++++++++- package.json | 1 + test/study-view-config.test.ts | 22 +++--- test/study-view-layout.test.ts | 59 ++++++++++++++++ 11 files changed, 436 insertions(+), 148 deletions(-) create mode 100644 app/lab/explore-grid.tsx create mode 100644 lib/study-view-layout.ts create mode 100644 test/study-view-layout.test.ts diff --git a/app/globals.css b/app/globals.css index ed8e9b488..11a364d18 100644 --- a/app/globals.css +++ b/app/globals.css @@ -222,31 +222,19 @@ 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: center; } +.svgrid { flex: none; } +.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: center; } .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: 0.3rem 0.5rem; border-radius: var(--r-md, 4px); } +/* 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; } .chk { display: flex; gap: 0.4rem; align-items: center; } .chk input { width: auto; } .qdesc { @@ -300,7 +288,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); } @@ -691,9 +679,9 @@ 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; } +.svcell > .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; } +.svcell > .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 +1201,9 @@ 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; } +.svcell > .card > div:first-child { padding-right: 1.8rem; } +.svcell > .card .chartgear { position: absolute; top: 0.45rem; right: 0.5rem; } .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); } diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index 4bc6be579..09dfddb75 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -5,6 +5,8 @@ // 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 { cardRank, type GridCard } from "./explore-grid.tsx"; +import { chartCells } from "../../lib/study-view-layout.ts"; import { api } from "./api.ts"; import { Choice } from "../_ui/choice.tsx"; import { Button } from "../_ui/button"; @@ -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 }: 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,9 +107,6 @@ 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 && ( @@ -113,10 +133,6 @@ export function ExploreCharts({ studies, selection, draft, attrs, endpoints, add )} - {shown.map(({ pair, added }) => ( - onRemovePair(pair) : undefined} onClear={onClearDensity ? () => onClearDensity(pair) : undefined} /> - ))} ; } diff --git a/app/lab/explore-grid.tsx b/app/lab/explore-grid.tsx new file mode 100644 index 000000000..5d3732362 --- /dev/null +++ b/app/lab/explore-grid.tsx @@ -0,0 +1,58 @@ +"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: 195 × 170 px cells 5 px apart, as many columns as the page holds, + * 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 { useEffect, useMemo, useState, 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, gridWidth, 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]; + +/** the window's width, followed as it resizes (`fallback` before the first read) */ +function useWindowWidth(fallback: number): number { + const [w, setW] = useState(null); + useEffect(() => { + const read = () => setW(window.innerWidth); + read(); + window.addEventListener("resize", read); + return () => window.removeEventListener("resize", read); + }, []); + return w ?? fallback; +} + +export function StudyViewGrid({ cards }: { cards: GridCard[] }) { + // measured only to know the page has laid out; the columns follow the window, as the portal's + const { width, containerRef, mounted } = useContainerWidth({ measureBeforeMount: true }); + const windowWidth = useWindowWidth(width); + const cols = gridCols(windowWidth); + 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 cbd97b439..5efca12ae 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -22,6 +22,8 @@ import { barFigureSvg, pieFigureSvg, type FigureBar, type PieSlice } from "../.. 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 { 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"; @@ -836,13 +838,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 @@ -1194,13 +1198,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 }) { @@ -1240,10 +1247,10 @@ function AssayFreqTable({ t, ctx }: { t: NonNullable - {(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 }) { @@ -1317,16 +1324,16 @@ function AssayFacet({ f, ctx }: { f: NonNullable - {(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 @@ -1355,19 +1362,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. @@ -1387,27 +1393,26 @@ export function TreatmentTables({ ctx }: { ctx: ExploreCtx }) {

); }; - 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" : ""}} @@ -1427,12 +1432,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.

}
- ); - })} - ; + ) }; + }); } -export function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { +/** 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: }] : []; +} + +function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { const { exStudies, setExploreStudies } = ctx; const explore = ctx.explore!; const picks = usePicks(); @@ -1473,7 +1489,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(); @@ -1530,9 +1546,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 */ @@ -1710,7 +1729,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,16 +1738,16 @@ 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 &&
+ 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 &&
+
}] : []), + ...(shown.caseLists ? [{ key: "caselists", ...cardRank('[data-special="caselists"]'), ...chartCells("table"), node:

Case Lists

limitRefusal(ids.length, ANY_LEAF_LIMIT, "alternatives")} @@ -1736,6 +1755,6 @@ export function EventsAndCaseLists({ ctx }: { ctx: ExploreCtx }) { 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/page.tsx b/app/lab/page.tsx index 299a0625b..9f415c69e 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"; @@ -39,8 +41,7 @@ import { DrawAtWidth } 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,36 @@ 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 }, { 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) => ({ + 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/lib/study-view-config.ts b/lib/study-view-config.ts index 585b1db6e..4094bc5b2 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 000000000..b7294f4d7 --- /dev/null +++ b/lib/study-view-layout.ts @@ -0,0 +1,76 @@ +/** + * The Study View's grid as the portal lays it out (STS-LY-1…3): a cell of 195 × 170 px with 5 px + * between cells, as many columns as the width holds, 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, and the gap between cells and around the grid (`StudyViewConfig.ts` layout) */ +export const GRID_CELL = { w: 195, h: 170, margin: 5 } as const; + +/** the grid's width in px for `cols` columns: cols·195 + (cols+1)·5 */ +export const gridWidth = (cols: number): number => cols * GRID_CELL.w + (cols + 1) * GRID_CELL.margin; + +/** the columns for a window `windowWidth` px wide, as the portal counts them: floor((window − 40) / 200), at least one */ +export function gridCols(windowWidth: number): number { + return Math.max(1, Math.floor((windowWidth - 40) / (GRID_CELL.w + GRID_CELL.margin))); +} + +/** 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 }; + } + } + }); +} diff --git a/package-lock.json b/package-lock.json index bc989ea51..bc3ef450a 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 9d95fbab9..de7d34c1e 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/study-view-config.test.ts b/test/study-view-config.test.ts index 25c489cbb..86a753c91 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 000000000..4fa6b7bd2 --- /dev/null +++ b/test/study-view-layout.test.ts @@ -0,0 +1,59 @@ +// 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, chartCells, findSpotLayout, gridCols, gridWidth, orderCards } from "../lib/study-view-layout.ts"; + +test("LY-1: a 195 × 170 cell, 5 px apart; the grid cols·195 + (cols+1)·5 wide", () => { + assert.deepEqual(GRID_CELL, { w: 195, h: 170, margin: 5 }); + assert.equal(gridWidth(6), 1205); + assert.equal(gridWidth(1), 205); +}); + +test("LY-1: floor((window − 40) / 200) columns, at least one", () => { + assert.equal(gridCols(1280), 6); + assert.equal(gridCols(1440), 7); + assert.equal(gridCols(1920), 9); + assert.equal(gridCols(1239), 5); + assert.equal(gridCols(1240), 6); + assert.equal(gridCols(200), 1); +}); + +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 }]); +}); From 23c74b3098223f8c46bb7cbff84573f6c3a80627 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Fri, 20 Nov 2026 16:38:32 +0000 Subject: [PATCH 02/17] Study View cards: one title treatment, one line, and only the portal's text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every card's title is drawn alike, as the portal's (STS-HD-1): its name only, bold and centred, on one 20 px line, a long one cut with an ellipsis. Text the portal does not show in a card moves into the title's tooltip (what a chart counts, its level, the selection a density drag holds) or goes (the min · median · max line and its median chips, the gene tables' gene counts, a list's 'scroll for more'). The survival card's title is the portal's "KM Plot: Overall (months)" (kmPlotTitle), drawn without the risk table; Data Types, Case Lists and the other tables no longer use the upper-case section heading. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 14 +++++++ app/lab/explore-charts.tsx | 16 ++++---- app/lab/explore-sections.tsx | 70 +++++++++------------------------- app/lab/explore-violin.tsx | 3 +- app/lab/page.tsx | 3 +- lib/study-view-layout.ts | 8 ++++ test/e2e/explore.cjs | 10 ++--- test/study-view-layout.test.ts | 9 ++++- 8 files changed, 65 insertions(+), 68 deletions(-) diff --git a/app/globals.css b/app/globals.css index 11a364d18..4528e4fc9 100644 --- a/app/globals.css +++ b/app/globals.css @@ -235,6 +235,20 @@ pre { /* 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; } +/* Every card's title alike, as the portal's (STS-HD-1): its name only, bold and centred, on one line, + a long one cut with an ellipsis (the whole of it, and what it counts, in its tooltip). A header row + that also holds controls keeps them on that line and gives the title the rest. */ +.svcell :is(.facettitle, .xc-title) { + font-size: var(--t-md); font-weight: 600; line-height: 20px; color: var(--ink); text-transform: none; letter-spacing: 0; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; min-width: 0; margin: 0; +} +.svcell .xc-head { flex-wrap: nowrap; gap: 0.3rem; } +.svcell .xc-head > .xc-title { flex: 1 1 0; } +.svcell [data-genetable] > .row:first-child { flex-wrap: nowrap; align-items: center; } +.svcell [data-genetable] > .row:first-child > .facettitle { flex: 1 1 0; } +.svcell .charticon svg { width: 0.85rem; height: 0.85rem; } +.svcell .titleicon { display: inline-flex; align-items: center; justify-content: center; height: 20px; width: 20px; vertical-align: top; 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 { diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index 09dfddb75..bdafc5e4a 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -5,8 +5,9 @@ // 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 } from "../../lib/study-view-layout.ts"; +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"; @@ -79,7 +80,7 @@ export function exploreChartCards(props: Props): GridCard[] { ]; } -function SurvivalCard({ studies, selection, draft, endpoints, km }: Props) { +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); @@ -112,7 +113,7 @@ function SurvivalCard({ studies, selection, draft, endpoints, km }: Props) { {ep && (
- {ep === "OS" ? "Overall survival" : ep + " survival"} of the selection + {kmPlotTitle(attrs.find((a) => a.attribute === ep + "_STATUS")?.displayName || ep + " Status")} setFileError((cur) => update(cur))), @@ -185,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) => ({ diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index 5efca12ae..f81c087ce 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -43,7 +43,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"; @@ -617,8 +616,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 @@ -874,15 +871,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 }; @@ -968,11 +959,9 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin }} /> {(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} ); } return ( @@ -1033,11 +1022,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)} />}
@@ -1226,13 +1210,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 ?
- {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), @@ -1285,7 +1269,6 @@ function AssayFacet({ f, ctx }: { f: NonNullable unchartAssay(f.profileType, f.entity)}>
- {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 && <> - - - } -
}
); } @@ -1334,9 +1310,8 @@ export function geneFacetCards(ctx: ExploreCtx): GridCard[] { const states = f.type === "CNA" && !explore.drivers ? f.states.filter((st) => st.n > 0) : f.states; 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 @@ -1382,7 +1357,7 @@ export function treatmentCards(ctx: ExploreCtx): GridCard[] { const on = new Set(appliedTreatmentKeys(draft, level)); return (
-
{title}{meta}
+
{title}
{leftOut} {rows.length ? 0; 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"}. @@ -1459,7 +1433,7 @@ 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) => ( 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]; @@ -1611,9 +1585,7 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore return (
-

{title}

- {drivers && OncoKB drivers} - +
{title}
setGeneFilter({ ...geneFilter, [kind]: e.target.value })} /> @@ -1679,9 +1651,6 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore ); }} - {needle - ? rows.length.toLocaleString() + " of " + all.length.toLocaleString() + " genes match" - : all.length.toLocaleString() + " genes"} {(() => { const n = picks.picked.length; const refusal = op === "intersection" && n > 1 ? intersectionRefusal(draftClauses.length, n) : null; @@ -1740,7 +1709,7 @@ export function specialCards(ctx: ExploreCtx): GridCard[] { const anyOf = (ls: any[]) => { if (ls.length) addClause(ls.length === 1 ? ls[0] : { any: ls }); }; return [ ...(shown.events ? [{ key: "events", ...cardRank('[data-special="events"]'), ...chartCells("table"), node:
-

Timeline Events Availability

+
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), @@ -1748,13 +1717,12 @@ export function specialCards(ctx: ExploreCtx): GridCard[] { onApply={(types) => anyOf(types.map((t) => ({ kind: "event", a: { eventType: t }, rel: { type: "NONE" } })))} />
}] : []), ...(shown.caseLists ? [{ key: "caselists", ...cardRank('[data-special="caselists"]'), ...chartCells("table"), node:
-

Case Lists

+
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 c04bd9dad..cc415c267 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/page.tsx b/app/lab/page.tsx index 9f415c69e..f670b6cf3 100644 --- a/app/lab/page.tsx +++ b/app/lab/page.tsx @@ -671,7 +671,8 @@ export default function AnalysisPage() { 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]} />, + addClauses: exploreState.addDensitySelection, // the portal's study-view KM has no risk table (STS-KM-3) + km: (curves) => survivalSvg({ kind: "survival", curves: (curves as any[]).map((c) => ({ ...c, atRisk: undefined })) 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) => ({ diff --git a/lib/study-view-layout.ts b/lib/study-view-layout.ts index b7294f4d7..fccd4a0bb 100644 --- a/lib/study-view-layout.ts +++ b/lib/study-view-layout.ts @@ -74,3 +74,11 @@ export function findSpotLayout(cards: { key: string; w: number; h: number }[], c } }); } + +/** + * 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/test/e2e/explore.cjs b/test/e2e/explore.cjs index 32ff68335..2d039a2e7 100644 --- a/test/e2e/explore.cjs +++ b/test/e2e/explore.cjs @@ -489,7 +489,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 +615,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 +697,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-layout.test.ts b/test/study-view-layout.test.ts index 4fa6b7bd2..701661b35 100644 --- a/test/study-view-layout.test.ts +++ b/test/study-view-layout.test.ts @@ -1,7 +1,7 @@ // 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, chartCells, findSpotLayout, gridCols, gridWidth, orderCards } from "../lib/study-view-layout.ts"; +import { GRID_CELL, chartCells, findSpotLayout, gridCols, gridWidth, kmPlotTitle, orderCards } from "../lib/study-view-layout.ts"; test("LY-1: a 195 × 170 cell, 5 px apart; the grid cols·195 + (cols+1)·5 wide", () => { assert.deepEqual(GRID_CELL, { w: 195, h: 170, margin: 5 }); @@ -57,3 +57,10 @@ 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)"); +}); From fffab2d9ce285570a26e140be5e3f15b3c9e2dac Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Fri, 20 Nov 2026 16:45:19 +0000 Subject: [PATCH 03/17] Study View KM plot: the curve alone, fitting its card MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Study View's survival chart draws the axes and curve only (survivalSvg's plotOnly), as the portal's small KM chart: no risk table, legend, tests or caption under it. The curve's median, patients and events are in the plot's tooltip, where the portal keeps its legend (STS-KM-3); the downloaded figure keeps the full legend. The endpoint picker is compact, so the header stays one 20 px line. On coadread the figure is 376 × 259 inside the 393 × 343 card, with nothing to scroll. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/lab/explore-charts.tsx | 9 +++++---- app/lab/page.tsx | 4 ++-- lib/views/survival/figure.ts | 21 +++++++++++++++------ 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index bdafc5e4a..72fe0178c 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -14,12 +14,12 @@ import { Button } from "../_ui/button"; import { useWidth } 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 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, @@ -122,11 +122,12 @@ function SurvivalCard({ studies, selection, draft, endpoints, km, attrs }: Props 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}

} diff --git a/app/lab/page.tsx b/app/lab/page.tsx index f670b6cf3..0cfba5104 100644 --- a/app/lab/page.tsx +++ b/app/lab/page.tsx @@ -671,8 +671,8 @@ export default function AnalysisPage() { 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, // the portal's study-view KM has no risk table (STS-KM-3) - km: (curves) => survivalSvg({ kind: "survival", curves: (curves as any[]).map((c) => ({ ...c, atRisk: undefined })) as any }, { width }, PORTAL_STUDY_VIEW_KM)} deps={[curves]} />, + addClauses: exploreState.addDensitySelection, // the portal's study-view KM: the plot alone, no risk table or legend (STS-KM-3) + km: (curves) => survivalSvg({ kind: "survival", curves: (curves as any[]).map((c) => ({ ...c, atRisk: undefined })) as any }, { width }, PORTAL_STUDY_VIEW_KM, true)} 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) => ({ diff --git a/lib/views/survival/figure.ts b/lib/views/survival/figure.ts index 9d26a2f16..6ea0cb5dc 100644 --- a/lib/views/survival/figure.ts +++ b/lib/views/survival/figure.ts @@ -12,8 +12,12 @@ 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). + */ +export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: string, plotOnly = false): 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[]; @@ -49,12 +53,10 @@ export function survivalSvg(v: DrawnResultOf<"survival">, o: SvgOpts, single?: s }); let y = T + PLOT + bottomAxisHeight(xTitle) + 10; + 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 +72,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[] = []; From 57527ac4cb6013a204a26ae86efb3ac643362cc3 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Fri, 20 Nov 2026 17:07:22 +0000 Subject: [PATCH 04/17] Study View pies as the portal draws them: the full square, counts on the slices, the values in a hover table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pie chart fills its 1 × 1 card below its title, radius min(w, h)/2 − 20 drawn 12 px above the centre (STS-PIE-2), with no legend beside it. Each slice carries its count (numeral 0.[0]a, portalPieCount) past a quarter of the pie, or where |tan(π·ratio/2)|·(r/5)·2 holds the label (pieLabelFits), in ink that contrasts with the slice (STS-PIE-3); a slice's tooltip is 'value:count' (STS-PIE-4). Hovering the pie shows its values as a table, # and Freq with the checkboxes, search and Select all of a value list (STS-PIE-5). While the chart has a filter, the values it leaves out are grey at half opacity and the selected ones outlined (STS-PIE-7). Verified on coadread: Sex 312 / 280 on the slices (NA 2 too small), Overall Survival Status 471 only; the hover table Male 312 52.5%, Female 280 47.1%, NA 2 0.3%; a click on Male greys Female and NA; the card fits 193 × 168 with nothing to scroll. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 27 +++++---------- app/lab/explore-sections.tsx | 65 +++++++++++++++++++++--------------- lib/chart/format.ts | 10 ++++++ lib/study-view-pie.ts | 27 +++++++++++++++ test/e2e/explore.cjs | 2 +- test/study-view-pie.test.ts | 32 ++++++++++++++++++ 6 files changed, 117 insertions(+), 46 deletions(-) create mode 100644 lib/study-view-pie.ts create mode 100644 test/study-view-pie.test.ts diff --git a/app/globals.css b/app/globals.css index 4528e4fc9..37186068f 100644 --- a/app/globals.css +++ b/app/globals.css @@ -542,25 +542,14 @@ main.analysis-main { max-width: min(132rem, 100%); } } /* 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: 0; display: flex; flex-direction: column; overflow: hidden; } +.svcell > .card[data-shape=pie] > .facettitle { flex: none; margin-top: 2px; } +.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; } diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index f81c087ce..c055bbca8 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -15,7 +15,7 @@ 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"; @@ -23,6 +23,9 @@ 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"; @@ -821,6 +824,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"; @@ -930,7 +936,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; @@ -942,11 +949,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, @@ -956,7 +963,10 @@ 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 @@ -964,26 +974,29 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable["clin ) : 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 && (() => { diff --git a/lib/chart/format.ts b/lib/chart/format.ts index f2325f8f4..a6bb70f95 100644 --- a/lib/chart/format.ts +++ b/lib/chart/format.ts @@ -53,6 +53,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-pie.ts b/lib/study-view-pie.ts new file mode 100644 index 000000000..618c7bd67 --- /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/test/e2e/explore.cjs b/test/e2e/explore.cjs index 2d039a2e7..701bd14ba 100644 --- a/test/e2e/explore.cjs +++ b/test/e2e/explore.cjs @@ -110,7 +110,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); diff --git a/test/study-view-pie.test.ts b/test/study-view-pie.test.ts new file mode 100644 index 000000000..2329e5eb5 --- /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 }); +}); From 2bbf875b56c972953d28917839631ea888a5ab06 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 17:59:58 +0000 Subject: [PATCH 05/17] Study View cards: search in the footer, titles centred, title and controls on one line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every card's header is one 20 px line 4 px from its top. The title is centred over the card's whole width, keeping as clear of the top-right controls on its left as on its right; the ☰ menu sits in the corner at 20 × 20 px and any other control (the frequency table's filter, a density chart's reset, a generic-assay chart's ✕) just left of it, on the same line. The gene tables' search box moves to the card's footer, as every value list's already is (STS-TBL-3); the survival chart's endpoint picker moves into its ☰ menu (Endpoint ▸ OS, PFS, …), so its title is centred too. Measured on coadread at 1440 px: every card's title within 0 px of its card's centre, and title, ☰ and other controls all 20 px tall at 5 px from the card's top. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 38 ++++++++++++++++++------------------ app/lab/explore-charts.tsx | 15 +++++++------- app/lab/explore-sections.tsx | 25 +++++++++++++----------- app/lab/partitions.tsx | 2 +- 4 files changed, 41 insertions(+), 39 deletions(-) diff --git a/app/globals.css b/app/globals.css index 37186068f..d82525d5d 100644 --- a/app/globals.css +++ b/app/globals.css @@ -231,23 +231,27 @@ pre { .facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: center; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } .nosamples p + p { margin-top: 0.6rem; } -.svcell > .card { height: 100%; margin: 0; min-width: 0; overflow: auto; box-sizing: border-box; padding: 0.3rem 0.5rem; border-radius: var(--r-md, 4px); } +.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; } -/* Every card's title alike, as the portal's (STS-HD-1): its name only, bold and centred, on one line, - a long one cut with an ellipsis (the whole of it, and what it counts, in its tooltip). A header row - that also holds controls keeps them on that line and gives the title the rest. */ +/* A card's header, as the portal's (STS-HD-1…3): one 20 px line at the card's top. 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) { - font-size: var(--t-md); font-weight: 600; line-height: 20px; color: var(--ink); text-transform: none; letter-spacing: 0; - white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; min-width: 0; margin: 0; -} -.svcell .xc-head { flex-wrap: nowrap; gap: 0.3rem; } -.svcell .xc-head > .xc-title { flex: 1 1 0; } -.svcell [data-genetable] > .row:first-child { flex-wrap: nowrap; align-items: center; } -.svcell [data-genetable] > .row:first-child > .facettitle { flex: 1 1 0; } -.svcell .charticon svg { width: 0.85rem; height: 0.85rem; } -.svcell .titleicon { display: inline-flex; align-items: center; justify-content: center; height: 20px; width: 20px; vertical-align: top; border: 0; background: none; color: var(--muted); cursor: pointer; } + 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; } +.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; } +.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; } @@ -543,8 +547,8 @@ main.analysis-main { max-width: min(132rem, 100%); } /* Explore: categorical clinical facets as pie charts (portal study-view style) */ /* 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: 0; display: flex; flex-direction: column; overflow: hidden; } -.svcell > .card[data-shape=pie] > .facettitle { flex: none; margin-top: 2px; } +.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; } @@ -682,9 +686,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 */ -.svcell > .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 */ -.svcell > .card > .facettitle > .meta { display: block; font-weight: 400; overflow: hidden; text-overflow: ellipsis; } /* ---------------- view-card tables (app/lab/kinds/.tsx) ---------------- */ .vscroll { overflow-x: auto; } @@ -1205,8 +1207,6 @@ details.cohortpick .gearmenu-items { min-width: 22rem; max-width: 30rem; gap: 0; /* an Explore chart's "⋯" menu: pinned to the card's corner, like a cohort box's */ .svcell > .card { position: relative; } -.svcell > .card > div:first-child { padding-right: 1.8rem; } -.svcell > .card .chartgear { position: absolute; top: 0.45rem; right: 0.5rem; } .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); } diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index 72fe0178c..93f5113d9 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -9,7 +9,6 @@ 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 { linear, axisLeft, axisBottom, leftAxisWidth, bottomAxisHeight } from "../../lib/svg-kit.ts"; @@ -114,17 +113,17 @@ function SurvivalCard({ studies, selection, draft, endpoints, km, attrs }: Props
{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}> @@ -189,8 +188,8 @@ function DensityCard({ pair, added, studies, draft, selection, addClauses, nameO
plot.n ? fmtInt(plot.n) + " of " + fmtInt(plot.coverage.total) + " samples have both · " : "") + (held ? "selected: " + heldText : "drag a box to filter")}>{title} - {held && onClear && } + {held && onClear && } saveDensity(swapDensity(dset)) }, ...(["x", "y"] as const).filter((k) => logOffered(axes[k].attribute)).map((k) => ({ diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index c055bbca8..679dca34b 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -1225,10 +1225,10 @@ function AssayFreqTable({ t, ctx }: { t: NonNullable
Frequency Table: {t.name} - {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).

} @@ -1269,8 +1269,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), @@ -1279,8 +1279,8 @@ 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)] : [])]} /> - +
{f.error &&

{f.error}

} {f.kind === "cat" && f.values && ( @@ -1597,11 +1597,8 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore const byKey = new Map(all.map((g: any) => [rowKey(g), g])); return (
-
-
{title}
- 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); @@ -1664,6 +1661,12 @@ function GeneTable({ kind, ctx }: { kind: "mutated" | "cna" | "sv"; ctx: Explore ); }} + {/* 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; diff --git a/app/lab/partitions.tsx b/app/lab/partitions.tsx index c27faad91..3ed2d5b20 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) => )} From 3055d2530325d04c7b9319c84bd1d838b7c3f0d2 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 19:01:36 +0000 Subject: [PATCH 06/17] Study View: the chart grid left-aligned Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/globals.css b/app/globals.css index d82525d5d..a0fd0c97b 100644 --- a/app/globals.css +++ b/app/globals.css @@ -226,9 +226,9 @@ pre { 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: center; } +.svgridbox { width: 100%; display: flex; justify-content: flex-start; } .svgrid { flex: none; } -.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: center; } +.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } .nosamples p + p { margin-top: 0.6rem; } .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; } From 1d25f785431766d63433ca61603e134108114253 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 19:19:46 +0000 Subject: [PATCH 07/17] Study View: no bar per row in the lists; a card's header buttons on hover MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The value lists, Data Types, Cancer Studies and the derived lists drop their proportion bar column. A card's ☰ and other header buttons show while the pointer is over the card, a button in it has focus, or its menu is open; on a screen without hover they always show. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 36 +++++++++++++++--------------------- app/lab/explore-sections.tsx | 5 ----- app/lab/pick-list.tsx | 6 ++---- test/e2e/explore.cjs | 14 +++----------- 4 files changed, 20 insertions(+), 41 deletions(-) diff --git a/app/globals.css b/app/globals.css index a0fd0c97b..fae179399 100644 --- a/app/globals.css +++ b/app/globals.css @@ -251,6 +251,12 @@ pre { .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; } @@ -454,9 +460,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); @@ -464,8 +469,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; } @@ -506,9 +509,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 @@ -556,7 +556,7 @@ main.analysis-main { max-width: min(132rem, 100%); } .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 @@ -567,21 +567,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 */ @@ -592,7 +590,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 @@ -600,10 +598,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 diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index 679dca34b..4893b64f0 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -574,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 }) => { @@ -605,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()} ))} @@ -1453,7 +1451,6 @@ function StudyBreakdown({ ctx }: { ctx: ExploreCtx }) { title={(r.instance !== "a" ? r.instanceLabel + " · " : "") + r.study + " — " + r.n.toLocaleString() + " samples"}> {r.study} {r.instance !== "a" ? "⧉ " + r.instanceLabel : ""} - {fmtPct(100 * r.n / total)} {r.n.toLocaleString()} @@ -1494,7 +1491,6 @@ 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[]; @@ -1512,7 +1508,6 @@ 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)} diff --git a/app/lab/pick-list.tsx b/app/lab/pick-list.tsx index 620e253f9..b9d712827 100644 --- a/app/lab/pick-list.tsx +++ b/app/lab/pick-list.tsx @@ -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/test/e2e/explore.cjs b/test/e2e/explore.cjs index 701bd14ba..085422b3f 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 From 6527dfedb4638e81e1a224ade1f97b09cfa94be5 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 19:25:59 +0000 Subject: [PATCH 08/17] Study View: each chart fills its card's height The histograms, the KM plot and the density scatter take the room under the title instead of a height of their own: the histogram's bars stretch above a fixed tick row; the KM plot is drawn at its box's width and height (survivalSvg plot-only takes a height; DrawAtSize measures both); the density draws at its box's height. Outside a grid card each keeps its old size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 14 +++++++++++++ app/lab/explore-charts.tsx | 8 +++++--- app/lab/figure.tsx | 31 +++++++++++++++++++++++++++++ app/lab/page.tsx | 4 ++-- lib/views/survival/figure.ts | 11 ++++++---- test/study-view-chart-files.test.ts | 9 +++++++++ 6 files changed, 68 insertions(+), 9 deletions(-) diff --git a/app/globals.css b/app/globals.css index fae179399..abb298dac 100644 --- a/app/globals.css +++ b/app/globals.css @@ -544,6 +544,13 @@ 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) */ /* 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 */ @@ -1597,6 +1604,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 93f5113d9..3860cb9de 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -10,7 +10,7 @@ import { cardRank, type GridCard } from "./explore-grid.tsx"; import { chartCells, kmPlotTitle } from "../../lib/study-view-layout.ts"; import { api } from "./api.ts"; 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, KmCurve } from "../../lib/types.ts"; @@ -223,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; diff --git a/app/lab/figure.tsx b/app/lab/figure.tsx index 5cc1ca5d3..94c0bc214 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 0cfba5104..0690cd13d 100644 --- a/app/lab/page.tsx +++ b/app/lab/page.tsx @@ -37,7 +37,7 @@ 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"; @@ -672,7 +672,7 @@ export default function AnalysisPage() { return eps.sort((a, b) => (a === "OS" ? -1 : b === "OS" ? 1 : a.localeCompare(b))); })(), addClauses: exploreState.addDensitySelection, // the portal's study-view KM: the plot alone, no risk table or legend (STS-KM-3) - km: (curves) => survivalSvg({ kind: "survival", curves: (curves as any[]).map((c) => ({ ...c, atRisk: undefined })) as any }, { width }, PORTAL_STUDY_VIEW_KM, true)} deps={[curves]} />, + km: (curves) => 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) => ({ diff --git a/lib/views/survival/figure.ts b/lib/views/survival/figure.ts index 6ea0cb5dc..307ccc768 100644 --- a/lib/views/survival/figure.ts +++ b/lib/views/survival/figure.ts @@ -16,15 +16,19 @@ import { * `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): string { +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]; @@ -37,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 })); @@ -52,7 +55,7 @@ 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) => ({ diff --git a/test/study-view-chart-files.test.ts b/test/study-view-chart-files.test.ts index 22a277185..93cc3f658 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)); +}); From 9d92682a687477d07783a8a27ce30b330e322da3 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 22:48:02 +0000 Subject: [PATCH 09/17] Study View: the density scatter's ticks condensed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit About five ticks an axis instead of eight, and thousands as K/M/B (10,000 → 10K, fmtCompactTick in lib/chart/format.ts), so the labels take less of the card from the plot. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/lab/explore-charts.tsx | 15 +++++++++------ lib/chart/format.ts | 14 ++++++++++++++ test/compact-tick-format.test.ts | 15 +++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 test/compact-tick-format.test.ts diff --git a/app/lab/explore-charts.tsx b/app/lab/explore-charts.tsx index 3860cb9de..6842aeafe 100644 --- a/app/lab/explore-charts.tsx +++ b/app/lab/explore-charts.tsx @@ -12,7 +12,7 @@ import { api } from "./api.ts"; import { Button } from "../_ui/button"; import { useSize } from "./figure.tsx"; import { linear, axisLeft, axisBottom, leftAxisWidth, bottomAxisHeight } from "../../lib/svg-kit.ts"; -import { fmtInt } from "../../lib/chart/format.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"; @@ -235,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/lib/chart/format.ts b/lib/chart/format.ts index a6bb70f95..5123fddd5 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 "–"; diff --git a/test/compact-tick-format.test.ts b/test/compact-tick-format.test.ts new file mode 100644 index 000000000..b3a3e6c6a --- /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"); +}); From d91dedbe1cc46b73cc832ce4967e5748f589a92b Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 22:54:03 +0000 Subject: [PATCH 10/17] Study View: tables striped, a shaded header, the scroll box ruled As the portal's study-view tables (FixedHeaderTable: #f9f9f9 every other row): each list row striped by its index, so the stripes stay with their rows as the virtual list scrolls; the header shaded; the scrolling box ruled above and below. Tokens --row-stripe and --table-head carry a dark-mode value. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 11 ++++++++++- app/lab/pick-list.tsx | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/app/globals.css b/app/globals.css index abb298dac..9c256c5f7 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 and its header, as the portal's study-view tables (#f9f9f9 every other row) */ + --row-stripe: light-dark(#f9f9f9, #1b2329); --table-head: light-dark(#f1f4f6, #1e282e); --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); @@ -615,6 +617,13 @@ 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), a shaded header, 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) .vrowshead { background: var(--table-head); border-bottom-color: var(--line); } +: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 diff --git a/app/lab/pick-list.tsx b/app/lab/pick-list.tsx index b9d712827..bd2ea3450 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)}
))} From ed75ca6162a9ae8c42d8d5b6dfbd78b414df1889 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 22:55:30 +0000 Subject: [PATCH 11/17] Study View: the shading on the card's title bar, not the table's header A grid card's header is a shaded bar edge to edge, ruled underneath, its title and buttons centred in it; the tables' column headers go back to the card's own background. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/app/globals.css b/app/globals.css index 9c256c5f7..f4a4c7dcf 100644 --- a/app/globals.css +++ b/app/globals.css @@ -105,8 +105,8 @@ 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); - /* a table's alternate rows and its header, as the portal's study-view tables (#f9f9f9 every other row) */ - --row-stripe: light-dark(#f9f9f9, #1b2329); --table-head: light-dark(#f1f4f6, #1e282e); --mark: light-dark(#b25e09, #e0a35c); --mark-soft: light-dark(#fbf0e2, #35270f); + /* a table's alternate rows, as the portal's study-view tables (#f9f9f9 every other row), and a grid card's title bar */ + --row-stripe: light-dark(#f9f9f9, #1b2329); --card-head: light-dark(#f1f4f6, #1e282e); --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); @@ -237,7 +237,7 @@ pre { /* 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 20 px line at the card's top. The title is its +/* A card's header, as the portal's (STS-HD-1…3): one line at the card's top, a shaded bar 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 @@ -249,6 +249,14 @@ pre { } .svcell > .card:has(.cardctl) :is(.facettitle, .xc-title) { padding: 0 50px; } .svcell .xc-head { display: block; } +/* the bar: 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; background: var(--card-head); border-bottom: 1px solid var(--line); +} +.svcell > .card > .facettitle { line-height: 28px; padding: 0 32px; } +.svcell > .card:has(.cardctl) > .facettitle { padding: 0 56px; } +.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; } @@ -618,11 +626,10 @@ main.analysis-main { max-width: min(132rem, 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), a shaded header, the scrolling box ruled above and below */ + 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) .vrowshead { background: var(--table-head); border-bottom-color: var(--line); } :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; } From 3fcaf4f1cde9a3500adad5d7b6dd14fc6d132fab Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 22:58:41 +0000 Subject: [PATCH 12/17] Study View: the chart grid on a white panel Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/globals.css b/app/globals.css index f4a4c7dcf..529842fa1 100644 --- a/app/globals.css +++ b/app/globals.css @@ -228,7 +228,7 @@ pre { 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; } +.svgridbox { width: 100%; display: flex; justify-content: flex-start; background: var(--card); border: 1px solid var(--line); border-radius: var(--r-lg); } .svgrid { flex: none; } .facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } From 5b558709ff53235655daf7fcf173b68e4faeb9f7 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Mon, 23 Nov 2026 22:59:29 +0000 Subject: [PATCH 13/17] Study View: the whole page white behind the chart grid A page showing the grid takes the card colour for its background, in place of the panel the grid sat on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/globals.css b/app/globals.css index 529842fa1..3aa76fc0a 100644 --- a/app/globals.css +++ b/app/globals.css @@ -228,7 +228,9 @@ pre { 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; background: var(--card); border: 1px solid var(--line); border-radius: var(--r-lg); } +.svgridbox { width: 100%; display: flex; justify-content: flex-start; } +/* a page showing the Study View's chart grid is white behind it, as the portal's */ +body:has(.svgridbox) { --page: var(--card); } .svgrid { flex: none; } .facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } From c3bfa439d4345f0b047052a7168b9eea4107f9a9 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Tue, 24 Nov 2026 15:44:58 +0000 Subject: [PATCH 14/17] Study View: the page's own background back; card headers white The page keeps its usual background behind the grid, and a card's header takes the card's white, ruled underneath. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/app/globals.css b/app/globals.css index 3aa76fc0a..cc0720f5c 100644 --- a/app/globals.css +++ b/app/globals.css @@ -105,8 +105,8 @@ 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); - /* a table's alternate rows, as the portal's study-view tables (#f9f9f9 every other row), and a grid card's title bar */ - --row-stripe: light-dark(#f9f9f9, #1b2329); --card-head: light-dark(#f1f4f6, #1e282e); --mark: light-dark(#b25e09, #e0a35c); --mark-soft: light-dark(#fbf0e2, #35270f); + /* 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); @@ -229,8 +229,6 @@ pre { 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; } -/* a page showing the Study View's chart grid is white behind it, as the portal's */ -body:has(.svgridbox) { --page: var(--card); } .svgrid { flex: none; } .facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } @@ -239,7 +237,7 @@ body:has(.svgridbox) { --page: var(--card); } /* 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, a shaded bar edge to edge. The title is its +/* 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 @@ -251,9 +249,9 @@ body:has(.svgridbox) { --page: var(--card); } } .svcell > .card:has(.cardctl) :is(.facettitle, .xc-title) { padding: 0 50px; } .svcell .xc-head { display: block; } -/* the bar: 28 px and a rule under it, across the card's padding; the buttons (top 4 px, 20 px) sit centred in it */ +/* 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; background: var(--card-head); border-bottom: 1px solid var(--line); + margin: -4px -6px 4px; height: 29px; flex: none; border-bottom: 1px solid var(--line); } .svcell > .card > .facettitle { line-height: 28px; padding: 0 32px; } .svcell > .card:has(.cardctl) > .facettitle { padding: 0 56px; } From ea46e8ed58cafebfa61cba16252d02b0bda7c057 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Tue, 24 Nov 2026 15:46:44 +0000 Subject: [PATCH 15/17] Study View: 7 px around the cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gap between cards and around the grid is 7 px, the portal's 5 and 2 more; the columns are counted with it, floor((window − 40) / 202), so a 1440 px window holds 6 columns where it held 7. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 2 +- lib/study-view-layout.ts | 13 +++++++------ test/study-view-layout.test.ts | 17 +++++++++-------- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/app/globals.css b/app/globals.css index cc0720f5c..2cc85d1a9 100644 --- a/app/globals.css +++ b/app/globals.css @@ -230,7 +230,7 @@ pre { same cells. */ .svgridbox { width: 100%; display: flex; justify-content: flex-start; } .svgrid { flex: none; } -.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 5px; justify-content: start; } +.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 7px; padding: 7px; justify-content: start; } .nosamples { max-width: 40rem; margin: 2rem auto; text-align: center; } .nosamples p + p { margin-top: 0.6rem; } .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; } diff --git a/lib/study-view-layout.ts b/lib/study-view-layout.ts index fccd4a0bb..e04963a99 100644 --- a/lib/study-view-layout.ts +++ b/lib/study-view-layout.ts @@ -1,17 +1,18 @@ /** - * The Study View's grid as the portal lays it out (STS-LY-1…3): a cell of 195 × 170 px with 5 px - * between cells, as many columns as the width holds, each chart a whole number of cells by its + * The Study View's grid as the portal lays it out (STS-LY-1…3): a cell of 195 × 170 px with 7 px + * between cells (the portal's 5, and 2 more), as many columns as the width holds, 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, and the gap between cells and around the grid (`StudyViewConfig.ts` layout) */ -export const GRID_CELL = { w: 195, h: 170, margin: 5 } as const; +/** one cell, as the portal's (`StudyViewConfig.ts` layout), and the gap between cells and around 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 grid's width in px for `cols` columns: cols·195 + (cols+1)·5 */ +/** the grid's width in px for `cols` columns: cols·195 + (cols+1)·7 */ export const gridWidth = (cols: number): number => cols * GRID_CELL.w + (cols + 1) * GRID_CELL.margin; -/** the columns for a window `windowWidth` px wide, as the portal counts them: floor((window − 40) / 200), at least one */ +/** the columns for a window `windowWidth` px wide, as the portal counts them, with our gap: floor((window − 40) / (195 + 7)), at least one */ export function gridCols(windowWidth: number): number { return Math.max(1, Math.floor((windowWidth - 40) / (GRID_CELL.w + GRID_CELL.margin))); } diff --git a/test/study-view-layout.test.ts b/test/study-view-layout.test.ts index 701661b35..b00421705 100644 --- a/test/study-view-layout.test.ts +++ b/test/study-view-layout.test.ts @@ -3,18 +3,19 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { GRID_CELL, chartCells, findSpotLayout, gridCols, gridWidth, kmPlotTitle, orderCards } from "../lib/study-view-layout.ts"; -test("LY-1: a 195 × 170 cell, 5 px apart; the grid cols·195 + (cols+1)·5 wide", () => { - assert.deepEqual(GRID_CELL, { w: 195, h: 170, margin: 5 }); - assert.equal(gridWidth(6), 1205); - assert.equal(gridWidth(1), 205); +test("LY-1: a 195 × 170 cell, 7 px apart (the portal's 5, and 2 more); the grid cols·195 + (cols+1)·7 wide", () => { + assert.deepEqual(GRID_CELL, { w: 195, h: 170, margin: 7 }); + assert.equal(gridWidth(6), 1219); + assert.equal(gridWidth(1), 209); }); -test("LY-1: floor((window − 40) / 200) columns, at least one", () => { +test("LY-1: floor((window − 40) / 202) columns, at least one", () => { assert.equal(gridCols(1280), 6); - assert.equal(gridCols(1440), 7); + assert.equal(gridCols(1440), 6); + assert.equal(gridCols(1454), 7); assert.equal(gridCols(1920), 9); - assert.equal(gridCols(1239), 5); - assert.equal(gridCols(1240), 6); + assert.equal(gridCols(1251), 5); + assert.equal(gridCols(1252), 6); assert.equal(gridCols(200), 1); }); From c708c151b8db66fc1e990f60beb8e61a424ae180 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Tue, 24 Nov 2026 15:57:26 +0000 Subject: [PATCH 16/17] Study View: the grid flush with both sides of the page The grid fills its box's width with no padding at its sides: the columns are the count whose cells, stretched or squeezed to fill it, come closest to the portal's 195 px, never under 175 (gridCols, cellWidth). A 1440 px window holds 7 columns of 193 px. The loading placeholders fill the width too, and a card's title keeps 26 px clear for its menu. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/globals.css | 6 +++--- app/lab/explore-grid.tsx | 30 ++++++++++-------------------- lib/study-view-layout.ts | 28 +++++++++++++++++++--------- test/study-view-layout.test.ts | 29 +++++++++++++++++------------ 4 files changed, 49 insertions(+), 44 deletions(-) diff --git a/app/globals.css b/app/globals.css index 2cc85d1a9..7d16ac8e3 100644 --- a/app/globals.css +++ b/app/globals.css @@ -230,7 +230,7 @@ pre { same cells. */ .svgridbox { width: 100%; display: flex; justify-content: flex-start; } .svgrid { flex: none; } -.facetgrid { display: grid; grid-template-columns: repeat(auto-fill, 195px); grid-auto-rows: 170px; gap: 7px; padding: 7px; justify-content: start; } +.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; } .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; } @@ -253,8 +253,8 @@ pre { .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 32px; } -.svcell > .card:has(.cardctl) > .facettitle { padding: 0 56px; } +.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; } diff --git a/app/lab/explore-grid.tsx b/app/lab/explore-grid.tsx index 5d3732362..45c1c03ef 100644 --- a/app/lab/explore-grid.tsx +++ b/app/lab/explore-grid.tsx @@ -1,16 +1,17 @@ "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: 195 × 170 px cells 5 px apart, as many columns as the page holds, + * 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 { useEffect, useMemo, useState, type ReactNode } from "react"; +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, gridWidth, orderCards, type CardSpec } from "../../lib/study-view-layout.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 }; @@ -23,31 +24,20 @@ export function cardRank(selector: string): { name: string; priority: number } { } const MARGIN: [number, number] = [GRID_CELL.margin, GRID_CELL.margin]; - -/** the window's width, followed as it resizes (`fallback` before the first read) */ -function useWindowWidth(fallback: number): number { - const [w, setW] = useState(null); - useEffect(() => { - const read = () => setW(window.innerWidth); - read(); - window.addEventListener("resize", read); - return () => window.removeEventListener("resize", read); - }, []); - return w ?? fallback; -} +/** 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[] }) { - // measured only to know the page has laid out; the columns follow the window, as the portal's + // 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 windowWidth = useWindowWidth(width); - const cols = gridCols(windowWidth); + 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/lib/study-view-layout.ts b/lib/study-view-layout.ts index e04963a99..f633beb02 100644 --- a/lib/study-view-layout.ts +++ b/lib/study-view-layout.ts @@ -1,22 +1,32 @@ /** - * The Study View's grid as the portal lays it out (STS-LY-1…3): a cell of 195 × 170 px with 7 px - * between cells (the portal's 5, and 2 more), as many columns as the width holds, each chart a whole number of cells by its + * 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 around the - * grid: 7 px, the portal's 5 and 2 more by the user's choice (2026-11-24) */ +/** 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 grid's width in px for `cols` columns: cols·195 + (cols+1)·7 */ -export const gridWidth = (cols: number): number => cols * GRID_CELL.w + (cols + 1) * GRID_CELL.margin; +/** the narrowest a column may be stretched or squeezed to, filling the width */ +const MIN_CELL_W = 175; -/** the columns for a window `windowWidth` px wide, as the portal counts them, with our gap: floor((window − 40) / (195 + 7)), at least one */ -export function gridCols(windowWidth: number): number { - return Math.max(1, Math.floor((windowWidth - 40) / (GRID_CELL.w + GRID_CELL.margin))); +/** + * 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 diff --git a/test/study-view-layout.test.ts b/test/study-view-layout.test.ts index b00421705..3e7936c06 100644 --- a/test/study-view-layout.test.ts +++ b/test/study-view-layout.test.ts @@ -1,22 +1,27 @@ // 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, chartCells, findSpotLayout, gridCols, gridWidth, kmPlotTitle, orderCards } from "../lib/study-view-layout.ts"; +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); the grid cols·195 + (cols+1)·7 wide", () => { +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(gridWidth(6), 1219); - assert.equal(gridWidth(1), 209); + 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: floor((window − 40) / 202) columns, at least one", () => { - assert.equal(gridCols(1280), 6); - assert.equal(gridCols(1440), 6); - assert.equal(gridCols(1454), 7); - assert.equal(gridCols(1920), 9); - assert.equal(gridCols(1251), 5); - assert.equal(gridCols(1252), 6); - assert.equal(gridCols(200), 1); +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", () => { From 5204bb6cc459913a02dc2620ebe0c37f5f2dd8e8 Mon Sep 17 00:00:00 2001 From: Aaron Lisman Date: Tue, 24 Nov 2026 19:29:40 +0000 Subject: [PATCH 17/17] Study View: the e2e drivers check waits on the gene table's data-drivers The table's title no longer shows "OncoKB drivers" (only the portal's text), so the check waits on a data-drivers attribute the table carries while counting drivers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht --- app/lab/explore-sections.tsx | 2 +- test/e2e/explore.cjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/lab/explore-sections.tsx b/app/lab/explore-sections.tsx index 4893b64f0..aa55d4850 100644 --- a/app/lab/explore-sections.tsx +++ b/app/lab/explore-sections.tsx @@ -1591,7 +1591,7 @@ 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} {(() => { diff --git a/test/e2e/explore.cjs b/test/e2e/explore.cjs index 085422b3f..420f1633b 100644 --- a/test/e2e/explore.cjs +++ b/test/e2e/explore.cjs @@ -299,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, ""));