Skip to content

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

fix(webv2): keep keyboard focus when reordering video references

Lincoln Steinb85d42295ec4
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index 53ac4f20a8..98894640da 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -32,7 +32,7 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { Select } from '@platform/ui/Select';
import { SliderNumberField } from '@platform/ui/SliderNumberField';
import { ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, FilmIcon, ImagePlusIcon, UploadIcon, XIcon } from 'lucide-react';
-import { memo, useCallback, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TrimBoundThumb } from './TrimBoundThumb';
@@ -94,6 +94,8 @@ const ReferenceCard = memo(function ReferenceCard({
reference: VideoReferenceItem;
}) {
const { t } = useTranslation();
+ const moveUpRef = useRef<HTMLButtonElement>(null);
+ const moveDownRef = useRef<HTMLButtonElement>(null);
const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;
const selectValue = useMemo(
() => [reference.kind === 'video' ? reference.conditioning : reference.detail],
@@ -149,8 +151,52 @@ const ReferenceCard = memo(function ReferenceCard({
reference.kind === 'video' && Number.isFinite(reference.clip.fps) && reference.clip.fps > 0
? (sampleFrames / reference.clip.fps).toFixed(1)
: null;
- const handleMoveUp = useCallback(() => onMove(index, -1), [index, onMove]);
- const handleMoveDown = useCallback(() => onMove(index, 1), [index, onMove]);
+ // A move that lands on an end -- the top of the stack, or the slot above the
+ // pinned continuity anchor -- disables the very button that was just pressed,
+ // and a disabled element cannot hold focus, so a keyboard user is dropped to
+ // <body> mid-gesture. Which button that is depends on the anchor rule, so the
+ // handoff reacts to what actually came back disabled rather than predicting
+ // it. It is armed only when the arrow ALREADY holds focus, because pressing a
+ // button does not focus it in every browser (Safari, Firefox on macOS): a
+ // pointer press there runs this handler with the caret still in the prompt,
+ // and moving focus would haul the user out of what they were typing.
+ const pendingFocusRef = useRef<'down' | 'up' | null>(null);
+ const handleMoveUp = useCallback(() => {
+ const arrow = moveUpRef.current;
+
+ pendingFocusRef.current = arrow !== null && document.activeElement === arrow ? 'up' : null;
+ onMove(index, -1);
+ }, [index, onMove]);
+ const handleMoveDown = useCallback(() => {
+ const arrow = moveDownRef.current;
+
+ pendingFocusRef.current = arrow !== null && document.activeElement === arrow ? 'down' : null;
+ onMove(index, 1);
+ }, [index, onMove]);
+
+ useLayoutEffect(() => {
+ const pending = pendingFocusRef.current;
+
+ if (pending === null) {
+ return;
+ }
+ pendingFocusRef.current = null;
+
+ const pressed = pending === 'up' ? moveUpRef.current : moveDownRef.current;
+ const sibling = pending === 'up' ? moveDownRef.current : moveUpRef.current;
+ // Hand off only the focus this card is responsible for losing. Disabling a
+ // focused button blurs it to <body>, so that -- or focus still sitting on
+ // the arrow -- is the whole set of states worth repairing. Anywhere else and
+ // the user has moved on since, which happens whenever the write did not land
+ // in this commit: `setReferences` drops writes from a panel that is no
+ // longer live, and `memo` then keeps this card from rendering at all, so the
+ // arm survives to a later render that has nothing to do with the gesture.
+ const isOursToRestore = document.activeElement === document.body || document.activeElement === pressed;
+
+ if (isOursToRestore && pressed?.disabled === true && sibling !== null && !sibling.disabled) {
+ sibling.focus();
+ }
+ });
const handleRemove = useCallback(() => onRemove(index), [index, onRemove]);
return (
@@ -246,6 +292,7 @@ const ReferenceCard = memo(function ReferenceCard({
</Stack>
<Stack gap="0">
<IconButton
+ ref={moveUpRef}
aria-label={t('widgets.video.moveReferenceUp')}
disabled={disabled || !canMoveUp}
size="2xs"
@@ -255,6 +302,7 @@ const ReferenceCard = memo(function ReferenceCard({
<ArrowUpIcon size={12} />
</IconButton>
<IconButton
+ ref={moveDownRef}
aria-label={t('widgets.video.moveReferenceDown')}
disabled={disabled || !canMoveDown}
size="2xs"
@@ -578,6 +626,35 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
},
[onChange]
);
+ // Identity for the list, and it must NOT contain the index: an index-bearing key
+ // changes for every card a reorder touches, so React unmounts and remounts them --
+ // reloading a video reference's seeking trim thumbnails and throwing away keyboard
+ // focus on the arrow just pressed. Media can legitimately appear twice (the same
+ // clip sampled over two different windows), so a bare name is not unique either; it
+ // is disambiguated by how many entries of the same kind and name precede it.
+ //
+ // That makes a card stable against every move EXCEPT a swap with its own twin,
+ // where the two occurrence numbers trade places and React swaps the props between
+ // the instances instead of moving one. Rendering stays correct; the cards simply do
+ // not travel. Giving twins independent identity needs a per-entry uid minted on add
+ // and carried through normalization, which the persisted reference shape has no
+ // room for today.
+ const referenceKeys = useMemo(() => {
+ const seen = new Map<string, number>();
+
+ return references.map((reference) => {
+ const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;
+ // Kind is part of the identity, matching `toGalleryItemKey`: an image and a
+ // video are different references even where a backend gives them one name.
+ const identity = `${reference.kind}:${name}`;
+ const occurrence = seen.get(identity) ?? 0;
+
+ seen.set(identity, occurrence + 1);
+
+ return `${identity}-${occurrence}`;
+ });
+ }, [references]);
+
const moveReference = useCallback(
(index: number, direction: -1 | 1) => {
onChange((current) => {
@@ -604,7 +681,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
<Stack gap="2">
{references.map((reference, index) => (
<ReferenceCard
- key={`${reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name}-${index}`}
+ key={referenceKeys[index]}
collections={collections}
disabled={isInert}
index={index}
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx
new file mode 100644
index 0000000000..307d7dd0f1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceReorderFocus.browser.test.tsx
@@ -0,0 +1,256 @@
+import type { VideoReferenceItem } from '@features/video/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act, useCallback, useMemo, useState } 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 { VideoReferenceListField } from './VideoReferenceListField';
+import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';
+
+/**
+ * Reordering the Ref2VA reference stack must not cost the user their place on
+ * the keyboard. Two ways it used to: the list was keyed by index, so every move
+ * remounted the cards it touched and the pressed arrow's DOM node was destroyed
+ * outright; and a move that lands on an end disables that arrow, which cannot
+ * then hold focus.
+ */
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ gallery: { picker: { dropHint: 'Drop', upload: 'Upload' } },
+ video: {
+ addReference: 'Add reference',
+ chooseReference: 'Choose from Gallery',
+ dropReference: 'Drop Reference',
+ moveReferenceDown: 'Move reference down',
+ moveReferenceUp: 'Move reference up',
+ referenceDetailMatch: 'Match generation size',
+ referenceDetailMax: 'Max detail',
+ referencesHelp: 'help',
+ removeReference: 'Remove reference',
+ uploadImageReference: 'Upload image',
+ uploadVideoReference: 'Upload video',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement;
+let root: Root;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const adapter = {
+ getUploadBoardId: () => 'none',
+ patchValues: vi.fn(),
+ reportError: vi.fn(),
+ touchGalleryImages: vi.fn(),
+} as unknown as VideoUiAdapter;
+
+const imageReference = (name: string): VideoReferenceItem => ({
+ detail: 'match',
+ image: { height: 512, image_name: name, width: 512 },
+ kind: 'image',
+});
+
+const Harness = ({ names }: { names: string[] }) => {
+ const [references, setReferences] = useState(() => names.map(imageReference));
+ const handleChange = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {
+ setReferences((current) => update(current));
+ }, []);
+
+ return (
+ <>
+ <input aria-label="Prompt" />
+ <VideoReferenceListField maxImages={9} maxVideos={3} references={references} onChange={handleChange} />
+ </>
+ );
+};
+
+/** Mirrors a panel whose write is dropped: the arrows fire, the list never changes. */
+const InertHarness = () => {
+ const [, forceRender] = useState(0);
+ const references = useMemo(() => ['a.png', 'b.png', 'c.png'].map(imageReference), []);
+ const handleChange = useCallback(() => forceRender((tick) => tick + 1), []);
+
+ return <VideoReferenceListField maxImages={9} maxVideos={3} references={references} onChange={handleChange} />;
+};
+
+const render = async (names: string[]) => {
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>
+ <Harness names={names} />
+ </VideoUiProvider>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+const buttons = (label: string): HTMLButtonElement[] =>
+ [...document.querySelectorAll(`button[aria-label="${label}"]`)] as HTMLButtonElement[];
+
+/** The thumbnails ARE the rendered order. */
+const order = (): string[] => [...document.querySelectorAll('img')].map((image) => image.src.split('/').at(-2) ?? '');
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('video reference reorder focus', () => {
+ it('keeps focus on the pressed arrow through an ordinary move', async () => {
+ await render(['a.png', 'b.png', 'c.png']);
+ expect(order()).toEqual(['a.png', 'b.png', 'c.png']);
+
+ const up = buttons('Move reference up')[2];
+
+ await act(() => up?.focus());
+ await act(() => up?.click());
+
+ expect(order()).toEqual(['a.png', 'c.png', 'b.png']);
+
+ // Same element still focused: the card survived the reorder rather than
+ // being remounted underneath the user.
+ expect(document.activeElement).toBe(up);
+ expect(buttons('Move reference up')[1]).toBe(up);
+ });
+
+ it('hands focus to the sibling arrow when the move lands on an end', async () => {
+ await render(['a.png', 'b.png', 'c.png']);
+
+ const up = buttons('Move reference up')[1];
+
+ await act(() => up?.focus());
+ await act(() => up?.click());
+
+ expect(order()).toEqual(['b.png', 'a.png', 'c.png']);
+ expect(up?.disabled).toBe(true);
+ expect(document.activeElement).toBe(buttons('Move reference down')[0]);
+ expect((document.activeElement as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it('leaves focus alone when the arrow was pressed without holding focus', async () => {
+ // Pressing a button does not focus it in every browser, so the handler can
+ // run with the caret still in the prompt. Handing focus to an arrow then
+ // would haul the user out of what they were typing.
+ await render(['a.png', 'b.png', 'c.png']);
+
+ const field = document.querySelector('[aria-label="Prompt"]') as HTMLInputElement;
+ const up = buttons('Move reference up')[1];
+
+ await act(() => field.focus());
+ await act(() => up?.click());
+
+ expect(order()).toEqual(['b.png', 'a.png', 'c.png']);
+ expect(document.activeElement).toBe(field);
+ });
+
+ it('never fires a stale handoff after a dropped write', async () => {
+ // The reviewer's path: the write is dropped, `memo` keeps the card from
+ // rendering, so the arm survives. Much later an unrelated change disables
+ // that same arrow -- and the stale arm must not haul focus out of whatever
+ // the user is doing by then.
+ let drop = true;
+ let mutate: (next: string[]) => void = () => undefined;
+
+ const StaleHarness = () => {
+ const [names, setNames] = useState(['a.png', 'b.png', 'c.png']);
+
+ mutate = setNames;
+
+ const references = useMemo(() => names.map(imageReference), [names]);
+ const handleChange = useCallback((update: (current: VideoReferenceItem[]) => VideoReferenceItem[]) => {
+ if (drop) {
+ return;
+ }
+ setNames((current) =>
+ update(current.map(imageReference)).map((reference) =>
+ reference.kind === 'image' ? reference.image.image_name : ''
+ )
+ );
+ }, []);
+
+ return (
+ <>
+ <input aria-label="Prompt" />
+ <VideoReferenceListField maxImages={9} maxVideos={3} references={references} onChange={handleChange} />
+ </>
+ );
+ };
+
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>
+ <StaleHarness />
+ </VideoUiProvider>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+
+ const up = buttons('Move reference up')[1];
+
+ await act(() => up?.focus());
+ await act(() => up?.click());
+
+ // Dropped: nothing moved, and the arm is still sitting on the card.
+ expect(order()).toEqual(['a.png', 'b.png', 'c.png']);
+
+ const field = document.querySelector('[aria-label="Prompt"]') as HTMLInputElement;
+
+ await act(() => field.focus());
+
+ // Now remove the first reference, which shifts this card to the top and
+ // disables the arrow it armed.
+ drop = false;
+ await act(() => mutate(['b.png', 'c.png']));
+
+ expect(order()).toEqual(['b.png', 'c.png']);
+ expect(buttons('Move reference up')[0]?.disabled).toBe(true);
+ expect(document.activeElement).toBe(field);
+ });
+
+ it('keeps focus when a card moves PAST a duplicate of another reference', async () => {
+ // The same clip can legitimately appear twice, sampled over two different
+ // windows, so the key disambiguates by occurrence. Moving `tail` down past
+ // the second `dup` re-numbers nothing under that scheme; a name+index key
+ // would have shifted `tail` from 1 to 2 and remounted it.
+ await render(['dup.png', 'tail.png', 'dup.png', 'end.png']);
+
+ const down = buttons('Move reference down')[1];
+
+ await act(() => down?.focus());
+ await act(() => down?.click());
+
+ expect(order()).toEqual(['dup.png', 'dup.png', 'tail.png', 'end.png']);
+ expect(document.activeElement).toBe(down);
+ expect(buttons('Move reference down')[2]).toBe(down);
+ });
+});