diff --git a/docs/configuration_file.md b/docs/configuration_file.md index d2a2232b0..bb31fa636 100644 --- a/docs/configuration_file.md +++ b/docs/configuration_file.md @@ -20,7 +20,7 @@ https://volview.kitware.com/?urls=[https://example.com/data.nrrd,https://example ## View Layouts -Define one or more named layouts using the `layouts` key. VolView will use the first layout as the default. Each named layout will be in the layout selector menu. Layout are specified in three formats: +Define one or more named layouts using the `layouts` key. VolView will use the first layout as the default, unless a session file opened alongside the config restores its own layout. Each named layout will be in the layout selector menu. Layout are specified in three formats: ### 1. Grid with View Types (2D String Array) diff --git a/docs/toolbar.md b/docs/toolbar.md index 6ed690683..454eeda00 100644 --- a/docs/toolbar.md +++ b/docs/toolbar.md @@ -2,7 +2,7 @@ ## Layout -Use the layout button to choose between window arrangements. Each view can display a different dataset. Use the view type switcher dropdown in each view to change between 2D slice, 3D volume, or oblique views. Double-click a view to maximize it. +Use the layout button to choose between window arrangements. Picking a named layout or a grid starts over with new views showing the current image, so earlier view settings such as slice and zoom are not kept. Each view can display a different dataset. Use the view type switcher dropdown in each view to change between 2D slice, 3D volume, or oblique views. Use the View actions button beside the view type selector to maximize or restore that view, or to split it side by side or top and bottom. You can split again to add more views within the same area. The new view starts with the same image and view settings. Standard slice and camera settings can be adjusted independently; window/level remains synchronized. Oblique views share their slice center and plane orientation. Close view removes a pane and expands its neighbor; at least one view stays open. Empty views and cine views also have this button. In a narrow view, the view type choices move into the View actions menu. Split actions remain visible but are disabled when the resulting panes would be too small to use; hover or focus the disabled action to see why. Double-clicking a view also maximizes or restores it. Drag a view's grip onto another view to move it, or drag the line between views to resize them. ![Layout](./assets/07-volview-layout-notes.jpg) diff --git a/src/components/CineViewerOverlay.vue b/src/components/CineViewerOverlay.vue index e808581b7..ec851e2f2 100644 --- a/src/components/CineViewerOverlay.vue +++ b/src/components/CineViewerOverlay.vue @@ -1,12 +1,19 @@ diff --git a/src/components/LayoutGrid.vue b/src/components/LayoutGrid.vue index 710dc2e71..d0afac7cc 100644 --- a/src/components/LayoutGrid.vue +++ b/src/components/LayoutGrid.vue @@ -1,88 +1,338 @@ - - - - + + diff --git a/src/components/LayoutGridItem.vue b/src/components/LayoutGridItem.vue index 87e0e8d5f..3af19fe5c 100644 --- a/src/components/LayoutGridItem.vue +++ b/src/components/LayoutGridItem.vue @@ -1,7 +1,8 @@ @@ -84,7 +81,11 @@ const isLockedOrientationView = computed(() => diff --git a/src/components/ViewLayoutActions.vue b/src/components/ViewLayoutActions.vue new file mode 100644 index 000000000..05db67b13 --- /dev/null +++ b/src/components/ViewLayoutActions.vue @@ -0,0 +1,120 @@ + + + diff --git a/src/components/ViewMoveHandle.vue b/src/components/ViewMoveHandle.vue new file mode 100644 index 000000000..19a19b0e7 --- /dev/null +++ b/src/components/ViewMoveHandle.vue @@ -0,0 +1,55 @@ + + + + + diff --git a/src/components/ViewOverlayGrid.vue b/src/components/ViewOverlayGrid.vue index 3971ba688..180484348 100644 --- a/src/components/ViewOverlayGrid.vue +++ b/src/components/ViewOverlayGrid.vue @@ -55,6 +55,27 @@ flex: 1; } +/* An empty center cell gives its share to the text beside it. */ +.cell.center { + flex: 0 1 auto; +} + +/* Narrow panes squeeze the text cells so the right-hand controls stay inside. */ +.cell.left, +.cell.center { + min-width: 0; +} + +/* Text truncates in its own cell instead of running under the controls. */ +.cell.left > :global(*), +.cell.center > :global(*), +.cell.left > :global(*) > :global(div), +.cell.center > :global(*) > :global(div) { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + .top, .left { align-items: flex-start; diff --git a/src/components/ViewTypeSwitcher.vue b/src/components/ViewTypeSwitcher.vue index e8e3b3956..c7b0d0240 100644 --- a/src/components/ViewTypeSwitcher.vue +++ b/src/components/ViewTypeSwitcher.vue @@ -1,17 +1,35 @@ diff --git a/src/enface/__tests__/layout.spec.ts b/src/enface/__tests__/layout.spec.ts index e43a40012..4944e3494 100644 --- a/src/enface/__tests__/layout.spec.ts +++ b/src/enface/__tests__/layout.spec.ts @@ -12,8 +12,6 @@ import LayoutSelector from '@/src/components/LayoutSelector.vue'; import ViewTypeSwitcher from '@/src/components/ViewTypeSwitcher.vue'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useViewStore } from '@/src/store/views'; -import { useViewSliceStore } from '@/src/store/view-configs/slicing'; -import { useEnFaceViewStore } from '@/src/enface/store'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; enableAutoUnmount(afterEach); @@ -39,7 +37,6 @@ function configureComparison() { describe('En face view configuration', () => { it.each([ ['named', true], - ['regridded', false], ['retyped', false], ] as const)( 'highlights a %s layout after restore only when its panes match', @@ -49,7 +46,6 @@ describe('En face view configuration', () => { views.setDataForAllViews('oct'); configureComparison(); views.switchToNamedLayout('Comparison'); - if (selection === 'regridded') views.setLayoutFromGrid([2, 1]); if (selection === 'retyped') views.replaceView(views.layoutViews[1].id, { name: 'Oblique', @@ -57,9 +53,6 @@ describe('En face view configuration', () => { dataID: 'oct', options: {}, }); - const hidden = views - .getAllViews() - .filter((view) => !views.layoutViews.includes(view)); const saved = await serialize({ writers: [ (state) => { @@ -92,9 +85,6 @@ describe('En face view configuration', () => { dataID: 'restored-oct', }, ]); - hidden.forEach(({ id, type }) => - expect(restored.getView(id)?.type).toBe(type) - ); const wrapper = mount(LayoutSelector, { global: { plugins: [createVuetify()] }, }); @@ -123,33 +113,18 @@ describe('En face view configuration', () => { ); }); - it('preserves matching view ids, slice and projection settings on named layout reselection', async () => { + it('replaces both views with fresh views of the image when a named layout is picked again', async () => { await loadVolume('oct'); const views = useViewStore(); views.setDataForAllViews('oct'); configureComparison(); views.switchToNamedLayout('Comparison'); const [source, enface] = views.visibleViews; - const ids = views.visibleViews.map(({ id }) => id); - const projection = useEnFaceViewStore().configFor(enface.id, 'oct'); - Object.assign(projection, { - method: 'max', - depthStart: 1, - depthEnd: 2, - thresholdMicrons: 31.5, - }); - useViewSliceStore().updateConfig(source.id, 'oct', { slice: 2 }); - views.setActiveView(enface.id); + views.switchToNamedLayout('Comparison'); - expect(views.visibleViews.map(({ id }) => id)).toEqual(ids); - expect(views.activeView).toBe(enface.id); - expect(useEnFaceViewStore().configFor(enface.id, 'oct')).toBe(projection); - expect(projection).toMatchObject({ - method: 'max', - depthStart: 1, - depthEnd: 2, - thresholdMicrons: 31.5, - }); - expect(useViewSliceStore().getConfig(source.id, 'oct').slice).toBe(2); + const [nextSource, nextEnface] = views.visibleViews; + expect([nextSource.id, nextEnface.id]).not.toContain(source.id); + expect([nextSource.id, nextEnface.id]).not.toContain(enface.id); + expect(nextEnface.dataID).toBe('oct'); }); }); diff --git a/src/enface/__tests__/store.spec.ts b/src/enface/__tests__/store.spec.ts index d3dd72e8f..9c02b9cdc 100644 --- a/src/enface/__tests__/store.spec.ts +++ b/src/enface/__tests__/store.spec.ts @@ -7,6 +7,7 @@ import { } from '@/src/enface/store'; import { ManifestSchema, type StateFile } from '@/src/io/state-file/schema'; import { parseNamedLayouts } from '@/src/utils/layoutParsing'; +import { layoutLeaves } from '@/src/utils/layoutEditing'; import { computeEffectiveView } from '@/src/core/views/effectiveView'; import { useViewConfigStore } from '@/src/store/view-configs'; import { useWindowingStore } from '@/src/store/view-configs/windowing'; @@ -188,11 +189,12 @@ describe('En face view settings', () => { it('resolves custom enface layouts without treating the projection as a slice', () => { const parsed = parseNamedLayouts({ OCT: [['enface', 'coronal']] }); - expect(parsed.OCT.views[0]).toMatchObject({ + const [enface] = layoutLeaves(parsed.OCT).map((leaf) => leaf.view); + expect(enface).toMatchObject({ type: 'EnFace', name: 'En face', }); - const view = { ...parsed.OCT.views[0], id: 'enface' }; + const view = { ...enface, id: 'enface' }; expect(computeEffectiveView(view, 'oct').kind).toBe('enface'); expect(computeEffectiveView(view, null).kind).toBe('empty'); }); diff --git a/src/enface/store.ts b/src/enface/store.ts index 79807a871..b3c649b91 100644 --- a/src/enface/store.ts +++ b/src/enface/store.ts @@ -2,6 +2,7 @@ import { defineStore } from 'pinia'; import { reactive } from 'vue'; import { createViewConfigSerializer } from '@/src/store/view-configs/common'; import { + cloneEntries, deleteSecondKey, getDoubleKeyRecord, type DoubleKeyRecord, @@ -126,6 +127,12 @@ export const useEnFaceViewStore = defineStore('enface-view', () => { delete controlStates[viewID]; } + function copyView(sourceID: string, targetID: string) { + cloneEntries(configs, sourceID).forEach(([dataID, config]) => + Object.assign(configFor(targetID, dataID), config) + ); + } + function removeData(dataID: string, viewID?: string) { if (viewID) { delete configs[viewID]?.[dataID]; @@ -166,6 +173,7 @@ export const useEnFaceViewStore = defineStore('enface-view', () => { controlStateFor, setControlState, removeView, + copyView, removeData, serialize, deserialize, diff --git a/src/io/import/__tests__/restoreLayoutViews.spec.ts b/src/io/import/__tests__/restoreLayoutViews.spec.ts new file mode 100644 index 000000000..4cb37a0c9 --- /dev/null +++ b/src/io/import/__tests__/restoreLayoutViews.spec.ts @@ -0,0 +1,46 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { setActivePinia, createPinia } from 'pinia'; +import { readSessionSetup } from '@/src/io/import/__tests__/restoreProcessorFixtures'; + +const savedView = (id: string) => ({ + id, + name: 'Axial', + type: '2D', + dataID: null, + options: { orientation: 'Axial' }, + config: { image: { slice: { slice: 3, min: 0, max: 9, syncState: false } } }, +}); + +const leaf = (viewId: string) => ({ type: 'view', viewId }); + +describe('restoring saved views', () => { + beforeEach(() => setActivePinia(createPinia())); + + it('restores settings only for the views its layout shows', async () => { + const { manifest } = await readSessionSetup({ + version: '9.0.0', + dataSources: [], + layout: { direction: 'row', items: [leaf('a'), leaf('b')] }, + viewByID: { + a: savedView('a'), + b: savedView('b'), + hidden: savedView('hidden'), + }, + }); + + expect(Object.keys(manifest.viewByID ?? {})).toEqual(['a', 'b']); + }); + + it('restores no saved views when the layout cannot be restored', async () => { + const { manifest } = await readSessionSetup({ + version: '9.0.0', + dataSources: [], + layout: { direction: 'row', items: [leaf('a'), leaf('a')] }, + activeView: 'a', + viewByID: { a: savedView('a') }, + }); + + expect(manifest.viewByID).toBeUndefined(); + expect(manifest.activeView).toBeUndefined(); + }); +}); diff --git a/src/io/import/common.ts b/src/io/import/common.ts index b29ce5174..d695eb34b 100644 --- a/src/io/import/common.ts +++ b/src/io/import/common.ts @@ -123,6 +123,8 @@ export type ImportContext = { fetchFileCache?: FetchCache; archiveCache?: ArchiveCache; dicomDataSources?: DataSource[]; + /** Set once a state file in this import has restored its layout. */ + restoredLayout?: boolean; onCleanup?: (fn: () => void) => void; importDataSources?: ( dataSources: DataSource[] diff --git a/src/io/import/configJson.ts b/src/io/import/configJson.ts index 1d90ea9ef..ef0ad161f 100644 --- a/src/io/import/configJson.ts +++ b/src/io/import/configJson.ts @@ -226,7 +226,7 @@ const reportUnparseableColors = ( if (message) addError(message); }; -const applyLayout = (manifest: Config) => { +const applyLayout = (manifest: Config, keepLayout: boolean) => { if (!manifest.layouts) return; const viewStore = useViewStore(); @@ -236,8 +236,7 @@ const applyLayout = (manifest: Config) => { viewStore.setNamedLayoutsFromConfig(manifest.layouts); - const firstLayoutName = layoutEntries[0][0]; - viewStore.switchToNamedLayout(firstLayoutName); + if (!keepLayout) viewStore.switchToNamedLayout(layoutEntries[0][0]); }; /** @@ -309,9 +308,12 @@ const applyRegisteredSections = (manifest: Config) => ) ); -export const applyPreStateConfig = async (manifest: Config) => { +export const applyPreStateConfig = async ( + manifest: Config, + { keepLayout = false } = {} +) => { applyDisabledViewTypes(manifest); - applyLayout(manifest); + applyLayout(manifest, keepLayout); applyShortcuts(manifest); applyIo(manifest); applyWindowing(manifest); diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 151ce62e9..01f40e1d0 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -182,7 +182,10 @@ async function processImportQueue( case 'config': configResults.push(result); try { - await applyPreStateConfig(result.config); + // A session restored in this import keeps its own layout. + await applyPreStateConfig(result.config, { + keepLayout: importContext.restoredLayout === true, + }); } catch (err) { results.push(asErrorResult(ensureError(err), result.dataSource)); } diff --git a/src/io/import/processors/restoreStateFile.ts b/src/io/import/processors/restoreStateFile.ts index 4049d723a..9b515aadd 100644 --- a/src/io/import/processors/restoreStateFile.ts +++ b/src/io/import/processors/restoreStateFile.ts @@ -10,7 +10,7 @@ import { StateFileSetupResult, } from '@/src/io/import/common'; import { MANIFEST, isStateFile } from '@/src/io/state-file/serialize'; -import { partition, getURLBasename } from '@/src/utils'; +import { omit, partition, pick, getURLBasename } from '@/src/utils'; import { basename } from '@/src/utils/path'; import { planLabelmapSources } from '@/src/io/import/labelmapImports'; import { deserializeSegmentation } from '@/src/segmentation/io/stateFile'; @@ -20,7 +20,8 @@ import { useLayersStore } from '@/src/store/datasets-layers'; import { extractFilesFromZip } from '@/src/io/zip'; import type { FileEntry } from '@/src/io/types'; import { Skip } from '@/src/utils/evaluateChain'; -import { useViewStore } from '@/src/store/views'; +import { isRestorableLayout, useViewStore } from '@/src/store/views'; +import { layoutViewIds } from '@/src/utils/layoutEditing'; import { useViewConfigStore } from '@/src/store/view-configs'; import { migrateManifest, @@ -338,7 +339,20 @@ async function parseManifestFromJson(file: File) { return { manifestString, stateFiles: [] as FileEntry[] }; } -export const restoreStateFile: ImportHandler = async (dataSource) => { +// Only the panes of a restored layout get views, so other saved views must not +// bind data or settings. A rejected layout keeps the current views instead. +const withLayoutViews = (manifest: Manifest) => { + const saved = manifest.viewByID; + if (!saved) return manifest; + if (!isRestorableLayout(manifest.layout, saved)) + return omit(manifest, ['viewByID', 'activeView', 'isActiveViewMaximized']); + return { + ...manifest, + viewByID: pick(saved, ...layoutViewIds(manifest.layout)), + }; +}; + +export const restoreStateFile: ImportHandler = async (dataSource, context) => { if (dataSource.type === 'file' && (await isStateFile(dataSource.file))) { const isJson = dataSource.fileType === 'application/json'; const { manifestString, stateFiles } = isJson @@ -351,7 +365,7 @@ export const restoreStateFile: ImportHandler = async (dataSource) => { let migration: ManifestMigration; try { const migrated = migrateManifest(manifestString); - manifest = ManifestSchema.parse(migrated.manifest); + manifest = withLayoutViews(ManifestSchema.parse(migrated.manifest)); migration = migrated.migration; } catch (e) { return asErrorResult( @@ -360,7 +374,8 @@ export const restoreStateFile: ImportHandler = async (dataSource) => { ); } - useViewStore().deserializeLayout(manifest); + if (useViewStore().deserializeLayout(manifest) && context) + context.restoredLayout = true; const { dataSources, missingFiles } = prepareLeafDataSources( manifest, diff --git a/src/io/state-file/__tests__/layerDisplaySaveSnapshot.spec.ts b/src/io/state-file/__tests__/layerDisplaySaveSnapshot.spec.ts index e0e20bedf..c85dde6f3 100644 --- a/src/io/state-file/__tests__/layerDisplaySaveSnapshot.spec.ts +++ b/src/io/state-file/__tests__/layerDisplaySaveSnapshot.spec.ts @@ -40,6 +40,13 @@ async function loadImages(base: string, overlay: string) { seatStatistics(getLayerId(base, overlay)); } +// Maximizing the first view hides the retained one. +const maximizeFirstView = () => { + const views = useViewStore(); + views.setActiveView(views.layoutViews[0].id); + views.toggleActiveViewMaximized(); +}; + const views2D = () => useViewStore() .getAllViews() @@ -79,7 +86,7 @@ async function restoreManifest(manifest: Manifest) { 'restoredBase', 'restoredOverlay' ))!; - views.switchToNamedLayout('Four Up'); + if (views.maximizedView) views.toggleActiveViewMaximized(); views.visibleViews .filter((view) => view.type === '2D') .forEach((view) => useLayerColoringStore().getConfig(view.id, layerID)); @@ -91,15 +98,17 @@ it.each([false, true])( async (readd) => { const { layerID, retainedView } = await prepareScene(); await exportManifest(); - const views = useViewStore(); - views.switchToNamedLayout('Axial Only'); + maximizeFirstView(); const layers = useLayersStore(); layers.deleteLayer('base', 'overlay'); await nextTick(); if (readd) { seatStatistics(layerID); await layers._addLayer('base', 'overlay'); - useLayerColoringStore().getConfig(views.visibleViews[0].id, layerID); + useLayerColoringStore().getConfig( + useViewStore().visibleViews[0].id, + layerID + ); } const saved = await exportManifest(); @@ -114,7 +123,7 @@ it.each([false, true])( const restoredLayerID = await restoreManifest(saved); const reexported = await exportManifest(); - expect(reexported.layoutSlots).toContain(retainedView.id); + expect(reexported.viewByID).toHaveProperty(retainedView.id); expect( Object.values(reexported.viewByID!) .filter((view) => view.type === '2D') @@ -142,7 +151,7 @@ it('preserves current per-view appearance and other view settings across repeate }, }); await exportManifest(); - useViewStore().switchToNamedLayout('Axial Only'); + maximizeFirstView(); const saved = await exportManifest(); const restoredLayerID = await restoreManifest(saved); const reexported = await exportManifest(); @@ -164,9 +173,14 @@ it('saves reset base appearance without losing retained slice and camera setting useSyncWindowing(); const views = useViewStore(); views.setDataForAllViews('base'); - views.switchToNamedLayout('Oblique'); - const obliqueView = views.visibleViews[0]; - const retainedView = views2D()[0]; + views.replaceView(views.layoutViews[3].id, { + name: 'Oblique', + type: 'Oblique', + dataID: 'base', + options: {}, + }); + const obliqueView = views.layoutViews[3]; + const retainedView = views2D()[1]; useViewSliceStore().updateConfig(retainedView.id, 'base', { slice: 0 }); useViewCameraStore().updateConfig(retainedView.id, 'base', { parallelScale: 2, diff --git a/src/io/state-file/__tests__/migrate700To800.spec.ts b/src/io/state-file/__tests__/migrate700To800.spec.ts index 9cc7808a6..4940d6557 100644 --- a/src/io/state-file/__tests__/migrate700To800.spec.ts +++ b/src/io/state-file/__tests__/migrate700To800.spec.ts @@ -83,7 +83,7 @@ describe('7.0.0 to 8.0.0 migration', () => { ), }); - expect(migrated.version).toBe('8.0.0'); + expect(migrated.version).toBe('9.0.0'); expect(migrated).not.toHaveProperty('selectedSegment'); expect(migrated).not.toHaveProperty('segments'); expect(migrated).not.toHaveProperty('segmentations'); diff --git a/src/io/state-file/__tests__/migrate800To900.spec.ts b/src/io/state-file/__tests__/migrate800To900.spec.ts new file mode 100644 index 000000000..bb7601cb7 --- /dev/null +++ b/src/io/state-file/__tests__/migrate800To900.spec.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest'; + +import { migrateManifest } from '@/src/io/state-file/migrations'; +import { ManifestSchema } from '@/src/io/state-file/schema'; + +const view = (id: string, orientation: string) => ({ + id, + name: orientation, + type: '2D', + dataID: null, + options: { orientation }, +}); + +const migrate = (overrides: Record) => + ManifestSchema.parse( + migrateManifest( + JSON.stringify({ version: '8.0.0', dataSources: [], ...overrides }) + ).manifest + ); + +describe('8.0.0 -> 9.0.0 migration', () => { + it('names each layout view and drops views the layout hid', () => { + const manifest = migrate({ + activeView: 'hidden', + layout: { + direction: 'column', + items: [ + { type: 'slot', slotIndex: 1 }, + { + type: 'layout', + direction: 'row', + items: [ + { type: 'slot', slotIndex: 0 }, + { type: 'slot', slotIndex: 3 }, + ], + }, + ], + }, + layoutSlots: ['a', 'b', 'hidden', 'c'], + viewByID: { + a: view('a', 'Axial'), + b: view('b', 'Coronal'), + hidden: view('hidden', 'Sagittal'), + c: view('c', 'Axial'), + }, + }); + + expect(manifest.version).toBe('9.0.0'); + expect(manifest.layout).toEqual({ + direction: 'column', + items: [ + { type: 'view', viewId: 'b' }, + { + type: 'layout', + direction: 'row', + items: [ + { type: 'view', viewId: 'a' }, + { type: 'view', viewId: 'c' }, + ], + }, + ], + }); + expect(Object.keys(manifest.viewByID!)).toEqual(['a', 'b', 'c']); + expect(manifest).not.toHaveProperty('activeView'); + expect(manifest).not.toHaveProperty('layoutSlots'); + }); + + it('drops the maximized flag along with a hidden active view', () => { + const manifest = migrate({ + activeView: 'hidden', + isActiveViewMaximized: true, + layout: { direction: 'column', items: [{ type: 'slot', slotIndex: 0 }] }, + layoutSlots: ['a', 'hidden'], + viewByID: { a: view('a', 'Axial'), hidden: view('hidden', 'Coronal') }, + }); + expect(manifest).not.toHaveProperty('activeView'); + expect(manifest).not.toHaveProperty('isActiveViewMaximized'); + }); + + it('drops a layout whose slot has no saved view', () => { + const manifest = migrate({ + activeView: 'a', + layout: { direction: 'row', items: [{ type: 'slot', slotIndex: 0 }] }, + viewByID: { a: view('a', 'Axial') }, + }); + expect(manifest).not.toHaveProperty('layout'); + expect(manifest).not.toHaveProperty('activeView'); + }); + + it('keeps a shown maximized view', () => { + const manifest = migrate({ + activeView: 'a', + isActiveViewMaximized: true, + layout: { direction: 'column', items: [{ type: 'slot', slotIndex: 0 }] }, + layoutSlots: ['a'], + viewByID: { a: view('a', 'Axial') }, + }); + expect(manifest.activeView).toBe('a'); + expect(manifest.isActiveViewMaximized).toBe(true); + }); +}); diff --git a/src/io/state-file/__tests__/segmentationArtifactSource.spec.ts b/src/io/state-file/__tests__/segmentationArtifactSource.spec.ts index 3aeb9a395..d83685703 100644 --- a/src/io/state-file/__tests__/segmentationArtifactSource.spec.ts +++ b/src/io/state-file/__tests__/segmentationArtifactSource.spec.ts @@ -135,6 +135,6 @@ describe('image segments wire shape', () => { describe('manifest version', () => { it('writes the image segment ownership version', () => { - expect(MANIFEST_VERSION).toBe('8.0.0'); + expect(MANIFEST_VERSION).toBe('9.0.0'); }); }); diff --git a/src/io/state-file/__tests__/serializeResilience.spec.ts b/src/io/state-file/__tests__/serializeResilience.spec.ts index 14d7703a9..f7812bb82 100644 --- a/src/io/state-file/__tests__/serializeResilience.spec.ts +++ b/src/io/state-file/__tests__/serializeResilience.spec.ts @@ -173,9 +173,8 @@ describe('state-file serialization resilience', () => { isActiveViewMaximized: true, layout: { direction: 'column', - items: [{ type: 'slot', slotIndex: 0 }], + items: [{ type: 'view', viewId: 'view-1' }], }, - layoutSlots: ['view-1'], viewByID: { 'view-1': { id: 'view-1', @@ -193,7 +192,6 @@ describe('state-file serialization resilience', () => { expect(normalized.manifest).not.toHaveProperty('activeView'); expect(normalized.manifest).not.toHaveProperty('isActiveViewMaximized'); expect(normalized.manifest).not.toHaveProperty('layout'); - expect(normalized.manifest).not.toHaveProperty('layoutSlots'); expect(normalized.omitted).toContain('view/layout: invalid viewByID state'); }); diff --git a/src/io/state-file/migrations.ts b/src/io/state-file/migrations.ts index a7168f28e..d24dbeb30 100644 --- a/src/io/state-file/migrations.ts +++ b/src/io/state-file/migrations.ts @@ -660,6 +660,46 @@ const migrate700To800 = (inputManifest: any, migration: ManifestMigration) => { return manifest; }; +// A 9.0.0 layout leaf names its view ID, and viewByID holds only the views +// the layout shows. +const migrate800To900 = (inputManifest: any) => { + const manifest = JSON.parse(JSON.stringify(inputManifest)); + const slots: unknown[] = Array.isArray(manifest.layoutSlots) + ? manifest.layoutSlots + : []; + const convertItem = (item: any): any => { + if (item?.type !== 'slot') + return Array.isArray(item?.items) + ? { ...item, items: item.items.map(convertItem) } + : item; + return { type: 'view', viewId: slots[item.slotIndex] }; + }; + const leafIds = (item: any): unknown[] => { + if (item?.type === 'view') return [item.viewId]; + return Array.isArray(item?.items) ? item.items.flatMap(leafIds) : []; + }; + if (Array.isArray(manifest.layout?.items)) { + manifest.layout.items = manifest.layout.items.map(convertItem); + const ids = manifest.layout.items.flatMap(leafIds); + // A slot no saved view fills leaves a layout that cannot be restored. + if (!ids.every((id: unknown) => typeof id === 'string')) + delete manifest.layout; + const shown = new Set(manifest.layout ? ids : []); + if (manifest.viewByID) { + manifest.viewByID = Object.fromEntries( + Object.entries(manifest.viewByID).filter(([id]) => shown.has(id)) + ); + } + if (manifest.activeView && !shown.has(manifest.activeView)) { + delete manifest.activeView; + delete manifest.isActiveViewMaximized; + } + } + delete manifest.layoutSlots; + manifest.version = '9.0.0'; + return manifest; +}; + export const migrateManifest = (manifestString: string) => { const inputManifest = JSON.parse(manifestString); const migration: ManifestMigration = { droppedMasks: [] }; @@ -671,7 +711,8 @@ export const migrateManifest = (manifestString: string) => { migrateOrPass(['6.3.0'], migrate630To640), // No 6.2.0 -> 6.3.0 step exists, so a 6.2 manifest arrives here directly. migrateOrPass(['6.2.0', '6.4.0'], migrate640To700), - migrateOrPass(['7.0.0'], (legacy) => migrate700To800(legacy, migration)) + migrateOrPass(['7.0.0'], (legacy) => migrate700To800(legacy, migration)), + migrateOrPass(['8.0.0'], migrate800To900) ); return { manifest, migration }; }; diff --git a/src/io/state-file/schema.ts b/src/io/state-file/schema.ts index e9a715e6c..5158617e4 100644 --- a/src/io/state-file/schema.ts +++ b/src/io/state-file/schema.ts @@ -114,13 +114,14 @@ const LayoutDirectionNative = z.enum([ const LayoutItem: z.ZodType = z.lazy(() => z.union([ z.object({ - type: z.literal('slot'), - slotIndex: z.number(), + type: z.literal('view'), + viewId: z.string(), }), z.object({ type: z.literal('layout'), direction: LayoutDirectionNative, items: z.array(LayoutItem), + sizes: z.array(z.number()).optional(), }), ]) ); @@ -129,6 +130,7 @@ const Layout: z.ZodType = z.lazy(() => z.object({ direction: LayoutDirectionNative, items: z.array(LayoutItem), + sizes: z.array(z.number()).optional(), }) ); @@ -531,7 +533,6 @@ export const ManifestSchema = z.object({ viewByID: z.record(z.string(), View).optional(), primarySelection: z.string().optional(), layout: Layout.optional(), - layoutSlots: z.array(z.string()).optional(), parentToLayers: ParentToLayers.optional(), layerDisplay: z.record(z.string(), LayerDisplayConfig).optional(), }); diff --git a/src/io/state-file/serialize.ts b/src/io/state-file/serialize.ts index 1f0fbb521..3931a134a 100644 --- a/src/io/state-file/serialize.ts +++ b/src/io/state-file/serialize.ts @@ -41,7 +41,7 @@ declareManifestRefs('primarySelection', (manifest) => ); export const MANIFEST = 'manifest.json'; -export const MANIFEST_VERSION = '8.0.0'; +export const MANIFEST_VERSION = '9.0.0'; type ManifestCandidate = Record; @@ -228,16 +228,15 @@ export function normalizeManifest(manifest: Manifest, zip: JSZip) { ); } - // These fields jointly describe the view layout. In particular, layoutSlots - // and activeView only make sense when their IDs can be resolved through - // viewByID. If that root is invalid, omit the complete cluster rather than - // saving slots that cannot be restored. + // These fields jointly describe the view layout. In particular, layout + // leaves and activeView only make sense when their IDs can be resolved + // through viewByID. If that root is invalid, omit the complete cluster + // rather than saving panes that cannot be restored. const viewLayoutRoots = new Set([ 'activeView', 'isActiveViewMaximized', 'viewByID', 'layout', - 'layoutSlots', ]); const invalidViewByID = candidate.viewByID !== undefined && @@ -259,7 +258,6 @@ export function normalizeManifest(manifest: Manifest, zip: JSZip) { 'viewByID', 'primarySelection', 'layout', - 'layoutSlots', ] as const; const optionalEntries = optionalRoots.flatMap((key) => { if (invalidViewByID && viewLayoutRoots.has(key)) return []; @@ -333,7 +331,6 @@ export async function serialize( direction: 'column', items: [], }, - layoutSlots: [], viewByID: {}, isActiveViewMaximized: false, parentToLayers: [], diff --git a/src/segmentation/__tests__/imageSetInitialization.spec.ts b/src/segmentation/__tests__/imageSetInitialization.spec.ts index dfc9e06fc..c6748c60f 100644 --- a/src/segmentation/__tests__/imageSetInitialization.spec.ts +++ b/src/segmentation/__tests__/imageSetInitialization.spec.ts @@ -363,14 +363,12 @@ describe('image segment initialization boundaries', () => { ? { layout: { direction: 'row', - items: Array.from({ length: slotCount }, (_, slotIndex) => ({ - type: 'slot', - slotIndex, - })), + items: [incomingViewId, previousViewId] + .slice(0, slotCount) + .map((viewId) => ({ type: 'view', viewId })), }, } : {}), - layoutSlots: [incomingViewId, previousViewId], isActiveViewMaximized: true, ...(savedViews ? { diff --git a/src/store/__tests__/datasetRemoveCascade.spec.ts b/src/store/__tests__/datasetRemoveCascade.spec.ts index b2c503889..5d5a16eaa 100644 --- a/src/store/__tests__/datasetRemoveCascade.spec.ts +++ b/src/store/__tests__/datasetRemoveCascade.spec.ts @@ -213,7 +213,10 @@ describe('manifest-ref declarations (cascade-owned save backstop coverage)', () const refs = collectManifestRefs({ viewByID: { 'view-1': { dataID: 'ghost-img' } }, activeView: 'ghost-view', - layoutSlots: ['ghost-slot'], + layout: { + direction: 'row', + items: [{ type: 'view', viewId: 'ghost-slot' }], + }, tools: { rulers: { tools: [{ imageID: 'ghost-ruler-img' }] }, rectangles: { tools: [{ imageID: 'ghost-rect-img' }] }, @@ -232,7 +235,7 @@ describe('manifest-ref declarations (cascade-owned save backstop coverage)', () const found = refs.map((ref) => `${ref.where} -> ${ref.kind} ${ref.id}`); expect(found).toContain('viewByID[view-1].dataID -> dataset ghost-img'); expect(found).toContain('activeView -> view ghost-view'); - expect(found).toContain('layoutSlots -> view ghost-slot'); + expect(found).toContain('layout -> view ghost-slot'); expect(found).toContain( 'tools.rulers[0].imageID -> dataset ghost-ruler-img' ); diff --git a/src/store/__tests__/viewSplitting.spec.ts b/src/store/__tests__/viewSplitting.spec.ts new file mode 100644 index 000000000..0518bf0a2 --- /dev/null +++ b/src/store/__tests__/viewSplitting.spec.ts @@ -0,0 +1,283 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import JSZip from 'jszip'; +import { useViewStore } from '@/src/store/views'; +import { useIdStore } from '@/src/store/id'; +import { + getLayoutDividers, + getLayoutPanes, + moveLayoutDividers, +} from '@/src/utils/layoutEditing'; +import { ManifestSchema, type StateFile } from '@/src/io/state-file/schema'; + +const snapshot = (store: ReturnType) => { + const state: StateFile = { + zip: new JSZip(), + manifest: { version: '9.0.0', dataSources: [] }, + }; + store.serialize(state); + return ManifestSchema.parse(JSON.parse(JSON.stringify(state.manifest))); +}; + +const ids = (store: ReturnType) => + store.layoutViews.map((view) => view.id); + +describe('Splitting layout views', () => { + beforeEach(() => setActivePinia(createPinia())); + + it.each(['row', 'column'] as const)( + 'splits only the chosen area along %s', + (direction) => { + const store = useViewStore(); + store.setLayoutFromGrid([2, 1]); + const [left, right] = store.layoutViews; + store.setDataForView(right.id, 'image'); + const before = getLayoutPanes(store.visibleLayout); + const newID = store.splitView(right.id, direction)!; + const panes = getLayoutPanes(store.visibleLayout); + expect(ids(store)).toEqual([left.id, right.id, newID]); + expect(panes.map((pane) => pane.viewId)).toEqual(ids(store)); + expect(panes[0]).toEqual(before[0]); + if (direction === 'row') + expect(panes.map(({ width }) => width)).toEqual([50, 25, 25]); + expect(store.getView(newID)).toEqual({ ...right, id: newID }); + expect(store.getView(newID)?.options).not.toBe(right.options); + expect(store.activeView).toBe(left.id); + expect(store.currentLayoutName).toBeUndefined(); + if (direction === 'column') + expect( + panes[1].width * panes[1].height + panes[2].width * panes[2].height + ).toBe(5000); + } + ); + + it('splits along the parent direction as a sibling', () => { + const store = useViewStore(); + store.setLayoutFromGrid([2, 1]); + const [left, right] = ids(store); + const middle = store.splitView(left, 'row')!; + expect(store.visibleLayout).toEqual({ + direction: 'row', + items: [left, middle, right].map((viewId) => ({ type: 'view', viewId })), + sizes: [0.25, 0.25, 0.5], + }); + }); + + it('closes views without leaving hidden views behind', () => { + const store = useViewStore(); + store.setLayoutFromGrid([2, 1]); + const [left, right] = ids(store); + const middle = store.splitView(right, 'column')!; + const last = store.splitView(middle, 'row')!; + store.setActiveView(middle); + expect(store.closeView(middle)).toBe(true); + expect(store.activeView).toBe(left); + expect(store.getView(middle)).toBeNull(); + expect(ids(store)).toEqual([left, right, last]); + const panes = getLayoutPanes(store.visibleLayout); + expect(panes.map((pane) => pane.viewId)).toEqual([left, right, last]); + expect(panes[2]).toMatchObject({ + left: 50, + top: 50, + width: 50, + height: 50, + }); + expect(Object.keys(snapshot(store).viewByID!)).toEqual([left, right, last]); + }); + + it('expands a maximized view before splitting and retains all peers', () => { + const store = useViewStore(); + const source = store.layoutViews[1]; + store.setActiveView(source.id); + store.toggleActiveViewMaximized(); + expect(store.visibleViews).toHaveLength(1); + const id = store.splitView(source.id, 'column')!; + expect(store.visibleViews).toHaveLength(5); + expect(store.activeView).toBe(source.id); + expect(store.visibleViews.map((view) => view.id)).toContain(id); + }); + + it('does not close the last view or split missing views', () => { + const store = useViewStore(); + const dropped = store.layoutViews[1].id; + store.setLayoutFromGrid([1, 1]); + const before = snapshot(store); + expect(ids(store)).toHaveLength(1); + expect(store.closeView(store.layoutViews[0].id)).toBe(false); + expect(store.closeView(dropped)).toBe(false); + expect(store.splitView(dropped, 'row')).toBeUndefined(); + expect(snapshot(store)).toEqual(before); + }); + + it('starts a picked named layout over from its template', () => { + const store = useViewStore(); + store.setDataForAllViews('image'); + const before = ids(store); + store.splitView(before[0], 'row'); + store.switchToNamedLayout('Four Up'); + expect(store.currentLayoutName).toBe('Four Up'); + expect(store.viewIDs).toEqual(ids(store)); + expect(store.layoutViews.map(({ name, dataID }) => [name, dataID])).toEqual( + ['Axial', 'Coronal', 'Sagittal', 'Volume'].map((name) => [name, 'image']) + ); + before.forEach((id) => expect(store.getView(id)).toBeNull()); + }); + + it('keeps the view count equal to the panes across layout cycles', () => { + const store = useViewStore(); + for (let round = 0; round < 3; round += 1) { + store.splitView(ids(store)[0], 'row'); + store.switchToNamedLayout('Axial Only'); + store.switchToNamedLayout('Four Up'); + store.closeView(ids(store)[1]); + store.setLayoutFromGrid([2, 2]); + expect(store.viewIDs).toEqual(expect.arrayContaining(ids(store))); + } + expect(ids(store)).toHaveLength(4); + }); + + it('restores a custom layout and can split without replacing restored IDs', () => { + const store = useViewStore(); + const id = store.splitView(store.layoutViews[0].id, 'row')!; + store.splitView(id, 'column'); + const manifest = snapshot(store); + setActivePinia(createPinia()); + const restored = useViewStore(); + restored.deserializeLayout(manifest); + useIdStore().reset(); + expect(restored.visibleLayout).toEqual(manifest.layout); + const source = restored.layoutViews[0]; + const originalIDs = [...restored.viewIDs]; + const newID = restored.splitView(source.id, 'column')!; + expect(originalIDs).not.toContain(newID); + expect(restored.viewIDs).toHaveLength(originalIDs.length + 1); + expect(restored.getView(source.id)).toMatchObject(source); + expect(restored.layoutViews).toHaveLength(7); + }); + + it('clears image bindings from split views without changing layout', () => { + const store = useViewStore(); + store.setDataForAllViews('image'); + const newID = store.splitView(store.layoutViews[0].id, 'row')!; + const before = snapshot(store).layout; + store.removeDataFromViews('image'); + expect(store.getAllViews().every((view) => view.dataID === null)).toBe( + true + ); + expect(snapshot(store).layout).toEqual(before); + store.setDataForView(newID, 'next-image'); + store.replaceView(newID, { + name: 'Volume', + type: '3D', + dataID: 'next-image', + options: { viewDirection: 'Posterior', viewUp: 'Superior' }, + }); + expect(store.getView(newID)).toBeNull(); + expect(store.layoutViews).toHaveLength(5); + expect(store.layoutViews[1]).toMatchObject({ + type: '3D', + dataID: 'next-image', + }); + }); + + it('keeps resized shares through save and load, and resets them on a named pick', () => { + const store = useViewStore(); + const container = { width: 1000, height: 1000 }; + const [across, upper] = getLayoutDividers(store.visibleLayout); + const resized = moveLayoutDividers( + moveLayoutDividers(store.visibleLayout, [across], 30, container), + [upper], + 70, + container + ); + store.resizeLayout(resized); + expect(store.visibleLayout).toEqual(resized); + expect(store.currentLayoutName).toBe('Four Up'); + + const manifest = snapshot(store); + setActivePinia(createPinia()); + const restored = useViewStore(); + restored.deserializeLayout(manifest); + expect(getLayoutPanes(restored.visibleLayout)).toEqual( + getLayoutPanes(resized) + ); + expect( + getLayoutPanes(restored.visibleLayout).map(({ width }) => + Math.round(width) + ) + ).toEqual([70, 30, 50, 50]); + + restored.switchToNamedLayout('Four Up'); + expect( + getLayoutPanes(restored.visibleLayout).map(({ height }) => height) + ).toEqual([50, 50, 50, 50]); + }); + + it('ignores a resize that changes which views the layout shows', () => { + const store = useViewStore(); + const before = store.visibleLayout; + store.resizeLayout({ + direction: 'row', + items: [{ type: 'view', viewId: store.layoutViews[0].id }], + }); + expect(store.visibleLayout).toBe(before); + }); + + it('keeps the active image shown through named layout picks', () => { + const store = useViewStore(); + store.setDataForAllViews('other'); + const [axial] = ids(store); + store.setDataForView(axial, 'active'); + store.setActiveView(axial); + + store.switchToNamedLayout('3D Only'); + expect(store.layoutViews.map((view) => view.dataID)).toEqual(['active']); + store.switchToNamedLayout('Four Up'); + expect(store.getView(store.activeView)?.dataID).toBe('active'); + expect(store.layoutViews.map((view) => view.dataID)).toContain('active'); + }); + + const savedView = (id: string) => ({ + id, + type: '2D' as const, + dataID: null, + name: 'Axial', + options: { orientation: 'Axial' as const }, + }); + const leaf = (viewId: string) => ({ type: 'view' as const, viewId }); + + it('restores a maximized view only when the layout shows it', () => { + const store = useViewStore(); + const restore = (activeView: string) => + store.deserializeLayout({ + version: '9.0.0', + dataSources: [], + activeView, + isActiveViewMaximized: true, + layout: { direction: 'row', items: [leaf('a'), leaf('b')] }, + viewByID: { a: savedView('a'), b: savedView('b') }, + }); + restore('missing'); + expect(store.activeView).toBeUndefined(); + expect(store.visibleViews.map(({ id }) => id)).toEqual(['a', 'b']); + restore('b'); + expect(store.visibleViews.map(({ id }) => id)).toEqual(['b']); + }); + + it('keeps the current layout when a saved layout repeats, omits or names unsaved views', () => { + const store = useViewStore(); + const before = ids(store); + const viewByID = { a: savedView('a'), b: savedView('b') }; + [[leaf('a'), leaf('a')], [], [leaf('a'), leaf('missing')]].forEach( + (items) => { + store.deserializeLayout({ + version: '9.0.0', + dataSources: [], + layout: { direction: 'row', items }, + viewByID, + }); + expect(ids(store)).toEqual(before); + } + ); + }); +}); diff --git a/src/store/__tests__/views.spec.ts b/src/store/__tests__/views.spec.ts index 708a2c35b..bf8125c5e 100644 --- a/src/store/__tests__/views.spec.ts +++ b/src/store/__tests__/views.spec.ts @@ -87,9 +87,8 @@ describe('View store', () => { activeView: null, layout: { direction: 'column', - items: [{ type: 'slot', slotIndex: 0 }], + items: [{ type: 'view', viewId: 'view-1' }], }, - layoutSlots: ['view-1'], viewByID: { 'view-1': { id: 'view-1', @@ -144,8 +143,9 @@ describe('View store', () => { }, }; const manifest: Manifest = { - version: '7.0.0', + version: '9.0.0', dataSources: [], + layout: { direction: 'row', items: [{ type: 'view', viewId: id }] }, viewByID: { [id]: { id, @@ -222,19 +222,19 @@ describe('View store layoutViews', () => { ]); }); - it('drops views the layout no longer has a slot for', () => { + it('replaces every view when a grid is picked', () => { const store = useViewStore(); const allIds = store.layoutViews.map((view) => view.id); store.setLayoutFromGrid([1, 1]); - - expect(store.layoutViews.map((view) => view.id)).toEqual([allIds[0]]); - // The orphaned views survive so a later layout switch can reuse them. - expect(store.viewIDs).toEqual(expect.arrayContaining(allIds)); + const single = store.layoutViews.map((view) => view.id); + expect(store.viewIDs).toEqual(single); + expect(single).toHaveLength(1); + expect(allIds).not.toContain(single[0]); store.setLayoutFromGrid([2, 2]); - - expect(store.layoutViews.map((view) => view.id)).toEqual(allIds); + expect(store.viewIDs).toHaveLength(4); + expect(store.viewIDs).not.toContain(single[0]); }); it('keeps hidden layout peers while a view is maximized', () => { diff --git a/src/store/reslice-cursor.ts b/src/store/reslice-cursor.ts index d7cbcdc6b..e42d0374f 100644 --- a/src/store/reslice-cursor.ts +++ b/src/store/reslice-cursor.ts @@ -5,6 +5,7 @@ import { ViewTypes } from '@kitware/vtk.js/Widgets/Core/WidgetManager/Constants' import vtkResliceCursorWidget, { vtkResliceCursorWidgetState, } from '@kitware/vtk.js/Widgets/Widgets3D/ResliceCursorWidget'; +import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import type { Vector3 } from '@kitware/vtk.js/types'; import { defineStore } from 'pinia'; import { toRaw, watchEffect } from 'vue'; @@ -47,6 +48,15 @@ function resetReslicePlanes( resliceCursorState.setPlanes(planes); } +// Every viewer shares one widget, so only a new image may reset it. +function setCursorImage( + resliceCursor: vtkResliceCursorWidget, + image: vtkImageData +) { + if (resliceCursor.getWidgetState().getImage() !== image) + resliceCursor.setImage(image); +} + function useResliceInit( resliceCursor: vtkResliceCursorWidget, resliceCursorState: vtkResliceCursorWidgetState @@ -56,7 +66,7 @@ function useResliceInit( watchEffect(() => { const image = currentImageData.value; if (!image) return; - resliceCursor.setImage(image); + setCursorImage(resliceCursor, image); // Reset to default plane values before transforming based on current image-data. resetReslicePlanes(resliceCursorState, currentImageMetadata.value); }); @@ -75,6 +85,7 @@ const useResliceCursorStore = defineStore('resliceCursor', () => { return { resliceCursor, resliceCursorState: widgetState, + setImage: (image: vtkImageData) => setCursorImage(resliceCursor, image), resetReslicePlanes: (imageMetadata: ImageMetadata) => { resetReslicePlanes(widgetState, imageMetadata); }, diff --git a/src/store/tools/__tests__/crosshairs.spec.ts b/src/store/tools/__tests__/crosshairs.spec.ts index 7d9968f0c..509389469 100644 --- a/src/store/tools/__tests__/crosshairs.spec.ts +++ b/src/store/tools/__tests__/crosshairs.spec.ts @@ -6,7 +6,7 @@ import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useViewStore } from '@/src/store/views'; import useViewSliceStore from '@/src/store/view-configs/slicing'; -import type { ViewInfo2D } from '@/src/types/views'; +import type { ViewInfo2D, ViewInfoInit } from '@/src/types/views'; import type { LPSAxis } from '@/src/types/lps'; import { useCrosshairsToolStore } from '@/src/store/tools/crosshairs'; import { useEnFaceViewStore } from '@/src/enface/store'; @@ -66,28 +66,31 @@ describe('crosshairs tool store', () => { const sliceOf = (viewId: string, imageId: string) => useViewSliceStore().getConfig(viewId, imageId)?.slice; + // Two more panes beside the default Four Up views. const projectionWithPeer = () => { const views = useViewStore(); - views.setLayoutFromGrid([3, 2]); - views.replaceView(views.layoutViews[4].id, { + const retype = (init: ViewInfoInit) => { + views.replaceView(views.splitView(sagittalA, 'row')!, init); + return views.layoutViews.find(({ name }) => name === init.name)!.id; + }; + const coronalA = retype({ type: '2D', - name: 'Coronal', + name: 'Coronal A', dataID: imageA, options: { orientation: 'Coronal' }, }); - const coronalA = views.layoutViews[4].id; useViewSliceStore().updateConfig(coronalA, imageA, { slice: 6, min: 0, max: 19, }); - views.replaceView(views.layoutViews[5].id, { + const projection = retype({ type: 'EnFace', name: 'En face', dataID: imageA, options: {}, }); - return { projection: views.layoutViews[5].id, coronalA }; + return { projection, coronalA }; }; it.each([0, 1, 2] as const)( @@ -102,7 +105,7 @@ describe('crosshairs tool store', () => { }); const before = { ...settings }; useViewStore().setActiveView(coronalB); - useViewStore().setLayoutFromGrid([1, 1]); + useViewStore().toggleActiveViewMaximized(); useCrosshairsToolStore().setPosition([2, 8, 17], projection); diff --git a/src/store/tools/crosshairs.ts b/src/store/tools/crosshairs.ts index f3b3d6c75..911602b67 100644 --- a/src/store/tools/crosshairs.ts +++ b/src/store/tools/crosshairs.ts @@ -53,8 +53,8 @@ export const useCrosshairsToolStore = defineStore('crosshairs', () => { * whichever view happens to be active, so images sharing a layout keep their * own slicing. * - * All registered views of the image are sliced, not just those in the - * current layout, so views hidden by a layout switch come back consistent. + * All views of the image are sliced, including peers hidden behind a + * maximized view, so they come back consistent. * An en face pick leaves the peer slices along its projection axis * unchanged: it selects an in-plane location without choosing depth. */ diff --git a/src/store/view-configs.ts b/src/store/view-configs.ts index d47a24d30..23438c8ad 100644 --- a/src/store/view-configs.ts +++ b/src/store/view-configs.ts @@ -1,8 +1,12 @@ import { defineStore } from 'pinia'; import { getLayerId } from '@/src/utils/layers'; +import { OBLIQUE_SUB_VIEWS } from '@/src/constants'; import useViewSliceStore from './view-configs/slicing'; -import { useWindowingStore } from './view-configs/windowing'; +import { + sharesSourceWindowing, + useWindowingStore, +} from './view-configs/windowing'; import useLayerColoringStore from './view-configs/layers'; import useViewCameraStore from './view-configs/camera'; import useVolumeColoringStore from './view-configs/volume-coloring'; @@ -10,6 +14,22 @@ import useCinePlaybackStore from './view-configs/cine-playback'; import { useEnFaceViewStore } from '@/src/enface/store'; import { StateFile, ViewConfig } from '../io/state-file/schema'; import type { SegmentResolver } from '@/src/segmentation/segments'; +import type { ViewInfo } from '@/src/types/views'; + +// Oblique viewers own these synthetic view IDs for their four renderers. +const OWNED_SUFFIXES = ['', ...Object.values(OBLIQUE_SUB_VIEWS)]; + +type PerViewConfigs = { + removeView: (viewID: string) => void; + copyView: (sourceID: string, targetID: string) => void; + removeData: (dataID: string, viewID?: string) => void; + serialize: (stateFile: StateFile) => void; + deserialize: ( + viewID: string, + config: Record, + resolveSegment: SegmentResolver + ) => void; +}; /** * This store saves view configuration that is associated with a specific @@ -24,34 +44,29 @@ export const useViewConfigStore = defineStore('viewConfig', () => { const cinePlaybackStore = useCinePlaybackStore(); const enFaceViewStore = useEnFaceViewStore(); + // Every per-view store, so copy, remove and save cannot miss one. + const perViewStores: PerViewConfigs[] = [ + viewSliceStore, + windowingStore, + layerColoringStore, + viewCameraStore, + volumeColoringStore, + cinePlaybackStore, + enFaceViewStore, + ]; + const removeView = (viewID: string) => { - viewSliceStore.removeView(viewID); - windowingStore.removeView(viewID); - layerColoringStore.removeView(viewID); - viewCameraStore.removeView(viewID); - volumeColoringStore.removeView(viewID); - cinePlaybackStore.removeView(viewID); - enFaceViewStore.removeView(viewID); + OWNED_SUFFIXES.forEach((suffix) => + perViewStores.forEach((store) => store.removeView(viewID + suffix)) + ); }; const removeData = (dataID: string, viewID?: string) => { - viewSliceStore.removeData(dataID, viewID); - windowingStore.removeData(dataID, viewID); - layerColoringStore.removeData(dataID, viewID); - viewCameraStore.removeData(dataID, viewID); - volumeColoringStore.removeData(dataID, viewID); - cinePlaybackStore.removeData(dataID, viewID); - enFaceViewStore.removeData(dataID, viewID); + perViewStores.forEach((store) => store.removeData(dataID, viewID)); }; const serialize = (stateFile: StateFile) => { - viewSliceStore.serialize(stateFile); - windowingStore.serialize(stateFile); - layerColoringStore.serialize(stateFile); - viewCameraStore.serialize(stateFile); - volumeColoringStore.serialize(stateFile); - cinePlaybackStore.serialize(stateFile); - enFaceViewStore.serialize(stateFile); + perViewStores.forEach((store) => store.serialize(stateFile)); }; const deserialize = ( @@ -60,21 +75,15 @@ export const useViewConfigStore = defineStore('viewConfig', () => { dataIDMap: Record, resolveSegment: SegmentResolver ) => { - // First update the view config map to use the new dataIDs const updatedConfig: Record = {}; Object.entries(config).forEach(([dataID, viewConfig]) => { const newDataID = dataIDMap[dataID]; // A dataset that failed to restore has no new id to carry its config. if (newDataID) updatedConfig[newDataID] = viewConfig; }); - - viewSliceStore.deserialize(viewID, updatedConfig); - windowingStore.deserialize(viewID, updatedConfig); - layerColoringStore.deserialize(viewID, updatedConfig); - viewCameraStore.deserialize(viewID, updatedConfig); - volumeColoringStore.deserialize(viewID, updatedConfig); - cinePlaybackStore.deserialize(viewID, updatedConfig); - enFaceViewStore.deserialize(viewID, updatedConfig, resolveSegment); + perViewStores.forEach((store) => + store.deserialize(viewID, updatedConfig, resolveSegment) + ); }; const deserializeAll = ( @@ -111,8 +120,27 @@ export const useViewConfigStore = defineStore('viewConfig', () => { }); }; + const copyView = (sourceID: string, targetID: string) => { + OWNED_SUFFIXES.forEach((suffix) => + perViewStores.forEach((store) => + store.copyView(sourceID + suffix, targetID + suffix) + ) + ); + }; + + // Window/level follows each image across views, so a new view starts with + // every image's, not just the one it shows. + const inheritWindowing = (sources: ViewInfo[], target: ViewInfo) => { + if (!sharesSourceWindowing(target)) return; + sources + .filter(sharesSourceWindowing) + .forEach((source) => windowingStore.copyView(source.id, target.id)); + }; + return { removeView, + copyView, + inheritWindowing, removeData, serialize, deserialize, diff --git a/src/store/view-configs/__tests__/viewConfigCopy.spec.ts b/src/store/view-configs/__tests__/viewConfigCopy.spec.ts new file mode 100644 index 000000000..207b8900d --- /dev/null +++ b/src/store/view-configs/__tests__/viewConfigCopy.spec.ts @@ -0,0 +1,122 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import { useViewSliceStore } from '@/src/store/view-configs/slicing'; +import { useWindowingStore } from '@/src/store/view-configs/windowing'; +import { useViewCameraStore } from '@/src/store/view-configs/camera'; +import { useVolumeColoringStore } from '@/src/store/view-configs/volume-coloring'; +import { useCinePlaybackStore } from '@/src/store/view-configs/cine-playback'; +import { useEnFaceViewStore } from '@/src/enface/store'; +import { useImageStore } from '@/src/store/datasets-images'; +import { useImageStatsStore } from '@/src/store/image-stats'; +import '@/src/vtk/ColorMaps'; +import { makeImage } from '@/src/segmentation/__tests__/segmentMaskFixtures'; + +describe('copying a view configuration', () => { + beforeEach(() => { + setActivePinia(createPinia()); + useImageStatsStore().stats.image = { + scalarMin: 0, + scalarMax: 0, + autoRangeValues: {}, + }; + useImageStore().addVTKImageData( + 'image', + makeImage({ dimensions: [2, 2, 12] }), + { id: 'image' } + ); + }); + + it('copies the slice, which then changes on its own', () => { + const slices = useViewSliceStore(); + slices.updateConfig('source', 'image', { slice: 7, min: 0, max: 11 }); + + slices.copyView('source', 'copy'); + expect(slices.getConfig('copy', 'image')).toEqual( + slices.getConfig('source', 'image') + ); + slices.updateConfig('copy', 'image', { slice: 3 }); + expect(slices.getConfig('source', 'image').slice).toBe(7); + }); + + it('copies the window and level', () => { + const windowing = useWindowingStore(); + windowing.updateConfig('source', 'image', { + width: 120, + level: 60, + useAuto: false, + }); + + windowing.copyView('source', 'copy'); + expect(windowing.getConfig('copy', 'image')).toMatchObject({ + width: 120, + level: 60, + useAuto: false, + }); + }); + + it('copies a fitted camera with a position of its own', () => { + const cameras = useViewCameraStore(); + cameras.updateConfig('source', 'image', { + position: [1, 2, 3], + focalPoint: [4, 5, 6], + parallelScale: 14, + autoFit: false, + }); + cameras.markCameraAsInitialized('source', 'image'); + + cameras.copyView('source', 'copy'); + const source = cameras.getConfig('source', 'image'); + const copy = cameras.getConfig('copy', 'image'); + expect(copy).toEqual(source); + expect(copy?.position).not.toBe(source?.position); + expect(cameras.isCameraInitialized('copy', 'image')).toBe(true); + }); + + it('copies the volume coloring with a mapping range of its own', () => { + const coloring = useVolumeColoringStore(); + coloring.updateColorTransferFunction('source', 'image', { + mappingRange: [10, 80], + }); + + coloring.copyView('source', 'copy'); + const source = coloring.getConfig('source', 'image')?.transferFunction; + const copy = coloring.getConfig('copy', 'image')?.transferFunction; + expect(copy?.mappingRange).toEqual([10, 80]); + expect(copy?.mappingRange).not.toBe(source?.mappingRange); + }); + + it('copies the cine frame and rate with playback paused', () => { + const cine = useCinePlaybackStore(); + cine.updateConfig('source', 'image', { frame: 1, fps: 30, playing: true }); + + cine.copyView('source', 'copy'); + expect(cine.getConfig('copy', 'image')).toEqual({ + frame: 1, + fps: 30, + playing: false, + }); + expect(cine.getConfig('source', 'image').playing).toBe(true); + }); + + it('copies en face settings, which then change on their own', () => { + const enFace = useEnFaceViewStore(); + Object.assign(enFace.configFor('source', 'image'), { + method: 'max', + depthStart: 2, + depthEnd: 9, + }); + enFace.patchSegment('source', 'image', 'segment', { + visible: true, + thresholdMicrons: 40, + }); + + enFace.copyView('source', 'copy'); + expect(enFace.settingsFor('copy', 'image')).toEqual( + enFace.settingsFor('source', 'image') + ); + enFace.patchSegment('copy', 'image', 'segment', { visible: false }); + expect( + enFace.settingsFor('source', 'image').segmentProjections.segment.visible + ).toBe(true); + }); +}); diff --git a/src/store/view-configs/__tests__/volumeColoringCopy.spec.ts b/src/store/view-configs/__tests__/volumeColoringCopy.spec.ts new file mode 100644 index 000000000..dc72d5540 --- /dev/null +++ b/src/store/view-configs/__tests__/volumeColoringCopy.spec.ts @@ -0,0 +1,33 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import { nextTick } from 'vue'; +import { useImageStatsStore } from '@/src/store/image-stats'; +import { useVolumeColoringStore } from '@/src/store/view-configs/volume-coloring'; +import { seatImage } from '@/src/segmentation/__tests__/segmentMaskFixtures'; + +describe('Volume coloring copies', () => { + beforeEach(() => setActivePinia(createPinia())); + + it('fits a copied view once the image stats arrive', async () => { + await seatImage('image', { + dimensions: [4, 1, 1], + values: Float32Array.from([0, 10, 20, 100]), + }); + const coloring = useVolumeColoringStore(); + coloring.setColorPreset('source', 'image', 'Grayscale'); + coloring.copyView('source', 'copy'); + + useImageStatsStore().stats.image = { + scalarMin: 0, + scalarMax: 100, + autoRangeValues: { LowContrast: [10, 20] }, + }; + await nextTick(); + + ['source', 'copy'].forEach((viewID) => + expect( + coloring.getConfig(viewID, 'image')?.transferFunction.mappingRange + ).toEqual([10, 20]) + ); + }); +}); diff --git a/src/store/view-configs/camera.ts b/src/store/view-configs/camera.ts index b4a2e95a0..aba7b9f32 100644 --- a/src/store/view-configs/camera.ts +++ b/src/store/view-configs/camera.ts @@ -1,6 +1,7 @@ import { defineStore } from 'pinia'; import { DoubleKeyRecord, + cloneEntries, deleteEntry, deleteFirstKey, deleteSecondKey, @@ -64,6 +65,13 @@ export const useViewCameraStore = defineStore('viewCamera', () => { deleteFirstKey(initializedCameras, viewID); }; + const copyView = (sourceID: string, targetID: string) => + cloneEntries(configs, sourceID).forEach(([dataID, config]) => { + updateConfig(targetID, dataID, config); + if (isCameraInitialized(sourceID, dataID)) + markCameraAsInitialized(targetID, dataID); + }); + const removeData = (dataID: string, viewID?: string) => { if (viewID) { deleteEntry(configs, viewID, dataID); @@ -133,6 +141,7 @@ export const useViewCameraStore = defineStore('viewCamera', () => { disableCameraAutoReset, toggleCameraAutoReset, removeView, + copyView, removeData, toggleSyncCameras, updateSyncConfigs, diff --git a/src/store/view-configs/cine-playback.ts b/src/store/view-configs/cine-playback.ts index 432237183..c3dfb91d7 100644 --- a/src/store/view-configs/cine-playback.ts +++ b/src/store/view-configs/cine-playback.ts @@ -4,6 +4,7 @@ import { Maybe } from '@/src/types'; import { clampValue } from '@/src/utils'; import { DoubleKeyRecord, + cloneEntries, deleteSecondKey, getDoubleKeyRecord, patchDoubleKeyRecord, @@ -89,6 +90,11 @@ export const useCinePlaybackStore = defineStore('cinePlayback', () => { delete configs[viewID]; }; + const copyView = (sourceID: string, targetID: string) => + cloneEntries(configs, sourceID).forEach(([dataID, config]) => + updateConfig(targetID, dataID, { ...config, playing: false }) + ); + const removeData = (dataID: string, viewID?: string) => { if (viewID) { delete configs[viewID]?.[dataID]; @@ -121,6 +127,7 @@ export const useCinePlaybackStore = defineStore('cinePlayback', () => { getConfig, updateConfig, removeView, + copyView, removeData, serialize, deserialize, diff --git a/src/store/view-configs/layers.ts b/src/store/view-configs/layers.ts index f9c0393b4..69f782f09 100644 --- a/src/store/view-configs/layers.ts +++ b/src/store/view-configs/layers.ts @@ -208,6 +208,9 @@ export const useLayerColoringStore = defineStore('layerColoring', () => { delete configs[viewID]; }; + // Coloring derives from each layer's shared display config. + const copyView = () => {}; + const removeData = (dataID: string, viewID?: string) => { if (viewID) { delete configs[viewID]?.[dataID]; @@ -285,6 +288,7 @@ export const useLayerColoringStore = defineStore('layerColoring', () => { updateDisplayConfig, getConfig, removeView, + copyView, removeData, serialize, deserialize, diff --git a/src/store/view-configs/slicing.ts b/src/store/view-configs/slicing.ts index e87242bf1..22cd5638e 100644 --- a/src/store/view-configs/slicing.ts +++ b/src/store/view-configs/slicing.ts @@ -3,6 +3,7 @@ import { defineStore } from 'pinia'; import { reactive } from 'vue'; import { DoubleKeyRecord, + cloneEntries, deleteSecondKey, getDoubleKeyRecord, patchDoubleKeyRecord, @@ -94,6 +95,11 @@ export const useViewSliceStore = defineStore('viewSlice', () => { delete configs[viewID]; }; + const copyView = (sourceID: string, targetID: string) => + cloneEntries(configs, sourceID).forEach(([dataID, config]) => + updateConfig(targetID, dataID, config) + ); + const removeData = (dataID: string, viewID?: string) => { if (viewID) { delete configs[viewID]?.[dataID]; @@ -156,6 +162,7 @@ export const useViewSliceStore = defineStore('viewSlice', () => { updateConfig, resetSlice, removeView, + copyView, removeData, toggleSyncImages, updateSyncConfigs, diff --git a/src/store/view-configs/volume-coloring.ts b/src/store/view-configs/volume-coloring.ts index 92b686f4d..2058d647e 100644 --- a/src/store/view-configs/volume-coloring.ts +++ b/src/store/view-configs/volume-coloring.ts @@ -14,6 +14,7 @@ import { defineStore } from 'pinia'; import { reactive, watch } from 'vue'; import { DoubleKeyRecord, + cloneEntries, deleteEntry, deleteFirstKey, deleteSecondKey, @@ -247,6 +248,15 @@ export const useVolumeColoringStore = defineStore('volumeColoring', () => { deleteFirstKey(awaitingFit, viewID); }; + const copyView = (sourceID: string, targetID: string) => { + cloneEntries(configs, sourceID).forEach(([imageID, config]) => + updateConfig(targetID, imageID, config) + ); + cloneEntries(awaitingFit, sourceID).forEach(([imageID, applied]) => + patchDoubleKeyRecord(awaitingFit, targetID, imageID, applied) + ); + }; + const removeData = (dataID: string, viewID?: string) => { if (viewID) { delete configs[viewID]?.[dataID]; @@ -281,6 +291,7 @@ export const useVolumeColoringStore = defineStore('volumeColoring', () => { getPresetColorRange, getFitRange, removeView, + copyView, removeData, serialize, deserialize, diff --git a/src/store/view-configs/windowing.ts b/src/store/view-configs/windowing.ts index 7befc329f..55f1071a0 100644 --- a/src/store/view-configs/windowing.ts +++ b/src/store/view-configs/windowing.ts @@ -5,6 +5,7 @@ import { createEventHook } from '@vueuse/core'; import deepEqual from 'fast-deep-equal'; import { DoubleKeyRecord, + cloneEntries, deleteSecondKey, getDoubleKeyRecord, patchDoubleKeyRecord, @@ -253,6 +254,11 @@ export const useWindowingStore = defineStore('windowing', () => { delete autoRangeSources[viewID]; }; + const copyView = (sourceID: string, targetID: string) => + cloneEntries(configs, sourceID).forEach(([dataID, config]) => + updateConfig(targetID, dataID, config) + ); + const resetConfig = (viewID: Maybe, dataID: Maybe) => { if (!viewID || !dataID) return; delete configs[viewID]?.[dataID]; @@ -313,6 +319,7 @@ export const useWindowingStore = defineStore('windowing', () => { resetConfig, resetContrast, removeView, + copyView, removeData, serialize, deserialize, diff --git a/src/store/views.ts b/src/store/views.ts index 943445f7c..fa4878e18 100644 --- a/src/store/views.ts +++ b/src/store/views.ts @@ -2,12 +2,18 @@ import { defineStore } from 'pinia'; import { computed, markRaw, reactive, ref, watch } from 'vue'; import { createEventHook } from '@vueuse/core'; import type { Maybe } from '@/src/types'; -import type { Layout, LayoutItem } from '@/src/types/layout'; +import type { + Layout, + LayoutDirection, + LayoutTemplate, + ViewLeaf, +} from '@/src/types/layout'; import { useIdStore } from '@/src/store/id'; import { useViewConfigStore } from '@/src/store/view-configs'; import type { ViewInfo, ViewInfoInit, ViewType } from '@/src/types/views'; import { DefaultNamedLayouts, getAvailableViews } from '@/src/config'; import { + parseLayoutConfig, parseNamedLayouts, type LayoutConfig, } from '@/src/utils/layoutParsing'; @@ -15,6 +21,23 @@ import type { Manifest, StateFile } from '../io/state-file/schema'; import { onImageDeleted } from '@/src/composables/onImageDeleted'; import { declareManifestRefs } from '@/src/core/manifestRefs'; import { isRecord } from '@/src/utils'; +import { + layoutViewIds, + mapLayoutLeaves, + moveLayoutView, + removeLayoutView, + replaceLayoutView, + sameLayoutShape, + type DropZone, + splitLayoutView, + viewLeaf, +} from '@/src/utils/layoutEditing'; + +const rawLayoutViewIds = (node: unknown): string[] => { + if (!isRecord(node)) return []; + if (typeof node.viewId === 'string') return [node.viewId]; + return Array.isArray(node.items) ? node.items.flatMap(rawLayoutViewIds) : []; +}; // The manifest references this store's remove cascade keeps clean (see the // onImageDeleted registration below), declared for the dev-only save backstop. @@ -41,74 +64,29 @@ declareManifestRefs('views', (manifest) => { }, ] : []), - ...(Array.isArray(manifest.layoutSlots) - ? manifest.layoutSlots - : [] - ).flatMap((id) => - typeof id === 'string' - ? [{ kind: 'view' as const, id, where: 'layoutSlots' }] - : [] - ), + ...rawLayoutViewIds(manifest.layout).map((id) => ({ + kind: 'view' as const, + id, + where: 'layout', + })), ]; }); -const DEFAULT_VIEW_INIT: ViewInfoInit = { - type: '2D', - dataID: null, - name: 'Axial', - options: { - orientation: 'Axial', - }, -}; - -function iterLayout( - layout: Layout, - cb: (item: LayoutItem & { type: 'slot' }) => void -) { - layout.items.forEach((item) => { - if (item.type === 'slot') cb(item); - else iterLayout(item, cb); - }); -} - -function calcLayoutViewCount(layout: Layout): number { - return layout.items.reduce((sum, item) => { - if (item.type === 'slot') return sum + 1; - return sum + calcLayoutViewCount(item); - }, 0); -} - -function generateLayoutFromGrid(size: [number, number]): Layout { - const [width, height] = size; - return { - direction: 'column', - items: Array.from({ length: height }).map((_, rowIndex) => { - return { - type: 'layout', - direction: 'row', - items: Array.from({ length: width }).map((__, colIndex) => { - return { - type: 'slot', - slotIndex: rowIndex * width + colIndex, - }; - }), - }; - }), - }; -} - -function sameLayout(a: Layout, b: Layout): boolean { +// Each saved view fills exactly one pane, and a layout shows at least one. +export const isRestorableLayout = ( + layout: Layout | undefined, + saved: Record +): layout is Layout => { + const ids = layout ? layoutViewIds(layout) : []; return ( - a.direction === b.direction && - a.items.length === b.items.length && - a.items.every((item, index) => { - const other = b.items[index]; - if (item.type === 'slot') - return other.type === 'slot' && item.slotIndex === other.slotIndex; - return other.type === 'layout' && sameLayout(item, other); - }) + ids.length > 0 && + new Set(ids).size === ids.length && + ids.every((id) => Object.hasOwn(saved, id)) ); -} +}; + +const cloneViewInit = (init: ViewInfoInit) => + JSON.parse(JSON.stringify(init)) as ViewInfoInit; function needsViewReplacement(existingView: ViewInfo, nextView: ViewInfoInit) { if (existingView.type !== nextView.type) return true; @@ -131,39 +109,34 @@ export const useViewStore = defineStore('view', () => { const LayoutViewReplacedEvent = markRaw(createEventHook<[string, string]>()); const parsedDefaultLayouts = parseNamedLayouts(DefaultNamedLayouts); + const firstLayout = Object.values(parsedDefaultLayouts)[0]; - const defaultNamedLayoutEntries = Object.entries(parsedDefaultLayouts); - const firstLayout = defaultNamedLayoutEntries[0][1]; - - const layout = ref(firstLayout.layout); - // which assigns view IDs to layout slots - const layoutSlots = ref([]); + // Every view in viewByID is a leaf of this tree; dropping a leaf deletes its view. + const layout = ref({ direction: 'column', items: [] }); const viewByID = reactive>({}); const activeView = ref>(); const disabledViewTypes = ref([]); - const namedLayouts = - ref>( - parsedDefaultLayouts + const namedLayouts = ref(parsedDefaultLayouts); + + const matchesTemplate = (template: LayoutTemplate) => + sameLayoutShape( + template, + layout.value, + ({ view: init }, { viewId }: ViewLeaf) => { + const view = viewByID[viewId]; + return !!view && !needsViewReplacement(view, init); + } ); - // A named layout is current when switching to it would only rename views. + + // A named layout is current when the layout has its shape and view kinds. const currentLayoutName = computed( () => - Object.entries(namedLayouts.value).find( - ([, named]) => - sameLayout(named.layout, layout.value) && - named.views.every((viewInit, index) => { - const view = viewByID[layoutSlots.value[index]]; - return view && !needsViewReplacement(view, viewInit); - }) + Object.entries(namedLayouts.value).find(([, template]) => + matchesTemplate(template) )?.[0] ); const isActiveViewMaximized = ref(false); - const maximizedView = computed(() => { - if (activeView.value && isActiveViewMaximized.value) - return viewByID[activeView.value]; - return undefined; - }); const availableViewsForSwitcher = computed(() => { const allViews = getAvailableViews(); @@ -172,16 +145,22 @@ export const useViewStore = defineStore('view', () => { ); }); - // Every view the current layout assigns a slot to, whether or not it is on - // screen. Reading the layout rather than `viewByID` keeps views orphaned by a - // layout switch out of the list. - const layoutViews = computed(() => { - const views: ViewInfo[] = []; - iterLayout(layout.value, (item) => { - const view = viewByID[layoutSlots.value[item.slotIndex]]; - if (view) views.push(view); - }); - return views; + // Every view in the layout, whether or not maximizing hides it. + const layoutViews = computed(() => + layoutViewIds(layout.value).flatMap((id) => + viewByID[id] ? [viewByID[id]] : [] + ) + ); + + // A lone view has nothing to hide, so it never counts as maximized. + const maximizedView = computed(() => { + if ( + activeView.value && + isActiveViewMaximized.value && + layoutViews.value.length > 1 + ) + return viewByID[activeView.value]; + return undefined; }); const visibleViews = computed(() => { @@ -247,54 +226,99 @@ export const useViewStore = defineStore('view', () => { return id; } + function deleteView(id: string) { + useViewConfigStore().removeView(id); + delete viewByID[id]; + } + + // Keeps only views the layout shows. + function commitLayout(nextLayout: Layout) { + const kept = new Set(layoutViewIds(nextLayout)); + isActiveViewMaximized.value = false; + layout.value = nextLayout; + viewIDs.value.filter((id) => !kept.has(id)).forEach(deleteView); + ensureActiveViewIsVisible(); + } + + const isInLayout = (id: string) => layoutViewIds(layout.value).includes(id); + function replaceView(id: string, viewInfo: ViewInfoInit) { - const slotIndex = layoutSlots.value.findIndex((viewId) => id === viewId); - if (slotIndex === -1) throw new Error('invalid view to replace'); + if (!isInLayout(id)) throw new Error('invalid view to replace'); const newViewId = addView(viewInfo); - layoutSlots.value[slotIndex] = newViewId; + layout.value = replaceLayoutView(layout.value, id, newViewId); LayoutViewReplacedEvent.trigger(id, newViewId); - useViewConfigStore().removeView(id); - if (activeView.value === id) { setActiveView(newViewId); } - - delete viewByID[id]; + deleteView(id); } - function applyLayoutChange( - newLayout: Layout, - options?: { - updateSlots?: (viewCount: number) => void; - activateView?: boolean; - } - ) { - isActiveViewMaximized.value = false; + function splitView(id: string, direction: LayoutDirection) { + const view = getView(id); + if (!view || !isInLayout(id)) return undefined; + + const newID = addView( + cloneViewInit({ + name: view.name, + type: view.type, + dataID: view.dataID, + options: view.options, + } as ViewInfoInit) + ); + useViewConfigStore().copyView(id, newID); + commitLayout(splitLayoutView(layout.value, id, newID, direction)); + return newID; + } - if (options?.updateSlots) { - const viewCount = calcLayoutViewCount(newLayout); - options.updateSlots(viewCount); - } + // Accepts only a layout that differs in shares, so no view comes or goes. + function resizeLayout(nextLayout: Layout) { + if ( + !sameLayoutShape( + nextLayout, + layout.value, + (next: ViewLeaf, current: ViewLeaf) => next.viewId === current.viewId + ) + ) + return; + layout.value = nextLayout; + } - layout.value = newLayout; - if (options?.activateView !== false) ensureActiveViewIsVisible(); + function moveView(id: string, targetId: string, zone: DropZone) { + if (id === targetId || !isInLayout(id) || !isInLayout(targetId)) return; + commitLayout(moveLayoutView(layout.value, id, targetId, zone)); + setActiveView(id); } - function ensureLayoutSlots(viewCount: number) { - // Preserve non-visible views so their state remains available later. - while (layoutSlots.value.length < viewCount) { - layoutSlots.value.push(addView(DEFAULT_VIEW_INIT)); - } + function closeView(id: string) { + if (layoutViews.value.length <= 1 || !isInLayout(id)) return false; + commitLayout(removeLayoutView(layout.value, id)); + return true; } - function setLayout(newLayout: Layout) { - applyLayoutChange(newLayout, { - updateSlots: ensureLayoutSlots, - }); + const activeImage = () => + getView(activeView.value)?.dataID ?? + layoutViews.value.find((view) => view.dataID)?.dataID ?? + null; + + // Picking a layout starts over with the template's views, all showing the + // active image. + function applyTemplate(template: LayoutTemplate) { + const dataID = activeImage(); + const previous = layoutViews.value; + // The first layout is built during store setup, before the config stores + // can load, and has no views to inherit from. + const configs = previous.length > 0 ? useViewConfigStore() : undefined; + commitLayout( + mapLayoutLeaves(template, ({ view: init }) => { + const id = addView({ ...cloneViewInit(init), dataID }); + configs?.inheritWindowing(previous, viewByID[id]); + return viewLeaf(id); + }) + ); } function setLayoutFromGrid(gridSize: [number, number]) { - setLayout(generateLayoutFromGrid(gridSize)); + applyTemplate(parseLayoutConfig({ gridSize })); } function setNamedLayoutsFromConfig(layouts: Record) { @@ -302,32 +326,11 @@ export const useViewStore = defineStore('view', () => { } function switchToNamedLayout(name: string) { - const namedLayout = namedLayouts.value[name]; - if (!namedLayout) { + const template = namedLayouts.value[name]; + if (!template) { throw new Error(`Named layout "${name}" not found`); } - applyLayoutChange(namedLayout.layout, { - updateSlots: () => { - namedLayout.views.forEach((viewInit, index) => { - if (index < layoutSlots.value.length) { - const existingViewId = layoutSlots.value[index]; - const existingView = viewByID[existingViewId]; - if (existingView) { - if (needsViewReplacement(existingView, viewInit)) { - replaceView(existingViewId, { - ...viewInit, - dataID: existingView.dataID, - }); - } else { - existingView.name = viewInit.name; - } - } - } else { - layoutSlots.value.push(addView(viewInit)); - } - }); - }, - }); + applyTemplate(template); } function setDataForView( @@ -363,23 +366,17 @@ export const useViewStore = defineStore('view', () => { } function removeDataFromViews(dataID: string) { - // Every `viewByID` entry is serialized (not just the ones currently in a - // layout slot), so a view preserved off-slot with a stale dataID would - // still dangle in the save manifest — unbind ALL matching views. - getViewsForData(dataID).forEach((view) => { - setDataForView(view.id, null); - }); + getViewsForData(dataID).forEach((view) => setDataForView(view.id, null)); } function applyDisabledViewTypesFilter() { if (!disabledViewTypes.value.length) return; - layoutSlots.value.forEach((id) => { - const view = viewByID[id]; + [...layoutViews.value].forEach((view) => { if (disabledViewTypes.value.includes(view.type)) { const replacement = availableViewsForSwitcher.value[0]; if (replacement) { - replaceView(id, replacement); + replaceView(view.id, replacement); } } }); @@ -390,42 +387,30 @@ export const useViewStore = defineStore('view', () => { manifest.layout = layout.value; manifest.activeView = activeView.value; manifest.isActiveViewMaximized = isActiveViewMaximized.value; - manifest.layoutSlots = layoutSlots.value; - manifest.viewByID = viewByID; + manifest.viewByID = Object.fromEntries( + layoutViews.value.map((view) => [view.id, view]) + ); } function deserializeLayout(manifest: Manifest) { // No old view is current while the incoming layout replaces its contents. setActiveView(undefined); - if (manifest.layoutSlots) { - layoutSlots.value = manifest.layoutSlots; - } - - if (manifest.viewByID) { - const viewConfigs = useViewConfigStore(); - viewIDs.value.forEach((key) => { - viewConfigs.removeView(key); - delete viewByID[key]; - }); - - Object.entries(manifest.viewByID).forEach(([id, view]) => { - viewByID[id] = { - ...view, - dataID: null, - } as unknown as ViewInfo; - }); - } - if (manifest.layout) { - applyLayoutChange(manifest.layout, { - updateSlots: ensureLayoutSlots, - activateView: false, + const saved = manifest.viewByID ?? {}; + const incoming = manifest.layout; + const restored = isRestorableLayout(incoming, saved); + if (restored) { + viewIDs.value.forEach(deleteView); + layoutViewIds(incoming).forEach((id) => { + viewByID[id] = { ...saved[id], dataID: null } as unknown as ViewInfo; }); + layout.value = incoming; } - if (manifest.isActiveViewMaximized !== undefined) { - isActiveViewMaximized.value = manifest.isActiveViewMaximized; - } + // A saved active view the layout no longer shows cannot stay maximized. + const hidden = !!manifest.activeView && !isInLayout(manifest.activeView); + isActiveViewMaximized.value = !hidden && !!manifest.isActiveViewMaximized; // Reused views acquire their saved selection after their data is rebound. - if (manifest.viewByID) setActiveView(manifest.activeView); + if (manifest.viewByID && !hidden) setActiveView(manifest.activeView); + return restored; } function bindViewsToData( @@ -444,13 +429,7 @@ export const useViewStore = defineStore('view', () => { // initialization - firstLayout.views.forEach((viewInit) => { - const viewId = addView(viewInit); - layoutSlots.value.push(viewId); - if (!activeView.value) { - setActiveView(viewId); - } - }); + applyTemplate(firstLayout); watch(disabledViewTypes, () => { applyDisabledViewTypesFilter(); @@ -465,11 +444,12 @@ export const useViewStore = defineStore('view', () => { if (maximizedView.value) return { direction: 'column', - items: [{ type: 'slot', slotIndex: 0 }], + items: [viewLeaf(maximizedView.value.id)], } satisfies Layout; return layout.value; }), visibleViews, + maximizedView, layoutViews, viewIDs, activeView, @@ -479,10 +459,13 @@ export const useViewStore = defineStore('view', () => { namedLayouts, currentLayoutName, getView, + splitView, + closeView, + moveView, + resizeLayout, getAllViews, getViewsForData, replaceView, - setLayout, setLayoutFromGrid, setNamedLayoutsFromConfig, switchToNamedLayout, diff --git a/src/types/layout.ts b/src/types/layout.ts index a3b4c0ef0..a881a68fc 100644 --- a/src/types/layout.ts +++ b/src/types/layout.ts @@ -1,15 +1,20 @@ -export type LayoutDirection = 'row' | 'column'; +import type { ViewInfoInit } from '@/src/types/views'; -export type LayoutItem = - | { - type: 'slot'; - slotIndex: number; - } - | ({ - type: 'layout'; - } & Layout); +export type LayoutDirection = 'row' | 'column'; -export type Layout = { +export type LayoutTree = { direction: LayoutDirection; - items: ReadonlyArray; + items: ReadonlyArray>; + /** Each item's share of the group, summing to 1. Absent means equal. */ + sizes?: ReadonlyArray; }; + +export type LayoutNode = Leaf | ({ type: 'layout' } & LayoutTree); + +export type ViewLeaf = { type: 'view'; viewId: string }; + +export type Layout = LayoutTree; +export type LayoutItem = LayoutNode; + +/** A named layout's shape, describing the views a pick should provide. */ +export type LayoutTemplate = LayoutTree<{ type: 'view'; view: ViewInfoInit }>; diff --git a/src/utils/__tests__/layoutEditing.spec.ts b/src/utils/__tests__/layoutEditing.spec.ts new file mode 100644 index 000000000..8bc81c528 --- /dev/null +++ b/src/utils/__tests__/layoutEditing.spec.ts @@ -0,0 +1,426 @@ +import { describe, expect, it } from 'vitest'; +import type { Layout, LayoutItem } from '@/src/types/layout'; +import { omit } from '@/src/utils'; +import { + alignedDividers, + getLayoutDividers, + getLayoutPanes, + moveLayoutDividers, + moveLayoutView, + removeLayoutView, + replaceLayoutView, + resetLayoutDividers, + sameLayoutShape, + splitLayoutView, +} from '@/src/utils/layoutEditing'; + +const v = (viewId: string): LayoutItem => ({ type: 'view', viewId }); +const row = (...items: LayoutItem[]): LayoutItem => ({ + type: 'layout', + direction: 'row', + items, +}); +const column = (...items: LayoutItem[]): LayoutItem => ({ + type: 'layout', + direction: 'column', + items, +}); +const root = (item: LayoutItem): Layout => { + if (item.type !== 'layout') return { direction: 'column', items: [item] }; + return omit(item, 'type'); +}; +const sized = (item: LayoutItem, sizes: number[]): LayoutItem => + item.type === 'layout' ? { ...item, sizes } : item; +const round = (value: number) => Math.round(value * 1e6) / 1e6; +const widths = (layout: Layout) => + getLayoutPanes(layout).map(({ width }) => round(width)); +const heights = (layout: Layout) => + getLayoutPanes(layout).map(({ height }) => round(height)); + +describe('layout editing', () => { + it('inserts a sibling when splitting along the parent direction', () => { + expect(splitLayoutView(root(row(v('a'), v('b'))), 'a', 'c', 'row')).toEqual( + root(sized(row(v('a'), v('c'), v('b')), [0.25, 0.25, 0.5])) + ); + }); + + it('nests a group when splitting across the parent direction', () => { + expect( + splitLayoutView(root(row(v('a'), v('b'))), 'b', 'c', 'column') + ).toEqual(root(row(v('a'), column(v('b'), v('c'))))); + }); + + it('grows a single-view root in the split direction', () => { + expect(splitLayoutView(root(column(row(v('a')))), 'a', 'b', 'row')).toEqual( + root(row(v('a'), v('b'))) + ); + expect(splitLayoutView(root(v('a')), 'a', 'b', 'row')).toEqual( + root(row(v('a'), v('b'))) + ); + }); + + it('merges a collapsed group into a parent of the same direction', () => { + const layout = root(row(v('a'), column(v('b'), row(v('c'), v('d'))))); + expect(removeLayoutView(layout, 'b')).toEqual( + root(sized(row(v('a'), v('c'), v('d')), [0.5, 0.25, 0.25])) + ); + }); + + it('replaces a one-view group with its view', () => { + const layout = root(column(row(v('a'), v('b')), row(v('c'), v('d')))); + expect(removeLayoutView(layout, 'a')).toEqual( + root(column(v('b'), row(v('c'), v('d')))) + ); + }); + + it('leaves untouched groups nested as configured', () => { + const layout = root(row(row(v('a'), v('b')), v('c'), v('d'))); + const removed = removeLayoutView(layout, 'd'); + expect(removed.items).toEqual([row(v('a'), v('b')), v('c')]); + expect(widths(removed)).toEqual([ + round(100 / 6), + round(100 / 6), + 66.666667, + ]); + }); + + it('matches shapes regardless of one-item groups', () => { + const same = (a: { viewId: string }, b: { viewId: string }) => + a.viewId === b.viewId; + expect( + sameLayoutShape(root(column(row(v('a')))), root(row(v('a'))), same) + ).toBe(true); + expect( + sameLayoutShape( + root(column(row(v('a'), v('b')))), + root(row(v('a'), v('b'))), + same + ) + ).toBe(true); + expect( + sameLayoutShape( + root(row(v('a'), v('b'))), + root(column(v('a'), v('b'))), + same + ) + ).toBe(false); + expect( + sameLayoutShape( + root(row(v('a'), v('b'))), + root(row(v('b'), v('a'))), + same + ) + ).toBe(false); + }); + + it('matches shapes regardless of sizes', () => { + const same = (a: { viewId: string }, b: { viewId: string }) => + a.viewId === b.viewId; + expect( + sameLayoutShape( + root(sized(row(v('a'), v('b')), [0.2, 0.8])), + root(row(v('a'), v('b'))), + same + ) + ).toBe(true); + }); +}); + +describe('moving views', () => { + const fourUp = root(column(row(v('a'), v('b')), row(v('c'), v('d')))); + + it('swaps two views on a center drop, keeping pane sizes in place', () => { + const layout = root(sized(row(v('a'), v('b')), [0.7, 0.3])); + expect(moveLayoutView(layout, 'a', 'b', 'center')).toEqual( + root(sized(row(v('b'), v('a')), [0.7, 0.3])) + ); + }); + + it('docks a view beside the target edge, halving the target', () => { + expect(moveLayoutView(fourUp, 'a', 'd', 'left')).toEqual( + root( + column(v('b'), sized(row(v('c'), v('a'), v('d')), [0.5, 0.25, 0.25])) + ) + ); + expect(moveLayoutView(fourUp, 'a', 'd', 'bottom')).toEqual( + root(column(v('b'), row(v('c'), column(v('d'), v('a'))))) + ); + }); + + it('moves a view across its only sibling', () => { + const pair = root(row(v('a'), v('b'))); + expect(moveLayoutView(pair, 'a', 'b', 'right')).toEqual( + root(row(v('b'), v('a'))) + ); + expect(moveLayoutView(pair, 'a', 'b', 'top')).toEqual( + root(column(v('a'), v('b'))) + ); + }); + + it('leaves the layout alone when dropped on itself', () => { + expect(moveLayoutView(fourUp, 'a', 'a', 'left')).toBe(fourUp); + }); +}); + +describe('layout sizes', () => { + const container = { width: 1000, height: 800 }; + + it('places panes by their group shares', () => { + const layout = root( + sized(column(sized(row(v('a'), v('b')), [0.3, 0.7]), v('c')), [0.6, 0.4]) + ); + expect(getLayoutPanes(layout)).toEqual([ + { viewId: 'a', left: 0, top: 0, width: 30, height: 60 }, + { viewId: 'b', left: 30, top: 0, width: 70, height: 60 }, + { viewId: 'c', left: 0, top: 60, width: 100, height: 40 }, + ]); + }); + + it('treats sizes that do not fit their items as equal', () => { + const invalid = [ + [0.5], + [0.5, 0.5, 0], + [-1, 2, 1], + [Infinity, 1, 1], + [NaN, 1, 1], + ]; + invalid.forEach((sizes) => + expect(widths(root(sized(row(v('a'), v('b'), v('c')), sizes)))).toEqual( + widths(root(row(v('a'), v('b'), v('c')))) + ) + ); + expect(widths(root(sized(row(v('a'), v('b')), [1, 3])))).toEqual([25, 75]); + }); + + it('lists the gap between each pair of siblings', () => { + const layout = root(sized(row(v('a'), column(v('b'), v('c'))), [0.4, 0.6])); + expect(getLayoutDividers(layout)).toEqual([ + { + path: [], + index: 1, + direction: 'row', + position: 40, + start: 0, + length: 100, + groupStart: 0, + groupSize: 100, + }, + { + path: [1], + index: 1, + direction: 'column', + position: 50, + start: 40, + length: 60, + groupStart: 0, + groupSize: 100, + }, + ]); + }); + + it('moves only the two neighbors of a divider', () => { + const layout = root(row(v('a'), v('b'), v('c'), v('d'))); + const [, middle] = getLayoutDividers(layout); + expect(widths(moveLayoutDividers(layout, [middle], 55, container))).toEqual( + [25, 30, 20, 25] + ); + }); + + it('stops a divider where a neighbor reaches the minimum pane size', () => { + const layout = root(row(v('a'), v('b'))); + const [divider] = getLayoutDividers(layout); + expect(widths(moveLayoutDividers(layout, [divider], 2, container))).toEqual( + [16, 84] + ); + expect( + widths(moveLayoutDividers(layout, [divider], 99, container)) + ).toEqual([84, 16]); + }); + + it('keeps every pane inside a nested neighbor above the minimum', () => { + const layout = root(row(v('a'), column(v('b'), row(v('c'), v('d'))))); + const [divider] = getLayoutDividers(layout); + const moved = moveLayoutDividers(layout, [divider], 90, container); + expect(widths(moved)).toEqual([68, 32, 16, 16]); + }); + + it('lets an undersized pane grow but never shrink further', () => { + const layout = root(sized(row(v('a'), v('b')), [0.1, 0.9])); + const [divider] = getLayoutDividers(layout); + const move = (position: number) => + widths(moveLayoutDividers(layout, [divider], position, container)); + expect(move(5)).toEqual([10, 90]); + expect(move(30)).toEqual([30, 70]); + expect(move(99)).toEqual([84, 16]); + + const cramped = root(row(v('a'), v('b'))); + const [middle] = getLayoutDividers(cramped); + expect( + widths( + moveLayoutDividers(cramped, [middle], 40, { width: 200, height: 200 }) + ) + ).toEqual([50, 50]); + }); + + it('couples only the adjacent run of aligned sibling groups', () => { + const layout = root( + column( + row(v('a'), v('b')), + row(v('c'), v('d')), + v('e'), + row(v('f'), v('g')) + ) + ); + const dividers = getLayoutDividers(layout); + const [top, , bottom] = dividers.filter(({ path }) => path.length === 1); + expect(alignedDividers(dividers, top).map(({ path }) => path)).toEqual([ + [0], + [1], + ]); + expect(alignedDividers(dividers, bottom).map(({ path }) => path)).toEqual([ + [3], + ]); + expect( + widths( + moveLayoutDividers( + layout, + alignedDividers(dividers, top), + 30, + container + ) + ) + ).toEqual([30, 70, 30, 70, 100, 50, 50]); + }); + + it('moves aligned dividers in sibling groups together', () => { + const fourUp = root(column(row(v('a'), v('b')), row(v('c'), v('d')))); + const dividers = getLayoutDividers(fourUp); + const vertical = dividers.find((divider) => divider.path.length === 1)!; + const aligned = alignedDividers(dividers, vertical); + expect(aligned.map(({ path }) => path)).toEqual([[0], [1]]); + const moved = moveLayoutDividers(fourUp, aligned, 70, container); + expect(widths(moved)).toEqual([70, 30, 70, 30]); + expect( + alignedDividers(getLayoutDividers(moved), getLayoutDividers(moved)[1]) + ).toHaveLength(2); + + const offset = moveLayoutDividers( + moved, + [getLayoutDividers(moved)[1]], + 40, + container + ); + const lowerRow = getLayoutDividers(offset).find( + ({ path }) => path[0] === 1 + )!; + expect(alignedDividers(getLayoutDividers(offset), lowerRow)).toEqual([ + lowerRow, + ]); + }); + + it('limits aligned dividers by the tightest group', () => { + const layout = root( + column( + sized(row(v('a'), v('b')), [0.5, 0.5]), + row(v('c'), column(v('d'), v('e'), v('f'))) + ) + ); + const aligned = alignedDividers( + getLayoutDividers(layout), + getLayoutDividers(layout)[1] + ); + expect(aligned).toHaveLength(2); + expect(widths(moveLayoutDividers(layout, aligned, 95, container))).toEqual([ + 84, 16, 84, 16, 16, 16, + ]); + }); + + it('evens out only the two neighbors of a reset divider', () => { + const layout = root(sized(row(v('a'), v('b'), v('c')), [0.2, 0.3, 0.5])); + const [first] = getLayoutDividers(layout); + expect(widths(resetLayoutDividers(layout, [first]))).toEqual([25, 25, 50]); + }); + + it('resets the groups of the given dividers to equal shares', () => { + const layout = root( + sized( + column( + sized(row(v('a'), v('b')), [0.2, 0.8]), + sized(row(v('c'), v('d')), [0.2, 0.8]) + ), + [0.3, 0.7] + ) + ); + const dividers = getLayoutDividers(layout); + const reset = resetLayoutDividers( + layout, + alignedDividers(dividers, dividers[1]) + ); + expect(widths(reset)).toEqual([50, 50, 50, 50]); + expect(heights(reset)).toEqual([30, 30, 70, 70]); + }); + + it('halves the split pane and keeps every other pane in place', () => { + const layout = root(sized(row(v('a'), v('b')), [0.4, 0.6])); + const sibling = splitLayoutView(layout, 'b', 'c', 'row'); + expect(widths(sibling)).toEqual([40, 30, 30]); + const nested = splitLayoutView(layout, 'b', 'c', 'column'); + expect(getLayoutPanes(nested)).toEqual([ + { viewId: 'a', left: 0, top: 0, width: 40, height: 100 }, + { viewId: 'b', left: 40, top: 0, width: 60, height: 50 }, + { viewId: 'c', left: 40, top: 50, width: 60, height: 50 }, + ]); + }); + + it('gives a closed pane share to its previous neighbor, or the next when first', () => { + const layout = root(sized(row(v('a'), v('b'), v('c')), [0.2, 0.3, 0.5])); + expect(widths(removeLayoutView(layout, 'c'))).toEqual([20, 80]); + expect(widths(removeLayoutView(layout, 'b'))).toEqual([50, 50]); + expect(widths(removeLayoutView(layout, 'a'))).toEqual([50, 50]); + }); + + it('gives a closed half of a split or dock to the other half', () => { + const layout = root(row(v('a'), v('b'))); + const split = splitLayoutView(layout, 'b', 'n', 'row'); + expect(removeLayoutView(split, 'b')).toEqual( + replaceLayoutView(layout, 'b', 'n') + ); + const fourUp = root(column(row(v('a'), v('b')), row(v('c'), v('d')))); + const docked = moveLayoutView(fourUp, 'a', 'd', 'left'); + expect(removeLayoutView(docked, 'a')).toEqual( + root(column(v('b'), row(v('c'), v('d')))) + ); + }); + + it('restores the original sizes when a split view is closed', () => { + const layout = root( + sized(column(sized(row(v('a'), v('b')), [0.3, 0.7]), v('c')), [0.6, 0.4]) + ); + (['row', 'column'] as const).forEach((direction) => { + const split = splitLayoutView(layout, 'b', 'n', direction); + expect(removeLayoutView(split, 'n')).toEqual(layout); + }); + expect( + removeLayoutView(splitLayoutView(layout, 'a', 'n', 'row'), 'a') + ).toEqual(replaceLayoutView(layout, 'a', 'n')); + }); + + it('scales a collapsed group into its parent by the group share', () => { + const layout = root( + sized( + row(v('a'), column(v('b'), sized(row(v('c'), v('d')), [0.25, 0.75]))), + [0.2, 0.8] + ) + ); + expect(widths(removeLayoutView(layout, 'b'))).toEqual([20, 20, 60]); + }); + + it('keeps the shares of a group that becomes the root', () => { + const layout = root( + sized(column(sized(row(v('a'), v('b')), [0.3, 0.7]), v('c')), [0.5, 0.5]) + ); + expect(removeLayoutView(layout, 'c')).toEqual( + root(sized(row(v('a'), v('b')), [0.3, 0.7])) + ); + }); +}); diff --git a/src/utils/doubleKeyRecord.ts b/src/utils/doubleKeyRecord.ts index b0c3b10a0..6b13c3afb 100644 --- a/src/utils/doubleKeyRecord.ts +++ b/src/utils/doubleKeyRecord.ts @@ -29,6 +29,12 @@ export function deleteFirstKey(record: DoubleKeyRecord, k1: string) { delete record[k1]; } +/** Independent copies of k1's entries, which must hold JSON values. */ +export const cloneEntries = (record: DoubleKeyRecord, k1: string) => + Object.entries(record[k1] ?? {}).map( + ([k2, value]) => [k2, JSON.parse(JSON.stringify(value)) as V] as const + ); + export function deleteEntry( record: DoubleKeyRecord, k1: string, diff --git a/src/utils/layoutEditing.ts b/src/utils/layoutEditing.ts new file mode 100644 index 000000000..51de5173d --- /dev/null +++ b/src/utils/layoutEditing.ts @@ -0,0 +1,541 @@ +import type { + Layout, + LayoutDirection, + LayoutItem, + LayoutNode, + LayoutTree, + ViewLeaf, +} from '@/src/types/layout'; +import { clampValue, omit } from '@/src/utils'; + +type Leaf = { type: 'view' }; + +export function layoutLeaves(tree: LayoutTree): L[] { + return tree.items.flatMap((item) => + item.type === 'layout' ? layoutLeaves(item) : [item as L] + ); +} + +export function mapLayoutLeaves( + tree: LayoutTree, + map: (leaf: A) => B +): LayoutTree { + return { + direction: tree.direction, + items: tree.items.map( + (item): LayoutNode => + item.type === 'layout' + ? { type: 'layout', ...mapLayoutLeaves(item, map) } + : map(item as A) + ), + ...(tree.sizes && { sizes: tree.sizes }), + }; +} + +const sum = (values: readonly number[]) => + values.reduce((total, value) => total + value, 0); + +/** Each item's share of its group; sizes that do not fit the items mean equal. */ +function groupShares(tree: LayoutTree) { + const count = tree.items.length; + const { sizes } = tree; + if ( + sizes?.length !== count || + !sizes.every((size) => Number.isFinite(size) && size > 0) + ) + return tree.items.map(() => 1 / count); + const total = sum(sizes); + return sizes.map((size) => size / total); +} + +const EQUAL_SHARE_TOLERANCE = 1e-9; + +const sameShare = (a: number, b: number) => + Math.abs(a - b) < EQUAL_SHARE_TOLERANCE; + +// Equal shares are stored as absent sizes, so untouched layouts stay plain. +function withShares(tree: Layout, shares: readonly number[]): Layout { + const rest = omit(tree, 'sizes'); + const total = sum(shares); + const sizes = shares.map((share) => share / total); + const equal = sizes.every((size) => sameShare(size, 1 / sizes.length)); + return equal ? rest : { ...rest, sizes }; +} + +type Shared = [item: LayoutItem, share: number]; + +const sharedGroup = (direction: LayoutDirection, entries: Shared[]) => + withShares( + { direction, items: entries.map(([item]) => item) }, + entries.map(([, share]) => share) + ); + +export const layoutViewIds = (layout: Layout) => + layoutLeaves(layout).map((leaf) => leaf.viewId); + +export const viewLeaf = (viewId: string): ViewLeaf => ({ + type: 'view', + viewId, +}); + +// A root holding one group draws exactly like that group. +const collapseRoot = (layout: Layout): Layout => { + const [only] = layout.items; + if (layout.items.length !== 1 || only.type !== 'layout') return layout; + return collapseRoot(omit(only, 'type')); +}; + +function insertBeside( + layout: Layout, + targetId: string, + added: ViewLeaf, + edge: DropEdge +) { + const direction = edge === 'left' || edge === 'right' ? 'row' : 'column'; + const before = edge === 'left' || edge === 'top'; + const insertIn = (tree: Layout): Layout => { + const shares = groupShares(tree); + return sharedGroup( + tree.direction, + tree.items.flatMap((item, index): Shared[] => { + const share = shares[index]; + if (item.type === 'layout') + return [[{ type: 'layout', ...insertIn(item) }, share]]; + if (item.viewId !== targetId) return [[item, share]]; + const pair = before ? [added, item] : [item, added]; + // A sibling keeps each divider between exactly two neighbors. + if (tree.direction === direction) + return pair.map((leaf): Shared => [leaf, share / 2]); + return [[{ type: 'layout', direction, items: pair }, share]]; + }) + ); + }; + return collapseRoot(insertIn(layout)); +} + +export const splitLayoutView = ( + layout: Layout, + viewId: string, + newViewId: string, + direction: LayoutDirection +) => + insertBeside( + layout, + viewId, + viewLeaf(newViewId), + direction === 'row' ? 'right' : 'bottom' + ); + +// A group left with one item is replaced by it, merging into a parent of the +// same direction with its shares scaled to the group's share. +function collapsedGroup( + child: Layout, + share: number, + parentDirection: LayoutDirection +): Shared[] { + if (child.items.length === 0) return []; + if (child.items.length > 1) return [[{ type: 'layout', ...child }, share]]; + const [only] = child.items; + if (only.type !== 'layout' || only.direction !== parentDirection) + return [[only, share]]; + const inner = groupShares(only); + return only.items.map((item, index) => [item, share * inner[index]]); +} + +// An emptied item's share goes to an adjacent item of equal share, usually the +// other half of its split or dock. When both neighbors match, or neither does, +// it goes to the previous sibling, or the next when first. +function giveToNeighbor(groups: Shared[][], shares: readonly number[]) { + const gifts = groups.flatMap((entries, index) => { + if (entries.length > 0) return []; + const previous = groups[index - 1]?.at(-1); + const next = groups[index + 1]?.[0]; + const isTwin = (entry?: Shared) => + !!entry && sameShare(entry[1], shares[index]); + const receiver = + !previous || (isTwin(next) && !isTwin(previous)) ? next : previous; + return receiver ? [{ receiver, share: shares[index] }] : []; + }); + return groups.map((entries) => + entries.map( + (entry): Shared => [ + entry[0], + gifts + .filter(({ receiver }) => receiver === entry) + .reduce((total, { share }) => total + share, entry[1]), + ] + ) + ); +} + +export function removeLayoutView(layout: Layout, viewId: string) { + const removeIn = (tree: Layout): Layout => { + const shares = groupShares(tree); + const groups = tree.items.map((item, index): Shared[] => { + if (item.type === 'layout') + return collapsedGroup(removeIn(item), shares[index], tree.direction); + return item.viewId === viewId ? [] : [[item, shares[index]]]; + }); + return sharedGroup(tree.direction, giveToNeighbor(groups, shares).flat()); + }; + return collapseRoot(removeIn(layout)); +} + +export function replaceLayoutView( + layout: Layout, + viewId: string, + nextViewId: string +) { + return mapLayoutLeaves(layout, (leaf) => + leaf.viewId === viewId ? viewLeaf(nextViewId) : leaf + ); +} + +const swapLayoutViews = (layout: Layout, a: string, b: string) => + mapLayoutLeaves(layout, (leaf) => { + if (leaf.viewId === a) return viewLeaf(b); + if (leaf.viewId === b) return viewLeaf(a); + return leaf; + }); + +type DropEdge = 'left' | 'right' | 'top' | 'bottom'; +/** Where a dragged view lands on a target pane: beside an edge, or swapped. */ +export type DropZone = DropEdge | 'center'; + +export function moveLayoutView( + layout: Layout, + viewId: string, + targetId: string, + zone: DropZone +) { + if (viewId === targetId) return layout; + if (zone === 'center') return swapLayoutViews(layout, viewId, targetId); + return insertBeside( + removeLayoutView(layout, viewId), + targetId, + viewLeaf(viewId), + zone + ); +} + +// A one-item group draws exactly like its item. +const unwrap = (node: LayoutNode): LayoutNode => + node.type === 'layout' && node.items.length === 1 + ? unwrap(node.items[0]) + : node; + +/** Whether two layouts draw the same panes, with leaves matched in order. */ +export function sameLayoutShape( + a: LayoutTree, + b: LayoutTree, + sameLeaf: (a: A, b: B) => boolean +) { + const match = (x: LayoutNode, y: LayoutNode): boolean => { + const left = unwrap(x); + const right = unwrap(y); + if (left.type !== 'layout' || right.type !== 'layout') + return ( + left.type !== 'layout' && + right.type !== 'layout' && + sameLeaf(left as A, right as B) + ); + return ( + left.direction === right.direction && + left.items.length === right.items.length && + left.items.every((item, index) => match(item, right.items[index])) + ); + }; + return match({ type: 'layout', ...a }, { type: 'layout', ...b }); +} + +export type Bounds = { + left: number; + top: number; + width: number; + height: number; +}; +type Size = { width: number; height: number }; + +const FULL_BOUNDS: Bounds = { left: 0, top: 0, width: 100, height: 100 }; + +export const axisOf = (direction: LayoutDirection) => + direction === 'row' + ? ({ start: 'left', size: 'width' } as const) + : ({ start: 'top', size: 'height' } as const); + +function itemBounds(tree: LayoutTree, bounds: Bounds): Bounds[] { + const { start, size } = axisOf(tree.direction); + const shares = groupShares(tree); + return shares.map((share, index) => ({ + ...bounds, + [start]: bounds[start] + sum(shares.slice(0, index)) * bounds[size], + [size]: share * bounds[size], + })); +} + +// Flat panes let Vue retain viewer instances when their nesting changes. +export function getLayoutPanes( + layout: Layout, + bounds: Bounds = FULL_BOUNDS +): (Bounds & { viewId: string })[] { + const children = itemBounds(layout, bounds); + return layout.items.flatMap((item, index) => + item.type === 'view' + ? [{ ...children[index], viewId: item.viewId }] + : getLayoutPanes(item, children[index]) + ); +} + +/** + * The gap before `items[index]` of the group at `path` (item indices from the + * root). Values are percentages of the layout; `position` and the group span + * run along the group's direction, `start` and `length` across it. + */ +export type LayoutDivider = { + path: readonly number[]; + index: number; + direction: LayoutDirection; + position: number; + start: number; + length: number; + groupStart: number; + groupSize: number; +}; + +export function getLayoutDividers(layout: Layout) { + const inGroup = ( + tree: Layout, + bounds: Bounds, + path: readonly number[] + ): LayoutDivider[] => { + const along = axisOf(tree.direction); + const across = axisOf(tree.direction === 'row' ? 'column' : 'row'); + const children = itemBounds(tree, bounds); + const own = children.slice(1).map((child, offset) => ({ + path, + index: offset + 1, + direction: tree.direction, + position: child[along.start], + start: bounds[across.start], + length: bounds[across.size], + groupStart: bounds[along.start], + groupSize: bounds[along.size], + })); + const nested = tree.items.flatMap((item, index) => + item.type === 'layout' + ? inGroup(item, children[index], [...path, index]) + : [] + ); + return [...own, ...nested]; + }; + return inGroup(layout, FULL_BOUNDS, []); +} + +const ALIGNED_TOLERANCE = 1e-6; + +const sameParent = (a: readonly number[], b: readonly number[]) => + a.length === b.length && a.slice(0, -1).every((step, i) => step === b[i]); + +const lastStep = (divider: LayoutDivider) => divider.path.at(-1) ?? -1; + +/** + * Dividers continuing `divider` across the run of adjacent sibling groups + * that share its position, itself included. + */ +export function alignedDividers( + dividers: readonly LayoutDivider[], + divider: LayoutDivider +) { + const aligned = dividers.filter( + (other) => + other.direction === divider.direction && + sameParent(other.path, divider.path) && + Math.abs(other.position - divider.position) < ALIGNED_TOLERANCE + ); + const at = new Set(aligned.map(lastStep)); + const reach = (step: number) => { + let index = lastStep(divider); + while (at.has(index + step)) index += step; + return index; + }; + const [first, last] = [reach(-1), reach(1)]; + return aligned.filter( + (other) => lastStep(other) >= first && lastStep(other) <= last + ); +} + +/** The smallest pane, in pixels, whose view controls stay usable. */ +const MIN_PANE_SIZE: Size = { width: 160, height: 120 }; + +/** Whether a pane of this pixel size can split in each direction. */ +export const canSplit = ({ width, height }: Size) => ({ + row: width >= 2 * MIN_PANE_SIZE.width, + column: height >= 2 * MIN_PANE_SIZE.height, +}); + +const groupAt = (tree: Layout, path: readonly number[]): Layout => { + if (path.length === 0) return tree; + const item = tree.items[path[0]]; + if (item.type !== 'layout') throw new Error('Divider path ends at a view'); + return groupAt(item, path.slice(1)); +}; + +const updateGroup = ( + tree: Layout, + path: readonly number[], + update: (group: Layout) => Layout +): Layout => { + if (path.length === 0) return update(tree); + const [head, ...rest] = path; + return { + ...tree, + items: tree.items.map((item, index) => + index === head && item.type === 'layout' + ? { type: 'layout', ...updateGroup(item, rest, update) } + : item + ), + }; +}; + +// Pixels an item needs along a direction so every pane in it keeps `minimum`. +const minimumExtent = ( + item: LayoutItem, + direction: LayoutDirection, + minimum: number +): number => { + if (item.type === 'view') return minimum; + const shares = groupShares(item); + return Math.max( + ...item.items.map( + (child, index) => + minimumExtent(child, direction, minimum) / + (item.direction === direction ? shares[index] : 1) + ) + ); +}; + +function dividerShares(group: Layout, divider: LayoutDivider) { + const shares = groupShares(group); + return { + shares, + before: sum(shares.slice(0, divider.index - 1)), + pair: shares[divider.index - 1] + shares[divider.index], + }; +} + +// Percent positions a divider may take with both neighbors above the minimum. +function dividerRange(layout: Layout, divider: LayoutDivider, container: Size) { + const { size } = axisOf(divider.direction); + const group = groupAt(layout, divider.path); + const groupPixels = (divider.groupSize / 100) * container[size]; + const toPercent = (fraction: number) => + divider.groupStart + fraction * divider.groupSize; + const need = (index: number) => + minimumExtent(group.items[index], divider.direction, MIN_PANE_SIZE[size]) / + groupPixels; + const { before, pair } = dividerShares(group, divider); + // An undersized neighbor may grow but never shrink further. + return { + low: Math.min( + toPercent(before + need(divider.index - 1)), + divider.position + ), + high: Math.max( + toPercent(before + pair - need(divider.index)), + divider.position + ), + }; +} + +// The second neighbor takes what the first leaves of their pair. +function setDividerShare( + layout: Layout, + divider: LayoutDivider, + first: (around: ReturnType) => number +) { + return updateGroup(layout, divider.path, (group) => { + const around = dividerShares(group, divider); + const share = first(around); + return withShares( + group, + around.shares.map((current, index) => { + if (index === divider.index - 1) return share; + if (index === divider.index) return around.pair - share; + return current; + }) + ); + }); +} + +/** + * Moves aligned dividers to one percent position, limited so no pane in either + * neighbor drops below MIN_PANE_SIZE pixels of `container`, or further below + * it when already smaller. + */ +export function moveLayoutDividers( + layout: Layout, + dividers: readonly LayoutDivider[], + position: number, + container: Size +) { + const ranges = dividers.map((divider) => + dividerRange(layout, divider, container) + ); + const clamped = clampValue( + position, + Math.max(...ranges.map((range) => range.low)), + Math.min(...ranges.map((range) => range.high)) + ); + return dividers.reduce( + (next, divider) => + setDividerShare( + next, + divider, + ({ before }) => + (clamped - divider.groupStart) / divider.groupSize - before + ), + layout + ); +} + +const DOCK_EDGE_FRACTION = 0.25; + +/** + * The drop zone under a point in a pane, both in layout percent. Edges dock + * only where the target can split without going below MIN_PANE_SIZE. + */ +export function pickDropZone( + pane: Bounds, + point: { x: number; y: number }, + container: Size +): DropZone { + const x = (point.x - pane.left) / pane.width; + const y = (point.y - pane.top) / pane.height; + const fits = canSplit({ + width: (pane.width / 100) * container.width, + height: (pane.height / 100) * container.height, + }); + const edges = [ + { zone: 'left', distance: x, direction: 'row' }, + { zone: 'right', distance: 1 - x, direction: 'row' }, + { zone: 'top', distance: y, direction: 'column' }, + { zone: 'bottom', distance: 1 - y, direction: 'column' }, + ] as const; + const nearest = edges + .filter( + ({ distance, direction }) => + fits[direction] && distance < DOCK_EDGE_FRACTION + ) + .sort((a, b) => a.distance - b.distance)[0]; + return nearest?.zone ?? 'center'; +} + +/** Splits each divider's two neighbors evenly again. */ +export const resetLayoutDividers = ( + layout: Layout, + dividers: readonly LayoutDivider[] +) => + dividers.reduce( + (next, divider) => setDividerShare(next, divider, ({ pair }) => pair / 2), + layout + ); diff --git a/src/utils/layoutParsing.ts b/src/utils/layoutParsing.ts index 5872fb9e2..6b354492e 100644 --- a/src/utils/layoutParsing.ts +++ b/src/utils/layoutParsing.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import type { Layout, LayoutItem } from '@/src/types/layout'; +import type { LayoutTemplate } from '@/src/types/layout'; import type { ViewInfoInit } from '@/src/types/views'; const viewString = z.enum([ @@ -158,33 +158,21 @@ const viewSpecToViewInfoInit = (spec: ViewSpec): ViewInfoInit => { throw new Error(`Unknown view spec type`); }; -const parseGridLayout = (grid: ViewString[][]) => { - let slotIndex = 0; +type TemplateItem = LayoutTemplate['items'][number]; - const items = grid.map((row) => { - const rowItems = row.map(() => { - const currentSlot = slotIndex; - slotIndex += 1; - return { type: 'slot' as const, slotIndex: currentSlot }; - }); - - return { - type: 'layout' as const, - direction: 'row' as const, - items: rowItems, - }; - }); - - const views = grid.flat().map((viewStr) => stringToViewInfoInit(viewStr)); +const templateLeaf = (view: ViewInfoInit): TemplateItem => ({ + type: 'view', + view, +}); - return { - layout: { - direction: 'column' as const, - items, - }, - views, - }; -}; +const parseGridLayout = (grid: ViewString[][]): LayoutTemplate => ({ + direction: 'column', + items: grid.map((row) => ({ + type: 'layout', + direction: 'row', + items: row.map((viewStr) => templateLeaf(stringToViewInfoInit(viewStr))), + })), +}); const parseGridSizeLayout = (gridSize: [number, number]) => { const cols = gridSize[0]; @@ -195,45 +183,29 @@ const parseGridSizeLayout = (gridSize: [number, number]) => { return parseGridLayout(grid); }; -const parseNestedLayout = (layoutItem: LayoutConfigItem) => { - const views: ViewInfoInit[] = []; - let slotIndex = 0; - - const isViewSpec = (item: LayoutConfigItem): item is ViewSpec => - typeof item === 'string' || 'type' in item; +const isViewSpec = (item: LayoutConfigItem): item is ViewSpec => + typeof item === 'string' || 'type' in item; - const processItem = (item: LayoutConfigItem): LayoutItem => { - if (isViewSpec(item)) { - const viewInfo = viewSpecToViewInfoInit(item); - views.push(viewInfo); - const currentSlot = slotIndex; - slotIndex += 1; - return { type: 'slot' as const, slotIndex: currentSlot }; - } - - return { - type: 'layout' as const, - direction: item.direction, - items: item.items.map(processItem), - }; - }; +const parseNestedItem = (item: LayoutConfigItem): TemplateItem => + isViewSpec(item) + ? templateLeaf(viewSpecToViewInfoInit(item)) + : { + type: 'layout', + direction: item.direction, + items: item.items.map(parseNestedItem), + }; +const parseNestedLayout = (layoutItem: LayoutConfigItem): LayoutTemplate => { const rootLayout = isViewSpec(layoutItem) ? { direction: 'column' as const, items: [layoutItem] } : layoutItem; - return { - layout: { - direction: rootLayout.direction, - items: rootLayout.items.map(processItem), - }, - views, + direction: rootLayout.direction, + items: rootLayout.items.map(parseNestedItem), }; }; -export const parseLayoutConfig = ( - layoutDef: LayoutConfig -): { layout: Layout; views: ViewInfoInit[] } => { +export const parseLayoutConfig = (layoutDef: LayoutConfig): LayoutTemplate => { if (Array.isArray(layoutDef)) { return parseGridLayout(layoutDef); } @@ -245,7 +217,7 @@ export const parseLayoutConfig = ( export const parseNamedLayouts = ( layouts: Record -): Record => { +): Record => { const entries = Object.entries(layouts); entries.forEach(([name]) => { diff --git a/tests/fixtures.ts b/tests/fixtures.ts index 9465655df..6b7889659 100644 --- a/tests/fixtures.ts +++ b/tests/fixtures.ts @@ -23,6 +23,7 @@ import { createOverlaySegmentationUtils } from './specs/overlaySegmentationTestU import { createVolumeUtils } from './specs/volumeTestUtils'; import { createCineUtils } from './specs/cineTestUtils'; import { createProbeUtils } from './specs/probeTestUtils'; +import { createViewLayoutUtils } from './specs/viewLayoutTestUtils'; export { expect } from '@playwright/test'; @@ -127,6 +128,7 @@ export const test = base.extend<{ volume: ReturnType; cine: ReturnType; probe: ReturnType; + layout: ReturnType; }>({ context: async ({ context }, use) => { await context.addInitScript(stringifyConsoleErrors); @@ -174,6 +176,7 @@ export const test = base.extend<{ volume: ({ page, scratch }, use) => use(createVolumeUtils(page, scratch)), cine: ({ page, scratch }, use) => use(createCineUtils(page, scratch)), probe: ({ page }, use) => use(createProbeUtils(page)), + layout: ({ page, scratch }, use) => use(createViewLayoutUtils(page, scratch)), }); const openSharedPage = async (browser: Browser) => { diff --git a/tests/specs/enface-slice-annotations.e2e.ts b/tests/specs/enface-slice-annotations.e2e.ts index 7d854ea86..b81c2422f 100644 --- a/tests/specs/enface-slice-annotations.e2e.ts +++ b/tests/specs/enface-slice-annotations.e2e.ts @@ -360,7 +360,8 @@ test.describe('En face annotations', () => { await size.focus(); await page.keyboard.press('Home'); await expect(size).toHaveAttribute('aria-valuenow', '1'); - const outside = await oct.enFaceScreenPoint(16.5, -3); + // Above the image, since the view controls sit beside its bottom edge. + const outside = await oct.enFaceScreenPoint(16.5, 25.5); const inside = await oct.enFaceScreenPoint(16.5, 12.5); await annotation.nudgeTo(outside.x, outside.y); await annotation.dragPointerTo(inside.x, inside.y); diff --git a/tests/specs/layout-config.e2e.ts b/tests/specs/layout-config.e2e.ts index fc0f73b9f..3dcfefd65 100644 --- a/tests/specs/layout-config.e2e.ts +++ b/tests/specs/layout-config.e2e.ts @@ -82,7 +82,7 @@ test.describe('VolView Layout Configuration', () => { await volview.waitForViewCounts(2, true); }); - test('should support multiple named layouts and preserve slice selection', async ({ + test('should support multiple named layouts that each start at default slices', async ({ volview, configUtils, }) => { @@ -129,7 +129,7 @@ test.describe('VolView Layout Configuration', () => { await volview.focusFirst2DView(); const sliceAfterLayoutSwitch = await volview.getFirst2DSlice(); - expect(sliceAfterLayoutSwitch).toBe(sliceAfterScroll); + expect(sliceAfterLayoutSwitch).toBe(initialSlice); await volview.openLayoutMenu(3); await volview.selectLayoutOption('Dual Axial'); @@ -137,7 +137,74 @@ test.describe('VolView Layout Configuration', () => { await volview.focusFirst2DView(); const sliceInFirstViewAfterDualSwitch = await volview.getFirst2DSlice(); - expect(sliceInFirstViewAfterDualSwitch).toBe(sliceAfterScroll); + expect(sliceInFirstViewAfterDualSwitch).toBe(initialSlice); + }); + + test('keeps the layout and views of a session opened with a config', async ({ + volview, + utils, + layout, + }) => { + const image = utils.writeMetaImage('config-session-layout.mha'); + const session = 'config-session-layout.volview.json'; + await utils.writeManifestToFile( + { + version: '9.0.0', + dataSources: [ + { id: 0, type: 'uri', uri: `/tmp/${image}`, name: image }, + ], + datasets: [{ id: '0', dataSourceId: 0 }], + layout: { + direction: 'row', + items: [ + { type: 'view', viewId: 'saved' }, + { type: 'view', viewId: 'other' }, + ], + }, + activeView: 'saved', + viewByID: { + saved: { + id: 'saved', + type: '2D', + name: 'Axial', + dataID: '0', + options: { orientation: 'Axial' }, + config: { + '0': { slice: { slice: 3, min: 0, max: 15, syncState: false } }, + }, + }, + other: { + id: 'other', + type: '2D', + name: 'Coronal', + dataID: '0', + options: { orientation: 'Coronal' }, + }, + }, + }, + session + ); + const config = 'config-session-layout-config.json'; + await utils.writeManifestToFile( + { + layouts: { + Reading: { + direction: 'row', + items: [{ type: '2D', orientation: 'Axial', name: 'Transverse' }], + }, + }, + }, + config + ); + + await volview.open(`?urls=[tmp/${session},tmp/${config}]`); + await volview.waitForViews(); + await expect + .poll(volview.getFirst2DSlice, { + message: 'Expected the saved slice, 4 of 16', + }) + .toBe(4); + await expect(layout.typeLabels).toHaveText(['Axial', 'Coronal']); }); test('should disable configured view types', async ({ diff --git a/tests/specs/oct-import.e2e.ts b/tests/specs/oct-import.e2e.ts index e5bb301d9..b06943dbd 100644 --- a/tests/specs/oct-import.e2e.ts +++ b/tests/specs/oct-import.e2e.ts @@ -56,13 +56,6 @@ test.describe('Retinal OCT import', () => { await oct.expectHighlight(true); await oct.expectControlsBesideSelector(); await page.keyboard.press('Escape'); - await octInteraction.dragEnFaceContrast(); - const retainedWindow = await oct.getEnFaceWindow(); - const retainedSlice = await volview.getFirst2DSlice(); - await oct.selectTwoRowLayout(); - await oct.expectHighlight(true); - expect(await oct.getEnFaceWindow()).toEqual(retainedWindow); - expect(await volview.getFirst2DSlice()).toBe(retainedSlice); await octInteraction.expectSliceLine(); await oct.expectEnFaceSegmentShown('Synthetic retinal layer', '31'); await volview.focusFirst2DView(); diff --git a/tests/specs/octTestUtils.ts b/tests/specs/octTestUtils.ts index d8b7ebc02..1e898a30e 100644 --- a/tests/specs/octTestUtils.ts +++ b/tests/specs/octTestUtils.ts @@ -177,24 +177,28 @@ export const createOctUtils = (page: Page, scratch: Scratch) => { const bounds = await page.evaluate(() => { const viewer = document.querySelector('[data-testid="enface-viewer"]'); const button = viewer?.querySelector('[data-testid="enface-controls"]'); + const split = viewer?.querySelector('button[aria-label="View actions"]'); const selector = viewer?.querySelector('.view-type-select'); const canvas = viewer?.querySelector('canvas'); const panel = document.querySelector( '.v-overlay--active [data-testid="enface-rendering-panel"]' ); - if (!button || !selector || !canvas || !panel) + if (!button || !split || !selector || !canvas || !panel) throw new Error('En face controls or image are missing'); const tune = button.getBoundingClientRect(); + const splitBounds = split.getBoundingClientRect(); const select = selector.getBoundingClientRect(); return { - gap: select.left - tune.right, + gaps: [select.left - tune.right, splitBounds.left - select.right], panelLeft: panel.getBoundingClientRect().left, panelRight: panel.getBoundingClientRect().right, viewportWidth: innerWidth, }; }); - expect(bounds.gap).toBeGreaterThanOrEqual(0); - expect(bounds.gap).toBeLessThan(12); + bounds.gaps.forEach((gap) => { + expect(gap).toBeGreaterThanOrEqual(0); + expect(gap).toBeLessThan(12); + }); expect(bounds.panelLeft).toBeGreaterThanOrEqual(0); expect(bounds.panelRight).toBeLessThanOrEqual(bounds.viewportWidth); }; diff --git a/tests/specs/rejected-layout-restore.e2e.ts b/tests/specs/rejected-layout-restore.e2e.ts new file mode 100644 index 000000000..5e829f633 --- /dev/null +++ b/tests/specs/rejected-layout-restore.e2e.ts @@ -0,0 +1,84 @@ +import { test, expect } from '../fixtures'; +import type { ViewLayoutUtils } from './viewLayoutTestUtils'; + +const waitForEveryPaneToShow = (layout: ViewLayoutUtils, name: string) => + expect + .poll( + async () => { + const texts = await layout.panes.allTextContents(); + return texts.length > 0 && texts.every((text) => text.includes(name)); + }, + { message: `Expected every pane to show ${name}` } + ) + .toBe(true); + +const sessionOf = (image: string, layoutFields: Record) => ({ + dataSources: [{ id: 0, type: 'uri', uri: `/tmp/${image}`, name: image }], + datasets: [{ id: '0', dataSourceId: 0 }], + ...layoutFields, +}); + +const axialView = (id: string) => ({ + id, + type: '2D', + name: 'Axial', + dataID: '0', + options: { orientation: 'Axial' }, +}); + +test.describe('Restoring a session whose layout cannot be restored', () => { + test('shows the restored image in the panes it keeps', async ({ + volview, + utils, + layout, + }) => { + const current = utils.writeMetaImage('rejected-layout-current.mha'); + const restored = utils.writeMetaImage('rejected-layout-restored.mha', { + step: 3, + }); + const session = await utils.writeManifestToFile( + sessionOf(restored, { + version: '9.0.0', + // A view shown in two panes is not a layout VolView can restore. + layout: { + direction: 'row', + items: [ + { type: 'view', viewId: 'saved' }, + { type: 'view', viewId: 'saved' }, + ], + }, + activeView: 'saved', + viewByID: { saved: axialView('saved') }, + }), + 'rejected-layout.volview.json' + ); + + await volview.open(`?urls=[tmp/${current}]`); + await volview.waitForViews(); + await waitForEveryPaneToShow(layout, current); + + await utils.openThroughDialog(session); + await waitForEveryPaneToShow(layout, restored); + }); + + test('opens an 8.0.0 session whose layout names a slot it never saved', async ({ + volview, + utils, + layout, + }) => { + const image = utils.writeMetaImage('unslotted-layout.mha'); + const session = 'unslotted-layout.volview.json'; + await utils.writeManifestToFile( + sessionOf(image, { + version: '8.0.0', + layout: { direction: 'row', items: [{ type: 'slot', slotIndex: 0 }] }, + viewByID: { axial: axialView('axial') }, + }), + session + ); + + await volview.open(`?urls=[tmp/${session}]`); + await volview.waitForViews(); + await waitForEveryPaneToShow(layout, image); + }); +}); diff --git a/tests/specs/session-state-lifecycle.e2e.ts b/tests/specs/session-state-lifecycle.e2e.ts index 3986ff586..4bf350a7c 100644 --- a/tests/specs/session-state-lifecycle.e2e.ts +++ b/tests/specs/session-state-lifecycle.e2e.ts @@ -181,7 +181,7 @@ test.describe('Session state lifecycle', () => { const segmentColorBefore = await segmentation.segmentColor('Right hip'); const { session, manifest } = await saveAndParseManifest(volview, scratch); - expect(manifest.version).toEqual('8.0.0'); + expect(manifest.version).toEqual('9.0.0'); await volview.open(`?urls=[tmp/${session}]`); await volview.waitForViews(); diff --git a/tests/specs/slice-display-lifecycle.e2e.ts b/tests/specs/slice-display-lifecycle.e2e.ts index d01243119..bcf881c52 100644 --- a/tests/specs/slice-display-lifecycle.e2e.ts +++ b/tests/specs/slice-display-lifecycle.e2e.ts @@ -14,6 +14,7 @@ import { import type { Utils } from './utils'; const baseName = 'slice-lifecycle-base.mha'; +const overlayName = 'slice-lifecycle-overlay.mha'; const obliqueSlices = '.oblique-grid > .d-flex:not(:nth-child(2)) [data-testid="vtk-view"]'; @@ -53,13 +54,11 @@ const createLifecycleHelpers = ({ utils.captureViewPixels(obliqueSlices, 40, fileName); const moveToHeader = () => utils.moveToElement(page.locator('header')); - async function showBaseInAllViews() { + async function showInAllViews(name = baseName) { await page.locator('[data-testid="module-tab-Data"]').click(); await utils.waitForModuleTransitions(); await utils.showInAllViews( - page - .locator('.image-list-card', { hasText: containsText(baseName) }) - .first() + page.locator('.image-list-card', { hasText: containsText(name) }).first() ); } @@ -121,9 +120,7 @@ const createLifecycleHelpers = ({ async function openDisplay(layout: 'Four Up' | 'flat' | 'grid' = 'Four Up') { const base = utils.writeMetaImage(baseName); - const overlay = utils.writeMetaImage('slice-lifecycle-overlay.mha', { - step: 29, - }); + const overlay = utils.writeMetaImage(overlayName, { step: 29 }); await utils.writeManifestToFile( { ...layeredImageManifest(base, overlay), @@ -164,7 +161,7 @@ const createLifecycleHelpers = ({ if (layout === 'flat') await volview.waitForViewCounts(2, false); else await utils.selectLayout('Four Up', 3, true); if (layout === 'grid') await utils.selectGrid(4, 4); - await showBaseInAllViews(); + await showInAllViews(); await layerDisplay.openLayerDisplayControls(); const palette = page.locator('[data-testid="base-image-colormap"]'); await palette.evaluate((element) => @@ -180,7 +177,7 @@ const createLifecycleHelpers = ({ await option.click(); await setBaseRange(20, 200); await expectBaseSettings(); - await expectColoredSlices(layout === 'flat' ? 2 : 3); + await expectColoredSlices({ flat: 2, 'Four Up': 3, grid: 4 }[layout]); } async function toggleVisibility(image: 'base-image' | 'layer') { @@ -197,7 +194,7 @@ const createLifecycleHelpers = ({ captureSlicePixels, captureOblique, moveToHeader, - showBaseInAllViews, + showInAllViews, setBaseRange, expectBaseSettings, expectColoredSlices, @@ -303,7 +300,7 @@ test.describe('Slice display lifecycle', () => { visibility, captureSlices, moveToHeader, - showBaseInAllViews, + showInAllViews, expectBaseSettings, expectColoredSlices, openDisplay, @@ -311,14 +308,14 @@ test.describe('Slice display lifecycle', () => { } = createLifecycleHelpers({ page, volview, utils, layerDisplay }); await openDisplay('grid'); await toggleVisibility('layer'); - await expectColoredSlices(3); + await expectColoredSlices(4); await toggleVisibility('base-image'); await expect(visibility('base-image')).toContainText('SHOW', { useInnerText: true, }); await utils.selectGrid(7, 6); - await showBaseInAllViews(); - await volview.waitForViewCounts(5, true); + await showInAllViews(); + await volview.waitForViewCounts(6, false); await layerDisplay.openLayerDisplayControls(); await expectBaseSettings(); await expect(visibility('base-image')).toContainText('SHOW', { @@ -329,12 +326,28 @@ test.describe('Slice display lifecycle', () => { .poll(async () => { const pixels = await captureSlices(); return ( - pixels.length === 5 && pixels.every(({ colored }) => colored < 100) + pixels.length === 6 && pixels.every(({ colored }) => colored < 100) ); }) .toBe(true); await toggleVisibility('base-image'); - await expectColoredSlices(5); + await expectColoredSlices(6); + await expectBaseSettings(); + }); + + test('keeps base palette and window through a grid picked while another image shows', async ({ + page, + volview, + utils, + layerDisplay, + }) => { + const { showInAllViews, expectBaseSettings, openDisplay } = + createLifecycleHelpers({ page, volview, utils, layerDisplay }); + await openDisplay(); + await showInAllViews(overlayName); + await utils.selectGrid(4, 4); + await showInAllViews(); + await layerDisplay.openLayerDisplayControls(); await expectBaseSettings(); }); diff --git a/tests/specs/view-moving.e2e.ts b/tests/specs/view-moving.e2e.ts new file mode 100644 index 000000000..5f64a9786 --- /dev/null +++ b/tests/specs/view-moving.e2e.ts @@ -0,0 +1,165 @@ +import type { Page } from '@playwright/test'; +import { test, expect } from '../fixtures'; +import { exactText } from '../pageobjects/volview.page'; +import { center, type ViewLayoutUtils } from './viewLayoutTestUtils'; + +const expectNear = (actual: number, expected: number) => + expect(Math.abs(actual - expected)).toBeLessThan(1); + +const createMoveHelpers = (page: Page, layout: ViewLayoutUtils) => { + const preview = page.locator('.layout-drop-preview'); + + const paneOf = (type: string) => + layout.panes.filter({ + has: page.locator('.v-select__selection-text', { + hasText: exactText(type), + }), + }); + + const boundsOf = (type: string) => layout.bounds(paneOf(type)); + + const boundsByType = async () => { + const [Axial, Coronal, Sagittal, Volume] = await Promise.all( + ['Axial', 'Coronal', 'Sagittal', 'Volume'].map(boundsOf) + ); + return { Axial, Coronal, Sagittal, Volume }; + }; + + const dragView = async ( + type: string, + to: { x: number; y: number }, + options?: { hold: boolean } + ) => { + const handle = paneOf(type).locator('button[aria-label="Move view"]'); + await layout.drag(center(await layout.bounds(handle)), to, options); + }; + + const openQuad = () => + layout.openLayoutFixture( + 'view-moving', + { + Quad: [ + ['axial', 'coronal'], + ['sagittal', 'volume'], + ], + }, + 4 + ); + + return { preview, boundsOf, boundsByType, dragView, openQuad }; +}; + +test.describe('Moving views', () => { + test('docks a dragged view beside the edge it is dropped on, keeping renderers', async ({ + page, + layout, + }) => { + const { boundsOf, boundsByType, dragView, openQuad } = createMoveHelpers( + page, + layout + ); + await openQuad(); + await layout.markCanvases(); + const before = await boundsByType(); + const volume = before.Volume; + + await dragView('Axial', { + x: Math.round(volume.left + volume.width - 10), + y: Math.round(volume.top + volume.height / 2), + }); + + await expect + .poll(async () => + Math.abs((await boundsOf('Coronal')).left - before.Axial.left) + ) + .toBeLessThan(1); + const after = await boundsByType(); + expectNear(after.Coronal.width, before.Axial.width * 2); + expectNear(after.Axial.top, volume.top); + expectNear( + after.Axial.left + after.Axial.width, + volume.left + volume.width + ); + expectNear(after.Volume.left, volume.left); + expectNear(after.Volume.width, volume.width / 2); + expectNear(after.Sagittal.width, before.Sagittal.width); + await expect(layout.keptCanvases).toHaveCount(4); + }); + + test('previews where a view docked beside its neighbor lands', async ({ + page, + layout, + }) => { + const { preview, boundsOf, dragView, openQuad } = createMoveHelpers( + page, + layout + ); + await openQuad(); + const coronal = await boundsOf('Coronal'); + + await dragView( + 'Axial', + { + x: Math.round(coronal.left + 10), + y: Math.round(coronal.top + coronal.height / 2), + }, + { hold: true } + ); + await expect(preview).toBeVisible(); + const expected = await layout.bounds(preview); + await page.mouse.up(); + await expect(preview).toBeHidden(); + + const landed = await boundsOf('Axial'); + (['left', 'top', 'width', 'height'] as const).forEach((side) => + expectNear(landed[side], expected[side]) + ); + }); + + test('swaps two views when one is dropped on the middle of the other', async ({ + page, + layout, + }) => { + const { boundsOf, boundsByType, dragView, openQuad } = createMoveHelpers( + page, + layout + ); + await openQuad(); + const before = await boundsByType(); + const sagittal = before.Sagittal; + + await dragView('Coronal', center(sagittal)); + + await expect + .poll(async () => + Math.abs((await boundsOf('Coronal')).top - sagittal.top) + ) + .toBeLessThan(1); + const after = await boundsByType(); + expect(after.Coronal).toEqual(sagittal); + expect(after.Sagittal).toEqual(before.Coronal); + expect(after.Axial).toEqual(before.Axial); + }); + + test('leaves the layout alone when the drag is canceled with Escape', async ({ + page, + layout, + }) => { + const { preview, boundsByType, dragView, openQuad } = createMoveHelpers( + page, + layout + ); + await openQuad(); + const before = await boundsByType(); + const sagittal = before.Sagittal; + + await dragView('Coronal', center(sagittal), { hold: true }); + await expect(preview).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(preview).toBeHidden(); + await page.mouse.up(); + + await layout.waitForPaneCount(4); + expect(await boundsByType()).toEqual(before); + }); +}); diff --git a/tests/specs/view-resizing.e2e.ts b/tests/specs/view-resizing.e2e.ts new file mode 100644 index 000000000..a3c608bae --- /dev/null +++ b/tests/specs/view-resizing.e2e.ts @@ -0,0 +1,297 @@ +import type { Locator, Page } from '@playwright/test'; +import { test, expect } from '../fixtures'; +import { center, type ViewLayoutUtils } from './viewLayoutTestUtils'; + +const MIN_PANE_WIDTH = 160; + +const createResizeHelpers = (page: Page, layout: ViewLayoutUtils) => { + const dividers = page.locator( + '[role="separator"][aria-label="Resize views"]' + ); + const verticalDividers = dividers.and( + page.locator('[aria-orientation="vertical"]') + ); + + const dragDivider = async (divider: Locator, dx: number) => { + const from = center(await layout.bounds(divider)); + await layout.drag(from, { x: from.x + dx, y: from.y }); + }; + + const waitForPaneWidth = (index: number, width: number) => + expect + .poll(async () => (await layout.paneBounds(index)).width, { + message: `Expected pane ${index} to be ${width}px wide`, + }) + .toBeCloseTo(width, 0); + + const openDual = () => + layout.openLayoutFixture( + 'view-resizing', + { Dual: [['axial', 'axial']] }, + 2 + ); + + const openDualPanes = async () => { + await openDual(); + return [await layout.paneBounds(0), await layout.paneBounds(1)]; + }; + + const narrowFirstPane = async () => { + await openDual(); + const left = await layout.paneBounds(0); + await dragDivider(verticalDividers.first(), -left.width); + await waitForPaneWidth(0, MIN_PANE_WIDTH); + expect((await layout.paneBounds(0)).left).toBe(left.left); + }; + + return { + dividers, + verticalDividers, + dragDivider, + waitForPaneWidth, + openDual, + openDualPanes, + narrowFirstPane, + }; +}; + +test.describe('Resizing views', () => { + test('moves only the two panes beside a dragged divider without remounting them', async ({ + page, + layout, + }) => { + const { verticalDividers, dragDivider, waitForPaneWidth, openDualPanes } = + createResizeHelpers(page, layout); + const [left, right] = await openDualPanes(); + const canvases = await page.locator('canvas').count(); + await layout.markCanvases(); + + await dragDivider(verticalDividers.first(), 120); + await waitForPaneWidth(0, left.width + 120); + const [nextLeft, nextRight] = [ + await layout.paneBounds(0), + await layout.paneBounds(1), + ]; + expect(nextLeft.left).toBe(left.left); + expect(nextRight.width).toBeCloseTo(right.width - 120, 0); + expect(nextRight.right).toBeCloseTo(right.right, 0); + await expect(page.locator('canvas')).toHaveCount(canvases); + await expect(layout.keptCanvases).toHaveCount(2); + }); + + test('stops a divider where a pane reaches its minimum width, keeping its controls inside', async ({ + page, + layout, + }) => { + const { narrowFirstPane } = createResizeHelpers(page, layout); + await narrowFirstPane(); + + const pane = layout.panes.first(); + const lines = pane + .locator('.annotation-cell', { has: page.locator('.slice-label') }) + .locator(':scope > *'); + await expect(lines.first()).toBeVisible(); + const fit = async () => { + const bounds = await layout.bounds(pane); + const controls = await layout.bounds(pane.locator('.view-controls')); + const textRights = await Promise.all( + (await lines.all()).map( + async (line) => (await layout.bounds(line)).right + ) + ); + return { + controlsInside: + controls.left >= bounds.left && controls.right <= bounds.right, + textClear: textRights.every((right) => right <= controls.left), + }; + }; + await expect.poll(fit).toEqual({ controlsInside: true, textClear: true }); + }); + + test('moves the view type into View actions while a pane is narrow', async ({ + page, + utils, + layout, + }) => { + const { narrowFirstPane } = createResizeHelpers(page, layout); + await narrowFirstPane(); + await expect(layout.panes.nth(0).locator('.view-type-select')).toHaveCount( + 0 + ); + await expect( + layout.panes.nth(1).locator('.view-type-select') + ).toBeAttached(); + + await layout.viewAction(0, 'Coronal'); + await layout.openViewActions(0); + await expect(utils.overlayOption('Coronal')).toHaveClass( + /\bv-list-item--active\b/ + ); + + await layout.expectCanvasPerPane(); + await layout.markCanvases(); + await layout.viewAction(0, 'Coronal'); + await layout.openViewActions(0); + await expect(utils.overlayOption('Coronal')).toHaveClass( + /\bv-list-item--active\b/ + ); + await expect(layout.keptCanvases).toHaveCount(2); + }); + + test('shows overlay text in full while the pane has room for it', async ({ + page, + layout, + }) => { + const { verticalDividers, dragDivider, waitForPaneWidth, openDual } = + createResizeHelpers(page, layout); + await openDual(); + const left = await layout.paneBounds(0); + const dx = Math.round(400 - left.width); + await dragDivider(verticalDividers.first(), dx); + await waitForPaneWidth(0, left.width + dx); + const pane = layout.panes.first(); + await expect(pane).toContainText('W/L:'); + + const truncated = () => + pane + .locator('.annotation-cell, .annotation-cell > div') + .evaluateAll((cells) => + cells + .filter((cell) => cell.scrollWidth > cell.clientWidth) + .map((cell) => cell.textContent?.trim()) + ); + await expect.poll(truncated).toEqual([]); + }); + + test('ignores secondary buttons and reverts a drag on Escape', async ({ + page, + layout, + }) => { + const { verticalDividers, waitForPaneWidth, openDual } = + createResizeHelpers(page, layout); + await openDual(); + const left = await layout.paneBounds(0); + const from = center(await layout.bounds(verticalDividers.first())); + const to = { x: from.x + 100, y: from.y }; + + await layout.drag(from, to, { button: 'right' }); + await page.keyboard.press('Escape'); + expect((await layout.paneBounds(0)).width).toBe(left.width); + + await layout.drag(from, to, { hold: true }); + await waitForPaneWidth(0, left.width + 100); + await page.keyboard.press('Escape'); + await waitForPaneWidth(0, left.width); + await page.mouse.up(); + expect((await layout.paneBounds(0)).width).toBe(left.width); + }); + + test('moves the Four Up cross as one', async ({ + page, + volview, + utils, + layout, + }) => { + const { verticalDividers, dragDivider, waitForPaneWidth } = + createResizeHelpers(page, layout); + const image = utils.writeMetaImage('view-resizing-four-up.mha'); + await volview.open(`?urls=[tmp/${image}]`); + await volview.waitForViews(); + await layout.waitForPaneCount(4); + await layout.expectCanvasPerPane(); + await expect(verticalDividers).toHaveCount(2); + const upper = await layout.paneBounds(0); + + await dragDivider(verticalDividers.first(), -150); + await waitForPaneWidth(0, upper.width - 150); + await waitForPaneWidth(2, upper.width - 150); + const [top, bottom] = [ + await layout.bounds(verticalDividers.nth(0)), + await layout.bounds(verticalDividers.nth(1)), + ]; + expect(top.left).toBe(bottom.left); + expect(top.bottom).toBe(bottom.top); + }); + + test('keeps resized panes in place through split, close and double-click reset', async ({ + page, + layout, + }) => { + const { verticalDividers, dragDivider, waitForPaneWidth, openDualPanes } = + createResizeHelpers(page, layout); + const [left, right] = await openDualPanes(); + await dragDivider(verticalDividers.first(), -100); + await waitForPaneWidth(0, left.width - 100); + const resized = await layout.paneBounds(1); + + await layout.viewAction(1, 'Split side by side'); + await layout.waitForPaneCount(3); + expect((await layout.paneBounds(0)).width).toBeCloseTo(left.width - 100, 0); + expect((await layout.paneBounds(1)).width).toBeCloseTo( + resized.width / 2, + 0 + ); + expect((await layout.paneBounds(2)).right).toBeCloseTo(resized.right, 0); + + await layout.viewAction(2, 'Close view'); + await layout.waitForPaneCount(2); + await waitForPaneWidth(1, resized.width); + expect((await layout.paneBounds(0)).width).toBeCloseTo(left.width - 100, 0); + + await verticalDividers.first().dblclick(); + await waitForPaneWidth(0, left.width); + expect((await layout.paneBounds(1)).width).toBeCloseTo(right.width, 0); + await expect(layout.panes).toHaveCount(2); + }); + + test('hides dividers while a view is maximized and restores the sizes after', async ({ + page, + layout, + }) => { + const { + dividers, + verticalDividers, + dragDivider, + waitForPaneWidth, + openDual, + } = createResizeHelpers(page, layout); + await openDual(); + const left = await layout.paneBounds(0); + await dragDivider(verticalDividers.first(), 80); + await waitForPaneWidth(0, left.width + 80); + const resized = [await layout.paneBounds(0), await layout.paneBounds(1)]; + + await layout.panes + .nth(1) + .locator('[data-testid~="vtk-view"] .view') + .dblclick(); + await layout.waitForPaneCount(1); + await expect(dividers).toHaveCount(0); + + await layout.panes + .first() + .locator('[data-testid~="vtk-view"] .view') + .dblclick(); + await layout.waitForPaneCount(2); + await expect(dividers).toHaveCount(1); + expect(await layout.paneBounds(0)).toEqual(resized[0]); + expect(await layout.paneBounds(1)).toEqual(resized[1]); + }); + + test('restores resized panes from a saved session', async ({ + page, + layout, + }) => { + const { verticalDividers, dragDivider, waitForPaneWidth, openDual } = + createResizeHelpers(page, layout); + await openDual(); + const left = await layout.paneBounds(0); + await dragDivider(verticalDividers.first(), -90); + await waitForPaneWidth(0, left.width - 90); + const resized = [await layout.paneBounds(0), await layout.paneBounds(1)]; + + await layout.saveAndReopen(2); + await waitForPaneWidth(0, resized[0].width); + expect((await layout.paneBounds(1)).width).toBeCloseTo(resized[1].width, 0); + }); +}); diff --git a/tests/specs/view-splitting.e2e.ts b/tests/specs/view-splitting.e2e.ts new file mode 100644 index 000000000..fe7dc9a91 --- /dev/null +++ b/tests/specs/view-splitting.e2e.ts @@ -0,0 +1,471 @@ +import type { Page } from '@playwright/test'; +import { test, expect } from '../fixtures'; +import type { VolViewPage } from '../pageobjects/volview.page'; +import type { Utils } from './utils'; +import { center, type ViewLayoutUtils } from './viewLayoutTestUtils'; + +const CANVASES_ONLY = + '.grid-item * { visibility: hidden !important; } .grid-item canvas { visibility: visible !important; }'; + +const near = (a: number, b: number) => Math.abs(a - b) <= 2; + +const createSplitHelpers = ({ + page, + volview, + utils, + layout, +}: { + page: Page; + volview: VolViewPage; + utils: Utils; + layout: ViewLayoutUtils; +}) => { + const { panes } = layout; + + // Rendered image width in each pane, with overlays hidden. + const imageWidths = async (fileName: string) => { + const style = await page.addStyleTag({ content: CANVASES_ONLY }); + try { + const views = await utils.captureViewPixels( + '.grid-item canvas', + 2, + fileName + ); + return views.map(({ width, data }) => { + const height = data.length / 4 / width; + const columns = Array.from({ length: width }, (_, x) => + Array.from({ length: height }, (__, y) => (y * width + x) * 4).some( + (offset) => + Math.max(data[offset], data[offset + 1], data[offset + 2]) > 10 + ) + ); + return columns.lastIndexOf(true) - columns.indexOf(true) + 1; + }); + } finally { + await style.evaluate((element) => (element as Element).remove()); + } + }; + + const openLayoutFixture = () => + layout.openLayoutFixture( + 'view-layouts', + { + Quad: [ + ['axial', 'coronal'], + ['sagittal', 'volume'], + ], + Single: [['axial']], + }, + 4 + ); + + const openSplitFixture = () => + layout.openLayoutFixture( + 'view-splitting', + { Dual: [['axial', 'axial']] }, + 2 + ); + + const openLoneView = async () => { + await openSplitFixture(); + await layout.viewAction(1, 'Close view'); + await layout.waitForPaneCount(1); + }; + + const paneOverlay = async (index: number) => { + const text = (await panes.nth(index).textContent()) ?? ''; + return [ + text.match(/Slice:\s*\d+\/\d+/)?.[0], + text.match(/W\/L:\s*\S+\s*\/\s*\S+/)?.[0], + ].join(' '); + }; + + const pickLayout = async (name: string, paneCount: number) => { + await volview.openLayoutMenu(2); + await volview.selectLayoutOption(name); + await volview.closeMenu(volview.layoutButton); + await layout.waitForPaneCount(paneCount); + await layout.expectCanvasPerPane(); + }; + + const dragFromPaneCenter = async (index: number, dx: number, dy: number) => { + const from = center(await layout.paneBounds(index)); + await layout.drag(from, { x: from.x + dx, y: from.y + dy }); + }; + + const changeSlice = async (index: number) => { + const before = await paneOverlay(index); + await panes.nth(index).locator('canvas').click(); + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('ArrowDown'); + await expect.poll(() => paneOverlay(index)).not.toBe(before); + }; + + const selectViewType = async (index: number, name: string) => { + await panes.nth(index).locator('.view-type-select .v-field').click(); + await utils.overlayOption(name).click(); + await expect( + panes.nth(index).locator('.v-select__selection-text') + ).toHaveText(name); + }; + + return { + imageWidths, + openLayoutFixture, + openSplitFixture, + openLoneView, + paneOverlay, + pickLayout, + dragFromPaneCenter, + changeSlice, + selectViewType, + }; +}; + +test.describe('Splitting individual views', () => { + test('retains existing renderers and image settings through nested splits and closes', async ({ + page, + volview, + utils, + layout, + }) => { + const { openSplitFixture } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openSplitFixture(); + const overview = await layout.paneBounds(0); + await layout.markCanvases(); + const sourceSlice = await layout.panes + .nth(1) + .locator('.slice-label') + .innerText(); + await layout.viewAction(1, 'Split top and bottom'); + await layout.waitForPaneCount(3); + expect(await layout.paneBounds(0)).toEqual(overview); + await expect(layout.panes.nth(2).locator('.slice-label')).toHaveText( + sourceSlice + ); + await expect(layout.keptCanvases).toHaveCount(2); + + await layout.viewAction(2, 'Split side by side'); + await layout.waitForPaneCount(4); + expect(await layout.paneBounds(0)).toEqual(overview); + await expect(layout.keptCanvases).toHaveCount(2); + + await layout.viewAction(2, 'Close view'); + await layout.waitForPaneCount(3); + expect(await layout.paneBounds(0)).toEqual(overview); + await expect(layout.keptCanvases).toHaveCount(2); + await expect(layout.panes.nth(2).locator('.slice-label')).toHaveText( + sourceSlice + ); + + for (let cycle = 0; cycle < 3; cycle++) { + await layout.viewAction( + 0, + cycle % 2 ? 'Split top and bottom' : 'Split side by side' + ); + await layout.waitForPaneCount(4); + await layout.viewAction(1, 'Close view'); + await layout.waitForPaneCount(3); + } + await expect(layout.keptCanvases).toHaveCount(2); + }); + + test('preserves manually adjusted zoom when the split renderer mounts and resizes', async ({ + page, + volview, + utils, + layout, + }) => { + const { imageWidths, openSplitFixture, dragFromPaneCenter } = + createSplitHelpers({ page, volview, utils, layout }); + await openSplitFixture(); + await volview.selectTool('mdi-magnify-plus-outline'); + await dragFromPaneCenter(1, 0, 60); + await expect + .poll(async () => { + const [fitted, zoomed] = await imageWidths('zoom-adjusted.png'); + return zoomed < fitted * 0.9; + }) + .toBe(true); + + // The unzoomed pane, split alike, shows what refitting would draw. + await layout.viewAction(1, 'Split top and bottom'); + await layout.waitForPaneCount(3); + await layout.viewAction(0, 'Split top and bottom'); + await layout.waitForPaneCount(4); + await expect + .poll( + async () => { + const [fitted, fittedCopy, source, split] = + await imageWidths('zoom-split.png'); + return ( + near(fitted, fittedCopy) && + near(source, split) && + source < fitted * 0.9 + ); + }, + { message: 'Expected both split panes to keep the adjusted zoom' } + ) + .toBe(true); + }); + + test('keeps narrow-pane controls inside the view and guards splits while maximized', async ({ + page, + volview, + utils, + layout, + }) => { + const { openSplitFixture } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openSplitFixture(); + await layout.viewAction(1, 'Split side by side'); + await layout.waitForPaneCount(3); + + const controlsFit = async () => { + for (const pane of await layout.panes.all()) { + const bounds = await layout.bounds(pane); + const controls = await layout.bounds(pane.locator('.view-controls')); + if ( + controls.left < bounds.left || + controls.right > bounds.right || + controls.top < bounds.top || + controls.bottom > bounds.bottom + ) + return false; + } + return true; + }; + await expect + .poll(controlsFit, { + message: 'Expected every pane to hold its controls', + }) + .toBe(true); + + const checkGuard = async (reason: string, topBottomDisabled: boolean) => { + await layout.expectMenuItemDisabled('Split side by side'); + await layout.expectMenuItemReason('Split side by side', reason); + await layout.expectMenuItemDisabled( + 'Split top and bottom', + topBottomDisabled + ); + }; + + await layout.openViewActions(2); + await checkGuard('This view is too narrow to split side by side', false); + await page.keyboard.press('Escape'); + await layout.panes + .nth(2) + .locator('[data-testid~="vtk-view"] .view') + .dblclick(); + await layout.waitForPaneCount(1); + await layout.openViewActions(0); + await checkGuard('Restore the view to split it', true); + }); + + test('gives either closed half of a split back to the other half', async ({ + page, + volview, + utils, + layout, + }) => { + const { openSplitFixture } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openSplitFixture(); + const before = [await layout.paneBounds(0), await layout.paneBounds(1)]; + for (const closed of [1, 2]) { + await layout.viewAction(1, 'Split side by side'); + await layout.waitForPaneCount(3); + await layout.viewAction(closed, 'Close view'); + await layout.waitForPaneCount(2); + expect([await layout.paneBounds(0), await layout.paneBounds(1)]).toEqual( + before + ); + } + }); + + test('keeps Close view visible and disabled when only one view remains', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLoneView } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openLoneView(); + await layout.openViewActions(0); + await layout.expectMenuItemDisabled('Close view'); + await layout.expectMenuItemReason( + 'Close view', + 'This is the only open view' + ); + }); + + test('keeps a lone view splittable after it is double-clicked', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLoneView } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openLoneView(); + await layout.panes + .first() + .locator('[data-testid~="vtk-view"] .view') + .dblclick(); + await layout.openViewActions(0); + await layout.expectMenuItemDisabled('Split side by side', false); + await layout.expectMenuItemDisabled('Maximize view'); + }); + + test('maximizes and restores a view from its view actions', async ({ + page, + volview, + utils, + layout, + }) => { + const { openSplitFixture } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openSplitFixture(); + await layout.viewAction(1, 'Maximize view'); + await layout.waitForPaneCount(1); + await layout.viewAction(0, 'Restore view'); + await layout.waitForPaneCount(2); + }); + + test('starts a picked named layout over with fresh views of the image', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLayoutFixture, changeSlice, paneOverlay, pickLayout } = + createSplitHelpers({ page, volview, utils, layout }); + await openLayoutFixture(); + await changeSlice(1); + const coronal = await paneOverlay(1); + await layout.viewAction(0, 'Close view'); + await layout.waitForPaneCount(3); + await layout.markCanvases(); + + await pickLayout('Quad', 4); + await expect(layout.typeLabels).toHaveText([ + 'Axial', + 'Coronal', + 'Sagittal', + 'Volume', + ]); + await expect(layout.keptCanvases).toHaveCount(0); + await expect.poll(() => paneOverlay(1)).toMatch(/Slice:/); + expect(await paneOverlay(1)).not.toBe(coronal); + }); + + test('renders one canvas per pane through split, close and layout cycles', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLayoutFixture, pickLayout } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openLayoutFixture(); + const canvases = page.locator('canvas'); + const outsidePanes = (await canvases.count()) - 4; + for (let cycle = 0; cycle < 3; cycle++) { + await layout.viewAction(0, 'Split side by side'); + await layout.waitForPaneCount(5); + await layout.expectCanvasPerPane(); + await pickLayout('Single', 1); + await pickLayout('Quad', 4); + await layout.viewAction(1, 'Close view'); + await layout.waitForPaneCount(3); + await layout.expectCanvasPerPane(); + await pickLayout('Quad', 4); + await expect(canvases).toHaveCount(outsidePanes + 4); + } + }); + + test('changes a split pane view type without touching its neighbors', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLayoutFixture, changeSlice, paneOverlay, selectViewType } = + createSplitHelpers({ page, volview, utils, layout }); + await openLayoutFixture(); + await layout.viewAction(0, 'Split side by side'); + await layout.waitForPaneCount(5); + await changeSlice(0); + const neighbors = [0, 2, 3]; + const before = await Promise.all(neighbors.map(paneOverlay)); + await layout.markCanvases(); + + await selectViewType(1, 'Sagittal'); + await layout.expectCanvasPerPane(); + await expect(layout.typeLabels).toHaveText([ + 'Axial', + 'Sagittal', + 'Coronal', + 'Sagittal', + 'Volume', + ]); + expect(await Promise.all(neighbors.map(paneOverlay))).toEqual(before); + await expect(layout.keptCanvases).toHaveCount(4); + }); + + test('restores split panes from a saved session', async ({ + page, + volview, + utils, + layout, + }) => { + const { openLayoutFixture, changeSlice, paneOverlay } = createSplitHelpers({ + page, + volview, + utils, + layout, + }); + await openLayoutFixture(); + await layout.viewAction(1, 'Split top and bottom'); + await layout.waitForPaneCount(5); + await changeSlice(2); + const types = await layout.paneTypes(); + const overlays = await Promise.all([0, 1, 2].map(paneOverlay)); + + await layout.saveAndReopen(5); + await expect(layout.typeLabels).toHaveText(types); + await expect + .poll(() => Promise.all([0, 1, 2].map(paneOverlay))) + .toEqual(overlays); + }); +}); diff --git a/tests/specs/viewLayoutTestUtils.ts b/tests/specs/viewLayoutTestUtils.ts new file mode 100644 index 000000000..773ada925 --- /dev/null +++ b/tests/specs/viewLayoutTestUtils.ts @@ -0,0 +1,144 @@ +import { expect, type Locator, type Page } from '@playwright/test'; +import { createVolViewPage } from '../pageobjects/volview.page'; +import type { Scratch } from '../scratch'; +import { createUtils } from './utils'; + +type Point = { x: number; y: number }; +type Rect = { left: number; top: number; width: number; height: number }; + +const DISABLED_ITEM = /\bv-list-item--disabled\b/; + +export const center = ({ left, top, width, height }: Rect) => ({ + x: Math.round(left + width / 2), + y: Math.round(top + height / 2), +}); + +export const createViewLayoutUtils = (page: Page, scratch: Scratch) => { + const volview = createVolViewPage(page, scratch); + const utils = createUtils(page, scratch); + const panes = page.locator('.grid-item'); + const typeLabels = panes.locator('.v-select__selection-text'); + const keptCanvases = page.locator('.grid-item canvas[data-kept]'); + + const waitForPaneCount = (count: number) => expect(panes).toHaveCount(count); + + const bounds = async (locator: Locator) => { + const box = await locator.boundingBox(); + if (!box) throw new Error('Expected the element to be on screen'); + return { + left: box.x, + top: box.y, + right: box.x + box.width, + bottom: box.y + box.height, + width: box.width, + height: box.height, + }; + }; + + const paneBounds = (index: number) => bounds(panes.nth(index)); + + const paneTypes = async () => + (await typeLabels.allTextContents()).map((text) => text.trim()); + + /** Presses at `from` and moves to `to`; `hold` leaves the button down. */ + const drag = async ( + from: Point, + to: Point, + { + button = 'left', + hold = false, + }: { button?: 'left' | 'right'; hold?: boolean } = {} + ) => { + await page.mouse.move(from.x, from.y); + await page.mouse.down({ button }); + await page.mouse.move(to.x, to.y); + if (!hold) await page.mouse.up({ button }); + }; + + const openViewActions = (index: number) => + volview.openMenu( + panes.nth(index).locator('button[aria-label="View actions"]') + ); + + const viewAction = async (index: number, title: string) => { + await openViewActions(index); + await utils.overlayOption(title).click(); + }; + + const expectMenuItemDisabled = async (title: string, disabled = true) => { + const item = utils.overlayOption(title); + await expect(item).toBeVisible(); + if (disabled) await expect(item).toHaveClass(DISABLED_ITEM); + else await expect(item).not.toHaveClass(DISABLED_ITEM); + }; + + /** The reason a disabled menu item's tooltip gives on hover. */ + const expectMenuItemReason = async (title: string, reason: string) => { + // A disabled item takes no pointer events, so hover its wrapper. + await utils.moveToElement(utils.overlayOption(title).locator('..')); + await expect( + page.locator('.v-tooltip.v-overlay--active .v-overlay__content') + ).toHaveText(reason); + }; + + const expectCanvasPerPane = () => + expect + .poll( + () => + panes.evaluateAll((items) => + items.every((pane) => pane.querySelectorAll('canvas').length === 1) + ), + { message: 'Expected exactly one rendered canvas in every pane' } + ) + .toBe(true); + + /** Tags the current canvases so `keptCanvases` finds the ones not remounted. */ + const markCanvases = () => + page.locator('.grid-item canvas').evaluateAll((canvases) => + canvases.forEach((canvas) => { + (canvas as HTMLElement).dataset.kept = 'true'; + }) + ); + + const openLayoutFixture = async ( + name: string, + layouts: Record, + paneCount: number + ) => { + const image = utils.writeMetaImage(`${name}.mha`); + await utils.writeManifestToFile({ layouts }, `${name}.json`); + await volview.open(`?urls=[tmp/${image},tmp/${name}.json]`); + await volview.waitForViews(); + await waitForPaneCount(paneCount); + await expectCanvasPerPane(); + }; + + const saveAndReopen = async (paneCount: number) => { + const session = await volview.saveSession(); + await volview.open(`?urls=[tmp/${session}]`); + await volview.waitForViews(); + await waitForPaneCount(paneCount); + await expectCanvasPerPane(); + }; + + return { + panes, + typeLabels, + keptCanvases, + waitForPaneCount, + bounds, + paneBounds, + paneTypes, + drag, + openViewActions, + viewAction, + expectMenuItemDisabled, + expectMenuItemReason, + expectCanvasPerPane, + markCanvases, + openLayoutFixture, + saveAndReopen, + }; +}; + +export type ViewLayoutUtils = ReturnType;