diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-default-cancer-type.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-default-cancer-type.png index 8789b667ac2..a4e3e615fc7 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-default-cancer-type.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-default-cancer-type.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-filtered-colorectal.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-filtered-colorectal.png index a25102b7c2f..947515fe8cb 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-filtered-colorectal.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-filtered-colorectal.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-full-width-filtered.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-full-width-filtered.png index 93f354410dd..a1cc3c00da5 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-full-width-filtered.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-full-width-filtered.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-cancer-type.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-cancer-type.png index c761ae66f94..8ea6545adab 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-cancer-type.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-cancer-type.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-egfr-mutations.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-egfr-mutations.png index a38004264ea..d8909850a28 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-egfr-mutations.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-egfr-mutations.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-filtered-colorectal.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-filtered-colorectal.png index b2b366e8491..4b211da2997 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-filtered-colorectal.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-filtered-colorectal.png differ diff --git a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-sex.png b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-sex.png index a1487efeb31..f0d9ecfcf9c 100644 Binary files a/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-sex.png and b/end-to-end-test-playwright/tests/__snapshots__/embeddings-screenshot.spec.ts/embeddings-legend-sex.png differ diff --git a/end-to-end-test-playwright/tests/embeddings-performance.spec.ts b/end-to-end-test-playwright/tests/embeddings-performance.spec.ts new file mode 100644 index 00000000000..05dbdfea8e0 --- /dev/null +++ b/end-to-end-test-playwright/tests/embeddings-performance.spec.ts @@ -0,0 +1,240 @@ +import { test, expect, Page } from '../fixtures'; +import { waitForStudyView } from './helpers/common'; + +/** + * Guards the study view against the Similarity Maps tab doing work while + * nobody is looking at it. + * + * The study view mounts its tabs with `unmountOnHide={false}`, so once the + * embeddings tab has been opened it stays mounted for the rest of the + * session. Without the `isTabActive` guards in EmbeddingsPanel that meant + * every study-view selection rebuilt the whole ~50k-point embedding + * pipeline for a hidden tab, and selecting on the Summary tab slowed to a + * crawl. + * + * The structural assertions here are the real guard - they're + * deterministic. The timing budget is deliberately loose: it exists to + * catch a pipeline-sized regression (seconds), not to benchmark the study + * view on a shared CI runner. + */ + +const STUDY = 'msk_impact_50k_2026'; +const SUMMARY_TAB = '#studyViewTabs a.tabAnchor_summary'; +const EMBEDDINGS_TAB = '#studyViewTabs a.tabAnchor_embeddings'; +const SUMMARY_CONTENT = '[data-test="summary-tab-content"]'; +const SELECTED_INFO = '[data-test="selected-info"]'; +const VIZ = '[data-test="embeddings-visualization"]'; +// Any pie slice in any chart will do - this is about selection latency, +// not which chart or cohort it produces. CANCER_TYPE specifically can't be +// used for this: STUDY_VIEW_CONFIG.tableAttrs forces it to a table (no svg +// at all) regardless of category count. Scoping to `.studyViewPieChartGroup +// path` (PieChart.tsx's own slice class, already used the same way in +// end-to-end-test/local/specs/core/group-color-chooser.spec.js) finds a +// slice in whichever chart actually rendered as a pie for this study. +const PIE_SLICE = + '[data-test^="chart-container-"] .studyViewPieChartGroup path'; + +// The embedding coordinates are a fixed remote asset, fetched only once +// the tab actually renders. +const EMBEDDING_ASSET = /umap_he_50k\.json/; + +// A guard against a regression, not a benchmark - a broken isTabActive +// guard would redundantly recompute the whole 50k-point pipeline and cost +// many extra seconds, not a few hundred ms. 10s was tight enough that a +// CI runner's normal variance alone (observed: 10.35s) could trip it. +const SELECTION_BUDGET_MS = 20000; + +// Split view turns the viewport lock on automatically, and the lock drives a +// requestAnimationFrame loop per panel. Victory and d3-timer also schedule +// frames for the summary tab's own charts, so the lock can only be measured +// as a delta against a baseline taken before the tab is ever opened - two +// locked panels would add ~60fps each on top of whatever the charts do. +const RAF_SAMPLE_MS = 2000; +const RAF_LOCK_ALLOWANCE = 60; + +function studyUrl(tab = 'summary'): string { + return `/study/${tab}?id=${STUDY}&featureFlags=EMBEDDINGS`; +} + +async function openSummary(page: Page) { + await page.goto(studyUrl()); + await expect(page.locator(SUMMARY_CONTENT)).toBeVisible({ + timeout: 60000, + }); + await waitForStudyView(page, 60000); +} + +// MSKTabs paginates the tab bar when its tabs don't all fit, and only +// renders the current page's tabs into the DOM - the rest are reachable +// only via a chevron. This study has enough data-type tabs that Embeddings +// can land on a later page, so page forward until its anchor shows up +// instead of assuming it's always on the first page. +async function openEmbeddingsTab(page: Page) { + const embeddingsTab = page.locator(EMBEDDINGS_TAB); + const nextPageArrow = page.locator('#studyViewTabs .fa-chevron-right'); + for (let i = 0; i < 10 && !(await embeddingsTab.isVisible()); i++) { + if (await nextPageArrow.isVisible()) { + await nextPageArrow.click(); + } else { + await page.waitForTimeout(500); + } + } + await embeddingsTab.click({ timeout: 30000 }); + await expect(page.locator(VIZ)).toBeVisible({ timeout: 60000 }); +} + +async function backToSummary(page: Page) { + // Opening Embeddings can leave the tab bar paged forward onto its page; + // Summary is the first tab, so page back until it's rendered again. + const summaryTab = page.locator(SUMMARY_TAB); + const prevPageArrow = page.locator('#studyViewTabs .fa-chevron-left'); + for (let i = 0; i < 10 && !(await summaryTab.isVisible()); i++) { + if (await prevPageArrow.isVisible()) { + await prevPageArrow.click(); + } else { + await page.waitForTimeout(500); + } + } + await summaryTab.click({ timeout: 30000 }); + await expect(page.locator(SUMMARY_CONTENT)).toBeVisible({ + timeout: 30000, + }); + // The wrapper appears before its charts finish (re-)loading their data - + // wait for every chart's spinner to clear so callers don't measure or + // click into a grid that's still being rebuilt. + await waitForStudyView(page, 60000); +} + +test.describe('study view is unaffected by the embeddings tab', () => { + test('the summary tab never fetches the embedding data', async ({ + page, + }) => { + // Same budget as the others in this file: opening the study view and + // then the embeddings tab for a 50k-sample study can outrun the + // config's default timeout on its own. + test.setTimeout(180000); + + const embeddingRequests: string[] = []; + page.on('request', request => { + if (EMBEDDING_ASSET.test(request.url())) { + embeddingRequests.push(request.url()); + } + }); + + await openSummary(page); + expect(embeddingRequests).toEqual([]); + + // ...and it is fetched once the tab is actually opened, so the + // assertion above is testing the guard rather than a dead URL. + await openEmbeddingsTab(page); + expect(embeddingRequests.length).toBeGreaterThan(0); + }); + + test('the embedding stops rendering once you leave the tab', async ({ + page, + }) => { + test.setTimeout(180000); + + await openSummary(page); + await openEmbeddingsTab(page); + await backToSummary(page); + + // The tab stays mounted, but its subtree must not - otherwise every + // study-view selection re-renders the deck.gl layers behind the + // summary tab. + await expect(page.locator(VIZ)).toHaveCount(0); + }); + + test('the viewport lock stops polling once you leave the tab', async ({ + page, + }) => { + test.setTimeout(180000); + + // Count frames scheduled over a fixed window. The page's own charts + // schedule some, so this is only meaningful as a before/after delta. + const countFrames = (ms: number) => + page.evaluate(async sampleMs => { + const original = window.requestAnimationFrame; + let count = 0; + window.requestAnimationFrame = function(cb) { + count++; + return original.call(window, cb); + } as typeof window.requestAnimationFrame; + await new Promise(resolve => setTimeout(resolve, sampleMs)); + window.requestAnimationFrame = original; + return count; + }, ms); + + await openSummary(page); + const baseline = await countFrames(RAF_SAMPLE_MS); + + await openEmbeddingsTab(page); + + // Two panels: this is what switches the shared viewport lock on, and + // the lock is what starts the rAF loop. The button itself reports + // visible/enabled/stable right away, but the click can still sit + // waiting to be processed for a while - the 50k-point layer's + // initial WebGL upload keeps the main thread busy well past the + // point the container is considered "visible". + await page + .locator('[data-test="embeddings-panel-count-2"]') + .click({ timeout: 60000 }); + await expect(page.locator(VIZ)).toHaveCount(2, { timeout: 60000 }); + + await backToSummary(page); + const afterLeaving = await countFrames(RAF_SAMPLE_MS); + + expect( + afterLeaving, + `summary tab scheduled ${afterLeaving} frames in ${RAF_SAMPLE_MS}ms after leaving the embeddings tab, against a ${baseline}-frame baseline - the viewport lock is still polling behind it` + ).toBeLessThan(baseline + RAF_LOCK_ALLOWANCE); + }); + + test('a summary selection still updates promptly after the embeddings tab has been opened', async ({ + page, + }) => { + test.setTimeout(180000); + + await openSummary(page); + await openEmbeddingsTab(page); + await backToSummary(page); + + const selectedInfo = page.locator(SELECTED_INFO); + await expect(selectedInfo).toBeVisible({ timeout: 30000 }); + const before = (await selectedInfo.innerText()).trim(); + + // Any slice will do - this is about how long the selection takes to + // come back, not which cohort it produces. But `click` targets the + // center of a locator's bounding box, and a pie slice's bounding box + // can be much bigger than its actual wedge (a 5% slice still spans + // most of the radius) - the center can fall outside the rendered + // path entirely. Picking the largest bounding box reliably lands + // inside its own wedge. backToSummary now waits for every chart's + // spinner to clear first, so this measurement isn't racing charts + // that are still (re-)inserting their own slices into the DOM. + const slices = page.locator(PIE_SLICE); + await expect(slices.first()).toBeVisible({ timeout: 60000 }); + const boxes = await slices.evaluateAll(paths => + paths.map(p => { + const { width, height } = p.getBoundingClientRect(); + return width * height; + }) + ); + const largest = boxes.indexOf(Math.max(...boxes)); + const slice = slices.nth(largest); + + const started = Date.now(); + await slice.click({ timeout: 30000 }); + await expect + .poll(async () => (await selectedInfo.innerText()).trim(), { + timeout: SELECTION_BUDGET_MS, + }) + .not.toBe(before); + const elapsed = Date.now() - started; + + expect( + elapsed, + `selection took ${elapsed}ms, over the ${SELECTION_BUDGET_MS}ms budget` + ).toBeLessThan(SELECTION_BUDGET_MS); + }); +}); diff --git a/end-to-end-test-playwright/tests/embeddings-screenshot.spec.ts b/end-to-end-test-playwright/tests/embeddings-screenshot.spec.ts index af248d96e3a..796ffdf7f96 100644 --- a/end-to-end-test-playwright/tests/embeddings-screenshot.spec.ts +++ b/end-to-end-test-playwright/tests/embeddings-screenshot.spec.ts @@ -235,28 +235,29 @@ test.describe('embeddings tab screenshots', () => { // Navigate straight to the embeddings route with the filter in the // URL hash: clicking the tab after a summary-tab load is not // actionable within the action timeout while the 50k-sample view - // renders. Filtering brings in the gray "Unselected" cohort. + // renders. Filtering dims everything outside it, so a category fully + // outside the filter reading "0 / total" means the filter has landed. const COLORECTAL = embeddingsUrl() + filterHash(['Colorectal Cancer']); - test('shows unselected samples as gray when filtering by cancer type', async ({ + test('dims samples outside the filter when filtering by cancer type', async ({ page, }) => { await page.goto(COLORECTAL); await snapViz( page, 'embeddings-filtered-colorectal.png', - /Unselected/ + /0\s*\/\s*[\d,]+/ ); }); - test('legend includes Unselected category when filtering', async ({ + test('legend reports the filtered-out categories as 0 of their total', async ({ page, }) => { await page.goto(COLORECTAL); await snapLegend( page, 'embeddings-legend-filtered-colorectal.png', - /Unselected/ + /0\s*\/\s*[\d,]+/ ); }); }); @@ -269,7 +270,7 @@ test.describe('embeddings tab screenshots', () => { await snapViz( page, 'embeddings-full-width-filtered.png', - /Unselected/ + /0\s*\/\s*[\d,]+/ ); }); }); diff --git a/end-to-end-test-playwright/tests/embeddings.spec.ts b/end-to-end-test-playwright/tests/embeddings.spec.ts index 9fe0ff5180d..3c3c585a731 100644 --- a/end-to-end-test-playwright/tests/embeddings.spec.ts +++ b/end-to-end-test-playwright/tests/embeddings.spec.ts @@ -18,7 +18,9 @@ import { test, expect, Page } from '../fixtures'; const STUDY = 'msk_impact_50k_2026'; const LEGEND = '[data-test="embeddings-legend"]'; const VIZ = '[data-test="embeddings-visualization"]'; -const LEGEND_ITEM = `${LEGEND} div[style*="cursor: pointer"]`; +const LEGEND_ITEM = `${LEGEND} [data-test="embeddings-legend-item"]`; +const LEGEND_SELECT_BUTTON = '[data-test="embeddings-legend-select-button"]'; +const LEGEND_HIDE_BUTTON = '[data-test="embeddings-legend-hide-button"]'; const STATUS_BAR = '[data-test="embeddings-status-bar"]'; const PAN_BUTTON = '[data-test="embeddings-pan-button"]'; const SELECT_BUTTON = '[data-test="embeddings-select-button"]'; @@ -57,18 +59,67 @@ async function gotoEmbeddings(page: Page, query = '') { test.describe('embeddings tab interactions', () => { test.describe('legend interactions', () => { - test('toggles category visibility when clicking a legend item', async ({ + test('offers Select and Hide on a legend row, swapping them in for the count on hover', async ({ page, }) => { await gotoEmbeddings(page); const firstItem = page.locator(LEGEND_ITEM).first(); await expect(firstItem).toBeVisible(); - await firstItem.click({ timeout: 30000 }); - await expect(firstItem).toHaveAttribute('style', /opacity:\s*0\.5/); + await expect(firstItem.locator(LEGEND_SELECT_BUTTON)).toHaveCount( + 0 + ); - await firstItem.click({ timeout: 30000 }); - await expect(firstItem).toHaveAttribute('style', /opacity:\s*1/); + await firstItem.hover({ timeout: 30000 }); + await expect(firstItem.locator(LEGEND_SELECT_BUTTON)).toContainText( + 'Select' + ); + await expect(firstItem.locator(LEGEND_HIDE_BUTTON)).toContainText( + 'Hide' + ); + }); + + test('hiding a category removes it from the plot; selecting one offers Unselect', async ({ + page, + }) => { + // This chains several hover/click round-trips on top of loading + // the 50k-sample embedding data, which can outrun the config's + // default timeout on a loaded CI runner - see the same + // reasoning in embeddings-performance.spec.ts. + test.setTimeout(180000); + + await gotoEmbeddings(page); + const firstItem = page.locator(LEGEND_ITEM).first(); + await expect(firstItem).toBeVisible(); + + // Select is its own axis, so the row stays visible and offers to undo. + await firstItem.hover({ timeout: 30000 }); + await firstItem + .locator(LEGEND_SELECT_BUTTON) + .click({ timeout: 30000 }); + await firstItem.hover({ timeout: 30000 }); + await expect(firstItem.locator(LEGEND_SELECT_BUTTON)).toContainText( + 'Unselect' + ); + + // Hiding is the other axis - the category drops out of the plot + // entirely, so its visible count goes to "0 / N", and a hidden + // row can no longer be selected. + await firstItem + .locator(LEGEND_HIDE_BUTTON) + .click({ timeout: 30000 }); + // The cursor is still sitting over the row after that click, and + // the row shows its hover actions (not the count) while hovered - + // move away so the count is what's actually rendered. + await page.mouse.move(0, 0); + await expect(firstItem).toContainText(/0\s*\/\s*[\d,]+/); + await firstItem.hover({ timeout: 30000 }); + await expect(firstItem.locator(LEGEND_HIDE_BUTTON)).toContainText( + 'Show' + ); + await expect(firstItem.locator(LEGEND_SELECT_BUTTON)).toHaveCount( + 0 + ); }); test('shows/hides all categories with the Show All/Hide All button', async ({ @@ -89,6 +140,28 @@ test.describe('embeddings tab interactions', () => { await expect(toggle).toContainText('Hide All'); }); + test('a legend search filters rows by name, case-insensitively', async ({ + page, + }) => { + await gotoEmbeddings(page); + const search = page.locator( + '[data-test="embeddings-legend-search"]' + ); + await expect(search).toBeVisible(); + + const itemCount = await page.locator(LEGEND_ITEM).count(); + // Default coloring is Cancer Type Detailed, so this matches + // "Colorectal Adenocarcinoma" - not the coarser "Colorectal + // Cancer" bucket from the plain Cancer Type attribute. + await search.fill('COLORECTAL'); + await expect(page.locator(LEGEND_ITEM)).toHaveCount(1); + await expect(page.locator(LEGEND_ITEM)).toContainText('Colorectal'); + + // Clearing the search restores every row. + await search.fill(''); + await expect(page.locator(LEGEND_ITEM)).toHaveCount(itemCount); + }); + test('displays the total embedded sample count in the status bar', async ({ page, }) => { @@ -97,18 +170,29 @@ test.describe('embeddings tab interactions', () => { await expect(page.locator(STATUS_BAR)).toContainText( /[\d,]+ samples embedded in/ ); + // An unfiltered cohort still has every patient "selected" in the + // store, which must not read as an active selection here. + await expect(page.locator(STATUS_BAR)).not.toContainText( + /Selection active/ + ); + await expect( + page.locator('[data-test="embeddings-highlight-mode-button"]') + ).toHaveCount(0); }); - test('status bar switches to "Selection active" once a category is hidden, and Clear restores it', async ({ + test('status bar switches to "Selection active" once a category is selected, and Clear restores it', async ({ page, }) => { await gotoEmbeddings(page); const firstItem = page.locator(LEGEND_ITEM).first(); await expect(firstItem).toBeVisible(); + // Default mode is Highlight, so the status bar reports a + // reduced "highlighted" count, not "visible" (that's Filter + // mode's wording - see the dedicated test below). await firstItem.click({ timeout: 30000 }); await expect(page.locator(STATUS_BAR)).toContainText( - /Selection active.*[\d,]+\s*\/\s*[\d,]+.*visible/ + /Selection active.*[\d,]+\s*\/\s*[\d,]+.*highlighted/ ); await expect(page.locator(CLEAR_BUTTON)).toBeVisible(); await expect(page.locator(MAKE_GLOBAL_BUTTON)).toBeVisible(); @@ -120,16 +204,47 @@ test.describe('embeddings tab interactions', () => { await expect(page.locator(CLEAR_BUTTON)).not.toBeVisible(); }); - test('legend row shows "visible / total" once its category is hidden', async ({ + test('legend counts reflect the selection in Highlight mode, where nothing is removed from the plot', async ({ page, }) => { await gotoEmbeddings(page); const firstItem = page.locator(LEGEND_ITEM).first(); + const secondItem = page.locator(LEGEND_ITEM).nth(1); await expect(firstItem).toBeVisible(); + // Every row reserves a 1px border to avoid layout shift, so + // check it's specifically no longer transparent once selected. + await expect(firstItem).toHaveAttribute( + 'style', + /border:\s*1px solid transparent/ + ); + await firstItem.click({ timeout: 30000 }); - // The filter applies to this same panel too, so its count drops to "0 / N". - await expect(firstItem).toContainText(/0\s*\/\s*[\d,]+/); + await expect(firstItem).not.toHaveAttribute( + 'style', + /border:\s*1px solid transparent/ + ); + // Highlight only dims the remainder, but the counts still track + // the selection: everything outside it reads "0 / total". + await expect(secondItem).toContainText(/0\s*\/\s*[\d,]+/); + }); + + test('Filter mode reports the same selection as "visible" rather than "highlighted"', async ({ + page, + }) => { + await gotoEmbeddings(page); + const firstItem = page.locator(LEGEND_ITEM).first(); + const secondItem = page.locator(LEGEND_ITEM).nth(1); + await expect(firstItem).toBeVisible(); + + await firstItem.click({ timeout: 30000 }); + await page + .locator('[data-test="embeddings-filter-mode-button"]') + .click({ timeout: 30000 }); + await expect(page.locator(STATUS_BAR)).toContainText( + /Selection active.*[\d,]+\s*\/\s*[\d,]+.*visible/ + ); + await expect(secondItem).toContainText(/0\s*\/\s*[\d,]+/); }); }); @@ -147,7 +262,7 @@ test.describe('embeddings tab interactions', () => { // URL: clicking the tab from a freshly-loaded summary view is not // actionable within the action timeout while the 50k-sample study // view renders. - test('shows an Unselected category when a study-view filter is applied', async ({ + test('a study-view filter highlights in place, without collapsing the rest into an Unselected bucket', async ({ page, }) => { await page.goto( @@ -156,9 +271,45 @@ test.describe('embeddings tab interactions', () => { )}` ); await expect(page.locator(LEGEND)).toBeVisible({ timeout: 60000 }); - await expect(page.locator(LEGEND)).toContainText('Unselected', { - timeout: 60000, - }); + await expect( + page.locator(STATUS_BAR) + ).toContainText(/Selection active/, { timeout: 60000 }); + + // Everything outside the filter keeps its own category and just + // dims, so its count reads "0 / total" rather than being rolled + // into one grey row. + await expect(page.locator(LEGEND)).not.toContainText('Unselected'); + await expect(page.locator(LEGEND)).toContainText(/0\s*\/\s*[\d,]+/); + }); + + test('a study-view filter alone (no local lasso/legend action) still offers the Filter/Highlight toggle', async ({ + page, + }) => { + await page.goto( + `/study/embeddings?id=${STUDY}&featureFlags=EMBEDDINGS${filterHash( + ['Colorectal Cancer'] + )}` + ); + await expect(page.locator(LEGEND)).toBeVisible({ timeout: 60000 }); + + // No local selection was made, so Clear/Make Global shouldn't + // show - there's nothing local to clear/promote - but the mode + // toggle should, since it also governs this page-wide selection. + const highlightModeButton = page.locator( + '[data-test="embeddings-highlight-mode-button"]' + ); + const filterModeButton = page.locator( + '[data-test="embeddings-filter-mode-button"]' + ); + await expect(highlightModeButton).toBeVisible({ timeout: 60000 }); + await expect(filterModeButton).toBeVisible(); + await expect(page.locator(CLEAR_BUTTON)).not.toBeVisible(); + await expect(page.locator(MAKE_GLOBAL_BUTTON)).not.toBeVisible(); + + await filterModeButton.click({ timeout: 30000 }); + await expect(page.locator(STATUS_BAR)).toContainText( + /Selection active.*[\d,]+\s*\/\s*[\d,]+.*visible/ + ); }); }); diff --git a/src/pages/studyView/tabs/EmbeddingsPanel.tsx b/src/pages/studyView/tabs/EmbeddingsPanel.tsx index fc7711fdc1b..caec114b4e2 100644 --- a/src/pages/studyView/tabs/EmbeddingsPanel.tsx +++ b/src/pages/studyView/tabs/EmbeddingsPanel.tsx @@ -10,6 +10,7 @@ import { } from 'mobx'; import { remoteData } from 'cbioportal-frontend-commons'; import { StudyViewPageStore } from 'pages/studyView/StudyViewPageStore'; +import { StudyViewPageTabKeyEnum } from 'pages/studyView/StudyViewPageTabs'; import LoadingIndicator from 'shared/components/loadingIndicator/LoadingIndicator'; import { ColoringMenuOmnibarOption, @@ -56,6 +57,8 @@ export interface IEmbeddingsPanelProps { panelCount: number; selectionMode: 'none' | 'lasso'; onSelectionModeChange: (mode: 'none' | 'lasso') => void; + // Shared across panels. + selectionEffect: 'filter' | 'highlight'; tooltipFields: Set; onTooltipFieldsChange: (fields: Set) => void; hiddenQcCategories: Set; @@ -66,6 +69,10 @@ export interface IEmbeddingsPanelProps { onReportSampleCounts?: (info: { total: number; visible: number; + highlighted: number; + hasLocalSelection: boolean; + // A page-wide Study View selection - also shows the Filter/Highlight toggle. + hasGlobalSelection: boolean; embeddingSampleSize: number; embeddingDescription: string; embeddingType: 'patients' | 'samples'; @@ -126,9 +133,10 @@ export class EmbeddingsPanel extends React.Component< @observable private windowHeight = window.innerHeight; @observable private legendCollapsed = false; @observable.ref private pinnedPoint: EmbeddingPoint | null = null; - // This panel's own legend toggle state - see ownHiddenSampleKeys for - // how it's translated into the shared cross-panel filter. - @observable.ref private localHiddenCategories = new Set(); + // Two axes: hidden removes a category from the plot in either mode; + // selected dims or filters everything else, like a lasso's remainder. + @observable.ref private hiddenCategories = new Set(); + @observable.ref private selectedCategories = new Set(); // null means no lasso filter active; applied globally only via // applyFilterGlobally (the "Make Global" button). @observable.ref private lassoSelectedKeys: Set | null = null; @@ -139,6 +147,7 @@ export class EmbeddingsPanel extends React.Component< private filterChangeReactionDisposer?: () => void; private hiddenSampleKeysReactionDisposer?: () => void; private sampleCountsReportReactionDisposer?: () => void; + private tabActivityReactionDisposer?: () => void; private viewStateInitialized = false; private centerViewTimeoutId?: ReturnType; // @observer makes `this.props` reactive as one unit, so any prop change was invalidating every computed; cache the never-changing store. @@ -312,26 +321,37 @@ export class EmbeddingsPanel extends React.Component< { fireImmediately: true } ); + this.tabActivityReactionDisposer = reaction( + () => this.isTabActive, + isActive => { + if (isActive) { + if (this.props.isLockedToPrimary) { + this.startLockPolling(); + } + } else { + this.stopLockPolling(); + } + } + ); + this.sampleCountsReportReactionDisposer = reaction( () => { - const allSamples = this.store.samples.result || []; const embeddingType = this.selectedEmbedding?.data.embedding_type || 'samples'; - // Same unit as the embedding, so directly comparable to - // totalSampleCount. - const cohortCount = - embeddingType === 'patients' - ? new Set(allSamples.map(s => s.patientId)).size - : allSamples.length; return { total: this.totalSampleCount, visible: this.visibleSampleCount, + highlighted: this.highlightedSampleCount, + hasLocalSelection: this.hasLocalSelection, + // selectedPatients is the whole cohort when unfiltered, + // so only a non-empty remainder counts as a selection. + hasGlobalSelection: this.storeExcludedKeys.size > 0, embeddingSampleSize: this.selectedEmbedding?.data.sampleSize || 0, embeddingDescription: this.selectedEmbedding?.data.description || '', embeddingType: embeddingType as 'patients' | 'samples', - cohortCount, + cohortCount: this.cohortCount, }; }, info => { @@ -394,7 +414,8 @@ export class EmbeddingsPanel extends React.Component< @action.bound private clearOwnFilters() { - this.localHiddenCategories = new Set(); + this.hiddenCategories = new Set(); + this.selectedCategories = new Set(); this.lassoSelectedKeys = null; } @@ -402,11 +423,13 @@ export class EmbeddingsPanel extends React.Component< private lockPollRafId?: number; private startLockPolling() { - if (this.lockPollRafId !== undefined) { + if (this.lockPollRafId !== undefined || !this.isTabActive) { return; } const poll = () => { - if (!this.props.isLockedToPrimary) { + // The tab stays mounted once shown, so without isTabActive this + // would keep running at 60fps behind whatever tab is open. + if (!this.props.isLockedToPrimary || !this.isTabActive) { this.lockPollRafId = undefined; return; } @@ -451,6 +474,9 @@ export class EmbeddingsPanel extends React.Component< if (this.filterChangeReactionDisposer) { this.filterChangeReactionDisposer(); } + if (this.tabActivityReactionDisposer) { + this.tabActivityReactionDisposer(); + } if (this.hiddenSampleKeysReactionDisposer) { this.hiddenSampleKeysReactionDisposer(); } @@ -569,7 +595,9 @@ export class EmbeddingsPanel extends React.Component< return new Map(); } - const cacheEntry = this.store.clinicalDataCache.get(attr); + const cacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( + attr + ); if (!cacheEntry?.isComplete || !cacheEntry.result) { return new Map(); } @@ -1042,7 +1070,31 @@ export class EmbeddingsPanel extends React.Component< invoke: () => Promise.resolve(true), }); + // Cached so the sample-counts reaction doesn't rebuild a 50k array and + // Set every time its tracking function re-runs. + @computed private get cohortCount(): number { + const allSamples = this.store.samples.result || []; + // Same unit as the embedding, so comparable to totalSampleCount. + return this.selectedEmbedding?.data.embedding_type === 'patients' + ? new Set(allSamples.map(s => s.patientId)).size + : allSamples.length; + } + + // The study view keeps hidden tabs mounted (unmountOnHide={false}), so + // without this gate every study-view selection would rebuild the whole + // ~50k-point pipeline for a tab nobody is looking at. + @computed private get isTabActive(): boolean { + // Cast: StudyViewPageTabKey has no EMBEDDINGS, same as StudyViewPage. + return ( + (this.store.currentTab as string) === + StudyViewPageTabKeyEnum.EMBEDDINGS + ); + } + @computed get rawPlotData(): EmbeddingPlotPoint[] { + if (!this.isTabActive) { + return []; + } if (!this.store.samples.isComplete || !this.selectedEmbedding?.data) { return []; } @@ -1075,7 +1127,7 @@ export class EmbeddingsPanel extends React.Component< EMBEDDING_DATA_PREFIX ) ) { - const clinicalDataCacheEntry = this.store.clinicalDataCache.get( + const clinicalDataCacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( this.selectedColoringOption.info.clinicalAttribute ); if (!clinicalDataCacheEntry?.isComplete) { @@ -1096,84 +1148,159 @@ export class EmbeddingsPanel extends React.Component< ); } - // Shared cross-panel by identity, not category name, so a differently-colored panel still filters the same samples. - @computed get ownHiddenSampleKeys(): Set { - const hasCategoryFilter = this.localHiddenCategories.size > 0; - const hasLassoFilter = this.lassoSelectedKeys !== null; - if (!hasCategoryFilter && !hasLassoFilter) { + @computed get hasLocalSelection(): boolean { + return ( + this.hiddenCategories.size > 0 || + this.selectedCategories.size > 0 || + this.lassoSelectedKeys !== null + ); + } + + // By identity, not category name: a differently-colored panel still + // matches the same samples. + private collectKeysByLabel( + matches: (label: string) => boolean + ): Set { + const keys = new Set(); + this.rawPlotData.forEach(point => { + const key = point.sampleId || point.patientId; + if (key && matches(point.displayLabel || '')) { + keys.add(key); + } + }); + return keys; + } + + @computed private get hiddenCategoryKeys(): Set { + if (this.hiddenCategories.size === 0) { return new Set(); } + return this.collectKeysByLabel(label => + this.hiddenCategories.has(label) + ); + } - const rawPlotData = this.rawPlotData; - const selectedPatientIds = this.selectedPatientIds; - const hasSelection = selectedPatientIds.length > 0; - const selectedPatientSet = new Set(selectedPatientIds); + // Everything outside the selected categories - the same kind of remainder a lasso leaves. + @computed private get categoryExcludedKeys(): Set { + if (this.selectedCategories.size === 0) { + return new Set(); + } + return this.collectKeysByLabel( + label => !this.selectedCategories.has(label) + ); + } + + @computed private get lassoExcludedKeys(): Set { const lassoKeys = this.lassoSelectedKeys; + if (lassoKeys === null) { + return new Set(); + } const keys = new Set(); - rawPlotData.forEach(point => { - let label = point.displayLabel || ''; - if (hasSelection && point.isInCohort !== false) { - const hasPatientId = Boolean(point.patientId); - const isSelected = - hasPatientId && selectedPatientSet.has(point.patientId!); - if (!isSelected) { - label = 'Unselected'; - } - } + this.rawPlotData.forEach(point => { const key = point.sampleId || point.patientId; - if (!key) { - return; - } - if (hasCategoryFilter && this.localHiddenCategories.has(label)) { - keys.add(key); - return; - } - if (hasLassoFilter && !lassoKeys!.has(key)) { + if (key && !lassoKeys.has(key)) { keys.add(key); } }); return keys; } - @computed get plotData(): EmbeddingPlotPoint[] { - const rawPlotData = this.rawPlotData; - - if (rawPlotData.length === 0) { - return []; + // Filter mode doesn't need to tell category and lasso exclusions apart - both are just removed. + @computed private get localSelectionExcludedKeys(): Set { + if ( + this.categoryExcludedKeys.size === 0 && + this.lassoExcludedKeys.size === 0 + ) { + return new Set(); } + const keys = new Set(this.categoryExcludedKeys); + this.lassoExcludedKeys.forEach(key => keys.add(key)); + return keys; + } + // Treated like a local selection's remainder, so the shared + // highlight/filter toggle governs the page-wide selection too. + @computed private get storeExcludedKeys(): Set { const selectedPatientIds = this.selectedPatientIds; - const hasSelection = selectedPatientIds.length > 0; - - if (!hasSelection) { - return rawPlotData; + if (selectedPatientIds.length === 0) { + return new Set(); } const selectedPatientSet = new Set(selectedPatientIds); - - let processedData = rawPlotData.map(point => { + const keys = new Set(); + this.rawPlotData.forEach(point => { if (point.isInCohort === false) { - return point; + return; } - const hasPatientId = Boolean(point.patientId); const isSelected = hasPatientId && selectedPatientSet.has(point.patientId!); - if (!isSelected) { - return { - ...point, - displayLabel: 'Unselected', - color: '#C8C8C8', - strokeColor: '#C8C8C8', - }; + const key = point.sampleId || point.patientId; + if (key) { + keys.add(key); + } } + }); + return keys; + } - return point; + // Everything left out by any active selection, local or page-wide. + @computed private get excludedKeys(): Set { + if (this.storeExcludedKeys.size === 0) { + return this.localSelectionExcludedKeys; + } + const keys = new Set(this.localSelectionExcludedKeys); + this.storeExcludedKeys.forEach(key => keys.add(key)); + return keys; + } + + // A hidden category is removed in either mode; a selection only removes + // its remainder in filter mode (highlight dims it instead). + @computed get ownHiddenSampleKeys(): Set { + const keys = new Set(this.hiddenCategoryKeys); + if (this.props.selectionEffect === 'filter') { + this.excludedKeys.forEach(key => keys.add(key)); + } + return keys; + } + + @computed private get deemphasizedKeys(): Set { + if (this.props.selectionEffect !== 'highlight') { + return new Set(); + } + return this.excludedKeys; + } + + // Shared by plotData/categoryCounts/categoryColors so all three agree + // on what is dimmed. + @computed private get dimmedPlotData(): EmbeddingPlotPoint[] { + const deemphasizedKeys = this.deemphasizedKeys; + if (deemphasizedKeys.size === 0) { + return this.rawPlotData; + } + + // Keeps its own color and category, and just recedes. + return this.rawPlotData.map(point => { + if (point.isInCohort === false) { + return point; + } + const key = point.sampleId || point.patientId; + return key && deemphasizedKeys.has(key) + ? { ...point, isDeemphasized: true } + : point; }); + } - // hiddenSampleKeys is the cross-panel identity filter; hiddenQcCategories is matched by name. - const filteredData = processedData.filter(point => { + @computed get plotData(): EmbeddingPlotPoint[] { + const processedData = this.dimmedPlotData; + if (processedData.length === 0) { + return []; + } + + // hiddenSampleKeys is the cross-panel identity filter (filter mode + // only); hiddenQcCategories matches by name. + return processedData.filter(point => { const label = point.displayLabel || ''; const key = point.sampleId || point.patientId || ''; return ( @@ -1181,15 +1308,17 @@ export class EmbeddingsPanel extends React.Component< !this.hiddenQcCategoriesMirror.has(label) ); }); - - return filteredData; } - // Per-category counts after every active filter - shown alongside - // categoryCounts' raw totals as "visible / total" in the legend. + // The "in selection" half of the legend's "in selection / total". + // Highlight mode leaves the remainder in plotData, so dimmed points + // have to be skipped for the count to track the selection. @computed get visibleCategoryCounts(): Map { const counts = new Map(); this.plotData.forEach(point => { + if (point.isDeemphasized) { + return; + } const label = point.displayLabel || ''; counts.set(label, (counts.get(label) || 0) + 1); }); @@ -1199,42 +1328,8 @@ export class EmbeddingsPanel extends React.Component< // Same transform as plotData, but unfiltered - used for the legend's // raw/unfiltered totals. @computed get categoryCounts(): Map { - const rawPlotData = this.rawPlotData; - - if (rawPlotData.length === 0) { - return new Map(); - } - - const selectedPatientIds = this.selectedPatientIds; - const hasSelection = selectedPatientIds.length > 0; - - let processedData; - if (!hasSelection) { - processedData = rawPlotData; - } else { - const selectedPatientSet = new Set(selectedPatientIds); - processedData = rawPlotData.map(point => { - if (point.isInCohort === false) { - return point; - } - const hasPatientId = Boolean(point.patientId); - const isSelected = - hasPatientId && selectedPatientSet.has(point.patientId!); - - if (!isSelected) { - return { - ...point, - displayLabel: 'Unselected', - color: '#C8C8C8', - strokeColor: '#C8C8C8', - }; - } - return point; - }); - } - const counts = new Map(); - processedData.forEach(point => { + this.dimmedPlotData.forEach(point => { const category = point.displayLabel || ''; counts.set(category, (counts.get(category) || 0) + 1); }); @@ -1246,45 +1341,11 @@ export class EmbeddingsPanel extends React.Component< string, { fillColor: string; strokeColor: string; hasStroke: boolean } > { - const rawPlotData = this.rawPlotData; - - if (rawPlotData.length === 0) { - return new Map(); - } - - const selectedPatientIds = this.selectedPatientIds; - const hasSelection = selectedPatientIds.length > 0; - - let processedData; - if (!hasSelection) { - processedData = rawPlotData; - } else { - const selectedPatientSet = new Set(selectedPatientIds); - processedData = rawPlotData.map(point => { - if (point.isInCohort === false) { - return point; - } - const hasPatientId = Boolean(point.patientId); - const isSelected = - hasPatientId && selectedPatientSet.has(point.patientId!); - - if (!isSelected) { - return { - ...point, - displayLabel: 'Unselected', - color: '#C8C8C8', - strokeColor: '#C8C8C8', - }; - } - return point; - }); - } - const colors = new Map< string, { fillColor: string; strokeColor: string; hasStroke: boolean } >(); - processedData.forEach(point => { + this.dimmedPlotData.forEach(point => { if ( point.displayLabel && point.color && @@ -1343,7 +1404,7 @@ export class EmbeddingsPanel extends React.Component< return result.numericalRange; } - const clinicalDataCacheEntry = this.store.clinicalDataCache.get( + const clinicalDataCacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( this.selectedColoringOption.info.clinicalAttribute ); @@ -1379,7 +1440,7 @@ export class EmbeddingsPanel extends React.Component< return result.numericalColorFn; } - const clinicalDataCacheEntry = this.store.clinicalDataCache.get( + const clinicalDataCacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( this.selectedColoringOption.info.clinicalAttribute ); @@ -1421,7 +1482,7 @@ export class EmbeddingsPanel extends React.Component< return values; } - const clinicalDataCacheEntry = this.store.clinicalDataCache.get( + const clinicalDataCacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( this.selectedColoringOption.info.clinicalAttribute ); if ( @@ -1501,6 +1562,24 @@ export class EmbeddingsPanel extends React.Component< return visibleCount; } + // The highlight-mode analogue of visibleSampleCount: highlighted points + // are never removed from plotData. + @computed get highlightedSampleCount(): number { + let count = 0; + this.plotData.forEach(point => { + const category = point.displayLabel || ''; + if ( + point.isDeemphasized || + category === 'Sample not in this cohort' || + category === 'Case not in this cohort' + ) { + return; + } + count++; + }); + return count; + } + @computed get totalSampleCount(): number { if (!this.categoryCounts) return 0; let total = 0; @@ -1522,7 +1601,7 @@ export class EmbeddingsPanel extends React.Component< let visibleCount = 0; this.categoryCounts.forEach((count, category) => { if ( - !this.localHiddenCategories.has(category) && + !this.hiddenCategories.has(category) && !this.hiddenQcCategoriesMirror.has(category) ) { visibleCount++; @@ -1547,6 +1626,10 @@ export class EmbeddingsPanel extends React.Component< } @computed get selectedPatientIds(): string[] { + // Wasted work while the tab is hidden - see isTabActive. + if (!this.isTabActive) { + return []; + } return this.store.selectedPatients?.map((p: any) => p.patientId) || []; } @@ -1587,7 +1670,7 @@ export class EmbeddingsPanel extends React.Component< EMBEDDING_DATA_PREFIX ) ) { - const cacheEntry = this.store.clinicalDataCache.get( + const cacheEntry = this.store.clinicalDataCache.unfilteredClinicalDataCache.get( this.selectedColoringOption.info.clinicalAttribute ); if (!cacheEntry.isComplete) { @@ -1820,13 +1903,30 @@ export class EmbeddingsPanel extends React.Component< @action.bound private toggleCategoryVisibility(category: string) { - const next = new Set(this.localHiddenCategories); + const next = new Set(this.hiddenCategories); if (next.has(category)) { next.delete(category); } else { next.add(category); + // Can't be part of the selection while it isn't in the plot. + if (this.selectedCategories.has(category)) { + const nextSelected = new Set(this.selectedCategories); + nextSelected.delete(category); + this.selectedCategories = nextSelected; + } } - this.localHiddenCategories = next; + this.hiddenCategories = next; + } + + @action.bound + private toggleCategorySelected(category: string) { + const next = new Set(this.selectedCategories); + if (next.has(category)) { + next.delete(category); + } else { + next.add(category); + } + this.selectedCategories = next; } @action.bound @@ -1838,7 +1938,7 @@ export class EmbeddingsPanel extends React.Component< 'Case not in this cohort', ]; - if (this.localHiddenCategories.size === 0) { + if (this.hiddenCategories.size === 0) { const toHide = new Set(); if (this.categoryCounts) { this.categoryCounts.forEach((count, category) => { @@ -1847,15 +1947,15 @@ export class EmbeddingsPanel extends React.Component< } }); } - this.localHiddenCategories = toHide; + this.hiddenCategories = toHide; } else { const keepHidden = new Set(); - this.localHiddenCategories.forEach(category => { + this.hiddenCategories.forEach(category => { if (embeddingConfigCategories.includes(category)) { keepHidden.add(category); } }); - this.localHiddenCategories = keepHidden; + this.hiddenCategories = keepHidden; } } @@ -1866,17 +1966,33 @@ export class EmbeddingsPanel extends React.Component< return false; } - const selectedPoints = this.plotData; + // plotData is already narrowed to this in filter mode, but not in + // highlight mode (a hidden category isn't even dimmed there). + const excludedKeys = this.localSelectionExcludedKeys; + const selectedPoints = + excludedKeys.size === 0 + ? this.plotData + : this.plotData.filter(p => { + const key = p.sampleId || p.patientId; + return key ? !excludedKeys.has(key) : true; + }); + if (selectedPoints.length === 0) { + return false; + } + const allSamples = this.store.samples.result || []; const embeddingType = this.selectedEmbedding.data.embedding_type; if (embeddingType === 'samples') { - const selectedSampleIds = new Set( - selectedPoints.map(p => p.sampleId).filter(Boolean) + // By uniqueSampleKey, not sampleId: an id is only unique within + // a study, so matching on it alone pulls in same-named samples + // from the other studies in the cohort. + const selectedSampleKeys = new Set( + selectedPoints.map(p => p.uniqueSampleKey).filter(Boolean) ); const samplesForSelection = allSamples.filter(sample => - selectedSampleIds.has(sample.sampleId) + selectedSampleKeys.has(sample.uniqueSampleKey) ); const customChartData = { @@ -1931,7 +2047,8 @@ export class EmbeddingsPanel extends React.Component< if (!selectedPoints || selectedPoints.length === 0) { return; } - const keys = new Set(); + // Additive, so consecutive draws build up a set instead of replacing it. + const keys = new Set(this.lassoSelectedKeys ?? []); selectedPoints.forEach(p => { const key = p.sampleId || p.patientId; if (key) { @@ -1997,14 +2114,18 @@ export class EmbeddingsPanel extends React.Component< categoryCounts: this.categoryCounts, visibleCategoryCounts: this.visibleCategoryCounts, categoryColors: this.categoryColors, - hiddenCategories: this.localHiddenCategories, + hiddenCategories: this.hiddenCategories, onToggleCategoryVisibility: this.toggleCategoryVisibility, + selectedCategories: this.selectedCategories, + onToggleCategorySelected: this.toggleCategorySelected, onToggleAllCategories: this.toggleAllCategories, hiddenQcCategories: this.props.hiddenQcCategories, onToggleQcCategoryVisibility: this.props .onToggleQcCategoryVisibility, showLegendHeaderAndConfiguration: this.props.panelIndex === 1, - isFilterActive: this.props.hiddenSampleKeys.size > 0, + isFilterActive: + this.props.hiddenSampleKeys.size > 0 || this.hasLocalSelection, + selectionEffect: this.props.selectionEffect, legendCollapsed: this.legendCollapsed, onLegendCollapsedChange: this.onLegendCollapsedChange, visibleSampleCount: this.visibleSampleCount, @@ -2082,6 +2203,12 @@ export class EmbeddingsPanel extends React.Component< } render() { + // Mounted while hidden, so skip the subtree (deck.gl layers + // included) rather than re-rendering it empty on every selection. + if (!this.isTabActive) { + return null; + } + if (this.currentStudyIds.length === 0) { return (
diff --git a/src/pages/studyView/tabs/EmbeddingsTab.tsx b/src/pages/studyView/tabs/EmbeddingsTab.tsx index cc378f64c1c..f855626f6fd 100644 --- a/src/pages/studyView/tabs/EmbeddingsTab.tsx +++ b/src/pages/studyView/tabs/EmbeddingsTab.tsx @@ -56,6 +56,9 @@ const TOOLTIP_FIELDS_PARAM = 'embeddings_tooltip_fields'; export class EmbeddingsTab extends React.Component { @observable private panelCount: number = 1; @observable private sharedSelectionMode: 'none' | 'lasso' = 'none'; + // Shared across panels, like sharedSelectionMode. + @observable private sharedSelectionEffect: 'filter' | 'highlight' = + 'highlight'; @observable.ref private sharedTooltipFields = new Set(); @observable private sharedHiddenQcCategories = new Set(); // Union of every panel's own hidden keys; .shallow since a contribution can hold tens of thousands of them. @@ -84,6 +87,25 @@ export class EmbeddingsTab extends React.Component { // Reported by whichever panel last fired its reaction; drives the status bar and its explainer tooltip. @observable private reportedTotalSampleCount = 0; @observable private reportedVisibleSampleCount = 0; + @observable private reportedHighlightedSampleCount = 0; + // Per panel: one panel reporting no selection must not clear the + // status bar while another still has one. + @observable.shallow private selectionFlagsByPanel = new Map< + number, + { local: boolean; global: boolean } + >(); + + @computed private get reportedHasLocalSelection(): boolean { + return Array.from(this.selectionFlagsByPanel.values()).some( + flags => flags.local + ); + } + + @computed private get reportedHasGlobalSelection(): boolean { + return Array.from(this.selectionFlagsByPanel.values()).some( + flags => flags.global + ); + } @observable private reportedEmbeddingSampleSize = 0; @observable private reportedEmbeddingDescription = ''; @observable private reportedEmbeddingType: 'patients' | 'samples' = @@ -137,6 +159,11 @@ export class EmbeddingsTab extends React.Component { this.sharedSelectionMode = mode; } + @action.bound + private onSharedSelectionEffectChange(effect: 'filter' | 'highlight') { + this.sharedSelectionEffect = effect; + } + @action.bound private onSharedTooltipFieldsChange(fields: Set) { this.sharedTooltipFields = fields; @@ -199,16 +226,35 @@ export class EmbeddingsTab extends React.Component { } @action.bound - private onReportSampleCounts(info: { - total: number; - visible: number; - embeddingSampleSize: number; - embeddingDescription: string; - embeddingType: 'patients' | 'samples'; - cohortCount: number; - }) { + private onReportSampleCounts( + panelIndex: number, + info: { + total: number; + visible: number; + highlighted: number; + hasLocalSelection: boolean; + hasGlobalSelection: boolean; + embeddingSampleSize: number; + embeddingDescription: string; + embeddingType: 'patients' | 'samples'; + cohortCount: number; + } + ) { + const existing = this.selectionFlagsByPanel.get(panelIndex); + if ( + !existing || + existing.local !== info.hasLocalSelection || + existing.global !== info.hasGlobalSelection + ) { + this.selectionFlagsByPanel.set(panelIndex, { + local: info.hasLocalSelection, + global: info.hasGlobalSelection, + }); + } + this.reportedTotalSampleCount = info.total; this.reportedVisibleSampleCount = info.visible; + this.reportedHighlightedSampleCount = info.highlighted; this.reportedEmbeddingSampleSize = info.embeddingSampleSize; this.reportedEmbeddingDescription = info.embeddingDescription; this.reportedEmbeddingType = info.embeddingType; @@ -238,12 +284,14 @@ export class EmbeddingsTab extends React.Component { const applied = this.panel1Ref.current?.applyFilterGlobally(); if (applied) { this.sharedClearFilterRequestId += 1; + this.sharedSelectionEffect = 'highlight'; } } @action.bound private onClearFilter() { this.sharedClearFilterRequestId += 1; + this.sharedSelectionEffect = 'highlight'; } // Plain field write, not a MobX @action - see primaryViewStateHolder. @@ -286,6 +334,7 @@ export class EmbeddingsTab extends React.Component { } for (let i = targetCount + 1; i <= currentCount; i++) { this.hiddenSampleKeysByPanel.delete(i); + this.selectionFlagsByPanel.delete(i); } setTimeout(() => { const updates: { [key: string]: any } = {}; @@ -343,6 +392,7 @@ export class EmbeddingsTab extends React.Component { onSelectionModeChange={ this.onSharedSelectionModeChange } + selectionEffect={this.sharedSelectionEffect} tooltipFields={this.sharedTooltipFields} onTooltipFieldsChange={ this.onSharedTooltipFieldsChange @@ -358,7 +408,9 @@ export class EmbeddingsTab extends React.Component { keys ) } - onReportSampleCounts={this.onReportSampleCounts} + onReportSampleCounts={info => + this.onReportSampleCounts(panelIndex, info) + } clearFilterRequestId={ this.sharedClearFilterRequestId } @@ -382,7 +434,13 @@ export class EmbeddingsTab extends React.Component { } render() { - const isFilterActive = this.sharedHiddenSampleKeys.size > 0; + // Clear/Make Global only apply to this local selection - a page-wide selection is handled elsewhere. + const isLocalSelectionActive = + this.sharedHiddenSampleKeys.size > 0 || + this.reportedHasLocalSelection; + // The Filter/Highlight toggle should also cover a page-wide selection. + const isSelectionActive = + isLocalSelectionActive || this.reportedHasGlobalSelection; return (
{ gap: '12px', marginBottom: '10px', padding: '8px 12px', - backgroundColor: isFilterActive ? '#fff8e1' : '#f8f9fa', - border: isFilterActive + backgroundColor: isSelectionActive + ? '#fff8e1' + : '#f8f9fa', + border: isSelectionActive ? '1px solid #ffe082' : '1px solid #dee2e6', borderRadius: '4px', @@ -507,13 +567,18 @@ export class EmbeddingsTab extends React.Component { gap: '4px', }} > - {isFilterActive ? ( + {isSelectionActive ? ( <> Selection active —{' '} - {this.reportedVisibleSampleCount.toLocaleString()}{' '} + {this.sharedSelectionEffect === 'highlight' + ? this.reportedHighlightedSampleCount.toLocaleString() + : this.reportedVisibleSampleCount.toLocaleString()}{' '} /{' '} {this.reportedTotalSampleCount.toLocaleString()}{' '} - {this.unitLabel} visible + {this.unitLabel}{' '} + {this.sharedSelectionEffect === 'highlight' + ? 'highlighted' + : 'visible'} ) : this.panelCount === 1 || this.sharedLockMap ? ( <> @@ -551,7 +616,7 @@ export class EmbeddingsTab extends React.Component { ) : null} - {!isFilterActive && + {!isSelectionActive && (this.panelCount === 1 || this.sharedLockMap) && ( { /> )} - {isFilterActive && ( -
- - + + +
+ {isLocalSelectionActive && ( + <> + + + + )}
)}
diff --git a/src/shared/cache/ClinicalDataCache.ts b/src/shared/cache/ClinicalDataCache.ts index 94b6f136de0..df94c630845 100644 --- a/src/shared/cache/ClinicalDataCache.ts +++ b/src/shared/cache/ClinicalDataCache.ts @@ -325,7 +325,10 @@ export class UnfilteredClinicalDataCache extends MobxPromiseCache< coverageInformationPromise.result!, customChartClinicalAttributes.result! ); - const coloring = getClinicalAttributeColoring(data, q.datatype); + const coloring = getClinicalAttributeColoring( + data, + q.datatype + ); return { data, ...coloring, @@ -341,7 +344,9 @@ export default class ClinicalDataCache extends MobxPromiseCache< ExtendedClinicalAttribute, ClinicalDataCacheEntry > { - private unfilteredClinicalDataCache: UnfilteredClinicalDataCache; + // Public for consumers that colour points outside the study view + // filter, e.g. the embeddings tab, which dims them in place. + public readonly unfilteredClinicalDataCache: UnfilteredClinicalDataCache; constructor( samplesPromise: MobxPromise, diff --git a/src/shared/components/embeddings/EmbeddingDeckGLVisualization.tsx b/src/shared/components/embeddings/EmbeddingDeckGLVisualization.tsx index f3fd16cef48..4f2ff39d5a2 100644 --- a/src/shared/components/embeddings/EmbeddingDeckGLVisualization.tsx +++ b/src/shared/components/embeddings/EmbeddingDeckGLVisualization.tsx @@ -222,6 +222,8 @@ export class EmbeddingDeckGLVisualization extends React.Component< onToggleCategoryVisibility={ this.props.onToggleCategoryVisibility } + selectedCategories={this.props.selectedCategories} + onToggleCategorySelected={this.props.onToggleCategorySelected} onToggleAllCategories={this.props.onToggleAllCategories} hiddenQcCategories={this.props.hiddenQcCategories} onToggleQcCategoryVisibility={ diff --git a/src/shared/components/embeddings/EmbeddingTypes.tsx b/src/shared/components/embeddings/EmbeddingTypes.tsx index 2f9b8f46b5e..fdf00009238 100644 --- a/src/shared/components/embeddings/EmbeddingTypes.tsx +++ b/src/shared/components/embeddings/EmbeddingTypes.tsx @@ -51,6 +51,8 @@ export interface EmbeddingPoint { strokeColor?: string; displayLabel?: string; isInCohort?: boolean; + // Rendered smaller/more transparent, without changing color or label. + isDeemphasized?: boolean; [key: string]: any; // Allow additional properties for extensibility } @@ -84,6 +86,8 @@ export interface EmbeddingVisualizationProps { >; hiddenCategories?: Set; onToggleCategoryVisibility?: (category: string) => void; + selectedCategories?: Set; + onToggleCategorySelected?: (category: string) => void; onToggleAllCategories?: () => void; // Shared across every split-view panel, unlike hiddenCategories. hiddenQcCategories?: Set; diff --git a/src/shared/components/embeddings/controls/LegendPanel.spec.tsx b/src/shared/components/embeddings/controls/LegendPanel.spec.tsx new file mode 100644 index 00000000000..082975200b6 --- /dev/null +++ b/src/shared/components/embeddings/controls/LegendPanel.spec.tsx @@ -0,0 +1,219 @@ +import { assert } from 'chai'; +import { mount } from 'enzyme'; +import * as React from 'react'; +import { LegendPanel, LegendPanelProps } from './LegendPanel'; +import { EmbeddingPoint } from '../EmbeddingTypes'; + +describe('LegendPanel', () => { + const data: EmbeddingPoint[] = [ + { x: 0, y: 0, sampleId: 's1', displayLabel: 'Lung', color: '#ff0000' }, + { + x: 1, + y: 1, + sampleId: 's2', + displayLabel: 'Breast', + color: '#00ff00', + }, + ]; + + function makeProps( + overrides: Partial = {} + ): LegendPanelProps { + return { + data, + actualHeight: 400, + categoryCounts: new Map([ + ['Lung', 10], + ['Breast', 5], + ]), + visibleCategoryCounts: new Map([ + ['Lung', 10], + ['Breast', 5], + ]), + categoryColors: new Map([ + [ + 'Lung', + { + fillColor: '#ff0000', + strokeColor: '#ff0000', + hasStroke: false, + }, + ], + [ + 'Breast', + { + fillColor: '#00ff00', + strokeColor: '#00ff00', + hasStroke: false, + }, + ], + ]), + hiddenCategories: new Set(), + selectedCategories: new Set(), + onToggleCategoryVisibility: () => {}, + onToggleCategorySelected: () => {}, + ...overrides, + }; + } + + function findRow(wrapper: any, displayLabel: string) { + return wrapper + .find(`span[title="${displayLabel}"]`) + .parents('div') + .filterWhere((n: any) => typeof n.prop('onClick') === 'function') + .first(); + } + + it('a neutral category offers both Select and Hide on hover', () => { + const wrapper = mount(); + findRow(wrapper, 'Lung').simulate('mouseenter'); + + const row = findRow(wrapper.update(), 'Lung'); + assert.include(row.text(), 'Select'); + assert.include(row.text(), 'Hide'); + assert.notInclude(row.text(), 'Unselect'); + }); + + it('an already-selected category offers Unselect instead of Select', () => { + const wrapper = mount( + + ); + findRow(wrapper, 'Lung').simulate('mouseenter'); + + const row = findRow(wrapper.update(), 'Lung'); + assert.include(row.text(), 'Unselect'); + assert.include(row.text(), 'Hide'); + }); + + it('a hidden category only offers Show - it cannot be part of a selection', () => { + const wrapper = mount( + + ); + findRow(wrapper, 'Lung').simulate('mouseenter'); + + const row = findRow(wrapper.update(), 'Lung'); + assert.include(row.text(), 'Show'); + assert.notInclude(row.text(), 'Select'); + }); + + it('swaps the count out for the actions on hover, and back on leave', () => { + const wrapper = mount(); + assert.include(findRow(wrapper, 'Lung').text(), '10'); + + findRow(wrapper, 'Lung').simulate('mouseenter'); + assert.notInclude(findRow(wrapper.update(), 'Lung').text(), '10'); + + findRow(wrapper.update(), 'Lung').simulate('mouseleave'); + assert.include(findRow(wrapper.update(), 'Lung').text(), '10'); + }); + + it('routes each action to its own handler, without the row click also firing', () => { + const selected: string[] = []; + const hidden: string[] = []; + const wrapper = mount( + selected.push(c), + onToggleCategoryVisibility: c => hidden.push(c), + })} + /> + ); + + findRow(wrapper, 'Lung').simulate('mouseenter'); + findRow(wrapper.update(), 'Lung') + .find('[data-test="embeddings-legend-hide-button"]') + .simulate('click'); + assert.deepEqual(hidden, ['Lung']); + assert.deepEqual(selected, []); + + findRow(wrapper.update(), 'Breast').simulate('mouseenter'); + findRow(wrapper.update(), 'Breast') + .find('[data-test="embeddings-legend-select-button"]') + .simulate('click'); + assert.deepEqual(selected, ['Breast']); + assert.deepEqual(hidden, ['Lung']); + }); + + it('shows "in selection / total" when a category is only partly in the selection', () => { + const wrapper = mount( + + ); + assert.include(findRow(wrapper, 'Lung').text(), '3 / 10'); + assert.include(findRow(wrapper, 'Breast').text(), '0 / 5'); + }); + + it('hides a hidden category with the grey/strikethrough treatment', () => { + const wrapper = mount( + + ); + const label = wrapper.find('span[title="Lung"]'); + assert.equal( + (label.prop('style') as any).textDecoration, + 'line-through' + ); + }); + + it('filters categories by a case-insensitive substring search', () => { + const wrapper = mount(); + assert.isTrue(wrapper.find('span[title="Lung"]').exists()); + assert.isTrue(wrapper.find('span[title="Breast"]').exists()); + + wrapper + .find('input[data-test="embeddings-legend-search"]') + .simulate('change', { target: { value: 'lu' } }); + + assert.isTrue( + wrapper + .update() + .find('span[title="Lung"]') + .exists() + ); + assert.isFalse( + wrapper + .update() + .find('span[title="Breast"]') + .exists() + ); + }); + + it('shows a message when the search matches no category', () => { + const wrapper = mount(); + + wrapper + .find('input[data-test="embeddings-legend-search"]') + .simulate('change', { target: { value: 'unknown primary' } }); + + const updated = wrapper.update(); + assert.isFalse(updated.find('span[title="Lung"]').exists()); + assert.isFalse(updated.find('span[title="Breast"]').exists()); + assert.include(updated.text(), 'No matching categories'); + }); + + it('does not show a search box for numeric attributes', () => { + const wrapper = mount( + '#ff0000', + })} + /> + ); + assert.isFalse( + wrapper.find('input[data-test="embeddings-legend-search"]').exists() + ); + }); +}); diff --git a/src/shared/components/embeddings/controls/LegendPanel.tsx b/src/shared/components/embeddings/controls/LegendPanel.tsx index d918caeb657..05d315a5c00 100644 --- a/src/shared/components/embeddings/controls/LegendPanel.tsx +++ b/src/shared/components/embeddings/controls/LegendPanel.tsx @@ -45,42 +45,73 @@ const getVUSColor = (displayLabel: string): string | undefined => { return undefined; }; -const renderLegendItem = ( - displayLabel: string, - styling: { fillColor: string; strokeColor: string; hasStroke: boolean }, - count: number, - visibleCount: number | undefined, - isHidden: boolean, - isClickable: boolean, - onToggleCategoryVisibility?: (category: string) => void -) => { +const ROW_ACTION_STYLE: React.CSSProperties = { + marginLeft: '4px', + flexShrink: 0, + padding: '1px 6px', + fontSize: '10px', + fontWeight: 600, + borderRadius: '3px', + border: '1px solid #ccc', + color: '#555', + backgroundColor: 'white', + cursor: 'pointer', +}; + +interface LegendItemRowProps { + displayLabel: string; + styling: { fillColor: string; strokeColor: string; hasStroke: boolean }; + count: number; + visibleCount: number | undefined; + isHidden: boolean; + isSelected: boolean; + isClickable: boolean; + onToggleCategoryVisibility?: (category: string) => void; + onToggleCategorySelected?: (category: string) => void; +} + +const LegendItemRow: React.FC = ({ + displayLabel, + styling, + count, + visibleCount, + isHidden, + isSelected, + isClickable, + onToggleCategoryVisibility, + onToggleCategorySelected, +}) => { + const [isHovered, setIsHovered] = React.useState(false); + const isDimmed = isHidden; + const canSelect = isClickable && !isHidden && !!onToggleCategorySelected; return (
{ - if (isClickable && onToggleCategoryVisibility) { - onToggleCategoryVisibility(displayLabel); - } - }} - onMouseEnter={e => { - if (isClickable) { - e.currentTarget.style.backgroundColor = '#f5f5f5'; - } - }} - onMouseLeave={e => { - if (isClickable) { - e.currentTarget.style.backgroundColor = 'transparent'; + if (canSelect && onToggleCategorySelected) { + onToggleCategorySelected(displayLabel); } }} + onMouseEnter={() => isClickable && setIsHovered(true)} + onMouseLeave={() => setIsHovered(false)} >
@@ -132,9 +163,9 @@ const renderLegendItem = ( {displayLabel} - - {visibleCount !== undefined && visibleCount !== count - ? `${formatCount(visibleCount)} / ${formatCount(count)}` - : formatCount(count)} - + {/* The count gives way to the actions on hover - the row is too narrow for both. */} + {isClickable && isHovered ? ( + + {canSelect && ( + { + e.stopPropagation(); + onToggleCategorySelected!(displayLabel); + }} + > + {isSelected ? 'Unselect' : 'Select'} + + )} + { + e.stopPropagation(); + onToggleCategoryVisibility!(displayLabel); + }} + > + {isHidden ? 'Show' : 'Hide'} + + + ) : ( + + {visibleCount !== undefined && visibleCount !== count + ? `${formatCount(visibleCount)} / ${formatCount( + count + )}` + : formatCount(count)} + + )}
); @@ -445,6 +506,8 @@ export interface LegendPanelProps { >; hiddenCategories?: Set; onToggleCategoryVisibility?: (category: string) => void; + selectedCategories?: Set; + onToggleCategorySelected?: (category: string) => void; onToggleAllCategories?: () => void; hiddenQcCategories?: Set; onToggleQcCategoryVisibility?: (category: string) => void; @@ -483,6 +546,8 @@ export const LegendPanel: React.FC = ({ categoryColors, hiddenCategories, onToggleCategoryVisibility, + selectedCategories, + onToggleCategorySelected, onToggleAllCategories, hiddenQcCategories, onToggleQcCategoryVisibility, @@ -506,6 +571,7 @@ export const LegendPanel: React.FC = ({ }) => { const [isConfigExpanded, setIsConfigExpanded] = React.useState(false); const [localIsCollapsed, setLocalIsCollapsed] = React.useState(false); + const [searchQuery, setSearchQuery] = React.useState(''); const isCollapsed = controlledIsCollapsed !== undefined ? controlledIsCollapsed @@ -623,6 +689,16 @@ export const LegendPanel: React.FC = ({ return null; } + // Categorical attributes like Cancer Type Detailed can carry dozens of + // entries (e.g. distinguishing "Unknown Primary" among them by eye is + // impractical) - a plain substring filter finds them by name instead. + const trimmedQuery = searchQuery.trim().toLowerCase(); + const filteredBiologicalEntries = trimmedQuery + ? biologicalEntries.filter(([displayLabel]) => + displayLabel.toLowerCase().includes(trimmedQuery) + ) + : biologicalEntries; + if (isCollapsed) { return (