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.

feat: video player with a loop toggle for Preview and the workflow frame picker (#10005)

Josh Corbett4b1b0790252c
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index b90bd6563e..5c443021bb 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -302,7 +302,27 @@
"decreaseValue": "Decrease value",
"increaseValue": "Increase value",
"on": "On",
- "off": "Off"
+ "off": "Off",
+ "videoPlayer": {
+ "buffering": "Buffering",
+ "exitFullscreen": "Exit full screen",
+ "frame": "Frame {{frame}}",
+ "frameOfLast": "Frame {{frame}}, last {{last}}",
+ "fullscreen": "Full screen",
+ "loop": "Loop",
+ "mute": "Mute",
+ "nextFrame": "Next frame",
+ "pause": "Pause",
+ "play": "Play",
+ "playbackSpeed": "Playback speed",
+ "playbackSpeedValue": "Playback speed: {{rate}}",
+ "previousFrame": "Previous frame",
+ "rate": "{{rate, number}}×",
+ "seek": "Seek",
+ "timeOfDuration": "{{current}} of {{duration}}",
+ "unmute": "Unmute",
+ "volume": "Volume"
+ }
},
"app": {
"name": "Invoke"
@@ -2029,6 +2049,11 @@
"nodeVersion": "Version: {{version}}",
"nodeClassification": "Classification: {{classification}}",
"seedModeTooltip": "Applies between queued runs of the workflow; a loop inside one run reuses that run's seed.",
+ "framePreview": "Frame preview",
+ "framePreviewPlaybackError": "Frame preview unavailable — the video could not be played.",
+ "useThisFrame": "Use this frame",
+ "useThisFrameTooltip": "Set Frame Index to the frame shown",
+ "useThisFrameUnavailable": "Pause on a different frame to use it",
"providedByConnection": "Provided by connection.",
"savedWorkflowChoose": "Choose a saved workflow",
"savedWorkflowMissing": "Saved workflow unavailable",
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 56d5529cf7..fe4b43c694 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -971,7 +971,11 @@ const runVideoPreviewJourney = async (browser) => {
assert.equal(await selectVideo.locator('xpath=..').locator('svg.lucide-play').getAttribute('aria-hidden'), 'true');
await selectVideo.press('Enter');
- const video = centerRegion(page).locator(`video[aria-label="Video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}"]`);
+ const player = centerRegion(page).getByRole('group', {
+ exact: true,
+ name: `Video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}`,
+ });
+ const video = player.locator('video');
try {
await video.waitFor();
@@ -981,11 +985,33 @@ const runVideoPreviewJourney = async (browser) => {
`${error instanceof Error ? error.message : String(error)}\nPage errors: ${pageErrors.map(String).join('\n')}\nConsole errors: ${consoleErrors.join('\n')}\nBody:\n${bodyText}`
);
}
- assert.equal(await video.getAttribute('controls'), '');
+ // The player's own controls replace the browser's.
+ assert.equal(await video.getAttribute('controls'), null);
assert.equal(await video.getAttribute('playsinline'), '');
assert.match((await video.getAttribute('poster')) ?? '', /fixture-video-001\.mp4\/thumbnail$/);
assert.equal(await video.getAttribute('draggable'), null);
+ // The video can be operated from the keyboard: its controls are tab stops, and Space plays and pauses it.
+ const play = player.locator('button[aria-label="Play"]:not([disabled])');
+ await play.waitFor();
+ assert.notEqual(await play.getAttribute('tabindex'), '-1');
+ await play.focus();
+ await expectFocused(play, 'The video player Play control must be keyboard focusable.');
+ await page.keyboard.press('Space');
+ await page.waitForFunction((element) => !element.paused, await video.elementHandle());
+ const pause = player.getByRole('button', { exact: true, name: 'Pause' });
+ await expectFocused(pause, 'The video player must keep focus on its play control while playing.');
+ await page.keyboard.press('Space');
+ await page.waitForFunction((element) => element.paused, await video.elementHandle());
+ const seek = player.getByRole('slider', { exact: true, name: 'Seek' });
+ assert.notEqual(await seek.getAttribute('tabindex'), '-1');
+ assert.equal(await player.getByRole('button', { exact: true, name: 'Loop' }).isEnabled(), true);
+ // A wide bar shows the volume slider; a narrow one opens it from a volume button.
+ const volume = player
+ .getByRole('slider', { exact: true, name: 'Volume' })
+ .or(player.getByRole('button', { exact: true, name: 'Volume' }));
+ assert.equal(await volume.isEnabled(), true);
+
// Media details live in the floating header chrome's Details popover; audit the surface with it open.
const details = page
.locator('[data-hotkey-widget-region="center"][data-hotkey-widget-type-id="preview"]')
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx
new file mode 100644
index 0000000000..fcf1ba178d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/VideoFramePicker.tsx
@@ -0,0 +1,159 @@
+import { Box, Center, Flex, Text } from '@chakra-ui/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { Button, useUnavailableControl } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { VideoPlayer } from '@platform/ui/video-player/VideoPlayer';
+import { getFrameAtTime, getFrameTime } from '@platform/ui/video-player/videoTimeline';
+import { useCallback, useMemo, useState, type SyntheticEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+export interface VideoFramePickerProps {
+ /** The stored value, which can differ from `resolvedIndex` (a negative index, a value past the end). */
+ fieldValue: number;
+ fps: number;
+ frameCount: number;
+ onChange: (value: unknown) => void;
+ posterUrl: string;
+ resolvedIndex: number;
+ videoUrl: string;
+}
+
+const showPausedAt = (video: HTMLVideoElement, seconds: number) => {
+ video.pause();
+
+ try {
+ video.currentTime = seconds;
+ } catch {
+ // Some browsers throw while nothing is seekable yet; the element keeps its position.
+ }
+};
+
+/**
+ * Shows the field's frame, paused, for one mount. Keyed by the field's frame, so every change re-seeks, including ones
+ * made outside this node (undo, a graph load).
+ */
+const FieldFrameSeek = ({ time, video }: { time: number; video: HTMLVideoElement }) => {
+ useMountEffect(() => {
+ const seek = () => showPausedAt(video, time);
+
+ if (video.readyState >= HTMLMediaElement.HAVE_METADATA) {
+ seek();
+
+ return undefined;
+ }
+
+ video.addEventListener('loadedmetadata', seek, { once: true });
+
+ return () => video.removeEventListener('loadedmetadata', seek);
+ });
+
+ return null;
+};
+
+/**
+ * A player that follows the field: it opens on the field's frame and returns to it whenever the field changes, while
+ * playing, looping and scrubbing leave the field alone. "Use this frame" commits the frame the player is paused on.
+ * Key it by the source: its media state belongs to one video.
+ */
+export const VideoFramePicker = ({
+ fieldValue,
+ fps,
+ frameCount,
+ onChange,
+ posterUrl,
+ resolvedIndex,
+ videoUrl,
+}: VideoFramePickerProps) => {
+ const { t } = useTranslation();
+ const [video, setVideo] = useState<HTMLVideoElement | null>(null);
+ // The frame the player rests on; null while it plays or before its media loads.
+ const [pausedFrame, setPausedFrame] = useState<number | null>(null);
+ const [hasMediaError, setHasMediaError] = useState(false);
+ const readPausedFrame = useCallback(
+ ({ currentTarget }: SyntheticEvent<HTMLVideoElement>) =>
+ setPausedFrame(
+ currentTarget.paused && currentTarget.readyState >= HTMLMediaElement.HAVE_METADATA
+ ? getFrameAtTime(currentTarget.currentTime, fps, frameCount)
+ : null
+ ),
+ [fps, frameCount]
+ );
+ const handleError = useCallback(() => {
+ setHasMediaError(true);
+ setPausedFrame(null);
+ }, []);
+ const errorOverlay = useMemo(
+ () =>
+ hasMediaError ? (
+ // A scrim: the poster stays behind the message.
+ <Center bg="blackAlpha.800" inset="0" position="absolute" px="2">
+ <Text color="whiteAlpha.800" fontSize="md" textAlign="center">
+ {t('nodes.framePreviewPlaybackError')}
+ </Text>
+ </Center>
+ ) : null,
+ [hasMediaError, t]
+ );
+ const canUseFrame = pausedFrame !== null && pausedFrame !== resolvedIndex;
+ // Unavailable rather than disabled: a commit makes the button unavailable while it holds focus, and a disabled
+ // button would drop that focus to the page.
+ const unavailable = useUnavailableControl(canUseFrame ? undefined : t('nodes.useThisFrameUnavailable'), undefined);
+ // Read from the element, not the last event, so the commit is the frame on screen.
+ const commitPlayerFrame = useCallback(() => {
+ if (!video?.paused || video.readyState < HTMLMediaElement.HAVE_METADATA) {
+ return;
+ }
+
+ const frame = getFrameAtTime(video.currentTime, fps, frameCount);
+
+ if (frame !== resolvedIndex) {
+ onChange(frame);
+ }
+ }, [fps, frameCount, onChange, resolvedIndex, video]);
+
+ return (
+ // `nodrag` keeps pointer drags on the scrubber from moving the node; `nokey` keeps its arrow keys from nudging it.
+ <Flex className="nodrag nokey" direction="column" gap="1" w="full">
+ <Box borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full">
+ <VideoPlayer
+ ref={setVideo}
+ aria-label={t('nodes.framePreview')}
+ fps={fps}
+ frameCount={frameCount}
+ muted
+ overlay={errorOverlay}
+ poster={posterUrl}
+ preload="auto"
+ size="compact"
+ src={videoUrl}
+ onError={handleError}
+ onPause={readPausedFrame}
+ onPlay={readPausedFrame}
+ onSeeked={readPausedFrame}
+ />
+ </Box>
+ {video ? (
+ <FieldFrameSeek
+ key={`${fps}|${fieldValue}|${resolvedIndex}`}
+ time={getFrameTime(resolvedIndex, fps)}
+ video={video}
+ />
+ ) : null}
+ {hasMediaError ? null : (
+ // Always wrapped, so the button keeps its element (and focus) as it turns unavailable.
+ <Tooltip content={canUseFrame ? t('nodes.useThisFrameTooltip') : t('nodes.useThisFrameUnavailable')}>
+ <Button
+ alignSelf="flex-start"
+ size="sm"
+ variant="outline"
+ {...unavailable?.props}
+ onClick={commitPlayerFrame}
+ >
+ {t('nodes.useThisFrame')}
+ {unavailable?.description}
+ </Button>
+ </Tooltip>
+ )}
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index 2cf21cbc21..4ac37e3f5b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -13,7 +13,7 @@ import { act, cloneElement, startTransition, useCallback, useState } from 'react
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { server, userEvent } from 'vitest/browser';
+import { page, server, userEvent } from 'vitest/browser';
import { WorkflowFieldInput, type WorkflowFieldInputProps } from './WorkflowFieldInput';
@@ -797,39 +797,6 @@ describe('WorkflowFieldInput media inputs', () => {
expect(uploadVideoMock.mock.calls[0]?.[1]).toBe('none');
});
- it('renders the frame scrubber for video-frame-index integer fields', async () => {
- resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, fps: 30 });
- graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));
-
- // Default of -1 (= last frame) resolves against duration * fps = 150 frames.
- await renderField(FRAME_INDEX_TEMPLATE, -1, vi.fn(), 'frame-node');
-
- await vi.waitFor(() => {
- expect(host.querySelector('video')?.src).toContain('/api/v1/videos/i/clip.mp4/full');
- });
- expect(host.textContent).toContain('149 / 149');
- expect(host.querySelector('input[type="number"]')).not.toBeNull();
- expect(host.querySelector('[role="slider"]')).not.toBeNull();
- });
-
- it('scrubs frames with the slider, writing the resolved index to the field', async () => {
- resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, fps: 30 });
- graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));
- const onChange = vi.fn();
-
- await renderField(FRAME_INDEX_TEMPLATE, 10, onChange, 'frame-node');
-
- await vi.waitFor(() => {
- expect(host.querySelector('[role="slider"]')).not.toBeNull();
- });
-
- const thumb = host.querySelector<HTMLElement>('[role="slider"]')!;
-
- thumb.focus();
- await act(() => thumb.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' })));
- expect(onChange).toHaveBeenCalledWith(11);
- });
-
it('falls back to a hint when the companion video field is unset', async () => {
graphNodes.push(makeFrameNode(undefined));
@@ -874,20 +841,6 @@ describe('WorkflowFieldInput media inputs', () => {
expect(resolveItemMock).not.toHaveBeenCalled();
});
- it('shows the preview without a slider for a single-frame video', async () => {
- // min === max would render a broken (NaN%) zag slider.
- resolveItemMock.mockResolvedValue({ ...SELECTED_GALLERY_VIDEO, durationSeconds: 0.02, fps: 30 });
- graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));
-
- await renderField(FRAME_INDEX_TEMPLATE, 0, vi.fn(), 'frame-node');
-
- await vi.waitFor(() => {
- expect(host.querySelector('video')).not.toBeNull();
- });
- expect(host.textContent).toContain('0 / 0');
- expect(host.querySelector('[role="slider"]')).toBeNull();
- });
-
it('reports a deleted video instead of a frame-rate story', async () => {
resolveItemMock.mockRejectedValue(new Error('404'));
graphNodes.push(makeFrameNode({ video_name: 'gone.mp4' }));
@@ -952,6 +905,193 @@ describe('WorkflowFieldInput media inputs', () => {
});
});
+describe('WorkflowFieldInput video frame picker', () => {
+ // The mock backend's clip: 10 frames at 10 fps, one second long. Vite serves the package root.
+ const FIXTURE_VIDEO = {
+ ...SELECTED_GALLERY_VIDEO,
+ durationSeconds: 1,
+ fps: 10,
+ fullUrl: '/scripts/mock-assets/fixture-video.mp4',
+ };
+ const i18n = createInstance();
+ beforeAll(async () => {
+ // Through the provider only: registering it globally would translate the raw keys later suites assert on.
+ await i18n.init({
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+ });
+ });
+ beforeEach(() => {
+ resolveItemMock.mockResolvedValue(FIXTURE_VIDEO);
+ graphNodes.push(makeFrameNode({ video_name: 'clip.mp4' }));
+ });
+
+ /** Renders, or re-renders as the document would after an edit, the frame field with the given stored value. */
+ const renderFrameField = async (value: unknown, onChange: (value: unknown) => void) => {
+ await act(() => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <DndContext>
+ <WorkflowFieldInput
+ nodeId="frame-node"
+ template={FRAME_INDEX_TEMPLATE}
+ value={value}
+ onChange={onChange}
+ />
+ </DndContext>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ };
+
+ const getVideo = async (): Promise<HTMLVideoElement> => {
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+
+ return host.querySelector('video')!;
+ };
+
+ /** Waits until the player rests, paused, on `frame` (seeked to the middle of its display interval). */
+ const expectShownFrame = async (video: HTMLVideoElement, frame: number) => {
+ await expect
+ .poll(() => video.paused && !video.seeking && Math.abs(video.currentTime - (frame + 0.5) / 10) < 0.01)
+ .toBe(true);
+ };
+
+ const frameButton = () => page.getByRole('button', { name: 'Use this frame' });
+ // Unavailable, not disabled: the button keeps focus while it cannot act.
+ const expectUseFrameAvailable = async (available: boolean) => {
+ if (available) {
+ await expect.element(frameButton()).not.toHaveAttribute('aria-disabled');
+ } else {
+ await expect.element(frameButton()).toHaveAttribute('aria-disabled', 'true');
+ }
+ };
+
+ const stepPlayerFrames = async (key: ',' | '.', count: number) => {
+ const player = page.getByRole('group', { name: 'Frame preview' }).element() as HTMLElement;
+
+ await act(() => player.focus());
+ for (let step = 0; step < count; step += 1) {
+ await userEvent.keyboard(key);
+ }
+ };
+
+ it("shows the field's frame in a compact player with the video's poster and frame count", async () => {
+ await renderFrameField(3, vi.fn());
+ const video = await getVideo();
+
+ expect(video.src).toContain('/scripts/mock-assets/fixture-video.mp4');
+ expect(video.poster).toContain('/api/v1/videos/i/clip.mp4/thumbnail');
+ await expectShownFrame(video, 3);
+ await expect.element(page.getByText('3 / 9')).toBeVisible();
+ await expectUseFrameAvailable(false);
+ });
+
+ it('resolves negative indices from the end', async () => {
+ await renderFrameField(-1, vi.fn());
+ const video = await getVideo();
+
+ await expectShownFrame(video, 9);
+
+ await renderFrameField(-3, vi.fn());
+ await expectShownFrame(video, 7);
+ });
+
+ it('returns to the field frame when the field changes from outside the player', async () => {
+ await renderFrameField(-1, vi.fn());
+ const video = await getVideo();
+ await expectShownFrame(video, 9);
+
+ await stepPlayerFrames(',', 4);
+ await expectShownFrame(video, 5);
+
+ // Undo or a graph load: a new value at a new frame.
+ await renderFrameField(2, vi.fn());
+ await expectShownFrame(video, 2);
+
+ // A typed value naming the frame -1 already resolved to still brings the field's frame back.
+ await renderFrameField(-1, vi.fn());
+ await expectShownFrame(video, 9);
+ await stepPlayerFrames(',', 1);
+ await expectShownFrame(video, 8);
+ await renderFrameField(9, vi.fn());
+ await expectShownFrame(video, 9);
+ });
+
+ it('commits the paused frame with "Use this frame", keeping focus once it is unavailable', async () => {
+ const onChange = vi.fn();
+ await renderFrameField(2, onChange);
+ const video = await getVideo();
+ await expectShownFrame(video, 2);
+ await expectUseFrameAvailable(false);
+
+ await stepPlayerFrames('.', 3);
+ await expectShownFrame(video, 5);
+ await expectUseFrameAvailable(true);
+ const button = frameButton().element() as HTMLButtonElement;
+ await act(() => button.focus());
+ await userEvent.keyboard('{Enter}');
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(5);
+
+ // The document adopts the value: the button has nothing to commit, but keeps focus inside the node's key guard.
+ await renderFrameField(5, onChange);
+ await expectShownFrame(video, 5);
+ await expectUseFrameAvailable(false);
+ await expect.element(frameButton()).toHaveAccessibleDescription('Pause on a different frame to use it');
+ expect(document.activeElement).toBe(button);
+ expect(button.closest('.nokey')).not.toBeNull();
+
+ await userEvent.keyboard('{Enter}');
+ await act(() => button.click());
+ expect(onChange).toHaveBeenCalledOnce();
+ });
+
+ it('plays past a loop without changing the field, and offers the frame it pauses on', async () => {
+ const onChange = vi.fn();
+ await renderFrameField(0, onChange);
+ const video = await getVideo();
+ await expectShownFrame(video, 0);
+ let wrapped = false;
+ let lastTime = video.currentTime;
+ const watchWrap = () => {
+ wrapped ||= video.currentTime < lastTime;
+ lastTime = video.currentTime;
+ };
+ video.addEventListener('timeupdate', watchWrap);
+
+ await userEvent.click(page.getByRole('button', { name: 'Play' }));
+ await expectUseFrameAvailable(false);
+ await expect.poll(() => wrapped, { timeout: 5_000 }).toBe(true);
+ video.removeEventListener('timeupdate', watchWrap);
+ expect(video.paused).toBe(false);
+ await userEvent.click(page.getByRole('button', { name: 'Pause' }));
+ // It may have paused on the field's frame; one step forward leaves it either way.
+ await stepPlayerFrames('.', 1);
+
+ await expectUseFrameAvailable(true);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('reports a video the browser cannot play, keeping the frame field usable', async () => {
+ resolveItemMock.mockResolvedValue({ ...FIXTURE_VIDEO, fullUrl: '/missing-video.mp4' });
+ const onChange = vi.fn();
+ await renderFrameField(0, onChange);
+
+ await expect.element(page.getByText('Frame preview unavailable — the video could not be played.')).toBeVisible();
+ await expect.element(frameButton()).not.toBeInTheDocument();
+
+ await userEvent.fill(page.getByRole('spinbutton'), '4');
+ await userEvent.keyboard('{Enter}');
+ expect(onChange).toHaveBeenCalledWith(4);
+ });
+});
+
describe('WorkflowFieldInput board field', () => {
const BOARD_TEMPLATE = {
name: 'board',
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 91b9b765f6..1cdbaebb5f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -106,7 +106,6 @@ import {
parseHexColor,
ResizableTextarea,
Select,
- Slider,
toaster,
Tooltip,
} from '@platform/ui';
@@ -119,7 +118,6 @@ import {
Suspense,
useCallback,
useDeferredValue,
- useEffect,
useId,
useMemo,
useRef,
@@ -1219,6 +1217,26 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr
);
};
+const VideoFramePicker = lazy(() =>
+ import('./VideoFramePicker').then((module) => ({ default: module.VideoFramePicker }))
+);
+
+/** The picker's box and button row while its player loads, so the node does not change size. */
+const VideoFramePickerFallback = ({ posterUrl }: { posterUrl: string }) => {
+ const { t } = useTranslation();
+
+ return (
+ <Flex direction="column" gap="1" w="full">
+ <Box bg="black" borderWidth="1px" h="32" overflow="hidden" rounded="sm" w="full">
+ <Image alt="" h="full" objectFit="contain" src={posterUrl} w="full" />
+ </Box>
+ <Button alignSelf="flex-start" disabled size="sm" variant="outline">
+ {t('nodes.useThisFrame')}
+ </Button>
+ </Flex>
+ );
+};
+
/**
* Convention shared with the legacy editor: a `video-frame-index` field's
* source video lives on a sibling field named `video` on the same node.
@@ -1226,8 +1244,8 @@ const MediaInput = ({ id, invalid, kind, onChange, value }: WorkflowFieldInputPr
const COMPANION_VIDEO_FIELD_NAME = 'video';
/**
- * Share one frame value across input, scrubber, and native video preview. Fall back to plain input when the
- * companion video/rate cannot resolve.
+ * The frame input is the value; the player beside it shows that frame and can pick another. Fall back to plain input
+ * when the companion video/rate cannot resolve.
*/
const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {
const { t } = useTranslation();
@@ -1270,8 +1288,7 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {
const videoItem: GalleryItem | undefined = data;
const video = videoItem && videoItem.kind === 'video' && videoItem.name === videoName ? videoItem : null;
- // Use estimated frame count only for scrubbing bounds; backend invocation resolves authoritative decoder
- // indices.
+ // The estimated frame count bounds the picker only; backend invocation resolves authoritative decoder indices.
const fps = video?.fps ?? null;
const frameCount =
video && fps && video.durationSeconds > 0 ? Math.max(1, Math.round(video.durationSeconds * fps)) : null;
@@ -1285,17 +1302,28 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {
? 0
: Math.max(0, Math.min(frameCount - 1, numericValue < 0 ? frameCount + numericValue : numericValue));
+ const posterUrl = video?.thumbnailUrl ?? null;
+ const pickerFallback = useMemo(
+ () => (posterUrl === null ? null : <VideoFramePickerFallback posterUrl={posterUrl} />),
+ [posterUrl]
+ );
+
return (
<Flex direction="column" gap="1" w="full">
<NumericInput {...props} />
{video && fps !== null && frameCount !== null ? (
- <FrameScrubber
- fps={fps}
- frameCount={frameCount}
- resolvedIndex={resolvedIndex}
- videoUrl={video.fullUrl}
- onChange={onChange}
- />
+ <Suspense fallback={pickerFallback}>
+ <VideoFramePicker
+ key={video.fullUrl}
+ fieldValue={numericValue}
+ fps={fps}
+ frameCount={frameCount}
+ posterUrl={video.thumbnailUrl}
+ resolvedIndex={resolvedIndex}
+ videoUrl={video.fullUrl}
+ onChange={onChange}
+ />
+ </Suspense>
) : (
<Flex borderStyle="dashed" borderWidth="1px" justifyContent="center" px="2" py="2" rounded="sm">
<Text color="fg.subtle" fontSize="md" textAlign="center">
@@ -1315,91 +1343,6 @@ const VideoFrameIndexInput = (props: WorkflowFieldInputProps) => {
);
};
-const FRAME_SLIDER_ARIA_LABEL = ['Frame'];
-const FRAME_VIDEO_STYLE = { height: '100%', objectFit: 'contain', width: '100%' } as const;
-
-const FrameScrubber = ({
- fps,
- frameCount,
- onChange,
- resolvedIndex,
- videoUrl,
-}: {
- fps: number;
- frameCount: number;
- onChange: (value: unknown) => void;
- resolvedIndex: number;
- videoUrl: string;
-}) => {
- const videoRef = useRef<HTMLVideoElement>(null);
-
- // Seek inside each frame's display interval to avoid boundary decoding artifacts.
- useEffect(() => {
- const el = videoRef.current;
-
- if (!el) {
- return;
- }
-
- const setTime = () => {
- try {
- el.currentTime = (resolvedIndex + 0.5) / fps;
- } catch {
- // Some browsers throw when seeking an element that isn't ready; the
- // preview keeps its previous frame and the next effect run re-seeks.
- }
- };
-
- if (el.readyState >= 1) {
- setTime();
- } else {
- el.addEventListener('loadedmetadata', setTime, { once: true });
-
- return () => el.removeEventListener('loadedmetadata', setTime);
- }
- }, [fps, resolvedIndex, videoUrl]);
-
- const onSliderChange = useCallback(
- ({ value: next }: { value: number[] }) => {
- if (next[0] !== undefined) {
- onChange(next[0]);
- }
- },
- [onChange]
- );
- const sliderValue = useMemo(() => [resolvedIndex], [resolvedIndex]);
-
- return (
- <Flex className="nodrag" direction="column" gap="1" w="full">
- <Box borderWidth="1px" h="32" overflow="hidden" position="relative" rounded="sm" w="full">
- <video ref={videoRef} muted playsInline preload="auto" src={videoUrl} style={FRAME_VIDEO_STYLE} />
- <Badge
- bottom="1"
- fontVariantNumeric="tabular-nums"
- insetInlineEnd="1"
- pointerEvents="none"
- position="absolute"
- variant="solid"
- >
- {`${resolvedIndex} / ${frameCount - 1}`}
- </Badge>
- </Box>
- {/* A single-frame video would give the slider min === max, which zag renders as NaN% CSS. */}
- {frameCount > 1 ? (
- <Slider
- aria-label={FRAME_SLIDER_ARIA_LABEL}
- max={frameCount - 1}
- min={0}
- step={1}
- value={sliderValue}
- withThumbTooltip
- onValueChange={onSliderChange}
- />
- ) : null}
- </Flex>
- );
-};
-
/** Convert workflow alpha integers 0–255 locally; platform RgbaColor uses unit alpha. */
const toColorFieldValue = (color: string): Record<string, number> => {
const { a, b, g, r } = parseHexColor(color);
diff --git a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts
index 7273d27003..f2682d0c3e 100644
--- a/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts
+++ b/invokeai/frontend/webv2/src/platform/browser/auditAccessibility.testing.ts
@@ -4,12 +4,13 @@ import { settleAnimations } from './settleAnimations.testing';
/**
* Settle animations before axe to avoid transient contrast failures; return violations so callers choose
- * assertions. Architecture checks enforce this entry point.
+ * assertions. Architecture checks enforce this entry point. `options` adds to axe's defaults, for rules it leaves
+ * off, such as WCAG 2.2 `target-size`, which the release journeys run.
*/
-export const auditAccessibility = async (target: Element): Promise<axe.Result[]> => {
+export const auditAccessibility = async (target: Element, options: axe.RunOptions = {}): Promise<axe.Result[]> => {
await settleAnimations();
- return (await axe.run(target)).violations;
+ return (await axe.run(target, options)).violations;
};
/**
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.browser.test.tsx
new file mode 100644
index 0000000000..20a49a09f1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.browser.test.tsx
@@ -0,0 +1,770 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act, Activity, createRef, type ReactNode, type RefObject } 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';
+import { page, userEvent } from 'vitest/browser';
+
+import { VideoPlayer, type VideoPlayerProps } from './VideoPlayer';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+// The mock backend's clip: 64×64 H.264, 10 frames at 10 fps, one second long. Vite serves the package root.
+const FIXTURE_VIDEO_URL = '/scripts/mock-assets/fixture-video.mp4';
+const MISSING_VIDEO_URL = '/missing-video.mp4';
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+
+let host: HTMLDivElement;
+let root: Root;
+let windowKeys: string[];
+const recordWindowKey = (event: KeyboardEvent) => windowKeys.push(event.key);
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ windowKeys = [];
+ window.addEventListener('keydown', recordWindowKey);
+});
+
+afterEach(async () => {
+ window.removeEventListener('keydown', recordWindowKey);
+ await act(() => root.unmount());
+ host.remove();
+});
+
+type TestProps = Partial<VideoPlayerProps> & {
+ videoRef?: RefObject<HTMLVideoElement | null>;
+ wrap?: (player: ReactNode) => ReactNode;
+};
+
+/** Renders (or re-renders) the player beside an outside button, without waiting for media. */
+const mount = async ({ videoRef, wrap = (player) => player, ...props }: TestProps = {}) => {
+ await act(() => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <button type="button">Outside</button>
+ <div style={{ height: props.size === 'compact' ? 128 : 270, width: 480 }}>
+ {wrap(<VideoPlayer ref={videoRef} aria-label="Clip" muted src={FIXTURE_VIDEO_URL} {...props} />)}
+ </div>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
+const renderPlayer = async ({ videoRef = createRef<HTMLVideoElement>(), ...props }: TestProps = {}) => {
+ await mount({ ...props, videoRef });
+ const video = videoRef.current;
+
+ if (!video) {
+ throw new Error('The player did not render its video.');
+ }
+
+ // Controls stay disabled until metadata loads.
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+
+ return { video };
+};
+
+const AUDIT_TARGET_SIZE = { rules: { 'target-size': { enabled: true } } };
+
+const getPlayer = () => page.getByRole('group', { name: 'Clip' }).element() as HTMLElement;
+
+const focus = async (element: Element) => {
+ await act(() => (element as HTMLElement).focus());
+};
+
+const play = async (video: HTMLVideoElement) => {
+ await userEvent.click(page.getByRole('button', { name: 'Play' }));
+ await expect.poll(() => video.paused).toBe(false);
+};
+
+/** Holds still on the clip's playback for a moment, long enough for a wrongly paused element to show it. */
+const settle = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 200);
+ });
+
+/** Dispatches a mouse pointer event at a fraction of the scrubber's width; the slider tracks moves on the document. */
+const scrubPointer = async (
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ fraction: number,
+ modifiers: Pick<PointerEventInit, 'ctrlKey'> = {}
+) => {
+ const control = getPlayer().querySelector('[data-part="control"]');
+
+ if (!control) {
+ throw new Error('The scrubber has no control.');
+ }
+
+ const rect = control.getBoundingClientRect();
+ await act(() => {
+ (type === 'pointerdown' ? control : document).dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ cancelable: true,
+ clientX: rect.left + rect.width * fraction,
+ clientY: rect.top + rect.height / 2,
+ isPrimary: true,
+ pointerId: 1,
+ pointerType: 'mouse',
+ ...modifiers,
+ })
+ );
+ });
+};
+
+/** A press and release on the picture, then its click unless `withClick` is false, from a touch or a mouse. */
+const tapPicture = async (video: HTMLVideoElement, pointerType: 'mouse' | 'touch', withClick = true) => {
+ const rect = video.getBoundingClientRect();
+ const init = {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 3,
+ isPrimary: true,
+ pointerId: 2,
+ pointerType,
+ };
+
+ await act(() => {
+ video.dispatchEvent(new PointerEvent('pointerdown', { ...init, button: 0, buttons: 1 }));
+ video.dispatchEvent(new PointerEvent('pointerup', { ...init, button: 0, buttons: 0 }));
+
+ if (withClick) {
+ video.dispatchEvent(new PointerEvent('click', { ...init, button: 0, detail: 1 }));
+ }
+ });
+};
+
+describe('VideoPlayer', () => {
+ it('plays and pauses from its button, Space on the player, and K', async () => {
+ const { video } = await renderPlayer();
+
+ await play(video);
+ await expect.element(page.getByRole('button', { name: 'Pause' })).toBeVisible();
+
+ await focus(getPlayer());
+ await userEvent.keyboard(' ');
+ await expect.poll(() => video.paused).toBe(true);
+
+ await userEvent.keyboard('k');
+ await expect.poll(() => video.paused).toBe(false);
+ });
+
+ it('leaves Space to a focused button, so it toggles once', async () => {
+ const { video } = await renderPlayer();
+
+ await focus(page.getByRole('button', { name: 'Play' }).element());
+ await userEvent.keyboard(' ');
+
+ await expect.poll(() => video.paused).toBe(false);
+ });
+
+ it("keeps a focused control's activation keys from application hotkeys, which would cancel the press", async () => {
+ // Like a workbench hotkey bound to Space: it runs on the window and prevents the key's default.
+ const appHotkey = (event: KeyboardEvent) => {
+ if (event.key === ' ' || event.key === 'Enter') {
+ event.preventDefault();
+ }
+ };
+ window.addEventListener('keydown', appHotkey);
+
+ try {
+ const { video } = await renderPlayer();
+
+ await focus(page.getByRole('button', { name: 'Play' }).element());
+ await userEvent.keyboard(' ');
+ await expect.poll(() => video.paused).toBe(false);
+
+ await focus(page.getByRole('button', { name: 'Loop' }).element());
+ await userEvent.keyboard('{Enter}');
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toHaveAttribute('aria-pressed', 'false');
+
+ await focus(page.getByRole('button', { name: 'Playback speed: 1×' }).element());
+ await userEvent.keyboard('{Enter}');
+ await expect.element(page.getByRole('menuitemradio', { name: '2×' })).toBeVisible();
+
+ expect(windowKeys).toEqual([]);
+
+ // The opened menu still picks from the keyboard (its keys are the menu's, which application hotkeys skip).
+ await userEvent.keyboard('{End}{Enter}');
+ await expect.poll(() => video.playbackRate).toBe(2);
+ } finally {
+ window.removeEventListener('keydown', appHotkey);
+ }
+ });
+
+ it('shows its tooltips above the bar, clear of whatever sits below the player', async () => {
+ await renderPlayer({ size: 'compact' });
+ const play = page.getByRole('button', { name: 'Play' });
+
+ await userEvent.hover(play);
+ const tooltip = page.getByRole('tooltip');
+ await expect.element(tooltip).toBeVisible();
+
+ expect(tooltip.element().getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ play.element().getBoundingClientRect().top
+ );
+ });
+
+ it('toggles once for a double-click on the video', async () => {
+ const { video } = await renderPlayer();
+
+ await userEvent.dblClick(video);
+ await settle();
+
+ expect(video.paused).toBe(false);
+ });
+
+ it('loops by default and toggles looping from L and its button', async () => {
+ const { video } = await renderPlayer();
+ const loopButton = page.getByRole('button', { name: 'Loop' });
+
+ expect(video.loop).toBe(true);
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'true');
+
+ await focus(getPlayer());
+ await userEvent.keyboard('l');
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'false');
+ expect(video.loop).toBe(false);
+
+ await userEvent.click(loopButton);
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'true');
+ expect(video.loop).toBe(true);
+ });
+
+ it('reports loop changes without changing a controlled loop', async () => {
+ const onLoopChange = vi.fn();
+ const { video } = await renderPlayer({ loop: false, onLoopChange });
+ const loopButton = page.getByRole('button', { name: 'Loop' });
+
+ await userEvent.click(loopButton);
+
+ expect(onLoopChange).toHaveBeenCalledExactlyOnceWith(true);
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'false');
+ expect(video.loop).toBe(false);
+ });
+
+ it('wraps a playback window back to its start instead of playing on', async () => {
+ const seeks: number[] = [];
+ const onEnded = vi.fn();
+ const { video } = await renderPlayer({
+ playbackWindow: { endSeconds: 0.5, startSeconds: 0.2 },
+ onEnded,
+ onSeeking: (event) => seeks.push(event.currentTarget.currentTime),
+ });
+
+ // The window, not the element, loops.
+ expect(video.loop).toBe(false);
+ await play(video);
+
+ await expect.poll(() => seeks.some((time) => Math.abs(time - 0.2) < 1e-6), { timeout: 3000 }).toBe(true);
+ expect(onEnded).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { from: 'the clip start', startAt: 0 },
+ { from: 'the window start, as a caller asking for the window does', startAt: 0.2 },
+ ])(
+ 'plays a window once from $from, rests on its last frame while looping is off, and replays it',
+ async ({ startAt }) => {
+ const seeks: number[] = [];
+ const onEnded = vi.fn();
+ const onPlay = vi.fn();
+ // Frames 2 to 4: the end is frame 5's start, exclusive.
+ const { video } = await renderPlayer({
+ defaultLoop: false,
+ fps: 10,
+ onEnded,
+ onPlay,
+ onSeeking: (event) => seeks.push(event.currentTarget.currentTime),
+ playbackWindow: { endSeconds: 0.5, startSeconds: 0.2 },
+ });
+ const isResting = () => video.paused && !video.seeking && Math.abs(video.currentTime - 0.45) < 1e-6;
+ const playButton = page.getByRole('button', { name: 'Play' });
+
+ expect(video.loop).toBe(false);
+
+ if (startAt > 0) {
+ await act(() => {
+ video.currentTime = startAt;
+ });
+ await expect.poll(() => video.seeking).toBe(false);
+ seeks.length = 0;
+ }
+
+ await userEvent.click(playButton);
+
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+ await expect.element(page.getByText('Frame 4 / 9')).toBeVisible();
+ expect(onPlay).toHaveBeenCalledOnce();
+ expect(seeks).toHaveLength(1);
+ expect(seeks[0]).toBeCloseTo(0.45);
+
+ // The replay is a 0.3 s window, which a slow runner can finish before any poll sees it playing; the record proves
+ // it happened: a second play, a rewind to the window start, and the rest again.
+ await userEvent.click(playButton);
+
+ await expect.poll(() => onPlay.mock.calls.length).toBe(2);
+ await expect.poll(() => seeks.length, { timeout: 3000 }).toBe(3);
+ expect(seeks[1]).toBeCloseTo(0.2);
+ expect(seeks[2]).toBeCloseTo(0.45);
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+ expect(onEnded).not.toHaveBeenCalled();
+ }
+ );
+
+ it('loops the whole clip for a collapsed playback window', async () => {
+ const { video } = await renderPlayer({ playbackWindow: { endSeconds: 0.4, startSeconds: 0.4 } });
+
+ expect(video.loop).toBe(true);
+ });
+
+ it('steps one frame at a time with a frame rate and shows the frame', async () => {
+ const { video } = await renderPlayer({ fps: 10 });
+
+ await expect.element(page.getByText('Frame 0 / 9')).toBeVisible();
+ await focus(getPlayer());
+ await userEvent.keyboard('.');
+ await expect.element(page.getByText('Frame 1 / 9')).toBeVisible();
+ expect(video.currentTime).toBeCloseTo(0.15);
+
+ await userEvent.click(page.getByRole('button', { name: 'Next frame' }));
+ await expect.element(page.getByText('Frame 2 / 9')).toBeVisible();
+
+ await focus(getPlayer());
+ await userEvent.keyboard(',,,');
+ await expect.element(page.getByText('Frame 0 / 9')).toBeVisible();
+ expect(video.currentTime).toBeCloseTo(0.05);
+ });
+
+ it('never loses a frame step pressed while earlier seeks are still pending', async () => {
+ const { video } = await renderPlayer({ fps: 10 });
+
+ // Faster than any key repeat: every press lands while all the earlier seeks are pending.
+ await act(() => {
+ for (let press = 0; press < 12; press += 1) {
+ getPlayer().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: '.' }));
+ }
+ });
+
+ await expect.element(page.getByText('Frame 9 / 9')).toBeVisible();
+ expect(video.currentTime).toBeCloseTo(0.95);
+ });
+
+ it('puts the scrubber thumb at the end of the track on the last frame', async () => {
+ await renderPlayer({ fps: 10 });
+ const seek = page.getByRole('slider', { name: 'Seek' });
+
+ await focus(getPlayer());
+
+ for (let frame = 1; frame <= 9; frame += 1) {
+ await userEvent.keyboard('.');
+ await expect.element(page.getByText(`Frame ${frame} / 9`)).toBeVisible();
+ }
+
+ await expect.element(seek).toHaveAttribute('aria-valuenow', seek.element().getAttribute('aria-valuemax'));
+ await expect.element(seek).toHaveAttribute('aria-valuetext', 'Frame 9, last 9');
+ });
+
+ it('takes a given frame count over the one the duration implies', async () => {
+ const { video } = await renderPlayer({ fps: 10, frameCount: 5 });
+
+ await expect.element(page.getByText('Frame 0 / 4')).toBeVisible();
+ await focus(getPlayer());
+ await userEvent.keyboard('.'.repeat(6));
+
+ await expect.element(page.getByText('Frame 4 / 4')).toBeVisible();
+ expect(video.currentTime).toBeCloseTo(0.45);
+ });
+
+ it('pauses while the scrubber is dragged, lands where it points, and resumes after', async () => {
+ const { video } = await renderPlayer();
+ await play(video);
+
+ await scrubPointer('pointerdown', 0.3);
+ await scrubPointer('pointermove', 0.537);
+ await settle();
+
+ expect(video.paused).toBe(true);
+ // Finer than the 0.1 s arrow-key step.
+ expect(video.currentTime).toBeCloseTo(0.537, 2);
+ expect(getPlayer().hasAttribute('data-controls-hidden')).toBe(false);
+
+ await scrubPointer('pointerup', 0.537);
+ await expect.poll(() => video.paused).toBe(false);
+ });
+
+ it('leaves playback alone for a modified click on the scrubber, which starts no drag', async () => {
+ const { video } = await renderPlayer();
+ await play(video);
+
+ await scrubPointer('pointerdown', 0.5, { ctrlKey: true });
+ await scrubPointer('pointerup', 0.5, { ctrlKey: true });
+ await settle();
+
+ expect(video.paused).toBe(false);
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+ });
+
+ it('drops a drag the player cancels by changing source, without pinning the controls', async () => {
+ const { video } = await renderPlayer();
+ await play(video);
+ await scrubPointer('pointerdown', 0.3);
+ expect(video.paused).toBe(true);
+
+ await mount({ src: `${FIXTURE_VIDEO_URL}?second` });
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+ // The slider cancelled the drag, so this release ends nothing and resumes nothing.
+ await scrubPointer('pointerup', 0.3);
+ await settle();
+ expect(video.paused).toBe(true);
+
+ await play(video);
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+
+ // A new drag starts from the current state: playing, so it resumes.
+ await scrubPointer('pointerdown', 0.3);
+ expect(video.paused).toBe(true);
+ await scrubPointer('pointerup', 0.3);
+ await expect.poll(() => video.paused).toBe(false);
+ });
+
+ it('moves the scrubber by a coarser step from arrow keys than a drag', async () => {
+ const { video } = await renderPlayer();
+ const seek = page.getByRole('slider', { name: 'Seek' });
+
+ await focus(seek.element());
+ await userEvent.keyboard('{ArrowRight}{ArrowRight}');
+ await expect.poll(() => video.currentTime).toBeCloseTo(0.2);
+
+ await userEvent.keyboard('{ArrowLeft}');
+ await expect.poll(() => video.currentTime).toBeCloseTo(0.1);
+ });
+
+ it('hides idle controls while playing until keyboard focus or a pause brings them back', async () => {
+ const { video } = await renderPlayer();
+ await play(video);
+ const controls = getPlayer().querySelector('[data-video-player-controls]');
+
+ if (!controls) {
+ throw new Error('The player has no controls.');
+ }
+
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+ await expect.poll(() => getComputedStyle(controls).opacity).toBe('0');
+
+ await userEvent.tab();
+ await expect.poll(() => getComputedStyle(controls).opacity).toBe('1');
+
+ await userEvent.keyboard('k');
+ await expect.poll(() => video.paused).toBe(true);
+ expect(getPlayer().hasAttribute('data-controls-hidden')).toBe(false);
+ });
+
+ it('brings hidden controls back for a touch tap on the picture without pausing; a mouse click still pauses', async () => {
+ const { video } = await renderPlayer();
+ await play(video);
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+
+ await tapPicture(video, 'touch');
+ await settle();
+
+ expect(getPlayer().hasAttribute('data-controls-hidden')).toBe(false);
+ expect(video.paused).toBe(false);
+
+ // With the controls showing, a tap plays and pauses as a click does.
+ await tapPicture(video, 'touch');
+ await expect.poll(() => video.paused).toBe(true);
+
+ await play(video);
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+
+ await tapPicture(video, 'mouse');
+ await expect.poll(() => video.paused).toBe(true);
+
+ // A touch press that ends in no click (a swipe) leaves a later activation without a press, such as assistive
+ // technology's, to play and pause.
+ await play(video);
+ await userEvent.unhover(getPlayer());
+ await expect.poll(() => getPlayer().hasAttribute('data-controls-hidden')).toBe(true);
+ await tapPicture(video, 'touch', false);
+ await act(() => video.click());
+ await expect.poll(() => video.paused).toBe(true);
+ });
+
+ it('offers no frame stepping without a frame rate', async () => {
+ const { video } = await renderPlayer();
+
+ expect(page.getByRole('button', { name: 'Next frame' }).query()).toBeNull();
+ await focus(getPlayer());
+ await userEvent.keyboard('.');
+ expect(video.currentTime).toBe(0);
+ });
+
+ it('changes speed and mute from the bar', async () => {
+ const { video } = await renderPlayer({ muted: false });
+
+ await userEvent.click(page.getByRole('button', { name: 'Playback speed: 1×' }));
+ await userEvent.click(page.getByRole('menuitemradio', { name: '2×' }));
+ await expect.poll(() => video.playbackRate).toBe(2);
+ await expect.element(page.getByRole('button', { name: 'Playback speed: 2×' })).toBeVisible();
+
+ await focus(getPlayer());
+ await userEvent.keyboard('m');
+ await expect.poll(() => video.muted).toBe(true);
+ await expect.element(page.getByRole('button', { name: 'Unmute' })).toBeVisible();
+ });
+
+ it('ignores its shortcuts while focus is outside the player', async () => {
+ const { video } = await renderPlayer({ fps: 10 });
+
+ await focus(page.getByRole('button', { name: 'Outside' }).element());
+ await userEvent.keyboard('kl.');
+
+ expect(video.paused).toBe(true);
+ expect(video.loop).toBe(true);
+ expect(video.currentTime).toBe(0);
+ expect(windowKeys).toEqual(['k', 'l', '.']);
+ });
+
+ it('keeps its shortcuts from the page even where they do nothing', async () => {
+ const { video } = await renderPlayer({ muted: false, size: 'compact' });
+
+ await focus(getPlayer());
+ // No frame rate, and compact has no volume or fullscreen.
+ await userEvent.keyboard(',.mf');
+
+ expect(video.muted).toBe(false);
+ expect(windowKeys).toEqual([]);
+ });
+
+ it('leaves modified keys to the page', async () => {
+ const { video } = await renderPlayer();
+
+ await focus(getPlayer());
+ await userEvent.keyboard('{Shift>}k{/Shift}');
+
+ expect(video.paused).toBe(true);
+ expect(windowKeys.map((key) => key.toLowerCase())).toEqual(['shift', 'k']);
+ });
+
+ it('leaves a media error to the caller, offers no controls, and keeps its shortcuts', async () => {
+ const onError = vi.fn();
+ await mount({ onError, src: MISSING_VIDEO_URL });
+
+ await expect.poll(() => onError.mock.calls.length, { timeout: 5000 }).toBe(1);
+ expect(page.getByRole('button', { name: 'Play' }).query()).toBeNull();
+ expect(page.getByRole('slider', { name: 'Seek' }).query()).toBeNull();
+
+ await focus(getPlayer());
+ await userEvent.keyboard(' fmk');
+ expect(windowKeys).toEqual([]);
+ });
+
+ it('keeps focus in the player when a new source takes its controls away', async () => {
+ const onError = vi.fn();
+ await renderPlayer({ onError });
+ await focus(page.getByRole('button', { name: 'Loop' }).element());
+
+ await mount({ onError, src: MISSING_VIDEO_URL });
+
+ await expect.poll(() => onError.mock.calls.length, { timeout: 5000 }).toBe(1);
+ expect(document.activeElement).toBe(getPlayer());
+ });
+
+ it('pauses when hidden', async () => {
+ const videoRef = createRef<HTMLVideoElement>();
+ const { video } = await renderPlayer({ videoRef, wrap: (player) => <Activity mode="visible">{player}</Activity> });
+ await play(video);
+
+ await mount({ videoRef, wrap: (player) => <Activity mode="hidden">{player}</Activity> });
+
+ expect(video.paused).toBe(true);
+ });
+
+ it('keeps playing when a caller passes a new ref callback each render', async () => {
+ const elements: (HTMLVideoElement | null)[] = [];
+ await mount({ ref: (element) => void elements.push(element) });
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+ const video = elements.at(-1);
+
+ if (!video) {
+ throw new Error('The player did not render its video.');
+ }
+
+ await play(video);
+ await mount({ ref: (element) => void elements.push(element) });
+ await mount({ ref: (element) => void elements.push(element) });
+ await settle();
+
+ expect(video.paused).toBe(false);
+ expect(elements.at(-1)).toBe(video);
+ });
+
+ it('stops tracking the element once unmounted', async () => {
+ const videoRef = createRef<HTMLVideoElement>();
+ const { video } = await renderPlayer({ playbackWindow: { endSeconds: 0.3, startSeconds: 0.1 }, videoRef });
+ await play(video);
+
+ await act(() => root.unmount());
+ root = createRoot(host);
+ // Unmounting paused it; play the retained element to see whether anything still drives it.
+ expect(video.paused).toBe(true);
+ const requestFrame = vi.spyOn(window, 'requestAnimationFrame');
+ const seeks: number[] = [];
+ video.addEventListener('seeking', () => seeks.push(video.currentTime));
+ video.currentTime = 0.4;
+ void video.play();
+ const onEnded = vi.fn();
+ video.addEventListener('ended', onEnded);
+
+ // A live playback window would have wrapped to 0.1 instead of reaching the end.
+ await expect.poll(() => onEnded.mock.calls.length, { timeout: 3000 }).toBe(1);
+ expect(videoRef.current).toBeNull();
+ expect(seeks).toEqual([0.4]);
+ expect(requestFrame).not.toHaveBeenCalled();
+ requestFrame.mockRestore();
+ video.pause();
+ });
+
+ it.each([220, 320, 420, 720])('fits its bar into %i px, showing what fits and dropping the rest', async (width) => {
+ const { video } = await renderPlayer({
+ fps: 10,
+ muted: false,
+ wrap: (player) => <div style={{ height: 240, width }}>{player}</div>,
+ });
+ const rootBox = getPlayer().getBoundingClientRect();
+ const controls = [...getPlayer().querySelectorAll('button, [role="slider"]')].filter((control) =>
+ control.checkVisibility()
+ );
+
+ for (const control of controls) {
+ const box = control.getBoundingClientRect();
+
+ expect(box.left, control.getAttribute('aria-label') ?? '').toBeGreaterThanOrEqual(rootBox.left);
+ expect(box.right, control.getAttribute('aria-label') ?? '').toBeLessThanOrEqual(rootBox.right);
+ }
+
+ for (const name of ['Play', 'Loop', 'Full screen']) {
+ await expect.element(page.getByRole('button', { exact: true, name })).toBeVisible();
+ }
+
+ await expect.element(page.getByRole('slider', { name: 'Seek' })).toBeVisible();
+ await expect.element(page.getByText('0:00 / 0:01')).toBeVisible();
+
+ // Role queries see only what is in the accessibility tree: a dropped control is gone from it, and from the tab
+ // order, not just out of sight.
+ const count = (role: 'button' | 'slider', name: string) =>
+ page.getByRole(role, { exact: true, name }).elements().length;
+ const isWide = width >= 450;
+
+ expect(count('slider', 'Volume')).toBe(isWide ? 1 : 0);
+ expect(count('button', 'Mute')).toBe(isWide ? 1 : 0);
+ // Below that, the volume button opens the level and mute in a popover.
+ expect(count('button', 'Volume')).toBe(isWide ? 0 : 1);
+ expect(count('button', 'Playback speed: 1×')).toBe(width >= 250 ? 1 : 0);
+ expect(count('button', 'Previous frame')).toBe(width >= 310 ? 1 : 0);
+ expect(count('button', 'Next frame')).toBe(width >= 310 ? 1 : 0);
+ expect(
+ page
+ .getByText(/^Frame /)
+ .elements()
+ .filter((readout) => readout.checkVisibility())
+ ).toHaveLength(width >= 370 ? 1 : 0);
+
+ if (width === 220) {
+ // The dropped controls' shortcuts stay.
+ await focus(getPlayer());
+ await userEvent.keyboard('.m');
+ await expect.poll(() => video.currentTime).toBeCloseTo(0.15);
+ expect(video.muted).toBe(true);
+ expect(await auditAccessibility(host, AUDIT_TARGET_SIZE)).toEqual([]);
+ }
+ });
+
+ it('keeps volume and mute reachable from a popover on a narrow bar, by pointer and keyboard', async () => {
+ const { video } = await renderPlayer({
+ muted: false,
+ wrap: (player) => <div style={{ width: 300 }}>{player}</div>,
+ });
+ const trigger = page.getByRole('button', { exact: true, name: 'Volume' });
+
+ await userEvent.click(trigger);
+ const popover = page.getByRole('dialog');
+ await expect.element(popover).toBeVisible();
+
+ await userEvent.click(popover.getByRole('button', { exact: true, name: 'Mute' }));
+ await expect.poll(() => video.muted).toBe(true);
+ await expect.element(popover.getByRole('button', { exact: true, name: 'Unmute' })).toBeVisible();
+ expect(await auditAccessibility(popover.element(), AUDIT_TARGET_SIZE)).toEqual([]);
+
+ await userEvent.keyboard('{Escape}');
+ await expect.element(popover).not.toBeInTheDocument();
+ await expect.poll(() => document.activeElement).toBe(trigger.element());
+
+ // Keyboard alone: open it, set the level, and the player's shortcuts work from inside it.
+ await userEvent.keyboard('{Enter}');
+ // Opening moves focus to the popover's first control (still muted from above); let it land before moving on.
+ await expect.element(page.getByRole('button', { exact: true, name: 'Unmute' })).toHaveFocus();
+ await userEvent.tab();
+ await expect.element(page.getByRole('slider', { name: 'Volume' })).toHaveFocus();
+ await userEvent.keyboard('{End}');
+ await expect.poll(() => video.volume).toBe(1);
+ expect(video.muted).toBe(false);
+ await userEvent.keyboard('m');
+ await expect.poll(() => video.muted).toBe(true);
+ // Escape (the popover's dismissal) and Tab (focus movement) reach the page as they do from any popover.
+ expect(windowKeys.filter((key) => key !== 'Escape' && key !== 'Tab')).toEqual([]);
+ });
+
+ // Thumbs at the ends of their tracks sit closest to the buttons beside them, where target spacing is tightest.
+ it.each([
+ { position: 'start', size: 'compact', volume: 1 },
+ { position: 'end', size: 'compact', volume: 1 },
+ { position: 'start', size: 'full', volume: 0 },
+ { position: 'end', size: 'full', volume: 1 },
+ ] as const)(
+ 'passes an accessibility audit at $size size with the scrubber at its $position and volume at $volume',
+ async ({ position, size, volume }) => {
+ const { video } = await renderPlayer({ fps: 10, muted: false, size });
+
+ await act(() => {
+ video.volume = volume;
+ video.currentTime = position === 'start' ? 0 : video.duration;
+ });
+ await expect
+ .poll(() => page.getByRole('slider', { name: 'Seek' }).element().getAttribute('aria-valuenow'))
+ .toBe(position === 'start' ? '0' : '0.9');
+
+ if (size === 'full') {
+ // The volume thumb at full volume sits beside it.
+ await expect.element(page.getByRole('button', { name: 'Full screen' })).toBeVisible();
+ }
+
+ // WCAG 2.2 target spacing, which axe leaves off by default and the release journeys run.
+ expect(await auditAccessibility(host, AUDIT_TARGET_SIZE)).toEqual([]);
+ }
+ );
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.tsx b/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.tsx
new file mode 100644
index 0000000000..718b9d956e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/VideoPlayer.tsx
@@ -0,0 +1,1163 @@
+import type { LucideIcon } from 'lucide-react';
+
+import {
+ Box,
+ Center,
+ chakra,
+ HStack,
+ Icon,
+ Kbd,
+ Menu,
+ mergeRefs,
+ Popover,
+ Portal,
+ Spinner,
+ Stack,
+ Text,
+} from '@chakra-ui/react';
+import { isImeComposing } from '@platform/browser/imeComposition';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+import { Button, IconButton } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { PopoverContent } from '@platform/ui/Popover';
+import { Slider } from '@platform/ui/Slider';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import {
+ MaximizeIcon,
+ MinimizeIcon,
+ PauseIcon,
+ PlayIcon,
+ RepeatIcon,
+ StepBackIcon,
+ StepForwardIcon,
+ Volume1Icon,
+ Volume2Icon,
+ VolumeXIcon,
+} from 'lucide-react';
+import {
+ useCallback,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type CSSProperties,
+ type KeyboardEvent,
+ type MouseEvent,
+ type PointerEvent,
+ type ReactNode,
+ type Ref,
+ type SyntheticEvent,
+ type VideoHTMLAttributes,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createMediaElementStore, type MediaElementSnapshot, type MediaElementStore } from './mediaElementStore';
+import {
+ clampPlaybackWindow,
+ formatMediaTime,
+ getFrameAtTime,
+ getFrameCount,
+ getFrameTime,
+ getPlaybackWindowRest,
+ getScrubSteps,
+ type PlaybackWindow,
+} from './videoTimeline';
+
+export interface VideoPlayerProps extends Omit<
+ VideoHTMLAttributes<HTMLVideoElement>,
+ 'aria-label' | 'children' | 'controls' | 'loop' | 'src'
+> {
+ /** Names the player. */
+ 'aria-label': string;
+ src: string;
+ /** Enables frame stepping and the frame readout. */
+ fps?: number;
+ /**
+ * The clip's frames, when the caller knows them (a probed count): it is authoritative over `duration × fps`, which
+ * container rounding can make disagree. Without it the count is derived from the duration. Needs `fps`.
+ */
+ frameCount?: number;
+ /** Controlled loop state; pair with `onLoopChange`. */
+ loop?: boolean;
+ /** Initial loop state when uncontrolled. */
+ defaultLoop?: boolean;
+ onLoopChange?: (loop: boolean) => void;
+ /**
+ * Plays this window instead of the whole clip. Playback that reaches its end wraps to its start while looping;
+ * otherwise it pauses on the window's last frame, and playing from there starts the window over. It is clamped to
+ * the media; a collapsed or inverted window is none, so playback covers the whole clip. Seeks never act on it, and
+ * one that leaves it keeps it: retiring it is the caller's call (`onSeeking`). A new window takes effect in the passive
+ * effects of the commit that renders it; playback started before then (a caller's `play()` in the same task) is
+ * judged against the previous window, so a caller starts it from an effect after the player's in that commit.
+ */
+ playbackWindow?: PlaybackWindow | null;
+ /** `compact` fits a small box: play, loop, scrubber and one readout; volume and fullscreen are left out. */
+ size?: 'compact' | 'full';
+ /** Caller content above the video and below the controls; the caller positions it. */
+ overlay?: ReactNode;
+ /** The video element, for behavior the player does not own. */
+ ref?: Ref<HTMLVideoElement>;
+}
+
+type PlayerSize = NonNullable<VideoPlayerProps['size']>;
+
+/** The frames of the clip; null without a frame rate. */
+interface FrameTiming {
+ fps: number;
+ /** Authoritative count from the caller, or null to derive it from the duration. */
+ frameCount: number | null;
+}
+
+const resolveFrameCount = ({ fps, frameCount }: FrameTiming, duration: number): number =>
+ frameCount ?? getFrameCount(duration, fps);
+
+const PLAYBACK_RATES = [0.25, 0.5, 1, 2] as const;
+const CONTROLS_IDLE_MS = 2000;
+const VIDEO_STYLE: CSSProperties = { display: 'block', height: '100%', objectFit: 'contain', width: '100%' };
+// The control bar and the player's own popups carry these.
+const VIDEO_PLAYER_CONTROLS_ATTRIBUTE = 'data-video-player-controls';
+const VIDEO_PLAYER_POPUP_ATTRIBUTE = 'data-video-player-popup';
+
+/** Whether `target` is in a player's control bar or one of its popups, so a caller can tell their input from the picture's. */
+export const isVideoPlayerControlsTarget = (target: Element): boolean =>
+ target.closest(`[${VIDEO_PLAYER_CONTROLS_ATTRIBUTE}], [${VIDEO_PLAYER_POPUP_ATTRIBUTE}]`) !== null;
+// Idle controls fade out, but stay focusable: keyboard focus inside the player, or the pointer resting on the bar,
+// keeps them shown.
+const CONTROLS_SHOWN_ANYWAY = `:has(:focus-visible, [${VIDEO_PLAYER_CONTROLS_ATTRIBUTE}]:hover)`;
+const CONTROLS_HIDDEN = `[data-controls-hidden]:not(${CONTROLS_SHOWN_ANYWAY})`;
+const PLAYER_CONTAINER = 'video-player';
+
+/**
+ * The full bar fits the player's own width by dropping controls, in this order as it narrows. Thresholds come from
+ * measuring the bar: each leaves about 25px spare for the controls still shown, room for a longer clip's time.
+ * - Below 450px the volume slider moves into a popover that the volume button opens, beside a mute toggle.
+ * - Below 370px the frame readout goes; the time stays.
+ * - Below 310px the frame-step buttons go; `,` and `.` still step.
+ * - Below 250px the speed menu goes, and the speed can no longer be changed.
+ * Play, loop, the scrubber, the time, volume and fullscreen always stay, and fit down to about 180px. A dropped control
+ * leaves the tab order and the accessibility tree; one that had focus when the player narrowed loses it.
+ */
+const hiddenBelow = (width: number) => ({
+ [`@container ${PLAYER_CONTAINER} (width < ${width}px)`]: { display: 'none' },
+});
+const hiddenFrom = (width: number) => ({
+ [`@container ${PLAYER_CONTAINER} (width >= ${width}px)`]: { display: 'none' },
+});
+const VOLUME_POPOVER_BELOW = 450;
+const VOLUME_INLINE_CSS = { display: 'flex', ...hiddenBelow(VOLUME_POPOVER_BELOW) };
+const VOLUME_POPOVER_CSS = { display: 'flex', ...hiddenFrom(VOLUME_POPOVER_BELOW) };
+const FRAME_READOUT_CSS = hiddenBelow(370);
+const FRAME_STEP_CSS = hiddenBelow(310);
+const PLAYBACK_RATE_CSS = { display: 'flex', ...hiddenBelow(250) };
+
+const ROOT_CSS = {
+ // The full bar drops controls by the player's own width, wherever it is placed.
+ containerName: PLAYER_CONTAINER,
+ containerType: 'inline-size',
+ [`&${CONTROLS_HIDDEN}`]: { cursor: 'none' },
+ [`&${CONTROLS_HIDDEN} [${VIDEO_PLAYER_CONTROLS_ATTRIBUTE}]`]: {
+ opacity: 0,
+ pointerEvents: 'none',
+ },
+};
+
+// The controls sit on a dark scrim in every theme, so they use fixed light colors.
+const SCRIM_BUTTON_HOVER = { bg: 'whiteAlpha.200' } as const;
+// The playback window is shaded under the progress fill (`::before` paints before the absolutely placed range).
+const SCRIM_SLIDER_CSS = {
+ '--slider-track-size': 'sizes.1',
+ '& [data-part="track"]': { bg: 'whiteAlpha.300', position: 'relative' },
+ '&[data-playback-window] [data-part="track"]::before': {
+ bg: 'whiteAlpha.500',
+ content: '""',
+ insetBlock: '0',
+ insetInlineEnd: 'var(--video-window-end)',
+ insetInlineStart: 'var(--video-window-start)',
+ pointerEvents: 'none',
+ position: 'absolute',
+ },
+};
+const MOTION_REDUCE = { transitionDuration: '0s' } as const;
+const CONTROLS_BAR_PROPS = {
+ [VIDEO_PLAYER_CONTROLS_ATTRIBUTE]: '',
+ _motionReduce: MOTION_REDUCE,
+ bgGradient: 'to-t',
+ bottom: '0',
+ color: 'white',
+ gradientFrom: 'blackAlpha.800',
+ gradientTo: 'transparent',
+ insetX: '0',
+ position: 'absolute',
+ transitionDuration: 'moderate',
+ transitionProperty: 'opacity',
+} as const;
+const RATE_MENU_POSITIONING = { placement: 'top-end' } as const;
+
+/**
+ * The player's shortcuts. While focus is inside the player they are always its own, even when one does nothing in
+ * the current state or size, so they never reach application hotkeys behind it.
+ */
+const PLAYER_KEYS = new Set([' ', ',', '.', 'f', 'k', 'l', 'm']);
+// Keys these targets own outright, and the activation key buttons and links own.
+const KEY_OWNER_SELECTOR = 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="menu"]';
+const ACTIVATION_OWNER_SELECTOR = 'button, a[href], [role="button"]';
+const ACTIVATION_KEYS = new Set([' ', 'enter']);
+
+interface PlayerStatus {
+ duration: number;
+ error: boolean;
+ paused: boolean;
+ ready: boolean;
+ waiting: boolean;
+}
+
+const selectStatus = (snapshot: MediaElementSnapshot): PlayerStatus => ({
+ duration: snapshot.duration,
+ error: snapshot.error,
+ paused: snapshot.paused,
+ ready: snapshot.ready,
+ waiting: snapshot.waiting,
+});
+const selectPlaybackRate = (snapshot: MediaElementSnapshot): number => snapshot.playbackRate;
+const selectVolume = (snapshot: MediaElementSnapshot) => ({ muted: snapshot.muted, volume: snapshot.volume });
+
+const useMediaSelector = <Selected,>(
+ store: MediaElementStore,
+ selector: (snapshot: MediaElementSnapshot) => Selected
+): Selected => useExternalStoreSelector(store.subscribe, store.getSnapshot, selector);
+
+const subscribeFullscreenChange = (listener: () => void): (() => void) => {
+ document.addEventListener('fullscreenchange', listener);
+
+ return () => document.removeEventListener('fullscreenchange', listener);
+};
+const getFullscreenElement = (): Element | null => document.fullscreenElement;
+const getNoFullscreenElement = (): Element | null => null;
+
+/** Registers the playback window for one mount; key it by every input so a change remounts it. */
+const PlaybackWindowBinding = ({
+ loop,
+ range,
+ restSeconds,
+ store,
+}: {
+ loop: boolean;
+ range: PlaybackWindow;
+ restSeconds: number;
+ store: MediaElementStore;
+}) => {
+ useMountEffect(() => store.setPlaybackWindow(range, { loop, restSeconds }));
+
+ return null;
+};
+
+const ShortcutLabel = ({ label, shortcut }: { label: string; shortcut: string }) => (
+ <HStack gap="1.5">
+ <Text>{label}</Text>
+ <Kbd variant="subtle">{shortcut}</Kbd>
+ </HStack>
+);
+
+interface ControlButtonProps {
+ disabled: boolean;
+ icon: LucideIcon;
+ label: string;
+ /** Inside a fullscreen player, popups render in place: only the fullscreen subtree is visible. */
+ portalled: boolean;
+ pressed?: boolean;
+ shortcut: string;
+ size: PlayerSize;
+ onClick: () => void;
+}
+
+const ControlButton = ({ disabled, icon, label, onClick, portalled, pressed, shortcut, size }: ControlButtonProps) => {
+ const content = useMemo(() => <ShortcutLabel label={label} shortcut={shortcut} />, [label, shortcut]);
+
+ return (
+ // Above the bar, so a tooltip never covers whatever sits below the player.
+ <Tooltip content={content} placement="top" portalled={portalled}>
+ <IconButton
+ _hover={pressed ? undefined : SCRIM_BUTTON_HOVER}
+ aria-label={label}
+ aria-pressed={pressed}
+ color={pressed ? undefined : 'white'}
+ disabled={disabled}
+ flexShrink={0}
+ size={size === 'compact' ? 'xs' : 'sm'}
+ variant={pressed ? 'solid' : 'ghost'}
+ onClick={onClick}
+ >
+ <Icon as={icon} boxSize={size === 'compact' ? '3' : '3.5'} />
+ </IconButton>
+ </Tooltip>
+ );
+};
+
+const ARROW_DIRECTIONS: Partial<Record<string, number>> = { ArrowDown: -1, ArrowLeft: -1, ArrowRight: 1, ArrowUp: 1 };
+
+const Scrubber = ({
+ disabled,
+ frames,
+ playbackWindow,
+ onScrubEnd,
+ onScrubStart,
+ store,
+}: {
+ disabled: boolean;
+ frames: FrameTiming | null;
+ playbackWindow: PlaybackWindow | null;
+ onScrubEnd: () => void;
+ onScrubStart: () => void;
+ store: MediaElementStore;
+}) => {
+ const { t } = useTranslation();
+ // Quantized to the slider's step, so frames that cannot move the thumb do not re-render it.
+ const selectPosition = useCallback(
+ ({ currentTime, duration }: MediaElementSnapshot) => {
+ if (frames === null) {
+ const { pointer } = getScrubSteps(duration);
+
+ return { duration, frameCount: 0, position: Math.min(duration, Math.round(currentTime / pointer) * pointer) };
+ }
+
+ const frameCount = resolveFrameCount(frames, duration);
+
+ // The thumb sits on its frame's start, so a keyboard step lands on the next frame, not past it.
+ return { duration, frameCount, position: getFrameAtTime(currentTime, frames.fps, frameCount) / frames.fps };
+ },
+ [frames]
+ );
+ const { duration, frameCount, position } = useMediaSelector(store, selectPosition);
+ // With frames the last position is the last frame's start, so the thumb reaches the end on the last frame.
+ const max = frames === null ? duration : (frameCount - 1) / frames.fps;
+ const isScrubbable = max > 0;
+ const steps = frames === null ? getScrubSteps(duration) : { keyboard: 1 / frames.fps, pointer: 1 / frames.fps };
+ const value = useMemo(() => [position], [position]);
+ const windowStyle = useMemo(() => {
+ if (!playbackWindow || !isScrubbable) {
+ return undefined;
+ }
+
+ const percentOf = (seconds: number) => Math.min(100, Math.max(0, (seconds / max) * 100));
+
+ return {
+ '--video-window-end': `${100 - percentOf(playbackWindow.endSeconds)}%`,
+ '--video-window-start': `${percentOf(playbackWindow.startSeconds)}%`,
+ } as CSSProperties;
+ }, [isScrubbable, max, playbackWindow]);
+ const ariaLabel = useMemo(() => [t('common.videoPlayer.seek')], [t]);
+ const frameOf = useCallback(
+ (seconds: number) => (frames === null ? 0 : getFrameAtTime(seconds, frames.fps, frameCount)),
+ [frameCount, frames]
+ );
+ const formatValue = useCallback(
+ (seconds: number) =>
+ frames === null ? formatMediaTime(seconds) : t('common.videoPlayer.frame', { frame: frameOf(seconds) }),
+ [frameOf, frames, t]
+ );
+ const getAriaValueText = useCallback(
+ ({ value: seconds }: { value: number }) =>
+ frames === null
+ ? t('common.videoPlayer.timeOfDuration', {
+ current: formatMediaTime(seconds),
+ duration: formatMediaTime(duration),
+ })
+ : t('common.videoPlayer.frameOfLast', { frame: frameOf(seconds), last: frameCount - 1 }),
+ [duration, frameCount, frameOf, frames, t]
+ );
+ // Capture phase: the slider's control stops the pointerdown from bubbling. The conditions are the slider's own for
+ // starting a drag (primary button, no Ctrl/Alt/Meta), so every scrub this starts is one the slider ends or cancels.
+ const handlePointerDownCapture = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (disabled || !isScrubbable || event.button !== 0 || event.ctrlKey || event.altKey || event.metaKey) {
+ return;
+ }
+
+ onScrubStart();
+ },
+ [disabled, isScrubbable, onScrubStart]
+ );
+ // The slider's step is fine so a drag lands anywhere; arrow keys move by the coarser keyboard step instead, which
+ // the slider cannot take separately. A handled key never reaches the slider (it ignores prevented keys).
+ const handleKeyDownCapture = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ const direction = ARROW_DIRECTIONS[event.key];
+
+ if (
+ frames !== null ||
+ direction === undefined ||
+ disabled ||
+ !isScrubbable ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ const step = event.shiftKey ? steps.keyboard * 10 : steps.keyboard;
+ store.seek(store.getSnapshot().currentTime + direction * step);
+ },
+ [disabled, frames, isScrubbable, steps.keyboard, store]
+ );
+ const handleValueChange = useCallback(
+ ({ value: [seconds] }: { value: number[] }) => {
+ if (seconds !== undefined) {
+ store.seek(frames === null ? seconds : getFrameTime(frameOf(seconds), frames.fps));
+ }
+ },
+ [frameOf, frames, store]
+ );
+
+ return (
+ <Slider
+ aria-label={ariaLabel}
+ colorPalette="accent"
+ css={SCRIM_SLIDER_CSS}
+ data-playback-window={windowStyle ? '' : undefined}
+ disabled={disabled || !isScrubbable}
+ flex="1"
+ formatValue={formatValue}
+ getAriaValueText={getAriaValueText}
+ largeStep={steps.keyboard * 10}
+ max={isScrubbable ? max : 1}
+ min={0}
+ minW="0"
+ size="md"
+ step={steps.pointer}
+ style={windowStyle}
+ thumbAlignment="center"
+ value={value}
+ onKeyDownCapture={handleKeyDownCapture}
+ onPointerDownCapture={handlePointerDownCapture}
+ onValueChange={handleValueChange}
+ onValueChangeEnd={onScrubEnd}
+ />
+ );
+};
+
+const READOUT_PROPS = {
+ color: 'whiteAlpha.900',
+ flexShrink: 0,
+ fontVariantNumeric: 'tabular-nums',
+ whiteSpace: 'nowrap',
+} as const;
+
+const TimeReadout = ({
+ frames,
+ size,
+ store,
+}: {
+ frames: FrameTiming | null;
+ size: PlayerSize;
+ store: MediaElementStore;
+}) => {
+ const { t } = useTranslation();
+ const selectReadout = useCallback(
+ ({ currentTime, duration }: MediaElementSnapshot) => {
+ if (frames === null) {
+ return {
+ frame: null,
+ time:
+ size === 'compact'
+ ? formatMediaTime(currentTime)
+ : `${formatMediaTime(currentTime)} / ${formatMediaTime(duration)}`,
+ };
+ }
+
+ const frameCount = resolveFrameCount(frames, duration);
+
+ return {
+ frame: `${getFrameAtTime(currentTime, frames.fps, frameCount)} / ${frameCount - 1}`,
+ time: `${formatMediaTime(currentTime)} / ${formatMediaTime(duration)}`,
+ };
+ },
+ [frames, size]
+ );
+ const { frame, time } = useMediaSelector(store, selectReadout);
+
+ if (size === 'compact') {
+ return (
+ <Text {...READOUT_PROPS} fontSize="xs">
+ {frame ?? time}
+ </Text>
+ );
+ }
+
+ return (
+ // Long clips' times can outgrow the narrowest bar; they truncate there rather than push controls out.
+ <HStack {...READOUT_PROPS} flexShrink={1} fontSize="sm" gap="2" minW="0">
+ <Text truncate>{time}</Text>
+ {frame === null ? null : (
+ <Text color="whiteAlpha.800" css={FRAME_READOUT_CSS} flexShrink={0}>
+ {t('common.videoPlayer.frame', { frame })}
+ </Text>
+ )}
+ </HStack>
+ );
+};
+
+const PlaybackRateMenu = ({
+ disabled,
+ onOpenChange,
+ portalled,
+ store,
+}: {
+ disabled: boolean;
+ onOpenChange: (open: boolean) => void;
+ portalled: boolean;
+ store: MediaElementStore;
+}) => {
+ const { t } = useTranslation();
+ const ids = useTooltipTriggerIds();
+ const rate = useMediaSelector(store, selectPlaybackRate);
+ const rateLabel = t('common.videoPlayer.rate', { rate });
+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);
+ const handleValueChange = useCallback(
+ ({ value }: { value: string }) => store.setPlaybackRate(Number(value)),
+ [store]
+ );
+
+ return (
+ <Menu.Root ids={ids} positioning={RATE_MENU_POSITIONING} onOpenChange={handleOpenChange}>
+ <Tooltip content={t('common.videoPlayer.playbackSpeed')} ids={ids} placement="top" portalled={portalled}>
+ <Menu.Trigger asChild>
+ <Button
+ _hover={SCRIM_BUTTON_HOVER}
+ aria-label={t('common.videoPlayer.playbackSpeedValue', { rate: rateLabel })}
+ color="white"
+ disabled={disabled}
+ flexShrink={0}
+ fontVariantNumeric="tabular-nums"
+ minW="9"
+ size="sm"
+ variant="ghost"
+ >
+ {rateLabel}
+ </Button>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal disabled={!portalled}>
+ <Menu.Positioner>
+ <MenuContent minW="6rem">
+ <Menu.RadioItemGroup value={String(rate)} onValueChange={handleValueChange}>
+ {PLAYBACK_RATES.map((option) => (
+ <Menu.RadioItem key={option} value={String(option)}>
+ <Menu.ItemIndicator />
+ <Menu.ItemText>{t('common.videoPlayer.rate', { rate: option })}</Menu.ItemText>
+ </Menu.RadioItem>
+ ))}
+ </Menu.RadioItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+const formatVolume = (volume: number): string => `${Math.round(volume * 100)}%`;
+const getVolumeValueText = ({ value }: { value: number }): string => formatVolume(value);
+
+const VOLUME_POPOVER_POSITIONING = { placement: 'top-end' } as const;
+const VOLUME_POPUP_PROPS = { [VIDEO_PLAYER_POPUP_ATTRIBUTE]: '' };
+
+const VolumeSlider = ({
+ disabled,
+ onScrim,
+ store,
+ value,
+}: {
+ disabled: boolean;
+ /** On the bar's dark scrim, rather than on a themed panel. */
+ onScrim: boolean;
+ store: MediaElementStore;
+ value: number[];
+}) => {
+ const { t } = useTranslation();
+ const ariaLabel = useMemo(() => [t('common.videoPlayer.volume')], [t]);
+ const handleValueChange = useCallback(
+ ({ value: [next] }: { value: number[] }) => {
+ if (next !== undefined) {
+ store.setVolume(next);
+ }
+ },
+ [store]
+ );
+
+ return (
+ // The margin keeps the thumb's 24px target clear of the buttons beside the slider at either end.
+ <Box mx="1">
+ <Slider
+ aria-label={ariaLabel}
+ colorPalette="accent"
+ css={onScrim ? SCRIM_SLIDER_CSS : undefined}
+ disabled={disabled}
+ formatValue={formatVolume}
+ getAriaValueText={getVolumeValueText}
+ max={1}
+ min={0}
+ size="md"
+ step={0.05}
+ value={value}
+ w={onScrim ? '16' : '24'}
+ onValueChange={handleValueChange}
+ />
+ </Box>
+ );
+};
+
+/** Mute and the volume level: inline on a wide bar; on a narrow one, in a popover the volume button opens. */
+const VolumeControls = ({
+ disabled,
+ onOpenChange,
+ onToggleMute,
+ portalled,
+ store,
+}: {
+ disabled: boolean;
+ onOpenChange: (open: boolean) => void;
+ onToggleMute: () => void;
+ portalled: boolean;
+ store: MediaElementStore;
+}) => {
+ const { t } = useTranslation();
+ const ids = useTooltipTriggerIds();
+ const { muted, volume } = useMediaSelector(store, selectVolume);
+ const silent = muted || volume === 0;
+ const value = useMemo(() => [silent ? 0 : volume], [silent, volume]);
+ const icon = silent ? VolumeXIcon : volume < 0.5 ? Volume1Icon : Volume2Icon;
+ const muteLabel = silent ? t('common.videoPlayer.unmute') : t('common.videoPlayer.mute');
+ const muteContent = useMemo(() => <ShortcutLabel label={muteLabel} shortcut="M" />, [muteLabel]);
+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);
+
+ return (
+ <>
+ <HStack css={VOLUME_INLINE_CSS} flexShrink={0} gap="1.5">
+ <ControlButton
+ disabled={disabled}
+ icon={icon}
+ label={muteLabel}
+ portalled={portalled}
+ shortcut="M"
+ size="full"
+ onClick={onToggleMute}
+ />
+ <VolumeSlider disabled={disabled} store={store} value={value} onScrim />
+ </HStack>
+ <Box css={VOLUME_POPOVER_CSS} flexShrink={0}>
+ <Popover.Root ids={ids} positioning={VOLUME_POPOVER_POSITIONING} onOpenChange={handleOpenChange}>
+ <Tooltip content={t('common.videoPlayer.volume')} ids={ids} placement="top" portalled={portalled}>
+ <Popover.Trigger asChild>
+ <IconButton
+ _hover={SCRIM_BUTTON_HOVER}
+ aria-label={t('common.videoPlayer.volume')}
+ color="white"
+ disabled={disabled}
+ size="sm"
+ variant="ghost"
+ >
+ <Icon as={icon} boxSize="3.5" />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal disabled={!portalled}>
+ <Popover.Positioner>
+ <PopoverContent {...VOLUME_POPUP_PROPS} aria-label={t('common.videoPlayer.volume')} w="auto">
+ <Popover.Body p="1.5">
+ <HStack gap="1.5">
+ <Tooltip content={muteContent} placement="top" portalled={portalled}>
+ <IconButton
+ aria-label={muteLabel}
+ disabled={disabled}
+ size="sm"
+ variant="ghost"
+ onClick={onToggleMute}
+ >
+ <Icon as={icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ <VolumeSlider disabled={disabled} onScrim={false} store={store} value={value} />
+ </HStack>
+ </Popover.Body>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ </Box>
+ </>
+ );
+};
+
+/**
+ * A video with its own controls: play, loop (on by default), an optional playback window, scrubbing, frame steps with
+ * `fps`, speed, volume and fullscreen. `isVideoPlayerControlsTarget` tells the controls' pointer input from the
+ * picture's. Clicking the picture plays and pauses, except that a touch tap while the controls are hidden only brings
+ * them back. Shortcuts act only while focus is inside the player. Hiding or unmounting the player pauses it, so audio
+ * never outlives its controls. Media errors leave the picture to the caller (`onError` and `overlay`) and remove the
+ * controls, since none of them could work.
+ */
+export const VideoPlayer = ({
+ 'aria-label': label,
+ defaultLoop = true,
+ fps: fpsProp,
+ frameCount: frameCountProp,
+ loop: loopProp,
+ onClick,
+ onEmptied,
+ onError,
+ onLoopChange,
+ onPlay,
+ overlay,
+ playbackWindow,
+ ref,
+ size = 'full',
+ style,
+ ...videoProps
+}: VideoPlayerProps) => {
+ const { t } = useTranslation();
+ const [store] = useState(createMediaElementStore);
+ const status = useMediaSelector(store, selectStatus);
+ const fps = fpsProp !== undefined && Number.isFinite(fpsProp) && fpsProp > 0 ? fpsProp : null;
+ const frameCount =
+ frameCountProp !== undefined && Number.isInteger(frameCountProp) && frameCountProp > 0 ? frameCountProp : null;
+ const frames = useMemo(() => (fps === null ? null : { fps, frameCount }), [fps, frameCount]);
+ const [uncontrolledLoop, setUncontrolledLoop] = useState(defaultLoop);
+ const loop = loopProp ?? uncontrolledLoop;
+ const activeWindow = playbackWindow ? clampPlaybackWindow(playbackWindow, status.duration) : null;
+ const rootId = useId();
+ const rootRef = useRef<HTMLDivElement>(null);
+ const videoElementRef = useRef<HTMLVideoElement>(null);
+ const fullscreenElement = useSyncExternalStore(
+ subscribeFullscreenChange,
+ getFullscreenElement,
+ getNoFullscreenElement
+ );
+ const isFullscreen = fullscreenElement !== null && fullscreenElement.id === rootId;
+ const canFullscreen = size === 'full' && document.fullscreenEnabled;
+ const [isIdle, setIsIdle] = useState(false);
+ // Set while a pointer drag on the scrubber holds playback paused; `resume` is whether it was playing before.
+ const [scrub, setScrub] = useState<{ resume: boolean } | null>(null);
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+ const [isVolumeOpen, setIsVolumeOpen] = useState(false);
+ const idleTimerRef = useRef<number | null>(null);
+ // Set by a touch press made while the controls were hidden: its tap only brings them back.
+ const revealingTapRef = useRef(false);
+ // A mid-playback error can leave metadata in place, but nothing the controls do would work.
+ const disabled = !status.ready || status.error;
+
+ // The slider cancels a drag without ending it when it becomes disabled (a new source, an error); drop the scrub
+ // rather than leave playback paused by it and the controls pinned. Adjusted during render, as derived state.
+ if (scrub !== null && disabled) {
+ setScrub(null);
+ }
+
+ const controlsHidden = !status.paused && isIdle && scrub === null && !isMenuOpen && !isVolumeOpen;
+ const portalled = !isFullscreen;
+
+ const attachVideo = useCallback(
+ (video: HTMLVideoElement | null) => (video ? store.attach(video) : undefined),
+ [store]
+ );
+ const videoRef = useMemo(() => mergeRefs(attachVideo, videoElementRef, ref), [attachVideo, ref]);
+ const videoStyle = useMemo(() => (style ? { ...VIDEO_STYLE, ...style } : VIDEO_STYLE), [style]);
+
+ const clearIdleTimer = useCallback(() => {
+ if (idleTimerRef.current !== null) {
+ window.clearTimeout(idleTimerRef.current);
+ idleTimerRef.current = null;
+ }
+ }, []);
+ const wake = useCallback(() => {
+ clearIdleTimer();
+ setIsIdle(false);
+ idleTimerRef.current = window.setTimeout(() => {
+ idleTimerRef.current = null;
+ setIsIdle(true);
+ }, CONTROLS_IDLE_MS);
+ }, [clearIdleTimer]);
+ // Hiding (Activity) or unmounting must silence the clip. Here rather than in the ref cleanup, which also runs when a
+ // caller's ref changes identity; a hidden Activity detaches refs first, hence the element captured at mount.
+ useMountEffect(() => {
+ const video = videoElementRef.current;
+
+ return () => {
+ clearIdleTimer();
+
+ if (video && !video.paused) {
+ video.pause();
+ }
+ };
+ });
+
+ const setLoop = useCallback(
+ (next: boolean) => {
+ if (loopProp === undefined) {
+ setUncontrolledLoop(next);
+ }
+
+ onLoopChange?.(next);
+ },
+ [loopProp, onLoopChange]
+ );
+ const toggleLoop = useCallback(() => setLoop(!loop), [loop, setLoop]);
+ // Pause while dragging so playback does not fight the thumb; resume once the drag ends. A second pointer joining a
+ // drag keeps the first one's resume.
+ const startScrub = useCallback(() => {
+ const resume = !store.getSnapshot().paused;
+
+ setScrub((current) => current ?? { resume });
+ store.pause();
+ }, [store]);
+ // Also called for keyboard changes, which start no scrub.
+ const endScrub = useCallback(() => {
+ if (scrub === null) {
+ return;
+ }
+
+ setScrub(null);
+
+ if (scrub.resume) {
+ store.play();
+ }
+ }, [scrub, store]);
+ const toggleMute = useCallback(() => {
+ const { muted, volume } = store.getSnapshot();
+
+ if (muted || volume === 0) {
+ store.setVolume(volume === 0 ? 1 : volume);
+ } else {
+ store.setMuted(true);
+ }
+ }, [store]);
+ const stepFrame = useCallback(
+ (delta: number) => {
+ if (frames === null) {
+ return;
+ }
+
+ const { currentTime, duration } = store.getSnapshot();
+ const count = resolveFrameCount(frames, duration);
+ const frame = Math.min(count - 1, Math.max(0, getFrameAtTime(currentTime, frames.fps, count) + delta));
+
+ store.pause();
+ store.seek(getFrameTime(frame, frames.fps));
+ },
+ [frames, store]
+ );
+ const stepBackward = useCallback(() => stepFrame(-1), [stepFrame]);
+ const stepForward = useCallback(() => stepFrame(1), [stepFrame]);
+ const toggleFullscreen = useCallback(() => {
+ const root = rootRef.current;
+
+ if (!root) {
+ return;
+ }
+
+ if (document.fullscreenElement === root) {
+ void document.exitFullscreen().catch(() => {});
+ } else {
+ void root.requestFullscreen().catch(() => {});
+ }
+ }, []);
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ const target = event.target;
+ const key = event.key.toLowerCase();
+ // React delivers keys from portalled popups here too. The volume popover is part of the player; the speed menu
+ // owns its keys (KEY_OWNER_SELECTOR).
+ const isOwnTarget =
+ target instanceof Element &&
+ (event.currentTarget.contains(target) || target.closest(`[${VIDEO_PLAYER_POPUP_ATTRIBUTE}]`) !== null);
+
+ // A focused control's activation keys are its own too. They stop here without being prevented, so the control
+ // still activates and no application hotkey behind the player acts on them, or cancels the press.
+ if (
+ ACTIVATION_KEYS.has(key) &&
+ !event.altKey &&
+ !event.ctrlKey &&
+ !event.metaKey &&
+ !event.shiftKey &&
+ isOwnTarget &&
+ target.closest(ACTIVATION_OWNER_SELECTOR)
+ ) {
+ event.stopPropagation();
+ return;
+ }
+
+ if (
+ !PLAYER_KEYS.has(key) ||
+ event.defaultPrevented ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey ||
+ isImeComposing(event.nativeEvent) ||
+ !isOwnTarget ||
+ target.closest(KEY_OWNER_SELECTOR)
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (disabled) {
+ return;
+ }
+
+ switch (key) {
+ case ' ':
+ case 'k':
+ store.togglePlay();
+ break;
+ case 'l':
+ toggleLoop();
+ break;
+ case ',':
+ stepFrame(-1);
+ break;
+ case '.':
+ stepFrame(1);
+ break;
+ case 'm':
+ if (size === 'full') {
+ toggleMute();
+ }
+ break;
+ case 'f':
+ if (canFullscreen) {
+ toggleFullscreen();
+ }
+ break;
+ }
+
+ wake();
+ },
+ [canFullscreen, disabled, size, stepFrame, store, toggleFullscreen, toggleLoop, toggleMute, wake]
+ );
+ // Hidden controls take no pointer input, so a touch lands on the picture; toggling playback there would leave a touch
+ // user no way to reach the controls of a playing clip.
+ const handlePointerDown = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ revealingTapRef.current = event.pointerType === 'touch' && event.currentTarget.matches(CONTROLS_HIDDEN);
+ wake();
+ },
+ [wake]
+ );
+ const handlePointerLeave = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ // Touch pointers leave on every lift; only a mouse leaving means nobody is looking at the controls.
+ if (event.pointerType === 'mouse') {
+ clearIdleTimer();
+ setIsIdle(true);
+ }
+ },
+ [clearIdleTimer]
+ );
+ const handleVideoClick = useCallback(
+ (event: MouseEvent<HTMLVideoElement>) => {
+ onClick?.(event);
+
+ // Only a click that a press produced (detail > 0): a touch press can end in no click, and an activation without a
+ // press (`click()`, assistive technology) must not be taken for its tap.
+ const isRevealingTap = revealingTapRef.current && event.detail > 0;
+
+ revealingTapRef.current = false;
+
+ // A double-click's second click is not a second toggle.
+ if (!event.defaultPrevented && !disabled && !isRevealingTap && event.detail <= 1) {
+ store.togglePlay();
+ }
+ },
+ [disabled, onClick, store]
+ );
+ const handlePlay = useCallback(
+ (event: SyntheticEvent<HTMLVideoElement>) => {
+ onPlay?.(event);
+ wake();
+ },
+ [onPlay, wake]
+ );
+ // A new source disables the controls and an error removes them; either would drop a focused control's focus to the
+ // page, so it moves to the player first.
+ const keepFocusInPlayer = useCallback(() => {
+ const root = rootRef.current;
+
+ if (root && document.activeElement !== root && root.contains(document.activeElement)) {
+ root.focus();
+ }
+ }, []);
+ const handleEmptied = useCallback(
+ (event: SyntheticEvent<HTMLVideoElement>) => {
+ keepFocusInPlayer();
+ onEmptied?.(event);
+ },
+ [keepFocusInPlayer, onEmptied]
+ );
+ const handleError = useCallback(
+ (event: SyntheticEvent<HTMLVideoElement>) => {
+ keepFocusInPlayer();
+ onError?.(event);
+ },
+ [keepFocusInPlayer, onError]
+ );
+
+ const loopButton = (
+ <ControlButton
+ disabled={disabled}
+ icon={RepeatIcon}
+ label={t('common.videoPlayer.loop')}
+ portalled={portalled}
+ pressed={loop}
+ shortcut="L"
+ size={size}
+ onClick={toggleLoop}
+ />
+ );
+ const playButton = (
+ <ControlButton
+ disabled={disabled}
+ icon={status.paused ? PlayIcon : PauseIcon}
+ label={status.paused ? t('common.videoPlayer.play') : t('common.videoPlayer.pause')}
+ portalled={portalled}
+ shortcut="K"
+ size={size}
+ onClick={store.togglePlay}
+ />
+ );
+ const scrubber = (
+ <Scrubber
+ disabled={disabled}
+ frames={frames}
+ playbackWindow={activeWindow}
+ store={store}
+ onScrubEnd={endScrub}
+ onScrubStart={startScrub}
+ />
+ );
+
+ return (
+ <Box
+ ref={rootRef}
+ aria-label={label}
+ bg="black"
+ css={ROOT_CSS}
+ data-controls-hidden={controlsHidden ? '' : undefined}
+ h="full"
+ id={rootId}
+ overflow="hidden"
+ position="relative"
+ role="group"
+ tabIndex={-1}
+ w="full"
+ onKeyDown={handleKeyDown}
+ onPointerDown={handlePointerDown}
+ onPointerLeave={handlePointerLeave}
+ onPointerMove={wake}
+ >
+ {/* Callers play arbitrary user media, which carries no caption-track contract. */}
+ {/* oxlint-disable-next-line jsx-a11y/media-has-caption */}
+ <video
+ ref={videoRef}
+ playsInline
+ preload="metadata"
+ {...videoProps}
+ loop={loop && activeWindow === null}
+ style={videoStyle}
+ onClick={handleVideoClick}
+ onEmptied={handleEmptied}
+ onError={handleError}
+ onPlay={handlePlay}
+ />
+ {activeWindow ? (
+ <PlaybackWindowBinding
+ key={`${loop}:${activeWindow.startSeconds}:${activeWindow.endSeconds}:${fps}`}
+ loop={loop}
+ range={activeWindow}
+ restSeconds={getPlaybackWindowRest(activeWindow, fps)}
+ store={store}
+ />
+ ) : null}
+ {overlay}
+ {status.waiting ? (
+ <Center inset="0" pointerEvents="none" position="absolute">
+ <Spinner color="white" size={size === 'compact' ? 'md' : 'lg'} />
+ </Center>
+ ) : null}
+ {/* Mounted throughout so the region exists before it announces. */}
+ <chakra.span aria-live="polite" srOnly>
+ {status.waiting ? t('common.videoPlayer.buffering') : null}
+ </chakra.span>
+ {status.error ? null : size === 'compact' ? (
+ <HStack {...CONTROLS_BAR_PROPS} gap="1" pb="1" pt="4" px="1.5">
+ {playButton}
+ {loopButton}
+ {/* The thumb centers on the track ends; the inset keeps a 24px target around it clear of the Loop button. */}
+ <HStack flex="1" minW="0" px="2.5">
+ {scrubber}
+ </HStack>
+ <TimeReadout frames={frames} size="compact" store={store} />
+ </HStack>
+ ) : (
+ // The gap keeps a 24px target circle around the scrubber thumb clear of the buttons below (WCAG 2.5.8).
+ <Stack {...CONTROLS_BAR_PROPS} gap="2" pb="1.5" pt="8" px="2">
+ <HStack px="1.5">{scrubber}</HStack>
+ <HStack gap="1" minW="0">
+ {playButton}
+ {frames === null ? null : (
+ <HStack css={FRAME_STEP_CSS} gap="1">
+ <ControlButton
+ disabled={disabled}
+ icon={StepBackIcon}
+ label={t('common.videoPlayer.previousFrame')}
+ portalled={portalled}
+ shortcut=","
+ size="full"
+ onClick={stepBackward}
+ />
+ <ControlButton
+ disabled={disabled}
+ icon={StepForwardIcon}
+ label={t('common.videoPlayer.nextFrame')}
+ portalled={portalled}
+ shortcut="."
+ size="full"
+ onClick={stepForward}
+ />
+ </HStack>
+ )}
+ {loopButton}
+ <TimeReadout frames={frames} size="full" store={store} />
+ <Box flex="1" />
+ <Box css={PLAYBACK_RATE_CSS}>
+ <PlaybackRateMenu disabled={disabled} portalled={portalled} store={store} onOpenChange={setIsMenuOpen} />
+ </Box>
+ <VolumeControls
+ disabled={disabled}
+ portalled={portalled}
+ store={store}
+ onOpenChange={setIsVolumeOpen}
+ onToggleMute={toggleMute}
+ />
+ {canFullscreen ? (
+ <ControlButton
+ disabled={disabled}
+ icon={isFullscreen ? MinimizeIcon : MaximizeIcon}
+ label={isFullscreen ? t('common.videoPlayer.exitFullscreen') : t('common.videoPlayer.fullscreen')}
+ portalled={portalled}
+ shortcut="F"
+ size="full"
+ onClick={toggleFullscreen}
+ />
+ ) : null}
+ </HStack>
+ </Stack>
+ )}
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.browser.test.ts b/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.browser.test.ts
new file mode 100644
index 0000000000..b69c9a8a1e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.browser.test.ts
@@ -0,0 +1,212 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createMediaElementStore } from './mediaElementStore';
+import { getPlaybackWindowRest } from './videoTimeline';
+
+// The mock backend's clip: 64×64 H.264, 10 frames at 10 fps, one second long. Vite serves the package root.
+const FIXTURE_VIDEO_URL = '/scripts/mock-assets/fixture-video.mp4';
+
+let video: HTMLVideoElement;
+
+beforeEach(() => {
+ video = document.createElement('video');
+ video.muted = true;
+ video.preload = 'auto';
+ document.body.append(video);
+});
+
+afterEach(() => {
+ video.pause();
+ video.remove();
+ vi.restoreAllMocks();
+});
+
+const loadFixture = async (): Promise<void> => {
+ video.src = FIXTURE_VIDEO_URL;
+ await expect.poll(() => video.readyState >= HTMLMediaElement.HAVE_METADATA).toBe(true);
+};
+
+/** Seek targets in the order the element reports them. */
+const recordSeeks = (): number[] => {
+ const seeks: number[] = [];
+ video.addEventListener('seeking', () => seeks.push(video.currentTime));
+ return seeks;
+};
+
+describe('createMediaElementStore', () => {
+ it('reports the element through its snapshot once attached', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+
+ await expect.poll(() => store.getSnapshot()).toMatchObject({ duration: 1, paused: true, ready: true });
+
+ store.seek(5);
+ expect(store.getSnapshot().currentTime).toBe(1);
+ });
+
+ it('wraps playback that crosses the window end back to its start', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ const seeks = recordSeeks();
+ const onEnded = vi.fn();
+ video.addEventListener('ended', onEnded);
+ store.setPlaybackWindow({ endSeconds: 0.5, startSeconds: 0.2 }, { loop: true, restSeconds: 0 });
+
+ store.play();
+
+ await expect.poll(() => seeks.some((time) => Math.abs(time - 0.2) < 1e-6), { timeout: 3000 }).toBe(true);
+ expect(store.getSnapshot().paused).toBe(false);
+ expect(onEnded).not.toHaveBeenCalled();
+ });
+
+ it('wraps a window that ends at the media end and keeps playing', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ const seeks = recordSeeks();
+ store.setPlaybackWindow({ endSeconds: 1, startSeconds: 0.6 }, { loop: true, restSeconds: 0 });
+ store.seek(0.7);
+
+ store.play();
+
+ await expect.poll(() => seeks.filter((time) => Math.abs(time - 0.6) < 1e-6).length, { timeout: 3000 }).toBe(1);
+ await expect.poll(() => video.paused).toBe(false);
+ });
+
+ it('never wraps or pauses a seek that lands past the window: playback goes on from there', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ store.setPlaybackWindow({ endSeconds: 0.5, startSeconds: 0.2 }, { loop: true, restSeconds: 0 });
+ store.seek(0.25);
+ store.play();
+ await expect.poll(() => !video.paused && video.currentTime > 0.3).toBe(true);
+ const seeks = recordSeeks();
+ const onEnded = vi.fn();
+ video.addEventListener('ended', onEnded);
+
+ store.seek(0.8);
+
+ await expect.poll(() => onEnded.mock.calls.length, { timeout: 3000 }).toBe(1);
+ expect(seeks).toEqual([0.8]);
+ });
+
+ it("leaves a seek into the next window alone while the previous one is still set, as a caller's swap lags", async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ store.setPlaybackWindow({ endSeconds: 0.4, startSeconds: 0.1 }, { loop: true, restSeconds: 0 });
+ store.seek(0.15);
+ store.play();
+ await expect.poll(() => !video.paused && video.currentTime > 0.2).toBe(true);
+ const seeks = recordSeeks();
+
+ // The next window's start, past the previous end; the caller replaces the window a moment later.
+ store.seek(0.6);
+ await new Promise((resolve) => {
+ setTimeout(resolve, 100);
+ });
+ store.setPlaybackWindow({ endSeconds: 0.9, startSeconds: 0.6 }, { loop: true, restSeconds: 0 });
+
+ await expect.poll(() => seeks.filter((time) => Math.abs(time - 0.6) < 1e-6).length, { timeout: 3000 }).toBe(2);
+ expect(seeks.some((time) => Math.abs(time - 0.1) < 1e-6)).toBe(false);
+ expect(video.paused).toBe(false);
+ });
+
+ it('stops at the window end even when sparse samples jump from before the window to past it', () => {
+ // Throttled frames and quarter-second timeupdates can step over a short window between two samples.
+ let currentTime = 0;
+ let paused = false;
+ Object.defineProperties(video, {
+ currentTime: {
+ configurable: true,
+ get: () => currentTime,
+ set: (value: number) => {
+ currentTime = value;
+ },
+ },
+ paused: { configurable: true, get: () => paused },
+ });
+ vi.spyOn(video, 'pause').mockImplementation(() => {
+ paused = true;
+ });
+ const store = createMediaElementStore();
+ store.attach(video);
+ store.setPlaybackWindow({ endSeconds: 0.5, startSeconds: 0.2 }, { loop: false, restSeconds: 0.45 });
+
+ currentTime = 0.18;
+ video.dispatchEvent(new Event('timeupdate'));
+ currentTime = 0.52;
+ video.dispatchEvent(new Event('timeupdate'));
+
+ expect(paused).toBe(true);
+ expect(currentTime).toBe(0.45);
+ });
+
+ it('rests on the last frame of a window that does not loop, and any play starts it over', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ // A real clip's rest, a frame's middle at 23.976 fps, which the element reports back only to its own precision.
+ const range = { endSeconds: 0.5, startSeconds: 0.2 };
+ const restSeconds = getPlaybackWindowRest(range, 23.976);
+ const isResting = () => video.paused && !video.seeking && Math.abs(video.currentTime - restSeconds) < 1e-4;
+ store.setPlaybackWindow(range, { loop: false, restSeconds });
+ store.seek(0.2);
+ store.play();
+
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+
+ // Media keys and other callers play the element directly; the window replays all the same.
+ const seeks = recordSeeks();
+ await video.play();
+
+ await expect.poll(() => seeks[0]).toBeCloseTo(0.2);
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+ });
+
+ it('stops wrapping once the window is cleared, and ignores clearing a replaced window', async () => {
+ const store = createMediaElementStore();
+ store.attach(video);
+ await loadFixture();
+ const clearFirst = store.setPlaybackWindow({ endSeconds: 0.5, startSeconds: 0.2 }, { loop: true, restSeconds: 0 });
+ const clearSecond = store.setPlaybackWindow({ endSeconds: 0.4, startSeconds: 0.1 }, { loop: true, restSeconds: 0 });
+ clearFirst();
+ const seeks = recordSeeks();
+
+ store.play();
+ await expect.poll(() => seeks.some((time) => Math.abs(time - 0.1) < 1e-6), { timeout: 3000 }).toBe(true);
+
+ clearSecond();
+ const onEnded = vi.fn();
+ video.addEventListener('ended', onEnded);
+ await expect.poll(() => onEnded.mock.calls.length, { timeout: 3000 }).toBe(1);
+ });
+
+ it('stops listening and requesting frames once detached', async () => {
+ const store = createMediaElementStore();
+ const detach = store.attach(video);
+ await loadFixture();
+ store.setPlaybackWindow({ endSeconds: 0.3, startSeconds: 0.1 }, { loop: true, restSeconds: 0 });
+ store.play();
+ await expect.poll(() => store.getSnapshot().paused).toBe(false);
+
+ detach();
+ const listener = vi.fn();
+ store.subscribe(listener);
+ const requestFrame = vi.spyOn(window, 'requestAnimationFrame');
+ const seeks = recordSeeks();
+ video.currentTime = 0.4;
+ const onEnded = vi.fn();
+ video.addEventListener('ended', onEnded);
+ await expect.poll(() => onEnded.mock.calls.length, { timeout: 3000 }).toBe(1);
+
+ expect(store.getSnapshot()).toMatchObject({ currentTime: 0, paused: true, ready: false });
+ expect(listener).not.toHaveBeenCalled();
+ expect(requestFrame).not.toHaveBeenCalled();
+ // Only the test's own seek: the window no longer wraps.
+ expect(seeks).toEqual([0.4]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.ts b/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.ts
new file mode 100644
index 0000000000..94d1b34236
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/mediaElementStore.ts
@@ -0,0 +1,320 @@
+import { createExternalStoreCore } from '@platform/state/externalStoreCore';
+
+import type { PlaybackWindow } from './videoTimeline';
+
+/** What the attached media element reports; a detached store reads as an empty, paused element. */
+export interface MediaElementSnapshot {
+ currentTime: number;
+ /** Finite seconds once known; 0 while unknown or unbounded. */
+ duration: number;
+ /** The element holds a media error; a new source clears it. */
+ error: boolean;
+ muted: boolean;
+ paused: boolean;
+ playbackRate: number;
+ /** Metadata loaded: duration is known and seeks can land. */
+ ready: boolean;
+ volume: number;
+ /** Playback is wanted but stalled on data or a seek. */
+ waiting: boolean;
+}
+
+export interface MediaElementStore {
+ /**
+ * A React 19 ref callback: binds the store to `video` and returns the unbinding. Unbinding removes every listener
+ * and frame callback and resets the snapshot; it leaves playback alone.
+ */
+ attach: (video: HTMLVideoElement) => () => void;
+ getSnapshot: () => MediaElementSnapshot;
+ pause: () => void;
+ /** Playback the browser refuses (autoplay policy, a missing source) leaves the element paused, as reported. */
+ play: () => void;
+ /** Clamped to the media. */
+ seek: (seconds: number) => void;
+ /**
+ * While set, playback that reaches the window's end wraps to its start with `loop`, including at the media end;
+ * without it, playback pauses and rests at `restSeconds`. A seek is not playback: one that lands at or past the end
+ * never wraps or pauses, though playback from before the window does once it reaches the end. Playing from the rest,
+ * or past it, starts the window over, whatever starts the playback (`play`, media keys, a caller's own `play()`).
+ * Playback is judged against the window set when it starts, so a caller playing a new window sets it first. Returns
+ * the clearing; a later window replaces this one, and clearing a replaced window does nothing.
+ */
+ setPlaybackWindow: (window: PlaybackWindow, options: { loop: boolean; restSeconds: number }) => () => void;
+ setMuted: (muted: boolean) => void;
+ setPlaybackRate: (rate: number) => void;
+ /** Also unmutes for an audible volume. */
+ setVolume: (volume: number) => void;
+ subscribe: (listener: () => void) => () => void;
+ togglePlay: () => void;
+}
+
+const DETACHED_SNAPSHOT: MediaElementSnapshot = {
+ currentTime: 0,
+ duration: 0,
+ error: false,
+ muted: false,
+ paused: true,
+ playbackRate: 1,
+ ready: false,
+ volume: 1,
+ waiting: false,
+};
+
+const MEDIA_EVENTS = [
+ 'canplay',
+ 'durationchange',
+ 'emptied',
+ 'ended',
+ 'error',
+ 'loadeddata',
+ 'loadedmetadata',
+ 'loadstart',
+ 'pause',
+ 'play',
+ 'playing',
+ 'ratechange',
+ 'seeked',
+ 'seeking',
+ 'timeupdate',
+ 'volumechange',
+ 'waiting',
+] as const;
+
+const readSnapshot = (video: HTMLVideoElement): MediaElementSnapshot => ({
+ currentTime: video.currentTime,
+ duration: Number.isFinite(video.duration) ? video.duration : 0,
+ error: video.error !== null,
+ muted: video.muted,
+ paused: video.paused,
+ playbackRate: video.playbackRate,
+ ready: video.readyState >= HTMLMediaElement.HAVE_METADATA,
+ volume: video.volume,
+ // An error can leave the element unpaused with no data coming; that is not waiting.
+ waiting:
+ !video.paused &&
+ !video.ended &&
+ video.error === null &&
+ (video.seeking || video.readyState < HTMLMediaElement.HAVE_FUTURE_DATA),
+});
+
+const seekElement = (video: HTMLVideoElement, seconds: number): void => {
+ try {
+ video.currentTime = seconds;
+ } catch {
+ // Some browsers throw while nothing is seekable yet; the element keeps its position.
+ }
+};
+
+const ignoreRefusal = (): void => {};
+
+// A playhead this close to a window's rest is at it: seeks land within a decoder's rounding of their target.
+const REST_TOLERANCE_SECONDS = 0.001;
+
+/**
+ * One media element's state as an external store, for `useSyncExternalStore` with narrow selectors. Every media
+ * event re-reads the element, so the snapshot cannot drift from it. The playhead follows animation frames only while
+ * playing, for a smooth scrubber; `timeupdate` covers paused seeks and background tabs, where frames stop.
+ */
+export const createMediaElementStore = (): MediaElementStore => {
+ const core = createExternalStoreCore<MediaElementSnapshot>(DETACHED_SNAPSHOT);
+ let element: HTMLVideoElement | null = null;
+ let frame: number | null = null;
+ let playbackWindow: { loop: boolean; range: PlaybackWindow; restSeconds: number } | null = null;
+ // The playhead at the last sample of uninterrupted playback; a seek clears it, so a landing is never a crossing.
+ let sampledTime: number | null = null;
+
+ const sync = (): void => core.patchSnapshot(element ? readSnapshot(element) : DETACHED_SNAPSHOT);
+ const stopFrames = (): void => {
+ if (frame !== null) {
+ cancelAnimationFrame(frame);
+ frame = null;
+ }
+ };
+ // A finished window plays again from its start, as an ended clip does. An ended element is past the rest too.
+ const replayFinishedWindow = (video: HTMLVideoElement): void => {
+ if (
+ playbackWindow &&
+ !playbackWindow.loop &&
+ video.currentTime >= playbackWindow.restSeconds - REST_TOLERANCE_SECONDS
+ ) {
+ seekElement(video, playbackWindow.range.startSeconds);
+ sampledTime = null;
+ }
+ };
+ /**
+ * Samples the playhead and acts when playback carried it to or past the window's end. Samples can be sparse
+ * (throttled frames, timeupdate every quarter second), so playback that jumps from before the window to past it
+ * between two samples has reached the end all the same. Frames and timeupdate both sample, so the window holds in
+ * visible tabs to the frame and in background tabs at all; a window ending at the media end is reached when playback
+ * ends, which pauses before any frame sees it.
+ */
+ const sampleWindowEnd = (): void => {
+ if (!element) {
+ return;
+ }
+
+ if (element.seeking) {
+ sampledTime = null;
+ return;
+ }
+
+ const previous = sampledTime;
+ const current = element.currentTime;
+
+ sampledTime = current;
+
+ if (
+ !playbackWindow ||
+ previous === null ||
+ (element.paused && !element.ended) ||
+ previous >= playbackWindow.range.endSeconds ||
+ current < playbackWindow.range.endSeconds
+ ) {
+ return;
+ }
+
+ sampledTime = null;
+
+ if (playbackWindow.loop) {
+ seekElement(element, playbackWindow.range.startSeconds);
+
+ if (element.paused) {
+ void element.play().catch(ignoreRefusal);
+ }
+ } else {
+ element.pause();
+ seekElement(element, playbackWindow.restSeconds);
+ }
+ };
+ const tick = (): void => {
+ frame = null;
+ sampleWindowEnd();
+ sync();
+
+ if (element && !element.paused) {
+ frame = requestAnimationFrame(tick);
+ }
+ };
+ const startFrames = (): void => {
+ if (frame === null && element && !element.paused) {
+ frame = requestAnimationFrame(tick);
+ }
+ };
+ const handleMediaEvent = (event: Event): void => {
+ switch (event.type) {
+ case 'seeking':
+ sampledTime = null;
+ break;
+ case 'play':
+ // Native play (media keys, a caller's own `play()`) replays a finished window as the controls do.
+ if (element) {
+ replayFinishedWindow(element);
+ }
+
+ sampleWindowEnd();
+ break;
+ default:
+ sampleWindowEnd();
+ }
+
+ if (element?.paused === false) {
+ startFrames();
+ } else {
+ stopFrames();
+ }
+
+ sync();
+ };
+ const play = (): void => {
+ if (!element) {
+ return;
+ }
+
+ // Rewound before playing, so not even a frame plays from the rest.
+ replayFinishedWindow(element);
+ void element.play().catch(ignoreRefusal);
+ };
+
+ return {
+ attach: (video) => {
+ element = video;
+
+ for (const type of MEDIA_EVENTS) {
+ video.addEventListener(type, handleMediaEvent);
+ }
+
+ startFrames();
+ sync();
+
+ return () => {
+ for (const type of MEDIA_EVENTS) {
+ video.removeEventListener(type, handleMediaEvent);
+ }
+
+ stopFrames();
+
+ if (element === video) {
+ element = null;
+ sync();
+ }
+ };
+ },
+ getSnapshot: core.getSnapshot,
+ pause: () => element?.pause(),
+ play,
+ seek: (seconds) => {
+ if (!element) {
+ return;
+ }
+
+ const duration = Number.isFinite(element.duration) ? element.duration : Number.POSITIVE_INFINITY;
+ seekElement(element, Math.min(duration, Math.max(0, seconds)));
+ // The element reports the target at once; its seeking event arrives a task later.
+ sync();
+ },
+ setPlaybackWindow: (range, { loop, restSeconds }) => {
+ const current = { loop, range, restSeconds };
+
+ playbackWindow = current;
+
+ return () => {
+ if (playbackWindow === current) {
+ playbackWindow = null;
+ }
+ };
+ },
+ setMuted: (muted) => {
+ if (element) {
+ element.muted = muted;
+ }
+ },
+ setPlaybackRate: (rate) => {
+ if (element) {
+ element.playbackRate = rate;
+ }
+ },
+ setVolume: (volume) => {
+ if (!element) {
+ return;
+ }
+
+ element.volume = Math.min(1, Math.max(0, volume));
+
+ if (volume > 0) {
+ element.muted = false;
+ }
+ },
+ subscribe: core.subscribe,
+ togglePlay: () => {
+ if (!element) {
+ return;
+ }
+
+ if (element.paused) {
+ play();
+ } else {
+ element.pause();
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.test.ts b/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.test.ts
new file mode 100644
index 0000000000..6bff17a580
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ clampPlaybackWindow,
+ formatMediaTime,
+ getFrameAtTime,
+ getFrameCount,
+ getFrameTime,
+ getPlaybackWindowRest,
+ getScrubSteps,
+} from './videoTimeline';
+
+describe('clampPlaybackWindow', () => {
+ it('keeps a range that fits the media', () => {
+ expect(clampPlaybackWindow({ endSeconds: 2, startSeconds: 1 }, 4)).toEqual({ endSeconds: 2, startSeconds: 1 });
+ });
+
+ it('clamps the end to the duration and the start into the media', () => {
+ expect(clampPlaybackWindow({ endSeconds: 9, startSeconds: -1 }, 4)).toEqual({ endSeconds: 4, startSeconds: 0 });
+ });
+
+ it('holds nothing when the window collapses, inverts, or starts past the end', () => {
+ expect(clampPlaybackWindow({ endSeconds: 1, startSeconds: 1 }, 4)).toBeNull();
+ expect(clampPlaybackWindow({ endSeconds: 1, startSeconds: 2 }, 4)).toBeNull();
+ expect(clampPlaybackWindow({ endSeconds: 6, startSeconds: 5 }, 4)).toBeNull();
+ });
+
+ it('keeps the requested end while the duration is unknown', () => {
+ expect(clampPlaybackWindow({ endSeconds: 9, startSeconds: 1 }, 0)).toEqual({ endSeconds: 9, startSeconds: 1 });
+ });
+});
+
+describe('getPlaybackWindowRest', () => {
+ it("rests on the window's last frame, the one before its exclusive end", () => {
+ // Frames 2 to 4 of a 10 fps clip: the end is frame 5's start.
+ expect(getPlaybackWindowRest({ endSeconds: 0.5, startSeconds: 0.2 }, 10)).toBeCloseTo(0.45);
+ // An end inside frame 4 still rests on frame 4.
+ expect(getPlaybackWindowRest({ endSeconds: 0.47, startSeconds: 0.2 }, 10)).toBeCloseTo(0.45);
+ });
+
+ it('rests just inside the end without a frame rate, and never before the start', () => {
+ expect(getPlaybackWindowRest({ endSeconds: 2, startSeconds: 1 }, null)).toBeCloseTo(1.999);
+ expect(getPlaybackWindowRest({ endSeconds: 0.47, startSeconds: 0.46 }, 10)).toBe(0.46);
+ });
+});
+
+describe('frame mapping', () => {
+ it('counts whole frames, tolerating a duration rounded just under the last frame', () => {
+ expect(getFrameCount(1, 10)).toBe(10);
+ expect(getFrameCount(0.9999999, 10)).toBe(10);
+ expect(getFrameCount(1.04, 10)).toBe(10);
+ expect(getFrameCount(0, 24)).toBe(1);
+ });
+
+ it('seeks to the middle of a frame, which maps back to the same frame', () => {
+ expect(getFrameTime(0, 10)).toBeCloseTo(0.05);
+ expect(getFrameTime(3, 24)).toBeCloseTo(3.5 / 24);
+
+ for (const frame of [0, 1, 7, 9]) {
+ expect(getFrameAtTime(getFrameTime(frame, 10), 10, 10)).toBe(frame);
+ }
+ });
+
+ it('reads frame boundaries as the frame they start, and the clip end as the last frame', () => {
+ expect(getFrameAtTime(0.3, 10, 10)).toBe(3);
+ expect(getFrameAtTime(1, 10, 10)).toBe(9);
+ expect(getFrameAtTime(-1, 10, 10)).toBe(0);
+ });
+});
+
+describe('getScrubSteps', () => {
+ it('steps arrow keys a hundredth of the clip, bounded for very short and very long clips', () => {
+ expect(getScrubSteps(0).keyboard).toBe(0.1);
+ expect(getScrubSteps(4).keyboard).toBe(0.1);
+ expect(getScrubSteps(60).keyboard).toBeCloseTo(0.6);
+ expect(getScrubSteps(3600).keyboard).toBe(5);
+ });
+
+ it('keeps pointer steps a thousandth of the clip, so long clips still drag finely', () => {
+ expect(getScrubSteps(3600).pointer).toBeCloseTo(3.6);
+ expect(getScrubSteps(600).pointer).toBeCloseTo(0.6);
+ expect(getScrubSteps(0).pointer).toBe(0.001);
+ });
+});
+
+describe('formatMediaTime', () => {
+ it('formats minutes and hours with padded seconds', () => {
+ expect(formatMediaTime(0)).toBe('0:00');
+ expect(formatMediaTime(4.9)).toBe('0:04');
+ expect(formatMediaTime(65)).toBe('1:05');
+ expect(formatMediaTime(3725)).toBe('1:02:05');
+ });
+
+ it('reads unknown times as zero', () => {
+ expect(formatMediaTime(Number.NaN)).toBe('0:00');
+ expect(formatMediaTime(Number.POSITIVE_INFINITY)).toBe('0:00');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.ts b/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.ts
new file mode 100644
index 0000000000..4d53712299
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/video-player/videoTimeline.ts
@@ -0,0 +1,67 @@
+/** A stretch of the media playback is confined to, in seconds; the end is exclusive. */
+export interface PlaybackWindow {
+ startSeconds: number;
+ endSeconds: number;
+}
+
+/**
+ * The part of `window` the media can play: the end is clamped to a known duration and the start into `[0, end]`.
+ * Collapsed or inverted windows hold nothing, so they return null.
+ */
+export const clampPlaybackWindow = (window: PlaybackWindow, durationSeconds: number): PlaybackWindow | null => {
+ const endSeconds = durationSeconds > 0 ? Math.min(window.endSeconds, durationSeconds) : window.endSeconds;
+ const startSeconds = Math.max(0, Math.min(window.startSeconds, endSeconds));
+
+ return endSeconds > startSeconds ? { endSeconds, startSeconds } : null;
+};
+
+// Containers round durations; a frame that starts within this of the end does not count as a frame.
+const FRAME_EPSILON = 1e-6;
+
+/** Whole frames in the media, at least one. */
+export const getFrameCount = (durationSeconds: number, fps: number): number =>
+ Math.max(1, Math.floor(durationSeconds * fps + FRAME_EPSILON));
+
+/** The frame shown at `timeSeconds`, clamped to the media's frames (the end of the clip shows the last one). */
+export const getFrameAtTime = (timeSeconds: number, fps: number, frameCount: number): number =>
+ Math.min(frameCount - 1, Math.max(0, Math.floor(timeSeconds * fps + FRAME_EPSILON)));
+
+/** Seek target for a frame: the middle of its display interval, since seeking onto a boundary can decode a neighbor. */
+export const getFrameTime = (frame: number, fps: number): number => (frame + 0.5) / fps;
+
+/**
+ * Scrubber steps without a frame rate. `pointer` is a thousandth of the clip, finer than a track's pixels, so a drag
+ * lands where it points. `keyboard` is a hundredth, between 0.1 s (short clips stay fine-grained) and 5 s (an arrow
+ * key on a long clip still moves visibly).
+ */
+export const getScrubSteps = (durationSeconds: number): { keyboard: number; pointer: number } => ({
+ keyboard: Math.min(5, Math.max(0.1, durationSeconds / 100)),
+ pointer: Math.max(0.001, durationSeconds / 1000),
+});
+
+/** `m:ss`, or `h:mm:ss` from an hour; negative and non-finite times read as zero. */
+export const formatMediaTime = (seconds: number): string => {
+ const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
+ const hours = Math.floor(total / 3600);
+ const minutes = Math.floor((total % 3600) / 60);
+ const secondsPart = String(total % 60).padStart(2, '0');
+
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${secondsPart}` : `${minutes}:${secondsPart}`;
+};
+
+// Without a frame rate, playback stopped at a window's end rests this far inside it.
+const REST_INSET_SECONDS = 0.001;
+
+/**
+ * Where playback stopped at a window's end rests, so the picture is the window's own: its last frame, the one that
+ * starts before the exclusive end, or just inside the end without a frame rate. Never before the window's start.
+ */
+export const getPlaybackWindowRest = (window: PlaybackWindow, fps: number | null): number => {
+ if (fps === null) {
+ return Math.max(window.startSeconds, window.endSeconds - REST_INSET_SECONDS);
+ }
+
+ const lastFrame = Math.ceil(window.endSeconds * fps - FRAME_EPSILON) - 1;
+
+ return Math.max(window.startSeconds, Math.min(getFrameTime(lastFrame, fps), window.endSeconds - REST_INSET_SECONDS));
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index aebad67e22..9f63916724 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -1,6 +1,7 @@
/* eslint-disable react/refs, react/immutability */
import type { GalleryItemKey, GalleryItemRef } from '@features/gallery';
import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';
+import type * as VideoPlayerModule from '@platform/ui/video-player/VideoPlayer';
import { Badge, Flex, Text } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
@@ -11,6 +12,8 @@ import { useMountEffect } from '@platform/react/useMountEffect';
import { Button } from '@platform/ui/Button';
import { GripHorizontalIcon } from 'lucide-react';
import {
+ lazy,
+ Suspense,
useCallback,
useEffect,
useId,
@@ -41,9 +44,21 @@ import {
import { usePreviewLoupe, type PreviewLoupeControls, type PreviewZoomState } from './usePreviewLoupe';
import { usePreviewSwipe, type PreviewSwipeNavigation } from './usePreviewSwipe';
+// Most selections are images, and other surfaces share the player: it loads with the first video shown, not with the
+// Preview, so it costs the Preview's own load no request. Its bar exists only once it has loaded, so the stage reads
+// the bar test from the loaded module.
+let loadedVideoPlayer: typeof VideoPlayerModule | null = null;
+const VideoPlayer = lazy(() =>
+ import('@platform/ui/video-player/VideoPlayer').then((module) => {
+ loadedVideoPlayer = module;
+
+ return { default: module.VideoPlayer };
+ })
+);
+
export type PreviewMediaSource =
| { itemKey: GalleryItemKey; kind: 'image'; source: StreamingImageSource }
- | { itemKey: GalleryItemKey; kind: 'video'; label: string; poster: string; src: string };
+ | { fps?: number; itemKey: GalleryItemKey; kind: 'video'; label: string; poster: string; src: string };
interface PreviewFrameProps {
children?: ReactNode;
@@ -71,6 +86,9 @@ interface PreviewFrameProps {
/** Touch swipe navigation between neighbors; framed, settled images only. */
swipe?: PreviewSwipeNavigation;
videoControllerRef?: Ref<PreviewVideoFrameController>;
+ /** Whether videos loop, when the caller remembers it; otherwise each player starts looping. */
+ videoLoop?: boolean;
+ onVideoLoopChange?: (loop: boolean) => void;
variant: 'framed' | 'inset';
}
@@ -83,8 +101,10 @@ export const PreviewFrame = (props: PreviewFrameProps) => {
frameHeight={props.frameHeight}
frameWidth={props.frameWidth}
isItemCurrent={props.isItemCurrent}
+ loop={props.videoLoop}
onContextMenu={props.onContextMenu}
onCopyAvailabilityChange={props.onVideoCopyAvailabilityChange}
+ onLoopChange={props.onVideoLoopChange}
padding={props.padding}
paddingBottom={props.paddingBottom}
source={props.source}
@@ -116,7 +136,15 @@ const PreviewImageFrame = ({
source,
swipe: swipeNavigation,
variant,
-}: Omit<PreviewFrameProps, 'isItemCurrent' | 'onVideoCopyAvailabilityChange' | 'source' | 'videoControllerRef'> & {
+}: Omit<
+ PreviewFrameProps,
+ | 'isItemCurrent'
+ | 'onVideoCopyAvailabilityChange'
+ | 'onVideoLoopChange'
+ | 'source'
+ | 'videoControllerRef'
+ | 'videoLoop'
+> & {
source: StreamingImageSource | null;
}) => {
const loupe = usePreviewLoupe({
@@ -389,8 +417,10 @@ const PreviewVideo = ({
frameHeight,
frameWidth,
isItemCurrent,
+ loop: loopPreference,
onContextMenu,
onCopyAvailabilityChange,
+ onLoopChange,
padding,
paddingBottom,
source,
@@ -401,8 +431,10 @@ const PreviewVideo = ({
frameHeight: number;
frameWidth: number;
isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
+ loop?: boolean;
onContextMenu?: (x: number, y: number) => void;
onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
+ onLoopChange?: (loop: boolean) => void;
padding?: string;
paddingBottom?: string;
source: Extract<PreviewMediaSource, { kind: 'video' }>;
@@ -411,7 +443,7 @@ const PreviewVideo = ({
}) => {
const { t } = useTranslation();
const videoRef = useRef<HTMLVideoElement | null>(null);
- // Use a corner drag grip for video so native seek-bar scrubbing cannot activate gallery dragging.
+ // Use a grip for video so scrubbing the player cannot activate gallery dragging.
const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);
const disabledDragId = useId();
const dragId = dragItem
@@ -435,16 +467,18 @@ const PreviewVideo = ({
navigation: swipeNavigation ?? null,
});
const { onPointerDown: handleSwipePointerDown } = swipe;
- // The native control bar owns touches along the frame's bottom edge: seeking and volume must never swipe. A
- // fullscreen player is out of the carousel entirely; navigating would unmount it and drop fullscreen.
+ // The control bar owns its touches: seeking and volume must never swipe. So do the player's popups, whose events
+ // reach the stage through their portals. A fullscreen player is out of the carousel entirely; navigating would
+ // unmount it and drop fullscreen.
const handleStagePointerDown = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
- const video = videoRef.current;
- const frame = video?.getBoundingClientRect();
+ const target = event.target;
if (
- (frame && event.clientY >= frame.bottom - VIDEO_CONTROL_BAND_PX) ||
- (video && video.ownerDocument.fullscreenElement === video)
+ !(target instanceof Element) ||
+ !event.currentTarget.contains(target) ||
+ loadedVideoPlayer?.isVideoPlayerControlsTarget(target) ||
+ target.ownerDocument.fullscreenElement?.contains(target)
) {
return;
}
@@ -530,33 +564,28 @@ const PreviewVideo = ({
return isCurrent() ? { ok: true } : { ok: false, reason: 'stale' };
}, [isItemCurrent, source.itemKey]);
const isCopyAvailable = useCallback(() => isVideoFrameCopyAvailable(videoRef.current), []);
- // Loop requested trim spans for preview without generation; keep loop state in refs because wraps change no
- // rendered UI.
+ // The span a request armed, which the player plays as its playback window. Handlers read the ref, which is current
+ // before the render that arms the span.
+ const [span, setSpan] = useState<VideoSpan | null>(null);
const spanRef = useRef<VideoSpan | null>(null);
// Expire spans parked before media readiness so retries or hidden remounts cannot start stale audio later.
const parkedSpanRef = useRef<{ expiresAt: number; span: VideoSpan; token: number } | null>(null);
- const spanFrameRef = useRef<number | null>(null);
- // Keep request identity through pause/hide while the loop stays armed; retire it when the playhead leaves or a
+ // Keep request identity through pause/hide while the span stays armed; retire it when the playhead leaves or a
// newer request arrives.
const spanTokenRef = useRef<number | null>(null);
- const seekWithinSpan = useCallback((video: HTMLVideoElement, time: number) => {
- try {
- video.currentTime = time;
- } catch {
- // Some browsers throw while the seekable range is still empty; the watch retries on
- // its next tick.
- }
- }, []);
- const stopSpanWatch = useCallback(() => {
- if (spanFrameRef.current !== null) {
- cancelAnimationFrame(spanFrameRef.current);
- spanFrameRef.current = null;
- }
+ // Where an armed span's playback starts once the player holds its window (see SpanPlaybackStart), until the same
+ // deadline a parked span has: a start that a hide holds up still happens on show while the gesture is fresh, unless
+ // a newer request has superseded it meanwhile.
+ const pendingSpanStartRef = useRef<{ expiresAt: number; startSeconds: number; token: number } | null>(null);
+ const [spanStartRequest, setSpanStartRequest] = useState(0);
+ const armSpan = useCallback((next: VideoSpan | null) => {
+ spanRef.current = next;
+ setSpan(next);
}, []);
const pauseSpanPlayback = useCallback(() => {
videoRef.current?.pause();
}, []);
- // Publish actual element play/pause state, including native controls and autoplay refusals.
+ // Publish actual element play/pause state, including the player's own controls and autoplay refusals.
const publishSpanState = useCallback(() => {
const token = spanTokenRef.current;
const video = videoRef.current;
@@ -576,76 +605,66 @@ const PreviewVideo = ({
clearVideoSpanPlaybackState(token);
}
}, []);
- // Use rAF for precise visible-tab wrapping and timeupdate as the background-tab fallback.
- const enforceSpan = useCallback(() => {
- const span = spanRef.current;
- const video = videoRef.current;
-
- if (!span || !video || video.paused || video.currentTime < span.endSeconds) {
- return;
- }
-
- seekWithinSpan(video, span.startSeconds);
- }, [seekWithinSpan]);
- const startSpanWatch = useCallback(() => {
- if (spanRef.current === null || spanFrameRef.current !== null) {
- return;
- }
-
- const tick = (): void => {
- spanFrameRef.current = null;
- enforceSpan();
-
- if (spanRef.current !== null && videoRef.current?.paused === false) {
- spanFrameRef.current = requestAnimationFrame(tick);
- }
- };
-
- spanFrameRef.current = requestAnimationFrame(tick);
- }, [enforceSpan]);
const playSpan = useCallback(
- (span: VideoSpan, token: number, expiresAt?: number) => {
+ (request: VideoSpan, token: number, expiresAt?: number) => {
const video = videoRef.current;
+ // The deadline belongs to the gesture, not to this attempt: minting a fresh one on
+ // every re-park would let hide/show cycles on a clip that never loads extend it
+ // indefinitely, which is the one thing the deadline exists to stop.
+ const deadline = expiresAt ?? Date.now() + PARKED_SPAN_TTL_MS;
// Defer seeks until metadata and element attachment exist; resume from loadedmetadata or remount.
if (!video || video.readyState < HTMLMediaElement.HAVE_METADATA) {
- // The deadline belongs to the gesture, not to this attempt: minting a fresh one on
- // every re-park would let hide/show cycles on a clip that never loads extend it
- // indefinitely, which is the one thing the deadline exists to stop.
- parkedSpanRef.current = { expiresAt: expiresAt ?? Date.now() + PARKED_SPAN_TTL_MS, span, token };
+ parkedSpanRef.current = { expiresAt: deadline, span: request, token };
return;
}
parkedSpanRef.current = null;
const duration = Number.isFinite(video.duration) ? video.duration : null;
- const endSeconds = duration === null ? span.endSeconds : Math.min(span.endSeconds, duration);
- const startSeconds = Math.max(0, Math.min(span.startSeconds, endSeconds));
+ const endSeconds = duration === null ? request.endSeconds : Math.min(request.endSeconds, duration);
+ const startSeconds = Math.max(0, Math.min(request.startSeconds, endSeconds));
+ // Arm any nonempty clamped span, including two-frame trims. Collapsed or inverted bounds are no window: the clip
+ // plays from their start as the loop toggle says.
+ const next = endSeconds > startSeconds ? { endSeconds, startSeconds } : null;
- // Loop any nonempty clamped span, including two-frame trims; collapsed/inverted bounds play without looping.
- spanRef.current = endSeconds > startSeconds ? { endSeconds, startSeconds } : null;
- // New requests replace prior loop ownership; report only an armed loop, not collapsed one-shot playback.
+ // New requests replace prior span ownership; report only an armed span.
retireSpanToken();
+ armSpan(next);
- if (spanRef.current !== null) {
+ if (next !== null) {
spanTokenRef.current = token;
}
- seekWithinSpan(video, startSeconds);
- // Autoplay policy can refuse an unmuted play(). That leaves the clip parked on the
- // first selected frame with the native controls live and the loop still armed, so
- // pressing play there plays the selection rather than the whole clip.
- void video.play().catch(() => {});
- // Arm onPlay for asynchronous play(), and immediately for already-playing elements that emit no new play
- // event.
- startSpanWatch();
- publishSpanState();
+ pendingSpanStartRef.current = { expiresAt: deadline, startSeconds, token };
+ setSpanStartRequest((request) => request + 1);
},
- [publishSpanState, retireSpanToken, seekWithinSpan, startSpanWatch]
+ [armSpan, retireSpanToken]
);
- // Retire loops only when seeks land outside the span; own-seek markers fail for no-op or delayed seeks.
- // In-window scrubs preserve looping.
- const handleSpanSeeking = useCallback(() => {
- const span = spanRef.current;
+ const startPendingSpan = useCallback(() => {
+ const pending = pendingSpanStartRef.current;
+ const video = videoRef.current;
+
+ pendingSpanStartRef.current = null;
+
+ // On show this runs before the show effect consumes a request made while hidden; tokens only grow, so a pending
+ // request newer than the held start supersedes it, and starting first would play the old span for a moment.
+ const request = getVideoSpanPlaybackRequest();
+
+ if (!pending || !video || Date.now() > pending.expiresAt || (request && request.token > pending.token)) {
+ return;
+ }
+
+ seekVideo(video, pending.startSeconds);
+ // Autoplay policy can refuse an unmuted play(). That leaves the clip parked on the first selected frame with
+ // the span still armed, so pressing play there plays the selection rather than the whole clip.
+ void video.play().catch(() => {});
+ publishSpanState();
+ }, [publishSpanState]);
+ // Retire spans only when seeks land outside them; own-seek markers fail for no-op or delayed seeks. In-span scrubs,
+ // and the player's own wraps, rests and replays, keep the span. The player never acts on a seek, so the retirement
+ // needs no particular timing.
+ const handleSeeking = useCallback(() => {
+ const current = spanRef.current;
const video = videoRef.current;
if (!video) {
@@ -653,51 +672,25 @@ const PreviewVideo = ({
}
if (
- span &&
- video.currentTime >= span.startSeconds - SPAN_SEEK_TOLERANCE_SECONDS &&
- video.currentTime <= span.endSeconds
+ current &&
+ video.currentTime >= current.startSeconds - SPAN_SEEK_TOLERANCE_SECONDS &&
+ video.currentTime <= current.endSeconds
) {
return;
}
- spanRef.current = null;
parkedSpanRef.current = null;
- stopSpanWatch();
+ armSpan(null);
retireSpanToken();
- }, [retireSpanToken, stopSpanWatch]);
- const handlePlay = useCallback(() => {
- startSpanWatch();
- publishSpanState();
- }, [publishSpanState, startSpanWatch]);
- const handlePause = useCallback(() => {
- stopSpanWatch();
- publishSpanState();
- }, [publishSpanState, stopSpanWatch]);
- // Handle emptied because load() pauses without a pause event; otherwise controls offer a stop that cannot change
- // anything.
+ }, [armSpan, retireSpanToken]);
+ // Handle emptied because load() pauses without a pause event; otherwise the Video panel offers a stop that cannot
+ // change anything.
const handleEmptied = useCallback(() => {
publishCopyAvailability();
publishSpanState();
}, [publishCopyAvailability, publishSpanState]);
- // Handle ended explicitly for spans ending at clip duration because pause has already stopped the frame watcher.
- const handleSpanEnded = useCallback(() => {
- const span = spanRef.current;
- const video = videoRef.current;
-
- if (!span || !video) {
- return;
- }
-
- seekWithinSpan(video, span.startSeconds);
- void video.play().catch(() => {});
- // Publish resumed playback in the same task as end wrapping so the control icon cannot blink between pause and
- // play events.
- publishSpanState();
- }, [publishSpanState, seekWithinSpan]);
- // Pause on unmount or hidden Activity cleanup so audio cannot outlive reachable controls. Subscribe by fixed
- // item key and consume pending requests on show.
+ // Subscribe by fixed item key and consume pending requests on show. The player pauses itself on hide and unmount.
useMountEffect(() => {
- const video = videoRef.current;
const itemKey = source.itemKey;
const consumeSpanRequest = (): void => {
const request = getVideoSpanPlaybackRequest();
@@ -731,9 +724,7 @@ const PreviewVideo = ({
return () => {
unsubscribe();
- stopSpanWatch();
- video?.pause();
- // Report nothing stoppable while hidden, but retain loop identity for native playback after showing.
+ // Report nothing stoppable while hidden, but retain span identity for playback after showing.
const token = spanTokenRef.current;
if (token !== null) {
@@ -814,7 +805,7 @@ const PreviewVideo = ({
// After load() recovery, restore the armed span's position without starting audio or running a nudge that
// would retire it.
if (spanRef.current) {
- seekWithinSpan(video, spanRef.current.startSeconds);
+ seekVideo(video, spanRef.current.startSeconds);
return;
}
@@ -822,12 +813,9 @@ const PreviewVideo = ({
return;
}
- try {
- video.currentTime = FIRST_FRAME_SEEK_SECONDS;
- } catch {
- // Some browsers throw if the seekable range is not populated yet; the poster stays up.
- }
- }, [playSpan, seekWithinSpan]);
+ // Some browsers throw if the seekable range is not populated yet; the poster stays up.
+ seekVideo(video, FIRST_FRAME_SEEK_SECONDS);
+ }, [playSpan]);
const handleRetry = useCallback(() => {
const video = videoRef.current;
@@ -850,6 +838,49 @@ const PreviewVideo = ({
},
[onContextMenu]
);
+ const playerFallback = useMemo(
+ () => (
+ <img
+ aria-hidden="true"
+ alt=""
+ draggable={false}
+ height={frameHeight}
+ src={source.poster}
+ style={VIDEO_PLAYER_FALLBACK_STYLE}
+ width={frameWidth}
+ />
+ ),
+ [frameHeight, frameWidth, source.poster]
+ );
+ const failure = hasFailed ? (
+ <>
+ <img
+ aria-hidden="true"
+ alt=""
+ draggable={false}
+ height={frameHeight}
+ src={source.poster}
+ style={VIDEO_FAILURE_POSTER_STYLE}
+ width={frameWidth}
+ />
+ <Flex
+ align="center"
+ bg="blackAlpha.700"
+ direction="column"
+ gap="3"
+ inset="0"
+ justify="center"
+ position="absolute"
+ >
+ <Text color="white" fontSize="lg" fontWeight="semibold">
+ {t('widgets.preview.videoFailed')}
+ </Text>
+ <Button aria-label={t('widgets.preview.videoRetry')} size="lg" onClick={handleRetry}>
+ {t('widgets.preview.videoRetry')}
+ </Button>
+ </Flex>
+ </>
+ ) : null;
return (
<PreviewStage
@@ -872,15 +903,46 @@ const PreviewVideo = ({
style={swipe.restStyle}
onContextMenu={onContextMenu ? handleContextMenu : undefined}
>
+ <Suspense fallback={playerFallback}>
+ <VideoPlayer
+ ref={setVideoRef}
+ aria-label={source.label}
+ fps={source.fps}
+ loop={loopPreference}
+ overlay={failure}
+ playbackWindow={span}
+ poster={source.poster}
+ size="full"
+ src={source.src}
+ onCanPlay={publishCopyAvailability}
+ onEmptied={handleEmptied}
+ // The player wraps a span ending on the clip's end in the same task as this; reporting here keeps the Video
+ // panel's control from blinking to play on every pass.
+ onEnded={publishSpanState}
+ onError={handleVideoError}
+ onLoadedData={publishCopyAvailability}
+ onLoadedMetadata={handleLoadedMetadata}
+ onLoopChange={onLoopChange}
+ onPause={publishSpanState}
+ onPlay={publishSpanState}
+ onPlaying={publishCopyAvailability}
+ onResize={publishCopyAvailability}
+ onSeeked={publishCopyAvailability}
+ onSeeking={handleSeeking}
+ onVolumeChange={rememberPreviewVideoAudio}
+ onWaiting={publishCopyAvailability}
+ />
+ {spanStartRequest > 0 ? <SpanPlaybackStart key={spanStartRequest} onStart={startPendingSpan} /> : null}
+ </Suspense>
{dragItem ? (
// Keep drag grips unfocusable so KeyboardSensor cannot start invisible Enter/Space drags.
<Badge
ref={setDragHandleRef}
{...listeners}
cursor={isDragging ? 'grabbing' : 'grab'}
- // Top-center: every corner belongs to some browser's own video
- // overlays (fullscreen, picture-in-picture), and the bottom strip
- // is the native control bar.
+ // Top-center, clear of the control bar along the bottom edge. Outside the player, so fullscreen leaves it
+ // behind, where a drag could reach no drop target; above the failure overlay, since a clip that cannot
+ // play can still be dragged into an input, which only needs its name.
insetInlineStart="50%"
position="absolute"
title={t('widgets.preview.dragVideo')}
@@ -888,70 +950,10 @@ const PreviewVideo = ({
touchAction="none"
transform="translateX(-50%)"
variant="solid"
- // Above the failure overlay: a clip that cannot play can still be
- // dragged into an input, which only needs its name.
- zIndex="2"
>
<GripHorizontalIcon aria-hidden="true" size={12} />
</Badge>
) : null}
- {/* User-provided gallery videos do not include a caption-track contract. */}
- {/* oxlint-disable-next-line jsx-a11y/media-has-caption */}
- <video
- ref={setVideoRef}
- aria-label={source.label}
- controls
- playsInline
- poster={source.poster}
- preload="metadata"
- src={source.src}
- style={VIDEO_STYLE}
- onCanPlay={publishCopyAvailability}
- onEmptied={handleEmptied}
- onError={handleVideoError}
- onLoadedData={publishCopyAvailability}
- onEnded={handleSpanEnded}
- onLoadedMetadata={handleLoadedMetadata}
- onPause={handlePause}
- onPlay={handlePlay}
- onPlaying={publishCopyAvailability}
- onResize={publishCopyAvailability}
- onSeeked={publishCopyAvailability}
- onSeeking={handleSpanSeeking}
- onTimeUpdate={enforceSpan}
- onVolumeChange={rememberPreviewVideoAudio}
- onWaiting={publishCopyAvailability}
- />
- {hasFailed ? (
- <>
- <img
- aria-hidden="true"
- alt=""
- draggable={false}
- height={frameHeight}
- src={source.poster}
- style={VIDEO_FAILURE_POSTER_STYLE}
- width={frameWidth}
- />
- <Flex
- align="center"
- bg="blackAlpha.700"
- direction="column"
- gap="3"
- inset="0"
- justify="center"
- position="absolute"
- zIndex="1"
- >
- <Text color="white" fontSize="lg" fontWeight="semibold">
- {t('widgets.preview.videoFailed')}
- </Text>
- <Button aria-label={t('widgets.preview.videoRetry')} size="lg" onClick={handleRetry}>
- {t('widgets.preview.videoRetry')}
- </Button>
- </Flex>
- </>
- ) : null}
</FittedFrame>
{swipeNavigation && swipe.showsNeighbors ? (
<PreviewSwipeNeighbors
@@ -1001,6 +1003,32 @@ const encodeCanvasPng = (canvas: HTMLCanvasElement): Promise<Blob | null> =>
const isCanvasSecurityError = (error: unknown): boolean =>
error instanceof DOMException && error.name === 'SecurityError';
+const seekVideo = (video: HTMLVideoElement, seconds: number): void => {
+ try {
+ video.currentTime = seconds;
+ } catch {
+ // Some browsers throw while the seekable range is still empty; the element keeps its position.
+ }
+};
+
+/**
+ * Starts an armed span's playback, for one request: keyed by it, rendered after the player in the same boundary.
+ * Playback started before the player holds the span's window is judged against the previous window (a finished span's
+ * rest would replay that span over the new one), and the player binds its window in a passive effect.
+ *
+ * Correctness depends on React's commit order: a commit runs all its passive cleanups (unbinding the previous window)
+ * before any passive mount effect, and runs mount effects in tree order, children first, then later siblings. So this
+ * must stay a passive effect, rendered after `VideoPlayer`; a layout effect, or an earlier position, would start
+ * playback before the window. Re-runs (StrictMode, Activity showing again) do nothing: `onStart` consumes its start.
+ */
+const SpanPlaybackStart = ({ onStart }: { onStart: () => void }) => {
+ useMountEffect(() => {
+ onStart();
+ });
+
+ return null;
+};
+
/** A trimmed window of a clip, in seconds, as the Video panel's play buttons request it. */
interface VideoSpan {
endSeconds: number;
@@ -1008,17 +1036,11 @@ interface VideoSpan {
}
/**
- * Allow slight seek undershoot because decoders may not land exactly at span start; own wraps must not retire the
- * loop.
+ * Allow slight seek undershoot because decoders may not land exactly at span start; the player's own wraps must not
+ * retire the span.
*/
const SPAN_SEEK_TOLERANCE_SECONDS = 0.05;
-/**
- * Height of the native video controls, measured up from the frame's bottom edge; touches there never swipe. Tall
- * enough for Chrome Android's timeline, which sits above its button row.
- */
-const VIDEO_CONTROL_BAND_PX = 72;
-
/** Fills the fitted frame, which already has the image's aspect ratio. */
const PLACEHOLDER_IMAGE_STYLE: CSSProperties = {
height: '100%',
@@ -1035,7 +1057,8 @@ const PARKED_SPAN_TTL_MS = 15_000;
// Seek far enough from zero to clear poster state while staying within frame zero.
const FIRST_FRAME_SEEK_SECONDS = 0.0001;
-const VIDEO_STYLE: CSSProperties = {
+/** The poster stands in, as the player would show it, while the player loads. */
+const VIDEO_PLAYER_FALLBACK_STYLE: CSSProperties = {
display: 'block',
height: '100%',
objectFit: 'contain',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx
new file mode 100644
index 0000000000..81bee6d321
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx
@@ -0,0 +1,96 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { expect, it, vi } from 'vitest';
+
+import { PreviewFrame } from './PreviewFrame';
+
+// Holds the player module back, so the frame renders before it arrives, as on a first video after boot.
+const playerModule = vi.hoisted(() => {
+ let release = (): void => {};
+ const loaded = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+
+ return { loaded, release: () => release() };
+});
+
+vi.mock('@platform/ui/video-player/VideoPlayer', async (importOriginal) => {
+ await playerModule.loaded;
+
+ return importOriginal();
+});
+
+vi.mock('@features/identity', () => ({
+ getAuthSession: () => ({ accountEpoch: 1 }),
+ refreshProtectedMediaCookie: () => Promise.resolve(false),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation: {} } } });
+
+const POSTER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
+
+const SOURCE = {
+ itemKey: 'video:clip.mp4',
+ kind: 'video',
+ label: 'Video clip.mp4',
+ poster: POSTER,
+ src: '/scripts/mock-assets/fixture-video.mp4',
+} as const;
+
+it('shows the poster while the player loads, then the player in its place', async () => {
+ const host = document.body.appendChild(document.createElement('div'));
+ const root = createRoot(host);
+
+ try {
+ await act(async () => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <div style={{ display: 'flex', height: 260, width: 420 }}>
+ <PreviewFrame
+ frameHeight={1080}
+ frameWidth={1920}
+ isLive={false}
+ shouldAntialiasLiveImage
+ source={SOURCE}
+ variant="framed"
+ />
+ </div>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await new Promise((resolve) => {
+ setTimeout(resolve, 50);
+ });
+ });
+
+ expect(host.querySelector('video')).toBeNull();
+ expect(host.querySelector(`img[src="${POSTER}"]`)?.getAttribute('aria-hidden')).toBe('true');
+
+ playerModule.release();
+
+ // The mocked module resolves through the test server, which a loaded machine can keep for well over a second;
+ // this test is about what shows first and what replaces it, not how fast.
+ await vi.waitFor(
+ async () => {
+ await act(async () => {});
+ expect(host.querySelector('video')?.getAttribute('poster')).toBe(POSTER);
+ },
+ { timeout: 10_000 }
+ );
+ expect(host.querySelector(`img[src="${POSTER}"]`)).toBeNull();
+ } finally {
+ await act(() => root.unmount());
+ host.remove();
+ }
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx
index 5925b066e3..62b87ae67b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameSwipe.browser.test.tsx
@@ -21,9 +21,23 @@ void i18n.use(initReactI18next).init({
fallbackLng: 'en',
initAsync: false,
lng: 'en',
- resources: { en: { translation: { widgets: { preview: { dragVideo: 'Drag video' } } } } },
+ resources: {
+ en: {
+ translation: {
+ common: { videoPlayer: { playbackSpeedValue: 'Playback speed: {{rate}}', rate: '{{rate}}×' } },
+ widgets: { preview: { dragVideo: 'Drag video' } },
+ },
+ },
+ },
});
+// Preview loads the player with its first video; loading it up front keeps a slow first transform out of these
+// tests' timing. PreviewFrameLazyPlayer covers the lazy path itself.
+await import('@platform/ui/video-player/VideoPlayer');
+
+// The mock backend's clip: 64×64 H.264, one second long. Vite serves the package root.
+const FIXTURE_VIDEO_URL = '/scripts/mock-assets/fixture-video.mp4';
+
// The production hold, so a slow runner cannot arm a drag between a touch and its first quick move.
const HOLD_DELAY_MS = 400;
const STAGE_WIDTH = 300;
@@ -45,7 +59,7 @@ const makeItem = (name: string, kind: 'image' | 'video' = 'image'): GalleryItem
width: 128,
};
- return kind === 'image' ? { ...base, kind } : { ...base, durationSeconds: 1, kind };
+ return kind === 'image' ? { ...base, kind } : { ...base, durationSeconds: 1, fullUrl: FIXTURE_VIDEO_URL, kind };
};
let host: HTMLDivElement | null = null;
@@ -224,8 +238,19 @@ const renderCarousel = async ({
const media = () => host!.querySelector<HTMLElement>('img[alt]:not([alt=""]), video')!;
+ // A video's player loads with the first one shown; until then only its poster stands in.
+ await vi.waitFor(async () => {
+ await act(async () => {});
+ expect(media()).not.toBeNull();
+ });
+
return {
- content: () => media().parentElement!,
+ // The fitted frame: an image's parent, or the frame around a video's player.
+ content: () => {
+ const element = media();
+
+ return (element.tagName === 'VIDEO' ? element.closest('[role="group"]')! : element).parentElement!;
+ },
media,
neighbors: () => [...host!.querySelectorAll<HTMLElement>('[data-swipe-neighbor]')],
onDrop,
@@ -477,12 +502,15 @@ describe('PreviewFrame touch swipe', () => {
expect(carousel.onNavigate).toHaveBeenCalledExactlyOnceWith(1);
});
- it('swipes a video from its picture but leaves the native control bar alone', async () => {
+ it("swipes a video from its picture but leaves the player's control bar alone", async () => {
const carousel = await renderCarousel({ items: [makeItem('red'), makeItem('clip', 'video'), makeItem('blue')] });
const video = carousel.media();
const rect = video.getBoundingClientRect();
+ const bar = host!.querySelector<HTMLElement>('[data-video-player-controls]')!;
+ const barRect = bar.getBoundingClientRect();
- await swipe(video, [200, 170, 140], { y: rect.bottom - 10 });
+ // Anywhere on the bar, its seek track included, belongs to the player.
+ await swipe(bar, [200, 170, 140], { y: barRect.top + barRect.height / 2 });
await interact(() => {}, 400);
expect(carousel.onNavigate).not.toHaveBeenCalled();
@@ -492,4 +520,30 @@ describe('PreviewFrame touch swipe', () => {
expect(carousel.onNavigate).toHaveBeenCalledExactlyOnceWith(1);
});
+
+ it("leaves a touch drag inside the player's portalled speed menu alone", async () => {
+ // Wide enough for the bar to keep its speed menu.
+ const clip = { ...makeItem('clip', 'video'), height: 180, width: 320 };
+ const carousel = await renderCarousel({ items: [makeItem('red'), clip, makeItem('blue')] });
+ const trigger = host!.querySelector<HTMLButtonElement>('[aria-label="Playback speed: 1×"]')!;
+
+ // The controls come alive once the clip's metadata is in.
+ await vi.waitFor(() => expect(trigger.disabled).toBe(false), { timeout: 5000 });
+ await interact(() => trigger.click(), 200);
+ const option = [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(
+ (item) => item.textContent === '2×'
+ )!;
+ const optionRect = option.getBoundingClientRect();
+
+ // The menu renders outside the stage, but its events still reach the stage through the portal.
+ expect(host!.contains(option)).toBe(false);
+
+ await swipe(option, [optionRect.left + 60, optionRect.left + 30, optionRect.left], {
+ y: optionRect.top + optionRect.height / 2,
+ });
+ await interact(() => {}, 400);
+
+ expect(carousel.onNavigate).not.toHaveBeenCalled();
+ expect(carousel.content().style.translate).toBe('');
+ });
});
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 a32972cdb7..f17f619e4f 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,10 +5,11 @@ 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, Activity, createRef, type Ref } from 'react';
+import { act, Activity, createRef, type Ref, StrictMode } 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';
+import { page, userEvent } from 'vitest/browser';
import {
PreviewFrame,
@@ -36,26 +37,20 @@ vi.mock('@features/identity', () => ({
}));
const i18n = createInstance();
-void i18n.use(initReactI18next).init({
+await i18n.use(initReactI18next).init({
fallbackLng: 'en',
- initAsync: false,
+ interpolation: { escapeValue: false },
lng: 'en',
- resources: {
- en: {
- translation: {
- widgets: {
- preview: {
- dropToCompare: 'Drop to compare',
- resetZoom: 'Reset zoom',
- videoFailed: 'Video could not be loaded',
- videoRetry: 'Retry',
- },
- },
- },
- },
- },
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
});
+// Preview loads the player with its first video. Loaded up front, it mounts in the render that asks for it, before the
+// element can load media the stubbed tests below stand in for.
+await import('@platform/ui/video-player/VideoPlayer');
+
+// The mock backend's clip: 64×64 H.264, 10 frames at 10 fps, one second long. Vite serves the package root.
+const FIXTURE_VIDEO_URL = '/scripts/mock-assets/fixture-video.mp4';
+
type VideoSource = Extract<PreviewMediaSource, { kind: 'video' }>;
const videoSource: VideoSource = {
@@ -66,6 +61,12 @@ const videoSource: VideoSource = {
src: 'data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA',
};
const invalidVideoSource: VideoSource = { ...videoSource, src: 'data:video/mp4;base64,AAAA' };
+const fixtureVideoSource: VideoSource = {
+ ...videoSource,
+ fps: 10,
+ itemKey: 'video:fixture.mp4',
+ src: FIXTURE_VIDEO_URL,
+};
let host: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -96,13 +97,17 @@ const DragMonitor = () => {
const VideoHarness = ({
isItemCurrent = () => true,
onCopyAvailabilityChange,
+ onVideoLoopChange,
source = videoSource,
videoControllerRef,
+ videoLoop,
}: {
isItemCurrent?: (itemKey: GalleryItemKey) => boolean;
onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
+ onVideoLoopChange?: (loop: boolean) => void;
source?: VideoSource;
videoControllerRef?: Ref<PreviewVideoFrameController>;
+ videoLoop?: boolean;
}) => {
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
@@ -120,6 +125,8 @@ const VideoHarness = ({
isItemCurrent={isItemCurrent}
onVideoCopyAvailabilityChange={onCopyAvailabilityChange}
videoControllerRef={videoControllerRef}
+ videoLoop={videoLoop}
+ onVideoLoopChange={onVideoLoopChange}
/>
</div>
</DndContext>
@@ -146,28 +153,21 @@ afterEach(async () => {
root = null;
});
-describe('PreviewFrame native video arm', () => {
- it('renders the native player with the protected media contract attributes', async () => {
- await interact(() => {
- root?.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <VideoHarness />
- </ChakraProvider>
- </I18nextProvider>
- );
- });
+describe('PreviewFrame video', () => {
+ it('renders the player with the protected media contract attributes', async () => {
+ await renderVideo();
- const video = host?.querySelector<HTMLVideoElement>('video');
+ const video = getVideo();
- expect(video).not.toBeNull();
expect(host?.querySelectorAll('video')).toHaveLength(1);
- expect(video?.controls).toBe(true);
- expect(video?.playsInline).toBe(true);
- expect(video?.getAttribute('preload')).toBe('metadata');
- expect(video?.getAttribute('poster')).toBe(videoSource.poster);
- expect(video?.getAttribute('src')).toBe(videoSource.src);
- expect(video?.getAttribute('aria-label')).toBe(videoSource.label);
+ expect(video.controls).toBe(false);
+ expect(video.playsInline).toBe(true);
+ expect(video.getAttribute('preload')).toBe('metadata');
+ expect(video.getAttribute('poster')).toBe(videoSource.poster);
+ expect(video.getAttribute('src')).toBe(videoSource.src);
+ await expect.element(page.getByRole('group', { name: videoSource.label })).toContainElement(video);
+ // Looping is on until the viewer turns it off.
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toHaveAttribute('aria-pressed', 'true');
expect(host?.querySelector('img[alt="Video clip.mp4"]')).toBeNull();
});
@@ -488,7 +488,7 @@ describe('PreviewFrame native video arm', () => {
expect(playback.getTime()).toBe(9);
});
- it('reports the loop under its request, stops it on demand, and resumes it from the native control', async () => {
+ it('reports the loop under its request, stops it on demand, and resumes it from the player', async () => {
const token = requestVideoSpanPlayback({ endSeconds: 4, itemKey: videoSource.itemKey, startSeconds: 2 });
await renderVideo();
const video = getVideo();
@@ -541,7 +541,7 @@ describe('PreviewFrame native video arm', () => {
await interact(() => undefined);
expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: third });
- // Hiding pauses and clears running status; showing preserves armed identity for native play.
+ // Hiding pauses and clears running status; showing preserves armed identity for the player's play.
await renderKeptVideo('hidden');
expect(getVideoSpanPlaybackState()).toBeNull();
@@ -552,30 +552,25 @@ describe('PreviewFrame native video arm', () => {
expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token: third });
});
- it('does not offer a stop for a window the clamp collapsed', async () => {
+ it('plays a span the clamp collapsed from its start as the loop toggle says, with no stop to offer', async () => {
await renderVideo();
const video = getVideo();
const playback = stubSpanPlayback(video, { duration: 6 });
- // Collapsed bounds play once without reporting an armed selection loop.
+ // Collapsed bounds are no window: the clip plays from there, and the viewer's loop stays as it was.
await interact(() => requestVideoSpanPlayback({ endSeconds: 9, itemKey: videoSource.itemKey, startSeconds: 8 }));
expect(playback.play).toHaveBeenCalledTimes(1);
+ expect(playback.getTime()).toBe(6);
expect(getVideoSpanPlaybackState()).toBeNull();
+ expect(video.loop).toBe(true);
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toHaveAttribute('aria-pressed', 'true');
});
- it('does not arm a drag or cancel wheel events from the video surface and native controls', async () => {
- await interact(() => {
- root?.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <VideoHarness />
- </ChakraProvider>
- </I18nextProvider>
- );
- });
+ it('does not arm a drag or cancel wheel events from the video surface and its player', async () => {
+ await renderVideo();
- const video = host!.querySelector<HTMLVideoElement>('video')!;
+ const video = getVideo();
const content = video.parentElement;
expect(content).not.toBeNull();
@@ -679,7 +674,7 @@ describe('PreviewFrame native video arm', () => {
await interact(() => firstVideo.dispatchEvent(new Event('error')));
expect(host?.textContent).toContain('Video could not be loaded');
- expect(host?.querySelector<HTMLButtonElement>('button')?.textContent).toBe('Retry');
+ await expect.element(page.getByRole('button', { name: 'Retry' })).toBeVisible();
expect(
[...(host?.querySelectorAll<HTMLImageElement>('img') ?? [])].some(
(image) => image.getAttribute('src') === videoSource.poster
@@ -708,7 +703,7 @@ describe('PreviewFrame native video arm', () => {
await interact(() => video.dispatchEvent(new Event('error')));
expect(identityMocks.refreshProtectedMediaCookie).toHaveBeenCalledTimes(1);
- await interact(() => host?.querySelector<HTMLButtonElement>('button')?.click());
+ await interact(() => getRetryButton().click());
expect(load).toHaveBeenCalledTimes(2);
expect(host?.textContent).not.toContain('Video could not be loaded');
@@ -952,46 +947,258 @@ describe('PreviewFrame native video arm', () => {
});
});
+describe('PreviewFrame video span playback through the player', () => {
+ it('loops a requested span within the clip while looping is on', async () => {
+ await renderHarness({ source: fixtureVideoSource });
+ const video = await loadedVideo();
+ const seeks = recordSeeks(video);
+ const token = requestVideoSpanPlayback({ endSeconds: 0.5, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.2 });
+
+ await expect.poll(() => video.paused).toBe(false);
+ // The scrubber shades the span the player now confines playback to.
+ await expect.poll(() => getScrubberRoot().hasAttribute('data-playback-window')).toBe(true);
+
+ // The request's own seek, then at least one wrap back from the span's end.
+ await expect.poll(() => seeks.filter(isSpanStart).length, { timeout: 3000 }).toBeGreaterThanOrEqual(2);
+ expect(video.paused).toBe(false);
+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });
+ video.pause();
+ });
+
+ it('plays a requested span once and rests on its last frame while looping is off, then replays it from the player', async () => {
+ await renderHarness({ source: fixtureVideoSource, videoLoop: false });
+ const video = await loadedVideo();
+ const seeks = recordSeeks(video);
+ // Frames 2 to 4, as the Video panel asks: the end is frame 5's start, exclusive.
+ const token = requestVideoSpanPlayback({ endSeconds: 0.5, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.2 });
+ const isResting = () => video.paused && !video.seeking && Math.abs(video.currentTime - 0.45) < 1e-6;
+
+ await expect.poll(() => video.paused).toBe(false);
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+
+ await expect.element(page.getByText('Frame 4 / 9')).toBeVisible();
+ expect(seeks.filter(isSpanStart)).toHaveLength(1);
+ // Still armed: the Video panel's control turns back into play for the same request.
+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false, token });
+
+ await userEvent.click(page.getByRole('button', { name: 'Play' }));
+
+ await expect.poll(() => seeks.filter(isSpanStart).length).toBe(2);
+ await expect.poll(() => getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });
+ await expect.poll(isResting, { timeout: 3000 }).toBe(true);
+ });
+
+ it("starts a span only once the player holds its window, so a finished span's rest cannot replay over it", async () => {
+ await renderHarness({ source: fixtureVideoSource, videoLoop: false });
+ const video = await loadedVideo();
+ requestVideoSpanPlayback({ endSeconds: 0.5, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.2 });
+ await expect
+ .poll(() => video.paused && !video.seeking && Math.abs(video.currentTime - 0.45) < 1e-6, { timeout: 3000 })
+ .toBe(true);
+ const seeks = recordSeeks(video);
+ // The player judges the play event that `play()` queues against the window it holds by then. Firing that event at
+ // the call asks the same question of the window it holds now, whatever the browser's task order: the finished
+ // span's window would take the new span's start, past its rest, back to its own start at once.
+ const placementsAtPlay: number[] = [];
+ const nativePlay = video.play.bind(video);
+ vi.spyOn(video, 'play').mockImplementation(() => {
+ video.dispatchEvent(new Event('play'));
+ placementsAtPlay.push(video.currentTime);
+ return nativePlay();
+ });
+
+ // Frames 5 to 8, which start past the finished span's rest; published outside any React event, as the Video panel
+ // does.
+ const token = requestVideoSpanPlayback({ endSeconds: 0.9, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.5 });
+
+ await expect.poll(() => getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });
+ expect(placementsAtPlay).toHaveLength(1);
+ expect(placementsAtPlay[0]).toBeCloseTo(0.5);
+ // It plays the new span once, from its start, and rests on its last frame.
+ await expect
+ .poll(() => video.paused && !video.seeking && Math.abs(video.currentTime - 0.85) < 1e-6, { timeout: 3000 })
+ .toBe(true);
+ expect(seeks[0]).toBeCloseTo(0.5);
+ expect(seeks.some(isSpanStart)).toBe(false);
+ expect(getVideoSpanPlaybackState()).toMatchObject({ isPlaying: false, token });
+ });
+
+ it('hands the loop toggle to the caller', async () => {
+ const onVideoLoopChange = vi.fn();
+ await renderHarness({ onVideoLoopChange, source: fixtureVideoSource, videoLoop: false });
+ const video = await loadedVideo();
+ const loopButton = page.getByRole('button', { name: 'Loop' });
+
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'false');
+ expect(video.loop).toBe(false);
+
+ await userEvent.click(loopButton);
+
+ expect(onVideoLoopChange).toHaveBeenCalledExactlyOnceWith(true);
+ });
+
+ it("retires the span when the player's scrubber takes the playhead outside it", async () => {
+ await renderHarness({ source: fixtureVideoSource });
+ const video = await loadedVideo();
+
+ requestVideoSpanPlayback({ endSeconds: 0.5, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.2 });
+ await expect.poll(() => getVideoSpanPlaybackState()?.isPlaying).toBe(true);
+
+ await act(() => page.getByRole('slider', { name: 'Seek' }).element().focus());
+ await userEvent.keyboard('{End}');
+
+ await expect.poll(() => getVideoSpanPlaybackState()).toBeNull();
+ await expect.poll(() => getScrubberRoot().hasAttribute('data-playback-window')).toBe(false);
+ // Back to the viewer's loop over the whole clip.
+ expect(video.loop).toBe(true);
+ video.pause();
+ });
+});
+
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');
+ const playback = stubSpanPlayback(video);
+ await interact(() => void video.play());
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.
+ // `display: none` does not stop media, so the player has to pause it itself, once.
expect(getVideo()).toBe(video);
expect(video.checkVisibility()).toBe(false);
- expect(pause).toHaveBeenCalledOnce();
+ expect(playback.pauseSpy).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');
+ const playback = stubSpanPlayback(video);
+ await interact(() => void video.play());
await renderKeptVideo('visible');
expect(getVideo()).toBe(video);
- expect(pause).not.toHaveBeenCalled();
+ expect(playback.pauseSpy).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { shownAfterMs: 0, starts: true },
+ { shownAfterMs: 16_000, starts: false },
+ ])(
+ 'starts a span the view hid before it started once shown $shownAfterMs ms later: $starts',
+ async ({ shownAfterMs, starts }) => {
+ const options = { source: fixtureVideoSource };
+ await renderKeptVideo('visible', options);
+ const video = await loadedVideo();
+ const now = Date.now();
+
+ // The request arms the span while shown; the hide lands in the same commit, before the span can start.
+ await interact(() => {
+ requestVideoSpanPlayback({ endSeconds: 0.9, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.5 });
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Activity mode="hidden">
+ <VideoHarness source={fixtureVideoSource} />
+ </Activity>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ expect(video.paused).toBe(true);
+ vi.spyOn(Date, 'now').mockReturnValue(now + shownAfterMs);
+ await renderKeptVideo('visible', options);
+ // Long enough for a start to have played past the span's first frame.
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 300);
+ });
+
+ expect(video.paused).toBe(!starts);
+ expect(video.currentTime >= 0.5).toBe(starts);
+ video.pause();
+ }
+ );
+
+ it('drops a held span for a newer request made while hidden, without playing it first', async () => {
+ const options = { source: fixtureVideoSource };
+ await renderKeptVideo('visible', options);
+ const video = await loadedVideo();
+
+ // Span A is armed while shown and held by a hide in the same commit; span B is requested while hidden.
+ let held = 0;
+ await interact(() => {
+ held = requestVideoSpanPlayback({ endSeconds: 0.9, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.5 });
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Activity mode="hidden">
+ <VideoHarness source={fixtureVideoSource} />
+ </Activity>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ const token = requestVideoSpanPlayback({ endSeconds: 0.4, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.2 });
+ const seeks = recordSeeks(video);
+ const playingTokens: number[] = [];
+ const unsubscribe = subscribeVideoSpanPlaybackState(() => {
+ const state = getVideoSpanPlaybackState();
+
+ if (state?.isPlaying) {
+ playingTokens.push(state.token);
+ }
+ });
+
+ try {
+ await renderKeptVideo('visible', options);
+
+ await expect.poll(() => getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });
+ expect(playingTokens).not.toContain(held);
+ expect(seeks.some((time) => Math.abs(time - 0.5) < 1e-6)).toBe(false);
+ } finally {
+ unsubscribe();
+ video.pause();
+ }
+ });
+
+ it('plays a span requested while hidden once shown, under StrictMode', async () => {
+ const options = { source: fixtureVideoSource, strict: true };
+ await renderKeptVideo('visible', options);
+ const video = await loadedVideo();
+ await renderKeptVideo('hidden', options);
+
+ // The Video panel raises Preview and requests the span before the reveal renders.
+ const token = requestVideoSpanPlayback({ endSeconds: 0.9, itemKey: fixtureVideoSource.itemKey, startSeconds: 0.5 });
+ await renderKeptVideo('visible', options);
+
+ await expect.poll(() => getVideoSpanPlaybackState()).toMatchObject({ isPlaying: true, token });
+ expect(video.currentTime).toBeGreaterThanOrEqual(0.5);
+ video.pause();
});
});
-const renderKeptVideo = async (mode: 'hidden' | 'visible'): Promise<void> => {
+/** Renders the player kept alive in an Activity; `strict` renders it as the app does in development. */
+const renderKeptVideo = async (
+ mode: 'hidden' | 'visible',
+ { source, strict = false }: { source?: VideoSource; strict?: boolean } = {}
+): Promise<void> => {
+ const app = (
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Activity mode={mode}>
+ <VideoHarness source={source} />
+ </Activity>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+
await interact(() => {
- root?.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <Activity mode={mode}>
- <VideoHarness />
- </Activity>
- </ChakraProvider>
- </I18nextProvider>
- );
+ root?.render(strict ? <StrictMode>{app}</StrictMode> : app);
});
+ await waitForPlayer();
};
const renderVideo = async (
@@ -1014,6 +1221,69 @@ const renderVideo = async (
</I18nextProvider>
);
});
+ await waitForPlayer();
+};
+
+const renderHarness = async (props: Parameters<typeof VideoHarness>[0]): Promise<void> => {
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <VideoHarness {...props} />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ await waitForPlayer();
+};
+
+/** The player loads with the first video Preview shows; until then the poster stands in. */
+const waitForPlayer = async (): Promise<void> => {
+ // Once loaded, the player mounts in the render itself; returning at once keeps the stubbed tests ahead of the media.
+ if (host?.querySelector('video')) {
+ return;
+ }
+
+ await vi.waitFor(async () => {
+ // Inside act, React holds the retry the loaded player schedules until act ends.
+ await act(async () => {});
+ expect(host?.querySelector('video')).not.toBeNull();
+ });
+};
+
+/** The mounted video once its metadata and first frame are in, so the player's controls are live. */
+const loadedVideo = async (): Promise<HTMLVideoElement> => {
+ const video = getVideo();
+
+ await expect.poll(() => video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA, { timeout: 5000 }).toBe(true);
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+ // A span request follows a press in the Video panel; without that activation the browser refuses audible playback.
+ await userEvent.keyboard('{Shift}');
+
+ return video;
+};
+
+const recordSeeks = (video: HTMLVideoElement): number[] => {
+ const seeks: number[] = [];
+
+ video.addEventListener('seeking', () => seeks.push(video.currentTime));
+
+ return seeks;
+};
+
+const isSpanStart = (seconds: number): boolean => Math.abs(seconds - 0.2) < 1e-6;
+
+const getScrubberRoot = (): Element => {
+ const scrubber = page
+ .getByRole('slider', { name: 'Seek' })
+ .element()
+ .closest('[data-scope="slider"][data-part="root"]');
+
+ if (!scrubber) {
+ throw new Error('Expected the player scrubber.');
+ }
+
+ return scrubber;
};
const getVideo = (): HTMLVideoElement => {
@@ -1026,6 +1296,9 @@ const getVideo = (): HTMLVideoElement => {
return video;
};
+const getRetryButton = (): HTMLButtonElement =>
+ page.getByRole('button', { name: 'Retry' }).element() as HTMLButtonElement;
+
const deferred = <T,>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((resolvePromise) => {
@@ -1118,6 +1391,7 @@ const stubSpanPlayback = (
},
},
duration: { configurable: true, get: () => duration },
+ ended: { configurable: true, get: () => paused && currentTime >= duration },
paused: { configurable: true, get: () => paused },
readyState: { configurable: true, get: () => currentReadyState },
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx
new file mode 100644
index 0000000000..2e4ddb696e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx
@@ -0,0 +1,125 @@
+import type { GalleryItem } from '@features/gallery';
+
+import { ChakraProvider, Flex } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import type { PreviewSwipeNavigation } from './usePreviewSwipe';
+
+import { PreviewFrame } from './PreviewFrame';
+import { PREVIEW_NAV_STAGE_CSS, PreviewNavButtons } from './PreviewNavButtons';
+
+vi.mock('@features/identity', () => ({
+ getAuthSession: () => ({ accountEpoch: 1 }),
+ refreshProtectedMediaCookie: () => Promise.resolve(false),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+// Preview loads the player with its first video; loaded up front, it mounts in the render that asks for it.
+await import('@platform/ui/video-player/VideoPlayer');
+
+const neighbor: GalleryItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-01-01T00:00:00Z',
+ fullUrl: '/neighbor.png',
+ height: 64,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'neighbor',
+ starred: false,
+ thumbnailUrl: '/neighbor.png',
+ width: 64,
+};
+const navigation: PreviewSwipeNavigation = {
+ neighbors: { next: { item: neighbor, kind: 'item' }, previous: { item: neighbor, kind: 'item' } },
+ onNavigate: () => Promise.resolve(true),
+};
+
+const SOURCE = {
+ fps: 10,
+ itemKey: 'video:clip',
+ kind: 'video',
+ label: 'Video clip',
+ poster: '',
+ src: '/scripts/mock-assets/fixture-video.mp4',
+} as const;
+
+const overlaps = (a: DOMRect, b: DOMRect): boolean =>
+ a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
+
+// A 16:9 clip in stages down to a small floating window, where the frame fills the stage and its bar is most of it.
+it.each([
+ [480, 300],
+ [290, 200],
+ [240, 160],
+ [220, 140],
+ [200, 120],
+])("keeps a video's arrows off its control bar in a %i x %i stage", async (width, height) => {
+ const host = document.body.appendChild(document.createElement('div'));
+ const root = createRoot(host);
+
+ try {
+ await act(() => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <Flex
+ css={PREVIEW_NAV_STAGE_CSS}
+ direction="column"
+ h={`${height}px`}
+ position="relative"
+ w={`${width}px`}
+ >
+ <PreviewFrame
+ frameHeight={1080}
+ frameWidth={1920}
+ isLive={false}
+ padding="3"
+ shouldAntialiasLiveImage
+ source={SOURCE}
+ swipe={navigation}
+ variant="framed"
+ />
+ <PreviewNavButtons isVideo navigation={navigation} />
+ </Flex>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+
+ const arrows = [...host.querySelectorAll('[data-preview-nav] button')].map((arrow) =>
+ arrow.getBoundingClientRect()
+ );
+ const controls = [
+ ...host.querySelectorAll('[data-video-player-controls] button, [data-video-player-controls] [role="slider"]'),
+ ]
+ .filter((control) => control.checkVisibility())
+ .map((control) => ({ box: control.getBoundingClientRect(), name: control.getAttribute('aria-label') }));
+
+ expect(arrows).toHaveLength(2);
+ expect(controls.length).toBeGreaterThan(0);
+ expect(
+ controls.filter((control) => arrows.some((arrow) => overlaps(arrow, control.box))).map((control) => control.name)
+ ).toEqual([]);
+ } finally {
+ await act(() => root.unmount());
+ host.remove();
+ }
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx
index 640ddd86d8..f71c8d2145 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx
@@ -104,8 +104,9 @@ const NavButton = ({
insetInlineEnd={side === 'end' ? '2' : undefined}
insetInlineStart={side === 'start' ? '2' : undefined}
position="absolute"
- // A video's controls run along the bottom of the stage; center over what is left above them.
- top={isVideo ? 'calc(50% - 1.5rem)' : '50%'}
+ // A video's control bar (about 4.5rem) overlays the bottom of its frame, which is centered in the stage; center
+ // over the picture above the bar, so a short frame's scrubber never sits under an arrow.
+ top={isVideo ? 'calc(50% - 2.25rem)' : '50%'}
transform="translateY(-50%)"
zIndex="1"
>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index b74cf065cb..1099c17305 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -25,7 +25,7 @@ import { act, useCallback } 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';
-import { commands, userEvent } from 'vitest/browser';
+import { commands, page, userEvent } from 'vitest/browser';
import { LivePreviewFollowProvider, useLivePreviewFollow } from './livePreviewFollow';
import { usePreviewHeaderContext, type PreviewItemPosition } from './previewHeaderStore';
@@ -64,6 +64,13 @@ const createImageItem = (name: string, createdAt: string): GalleryImageItem => (
width: 1280,
});
+// Preview loads the player with its first video; loading it up front keeps a slow first transform out of these
+// tests' timing. PreviewFrameLazyPlayer covers the lazy path itself.
+await import('@platform/ui/video-player/VideoPlayer');
+
+// The mock backend's clip: 64×64 H.264, one second long. Vite serves the package root.
+const FIXTURE_VIDEO_URL = '/scripts/mock-assets/fixture-video.mp4';
+
const createVideoItem = (name: string, createdAt: string): GalleryVideoItem => ({
boardId: 'none',
category: 'general',
@@ -477,7 +484,20 @@ await i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
- common: { countOfTotal: '{{count}} of {{total}}', generating: 'Generating' },
+ common: {
+ countOfTotal: '{{count}} of {{total}}',
+ generating: 'Generating',
+ videoPlayer: {
+ frame: 'Frame {{frame}}',
+ frameOfLast: 'Frame {{frame}}, last {{last}}',
+ loop: 'Loop',
+ mute: 'Mute',
+ nextFrame: 'Next frame',
+ previousFrame: 'Previous frame',
+ seek: 'Seek',
+ volume: 'Volume',
+ },
+ },
widgets: {
gallery: { commands: { clearSelection: 'Clear gallery selection' } },
preview: {
@@ -488,6 +508,7 @@ await i18n.use(initReactI18next).init({
itemCount_one: '{{count}} item',
itemCount_other: '{{count}} items',
videoDuration: 'Duration {{duration}}',
+ videoLabel: 'Video {{name}}',
},
},
},
@@ -3600,43 +3621,110 @@ describe('preview keyboard navigation boundary', () => {
expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(sameNameImage, undefined, 0, true);
});
- it('leaves native video keys untouched and omits image-only hotkey registrations', async () => {
- const videoItem = createVideoItem('native-controls', '2026-07-30T12:00:00Z');
+ it('steps items with the arrows from the player, leaves them to its scrubber, and omits image-only hotkeys', async () => {
+ const videoItem = { ...createVideoItem('player-keys', '2026-07-30T12:00:00Z'), fullUrl: FIXTURE_VIDEO_URL };
+ const newerNeighbor = createImageItem('newer-neighbor', '2026-07-30T13:00:00Z');
const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
galleryValues.recentImages = [];
galleryValues.selectedImage = videoItem;
- galleryValues.selectedImageName = 'video:native-controls';
- // A neighbour on each side, so an arrow the video lost to the workbench would select one.
+ galleryValues.selectedImageName = 'video:player-keys';
+ // A neighbour on each side, so an arrow the scrubber lost to the workbench would select one.
mocks.galleryItemPages = [
{
- items: [
- createImageItem('newer-neighbor', '2026-07-30T13:00:00Z'),
- videoItem,
- createImageItem('older-neighbor', '2026-07-30T11:00:00Z'),
- ],
+ items: [newerNeighbor, videoItem, createImageItem('older-neighbor', '2026-07-30T11:00:00Z')],
total: 3,
},
];
await render();
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
- const video = host?.querySelector<HTMLVideoElement>('video');
- expect(video).not.toBeNull();
+ // A focused scrubber seeks with the arrows; neither the player nor Preview steps the item.
+ for (const key of ['ArrowLeft', 'ArrowRight']) {
+ const event = await pressKeyOn(page.getByRole('slider', { name: 'Seek' }).element() as HTMLElement, key);
+
+ expect(event.defaultPrevented).toBe(true);
+ }
+
+ // So does the volume slider, here in the popover a player this narrow opens it from. The popover moves focus to
+ // its first control as it opens; let that land before focusing the slider, or it takes focus back mid-press.
+ await act(() => (page.getByRole('button', { exact: true, name: 'Volume' }).element() as HTMLElement).click());
+ await expect.element(page.getByRole('button', { exact: true, name: 'Mute' })).toHaveFocus();
- // The video seeks with the arrows itself; Preview's own image-only keys are not registered for it at all.
for (const key of ['ArrowLeft', 'ArrowRight']) {
- const event = await pressKeyOn(video!, key);
+ const event = await pressKeyOn(page.getByRole('slider', { name: 'Volume' }).element() as HTMLElement, key);
- expect(event.defaultPrevented).toBe(false);
+ expect(event.defaultPrevented).toBe(true);
}
+ await userEvent.keyboard('{Escape}');
expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();
+
+ // Anywhere else in the player the arrows are Preview's, and step once.
+ await pressKeyOn(page.getByRole('group', { name: 'Video player-keys' }).element() as HTMLElement, 'ArrowLeft');
+
+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(newerNeighbor, undefined, 0, true);
expect([...registeredHotkeys.keys()]).not.toContain('viewer.swapImages');
expect([...registeredHotkeys.keys()]).not.toContain('viewer.zoomToActual');
expect([...registeredHotkeys.keys()]).not.toContain('viewer.zoomToFit');
});
+ it("hands the item's frame rate to the player, which steps one of its frames", async () => {
+ const videoItem = { ...createVideoItem('framed', '2026-07-30T12:00:00Z'), fullUrl: FIXTURE_VIDEO_URL };
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = videoItem;
+ galleryValues.selectedImageName = 'video:framed';
+ mocks.galleryItemPages = [{ items: [videoItem], total: 1 }];
+
+ await render();
+ const player = page.getByRole('group', { name: 'Video framed' });
+
+ const scrubber = page.getByRole('slider', { name: 'Seek' });
+
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toBeEnabled();
+ // The one-second clip at the item's 23.976 fps: frames 0 to 22, whatever the bar has room to show.
+ await expect.element(scrubber).toHaveAttribute('aria-valuetext', 'Frame 0, last 22');
+
+ await pressKeyOn(player.element() as HTMLElement, '.');
+
+ // Frame 1 is sought at its middle.
+ await expect.poll(() => player.element().querySelector('video')?.currentTime).toBeCloseTo(1.5 / 23.976, 3);
+ await expect.element(scrubber).toHaveAttribute('aria-valuetext', 'Frame 1, last 22');
+ });
+
+ it("remembers the player's loop toggle as a Preview value", async () => {
+ const videoItem = { ...createVideoItem('looping', '2026-07-30T12:00:00Z'), fullUrl: FIXTURE_VIDEO_URL };
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = videoItem;
+ galleryValues.selectedImageName = 'video:looping';
+ mocks.galleryItemPages = [{ items: [videoItem], total: 1 }];
+
+ await render();
+ const loopButton = page.getByRole('button', { name: 'Loop' });
+
+ await expect.element(loopButton).toBeEnabled();
+ await expect.element(loopButton).toHaveAttribute('aria-pressed', 'true');
+ await act(() => (loopButton.element() as HTMLButtonElement).click());
+
+ expect(mocks.commands.widgets.patchValues).toHaveBeenLastCalledWith('preview', { videoLoop: false });
+
+ mocks.project.widgetInstances.preview.state.values = { videoLoop: false };
+
+ try {
+ await render();
+
+ await expect.element(page.getByRole('button', { name: 'Loop' })).toHaveAttribute('aria-pressed', 'false');
+ expect(host?.querySelector('video')?.loop).toBe(false);
+ } finally {
+ mocks.project.widgetInstances.preview.state.values = {};
+ }
+ });
+
it('binds I to toggling the details panel through the preview widget value', async () => {
await render();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index c0ac46977a..5d1101df84 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -68,17 +68,7 @@ import {
useWorkbenchCommands,
useWorkbenchQueries,
} from '@workbench/WorkbenchContext';
-import {
- useCallback,
- useEffect,
- useEffectEvent,
- useMemo,
- useRef,
- useState,
- type KeyboardEvent,
- type ReactNode,
- type Ref,
-} from 'react';
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';
import { useTranslation } from 'react-i18next';
import type { PreviewLoupeControls } from './usePreviewLoupe';
@@ -101,6 +91,7 @@ import {
getPreviewComparisonMode,
getPreviewFilmstripVisible,
getPreviewMetadataOpen,
+ getPreviewVideoLoop,
type PreviewComparisonMode,
} from './previewSettings';
import { usePreviewNavigation } from './usePreviewNavigation';
@@ -182,17 +173,6 @@ const FLOATING_RAIL_SX: SystemStyleObject = {
zIndex: 3,
};
-/** A focused video seeks with the arrows; keep them from the workbench hotkeys, which would step to another item. */
-const keepVideoArrowKeys = (event: KeyboardEvent<HTMLElement>) => {
- if (
- (event.key === 'ArrowLeft' || event.key === 'ArrowRight') &&
- event.target instanceof Element &&
- event.target.closest('video')
- ) {
- event.stopPropagation();
- }
-};
-
export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const galleryValues = useWidgetValuesSelector('gallery', (values) => values);
const queueItems = useActiveProjectSelector((project) => project.queue.items);
@@ -383,6 +363,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[widgets]
);
const openVideoDetails = useCallback(() => widgets.patchValues('preview', { metadataOpen: true }), [widgets]);
+ const isVideoLooping = getPreviewVideoLoop(previewValues);
+ const setVideoLoop = useCallback((videoLoop: boolean) => widgets.patchValues('preview', { videoLoop }), [widgets]);
const handleVideoCopyAvailabilityChange = useCallback((itemKey: GalleryItemKey, isAvailable: boolean) => {
setCopyAvailableItemKey((current) => (isAvailable ? itemKey : current === itemKey ? null : current));
}, []);
@@ -660,7 +642,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
role="region"
tabIndex={0}
w="full"
- onKeyDown={keepVideoArrowKeys}
>
{shouldFollowLive && activeGalleryPlaceholder ? (
<LivePreview
@@ -700,8 +681,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
item={selectedItem}
swipe={swipeNavigation}
videoControllerRef={videoControllerRef}
+ videoLoop={isVideoLooping}
onContextMenu={openItemContextMenu}
onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}
+ onVideoLoopChange={setVideoLoop}
/>
)}
<ImageContextMenu
@@ -781,6 +764,7 @@ const SelectedVideoPreview = ({
const { t } = useTranslation();
const source = useMemo<PreviewMediaSource>(
() => ({
+ ...(item.fps === undefined ? {} : { fps: item.fps }),
itemKey: toGalleryItemKey(item),
kind: 'video',
label: t('widgets.preview.videoLabel', { name: item.name }),
@@ -815,6 +799,8 @@ interface SelectedMediaPreviewProps {
onContextMenu: (x: number, y: number) => void;
swipe?: PreviewSwipeNavigation;
videoControllerRef?: Ref<PreviewVideoFrameController>;
+ videoLoop?: boolean;
+ onVideoLoopChange?: (loop: boolean) => void;
}
/**
@@ -849,6 +835,8 @@ const SelectedMediaPreview = ({
swipe,
onContextMenu,
videoControllerRef,
+ videoLoop,
+ onVideoLoopChange,
}: SelectedMediaPreviewProps & {
dragItem?: GalleryItemRef;
frameHeight: number;
@@ -883,7 +871,9 @@ const SelectedMediaPreview = ({
swipe={swipe}
variant="framed"
videoControllerRef={videoControllerRef}
+ videoLoop={videoLoop}
onContextMenu={onContextMenu}
+ onVideoLoopChange={onVideoLoopChange}
/>
{swipe ? <PreviewNavButtons isVideo={item.kind === 'video'} navigation={swipe} /> : null}
</Flex>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts
index 13a80d8690..18597a9892 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts
@@ -12,3 +12,6 @@ export const getPreviewMetadataOpen = (values: Record<string, unknown>): boolean
export const getPreviewFilmstripVisible = (values: Record<string, unknown>): boolean =>
values.filmstripVisible !== false;
+
+/** Whether the Preview's videos loop: on until the viewer turns it off in the player. */
+export const getPreviewVideoLoop = (values: Record<string, unknown>): boolean => values.videoLoop !== false;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts
index f563eccaf5..01a7cbabaa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/spanPlaybackRequest.ts
@@ -1,7 +1,7 @@
import type { GalleryItemKey } from '@features/gallery';
/**
- * Publish ephemeral tokenized trim-loop intents after selecting media and raising Preview. Expire stale requests
+ * Publish ephemeral tokenized trim-playback intents after selecting media and raising Preview. Expire stale requests
* to prevent unexpected delayed audio; the player reports running state and stop control under the same token.
*/
@@ -65,8 +65,8 @@ export const subscribeVideoSpanPlaybackRequests = (listener: () => void): (() =>
};
/**
- * Report actual element playback for the current loop, null before use, after leaving its span, or while hidden.
- * Pausing keeps the loop armed for native resume.
+ * Report actual element playback for the current span, null before use, after leaving it, or while hidden.
+ * Pausing keeps the span armed for the player's resume.
*/
export interface VideoSpanPlaybackState {
isPlaying: boolean;
@@ -84,7 +84,7 @@ const notifyStateListeners = (): void => {
}
};
-/** The player's report. Replaces whatever stood before: one loop is on screen at a time. */
+/** The player's report. Replaces whatever stood before: one span is on screen at a time. */
export const publishVideoSpanPlaybackState = (state: VideoSpanPlaybackState): void => {
if (
currentState !== null &&
@@ -99,7 +99,7 @@ export const publishVideoSpanPlaybackState = (state: VideoSpanPlaybackState): vo
notifyStateListeners();
};
-/** Retires `token`'s state. A report from a newer loop is left alone. */
+/** Retires `token`'s state. A report from a newer span is left alone. */
export const clearVideoSpanPlaybackState = (token: number): void => {
if (currentState?.token !== token) {
return;
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index f5eeef298a..8dd89bbe24 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -76,6 +76,12 @@ const ROUTE_SHARED_MODULES = [
'/platform/ui/Slider.tsx',
'/platform/ui/SliderNumberField.tsx',
'/platform/ui/Tooltip.tsx',
+ // Eager menus and popovers and the lazily loaded video player share these controls and their overlay registry;
+ // alone they cost both routes a request.
+ '/platform/ui/Menu.tsx',
+ '/platform/ui/Popover.tsx',
+ '/platform/ui/widgetOverlayRegistry.ts',
+ '/platform/ui/widgetOverlays.ts',
'/platform/ui/RetryBoundary.tsx',
'/platform/ui/PanelHeader.tsx',
'/platform/ui/settings/contracts.ts',