Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): scope kept widgets and pause hidden video

joshistoastd32c4bf7c5f3
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
index 075e98da39..5bcb9a84d1 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
@@ -53,6 +53,7 @@ vi.mock('@workbench/widgetRegionViewModel', () => ({
}));
vi.mock('@workbench/widgetRegistry', () => ({ getWidgetById: () => undefined, getWidgetsForRegion: () => [] }));
vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectId: () => centerAreaMocks.project.id,
useActiveProjectSelector: (selector: (project: typeof centerAreaMocks.project) => unknown) =>
selector(centerAreaMocks.project),
useWorkbenchCommands: () => ({ widgets: {} }),
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
index 78d4bf29c5..799f926b61 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
@@ -25,12 +25,17 @@ import {
isRequiredCenterView,
} from '@workbench/widgetRegionViewModel';
import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';
-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { CheckIcon, ChevronDownIcon, XIcon } from 'lucide-react';
import { Activity, Suspense, useCallback, useMemo, useRef, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { useMountedInstanceIds } from './useMountedInstanceIds';
+import {
+ areInstanceIdListsEqual,
+ getActiveInstanceIdsOutside,
+ useMountedInstanceIds,
+ withoutInstancesShownElsewhere,
+} from './useMountedInstanceIds';
type CenterWidgetItem = PlacedWidgetRegionItem<WidgetPlacementInstanceMeta>;
@@ -78,7 +83,16 @@ export const CenterArea = () => {
? centerRegion.activeInstanceId
: centerViewItems[0]?.id;
const activeItem = centerViewItems.find((item) => item.id === activeCenterViewId);
- const mountedCenterIds = useMountedInstanceIds(activeCenterViewId);
+ const projectId = useActiveProjectId();
+ const activeIdsElsewhere = useActiveProjectSelector(
+ (project) => getActiveInstanceIdsOutside(project.widgetRegions, 'center'),
+ areInstanceIdListsEqual
+ );
+ const mountedCenterIds = withoutInstancesShownElsewhere(
+ useMountedInstanceIds(activeCenterViewId, projectId),
+ activeCenterViewId,
+ activeIdsElsewhere
+ );
const focusRegionProps = useFocusRegionProps('center');
const openCenterWidget = useCallback(
@@ -140,7 +154,7 @@ export const CenterArea = () => {
>
<Box flex="1" minH="0" position="relative">
<Box aria-label={t('widgets.centerRegion')} h="full" role="region">
- {mountedCenterIds.length > 0 ? (
+ {activeCenterViewId !== undefined && mountedCenterIds.length > 0 ? (
mountedCenterIds.map((instanceId) => (
<Activity key={instanceId} mode={instanceId === activeCenterViewId ? 'visible' : 'hidden'}>
<KeptCenterViewSlot instanceId={instanceId} />
diff --git a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
index a58a59daec..1437bd704b 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
@@ -4,11 +4,16 @@ import { MissingWidgetFrame, WidgetRendererById } from '@workbench/widget-frame'
import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';
import { resolveWidgetLabel } from '@workbench/widgetLabels';
import { getWidgetById } from '@workbench/widgetRegistry';
-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { Activity } from 'react';
import { useTranslation } from 'react-i18next';
-import { useMountedInstanceIds } from './useMountedInstanceIds';
+import {
+ areInstanceIdListsEqual,
+ getActiveInstanceIdsOutside,
+ useMountedInstanceIds,
+ withoutInstancesShownElsewhere,
+} from './useMountedInstanceIds';
/** Left panel — hosts the active registered widget panel view. */
export const LeftPanel = ({ instanceId }: { instanceId: WidgetInstanceId }) => (
@@ -32,13 +37,22 @@ const panelRegions = {
* independent of the region's `instanceIds`, which a preset replaces wholesale.
*/
const WidgetPanelSlot = ({ instanceId, panel }: { instanceId: WidgetInstanceId; panel: keyof typeof panelRegions }) => {
- const mountedIds = useMountedInstanceIds(instanceId);
+ const projectId = useActiveProjectId();
+ const activeIdsElsewhere = useActiveProjectSelector(
+ (project) => getActiveInstanceIdsOutside(project.widgetRegions, panelRegions[panel]),
+ areInstanceIdListsEqual
+ );
+ const mountedIds = withoutInstancesShownElsewhere(
+ useMountedInstanceIds(instanceId, projectId),
+ instanceId,
+ activeIdsElsewhere
+ );
return (
<>
{mountedIds.map((id) => (
<Activity key={id} mode={id === instanceId ? 'visible' : 'hidden'}>
- <WidgetPanelInstance instanceId={id as WidgetInstanceId} panel={panel} />
+ <WidgetPanelInstance instanceId={id} panel={panel} />
</Activity>
))}
</>
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
index ece93ca622..a16174e592 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
@@ -24,37 +24,62 @@ const keepAliveMocks = vi.hoisted(() => {
status: 'enabled',
},
};
- const typeIdByInstanceId: Record<string, string> = { canvas: 'canvas', 'workflow:center': 'workflow' };
+ const typeIdByInstanceId: Record<string, string> = {
+ canvas: 'canvas',
+ layers: 'canvas',
+ preview: 'workflow',
+ 'workflow:center': 'workflow',
+ };
const widgetInstances = {
canvas: { createdAt: 1, id: 'canvas', typeId: 'canvas' },
+ layers: { createdAt: 1, id: 'layers', typeId: 'canvas' },
+ preview: { createdAt: 1, id: 'preview', typeId: 'workflow' },
'workflow:center': { createdAt: 1, id: 'workflow:center', typeId: 'workflow' },
};
- const createProject = (activeInstanceId: string) => ({
+ const createProject = ({
+ activeInstanceId,
+ projectId = 'project-a',
+ rightInstanceId = 'layers',
+ }: {
+ activeInstanceId: string | undefined;
+ projectId?: string;
+ rightInstanceId?: string;
+ }) => ({
floatingWidgets: [],
- id: 'test-project',
+ id: projectId,
invocation: { sourceId: 'generate' },
queue: { items: [] },
widgetInstances,
widgetRegions: {
- center: { activeInstanceId, instanceIds: [activeInstanceId], isCollapsed: false, sizePx: 0 },
+ center: {
+ activeInstanceId: activeInstanceId ?? '',
+ instanceIds: activeInstanceId === undefined ? [] : [activeInstanceId],
+ isCollapsed: false,
+ sizePx: 0,
+ },
+ right: { activeInstanceId: rightInstanceId, instanceIds: [rightInstanceId], isCollapsed: false, sizePx: 0 },
},
});
- let project = createProject('canvas');
+ let project = createProject({ activeInstanceId: 'canvas' });
const listeners = new Set<() => void>();
+ const publish = (next: ReturnType<typeof createProject>) => {
+ project = next;
+ for (const listener of listeners) {
+ listener();
+ }
+ };
return {
getProject: () => project,
getWidgetById: (typeId: string) => widgets[typeId],
reset: () => {
- project = createProject('canvas');
- },
- setActiveInstanceId: (activeInstanceId: string) => {
- project = createProject(activeInstanceId);
- for (const listener of listeners) {
- listener();
- }
+ project = createProject({ activeInstanceId: 'canvas' });
},
+ setActiveInstanceId: (activeInstanceId: string | undefined) => publish(createProject({ activeInstanceId })),
+ setProjectId: (projectId: string) => publish(createProject({ activeInstanceId: 'canvas', projectId })),
+ setRightInstanceId: (rightInstanceId: string) =>
+ publish(createProject({ activeInstanceId: project.widgetRegions.center.activeInstanceId, rightInstanceId })),
subscribe: (listener: () => void) => {
listeners.add(listener);
@@ -98,6 +123,7 @@ vi.mock('@workbench/WorkbenchContext', async () => {
const { useSyncExternalStore } = await import('react');
return {
+ useActiveProjectId: () => useSyncExternalStore(keepAliveMocks.subscribe, keepAliveMocks.getProject).id,
useActiveProjectSelector: (selector: (project: unknown) => unknown) =>
selector(useSyncExternalStore(keepAliveMocks.subscribe, keepAliveMocks.getProject)),
useWorkbenchCommands: () => ({ widgets: {} }),
@@ -150,13 +176,18 @@ const renderCenterArea = async () => {
await Promise.resolve();
});
+ const publish = async (mutate: () => void) => {
+ await act(async () => {
+ mutate();
+ await Promise.resolve();
+ });
+ };
+
return {
- setActiveInstanceId: async (instanceId: string) => {
- await act(async () => {
- keepAliveMocks.setActiveInstanceId(instanceId);
- await Promise.resolve();
- });
- },
+ setActiveInstanceId: (instanceId: string | undefined) =>
+ publish(() => keepAliveMocks.setActiveInstanceId(instanceId)),
+ setProjectId: (projectId: string) => publish(() => keepAliveMocks.setProjectId(projectId)),
+ setRightInstanceId: (instanceId: string) => publish(() => keepAliveMocks.setRightInstanceId(instanceId)),
};
};
@@ -211,6 +242,45 @@ describe('preset switch keep-alive', () => {
expect(hiddenCanvas?.getClientRects().length).toBe(0);
});
+ it('drops a kept instance once another region starts showing it', async () => {
+ const { setActiveInstanceId, setRightInstanceId } = await renderCenterArea();
+
+ await setActiveInstanceId('preview');
+ await setActiveInstanceId('workflow:center');
+
+ // Kept and hidden while the right rail shows something else.
+ expect(centerWidget('preview')).not.toBeNull();
+
+ await setRightInstanceId('preview');
+
+ // The right rail is now rendering this instance for real; a hidden centre
+ // copy would be the same instance mounted twice, one of them a ghost.
+ expect(centerWidget('preview')).toBeNull();
+ });
+
+ it('forgets what the previous project had shown', async () => {
+ const { setActiveInstanceId, setProjectId } = await renderCenterArea();
+
+ await setActiveInstanceId('workflow:center');
+ expect(centerWidget('canvas')).not.toBeNull();
+
+ await setProjectId('project-b');
+
+ // Instance ids repeat across projects, so a kept id would resolve to a real
+ // instance of the new project carrying the old project's local state.
+ expect(centerWidget('workflow:center')).toBeNull();
+ expect(centerWidget('canvas')).not.toBeNull();
+ });
+
+ it('says the centre is unavailable rather than rendering nothing', async () => {
+ const { setActiveInstanceId } = await renderCenterArea();
+
+ await setActiveInstanceId(undefined);
+
+ expect(centerWidget('canvas')).toBeNull();
+ expect(host?.textContent).toContain('Center widget unavailable');
+ });
+
it('keeps chrome on the live region rather than on the kept widget', async () => {
const { setActiveInstanceId } = await renderCenterArea();
diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx
index aa03478730..af011f599c 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx
@@ -2,7 +2,11 @@ import { act, useEffect } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it } from 'vitest';
-import { useMountedInstanceIds } from './useMountedInstanceIds';
+import {
+ getActiveInstanceIdsOutside,
+ useMountedInstanceIds,
+ withoutInstancesShownElsewhere,
+} from './useMountedInstanceIds';
// `@testing-library/react` is not a dependency of this package, so the hook is
// driven through a probe component the way the other browser suites here do.
@@ -17,8 +21,8 @@ let root: Root | null = null;
*/
const latest: { ids: string[] } = { ids: [] };
-const Probe = ({ activeId, limit }: { activeId: string | undefined; limit?: number }) => {
- const ids = useMountedInstanceIds(activeId, limit);
+const Probe = ({ activeId, limit, resetKey }: { activeId: string | undefined; limit?: number; resetKey: string }) => {
+ const ids = useMountedInstanceIds(activeId, resetKey, limit);
useEffect(() => {
latest.ids = ids;
@@ -32,9 +36,9 @@ const renderHook = async (activeId: string | undefined, limit?: number) => {
document.body.append(host);
root = createRoot(host);
- const rerender = async (nextActiveId: string | undefined) => {
+ const rerender = async (nextActiveId: string | undefined, resetKey = 'project-a') => {
await act(async () => {
- root?.render(<Probe activeId={nextActiveId} limit={limit} />);
+ root?.render(<Probe activeId={nextActiveId} limit={limit} resetKey={resetKey} />);
await Promise.resolve();
});
};
@@ -99,4 +103,48 @@ describe('mounted instance ids', () => {
expect(latest.ids).toEqual(['canvas']);
});
+
+ it('forgets everything the previous project had shown', async () => {
+ const { rerender } = await renderHook('canvas');
+
+ await rerender('workflow:center');
+ expect(latest.ids).toEqual(['canvas', 'workflow:center']);
+
+ // Instance ids are identical in every project, so a remembered id would
+ // otherwise resolve to a real — but wrong — instance of the new project.
+ await rerender('workflow:center', 'project-b');
+ expect(latest.ids).toEqual(['workflow:center']);
+ });
+});
+
+describe('instances shown elsewhere', () => {
+ it('drops a kept instance another region is actively rendering', () => {
+ expect(withoutInstancesShownElsewhere(['preview', 'canvas'], 'canvas', ['preview'])).toEqual(['canvas']);
+ });
+
+ it('never drops the active instance of the region asking', () => {
+ expect(withoutInstancesShownElsewhere(['gallery', 'preview'], 'preview', ['preview'])).toEqual([
+ 'gallery',
+ 'preview',
+ ]);
+ });
+
+ it('keeps the list identity when nothing is shown elsewhere', () => {
+ const mountedIds = ['preview', 'canvas'];
+
+ expect(withoutInstancesShownElsewhere(mountedIds, 'canvas', ['layers'])).toBe(mountedIds);
+ });
+
+ it('reads actives only, never region membership', () => {
+ const widgetRegions = {
+ bottom: { activeInstanceId: 'gallery:bottom', instanceIds: ['gallery:bottom'] },
+ center: { activeInstanceId: 'canvas', instanceIds: ['canvas', 'preview'] },
+ left: { activeInstanceId: 'generate', instanceIds: ['generate', 'upscale'] },
+ right: { activeInstanceId: 'layers', instanceIds: ['layers', 'preview', 'gallery'] },
+ };
+
+ // `preview` is a member of the right rail but not its active instance, so it
+ // stays available for the centre to keep.
+ expect(getActiveInstanceIdsOutside(widgetRegions, 'center')).toEqual(['gallery:bottom', 'generate', 'layers']);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts
index fac1fda9a5..366c532ff8 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts
@@ -1,9 +1,10 @@
import { useState } from 'react';
/**
- * How many instances a region keeps mounted behind it. A kept canvas holds its
- * WebGL context and a kept gallery holds its virtualizer, so this is bounded
- * rather than unlimited; three covers every realistic back-and-forth.
+ * How many instances a region keeps mounted behind it. A kept gallery holds its
+ * virtualizer, its measurement cache and the decoded images in its window, and
+ * every kept widget holds its DOM, so this is bounded rather than unlimited;
+ * three covers every realistic back-and-forth.
*/
export const MOUNTED_INSTANCE_LIMIT = 3;
@@ -16,19 +17,76 @@ export const MOUNTED_INSTANCE_LIMIT = 3;
* hold it — and with it the canvas viewport, gallery scroll and selection that
* a full unmount would take.
*
+ * `resetKey` is the active project id. Widget instance ids are deterministic and
+ * identical in every project, so a remembered id does not go stale on a project
+ * switch — it silently resolves to a real instance of the *new* project, and the
+ * previous project's scroll offsets and in-widget selection would surface under
+ * it. Dropping the set when the key changes is what keeps a session's memory
+ * scoped to the project it belongs to.
+ *
* Ephemeral by design. A remembered mount is a session affordance, not state
* worth persisting.
+ *
+ * Known and accepted: closing a widget reads as hiding it. `closeWidgetPlacement`
+ * takes the instance out of its region but leaves it in `widgetInstances`, so a
+ * closed widget is kept like any other and reopens with its state intact — the
+ * way a desktop editor reopens a panel you closed. Telling a close apart from a
+ * layout switch needs an explicit dismissal signal that does not exist yet; until
+ * it does, `limit` is what bounds the consequence.
*/
-export const useMountedInstanceIds = (activeId: string | undefined, limit = MOUNTED_INSTANCE_LIMIT): string[] => {
- const [ids, setIds] = useState<string[]>(() => (activeId === undefined ? [] : [activeId]));
+export const useMountedInstanceIds = (
+ activeId: string | undefined,
+ resetKey: string,
+ limit = MOUNTED_INSTANCE_LIMIT
+): string[] => {
+ const [remembered, setRemembered] = useState<{ ids: string[]; resetKey: string }>(() => ({
+ ids: activeId === undefined ? [] : [activeId],
+ resetKey,
+ }));
+ const ids = remembered.resetKey === resetKey ? remembered.ids : [];
const next =
activeId === undefined || ids.at(-1) === activeId
? ids
: [...ids.filter((id) => id !== activeId), activeId].slice(-limit);
- if (next !== ids) {
- setIds(next);
+ if (next !== remembered.ids || resetKey !== remembered.resetKey) {
+ setRemembered({ ids: next, resetKey });
}
return next;
};
+
+/**
+ * Kept ids, minus any instance another region is actively rendering.
+ *
+ * One instance can be placed in more than one region — `preview` is Compose's
+ * centre view and also sits in Edit's and Automate's right rails — so a kept
+ * hidden copy can end up shadowing a live one: the same instance mounted twice,
+ * one of them a ghost the user can neither see nor dismiss.
+ *
+ * Only the regions' `activeInstanceId` values are consulted. Region membership
+ * (`instanceIds`) is the thing a preset replaces wholesale, and deriving
+ * anything here from it would reintroduce the very filtering bug this mechanism
+ * exists to avoid. Actives are a small, stable signal that cannot.
+ */
+export const withoutInstancesShownElsewhere = (
+ mountedIds: string[],
+ activeId: string | undefined,
+ activeIdsElsewhere: readonly string[]
+): string[] => {
+ const kept = mountedIds.filter((id) => id === activeId || !activeIdsElsewhere.includes(id));
+
+ return kept.length === mountedIds.length ? mountedIds : kept;
+};
+
+/** The `activeInstanceId` of every region except `region`. */
+export const getActiveInstanceIdsOutside = (
+ widgetRegions: Record<string, { activeInstanceId: string }>,
+ region: string
+): string[] =>
+ Object.entries(widgetRegions)
+ .filter(([name]) => name !== region)
+ .map(([, regionState]) => regionState.activeInstanceId);
+
+export const areInstanceIdListsEqual = (left: readonly string[], right: readonly string[]): boolean =>
+ left.length === right.length && left.every((id, index) => id === right[index]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index 8ddc3aab68..41b41322c7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -6,6 +6,7 @@ import { Badge, Flex, Text } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';
import { getAuthSession, refreshProtectedMediaCookie } from '@features/identity';
+import { useMountEffect } from '@platform/react/useMountEffect';
import { Button } from '@platform/ui/Button';
import {
useCallback,
@@ -317,6 +318,20 @@ const PreviewVideo = ({
return isCurrent() ? { ok: true } : { ok: false, reason: 'stale' };
}, [isItemCurrent, source.itemKey]);
const isCopyAvailable = useCallback(() => isVideoFrameCopyAvailable(videoRef.current), []);
+ // Playback must not outlive this view being on screen. A widget the shell
+ // keeps mounted behind a layout switch is hidden with `display: none`, which
+ // does not stop media — the clip would keep running, with audio, behind a
+ // layout the user moved away from and with no reachable controls. Effects are
+ // torn down whenever the subtree stops being shown, whether that is a real
+ // unmount or a hidden keep-alive boundary, so pausing here covers both without
+ // this component needing to know which one happened.
+ useMountEffect(() => {
+ const video = videoRef.current;
+
+ return () => {
+ video?.pause();
+ };
+ });
useImperativeHandle(
videoControllerRef,
() => ({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
index 6f0338eec7..2001f676b3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx
@@ -5,7 +5,7 @@ import { ChakraProvider } from '@chakra-ui/react';
import { DndContext, PointerSensor, useDndMonitor, useSensor, useSensors, type DragStartEvent } from '@dnd-kit/core';
import { system } from '@theme/system';
import { createInstance } from 'i18next';
-import { act, createRef, type Ref } from 'react';
+import { act, Activity, createRef, type Ref } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -524,6 +524,48 @@ describe('PreviewFrame native video arm', () => {
});
});
+describe('PreviewFrame video keep-alive', () => {
+ it('stops playback when the shell hides the widget instead of unmounting it', async () => {
+ await renderKeptVideo('visible');
+ const video = getVideo();
+ const pause = vi.spyOn(video, 'pause');
+
+ await renderKeptVideo('hidden');
+
+ // The element survives — this is the keep-alive path, not an unmount — but
+ // `display: none` does not stop media, so the frame has to pause it itself.
+ expect(getVideo()).toBe(video);
+ expect(video.checkVisibility()).toBe(false);
+ expect(pause).toHaveBeenCalledOnce();
+ expect(video.paused).toBe(true);
+ });
+
+ it('leaves playback alone while the widget stays visible', async () => {
+ await renderKeptVideo('visible');
+ const video = getVideo();
+ const pause = vi.spyOn(video, 'pause');
+
+ await renderKeptVideo('visible');
+
+ expect(getVideo()).toBe(video);
+ expect(pause).not.toHaveBeenCalled();
+ });
+});
+
+const renderKeptVideo = async (mode: 'hidden' | 'visible'): Promise<void> => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Activity mode={mode}>
+ <VideoHarness />
+ </Activity>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
const renderVideo = async (
isItemCurrent?: (itemKey: GalleryItemKey) => boolean,
source: VideoSource = videoSource,