From ec208960e892b57e28bb8a1ff34edab2a2e086b0 Mon Sep 17 00:00:00 2001 From: Anshuman Pandey <54475686+pandeymangg@users.noreply.github.com> Date: Fri, 30 May 2025 00:30:28 +0530 Subject: [PATCH] fix: surveys package resize observer issue (#5907) Co-authored-by: Matthias Nannt --- .../wrappers/stacked-cards-container.test.tsx | 1 + .../wrappers/stacked-cards-container.tsx | 20 +++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/surveys/src/components/wrappers/stacked-cards-container.test.tsx b/packages/surveys/src/components/wrappers/stacked-cards-container.test.tsx index c2be0f83b0..7e43a96bec 100644 --- a/packages/surveys/src/components/wrappers/stacked-cards-container.test.tsx +++ b/packages/surveys/src/components/wrappers/stacked-cards-container.test.tsx @@ -399,6 +399,7 @@ describe("StackedCardsContainer", () => { const resizeCallback = (global.ResizeObserver as any).mock.calls[0][0]; act(() => { resizeCallback([{ contentRect: { height: 500, width: 300 } }]); + vi.runAllTimers(); // Advance timers after resize callback to handle potential internal delays }); // Check that cardHeight and cardWidth are passed to StackedCard instances (e.g., next card) diff --git a/packages/surveys/src/components/wrappers/stacked-cards-container.tsx b/packages/surveys/src/components/wrappers/stacked-cards-container.tsx index c79c148a95..7639814f44 100644 --- a/packages/surveys/src/components/wrappers/stacked-cards-container.tsx +++ b/packages/surveys/src/components/wrappers/stacked-cards-container.tsx @@ -98,24 +98,36 @@ export function StackedCardsContainer({ // UseEffect to handle the resize of current question card and set cardHeight accordingly useEffect(() => { + let resizeTimeout: NodeJS.Timeout; + + const handleDebouncedResize = (entries: ResizeObserverEntry[]) => { + clearTimeout(resizeTimeout); + resizeTimeout = setTimeout(() => { + for (const entry of entries) { + setCardHeight(`${entry.contentRect.height.toString()}px`); + setCardWidth(entry.contentRect.width); + } + }, 50); // 50ms debounce + }; + const timer = setTimeout(() => { const currentElement = cardRefs.current[questionIdxTemp]; if (currentElement) { if (resizeObserver.current) { resizeObserver.current.disconnect(); } + resizeObserver.current = new ResizeObserver((entries) => { - for (const entry of entries) { - setCardHeight(`${entry.contentRect.height.toString()}px`); - setCardWidth(entry.contentRect.width); - } + handleDebouncedResize(entries); }); resizeObserver.current.observe(currentElement); } }, 0); + return () => { resizeObserver.current?.disconnect(); clearTimeout(timer); + clearTimeout(resizeTimeout); }; }, [questionIdxTemp, cardArrangement, cardRefs]);