@@ -202,7 +202,7 @@ watch(
:close-on-content-click="false"
location="top end"
:offset="8"
- :max-width="320"
+ :max-width="450"
>
();
const { geometry, measurement, micronsPerVoxel, threshold, appearance } =
toRefs(props);
const view = inject(VtkViewContext);
if (!view) throw new Error('No VtkView');
-const thinRegions = useEnFaceLabelmaps(
+const plane = useEnFaceLabelmaps(
geometry,
measurement,
threshold,
@@ -30,7 +30,7 @@ const thinRegions = useEnFaceLabelmaps(
);
useLabelmapRepresentation(
view,
- computed(() => (appearance.value ? thinRegions.value : null)),
+ computed(() => (appearance.value ? plane.value : null)),
appearance,
2
);
diff --git a/src/enface/__tests__/controls.spec.ts b/src/enface/__tests__/controls.spec.ts
index e96663ded..46b143db6 100644
--- a/src/enface/__tests__/controls.spec.ts
+++ b/src/enface/__tests__/controls.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { enableAutoUnmount, mount } from '@vue/test-utils';
-import { computed, defineComponent, h, nextTick, reactive, ref } from 'vue';
+import { defineComponent, h, nextTick, reactive, ref } from 'vue';
import { createPinia, setActivePinia } from 'pinia';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
@@ -9,16 +9,17 @@ import { useImageCacheStore } from '@/src/store/image-cache';
import { useSegmentationStore } from '@/src/segmentation/store';
import { useSegmentStore } from '@/src/segmentation/segments';
import { useEnFaceInput } from '@/src/enface/useEnFaceInput';
-import { useEnFaceOccupiedDepth } from '@/src/enface/useEnFaceOccupiedDepth';
+import { useThinCalibration } from '@/src/enface/useThinCalibration';
import { createVuetify } from 'vuetify';
import EnFaceControls from '@/src/enface/EnFaceControls.vue';
import {
defaultEnFaceViewConfig,
+ defaultSegmentProjection,
useEnFaceViewStore,
type EnFaceViewConfig,
- type ThicknessControlState,
+ type SegmentControlState,
+ type SegmentProjection,
} from '@/src/enface/store';
-import ReasonedAction from '@/src/components/ReasonedAction.vue';
beforeEach(() => {
vi.stubGlobal('visualViewport', null);
@@ -26,8 +27,21 @@ beforeEach(() => {
afterEach(() => vi.unstubAllGlobals());
enableAutoUnmount(afterEach);
-function mountControls(overrides = {}) {
- const settings = reactive({ ...defaultEnFaceViewConfig(), ...overrides });
+const thin = { visible: true, thresholdMicrons: 100 };
+const names = (count: number) =>
+ Array.from({ length: count }, (_, index) => ({
+ id: `segment-${index}`,
+ title: `Segment ${index}`,
+ listHidden: false,
+ thresholdMaximum: 200,
+ }));
+
+function mountControls(overrides: Partial = {}) {
+ const settings = reactive({
+ ...defaultEnFaceViewConfig(),
+ segmentProjections: { retina: { ...thin } },
+ ...overrides,
+ });
return mount(EnFaceControls, {
attachTo: document.body,
props: {
@@ -39,18 +53,27 @@ function mountControls(overrides = {}) {
],
onPatch: (patch: Partial) =>
Object.assign(settings, patch),
+ onSegment: (id: string, patch: Partial) => {
+ settings.segmentProjections[id] = {
+ ...defaultSegmentProjection(),
+ ...settings.segmentProjections[id],
+ ...patch,
+ };
+ },
depthMaximum: 221,
projectionReason: null,
- thickness: {
- thresholdMaximum: 200,
- segmentationReason: null,
- highlightReason: null,
- thicknessReason: null,
+ segmentControls: {
segments: [
- { value: 'retina', title: 'Retinal layer', color: '#ff0000' },
+ {
+ id: 'retina',
+ title: 'Retinal layer',
+ color: '#ff0000',
+ listHidden: false,
+ thresholdMaximum: 200,
+ },
],
- segmentId: 'retina',
- highlightThin: true,
+ segmentationReason: null,
+ thinReason: null,
},
},
global: { plugins: [createVuetify()] },
@@ -61,55 +84,44 @@ function lastPatch(wrapper: ReturnType) {
return wrapper.emitted('patch')?.at(-1)?.[0];
}
-function setThickness(
+function lastSegmentPatch(wrapper: ReturnType) {
+ return wrapper.emitted('segment')?.at(-1);
+}
+
+function setSegmentControls(
wrapper: ReturnType,
- thickness: Partial
+ controls: Partial
) {
return wrapper.setProps({
- thickness: { ...wrapper.props('thickness'), ...thickness },
+ segmentControls: { ...wrapper.props('segmentControls'), ...controls },
});
}
+const rowNames = (wrapper: ReturnType) =>
+ wrapper
+ .findAll('[data-testid="enface-segment-row"]')
+ .map((row) => row.attributes('data-segment-name'));
+
describe('En face rendering controls', () => {
it('starts both sections expanded and collapses them independently', async () => {
const wrapper = mountControls();
- for (const section of ['projection', 'thickness']) {
- expect(
- wrapper
- .get(`[data-testid="enface-${section}-toggle"]`)
- .attributes('aria-expanded')
- ).toBe('true');
- }
- expect(
- wrapper.find('[data-testid="enface-segmentation-segment"] input').exists()
- ).toBe(true);
- expect(
- wrapper
- .find('[data-testid="enface-thickness-threshold-input"] input')
- .exists()
- ).toBe(true);
+ const projection = wrapper.get('[data-testid="enface-projection-toggle"]');
+ const segments = wrapper.get('[data-testid="enface-segments-toggle"]');
+ expect(projection.attributes('aria-expanded')).toBe('true');
+ expect(segments.attributes('aria-expanded')).toBe('true');
+ expect(wrapper.find('[data-testid="enface-segment-row"]').exists()).toBe(
+ true
+ );
expect(wrapper.find('[data-testid="enface-window-width"]').exists()).toBe(
false
);
- expect(
- wrapper.get('[data-testid="enface-projection-method"] input').element
- ).toBeDefined();
- expect(
- wrapper
- .get('[data-testid="enface-thin-highlight"]')
- .element.compareDocumentPosition(
- wrapper.get('[data-testid="enface-segmentation-segment"]').element
- ) & Node.DOCUMENT_POSITION_FOLLOWING
- ).toBeTruthy();
- const projection = wrapper.get('[data-testid="enface-projection-toggle"]');
- const thickness = wrapper.get('[data-testid="enface-thickness-toggle"]');
await projection.trigger('click');
expect(projection.attributes('aria-expanded')).toBe('false');
- expect(thickness.attributes('aria-expanded')).toBe('true');
- await thickness.trigger('click');
+ expect(segments.attributes('aria-expanded')).toBe('true');
+ await segments.trigger('click');
await projection.trigger('click');
expect(projection.attributes('aria-expanded')).toBe('true');
- expect(thickness.attributes('aria-expanded')).toBe('false');
+ expect(segments.attributes('aria-expanded')).toBe('false');
});
it('preserves saved projection settings when collapsed and reopened', async () => {
@@ -147,176 +159,310 @@ describe('En face rendering controls', () => {
expect(wrapper.emitted('patch')).toBeUndefined();
});
- it('shows segment colors in the selected segment and its dropdown options', async () => {
- const wrapper = mountControls();
- const swatch = () => wrapper.get('[data-testid="enface-segment-color"]');
- expect(swatch().attributes('style')).toContain('background-color: #ff0000');
- await wrapper.setProps({
- thickness: {
- ...wrapper.props('thickness'),
- segments: [
- { value: 'retina', title: 'Retinal layer', color: '#ff0000' },
- { value: 'other-layer', title: 'Other layer', color: '#00ff00' },
- ],
- segmentId: 'other-layer',
- },
+ it('lists every segment hidden by default and shows each with its eye', async () => {
+ const wrapper = mountControls({ segmentProjections: {} });
+ await setSegmentControls(wrapper, {
+ segments: [
+ {
+ id: 'retina',
+ title: 'Retinal layer',
+ color: '#ff0000',
+ listHidden: false,
+ thresholdMaximum: 200,
+ },
+ {
+ id: 'other',
+ title: 'Other layer',
+ listHidden: false,
+ thresholdMaximum: 200,
+ },
+ ],
});
- expect(swatch().attributes('style')).toContain('background-color: #00ff00');
+ expect(rowNames(wrapper)).toEqual(['Retinal layer', 'Other layer']);
expect(
- wrapper.get('[data-testid="enface-segmentation-segment"]').text()
- ).toContain('Other layer');
- await wrapper
- .get('[data-testid="enface-segmentation-segment"] input')
- .trigger('keydown', { key: 'Enter' });
- await vi.waitFor(() => {
- const options = document.body.querySelectorAll('[role="option"]');
- expect(options).toHaveLength(2);
- for (const [index, [name, color]] of [
- ['Retinal layer', '#ff0000'],
- ['Other layer', '#00ff00'],
- ].entries()) {
- expect(options[index].textContent).toContain(name);
- expect(
- options[index]
- .querySelector('[data-testid="enface-segment-option-color"]')
- ?.getAttribute('style')
- ).toContain(`background-color: ${color}`);
- }
- });
- (
- document.body.querySelectorAll('[role="option"]')[0] as HTMLElement
- ).click();
- await nextTick();
- expect(lastPatch(wrapper)).toEqual({
- segmentId: 'retina',
- highlightThin: true,
- });
+ wrapper.get('[data-testid="enface-segment-color"]').attributes('style')
+ ).toContain('background-color: #ff0000');
+ const eyes = wrapper.findAll('[data-testid="enface-segment-visible"]');
+ expect(eyes.map((eye) => eye.attributes('aria-pressed'))).toEqual([
+ 'false',
+ 'false',
+ ]);
expect(
- wrapper
- .get('[data-testid="enface-thin-highlight"]')
- .find('.color-dot')
- .exists()
+ wrapper.find('[data-testid="enface-segment-threshold"]').exists()
).toBe(false);
+ await eyes[1].trigger('click');
+ expect(lastSegmentPatch(wrapper)).toEqual(['other', { visible: true }]);
+ expect(eyes[1].attributes('aria-pressed')).toBe('true');
+ expect(eyes[0].attributes('aria-pressed')).toBe('false');
+ const input = wrapper.get(
+ '[data-testid="enface-segment-threshold-input"] input'
+ );
+ expect(input.element.value).toBe('');
+ expect(input.attributes('placeholder')).toBe('Any');
+ await eyes[1].trigger('click');
+ expect(lastSegmentPatch(wrapper)).toEqual(['other', { visible: false }]);
expect(
- wrapper.get('[data-testid="enface-thin-highlight"]').text()
- ).toContain('Highlight thin regions');
- await setThickness(wrapper, { segments: [] });
- expect(wrapper.find('[data-testid="enface-segment-color"]').exists()).toBe(
- false
+ wrapper.find('[data-testid="enface-segment-threshold"]').exists()
+ ).toBe(false);
+ });
+
+ it('shows or hides every segment from the section header', async () => {
+ const wrapper = mountControls({
+ segmentProjections: { 'segment-1': { ...thin } },
+ });
+ await setSegmentControls(wrapper, { segments: names(3) });
+ const all = wrapper.get('[data-testid="enface-segments-visible"]');
+ expect(all.attributes('aria-label')).toBe('Show every segment');
+ await all.trigger('click');
+ const pressed = () =>
+ wrapper
+ .findAll('[data-testid="enface-segment-visible"]')
+ .map((eye) => eye.attributes('aria-pressed'));
+ expect(pressed()).toEqual(['true', 'true', 'true']);
+ expect(all.attributes('aria-label')).toBe('Hide every segment');
+ await all.trigger('click');
+ expect(pressed()).toEqual(['false', 'false', 'false']);
+ });
+
+ it('turns the thin filter on below the slider end and off at it', async () => {
+ const wrapper = mountControls({
+ segmentProjections: { retina: { visible: true, thresholdMicrons: null } },
+ });
+ const slider = wrapper.get(
+ '[data-testid="enface-segment-threshold"] [role="slider"]'
);
+ const input = wrapper.get(
+ '[data-testid="enface-segment-threshold-input"] input'
+ );
+ expect(slider.attributes('aria-valuenow')).toBe('200');
+ await slider.trigger('keydown', { key: 'Home' });
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: 0 },
+ ]);
+ expect(input.element.value).toBe('0');
+ await slider.trigger('keydown', { key: 'End' });
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: null },
+ ]);
+ expect(input.element.value).toBe('');
+ await input.setValue('42');
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: 42 },
+ ]);
+ await input.setValue('');
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: null },
+ ]);
});
- it('preserves a decimal micron threshold and ignores a cleared numeric entry', async () => {
+
+ it('keeps a separate threshold for each thin-highlighted segment', async () => {
+ const wrapper = mountControls({
+ segmentProjections: {
+ 'segment-0': { ...thin },
+ 'segment-1': { ...thin, thresholdMicrons: 40 },
+ },
+ });
+ await setSegmentControls(wrapper, { segments: names(2) });
+ const inputs = wrapper.findAll(
+ '[data-testid="enface-segment-threshold-input"] input'
+ );
+ expect(inputs.map((input) => input.element.value)).toEqual(['100', '40']);
+ await inputs[1].setValue('55.5');
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'segment-1',
+ { thresholdMicrons: 55.5 },
+ ]);
+ expect(inputs[0].element.value).toBe('100');
+ });
+
+ it('preserves a decimal micron threshold', async () => {
const wrapper = mountControls();
const input = wrapper.get(
- '[data-testid="enface-thickness-threshold-input"] input'
+ '[data-testid="enface-segment-threshold-input"] input'
);
await input.setValue('20.8');
- expect(lastPatch(wrapper)).toEqual({ thresholdMicrons: 20.8 });
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: 20.8 },
+ ]);
expect(
wrapper
- .get('[data-testid="enface-thickness-threshold"] [role="slider"]')
+ .get('[data-testid="enface-segment-threshold"] [role="slider"]')
.attributes('aria-valuenow')
).toBe('20.8');
- const previousCount = wrapper.emitted('patch')!.length;
- await input.setValue('');
- expect(wrapper.emitted('patch')).toHaveLength(previousCount);
});
it('keeps the threshold slider range fixed while preserving larger numeric thresholds', async () => {
const wrapper = mountControls();
const slider = wrapper.get(
- '[data-testid="enface-thickness-threshold"] [role="slider"]'
+ '[data-testid="enface-segment-threshold"] [role="slider"]'
+ );
+ const input = wrapper.get(
+ '[data-testid="enface-segment-threshold-input"] input'
);
expect(slider.attributes('aria-label')).toBe(
- 'Thickness threshold in micrometers'
+ 'Thickness threshold of Retinal layer in micrometers'
);
expect(slider.attributes('aria-valuemax')).toBe('200');
await slider.trigger('keydown', { key: 'ArrowRight' });
- expect(lastPatch(wrapper)).toEqual({ thresholdMicrons: 100.1 });
- expect(
- wrapper.get(
- '[data-testid="enface-thickness-threshold-input"] input'
- ).element.value
- ).toBe(slider.attributes('aria-valuenow'));
- for (const [key, expected] of [
- ['Home', 0],
- ['End', 200],
- ] as const) {
- await slider.trigger('keydown', { key });
- expect(lastPatch(wrapper)).toEqual({ thresholdMicrons: expected });
- }
- await wrapper
- .get(
- '[data-testid="enface-thickness-threshold-input"] input'
- )
- .setValue('750.25');
- expect(lastPatch(wrapper)).toEqual({ thresholdMicrons: 750.25 });
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: 100.1 },
+ ]);
+ expect(input.element.value).toBe(slider.attributes('aria-valuenow'));
+ await input.setValue('750.25');
expect(slider.attributes('aria-valuemax')).toBe('200');
expect(slider.attributes('aria-valuenow')).toBe('200');
- expect(
- wrapper.get(
- '[data-testid="enface-thickness-threshold-input"] input'
- ).element.value
- ).toBe('750.25');
- await setThickness(wrapper, { thresholdMaximum: 50 });
+ expect(input.element.value).toBe('750.25');
+ await setSegmentControls(wrapper, {
+ segments: [
+ {
+ id: 'retina',
+ title: 'Retinal layer',
+ listHidden: false,
+ thresholdMaximum: 50,
+ },
+ ],
+ });
expect(slider.attributes('aria-valuemax')).toBe('50');
expect(slider.attributes('aria-valuenow')).toBe('50');
- expect(
- wrapper.get(
- '[data-testid="enface-thickness-threshold-input"] input'
- ).element.value
- ).toBe('750.25');
+ expect(input.element.value).toBe('750.25');
});
- it('keeps thickness actions disabled when the selected axis has unusable spacing', async () => {
+ it('explains why thickness filtering is unavailable while the eye stays usable', async () => {
const wrapper = mountControls();
const reason = 'The selected image axis has unusable voxel spacing.';
- await setThickness(wrapper, {
- highlightReason: reason,
- thicknessReason: reason,
- });
+ await setSegmentControls(wrapper, { thinReason: reason });
+ expect(wrapper.get('[data-testid="enface-thin-reason"]').text()).toBe(
+ `Thickness filtering is unavailable. ${reason}`
+ );
expect(
wrapper
- .get('[data-testid="enface-segmentation-segment"] input')
+ .get('[data-testid="enface-segment-visible"]')
.attributes('disabled')
).toBeUndefined();
expect(
- wrapper
- .get('[data-testid="enface-thin-highlight"] input')
- .attributes('disabled')
- ).toBeDefined();
+ wrapper.find('[data-testid="enface-segment-threshold"]').exists()
+ ).toBe(false);
+ });
+
+ it('leaves segments hidden in the Annotations list out of en face eyes, keeping their settings', async () => {
+ const wrapper = mountControls();
+ const retina = {
+ id: 'retina',
+ title: 'Retinal layer',
+ color: '#ff0000',
+ thresholdMaximum: 200,
+ };
+ const other = { id: 'other', title: 'Other layer', thresholdMaximum: 200 };
+ const eye = (name: string) =>
+ wrapper.get(
+ `[data-segment-name="${name}"] [data-testid="enface-segment-visible"]`
+ );
+ const threshold = () =>
+ wrapper.find(
+ '[data-testid="enface-segment-threshold-input"] input'
+ );
+ const all = () => wrapper.get('[data-testid="enface-segments-visible"]');
+ await setSegmentControls(wrapper, {
+ segments: [
+ { ...retina, listHidden: true },
+ { ...other, listHidden: true },
+ ],
+ });
+ expect(eye('Retinal layer').attributes('disabled')).toBeDefined();
+ expect(eye('Retinal layer').attributes('aria-pressed')).toBe('false');
+ expect(eye('Retinal layer').find('.mdi-eye-off').exists()).toBe(true);
+ expect(threshold().exists()).toBe(false);
+ expect(all().attributes('disabled')).toBeDefined();
+
+ await setSegmentControls(wrapper, {
+ segments: [
+ { ...retina, listHidden: true },
+ { ...other, listHidden: false },
+ ],
+ });
+ expect(all().attributes('aria-label')).toBe('Show every segment');
+ await all().trigger('click');
+ expect(eye('Other layer').attributes('aria-pressed')).toBe('true');
+ expect(all().attributes('aria-label')).toBe('Hide every segment');
+ await all().trigger('click');
+ expect(eye('Other layer').attributes('aria-pressed')).toBe('false');
+
+ await setSegmentControls(wrapper, {
+ segments: [
+ { ...retina, listHidden: false },
+ { ...other, listHidden: false },
+ ],
+ });
+ expect(eye('Retinal layer').attributes('disabled')).toBeUndefined();
+ expect(eye('Retinal layer').attributes('aria-pressed')).toBe('true');
+ expect(threshold().element.value).toBe('100');
+ });
+
+ it('keeps the threshold field usable while the slider waits for a measurement', async () => {
+ const wrapper = mountControls();
+ await setSegmentControls(wrapper, {
+ segments: [
+ {
+ id: 'retina',
+ title: 'Retinal layer',
+ listHidden: false,
+ thresholdMaximum: null,
+ },
+ ],
+ });
const slider = wrapper.get(
- '[data-testid="enface-thickness-threshold"] [role="slider"]'
- );
- expect(slider.attributes('aria-label')).toBe(
- 'Thickness threshold in micrometers'
+ '[data-testid="enface-segment-threshold"] [role="slider"]'
);
expect(slider.attributes('tabindex')).toBe('-1');
- await slider.trigger('keydown', { key: 'ArrowRight' });
- expect(wrapper.emitted('patch')).toBeUndefined();
- const action = wrapper
- .findAllComponents(ReasonedAction)
- .find((candidate) =>
- candidate.find('[data-testid="enface-thin-highlight"]').exists()
- );
- expect(action?.props('reason')).toBe(reason);
+ await slider.trigger('keydown', { key: 'ArrowLeft' });
+ expect(wrapper.emitted('segment')).toBeUndefined();
+ await wrapper
+ .get('[data-testid="enface-segment-threshold-input"] input')
+ .setValue('42');
+ expect(lastSegmentPatch(wrapper)).toEqual([
+ 'retina',
+ { thresholdMicrons: 42 },
+ ]);
});
- it('explains occupied-mask thickness and its user threshold on keyboard focus', async () => {
+ it('keeps segment rows listed but disabled while the projection is unavailable', async () => {
const wrapper = mountControls();
- expect(
- wrapper.get('[data-testid="enface-segmentation-segment"]').text()
- ).toContain('Thickness segment');
- const help = wrapper.get(
- '[data-testid="enface-thickness-help"]'
+ const reason = 'The volume is still loading.';
+ await setSegmentControls(wrapper, { segmentationReason: reason });
+ expect(wrapper.get('[data-testid="enface-segments-reason"]').text()).toBe(
+ reason
);
- help.element.focus();
- expect(document.activeElement).toBe(help.element);
- await vi.waitFor(() => {
- expect(document.body.textContent).toContain(
- 'Thickness of the selected segment within the slab, along the projection axis.'
- );
+ expect(rowNames(wrapper)).toEqual(['Retinal layer']);
+ expect(
+ wrapper
+ .get('[data-testid="enface-segment-visible"]')
+ .attributes('disabled')
+ ).toBeDefined();
+ expect(
+ wrapper.find('[data-testid="enface-segment-threshold"]').exists()
+ ).toBe(false);
+ });
+
+ it('explains why no segments are listed', async () => {
+ const wrapper = mountControls();
+ const reason =
+ 'Load or create a segmentation mask associated with this volume.';
+ await setSegmentControls(wrapper, {
+ segments: [],
+ segmentationReason: reason,
});
+ expect(wrapper.get('[data-testid="enface-segments-reason"]').text()).toBe(
+ reason
+ );
+ expect(wrapper.find('[data-testid="enface-segment-row"]').exists()).toBe(
+ false
+ );
});
it('keeps slab help on its information button while leaving the range free of hover tooltips', async () => {
@@ -324,7 +470,7 @@ describe('En face rendering controls', () => {
await nextTick();
const range = wrapper.get('[data-testid="enface-slab-range"]');
expect(range.attributes('aria-describedby')).toBeUndefined();
- const help = range.get(
+ const help = wrapper.get(
'[data-testid="enface-slab-help"]'
);
expect(help.attributes('aria-label')).toBe('About slab range');
@@ -381,53 +527,6 @@ describe('En face rendering controls', () => {
expect(end.attributes('aria-valuenow')).toBe('181');
expect(range.text()).toContain('181');
});
- it('keeps unavailable thickness controls visible and exposes the reason through their wrapper', async () => {
- const wrapper = mountControls();
- const toggle = wrapper.get('[data-testid="enface-thin-highlight"] input');
- const segment = wrapper.get(
- '[data-testid="enface-segmentation-segment"] input'
- );
- await toggle.setValue(false);
- expect(segment.attributes('disabled')).toBeUndefined();
- const segmentAction = wrapper
- .findAllComponents(ReasonedAction)
- .find((action) =>
- action.find('[data-testid="enface-segmentation-segment"]').exists()
- );
- expect(segmentAction?.props('reason')).toBeUndefined();
- await setThickness(wrapper, {
- thicknessReason: 'The selected segment is hidden.',
- });
- expect(toggle.attributes('disabled')).toBeUndefined();
- await toggle.setValue(true);
- expect(segment.attributes('disabled')).toBeUndefined();
- const reason = 'Load an associated segmentation to measure thickness.';
- await setThickness(wrapper, {
- segments: [],
- segmentationReason: reason,
- highlightReason: reason,
- thicknessReason: reason,
- });
- expect(
- wrapper
- .get('[data-testid="enface-thin-highlight"] input')
- .attributes('disabled')
- ).toBeDefined();
- expect(
- wrapper
- .get(
- '[data-testid="enface-thickness-threshold-input"] input'
- )
- .attributes('disabled')
- ).toBeDefined();
- const thresholdAction = wrapper
- .findAllComponents(ReasonedAction)
- .find((action) =>
- action.find('[data-testid="enface-thickness-threshold-input"]').exists()
- );
- expect(thresholdAction?.props('reason')).toBe(reason);
- expect(thresholdAction?.attributes('tabindex')).toBe('0');
- });
});
function mountImageControls(spacing = 0.01) {
@@ -453,15 +552,17 @@ function mountImageControls(spacing = 0.01) {
voxels.materialize();
voxels.ensureContains([0, 1, 0, 1, 0, 1]);
voxels.apply(new Uint8Array(8).fill(1));
+ useEnFaceViewStore().configFor(
+ 'measurement-view',
+ imageId
+ ).segmentProjections[segmentId] = {
+ ...defaultSegmentProjection(),
+ visible: true,
+ };
const component = defineComponent({
setup() {
const input = useEnFaceInput('measurement-view');
- const thickness = useEnFaceOccupiedDepth('measurement-view', {
- source: input.source,
- slab: input.specification,
- geometry: input.geometry,
- blockedReason: computed(() => input.controls.value.projectionReason),
- });
+ const calibration = useThinCalibration(input.source, input.specification);
const enFaceStore = useEnFaceViewStore();
return () =>
h(EnFaceControls, {
@@ -470,7 +571,18 @@ function mountImageControls(spacing = 0.01) {
'measurement-view',
input.source.currentImageID.value
),
- thickness: thickness.controls.value,
+ segmentControls: {
+ segments: [
+ {
+ id: segmentId,
+ title: 'Retina',
+ listHidden: false,
+ thresholdMaximum: 1,
+ },
+ ],
+ segmentationReason: null,
+ thinReason: calibration.reason.value,
+ },
});
},
});
@@ -494,9 +606,9 @@ describe('thickness control geometry', () => {
try {
expect(
wrapper
- .get('[data-testid="enface-thin-highlight"] input')
- .attributes('disabled')
- ).toBeUndefined();
+ .find('[data-testid="enface-segment-threshold-input"]')
+ .exists()
+ ).toBe(true);
} finally {
wrapper.unmount();
dispose();
@@ -513,19 +625,12 @@ describe('thickness control geometry', () => {
await nextTick();
expect(
wrapper
- .get('[data-testid="enface-thin-highlight"] input')
- .attributes('disabled')
- ).toBeDefined();
- const action = wrapper
- .get('[data-testid="enface-thin-highlight"]')
- .element.closest('[tabindex="0"]');
- expect(action).not.toBeNull();
- action!.focus();
- await vi.waitFor(() => {
- expect(document.body.textContent).toContain(
- 'The projection axis has invalid voxel spacing'
- );
- });
+ .find('[data-testid="enface-segment-threshold-input"]')
+ .exists()
+ ).toBe(false);
+ expect(
+ wrapper.get('[data-testid="enface-thin-reason"]').text()
+ ).toContain('The projection axis has invalid voxel spacing');
} finally {
wrapper.unmount();
dispose();
diff --git a/src/enface/__tests__/inputCalibration.spec.ts b/src/enface/__tests__/inputCalibration.spec.ts
index 83d907b2a..9ab83cdae 100644
--- a/src/enface/__tests__/inputCalibration.spec.ts
+++ b/src/enface/__tests__/inputCalibration.spec.ts
@@ -1,14 +1,15 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createPinia, setActivePinia } from 'pinia';
-import { computed, defineComponent, h, markRaw, nextTick, ref } from 'vue';
+import { defineComponent, h, markRaw, nextTick, ref } from 'vue';
import { createVuetify } from 'vuetify';
import { Tags } from '@/src/core/dicomTags';
import { CurrentImageInjectionKey } from '@/src/composables/useCurrentImage';
import { untilLoaded } from '@/src/composables/untilLoaded';
import { useImageCacheStore } from '@/src/store/image-cache';
import { useEnFaceInput } from '@/src/enface/useEnFaceInput';
-import { useOccupiedDepthInput } from '@/src/enface/useOccupiedDepthInput';
+import { useThinCalibration } from '@/src/enface/useThinCalibration';
+import { useMaskDepthRequest } from '@/src/enface/useMaskDepthRequest';
import EnFaceControls from '@/src/enface/EnFaceControls.vue';
import { useEnFaceViewStore } from '@/src/enface/store';
import { useSegmentStore } from '@/src/segmentation/segments';
@@ -61,19 +62,25 @@ async function mountInput(id: string) {
};
segmentation.maskVoxels(mask.id).apply(new Uint8Array(8).fill(1));
const settings = useEnFaceViewStore().configFor('calibration', id);
- Object.assign(settings, { highlightThin: true, segmentId: segment });
+ settings.segmentProjections[segment] = {
+ visible: true,
+ thresholdMicrons: 100,
+ };
const host = defineComponent({
setup() {
const projection = useEnFaceInput('calibration');
- const input = useOccupiedDepthInput('calibration', {
- source: projection.source,
- slab: projection.specification,
- blockedReason: computed(
- () => projection.controls.value.projectionReason
- ),
- });
+ const calibration = useThinCalibration(
+ projection.source,
+ projection.specification
+ );
+ const depth = useMaskDepthRequest(
+ projection.source,
+ projection.specification,
+ mask.id
+ );
return () => {
- const request = input.request.value;
+ const reason = calibration.reason.value || depth.geometryReason.value;
+ const request = reason ? null : depth.request.value;
const result = request ? measureOccupiedDepth(request) : null;
return h('div', [
h(
@@ -82,22 +89,25 @@ async function mountInput(id: string) {
'data-measurable': Boolean(request),
'data-counts': result ? Array.from(result.counts).join(',') : '',
'data-depth': result
- ? result.maximumCount * input.micronsPerVoxel.value
+ ? result.maximumCount * calibration.micronsPerVoxel.value
: '',
},
- input.thicknessReason.value ?? 'Ready'
+ reason ?? 'Ready'
),
h(EnFaceControls, {
...projection.controls.value,
- settings: input.settings.value,
- thickness: {
- thresholdMaximum: 200,
- segmentationReason: input.segmentationReason.value,
- highlightReason: input.highlightReason.value,
- thicknessReason: input.thicknessReason.value,
- segments: input.segmentOptions.value,
- segmentId: input.segmentId.value,
- highlightThin: input.highlightThin.value,
+ settings,
+ segmentControls: {
+ segments: [
+ {
+ id: segment,
+ title: 'Layer',
+ listHidden: false,
+ thresholdMaximum: 200,
+ },
+ ],
+ segmentationReason: null,
+ thinReason: calibration.reason.value,
},
}),
]);
@@ -131,12 +141,14 @@ describe('occupied-depth input calibration', () => {
'false'
);
expect(wrapper.text()).toMatch(/no reliable declared voxel spacing/);
- for (const control of ['thin-highlight', 'thickness-threshold-input'])
- expect(
- wrapper
- .get(`[data-testid="enface-${control}"] input`)
- .attributes('disabled')
- ).toBeDefined();
+ expect(
+ wrapper.find('[data-testid="enface-thin-reason"]').exists()
+ ).toBe(true);
+ expect(
+ wrapper
+ .find('[data-testid="enface-segment-threshold-input"]')
+ .exists()
+ ).toBe(false);
} finally {
wrapper.unmount();
}
@@ -148,20 +160,16 @@ describe('occupied-depth input calibration', () => {
try {
expect(wrapper.get('output').attributes('data-measurable')).toBe('true');
expect(wrapper.get('output').attributes('data-depth')).toBe('20.8');
- const highlight = wrapper.get(
- '[data-testid="enface-thin-highlight"] input'
- );
- const threshold = wrapper.get(
- '[data-testid="enface-thickness-threshold-input"] input'
- );
- expect(highlight.attributes('disabled')).toBeUndefined();
- expect(threshold.attributes('disabled')).toBeUndefined();
+ const reason = '[data-testid="enface-thin-reason"]';
+ const threshold = '[data-testid="enface-segment-threshold-input"]';
+ expect(wrapper.find(reason).exists()).toBe(false);
+ expect(wrapper.find(threshold).exists()).toBe(true);
settings.axis = 0;
await nextTick();
expect(wrapper.get('output').attributes('data-measurable')).toBe('false');
expect(wrapper.text()).toMatch(/no reliable declared voxel spacing/);
- expect(highlight.attributes('disabled')).toBeDefined();
- expect(threshold.attributes('disabled')).toBeDefined();
+ expect(wrapper.find(reason).exists()).toBe(true);
+ expect(wrapper.find(threshold).exists()).toBe(false);
} finally {
wrapper.unmount();
}
diff --git a/src/enface/__tests__/restoreSelection.spec.ts b/src/enface/__tests__/restoreSelection.spec.ts
deleted file mode 100644
index 5a4eeb51a..000000000
--- a/src/enface/__tests__/restoreSelection.spec.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils';
-import { computed, defineComponent, h, nextTick, ref } from 'vue';
-import { disposePinia } from 'pinia';
-import { createVuetify } from 'vuetify';
-import JSZip from 'jszip';
-import { CurrentImageInjectionKey } from '@/src/composables/useCurrentImage';
-import { ManifestSchema, type StateFile } from '@/src/io/state-file/schema';
-import { useViewConfigStore } from '@/src/store/view-configs';
-import { useImageStatsStore } from '@/src/store/image-stats';
-import { useEnFaceViewStore } from '@/src/enface/store';
-import { useEnFaceInput } from '@/src/enface/useEnFaceInput';
-import { useEnFaceOccupiedDepth } from '@/src/enface/useEnFaceOccupiedDepth';
-import EnFaceControls from '@/src/enface/EnFaceControls.vue';
-import { createThinRegionMask, thinCountCutoff } from '@/src/enface/thickness';
-import { useSegmentStore } from '@/src/segmentation/segments';
-import { useSegmentationStore } from '@/src/segmentation/store';
-import {
- measureOccupiedDepth,
- type OccupiedDepthInput,
-} from '@/src/segmentation/measurements/occupiedDepth';
-import {
- activateAppPinia,
- makeImage,
- seatImage,
-} from '@/src/segmentation/__tests__/segmentMaskFixtures';
-import { defer } from '@/src/utils';
-
-let pinia: ReturnType;
-beforeEach(() => {
- pinia = activateAppPinia();
- vi.stubGlobal('visualViewport', null);
-});
-enableAutoUnmount(afterEach);
-afterEach(() => {
- disposePinia(pinia);
- vi.unstubAllGlobals();
-});
-
-const measureInProcess = () => ({
- measure: async (input: OccupiedDepthInput) => measureOccupiedDepth(input),
- release: () => {},
-});
-
-it('keeps the projection ready and restores the non-first segment after deferred mask decoding', async () => {
- useImageStatsStore().stats.oct = {
- scalarMin: 0,
- scalarMax: 1,
- autoRangeValues: {},
- };
- const image = await seatImage('oct', {
- dimensions: [2, 2, 2],
- spacing: [0.01, 0.01, 0.01],
- });
- const manifest = ManifestSchema.parse({
- version: '7.0.0',
- datasets: [],
- dataSources: [],
- segments: ['first', 'chosen'].map((id, index) => ({
- id,
- name: id,
- color: index ? [0, 255, 0, 255] : [255, 0, 0, 255],
- visible: true,
- locked: false,
- })),
- segmentations: [
- {
- id: 'segmentation',
- name: 'OCT layers',
- parentImage: 'saved-oct',
- order: ['first', 'chosen'],
- masks: ['first', 'chosen'].map((id) => ({
- id,
- segmentId: id,
- representations: {
- labelmap: {
- path: `${id}.vti`,
- extent: [0, 1, 0, 1, 0, 1],
- },
- },
- })),
- },
- ],
- viewByID: {
- view: {
- id: 'view',
- type: 'EnFace',
- name: 'En face',
- config: {
- 'saved-oct': {
- enFace: {
- axis: 1,
- method: 'mean',
- depthStart: 0,
- depthEnd: null,
- highlightThin: true,
- thresholdMicrons: 15,
- segmentId: 'chosen',
- },
- },
- },
- },
- },
- });
- const { segmentIdMap } = useSegmentStore().deserialize(manifest);
- const dataIDMap = { 'saved-oct': 'oct' };
- useViewConfigStore().deserializeAll(manifest, dataIDMap, segmentIdMap);
- const reading = defer();
- const release = defer();
- const segmentation = useSegmentationStore();
- const restored = segmentation.deserialize({
- manifest,
- dataIDMap,
- segmentIdMap,
- stateFiles: ['first', 'chosen'].map((id) => ({
- archivePath: `${id}.vti`,
- file: new File([], `${id}.vti`),
- })),
- io: {
- write: async () => '',
- read: async (file) => {
- reading.resolve();
- await release.promise;
- return {
- image: makeImage({
- dimensions: [2, 2, 2],
- spacing: [0.01, 0.01, 0.01],
- values:
- file.name === 'chosen.vti'
- ? new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0])
- : new Uint8Array(8).fill(1),
- }),
- };
- },
- },
- });
- await reading.promise;
- let projection!: ReturnType;
- let thickness!: ReturnType;
- const wrapper = mount(
- defineComponent({
- setup() {
- projection = useEnFaceInput('view');
- thickness = useEnFaceOccupiedDepth(
- 'view',
- {
- source: projection.source,
- slab: projection.specification,
- geometry: projection.geometry,
- blockedReason: computed(
- () => projection.controls.value.projectionReason
- ),
- },
- measureInProcess
- );
- return () =>
- h(EnFaceControls, {
- ...projection.controls.value,
- settings: useEnFaceViewStore().configFor('view', 'oct'),
- thickness: thickness.controls.value,
- });
- },
- }),
- {
- global: {
- plugins: [pinia, createVuetify()],
- provide: {
- [CurrentImageInjectionKey as symbol]: { imageID: ref('oct') },
- },
- },
- }
- );
- try {
- await nextTick();
- expect(projection.source.currentImageData.value).toBe(image);
- expect(projection.geometry.value).not.toBeNull();
- expect(
- wrapper.get(
- '[data-testid="enface-thin-highlight"] input'
- ).element.checked
- ).toBe(true);
- expect(
- wrapper.get('[data-testid="enface-segmentation-segment"]').text()
- ).toContain('chosen');
- for (const control of ['thin-highlight', 'thickness-threshold-input'])
- expect(
- wrapper
- .get(`[data-testid="enface-${control}"] input`)
- .attributes('disabled')
- ).toBeDefined();
- expect(thickness.overlay.value.measurement).toBeNull();
- expect(thickness.overlay.value.appearance).toBeNull();
-
- // Saving while decoding must retain the chosen segment, too.
- const saved: StateFile = {
- zip: new JSZip(),
- manifest: { ...manifest, datasets: [{ id: 'oct', dataSourceId: 0 }] },
- };
- useEnFaceViewStore().serialize(saved);
- expect(saved.manifest.viewByID!.view.config!.oct.enFace).toMatchObject({
- segmentId: segmentIdMap.chosen,
- highlightThin: true,
- });
- } finally {
- release.resolve();
- await restored;
- }
- await flushPromises();
- expect(thickness.overlay.value.appearance?.color).toEqual([0, 255, 0, 255]);
- expect(thickness.overlay.value.measurement?.counts).toEqual(
- new Uint32Array([1, 0, 0, 0])
- );
- const measurement = thickness.overlay.value.measurement!;
- expect(
- Array.from(
- createThinRegionMask(
- measurement.counts,
- thinCountCutoff(measurement, 15, 10)
- )
- )
- ).toEqual([1, 0, 0, 0]);
- for (const control of ['thin-highlight', 'thickness-threshold-input'])
- expect(
- wrapper
- .get(`[data-testid="enface-${control}"] input`)
- .attributes('disabled')
- ).toBeUndefined();
-});
diff --git a/src/enface/__tests__/store.spec.ts b/src/enface/__tests__/store.spec.ts
index d0515c772..0772f2dc9 100644
--- a/src/enface/__tests__/store.spec.ts
+++ b/src/enface/__tests__/store.spec.ts
@@ -1,7 +1,10 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { createPinia, setActivePinia } from 'pinia';
import JSZip from 'jszip';
-import { useEnFaceViewStore } from '@/src/enface/store';
+import {
+ defaultEnFaceViewConfig,
+ useEnFaceViewStore,
+} from '@/src/enface/store';
import { ManifestSchema, type StateFile } from '@/src/io/state-file/schema';
import { parseNamedLayouts } from '@/src/utils/layoutParsing';
import { computeEffectiveView } from '@/src/core/views/effectiveView';
@@ -31,7 +34,9 @@ describe('En face view settings', () => {
axis: 1,
depthStart: 20,
depthEnd: 40,
- thresholdMicrons: 35,
+ segmentProjections: {
+ layer: { visible: true, thresholdMicrons: null },
+ },
});
const state: StateFile = {
zip: new JSZip(),
@@ -78,10 +83,8 @@ describe('En face view settings', () => {
method: 'sum',
depthStart: 20,
depthEnd: 40,
- thresholdMicrons: 35,
- highlightThin: false,
+ segmentProjections: {},
});
- expect(store.configFor('restored', 'new-oct').segmentId).toBeNull();
expect(useWindowingStore().getConfig('restored', 'new-oct')).toMatchObject({
width: 120,
level: 60,
@@ -89,7 +92,7 @@ describe('En face view settings', () => {
});
});
- it('restores a slab scene saved without occupied-depth settings', () => {
+ it('restores a slab scene saved before per-segment settings with every segment hidden', () => {
const parsed = ManifestSchema.parse({
version: '7.0.0',
datasets: [],
@@ -101,7 +104,15 @@ describe('En face view settings', () => {
name: 'En face',
config: {
source: {
- enFace: { axis: 2, method: 'max', depthStart: 1, depthEnd: 4 },
+ enFace: {
+ axis: 2,
+ method: 'max',
+ depthStart: 1,
+ depthEnd: 4,
+ highlightThin: true,
+ thresholdMicrons: 30,
+ segmentId: 'layer',
+ },
},
},
},
@@ -118,32 +129,34 @@ describe('En face view settings', () => {
method: 'max',
depthStart: 1,
depthEnd: 4,
- highlightThin: false,
- thresholdMicrons: 100,
- segmentId: null,
+ segmentProjections: {},
});
});
it('remaps saved segment ids and drops unknown ones on restore', () => {
const store = useEnFaceViewStore();
- const saved = (segmentId: string) => ({
- enFace: {
- axis: 1 as const,
- method: 'mean' as const,
- depthStart: 0,
- depthEnd: null,
- thresholdMicrons: 35,
- highlightThin: true,
- segmentId,
- },
- });
+ const projection = {
+ visible: true,
+ thresholdMicrons: 35,
+ };
store.deserialize(
'view',
- { kept: saved('saved-layer'), dropped: saved('missing-layer') },
+ {
+ data: {
+ enFace: {
+ ...defaultEnFaceViewConfig(),
+ segmentProjections: {
+ 'saved-layer': projection,
+ 'missing-layer': projection,
+ },
+ },
+ },
+ },
{ 'saved-layer': 'chosen' }
);
- expect(store.configFor('view', 'kept').segmentId).toBe('chosen');
- expect(store.configFor('view', 'dropped').segmentId).toBeNull();
+ expect(store.configFor('view', 'data').segmentProjections).toEqual({
+ chosen: projection,
+ });
});
it('resolves custom enface layouts without treating the projection as a slice', () => {
diff --git a/src/enface/__tests__/thinRegionAppearance.spec.ts b/src/enface/__tests__/thinRegionAppearance.spec.ts
deleted file mode 100644
index 889bce294..000000000
--- a/src/enface/__tests__/thinRegionAppearance.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { beforeEach, describe, expect, it } from 'vitest';
-import { createPinia, setActivePinia } from 'pinia';
-import { ref } from 'vue';
-import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
-import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
-import { useImageCacheStore } from '@/src/store/image-cache';
-import { useSegmentationStore } from '@/src/segmentation/store';
-import { useSegmentStore } from '@/src/segmentation/segments';
-import { useThinRegionAppearance } from '@/src/enface/useThinRegionAppearance';
-
-beforeEach(() => setActivePinia(createPinia()));
-
-function appearanceScene() {
- const parent = vtkImageData.newInstance();
- parent.setDimensions(2, 2, 2);
- parent
- .getPointData()
- .setScalars(vtkDataArray.newInstance({ values: new Uint16Array(8) }));
- const parentId = useImageCacheStore().addVTKImageData(parent, 'OCT');
- const store = useSegmentationStore();
- const registry = useSegmentStore().segments;
- const group = store.ensureSegmentationForImage(parentId);
- const segmentId = registry.addSegment({ color: [35, 215, 190, 255] });
- const mask = store.createMask(group.id, segmentId);
- const binding = store.ensureLabelmapBinding(mask.id);
- const maskId = ref(mask.id);
- const appearance = useThinRegionAppearance(maskId);
- return {
- store,
- registry,
- group,
- segmentId,
- mask,
- binding,
- maskId,
- appearance,
- };
-}
-
-describe('thin-region appearance from the source segmentation', () => {
- it('uses the selected segment color and normal default fill without modifying mask storage', () => {
- const { appearance, binding } = appearanceScene();
- const scalars = binding.image.getPointData().getScalars().getData();
- expect(appearance.value).toEqual({
- color: [35, 215, 190, 255],
- fillOpacity: 0.3,
- outlineThickness: 2,
- outlineOpacity: 1,
- value: 1,
- reason: null,
- });
- expect(binding.image.getPointData().getScalars().getData()).toBe(scalars);
- });
-
- it('updates the resolved style when segment color or either fill opacity changes', () => {
- const { appearance, registry, store, group, segmentId } = appearanceScene();
- registry.updateSegment(segmentId, { color: [255, 0, 0, 255] });
- expect(appearance.value).toMatchObject({
- color: [255, 0, 0, 255],
- fillOpacity: 0.3,
- });
- registry.updateSegment(segmentId, { fillOpacity: 0.5 });
- expect(appearance.value!.fillOpacity).toBe(0.15);
- store.updateSegmentationDisplay(group.id, { fillOpacity: 0.8 });
- expect(appearance.value!.fillOpacity).toBe(0.4);
- registry.updateSegment(segmentId, { color: [255, 0, 0, 128] });
- expect(appearance.value!.color).toEqual([255, 0, 0, 128]);
- expect(appearance.value!.fillOpacity).toBeCloseTo((128 / 255) * 0.5 * 0.8);
- });
-
- it('changes appearance with the selected mask and drops missing selections', () => {
- const { appearance, registry, store, group, maskId } = appearanceScene();
- const second = registry.addSegment({ color: [0, 255, 0, 255] });
- const mask = store.createMask(group.id, second);
- store.ensureLabelmapBinding(mask.id);
- maskId.value = mask.id;
- expect(appearance.value!.color).toEqual([0, 255, 0, 255]);
- registry.deleteSegment(second);
- expect(appearance.value).toBeNull();
- maskId.value = null;
- expect(appearance.value).toBeNull();
- });
-
- it('keeps outline-only highlighting available and explains fully hidden appearances', () => {
- const { appearance, registry, store, group, segmentId } = appearanceScene();
- registry.updateSegment(segmentId, { visible: false });
- expect(appearance.value).toMatchObject({
- fillOpacity: 0,
- reason: 'Show the selected segment to highlight thin regions.',
- });
- registry.updateSegment(segmentId, { visible: true, fillOpacity: 0 });
- expect(appearance.value).toMatchObject({
- fillOpacity: 0,
- outlineThickness: 2,
- outlineOpacity: 1,
- reason: null,
- });
- registry.updateSegment(segmentId, { fillOpacity: 1 });
- store.updateSegmentationDisplay(group.id, { fillOpacity: 0 });
- expect(appearance.value).toMatchObject({
- fillOpacity: 0,
- reason: null,
- });
- registry.updateSegment(segmentId, { outlineOpacity: 0.5 });
- store.updateSegmentationDisplay(group.id, {
- outlineOpacity: 0.4,
- outlineThickness: 4,
- });
- expect(appearance.value).toMatchObject({
- outlineThickness: 4,
- outlineOpacity: 0.2,
- reason: null,
- });
- store.updateSegmentationDisplay(group.id, { outlineOpacity: 0 });
- expect(appearance.value!.reason).toContain(
- 'fill opacity or enable an outline'
- );
- store.updateSegmentationDisplay(group.id, { outlineOpacity: 1 });
- expect(appearance.value!.reason).toBeNull();
- store.updateSegmentationDisplay(group.id, { outlineThickness: 0 });
- expect(appearance.value!.reason).toContain(
- 'fill opacity or enable an outline'
- );
- store.updateSegmentationDisplay(group.id, { outlineThickness: 2 });
- store.updateSegmentationDisplay(group.id, { fillOpacity: 0.3 });
- registry.updateSegment(segmentId, { color: [35, 215, 190, 0] });
- expect(appearance.value).toMatchObject({ fillOpacity: 0 });
- expect(appearance.value!.reason).toBeNull();
- registry.updateSegment(segmentId, {
- color: [35, 215, 190, 255],
- outlineOpacity: 0,
- });
- store.updateSegmentationDisplay(group.id, {
- outlineOpacity: 0,
- outlineThickness: 0,
- });
- expect(appearance.value).toMatchObject({ fillOpacity: 0.3, reason: null });
- });
-});
diff --git a/src/enface/store.ts b/src/enface/store.ts
index 1a5884955..86ce299cc 100644
--- a/src/enface/store.ts
+++ b/src/enface/store.ts
@@ -15,26 +15,35 @@ export type EnFaceViewConfig = {
method: SlabMethod;
depthStart: number;
depthEnd: number | null;
- highlightThin: boolean;
- thresholdMicrons: number;
- segmentId: string | null;
+ /** By segment id. Segments without an entry stay hidden. */
+ segmentProjections: Record;
};
-export type ThicknessControlState = {
- thresholdMaximum: number;
+export type SegmentProjection = {
+ visible: boolean;
+ /** Keeps only regions thinner than this within the slab; null keeps all. */
+ thresholdMicrons: number | null;
+};
+
+export type SegmentControlState = {
+ segments: {
+ id: string;
+ title: string;
+ color?: string;
+ /** Hidden by its eye in the Annotations segment list. */
+ listHidden: boolean;
+ /** Null while the segment has no measurement. */
+ thresholdMaximum: number | null;
+ }[];
segmentationReason: string | null;
- highlightReason: string | null;
- thicknessReason: string | null;
- segments: { value: string; title: string; color?: string }[];
- segmentId: string | null;
- highlightThin: boolean;
+ thinReason: string | null;
};
export type EnFaceViewControlState = {
axes: { title: string; value: number }[];
depthMaximum: number;
projectionReason: string | null;
- thickness: ThicknessControlState;
+ segmentControls: SegmentControlState;
};
export const defaultEnFaceViewConfig = (): EnFaceViewConfig => ({
@@ -42,9 +51,12 @@ export const defaultEnFaceViewConfig = (): EnFaceViewConfig => ({
method: 'mean',
depthStart: 0,
depthEnd: null,
- highlightThin: false,
- thresholdMicrons: 100,
- segmentId: null,
+ segmentProjections: {},
+});
+
+export const defaultSegmentProjection = (): SegmentProjection => ({
+ visible: false,
+ thresholdMicrons: null,
});
export const useEnFaceViewStore = defineStore('enface-view', () => {
@@ -105,7 +117,12 @@ export const useEnFaceViewStore = defineStore('enface-view', () => {
const saved = viewConfig.enFace;
if (!saved) return;
Object.assign(configFor(viewID, dataID), saved, {
- segmentId: (saved.segmentId && segmentIdMap[saved.segmentId]) || null,
+ segmentProjections: Object.fromEntries(
+ Object.entries(saved.segmentProjections).flatMap(
+ ([id, projection]) =>
+ segmentIdMap[id] ? [[segmentIdMap[id], projection]] : []
+ )
+ ),
});
});
}
diff --git a/src/enface/thickness.ts b/src/enface/thickness.ts
index 064e34efc..c09895e69 100644
--- a/src/enface/thickness.ts
+++ b/src/enface/thickness.ts
@@ -48,4 +48,4 @@ export function thicknessSliderMaximum(
}
export const EN_FACE_THICKNESS_HELP =
- 'Thickness of the selected segment within the slab, along the projection axis. Only occupied voxels are counted; gaps are excluded.';
+ 'Thickness is measured within the shown depth, along the projection axis. Only occupied voxels are counted; gaps are excluded.';
diff --git a/src/enface/useEnFaceLabelmaps.ts b/src/enface/useEnFaceLabelmaps.ts
index b59d5b09a..f4ef98e5e 100644
--- a/src/enface/useEnFaceLabelmaps.ts
+++ b/src/enface/useEnFaceLabelmaps.ts
@@ -32,7 +32,7 @@ const sameGeometry = (
export function useEnFaceLabelmaps(
geometry: MaybeRef,
measurement: MaybeRef,
- threshold: MaybeRef,
+ threshold: MaybeRef,
micronsPerVoxel: MaybeRef
) {
const image = vtkImageData.newInstance();
@@ -43,14 +43,17 @@ export function useEnFaceLabelmaps(
image.getPointData().setScalars(scalars);
const cutoff = computed(() => {
const result = unref(measurement);
- return result
- ? thinCountCutoff(result, unref(threshold), unref(micronsPerVoxel))
- : 0;
+ const value = unref(threshold);
+ if (!result) return 0;
+ return value === null
+ ? result.maximumCount
+ : thinCountCutoff(result, value, unref(micronsPerVoxel));
});
// New counts or cutoffs need no render when the highlighted pixels agree.
const pixels = computed((previous: Uint8Array | null = null) => {
const result = unref(measurement);
- if (!result) return null;
+ // A segment outside the slab gets no plane, so no actor or texture.
+ if (!result || result.maximumCount === 0) return null;
const values = createThinRegionMask(result.counts, cutoff.value);
return previous && arrayEquals(previous, values) ? previous : values;
});
diff --git a/src/enface/useEnFaceOccupiedDepth.ts b/src/enface/useEnFaceOccupiedDepth.ts
deleted file mode 100644
index fef465b97..000000000
--- a/src/enface/useEnFaceOccupiedDepth.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { computed, unref, type MaybeRef } from 'vue';
-import {
- useOccupiedDepth,
- type OccupiedDepthMeasurer,
-} from '@/src/segmentation/measurements/useOccupiedDepth';
-import type { SlabGeometry } from '@/src/core/slab/geometry';
-import {
- useOccupiedDepthInput,
- type OccupiedDepthProjection,
-} from './useOccupiedDepthInput';
-import { useThinRegionAppearance } from './useThinRegionAppearance';
-import { thicknessSliderMaximum } from './thickness';
-import type { ThicknessControlState } from './store';
-
-/** Thin-region highlighting for one En face view, layered over its projection. */
-export function useEnFaceOccupiedDepth(
- viewId: MaybeRef,
- projection: OccupiedDepthProjection & {
- geometry: MaybeRef;
- },
- createMeasurer?: () => OccupiedDepthMeasurer
-) {
- const { geometry, blockedReason } = projection;
- const input = useOccupiedDepthInput(viewId, projection);
- const { settings, highlightThin, micronsPerVoxel } = input;
- const appearance = useThinRegionAppearance(
- computed(() => input.selectedMask.value?.id)
- );
- const {
- accepted: measurement,
- computing: measuring,
- error,
- } = useOccupiedDepth(input.request, createMeasurer);
- const thicknessReason = computed(
- () =>
- input.thicknessReason.value ||
- appearance.value?.reason ||
- error.value ||
- (measuring.value && !measurement.value
- ? 'Measuring thickness in the selected slab…'
- : null)
- );
- const message = computed(() => {
- if (!highlightThin.value || unref(blockedReason)) return null;
- // Without a reason, a running measurement has a previous result to show.
- return (
- thicknessReason.value ||
- (measuring.value
- ? 'Updating thickness; showing the previous result.'
- : null)
- );
- });
- const overlay = computed(() => ({
- geometry: unref(geometry),
- measurement: measurement.value,
- micronsPerVoxel: micronsPerVoxel.value,
- threshold: settings.value.thresholdMicrons,
- appearance:
- highlightThin.value && !thicknessReason.value && unref(geometry)
- ? appearance.value
- : null,
- }));
- const controls = computed(
- () =>
- ({
- thresholdMaximum: thicknessSliderMaximum(
- measurement.value,
- micronsPerVoxel.value
- ),
- segmentationReason: input.segmentationReason.value,
- highlightReason: input.highlightReason.value,
- thicknessReason: thicknessReason.value,
- segments: input.segmentOptions.value,
- segmentId: input.segmentId.value,
- highlightThin: highlightThin.value,
- }) satisfies ThicknessControlState
- );
- return { overlay, controls, measuring, message };
-}
diff --git a/src/enface/useMaskDepthRequest.ts b/src/enface/useMaskDepthRequest.ts
new file mode 100644
index 000000000..93aab873e
--- /dev/null
+++ b/src/enface/useMaskDepthRequest.ts
@@ -0,0 +1,151 @@
+import { computed, ref, unref, type MaybeRef } from 'vue';
+import { areEquals, dot } from '@kitware/vtk.js/Common/Core/Math';
+import type { Vector3 } from '@kitware/vtk.js/types';
+import type { useCurrentImage } from '@/src/composables/useCurrentImage';
+import { onVTKEvent } from '@/src/composables/onVTKEvent';
+import { useSegmentationStore } from '@/src/segmentation/store';
+import {
+ extentContains,
+ extentSize,
+ fullExtent,
+ isEmptyExtent,
+} from '@/src/segmentation/geometry';
+import type { OccupiedDepthRequest } from '@/src/segmentation/measurements/useOccupiedDepth';
+import type { SlabSpecification } from '@/src/core/slab/types';
+
+export type EnFaceImageSource = Pick<
+ ReturnType,
+ 'currentImageID' | 'currentImageData'
+>;
+
+/** Binds one segment mask and a slab to an occupied-depth request. */
+export function useMaskDepthRequest(
+ source: EnFaceImageSource,
+ slab: MaybeRef,
+ maskId: MaybeRef
+) {
+ const { currentImageData } = source;
+ const segmentationStore = useSegmentationStore();
+ // Separate fields keep projection method changes from invalidating requests.
+ const slabAxis = computed(() => unref(slab).axis);
+ const slabFirst = computed(() => unref(slab).first);
+ const slabLast = computed(() => unref(slab).last);
+ const volumeRevision = ref(0);
+ const maskRevision = ref(0);
+
+ const binding = computed(() =>
+ segmentationStore.findMaskBinding(unref(maskId))
+ );
+ const measurementMask = computed(() => {
+ void maskRevision.value;
+ if (!binding.value) return null;
+ const scalars = binding.value.image.getPointData().getScalars();
+ const values = scalars?.getData();
+ if (
+ !(values instanceof Uint8Array) ||
+ scalars.getNumberOfComponents() !== 1
+ )
+ return null;
+ return {
+ values,
+ dimensions: binding.value.image.getDimensions(),
+ extent: binding.value.extent,
+ };
+ });
+ const geometryReason = computed(() => {
+ void volumeRevision.value;
+ void maskRevision.value;
+ const parent = currentImageData.value;
+ if (!binding.value || !parent) return null;
+ const { extent, image } = binding.value;
+ const validExtent = extentContains(
+ fullExtent(parent.getDimensions()),
+ extent
+ );
+ const direction = parent.getDirection();
+ const bases = [0, 1, 2].map((axis) => {
+ const offset = axis * 3;
+ const basis: Vector3 = [
+ direction[offset],
+ direction[offset + 1],
+ direction[offset + 2],
+ ];
+ const length = Math.hypot(...basis);
+ return Number.isFinite(length) && length > 0
+ ? (basis.map((value) => value / length) as Vector3)
+ : null;
+ });
+ const orthogonal = [
+ [0, 1],
+ [0, 2],
+ [1, 2],
+ ].every(([a, b]) => {
+ const left = bases[a];
+ const right = bases[b];
+ return (
+ left !== null && right !== null && Math.abs(dot(left, right)) < 1e-4
+ );
+ });
+ if (!orthogonal)
+ return 'Occupied depth requires an orthogonal source voxel grid.';
+ const gridMatches =
+ areEquals(image.getDimensions(), extentSize(extent), 1e-5) &&
+ areEquals(image.getSpacing(), parent.getSpacing(), 1e-5) &&
+ areEquals([...image.getDirection()], [...parent.getDirection()], 1e-5);
+ const originMatches = areEquals(
+ image.getOrigin(),
+ [...parent.indexToWorld([extent[0], extent[2], extent[4]])],
+ 1e-5
+ );
+ return validExtent && gridMatches && originMatches
+ ? null
+ : 'This segmentation mask does not match the source voxel grid; align it to the volume before measuring thickness.';
+ });
+
+ // Scalar and mask storage can change in place during streaming or segmentation editing.
+ const volumeScalars = computed(() => {
+ void volumeRevision.value;
+ return currentImageData.value?.getPointData().getScalars();
+ });
+ const maskImage = computed(() => binding.value?.image);
+ const maskScalars = computed(() => {
+ void maskRevision.value;
+ return maskImage.value?.getPointData().getScalars();
+ });
+ onVTKEvent(currentImageData, 'onModified', () => {
+ volumeRevision.value += 1;
+ });
+ onVTKEvent(volumeScalars, 'onModified', () => {
+ volumeRevision.value += 1;
+ });
+ onVTKEvent(maskImage, 'onModified', () => {
+ maskRevision.value += 1;
+ });
+ onVTKEvent(maskScalars, 'onModified', () => {
+ maskRevision.value += 1;
+ });
+
+ const request = computed((): OccupiedDepthRequest | null => {
+ void volumeRevision.value;
+ const image = currentImageData.value;
+ const mask = measurementMask.value;
+ if (!image || !mask || isEmptyExtent(mask.extent) || geometryReason.value)
+ return null;
+ return {
+ dimensions: image.getDimensions(),
+ source: image,
+ segment: unref(maskId),
+ grid: JSON.stringify([
+ image.getOrigin(),
+ image.getSpacing(),
+ image.getDirection(),
+ ]),
+ axis: slabAxis.value,
+ first: slabFirst.value,
+ last: slabLast.value,
+ mask,
+ };
+ });
+
+ return { geometryReason, request };
+}
diff --git a/src/enface/useOccupiedDepthInput.ts b/src/enface/useOccupiedDepthInput.ts
deleted file mode 100644
index 9bb19b00a..000000000
--- a/src/enface/useOccupiedDepthInput.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-import { computed, ref, unref, type MaybeRef } from 'vue';
-import { areEquals, dot } from '@kitware/vtk.js/Common/Core/Math';
-import type { Vector3 } from '@kitware/vtk.js/types';
-import type { useCurrentImage } from '@/src/composables/useCurrentImage';
-import { onVTKEvent } from '@/src/composables/onVTKEvent';
-import { useSegmentationStore } from '@/src/segmentation/store';
-import { useSegmentStore } from '@/src/segmentation/segments';
-import {
- extentContains,
- extentSize,
- fullExtent,
- isEmptyExtent,
-} from '@/src/segmentation/geometry';
-import type { OccupiedDepthRequest } from '@/src/segmentation/measurements/useOccupiedDepth';
-import type { SlabSpecification } from '@/src/core/slab/types';
-import { getOccupiedDepthSupport } from './occupiedDepthSupport';
-import { useEnFaceViewStore } from './store';
-
-export type OccupiedDepthProjection = {
- source: Pick<
- ReturnType,
- 'currentImageID' | 'currentImageData'
- >;
- slab: MaybeRef;
- /** Blocks every thickness control, such as an unavailable projection. */
- blockedReason: MaybeRef;
-};
-
-/** Binds the selected segment mask and calibrated slab to a measurement request. */
-export function useOccupiedDepthInput(
- viewId: MaybeRef,
- { source, slab, blockedReason }: OccupiedDepthProjection
-) {
- const { currentImageID, currentImageData } = source;
- const segmentationStore = useSegmentationStore();
- const segmentsRegistry = useSegmentStore().segments;
- const enFaceStore = useEnFaceViewStore();
- const settings = computed(() =>
- enFaceStore.settingsFor(unref(viewId), currentImageID.value)
- );
- // Separate fields keep projection method changes from invalidating requests.
- const slabAxis = computed(() => unref(slab).axis);
- const slabFirst = computed(() => unref(slab).first);
- const slabLast = computed(() => unref(slab).last);
- const volumeRevision = ref(0);
- const maskRevision = ref(0);
- const support = computed(() => {
- void volumeRevision.value;
- return getOccupiedDepthSupport(currentImageID.value);
- });
-
- const storedSegment = computed(() =>
- segmentsRegistry.getSegment(settings.value.segmentId)
- );
- const segmentOptions = computed(() => {
- if (!currentImageID.value) return [];
- const segmentIds = segmentationStore
- .imageMasks(currentImageID.value)
- .map((mask) => mask.segmentId);
- const selected = storedSegment.value;
- // A saved segment stays listed without a mask, as while restored voxels decode.
- if (selected && !segmentIds.includes(selected.id))
- segmentIds.push(selected.id);
- return segmentIds.map((segmentId) => {
- const appearance = segmentsRegistry.appearanceOf(segmentId);
- return {
- value: segmentId,
- title: appearance.displayName,
- color: appearance.cssColor,
- };
- });
- });
- // Saved choices stay raw; a deleted one shows the first option, unhighlighted.
- const segmentId = computed(
- () => storedSegment.value?.id ?? segmentOptions.value[0]?.value ?? null
- );
- const highlightThin = computed(
- () => settings.value.highlightThin && !!storedSegment.value
- );
- const selectedMask = computed(() =>
- segmentationStore.maskFor(currentImageID.value, segmentId.value)
- );
- const selectedBinding = computed(() =>
- selectedMask.value
- ? segmentationStore.findMaskBinding(selectedMask.value.id)
- : undefined
- );
- const segmentationReason = computed(
- () =>
- unref(blockedReason) ||
- (!segmentOptions.value.length
- ? 'Load or create a segmentation mask associated with this volume.'
- : null)
- );
- const measurementMask = computed(() => {
- void maskRevision.value;
- const binding = selectedBinding.value;
- if (!binding) return null;
- const scalars = binding.image.getPointData().getScalars();
- const values = scalars?.getData();
- if (
- !(values instanceof Uint8Array) ||
- scalars.getNumberOfComponents() !== 1
- )
- return null;
- return {
- values,
- dimensions: binding.image.getDimensions(),
- extent: binding.extent,
- };
- });
- const maskStorageReason = computed(() => {
- const binding = selectedBinding.value;
- if (!binding)
- return 'The selected segment voxels are not available; load or create its mask to measure occupied depth.';
- if (isEmptyExtent(binding.extent))
- return 'The selected segment has no occupied voxels to measure.';
- if (!measurementMask.value)
- return 'The selected segment does not have a supported binary voxel mask.';
- return null;
- });
- const maskGeometryReason = computed(() => {
- void volumeRevision.value;
- void maskRevision.value;
- const binding = selectedBinding.value;
- const parent = currentImageData.value;
- if (!binding || !parent) return null;
- const extent = binding.extent;
- const validExtent = extentContains(
- fullExtent(parent.getDimensions()),
- extent
- );
- const direction = parent.getDirection();
- const bases = [0, 1, 2].map((axis) => {
- const offset = axis * 3;
- const basis: Vector3 = [
- direction[offset],
- direction[offset + 1],
- direction[offset + 2],
- ];
- const length = Math.hypot(...basis);
- return Number.isFinite(length) && length > 0
- ? (basis.map((value) => value / length) as Vector3)
- : null;
- });
- const orthogonal = [
- [0, 1],
- [0, 2],
- [1, 2],
- ].every(([a, b]) => {
- const left = bases[a];
- const right = bases[b];
- return (
- left !== null && right !== null && Math.abs(dot(left, right)) < 1e-4
- );
- });
- if (!orthogonal)
- return 'Occupied depth requires an orthogonal source voxel grid.';
- const gridMatches =
- areEquals(binding.image.getDimensions(), extentSize(extent), 1e-5) &&
- areEquals(binding.image.getSpacing(), parent.getSpacing(), 1e-5) &&
- areEquals(
- [...binding.image.getDirection()],
- [...parent.getDirection()],
- 1e-5
- );
- const originMatches = areEquals(
- binding.image.getOrigin(),
- [...parent.indexToWorld([extent[0], extent[2], extent[4]])],
- 1e-5
- );
- return validExtent && gridMatches && originMatches
- ? null
- : 'This segmentation mask does not match the source voxel grid; align it to the volume before measuring thickness.';
- });
- const micronsPerVoxel = computed(() => {
- void volumeRevision.value;
- const image = currentImageData.value;
- if (!image) return 0;
- const axis = slabAxis.value;
- // Declared DICOM spacing is physical, so rounded unit cosines must not
- // rescale it. Generic image directions can carry scale.
- const scale = support.value.calibratedAxes?.[axis]
- ? 1
- : Math.hypot(...image.getDirection().slice(axis * 3, axis * 3 + 3));
- return Math.abs(image.getSpacing()[axis]) * scale * 1000;
- });
- const highlightReason = computed(
- () =>
- segmentationReason.value ||
- (!selectedBinding.value ? maskStorageReason.value : null) ||
- support.value.reason ||
- (support.value.calibratedAxes?.[slabAxis.value] === false
- ? 'The projection axis has no reliable declared voxel spacing; occupied depth is unavailable.'
- : null) ||
- (!Number.isFinite(micronsPerVoxel.value) || micronsPerVoxel.value <= 0
- ? 'The projection axis has invalid voxel spacing; occupied depth is unavailable.'
- : null)
- );
- const thicknessReason = computed(
- () =>
- highlightReason.value ||
- maskStorageReason.value ||
- maskGeometryReason.value
- );
-
- // Scalar and mask storage can change in place during streaming or segmentation editing.
- const volumeScalars = computed(() => {
- void volumeRevision.value;
- return currentImageData.value?.getPointData().getScalars();
- });
- const maskImage = computed(() => selectedBinding.value?.image);
- const maskScalars = computed(() => {
- void maskRevision.value;
- return maskImage.value?.getPointData().getScalars();
- });
- onVTKEvent(currentImageData, 'onModified', () => {
- volumeRevision.value += 1;
- });
- onVTKEvent(volumeScalars, 'onModified', () => {
- volumeRevision.value += 1;
- });
- onVTKEvent(maskImage, 'onModified', () => {
- maskRevision.value += 1;
- });
- onVTKEvent(maskScalars, 'onModified', () => {
- maskRevision.value += 1;
- });
-
- const request = computed((): OccupiedDepthRequest | null => {
- if (!highlightThin.value) return null;
- void volumeRevision.value;
- const image = currentImageData.value;
- const mask = measurementMask.value;
- if (!image || !mask || thicknessReason.value) return null;
- return {
- dimensions: image.getDimensions(),
- source: image,
- segment: selectedMask.value!.id,
- grid: JSON.stringify([
- image.getOrigin(),
- image.getSpacing(),
- image.getDirection(),
- ]),
- axis: slabAxis.value,
- first: slabFirst.value,
- last: slabLast.value,
- mask,
- };
- });
-
- return {
- settings,
- segmentId,
- highlightThin,
- selectedMask,
- segmentOptions,
- segmentationReason,
- highlightReason,
- thicknessReason,
- micronsPerVoxel,
- request,
- };
-}
diff --git a/src/enface/useThinCalibration.ts b/src/enface/useThinCalibration.ts
new file mode 100644
index 000000000..86bc20c63
--- /dev/null
+++ b/src/enface/useThinCalibration.ts
@@ -0,0 +1,45 @@
+import { computed, ref, unref, type MaybeRef } from 'vue';
+import { onVTKEvent } from '@/src/composables/onVTKEvent';
+import type { SlabSpecification } from '@/src/core/slab/types';
+import { getOccupiedDepthSupport } from './occupiedDepthSupport';
+import type { EnFaceImageSource } from './useMaskDepthRequest';
+
+/** Physical voxel depth along the slab axis, or why thickness cannot be measured. */
+export function useThinCalibration(
+ { currentImageID, currentImageData }: EnFaceImageSource,
+ slab: MaybeRef
+) {
+ const revision = ref(0);
+ onVTKEvent(currentImageData, 'onModified', () => {
+ revision.value += 1;
+ });
+ const axis = computed(() => unref(slab).axis);
+ const support = computed(() => {
+ void revision.value;
+ return getOccupiedDepthSupport(currentImageID.value);
+ });
+ const micronsPerVoxel = computed(() => {
+ void revision.value;
+ const image = currentImageData.value;
+ if (!image) return 0;
+ // Declared DICOM spacing is physical, so rounded unit cosines must not
+ // rescale it. Generic image directions can carry scale.
+ const scale = support.value.calibratedAxes?.[axis.value]
+ ? 1
+ : Math.hypot(
+ ...image.getDirection().slice(axis.value * 3, axis.value * 3 + 3)
+ );
+ return Math.abs(image.getSpacing()[axis.value]) * scale * 1000;
+ });
+ const reason = computed(
+ () =>
+ support.value.reason ||
+ (support.value.calibratedAxes?.[axis.value] === false
+ ? 'The projection axis has no reliable declared voxel spacing; occupied depth is unavailable.'
+ : null) ||
+ (!Number.isFinite(micronsPerVoxel.value) || micronsPerVoxel.value <= 0
+ ? 'The projection axis has invalid voxel spacing; occupied depth is unavailable.'
+ : null)
+ );
+ return { micronsPerVoxel, reason };
+}
diff --git a/src/enface/useThinRegionAppearance.ts b/src/enface/useThinRegionAppearance.ts
deleted file mode 100644
index 810bfa33b..000000000
--- a/src/enface/useThinRegionAppearance.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { computed, unref, type MaybeRef } from 'vue';
-import type { Maybe } from '@/src/types';
-import { useSegmentationStore } from '@/src/segmentation/store';
-import { labelmapAppearance } from '@/src/segmentation/rendering/display';
-
-/** The selected mask uses its source slice's normal fill and outline settings. */
-export function useThinRegionAppearance(maskId: MaybeRef>) {
- const segmentationStore = useSegmentationStore();
- return computed(() => {
- const id = unref(maskId);
- if (!id) return null;
- const descriptor = segmentationStore.labelmapDescriptorByMask[id];
- const segmentation = segmentationStore.segmentationOfMask(id);
- if (!descriptor || !segmentation) return null;
- const appearance = labelmapAppearance(descriptor, segmentation);
- let reason: string | null = null;
- if (!descriptor.visible)
- reason = 'Show the selected segment to highlight thin regions.';
- else if (
- appearance.fillOpacity <= 0 &&
- (appearance.outlineThickness <= 0 || appearance.outlineOpacity <= 0)
- )
- reason =
- 'Increase segmentation fill opacity or enable an outline to highlight thin regions.';
- return { ...appearance, reason };
- });
-}
diff --git a/src/io/state-file/schema.ts b/src/io/state-file/schema.ts
index 224c56bed..001e456bf 100644
--- a/src/io/state-file/schema.ts
+++ b/src/io/state-file/schema.ts
@@ -287,9 +287,15 @@ const EnFaceViewConfig = z.object({
method: z.enum(SLAB_METHODS),
depthStart: z.number().int().nonnegative(),
depthEnd: z.number().int().nonnegative().nullable(),
- highlightThin: z.boolean().default(false),
- thresholdMicrons: z.number().nonnegative().default(100),
- segmentId: z.string().nullable().default(null),
+ segmentProjections: z
+ .record(
+ z.string(),
+ z.object({
+ visible: z.boolean(),
+ thresholdMicrons: z.number().nonnegative().nullable(),
+ })
+ )
+ .default({}),
}) satisfies z.ZodType;
const ViewConfig = z.object({
diff --git a/src/segmentation/measurements/occupiedDepth.worker.ts b/src/segmentation/measurements/occupiedDepth.worker.ts
index 700a3550d..20ba69c7e 100644
--- a/src/segmentation/measurements/occupiedDepth.worker.ts
+++ b/src/segmentation/measurements/occupiedDepth.worker.ts
@@ -4,23 +4,34 @@ import {
type OccupiedDepthInput,
} from '@/src/segmentation/measurements/occupiedDepth';
-let measure: ReturnType | undefined;
+const measurements = new Map<
+ string,
+ ReturnType
+>();
const api = {
- /** Without a mask, reuses the one this worker was last sent. */
+ /** Without a mask, reuses the snapshot for this segment. */
measure(
input: Omit,
- mask?: OccupiedDepthInput['mask']
+ mask: OccupiedDepthInput['mask'] | undefined,
+ segment: string
) {
if (mask) {
// A rejected replacement must not leave the previous mask measurable.
- measure = undefined;
- measure = createOccupiedDepthMeasurer(mask);
+ measurements.delete(segment);
+ measurements.set(segment, createOccupiedDepthMeasurer(mask));
}
+ const measure = measurements.get(segment);
if (!measure) throw new Error('Occupied depth has no measurable mask.');
const result = measure(input);
return Comlink.transfer(result, [result.counts.buffer as ArrayBuffer]);
},
+ retain(segments: string[]) {
+ const retained = new Set(segments);
+ measurements.forEach((_measurement, segment) => {
+ if (!retained.has(segment)) measurements.delete(segment);
+ });
+ },
};
export type OccupiedDepthWorkerApi = typeof api;
diff --git a/src/segmentation/measurements/useOccupiedDepth.ts b/src/segmentation/measurements/useOccupiedDepth.ts
index b09c9bcdc..f01a1b862 100644
--- a/src/segmentation/measurements/useOccupiedDepth.ts
+++ b/src/segmentation/measurements/useOccupiedDepth.ts
@@ -39,13 +39,24 @@ const spawnMeasurementWorker = () =>
/** A view's worker, sent each mask revision once and reusing it across slabs. */
export function createWorkerMeasurer(spawn = spawnMeasurementWorker) {
const host = createWorkerHost(spawn);
- let sent: { api: unknown; mask: OccupiedDepthInput['mask'] } | undefined;
+ const sent = new Map<
+ string,
+ { api: unknown; mask: OccupiedDepthInput['mask'] }
+ >();
return {
- measure: ({ mask, dimensions, axis, first, last }: OccupiedDepthInput) =>
+ measure: ({
+ mask,
+ dimensions,
+ axis,
+ first,
+ last,
+ segment,
+ }: OccupiedDepthInput & { segment: string }) =>
host.call((api) => {
// A respawned worker holds no mask.
- const fresh = sent?.api !== api || sent?.mask !== mask;
- sent = { api, mask };
+ const previous = sent.get(segment);
+ const fresh = previous?.api !== api || previous?.mask !== mask;
+ sent.set(segment, { api, mask });
const values = fresh ? new Uint8Array(mask.values) : undefined;
return api.measure(
{ dimensions: [...dimensions], axis, first, last },
@@ -57,17 +68,29 @@ export function createWorkerMeasurer(spawn = spawnMeasurementWorker) {
extent: [...mask.extent],
},
[values.buffer]
- )
+ ),
+ segment
);
}),
+ retain(segments: string[]) {
+ if (!sent.size) return;
+ const retained = new Set(segments);
+ sent.forEach((_snapshot, segment) => {
+ if (!retained.has(segment)) sent.delete(segment);
+ });
+ void host.call((api) => api.retain(segments)).catch(() => {});
+ },
release() {
- sent = undefined;
+ sent.clear();
host.terminate();
},
};
}
-export type OccupiedDepthMeasurer = ReturnType;
+export type OccupiedDepthMeasurer = Pick<
+ ReturnType,
+ 'measure' | 'release'
+>;
/** Measures the latest request, keeping a compatible result while it updates. */
export function useOccupiedDepth(
@@ -121,7 +144,10 @@ export function useOccupiedDepth(
},
{ immediate: true, flush: 'pre' }
);
- onScopeDispose(measurer.release);
+ onScopeDispose(() => {
+ pending = null;
+ measurer.release();
+ });
const accepted = computed(() => {
const input = unref(request);
return input && latest.value && compatible(latest.value.input, input)
diff --git a/tests/specs/enface-segmentation-projection.e2e.ts b/tests/specs/enface-segmentation-projection.e2e.ts
new file mode 100644
index 000000000..188c6a4a2
--- /dev/null
+++ b/tests/specs/enface-segmentation-projection.e2e.ts
@@ -0,0 +1,329 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import JSZip from 'jszip';
+import { createNrrdVolume, createVtiVolume } from '../fixtures/oct/volumes';
+import { volViewPage } from '../pageobjects/volview.page';
+import { TEMP_DIR } from '../../wdio.shared.conf';
+import { makeTempDir, SESSION_SAVE_TIMEOUT, waitForDownload } from './utils';
+import {
+ enFacePixel,
+ expandEnFaceSection,
+ openEnFaceControls,
+ openEnFaceSidebarControls,
+ PANEL,
+ segmentEye,
+ segmentThreshold,
+ setEnFaceWindow,
+ setSegmentShown,
+ setSegmentThreshold,
+ setSlabRange,
+ waitForEnFaceReady,
+} from './octTestUtils';
+import { registerOctTestHooks } from './octInteractionTestUtils';
+import {
+ openAnnotationSegments,
+ setSegmentVisible,
+} from './segmentationTestUtils';
+
+const SIZE = 12;
+const STEM = 'enface-footprints-' + process.pid;
+const [RED_NAME, BLUE_NAME] = ['Red columns', 'Blue columns'];
+const RED = [2, 3] as const;
+const BLUE = [7, 8] as const;
+const OVERLAP = [4, 6] as const;
+const DEEP = [9, 2] as const;
+const EMPTY = [10, 10] as const;
+type PixelKind = 'gray' | 'red' | 'blue' | 'overlap';
+type Sample = readonly [readonly [number, number], PixelKind];
+
+const maskValues = (inside: (x: number, y: number, z: number) => boolean) =>
+ Uint16Array.from({ length: SIZE ** 3 }, (_, index) =>
+ Number(
+ inside(
+ index % SIZE,
+ Math.floor(index / SIZE) % SIZE,
+ Math.floor(index / SIZE ** 2)
+ )
+ )
+ );
+
+async function openFootprintScene() {
+ const directory = makeTempDir(STEM);
+ fs.writeFileSync(
+ path.join(directory, 'parent.vti'),
+ createVtiVolume({
+ values: new Uint16Array(SIZE ** 3).fill(100),
+ dimensions: [SIZE, SIZE, SIZE],
+ type: 'UInt16',
+ })
+ );
+ const zip = new JSZip();
+ const masks = [
+ {
+ id: 'red',
+ name: RED_NAME,
+ color: [255, 0, 0, 255],
+ values: maskValues(
+ (x, y, z) => x >= 1 && x <= 5 && y >= 1 && y <= 5 && z >= 2 && z <= 8
+ ),
+ },
+ {
+ id: 'blue',
+ name: BLUE_NAME,
+ color: [0, 0, 255, 255],
+ values: maskValues(
+ (x, y, z) =>
+ (x >= 4 && x <= 8 && y >= 6 && y <= 10 && z >= 5 && z <= 10) ||
+ (x >= 8 && x <= 10 && y >= 9 && y <= 10 && z >= 1 && z <= 3)
+ ),
+ },
+ ];
+ masks.forEach(({ id, values }) =>
+ zip.file(
+ `${id}.nrrd`,
+ createNrrdVolume({
+ dimensions: [SIZE, SIZE, SIZE],
+ spacing: [1, 1, 1],
+ scalars: values,
+ })
+ )
+ );
+ zip.file(
+ 'manifest.json',
+ JSON.stringify({
+ version: '7.0.0',
+ dataSources: [{ id: 0, type: 'uri', uri: `/tmp/${STEM}/parent.vti` }],
+ segments: masks.map(({ id, name, color }) => ({ id, name, color })),
+ selectedSegment: 'red',
+ segmentations: [
+ {
+ id: 'segmentation',
+ name: 'Columns',
+ parentImage: '0',
+ fillOpacity: 0.5,
+ outlineOpacity: 0,
+ outlineThickness: 0,
+ order: masks.map(({ id }) => `${id}-mask`),
+ masks: masks.map(({ id }) => ({
+ id: `${id}-mask`,
+ segmentId: id,
+ representations: {
+ labelmap: {
+ path: `${id}.nrrd`,
+ extent: [0, SIZE - 1, 0, SIZE - 1, 0, SIZE - 1],
+ },
+ },
+ })),
+ },
+ ],
+ viewByID: {
+ enface: {
+ id: 'enface',
+ name: 'En face',
+ type: 'EnFace',
+ dataID: '0',
+ config: {
+ '0': {
+ enFace: {
+ axis: 1,
+ method: 'mean',
+ depthStart: 0,
+ depthEnd: null,
+ },
+ },
+ },
+ },
+ },
+ layout: { direction: 'row', items: [{ type: 'slot', slotIndex: 0 }] },
+ layoutSlots: ['enface'],
+ activeView: 'enface',
+ })
+ );
+ fs.writeFileSync(
+ path.join(directory, 'columns.volview.zip'),
+ await zip.generateAsync({ type: 'nodebuffer' })
+ );
+ await volViewPage.open(`?urls=[tmp/${STEM}/columns.volview.zip]`);
+ await waitForEnFaceReady();
+ await setEnFaceWindow(200, 100);
+ await openEnFaceControls();
+}
+
+function pixelMatches([red, green, blue]: number[], kind: PixelKind) {
+ const matches = {
+ gray: red > 20 && red === green && green === blue,
+ red: red > green + 30 && red > blue + 30,
+ blue: blue > red + 30 && blue > green + 30,
+ overlap: red > green + 20 && blue > green + 20,
+ };
+ return matches[kind];
+}
+
+async function expectPixels(samples: readonly Sample[]) {
+ await waitForEnFaceReady();
+ await browser.waitUntil(
+ async () => {
+ const matches = await Promise.all(
+ samples.map(async ([point, kind]) =>
+ pixelMatches(await enFacePixel(...point), kind)
+ )
+ );
+ return matches.every(Boolean);
+ },
+ {
+ timeoutMsg: `Expected projected segmentation pixels: ${JSON.stringify(samples)}`,
+ }
+ );
+}
+
+describe('En face segmentation projections', () => {
+ registerOctTestHooks();
+
+ it('draws shown segments where they cross the slab, with overlaps', async () => {
+ await openFootprintScene();
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'gray'],
+ [OVERLAP, 'gray'],
+ ]);
+ await setSegmentShown(RED_NAME, true);
+ await expectPixels([
+ [RED, 'red'],
+ [BLUE, 'gray'],
+ ]);
+ await setSegmentShown(BLUE_NAME, true);
+ await expectPixels([
+ [RED, 'red'],
+ [BLUE, 'blue'],
+ [OVERLAP, 'overlap'],
+ [DEEP, 'blue'],
+ [EMPTY, 'gray'],
+ ]);
+
+ await expandEnFaceSection('projection');
+ await setSlabRange(6, 8);
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'blue'],
+ [OVERLAP, 'blue'],
+ [DEEP, 'gray'],
+ ]);
+ await setSlabRange(0, 11);
+
+ const all = $(PANEL).$('[data-testid="enface-segments-visible"]');
+ await expect(all).toHaveAttribute('aria-label', 'Hide every segment');
+ await all.click();
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'gray'],
+ ]);
+ await all.click();
+ await expectPixels([
+ [RED, 'red'],
+ [OVERLAP, 'overlap'],
+ ]);
+
+ await browser.keys('Escape');
+ await openAnnotationSegments();
+ await setSegmentVisible(RED_NAME, false);
+ await expectPixels([
+ [RED, 'gray'],
+ [OVERLAP, 'blue'],
+ [BLUE, 'blue'],
+ ]);
+ await setSegmentVisible(RED_NAME, true);
+ await expectPixels([
+ [RED, 'red'],
+ [OVERLAP, 'overlap'],
+ ]);
+ expect(await volViewPage.getNotificationsCount()).toBe(0);
+ });
+
+ it('highlights thin regions of two segments against their own thresholds', async () => {
+ await openFootprintScene();
+ await setSegmentShown(BLUE_NAME, true);
+ // Red is 5000 um deep; blue is 5000 um deep except its 2000 um corner.
+ await setSegmentThreshold(RED_NAME, 4000);
+ await expectPixels([
+ [RED, 'gray'],
+ [OVERLAP, 'blue'],
+ [BLUE, 'blue'],
+ [DEEP, 'blue'],
+ ]);
+ await setSegmentThreshold(BLUE_NAME, 3000);
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'gray'],
+ [DEEP, 'blue'],
+ ]);
+ await setSegmentThreshold(RED_NAME, 6000);
+ await expectPixels([
+ [RED, 'red'],
+ [OVERLAP, 'red'],
+ [BLUE, 'gray'],
+ [DEEP, 'blue'],
+ ]);
+ await expect(segmentThreshold(RED_NAME)).toHaveValue('6000');
+ await expect(segmentThreshold(BLUE_NAME)).toHaveValue('3000');
+ await setSegmentThreshold(RED_NAME, 4000);
+ await expectPixels([[RED, 'gray']]);
+ await setSegmentThreshold(RED_NAME, null);
+ await expect(segmentThreshold(RED_NAME)).toHaveValue('');
+ await expectPixels([
+ [RED, 'red'],
+ [BLUE, 'gray'],
+ [DEEP, 'blue'],
+ ]);
+ expect(await volViewPage.getNotificationsCount()).toBe(0);
+ });
+
+ it('shares segment settings with Rendering controls and restores them from a session', async () => {
+ await openFootprintScene();
+ await expandEnFaceSection('projection');
+ await setSlabRange(1, 8);
+ await setSegmentShown(BLUE_NAME, true);
+ await setSegmentThreshold(RED_NAME, 4000);
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'blue'],
+ [DEEP, 'gray'],
+ ]);
+
+ const sidebar = await openEnFaceSidebarControls();
+ await expandEnFaceSection('segments', sidebar);
+ const expectSettings = async (scope?: string) => {
+ for (const name of [BLUE_NAME, RED_NAME])
+ await expect(segmentEye(name, scope)).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(segmentThreshold(RED_NAME, scope)).toHaveValue('4000');
+ await expect(segmentThreshold(BLUE_NAME, scope)).toHaveValue('');
+ };
+ await expectSettings(sidebar);
+ await setSegmentShown(BLUE_NAME, false, sidebar);
+ await expectPixels([[BLUE, 'gray']]);
+ await openEnFaceControls();
+ await expect(segmentEye(BLUE_NAME)).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ );
+ await setSegmentShown(BLUE_NAME, true);
+ await browser.keys('Escape');
+
+ const saved = await volViewPage.saveSession();
+ await waitForDownload(path.join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT);
+ await volViewPage.open(`?urls=[tmp/${saved}]`);
+ await waitForEnFaceReady();
+ await expectPixels([
+ [RED, 'gray'],
+ [BLUE, 'blue'],
+ [DEEP, 'gray'],
+ ]);
+ await openEnFaceControls();
+ await expectSettings();
+ await setSegmentShown(BLUE_NAME, false);
+ await expectPixels([[BLUE, 'gray']]);
+ expect(await volViewPage.getNotificationsCount()).toBe(0);
+ });
+});
diff --git a/tests/specs/oct-en-face.e2e.ts b/tests/specs/oct-en-face.e2e.ts
index 4c4918be0..c39f65049 100644
--- a/tests/specs/oct-en-face.e2e.ts
+++ b/tests/specs/oct-en-face.e2e.ts
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { Key } from 'webdriverio';
import {
+ setSegmentShown,
waitForEnFaceReady,
expectEnFaceDisabledInSwitcher,
setSlabRange,
@@ -16,9 +17,9 @@ import {
openEnFaceControls,
expandEnFaceSection,
selectSetting,
- THRESHOLD,
- setHighlight,
- setThicknessThreshold,
+ segmentThreshold,
+ segmentThresholdSlider,
+ setSegmentThreshold,
} from './octTestUtils';
import { TEMP_DIR } from '../../wdio.shared.conf';
import { volViewPage } from '../pageobjects/volview.page';
@@ -29,6 +30,7 @@ import {
waitForModuleTransitions,
} from './utils';
import { selectBasePalette } from './layerDisplayTestUtils';
+import { setSegmentVisible } from './segmentationTestUtils';
import { deflatedExplicitVR, nonOCTDicom } from '../fixtures/oct/volumes';
import { createSyntheticOCT } from '../fixtures/oct/dicom';
import { paddedSyntheticOCT } from '../fixtures/oct/padding';
@@ -60,28 +62,10 @@ describe('Retinal OCT en-face', () => {
await $(CONTROLS).doubleClick();
await expectBothViews();
await openEnFaceControls();
- await setHighlight(true);
- const inlineHelp = await $(
- '.v-overlay--active [data-testid="enface-thickness-help"]'
- ).execute((button) => {
- const text = button.parentElement?.parentElement?.firstChild;
- if (!text) return false;
- const range = document.createRange();
- range.selectNodeContents(text);
- const caption = range.getBoundingClientRect();
- const icon = button.getBoundingClientRect();
- return (
- icon.left >= caption.right &&
- icon.top < caption.bottom &&
- icon.bottom > caption.top
- );
- });
- expect(inlineHelp).toBe(true);
- await $(THRESHOLD).doubleClick();
+ await setSegmentShown('Synthetic retinal layer', true);
+ await segmentThreshold('Synthetic retinal layer').doubleClick();
await expectBothViews();
- await $(
- '.v-overlay--active [data-testid="enface-thickness-threshold"] [role="slider"]'
- ).doubleClick();
+ await segmentThresholdSlider('Synthetic retinal layer').doubleClick();
await expectBothViews();
await expandEnFaceSection('projection');
await slabThumb('start').doubleClick();
@@ -103,7 +87,7 @@ describe('Retinal OCT en-face', () => {
await openRetina();
expect(await $(WINDOW_TOOL).isEnabled()).toBe(true);
const compactPanel = await $(PANEL).getSize();
- expect(compactPanel.width).toBe(300);
+ expect(compactPanel.width).toBe(450);
expect(compactPanel.height).toBeGreaterThan(0);
expect(compactPanel.height).toBeLessThanOrEqual(320);
const contained = await $(PANEL).execute((panel) => {
@@ -116,7 +100,7 @@ describe('Retinal OCT en-face', () => {
);
});
expect(contained).toBe(true);
- for (const section of ['projection', 'thickness'])
+ for (const section of ['projection', 'segments'])
await expect(
$(PANEL).$('[data-testid="enface-' + section + '-toggle"]')
).toHaveAttribute('aria-expanded', 'true');
@@ -155,18 +139,18 @@ describe('Retinal OCT en-face', () => {
).toHaveValue('Sagittal');
await expect(slabThumb('start')).toHaveAttribute('aria-valuenow', '0');
await expect(slabThumb('end')).toHaveAttribute('aria-valuenow', '127');
- await expandEnFaceSection('thickness');
+ await expandEnFaceSection('segments');
await expect(
- $('.v-overlay--active [data-testid="enface-thin-highlight"] input')
- ).toBeDisabled();
- await expect($(THRESHOLD)).toBeDisabled();
+ $(PANEL).$('[data-testid="enface-segments-reason"]')
+ ).toHaveText(expect.stringContaining('Load or create a segmentation mask'));
await expect(
- $('.v-overlay--active [data-testid="enface-segmentation-segment"] input')
- ).toBeDisabled();
+ $(PANEL).$('[data-testid="enface-segment-row"]')
+ ).not.toExist();
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
it('shows slab values only during interaction and applies a drag on release', async () => {
+ const band = 'Synthetic retinal band';
await openRetina(true);
await waitForEnFaceReady();
const labels = $$(
@@ -174,18 +158,19 @@ describe('Retinal OCT en-face', () => {
);
expect(await labels.length).toBe(2);
for (const label of await labels) await expect(label).not.toBeDisplayed();
+ await browser.keys(Key.Escape);
+ await setSegmentVisible('Alternative synthetic band', false);
await setEnFaceWindow(1000, 500);
- await expectProjectionPixel(81);
await openEnFaceControls();
- const threshold = $(
- '.v-overlay--active [data-testid="enface-thickness-threshold"] [role="slider"]'
- );
- await setHighlight(true);
- await expect($(THRESHOLD)).toBeEnabled();
- await setThicknessThreshold(0);
+ const threshold = segmentThresholdSlider(band);
+ await setSegmentShown(band, true);
+ await expect(segmentThreshold(band)).toBeEnabled();
+ // A zero threshold draws no region, leaving the projection gray to sample.
+ await setSegmentThreshold(band, 0);
+ await expectProjectionPixel(81);
const thresholdMaximum = await threshold.getAttribute('aria-valuemax');
expect(Number(thresholdMaximum)).toBeGreaterThan(1);
- const thresholdValue = await $(THRESHOLD).getValue();
+ const thresholdValue = await segmentThreshold(band).getValue();
const start = slabThumb('start');
const end = slabThumb('end');
await start.scrollIntoView({ block: 'center', inline: 'nearest' });
@@ -215,7 +200,7 @@ describe('Retinal OCT en-face', () => {
'aria-valuemax',
thresholdMaximum!
);
- await expect($(THRESHOLD)).toHaveValue(thresholdValue);
+ await expect(segmentThreshold(band)).toHaveValue(thresholdValue);
await expectProjectionPixel(81);
expect(await readProjectionChanges()).toEqual([]);
} finally {
@@ -227,7 +212,7 @@ describe('Retinal OCT en-face', () => {
Math.round(((317 + draggedStart) * 255) / 1000)
);
await expect(threshold).toHaveAttribute('aria-valuemax', '0.1');
- await expect($(THRESHOLD)).toHaveValue(thresholdValue);
+ await expect(segmentThreshold(band)).toHaveValue(thresholdValue);
await browser.keys(Key.Home);
await expect(start).toHaveAttribute('aria-valuenow', '0');
await expectProjectionPixel(81);
diff --git a/tests/specs/oct-import.e2e.ts b/tests/specs/oct-import.e2e.ts
index f11e7f49e..517e51ff2 100644
--- a/tests/specs/oct-import.e2e.ts
+++ b/tests/specs/oct-import.e2e.ts
@@ -17,9 +17,9 @@ import {
openEnFaceProjection,
openEnFaceControls,
selectSetting,
- THRESHOLD,
- setThicknessThreshold,
- setHighlight,
+ segmentThreshold,
+ segmentEye,
+ setSegmentThreshold,
expectHighlight,
} from './octTestUtils';
import { TEMP_DIR } from '../../wdio.shared.conf';
@@ -85,13 +85,7 @@ describe('Retinal OCT import', () => {
await expectStackedMaskWithoutSidebar();
await openEnFaceControls();
- await setHighlight(true);
- expect(
- await $(
- '.v-overlay--active [data-testid="enface-segmentation-segment"]'
- ).getText()
- ).toContain('Synthetic retinal layer');
- await setThicknessThreshold(31);
+ await setSegmentThreshold('Synthetic retinal layer', 31);
await expectHighlight(true);
await expectControlsBesideSelector();
await browser.keys('Escape');
@@ -104,13 +98,12 @@ describe('Retinal OCT import', () => {
expect(await volViewPage.getFirst2DSlice()).toBe(retainedSlice);
await expectSliceLine();
await openEnFaceControls();
- await expandEnFaceSection('thickness');
- expect(
- await $(
- '.v-overlay--active [data-testid="enface-segmentation-segment"]'
- ).getText()
- ).toContain('Synthetic retinal layer');
- expect(Number(await $(THRESHOLD).getValue())).toBe(31);
+ await expandEnFaceSection('segments');
+ await expect(segmentEye('Synthetic retinal layer')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(segmentThreshold('Synthetic retinal layer')).toHaveValue('31');
await browser.keys('Escape');
await volViewPage.focusFirst2DView();
const before = await volViewPage.getFirst2DSlice();
diff --git a/tests/specs/oct-native-dicom.e2e.ts b/tests/specs/oct-native-dicom.e2e.ts
index 87dea4077..5e7630513 100644
--- a/tests/specs/oct-native-dicom.e2e.ts
+++ b/tests/specs/oct-native-dicom.e2e.ts
@@ -9,6 +9,7 @@ import { expectProjectionPixel } from './octInteractionTestUtils';
import { waitForFirstCachedImageSpacing } from './imageCacheUtils';
import { useReferenceLines } from './referenceLinesTestUtils';
import {
+ setSegmentShown,
canvasAppearance,
chooseEnFaceProjection,
projectionTransform,
@@ -26,11 +27,11 @@ import {
openEnFaceControls,
setEnFaceSlab,
selectSetting,
- setHighlight,
- setThicknessThreshold,
+ setSegmentThreshold,
expectHighlight,
- THRESHOLD,
- THRESHOLD_SLIDER,
+ segmentThreshold,
+ segmentThresholdSlider,
+ segmentEye,
} from './octTestUtils';
import {
openAnnotationSegments,
@@ -200,21 +201,26 @@ describe('Public OCT exports', () => {
await selectEnFace(1);
await waitForEnFaceReady();
await openEnFaceControls();
- for (const section of ['projection', 'thickness'])
+ for (const section of ['projection', 'segments'])
await expect(
$('[data-testid="enface-' + section + '-toggle"]')
).toHaveAttribute('aria-expanded', 'true');
await expandEnFaceSection('projection');
await selectSetting('enface-projection-axis', 'Coronal');
- await expandEnFaceSection('thickness');
- await expect(
- $('.v-overlay--active [data-testid="enface-segmentation-segment"] input')
- ).toBeEnabled();
- await setHighlight(true);
- await selectSetting('enface-segmentation-segment', names[2]);
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuemax', '58.1');
- await setThicknessThreshold(20);
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuenow', '20');
+ await expandEnFaceSection('segments');
+ for (const name of names)
+ await expect(segmentEye(name)).toHaveAttribute('aria-pressed', 'false');
+ await expect(segmentEye(names[2])).toBeEnabled();
+ await setSegmentShown(names[2], true);
+ await expect(segmentThresholdSlider(names[2])).toHaveAttribute(
+ 'aria-valuemax',
+ '58.1'
+ );
+ await setSegmentThreshold(names[2], 20);
+ await expect(segmentThresholdSlider(names[2])).toHaveAttribute(
+ 'aria-valuenow',
+ '20'
+ );
await $(
'.v-overlay--active [data-testid="enface-projection-toggle"]'
).click();
@@ -223,9 +229,9 @@ describe('Public OCT exports', () => {
.$('.v-expansion-panel-text')
.waitForDisplayed({ reverse: true });
await expect(
- $('.v-overlay--active [data-testid="enface-thickness-toggle"]')
+ $('.v-overlay--active [data-testid="enface-segments-toggle"]')
).toHaveAttribute('aria-expanded', 'true');
- await expect($(THRESHOLD)).toHaveValue('20');
+ await expect(segmentThreshold(names[2])).toHaveValue('20');
const captureDirectory = process.env.VOLVIEW_OCT_CAPTURE_DIR;
if (captureDirectory) {
fs.mkdirSync(captureDirectory, { recursive: true });
diff --git a/tests/specs/oct-navigation.e2e.ts b/tests/specs/oct-navigation.e2e.ts
index c24db46fb..dcf83e205 100644
--- a/tests/specs/oct-navigation.e2e.ts
+++ b/tests/specs/oct-navigation.e2e.ts
@@ -19,8 +19,9 @@ import {
openEnFaceProjection,
openEnFaceControls,
selectSetting,
- setThicknessThreshold,
- setHighlight,
+ segmentThreshold,
+ segmentEye,
+ setSegmentThreshold,
expectHighlight,
} from './octTestUtils';
import { TEMP_DIR } from '../../wdio.shared.conf';
@@ -351,8 +352,7 @@ describe('Retinal OCT navigation', () => {
// Select before capturing the comparison with a textured overlay.
await $('button[data-testid^="control-button-Select "]').click();
await openEnFaceControls();
- await setHighlight(true);
- await setThicknessThreshold(31);
+ await setSegmentThreshold('Synthetic retinal layer', 31);
await expectHighlight(true);
await expectSliceLine();
await expectControlsBesideSelector();
@@ -378,12 +378,12 @@ describe('Retinal OCT navigation', () => {
await $(CANVAS).waitForDisplayed();
await expectHighlight(true);
await openEnFaceControls();
- await expandEnFaceSection('thickness');
- expect(
- await $(
- '.v-overlay--active [data-testid="enface-segmentation-segment"]'
- ).getText()
- ).toContain('Synthetic retinal layer');
+ await expandEnFaceSection('segments');
+ await expect(segmentEye('Synthetic retinal layer')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(segmentThreshold('Synthetic retinal layer')).toHaveValue('31');
await browser.keys('Escape');
await expectSliceLine();
expect(await getWindow()).toEqual(savedWindow);
diff --git a/tests/specs/oct-occupied-depth.e2e.ts b/tests/specs/oct-occupied-depth.e2e.ts
index 7a2a486c7..3b70d3412 100644
--- a/tests/specs/oct-occupied-depth.e2e.ts
+++ b/tests/specs/oct-occupied-depth.e2e.ts
@@ -1,10 +1,9 @@
import fs from 'node:fs';
import path from 'node:path';
import JSZip from 'jszip';
-import { createNrrdVolume, createVtiVolume } from '../fixtures/oct/volumes';
import { Key } from 'webdriverio';
+import { createNrrdVolume, createVtiVolume } from '../fixtures/oct/volumes';
import {
- PANEL,
enFaceAppearance,
enFacePixel,
waitForEnFaceReady,
@@ -15,12 +14,14 @@ import {
slabThumb,
selectEnFace,
openEnFaceControls,
+ openEnFaceSidebarControls,
selectSetting,
- THRESHOLD,
- THRESHOLD_SLIDER,
+ segmentThreshold,
+ segmentThresholdSlider,
+ segmentEye,
attachAndSelectMask,
- setThicknessThreshold,
- setHighlight,
+ setSegmentShown,
+ setSegmentThreshold,
expectHighlight,
} from './octTestUtils';
import { TEMP_DIR } from '../../wdio.shared.conf';
@@ -30,18 +31,29 @@ import {
openThroughDialog,
waitForDownload,
SESSION_SAVE_TIMEOUT,
- waitForModuleTransitions,
} from './utils';
-import { setSegmentationDisplaySlider as setDisplaySlider } from './segmentationTestUtils';
+import {
+ setSegmentationDisplaySlider as setDisplaySlider,
+ setSegmentVisible,
+} from './segmentationTestUtils';
import {
STEM,
stageFixture,
- expectProjectionPixel,
openHighlightedSegmentationDisplay,
openRetina,
registerOctTestHooks,
} from './octInteractionTestUtils';
+const BAND = 'Synthetic retinal band';
+const ALTERNATIVE = 'Alternative synthetic band';
+
+/** Leaves the popup closed so each test opens the controls it needs. */
+async function openRetinaWithBand() {
+ await openRetina(true);
+ await browser.keys('Escape');
+ await setSegmentVisible(ALTERNATIVE, false);
+}
+
async function stageDepthScene() {
const directory = makeTempDir(STEM);
const name = 'depth';
@@ -108,9 +120,12 @@ async function stageDepthScene() {
method: 'mean',
depthStart: 0,
depthEnd: null,
- highlightThin: true,
- thresholdMicrons: 3000,
- segmentId: 'band',
+ segmentProjections: {
+ band: {
+ visible: true,
+ thresholdMicrons: 3000,
+ },
+ },
},
},
},
@@ -130,63 +145,85 @@ async function stageDepthScene() {
describe('Retinal OCT occupied-depth', () => {
registerOctTestHooks();
- it('highlights physical thickness and restores its selected segment, threshold and slab', async () => {
- await openRetina(true);
- await setHighlight(true);
- await setThicknessThreshold(31);
+ it('highlights physical thickness per segment and restores each threshold and the slab', async () => {
+ await openRetinaWithBand();
+ await openEnFaceControls();
+ await setSegmentThreshold(BAND, 31);
await expectHighlight(true);
- const expectThinColumns = async () => {
+ // Either tint leaves blue as the untinted reference channel.
+ const tinted = (channel: number) => (pixel: number[]) =>
+ pixel[channel] > pixel[2] + 20;
+ const untinted = (channel: number) => (pixel: number[]) =>
+ pixel[channel] === pixel[2];
+ const expectColumns = async (alternativeDrawn: boolean) => {
+ await waitForEnFaceReady();
+ const alternative = (alternativeDrawn ? tinted : untinted)(1);
await browser.waitUntil(
async () => {
const thin = await enFacePixel(20, 12);
const thick = await enFacePixel(60, 12);
const absent = await enFacePixel(100, 12);
return (
- thin[0] > thin[1] + 20 &&
- thick[0] === thick[1] &&
- absent[0] === absent[1]
+ tinted(0)(thin) &&
+ untinted(0)(thick) &&
+ untinted(0)(absent) &&
+ [thin, thick, absent].every(alternative)
);
},
{
timeoutMsg:
- 'Only positive thickness below the threshold should be highlighted',
+ 'Only positive thickness below each threshold should be highlighted' +
+ (alternativeDrawn ? ', over the alternative band' : ''),
}
);
};
+ const expectThinColumns = () => expectColumns(false);
await expectThinColumns();
- const slider = $(THRESHOLD_SLIDER);
- await $(THRESHOLD).click();
- await browser.keys('Tab');
+ const threshold = segmentThreshold(BAND);
+ const slider = segmentThresholdSlider(BAND);
+ await threshold.click();
+ await browser
+ .action('key')
+ .down(Key.Shift)
+ .down(Key.Tab)
+ .up(Key.Tab)
+ .up(Key.Shift)
+ .perform();
await expect(slider).toBeFocused();
await browser.keys('ArrowRight');
- await expect($(THRESHOLD)).toHaveValue('31.1');
+ await expect(threshold).toHaveValue('31.1');
await browser.keys('Home');
- await expect($(THRESHOLD)).toHaveValue('0');
+ await expect(threshold).toHaveValue('0');
await expectHighlight(false);
- const maximum = await slider.getAttribute('aria-valuemax');
await browser.keys('End');
- await expect($(THRESHOLD)).toHaveValue(maximum!);
+ await expect(threshold).toHaveValue('');
await expectHighlight(true);
- await setThicknessThreshold(20.8);
+ await setSegmentThreshold(BAND, 20.8);
await expectHighlight(false);
- await setThicknessThreshold(31);
+ await setSegmentThreshold(BAND, 31);
await expectHighlight(true);
await expectThinColumns();
await expandEnFaceSection('projection');
await setSlabRange(0, 10);
await expectHighlight(false);
await expect(slider).toHaveAttribute('aria-valuemax', '0.1');
- await expect($(THRESHOLD)).toHaveValue('31');
+ await expect(threshold).toHaveValue('31');
await setSlabRange(100, 114);
await expectHighlight(true);
await expectThinColumns();
- await selectSetting(
- 'enface-segmentation-segment',
- 'Alternative synthetic band'
- );
- await expectHighlight(false);
- await setThicknessThreshold(60);
- await expectHighlight(true);
+
+ await expect(segmentEye(ALTERNATIVE)).toBeDisabled();
+ await browser.keys('Escape');
+ await setSegmentVisible(ALTERNATIVE, true);
+ await openEnFaceControls();
+ await setSegmentShown(ALTERNATIVE, true);
+ await expectColumns(true);
+ await setSegmentThreshold(ALTERNATIVE, 50);
+ await expectThinColumns();
+ await setSegmentThreshold(ALTERNATIVE, 60);
+ const expectBothThin = () => expectColumns(true);
+ await expectBothThin();
+ await expandEnFaceSection('projection');
await selectSetting('enface-projection-method', 'Maximum');
await waitForEnFaceReady();
await browser.keys('Escape');
@@ -194,7 +231,7 @@ describe('Retinal OCT occupied-depth', () => {
await waitForDownload(path.join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT);
await volViewPage.open('?urls=[tmp/' + saved + ']');
await waitForEnFaceReady();
- await expectHighlight(true);
+ await expectBothThin();
await openEnFaceControls();
await expandEnFaceSection('projection');
await expect(
@@ -202,14 +239,14 @@ describe('Retinal OCT occupied-depth', () => {
).toHaveValue('Maximum');
await expect(slabThumb('start')).toHaveAttribute('aria-valuenow', '100');
await expect(slabThumb('end')).toHaveAttribute('aria-valuenow', '114');
- await expandEnFaceSection('thickness');
- await expect($(THRESHOLD)).toHaveValue('60');
- await expect(
- $('.v-overlay--active [data-testid="enface-segmentation-segment"]')
- ).toHaveText(expect.stringContaining('Alternative synthetic band'));
- await expect(
- $('.v-overlay--active [data-testid="enface-thin-highlight"] input')
- ).toBeSelected();
+ await expandEnFaceSection('segments');
+ for (const [name, value] of [
+ [BAND, '31'],
+ [ALTERNATIVE, '60'],
+ ]) {
+ await expect(segmentEye(name)).toHaveAttribute('aria-pressed', 'true');
+ await expect(segmentThreshold(name)).toHaveValue(value);
+ }
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
@@ -219,10 +256,11 @@ describe('Retinal OCT occupied-depth', () => {
await waitForEnFaceReady();
await setEnFaceWindow(200, 100);
await openEnFaceControls();
- await expandEnFaceSection('thickness');
- await expect(
- $('.v-overlay--active [data-testid="enface-thin-highlight"] input')
- ).toBeEnabled();
+ await expandEnFaceSection('segments');
+ const eye = segmentEye('Depth band');
+ await expect(eye).toBeEnabled();
+ await expect(eye).toHaveAttribute('aria-pressed', 'true');
+ await expect(segmentThreshold('Depth band')).toHaveValue('3000');
const slabs = [
[0, 7, [true, false, false]],
[0, 1, [false, false, false]],
@@ -263,49 +301,43 @@ describe('Retinal OCT occupied-depth', () => {
await selectSetting('enface-projection-axis', 'Coronal');
await waitForEnFaceReady();
await browser.keys('Escape');
- await attachAndSelectMask(
- stageFixture('synthetic-thickness.nrrd'),
- 'Synthetic retinal band'
- );
+ await attachAndSelectMask(stageFixture('synthetic-thickness.nrrd'), BAND);
+ await setSegmentVisible(ALTERNATIVE, false);
await openEnFaceControls();
- await expandEnFaceSection('thickness');
- await expect(
- $('.v-overlay--active [data-testid="enface-thin-highlight"] input')
- ).toBeEnabled();
- await setHighlight(true);
- await setThicknessThreshold(1);
+ await expandEnFaceSection('segments');
+ await expect(segmentEye(BAND)).toBeEnabled();
+ await setSegmentThreshold(BAND, 1);
await expectHighlight(false);
- await setThicknessThreshold(31);
+ await setSegmentThreshold(BAND, 31);
await expectHighlight(true);
- await browser.keys(Key.Escape);
- await $(PANEL).waitForDisplayed({ reverse: true });
- await volViewPage.renderingModuleTab.click();
- await waitForModuleTransitions();
- const toggle = $('[data-testid="enface-rendering-toggle"]');
- await toggle.scrollIntoView({ block: 'center', behavior: 'instant' });
- await toggle.waitForClickable();
- if ((await toggle.getAttribute('aria-expanded')) !== 'true')
- await toggle.click();
- const sidebar = $('[data-testid="enface-sidebar-controls"]');
- await sidebar.waitForDisplayed();
- await toggle.$('..').waitForStable();
- for (const selector of [
- '[data-testid="enface-thin-highlight"] input',
- '[data-testid="enface-segmentation-segment"] input',
- '[data-testid="enface-thickness-threshold-input"] input',
- ])
- await expect(sidebar.$(selector)).toBeEnabled();
- await expect(
- sidebar.$('[data-testid="enface-thickness-threshold-input"] input')
- ).toHaveValue('31');
+ const sidebar = await openEnFaceSidebarControls();
+ await expandEnFaceSection('segments', sidebar);
+ await expect(segmentEye(BAND, sidebar)).toBeEnabled();
+ await expect(segmentEye(BAND, sidebar)).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(segmentThreshold(BAND, sidebar)).toBeEnabled();
+ await expect(segmentThreshold(BAND, sidebar)).toHaveValue('31');
await expectHighlight(true);
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
it('renders below-threshold labels with normal fill, outline and visibility controls', async () => {
await openRetina(true);
+ // Keeps the alternative band, which no control here hides, out of the slab.
+ await setSlabRange(100, 105);
+ await browser.keys('Escape');
+ const toggleEverySegment = () =>
+ $('[data-testid="toggle-segments-visible-button"]').click();
+ await toggleEverySegment();
+ await expectHighlight(false);
+ const unwindowed = JSON.stringify(await enFacePixel(60, 12));
await setEnFaceWindow(1000, 500);
- await expectProjectionPixel(81);
+ // Baselines must come from a frame drawn with the new window.
+ await browser.waitUntil(
+ async () => JSON.stringify(await enFacePixel(60, 12)) !== unwindowed
+ );
const interior = () => enFacePixel(20, 12);
const boundary = () => enFacePixel(42.5, 12, { x: -2, y: 0 });
const innerBoundary = () => enFacePixel(42.5, 12, { x: -12, y: 0 });
@@ -335,7 +367,8 @@ describe('Retinal OCT occupied-depth', () => {
? 255
: Math.round(channel * (1 - alpha) + (index === 0 ? 255 : 0) * alpha)
);
- await openHighlightedSegmentationDisplay();
+ await toggleEverySegment();
+ await openHighlightedSegmentationDisplay(BAND);
await setDisplaySlider('Outline Thickness', 10);
await setDisplaySlider('Fill Opacity', 0);
@@ -365,11 +398,11 @@ describe('Retinal OCT occupied-depth', () => {
await expectPixel(boundary, [255, 0, 0, 255]);
await expectPixel(interior, baseline.interior);
- await $('[data-testid="toggle-segments-visible-button"]').click();
+ await toggleEverySegment();
await expectHighlight(false);
await setDisplaySlider('Fill Opacity', 1);
await expectHighlight(false);
- await $('[data-testid="toggle-segments-visible-button"]').click();
+ await toggleEverySegment();
await expectPixel(interior, [255, 0, 0, 255]);
await expectPixel(boundary, [255, 0, 0, 255]);
});
diff --git a/tests/specs/octInteractionTestUtils.ts b/tests/specs/octInteractionTestUtils.ts
index 51d173d5d..7d9a6ef98 100644
--- a/tests/specs/octInteractionTestUtils.ts
+++ b/tests/specs/octInteractionTestUtils.ts
@@ -12,8 +12,7 @@ import {
displayedWindow,
selectEnFace,
openEnFaceControls,
- setHighlight,
- setThicknessThreshold,
+ setSegmentThreshold,
expectHighlight,
CANVAS,
CONTROLS,
@@ -52,7 +51,7 @@ export async function observeSlabProjectionChanges() {
await browser.execute(() => {
const viewer = document.querySelector('[data-testid="enface-viewer"]')!;
const threshold = document.querySelector(
- '.v-overlay--active [data-testid="enface-thickness-threshold"] [role="slider"]'
+ '.v-overlay--active [data-testid="enface-segment-threshold"] [role="slider"]'
)!;
const changes: string[] = [];
const observer = new MutationObserver((records) => {
@@ -103,10 +102,9 @@ export async function getOriginalWindow() {
return displayedWindow(source);
}
-export async function openHighlightedSegmentationDisplay() {
+export async function openHighlightedSegmentationDisplay(segment: string) {
await openEnFaceControls();
- await setHighlight(true);
- await setThicknessThreshold(31);
+ await setSegmentThreshold(segment, 31);
await expectHighlight(true);
await browser.keys('Escape');
await openSegmentDisplay();
diff --git a/tests/specs/octTestUtils.ts b/tests/specs/octTestUtils.ts
index 4693d4066..fbf95ecb6 100644
--- a/tests/specs/octTestUtils.ts
+++ b/tests/specs/octTestUtils.ts
@@ -138,12 +138,6 @@ export const VIEWER = '[data-testid="enface-viewer"]';
export const CONTROLS = '[data-testid="enface-controls"]';
export const PANEL =
'.v-overlay--active [data-testid="enface-rendering-panel"]';
-export const THRESHOLD =
- PANEL + ' [data-testid="enface-thickness-threshold-input"] input';
-export const THRESHOLD_SLIDER =
- PANEL + ' [data-testid="enface-thickness-threshold"] [role="slider"]';
-export const HIGHLIGHT_TOGGLE =
- PANEL + ' [data-testid="enface-thin-highlight"]';
export const WINDOW_TOOL =
'button[data-testid^="control-button-Window & Level "]';
export const toolButton = (name: string) =>
@@ -153,9 +147,10 @@ export const windowedGray = (
value: number,
{ width, level }: { width: number; level: number }
) => Math.round(255 * Math.min(1, Math.max(0, (value - level) / width + 0.5)));
-type EnFaceSection = 'projection' | 'thickness';
-const sectionToggle = (section: EnFaceSection) =>
- '.v-overlay--active [data-testid="enface-' + section + '-toggle"]';
+const SECTIONS = ['projection', 'segments'] as const;
+type EnFaceSection = (typeof SECTIONS)[number];
+const sectionToggle = (section: EnFaceSection, scope = PANEL) =>
+ scope + ' [data-testid="enface-' + section + '-toggle"]';
const enFaceView = async (view?: WebdriverIO.Element) =>
view ?? $(VIEWER).getElement();
@@ -190,9 +185,10 @@ export async function displayedWindow(view: WebdriverIO.Element) {
}
export async function expandEnFaceSection(
- section: EnFaceSection = 'projection'
+ section: EnFaceSection = 'projection',
+ scope = PANEL
) {
- const toggle = $(sectionToggle(section));
+ const toggle = $(sectionToggle(section, scope));
await toggle.scrollIntoView({ block: 'center', inline: 'nearest' });
await toggle.waitForClickable();
if ((await toggle.getAttribute('aria-expanded')) !== 'true')
@@ -201,7 +197,7 @@ export async function expandEnFaceSection(
const content = toggle.$('..').$('.v-expansion-panel-text');
await content.waitForDisplayed();
await content.waitForStable();
- await $(PANEL).waitForStable();
+ await $(scope).waitForStable();
}
export async function openEnFaceControls(view?: WebdriverIO.Element) {
@@ -211,21 +207,65 @@ export async function openEnFaceControls(view?: WebdriverIO.Element) {
await panel.waitForStable();
}
-export async function setThicknessThreshold(value: number) {
- await expandEnFaceSection('thickness');
- const input = $(THRESHOLD);
- await input.scrollIntoView({ block: 'center', inline: 'nearest' });
- await input.waitForClickable();
- await setValueVueInput(input, String(value));
+export async function openEnFaceSidebarControls() {
+ await browser.keys(Key.Escape);
+ await $(PANEL).waitForDisplayed({ reverse: true });
+ await volViewPage.renderingModuleTab.click();
+ await waitForModuleTransitions();
+ const toggle = $('[data-testid="enface-rendering-toggle"]');
+ await toggle.scrollIntoView({ block: 'center', behavior: 'instant' });
+ await toggle.waitForClickable();
+ if ((await toggle.getAttribute('aria-expanded')) !== 'true')
+ await toggle.click();
+ const sidebar = '[data-testid="enface-sidebar-controls"]';
+ await $(sidebar).waitForDisplayed();
+ await toggle.$('..').waitForStable();
+ return sidebar;
}
-export async function setHighlight(enabled: boolean) {
- await expandEnFaceSection('thickness');
- const label = $(HIGHLIGHT_TOGGLE + ' label');
- await label.scrollIntoView({ block: 'center', inline: 'nearest' });
- await label.waitForClickable();
- if ((await $(HIGHLIGHT_TOGGLE + ' input').isSelected()) !== enabled)
- await label.click();
+export const enFaceSegmentRow = (name: string, scope = PANEL) =>
+ $(scope).$(
+ '[data-testid="enface-segment-row"][data-segment-name="' + name + '"]'
+ );
+
+export const segmentEye = (name: string, scope = PANEL) =>
+ enFaceSegmentRow(name, scope).$('[data-testid="enface-segment-visible"]');
+
+export const segmentThreshold = (name: string, scope = PANEL) =>
+ enFaceSegmentRow(name, scope).$(
+ '[data-testid="enface-segment-threshold-input"] input'
+ );
+
+export const segmentThresholdSlider = (name: string, scope = PANEL) =>
+ enFaceSegmentRow(name, scope).$(
+ '[data-testid="enface-segment-threshold"] [role="slider"]'
+ );
+
+export async function setSegmentShown(
+ name: string,
+ shown: boolean,
+ scope = PANEL
+) {
+ await expandEnFaceSection('segments', scope);
+ const eye = segmentEye(name, scope);
+ await eye.scrollIntoView({ block: 'center', inline: 'nearest' });
+ await eye.waitForClickable();
+ if ((await eye.getAttribute('aria-pressed')) !== String(shown))
+ await eye.click();
+ await expect(eye).toHaveAttribute('aria-pressed', String(shown));
+}
+
+/** Null keeps every region of the segment. */
+export async function setSegmentThreshold(
+ name: string,
+ value: number | null,
+ scope = PANEL
+) {
+ await setSegmentShown(name, true, scope);
+ const input = segmentThreshold(name, scope);
+ await input.scrollIntoView({ block: 'center', inline: 'nearest' });
+ await input.waitForClickable();
+ await setValueVueInput(input, value === null ? '' : String(value));
}
export async function expectHighlight(present: boolean) {
@@ -564,9 +604,8 @@ export async function getEnFaceWindow(view?: WebdriverIO.Element) {
const controls = viewer.$(CONTROLS);
const restorePanel =
(await controls.getAttribute('aria-expanded')) === 'true';
- const sections = ['projection', 'thickness'] as const;
const expanded = await Promise.all(
- sections.map(
+ SECTIONS.map(
async (section) =>
restorePanel &&
(await $(sectionToggle(section)).getAttribute('aria-expanded')) ===
@@ -589,7 +628,7 @@ export async function getEnFaceWindow(view?: WebdriverIO.Element) {
const reopened = $(PANEL);
await reopened.waitForDisplayed();
await reopened.waitForStable();
- for (const [index, section] of sections.entries()) {
+ for (const [index, section] of SECTIONS.entries()) {
const toggle = $(sectionToggle(section));
if (expanded[index]) {
await expandEnFaceSection(section);
diff --git a/tests/specs/projection-camera.e2e.ts b/tests/specs/projection-camera.e2e.ts
index 4f07f4402..56aa3b145 100644
--- a/tests/specs/projection-camera.e2e.ts
+++ b/tests/specs/projection-camera.e2e.ts
@@ -22,11 +22,10 @@ import {
openEnFaceProjection,
openEnFaceControls,
selectSetting,
- setHighlight,
- setThicknessThreshold,
+ setSegmentThreshold,
expectHighlight,
- HIGHLIGHT_TOGGLE,
- THRESHOLD,
+ segmentThreshold,
+ segmentEye,
} from './octTestUtils';
import {
makeTempDir,
@@ -237,16 +236,15 @@ describe('Projection camera persistence', () => {
await stageCameraScene();
await openCameraScene();
await waitForEnFaceReady();
- await attachAndSelectMask(STEM + '/' + MASK_NAME, SEGMENT_NAME);
await openEnFaceProjection();
await selectSetting('enface-projection-axis', 'Sagittal');
await setSlabRange(10, 100);
await waitForEnFaceReady();
+ // Captured before the mask exists, as the restore shows it while decoding.
const baseProjection = await panAndZoom();
+ await attachAndSelectMask(STEM + '/' + MASK_NAME, SEGMENT_NAME);
await openEnFaceControls();
- await setHighlight(true);
- await selectSetting('enface-segmentation-segment', SEGMENT_NAME);
- await setThicknessThreshold(6500);
+ await setSegmentThreshold(SEGMENT_NAME, 6500);
await expectHighlight(true);
await expectProjectionTransform(baseProjection.transform);
const inspected = {
@@ -266,12 +264,12 @@ describe('Projection camera persistence', () => {
await expectCameraAndPixels(inspected);
await openEnFaceControls();
await expectEnFaceProjectionSettings('Sagittal', 10, 100);
- await expandEnFaceSection('thickness');
- await expect(
- $('.v-overlay--active [data-testid="enface-segmentation-segment"]')
- ).toHaveText(expect.stringContaining(SEGMENT_NAME));
- await expect($(HIGHLIGHT_TOGGLE + ' input')).toBeSelected();
- await expect($(THRESHOLD)).toHaveValue('6500');
+ await expandEnFaceSection('segments');
+ await expect(segmentEye(SEGMENT_NAME)).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(segmentThreshold(SEGMENT_NAME)).toHaveValue('6500');
await expectHighlight(true);
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
diff --git a/tests/specs/projection-contrast.e2e.ts b/tests/specs/projection-contrast.e2e.ts
index e6d8cb91e..f0fc3e0fa 100644
--- a/tests/specs/projection-contrast.e2e.ts
+++ b/tests/specs/projection-contrast.e2e.ts
@@ -28,6 +28,8 @@ import {
writeManifestToFile,
} from './utils';
+import { openAnnotationSegments } from './segmentationTestUtils';
+
const STEM = 'projection-contrast';
function stageSumContrastControl(
@@ -161,6 +163,16 @@ describe('Projection default contrast', () => {
await sample.waitForClickable();
await sample.click();
await waitForEnFaceReady();
+ // The sample's layers would tint the projection this test measures.
+ await openAnnotationSegments();
+ const everySegment = $('[data-testid="toggle-segments-visible-button"]');
+ await everySegment.waitForEnabled();
+ await everySegment.click();
+ await expect(everySegment).toHaveAttribute(
+ 'aria-label',
+ 'Show every segment'
+ );
+ await waitForEnFaceReady();
await expectVisibleContrast(35);
});
diff --git a/tests/specs/segmentationTestUtils.ts b/tests/specs/segmentationTestUtils.ts
index ae2cd4b5d..760fdb3d3 100644
--- a/tests/specs/segmentationTestUtils.ts
+++ b/tests/specs/segmentationTestUtils.ts
@@ -31,6 +31,16 @@ export const segmentRow = async (name: string) => {
return row as NonNullable;
};
+const eyeButton = (visible: boolean) =>
+ 'button:has(i.' + (visible ? 'mdi-eye' : 'mdi-eye-off') + ')';
+
+export const setSegmentVisible = async (name: string, visible: boolean) => {
+ const row = await segmentRow(name);
+ if (await row.$(eyeButton(!visible)).isExisting())
+ await row.$(eyeButton(!visible)).click();
+ await row.$(eyeButton(visible)).waitForExist();
+};
+
export const segmentColor = async (name: string) => {
const row = await segmentRow(name);
const dot = await row.$('.color-dot');
diff --git a/tests/specs/slab-occupied-depth.e2e.ts b/tests/specs/slab-occupied-depth.e2e.ts
index 719fd4bca..860f6d41b 100644
--- a/tests/specs/slab-occupied-depth.e2e.ts
+++ b/tests/specs/slab-occupied-depth.e2e.ts
@@ -22,14 +22,15 @@ import {
enFacePixel,
expandEnFaceSection,
openEnFaceControls,
- setHighlight,
+ segmentThreshold,
+ segmentThresholdSlider,
+ segmentEye,
+ setSegmentShown,
+ setSegmentThreshold,
setSlabRange,
- setThicknessThreshold,
slabThumb,
waitForEnFaceReady,
PANEL,
- THRESHOLD,
- THRESHOLD_SLIDER,
} from './octTestUtils';
import {
openSegmentDisplay,
@@ -37,7 +38,12 @@ import {
} from './segmentationTestUtils';
const STEM = 'slab-occupied-depth';
+const GAPPED = 'Gapped band';
+const BAND = 'Synthetic retinal band';
+const ALTERNATIVE = 'Alternative synthetic band';
+const DIRECTIONAL = 'Directional band';
+/** Whether the red band tints the pixel, as a thin region or a plain footprint. */
async function expectHighlighted(present: boolean, point = [60, 12]) {
await waitForEnFaceReady();
await browser.waitUntil(
@@ -46,7 +52,7 @@ async function expectHighlighted(present: boolean, point = [60, 12]) {
return present ? pixel[0] > pixel[1] + 20 : pixel[0] === pixel[1];
},
{
- timeoutMsg: `Expected the selected slab to ${present ? 'qualify' : 'not qualify'} for highlighting`,
+ timeoutMsg: `Expected the selected slab to ${present ? 'draw' : 'not draw'} the band`,
}
);
}
@@ -72,12 +78,10 @@ async function openGappedMask(twoViews = false) {
'?urls=[tmp/' + STEM + '.json,tmp/' + STEM + '/retina.dcm]'
);
await waitForEnFaceReady();
- await attachAndSelectMask(
- STEM + '/gapped-band.nrrd',
- twoViews ? 'Synthetic retinal band' : 'Gapped band'
- );
+ const segment = twoViews ? BAND : GAPPED;
+ await attachAndSelectMask(STEM + '/gapped-band.nrrd', segment);
await openEnFaceControls();
- await setHighlight(true);
+ await setSegmentShown(segment, true);
}
async function openAxisMask(axis: number) {
@@ -114,7 +118,7 @@ async function openAxisMask(axis: number) {
units: [],
metadata: {
Segment0_LabelValue: '1',
- Segment0_Name: 'Directional band',
+ Segment0_Name: DIRECTIONAL,
Segment0_Color: '1 0 0',
},
})
@@ -127,13 +131,13 @@ async function openAxisMask(axis: number) {
'?urls=[tmp/' + STEM + '.json,tmp/' + STEM + '/' + sourceFile + ']'
);
await waitForEnFaceReady();
- await attachAndSelectMask(STEM + '/' + maskFile, 'Directional band');
+ await attachAndSelectMask(STEM + '/' + maskFile, DIRECTIONAL);
await chooseEnFaceProjection(
'enface-projection-axis',
['Sagittal', 'Coronal', 'Axial'][axis]
);
await openEnFaceControls();
- await setHighlight(true);
+ await setSegmentShown(DIRECTIONAL, true);
return spacing[axis] * 1000;
}
@@ -155,14 +159,13 @@ describe('Selected-slab occupied depth', () => {
await expandEnFaceSection('projection');
await setSlabRange(first, last);
await waitForEnFaceReady();
- await expandEnFaceSection('thickness');
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute(
+ await expect(segmentThresholdSlider(GAPPED)).toHaveAttribute(
'aria-valuemax',
String(maximum)
);
- await setThicknessThreshold(occupied);
+ await setSegmentThreshold(GAPPED, occupied);
await expectHighlighted(false);
- await setThicknessThreshold(occupied + 0.1);
+ await setSegmentThreshold(GAPPED, occupied + 0.1);
await expectHighlighted(true);
const absent = await enFacePixel(0, 12);
expect(absent[0]).toBe(absent[1]);
@@ -170,24 +173,35 @@ describe('Selected-slab occupied depth', () => {
await expandEnFaceSection('projection');
await setSlabRange(102, 103);
await waitForEnFaceReady();
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuemax', '0.1');
- await expect($(THRESHOLD)).toHaveValue('41.7');
+ await expect(segmentThresholdSlider(GAPPED)).toHaveAttribute(
+ 'aria-valuemax',
+ '0.1'
+ );
+ await expect(segmentThreshold(GAPPED)).toHaveValue('41.7');
await expectHighlighted(false);
- await setHighlight(false);
await expandEnFaceSection('projection');
await setSlabRange(100, 105);
- await waitForEnFaceReady();
+ await setSegmentThreshold(GAPPED, 41.6);
await expectHighlighted(false);
- await setHighlight(true);
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuemax', '41.7');
+ await setSegmentThreshold(GAPPED, null);
+ await expect(segmentThreshold(GAPPED)).toHaveValue('');
+ await expect(segmentThresholdSlider(GAPPED)).toHaveAttribute(
+ 'aria-valuenow',
+ '41.7'
+ );
await expectHighlighted(true);
+ await setSegmentThreshold(GAPPED, 41.6);
+ await expectHighlighted(false);
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
it('remeasures mask storage grown by painting in an ordinary source slice', async () => {
await openGappedMask();
- await setThicknessThreshold(50);
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuemax', '41.7');
+ await setSegmentThreshold(GAPPED, 50);
+ await expect(segmentThresholdSlider(GAPPED)).toHaveAttribute(
+ 'aria-valuemax',
+ '41.7'
+ );
await browser.keys(Key.Escape);
await $(PANEL).waitForDisplayed({ reverse: true });
const source = $('[data-testid~="vtk-two-view"]');
@@ -223,40 +237,34 @@ describe('Selected-slab occupied depth', () => {
{ timeoutMsg: 'Expected the thicker painted column to stop qualifying.' }
);
await openEnFaceControls();
- await expandEnFaceSection('thickness');
+ await expandEnFaceSection('segments');
await browser.waitUntil(
async () =>
- Number(await $(THRESHOLD_SLIDER).getAttribute('aria-valuemax')) > 41.7,
+ Number(
+ await segmentThresholdSlider(GAPPED).getAttribute('aria-valuemax')
+ ) > 41.7,
{
timeoutMsg:
'Expected the fitted thickness maximum to reflect source mask growth.',
}
);
- await expect($(THRESHOLD)).toHaveValue('50');
+ await expect(segmentThreshold(GAPPED)).toHaveValue('50');
expect(await volViewPage.getNotificationsCount()).toBe(0);
});
- it('restores different selected segments, slabs, thresholds and enabled states in two panes', async () => {
+ it('restores different thin segments, slabs, thresholds and enabled states in two panes', async () => {
await openGappedMask(true);
const panes = await $$('[data-testid="enface-viewer"]').map((view) =>
view.getElement()
);
- await setThicknessThreshold(31);
+ await setSegmentThreshold(BAND, 31);
await expandEnFaceSection('projection');
await setSlabRange(100, 103);
await browser.keys(Key.Escape);
await openEnFaceControls(panes[1]);
- await setHighlight(true);
- await chooseEnFaceProjection(
- 'enface-segmentation-segment',
- 'Alternative synthetic band',
- panes[1]
- );
- await openEnFaceControls(panes[1]);
- await setThicknessThreshold(60);
await expandEnFaceSection('projection');
await setSlabRange(110, 114);
- await setHighlight(false);
+ await setSegmentShown(ALTERNATIVE, true);
await browser.keys(Key.Escape);
await openSegmentDisplay();
await setSegmentationDisplaySlider('Fill Opacity', 0.5);
@@ -267,16 +275,22 @@ describe('Selected-slab occupied depth', () => {
const [r, g] = await firstPixel();
return r > g + 20;
},
+ {
+ timeoutMsg: 'Expected the first pane to show its thin band.',
+ }
+ );
+ const secondPixel = () => enFacePixel(60, 12, undefined, panes[1]);
+ await browser.waitUntil(
+ async () => {
+ const [r, g] = await secondPixel();
+ return g > r + 20;
+ },
{
timeoutMsg:
- 'Expected only the first pane to show its selected thin band.',
+ 'Expected the second pane to draw its whole band with Thin off.',
}
);
- const expected = [
- await firstPixel(),
- await enFacePixel(60, 12, undefined, panes[1]),
- ];
- expect(expected[1][0]).toBe(expected[1][1]);
+ const expected = [await firstPixel(), await secondPixel()];
const saved = await volViewPage.saveSession();
await waitForDownload(path.join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT);
await volViewPage.open('?urls=[tmp/' + saved + ']');
@@ -308,18 +322,17 @@ describe('Selected-slab occupied depth', () => {
'aria-valuenow',
index ? '114' : '103'
);
- await expandEnFaceSection('thickness');
- await expect($(THRESHOLD)).toHaveValue(index ? '60' : '31');
- await expect(
- $(PANEL).$('[data-testid="enface-segmentation-segment"]')
- ).toHaveText(
- expect.stringContaining(
- index ? 'Alternative synthetic band' : 'Synthetic retinal band'
- )
- );
- const enabled = $(PANEL).$('[data-testid="enface-thin-highlight"] input');
- if (index) await expect(enabled).not.toBeSelected();
- else await expect(enabled).toBeSelected();
+ await expandEnFaceSection('segments');
+ for (const [name, pressed] of [
+ [BAND, !index],
+ [ALTERNATIVE, !!index],
+ ] as const)
+ await expect(segmentEye(name)).toHaveAttribute(
+ 'aria-pressed',
+ String(pressed)
+ );
+ if (index) await expect(segmentThreshold(ALTERNATIVE)).toHaveValue('');
+ else await expect(segmentThreshold(BAND)).toHaveValue('31');
await browser.keys(Key.Escape);
}
await openSegmentDisplay();
@@ -336,11 +349,12 @@ describe('Selected-slab occupied depth', () => {
).toHaveAttribute('aria-valuenow', value);
}
await openEnFaceControls(restored[1]);
- await setHighlight(true);
+ // Below the 52 um band, so the threshold hides it.
+ await setSegmentThreshold(ALTERNATIVE, 40);
await browser.waitUntil(
async () => {
const [r, g] = await enFacePixel(60, 12, undefined, restored[1]);
- return g > r + 20;
+ return g === r;
},
{
timeoutMsg:
@@ -363,21 +377,23 @@ describe('Selected-slab occupied depth', () => {
await expandEnFaceSection('projection');
await setSlabRange(first, last);
await waitForEnFaceReady();
- await expandEnFaceSection('thickness');
const occupied = count * cellLength;
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute(
+ await expect(segmentThresholdSlider(DIRECTIONAL)).toHaveAttribute(
'aria-valuemax',
String(occupied + 0.1)
);
- await setThicknessThreshold(occupied);
+ await setSegmentThreshold(DIRECTIONAL, occupied);
await expectHighlighted(false, [15, 14]);
- await setThicknessThreshold(occupied + 0.1);
+ await setSegmentThreshold(DIRECTIONAL, occupied + 0.1);
await expectHighlighted(true, [15, 14]);
}
await expandEnFaceSection('projection');
await setSlabRange(5, 6);
await waitForEnFaceReady();
- await expect($(THRESHOLD_SLIDER)).toHaveAttribute('aria-valuemax', '0.1');
+ await expect(segmentThresholdSlider(DIRECTIONAL)).toHaveAttribute(
+ 'aria-valuemax',
+ '0.1'
+ );
await expectHighlighted(false, [15, 14]);
expect(await volViewPage.getNotificationsCount()).toBe(0);
});