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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): preserve horizontal scroll offset too
joshistoast8b9801f388a4
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 14d4102da0..39a1bd7ac6 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -666,18 +666,27 @@ const runKeepAliveStateJourney = async (browser) => {const id = 'workbench-keep-alive-state';/**- * Every scroll offset in the panel, in DOM order. Restricted to real scroll- * containers — an overflow-clipped label is technically taller than its box- * and would otherwise wander into the comparison as noise.+ * Every scroll offset in the panel, in DOM order, on both axes. Restricted+ * to real scroll containers — an overflow-clipped label is technically+ * taller than its box and would otherwise wander into the comparison as+ * noise. Both `overflowX` and `overflowY` are checked: `Scrollable`+ * installs `usePreservedScrollOffset` regardless of its own `orientation`+ * prop, and a horizontal-only strip like the preview filmstrip would+ * otherwise never be exercised here.*/const SCROLLER_QUERY = `(element) => [...element.querySelectorAll('*')].filter((node) => {- const overflowY = getComputedStyle(node).overflowY;- return (overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight + 40;+ const style = getComputedStyle(node);+ const scrollsY = (style.overflowY === 'auto' || style.overflowY === 'scroll') && node.scrollHeight > node.clientHeight + 40;+ const scrollsX = (style.overflowX === 'auto' || style.overflowX === 'scroll') && node.scrollWidth > node.clientWidth + 40;+ return scrollsY || scrollsX;})`;const readScrollOffsets = (panel) =>panel.evaluate(- new Function('element', `return (${SCROLLER_QUERY})(element).map((node) => Math.round(node.scrollTop));`)+ new Function(+ 'element',+ `return (${SCROLLER_QUERY})(element).map((node) => ({ left: Math.round(node.scrollLeft), top: Math.round(node.scrollTop) }));`+ ));const scrollAll = (panel, offset) =>@@ -686,8 +695,11 @@ const runKeepAliveStateJourney = async (browser) => {'element','target',`const scrollers = (${SCROLLER_QUERY})(element);- for (const scroller of scrollers) { scroller.scrollTop = target; }- return scrollers.map((scroller) => Math.round(scroller.scrollTop));`+ for (const scroller of scrollers) {+ scroller.scrollTop = target;+ scroller.scrollLeft = target;+ }+ return scrollers.map((scroller) => ({ left: Math.round(scroller.scrollLeft), top: Math.round(scroller.scrollTop) }));`),offset);@@ -700,13 +712,55 @@ const runKeepAliveStateJourney = async (browser) => {const galleryItems = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });await galleryItems.waitFor();+ // The preview filmstrip only renders once an item is selected — with+ // nothing selected the centre view is a "No gallery selection" empty+ // state, filmstrip included.+ await galleryItems+ .getByRole('button', { name: /for preview$/ })+ .first()+ .click();+const leftPanel = page.getByRole('complementary', { exact: true, name: 'left widget panel' });const scrolledLeftOffsets = await scrollAll(leftPanel, 400);const scrolledOffsets = await scrollAll(rightPanel, 600);assert.ok(- scrolledOffsets.length >= 2 && scrolledOffsets.every((offset) => offset > 0),+ scrolledOffsets.length >= 2 && scrolledOffsets.every(({ left, top }) => top > 0 || left > 0),`The representative gallery must have scrollable boards and items; got ${JSON.stringify(scrolledOffsets)}.`);++ // The preview filmstrip is a horizontal-only `Scrollable` living in the+ // centre region, not either side panel. `usePreservedScrollOffset` is+ // installed unconditionally inside `Scrollable` regardless of its+ // `orientation`, so this is the one axis the panel assertions above never+ // exercise. The filmstrip's items come from the widget's own board-scoped+ // fetch, a separate round trip from the gallery panel's list, so it is+ // not necessarily painted yet the instant the panel assertions above are —+ // waiting for the overflow condition itself, rather than a fixed delay,+ // is what actually pins that race rather than papering over it.+ const centerPanel = centerRegion(page);+ await page.waitForFunction(+ () => {+ const region = [...document.querySelectorAll('[role="region"]')].find(+ (node) => node.getAttribute('aria-label') === 'Center view'+ );++ return region+ ? [...region.querySelectorAll('*')].some((node) => {+ const style = getComputedStyle(node);+ return (+ (style.overflowX === 'auto' || style.overflowX === 'scroll') && node.scrollWidth > node.clientWidth + 40+ );+ })+ : false;+ },+ undefined,+ { timeout: 10_000 }+ );+ const scrolledCenterOffsets = await scrollAll(centerPanel, 300);+ assert.ok(+ scrolledCenterOffsets.some(({ left }) => left > 0),+ `The representative preview filmstrip must scroll horizontally; got ${JSON.stringify(scrolledCenterOffsets)}.`+ );await waitForSettledDocument(page);await selectLayoutPreset(page, 'Edit', 'Canvas');@@ -743,6 +797,11 @@ const runKeepAliveStateJourney = async (browser) => {scrolledLeftOffsets,'Returning to a layout must keep a panel body scrolled where the user left it.');+ assert.deepEqual(+ await readScrollOffsets(centerPanel),+ scrolledCenterOffsets,+ 'Returning to a layout must keep the preview filmstrip scrolled where the user left it.'+ );if (pageErrors.length > 0) {throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);diff --git a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsxindex 60cd5a2015..d1efddcc7d 100644--- a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.browser.test.tsx@@ -9,12 +9,24 @@ import { usePreservedScrollOffset } from './usePreservedScrollOffset';const VIEWPORT_STYLE = { height: '100px', overflow: 'auto', width: '100px' } as const;/**- * Stands in for a virtualized list: the scrollable content is sized from a- * measurement, so it does not survive the container being taken out of layout.- * That is what defeats the browser's own scroll restoration, and a container- * with fixed content would not reproduce the bug at all.+ * Stands in for a plain, non-virtualized list — the gallery's board list is+ * the real reproduction case — whose content is sized from actual DOM layout+ * rather than from a row count, so it does not survive the container being+ * taken out of layout unchanged. That is what defeats the browser's own+ * scroll restoration, and a container with fixed content would not reproduce+ * the bug at all. A virtualized list does not have this problem: its content+ * height is a pure function of row count and estimated sizes, so it survives+ * unaided and needs no help from this hook.*/-const Scroller = ({ contentHeight, isPreserved }: { contentHeight: number; isPreserved: boolean }) => {+const Scroller = ({+ contentHeight,+ contentWidth = 0,+ isPreserved,+}: {+ contentHeight: number;+ contentWidth?: number;+ isPreserved: boolean;+}) => {const preservedRef = useRef<HTMLDivElement>(null);const plainRef = useRef<HTMLDivElement>(null);@@ -22,7 +34,7 @@ const Scroller = ({ contentHeight, isPreserved }: { contentHeight: number; isPrereturn (<div ref={isPreserved ? preservedRef : undefined} data-testid="scroller" style={VIEWPORT_STYLE}>- <div style={{ height: `${String(contentHeight)}px` }} />+ <div style={{ height: `${String(contentHeight)}px`, width: `${String(contentWidth)}px` }} /></div>);};@@ -30,11 +42,11 @@ const Scroller = ({ contentHeight, isPreserved }: { contentHeight: number; isPrelet host: HTMLDivElement | null = null;let root: Root | null = null;-const render = async (mode: 'hidden' | 'visible', contentHeight: number, isPreserved: boolean) => {+const render = async (mode: 'hidden' | 'visible', contentHeight: number, isPreserved: boolean, contentWidth = 0) => {await act(async () => {root?.render(<Activity mode={mode}>- <Scroller contentHeight={contentHeight} isPreserved={isPreserved} />+ <Scroller contentHeight={contentHeight} contentWidth={contentWidth} isPreserved={isPreserved} /></Activity>);await new Promise((resolve) => {@@ -65,10 +77,23 @@ const scrollTo = async (offset: number) => {});};+/** Scrolls both axes and lets the real scroll event land. */+const scrollToBothAxes = async (top: number, left: number) => {+ const element = scroller();++ await act(async () => {+ element.scrollTop = top;+ element.scrollLeft = left;+ await new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });+ });+};+/** Hides the container, collapses its measured content, then shows it again. */-const hideAndShow = async (isPreserved: boolean) => {- await render('hidden', 0, isPreserved);- await render('visible', 2000, isPreserved);+const hideAndShow = async (isPreserved: boolean, contentWidth = 0) => {+ await render('hidden', 0, isPreserved, 0);+ await render('visible', 2000, isPreserved, contentWidth);};const mount = () => {@@ -103,11 +128,26 @@ describe('preserved scroll offset', () => {// Chrome restores this much on its own when the scrollable content happens// to survive, so this pins the contract rather than reproducing the bug —// the real reproduction is the `workbench-keep-alive-state` journey, which- // runs the actual virtualized gallery.+ // runs the gallery's actual non-virtualized board list.expect(scroller()).toBe(element);expect(element.scrollTop).toBe(500);});+ it('keeps both axes across a keep-alive hide and show', async () => {+ // `Scrollable` installs this hook unconditionally regardless of its own+ // `orientation` prop, and `PreviewFilmstrip` is a horizontal `Scrollable`+ // inside the keep-alive-able Preview widget — a vertical-only fix would+ // leave that filmstrip snapping back to its start on every preset switch.+ mount();+ await render('visible', 2000, true, 2000);+ await scrollToBothAxes(500, 300);++ await hideAndShow(true, 2000);++ expect(scroller().scrollTop).toBe(500);+ expect(scroller().scrollLeft).toBe(300);+ });+it('does not carry an offset into a genuinely new instance', async () => {mount();await render('visible', 2000, true);diff --git a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.tsindex a5fbf71bf7..4aaea55096 100644--- a/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts+++ b/invokeai/frontend/webv2/src/platform/react/usePreservedScrollOffset.ts@@ -7,9 +7,12 @@ import { useLayoutEffect, useRef, type RefObject } from 'react';* `display: none`, which takes the element out of layout entirely: it has no* scrollable overflow, its `scrollTop` reads 0, and the browser's own scroll* restoration only survives if the scrollable content happens to be unchanged- * when it comes back. A virtualized list sizes its content from a measured- * viewport, so its content is not unchanged, and the offset is simply lost —- * the list returns pinned to the top with no scroll event ever having fired.+ * when it comes back. A plain, non-virtualized list — the gallery's board+ * list is the real reproduction case — has its content sized from actual DOM+ * layout, which is not guaranteed to come back identical, and the offset is+ * simply lost. A virtualized list is not the problem: its content height is a+ * pure function of row count and estimated sizes rather than of being laid+ * out at all, so it survives the round trip unaided and needs no help here.** The offset is tracked as the user scrolls rather than read back at teardown,* because by the time a hidden subtree's effects are cleaned up the element is@@ -23,7 +26,7 @@ import { useLayoutEffect, useRef, type RefObject } from 'react';* remembered offset with it, exactly as before.*/export const usePreservedScrollOffset = (ref: RefObject<HTMLElement | null>): void => {- const offsetRef = useRef(0);+ const offsetRef = useRef({ left: 0, top: 0 });useLayoutEffect(() => {const element = ref.current;@@ -32,12 +35,16 @@ export const usePreservedScrollOffset = (ref: RefObject<HTMLElement | null>): voreturn;}- if (offsetRef.current > 0) {- element.scrollTop = offsetRef.current;+ if (offsetRef.current.top > 0) {+ element.scrollTop = offsetRef.current.top;+ }++ if (offsetRef.current.left > 0) {+ element.scrollLeft = offsetRef.current.left;}const recordOffset = () => {- offsetRef.current = element.scrollTop;+ offsetRef.current = { left: element.scrollLeft, top: element.scrollTop };};element.addEventListener('scroll', recordOffset, { passive: true });