An open source design system that's fully customizable and agent ready
TypeScript
fix: reset TransferListSelector drafts, Tour steps, and Lightbox zoom during render (#7351)
Cindy Zhang94bdc8e8b128
diff --git a/.changeset/lightbox-zoom-reset-same-frame.md b/.changeset/lightbox-zoom-reset-same-frame.mdnew file mode 100644index 0000000000..2f4b40480e--- /dev/null+++ b/.changeset/lightbox-zoom-reset-same-frame.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Lightbox shows the next or previous image unzoomed from its first frame. The zoom and pan reset when the image changes now happens in the same update, instead of painting the new image at the previous image's zoom for one frame.++@cixzhangdiff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsxindex 531c69c41b..e2d0cffcd4 100644--- a/packages/core/src/Lightbox/Lightbox.test.tsx+++ b/packages/core/src/Lightbox/Lightbox.test.tsx@@ -2,6 +2,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';+import {Profiler} from 'react';import {Lightbox} from './Lightbox';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {InternationalizationProvider} from '../i18n';@@ -676,3 +677,60 @@ describe('Lightbox', () => {});});});++describe('Lightbox zoom reset timing', () => {+ it('shows the next image unzoomed in the same commit that changes it', () => {+ const media = [+ {src: '/a.jpg', alt: 'Image A'},+ {src: '/b.jpg', alt: 'Image B'},+ ];+ const frames: string[] = [];+ const onRender = () =>+ frames.push(+ screen+ .queryByRole('button', {name: 'Zoom'})+ ?.getAttribute('aria-pressed') ?? '',+ );+ render(+ <Profiler id="lightbox" onRender={onRender}>+ <Lightbox isOpen={true} onOpenChange={() => {}} media={media} hasZoom />+ </Profiler>,+ );+ fireEvent.keyDown(screen.getByRole('button', {name: 'Zoom'}), {+ key: 'Enter',+ });+ expect(screen.getByRole('button', {name: 'Zoom'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );++ frames.length = 0;+ fireEvent.click(screen.getByRole('button', {name: /next/i}));++ expect(frames.length).toBeGreaterThan(0);+ expect(frames).not.toContain('true');+ expect(screen.getByRole('button', {name: 'Zoom'})).toHaveAttribute(+ 'aria-pressed',+ 'false',+ );+ });+});++describe('Lightbox with an unusable controlled index', () => {+ it('renders without looping when index is NaN', () => {+ expect(() =>+ render(+ <Lightbox+ isOpen={false}+ onOpenChange={() => {}}+ media={[+ {src: '/a.jpg', alt: 'Image A'},+ {src: '/b.jpg', alt: 'Image B'},+ ]}+ index={Number.NaN}+ onIndexChange={() => {}}+ />,+ ),+ ).not.toThrow();+ });+});diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex 07e86f37e4..e86444aad4 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -367,14 +367,20 @@ export function Lightbox({// Scroll lockuseScrollLock(isOpen);- // Reset zoom on image change- useEffect(() => {- // Reset image view state when the active media item changes.- // eslint-disable-next-line @eslint-react/set-state-in-effect+ // A new media item starts unzoomed. Adjusted during render, so the new item+ // never paints at the previous item's zoom and pan.+ const currentSrc = currentItem?.src;+ const [viewedItem, setViewedItem] = useState({index, src: currentSrc});+ // Object.is, matching the dependency comparison of the effect this replaces:+ // a controlled index of NaN must not re-render forever.+ if (+ !Object.is(viewedItem.index, index) ||+ !Object.is(viewedItem.src, currentSrc)+ ) {+ setViewedItem({index, src: currentSrc});setZoom(1);- // eslint-disable-next-line @eslint-react/set-state-in-effectsetPan({x: 0, y: 0});- }, [index, currentItem?.src]);+ }// Announce gallery navigation to screen readers. Moving between images only// updates the visual counter, which is silent to assistive tech, so mirrordiff --git a/packages/lab/src/Tour/Tour.test.tsx b/packages/lab/src/Tour/Tour.test.tsxindex a80ddd629f..df8d30f50c 100644--- a/packages/lab/src/Tour/Tour.test.tsx+++ b/packages/lab/src/Tour/Tour.test.tsx@@ -12,7 +12,7 @@import {describe, it, expect, vi, beforeAll} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';-import {useRef, useState} from 'react';+import {Profiler, useRef, useState} from 'react';import {Tour} from './Tour';import {TourStep} from './TourStep';import {useTour} from './useTour';@@ -259,3 +259,55 @@ describe('useTour', () => {expect(last.last).toBe(false);});});++describe('Tour reset timing', () => {+ function StepProbe() {+ const tour = useTour();+ return <output data-testid="step-index">{tour?.activeStepIndex}</output>;+ }++ function Harness({isActive}: {isActive: boolean}) {+ const aRef = useRef<HTMLButtonElement>(null);+ const bRef = useRef<HTMLButtonElement>(null);+ return (+ <>+ <button type="button" ref={aRef}>+ Target A+ </button>+ <button type="button" ref={bRef}>+ Target B+ </button>+ <Tour isActive={isActive} onDismiss={() => {}}>+ <StepProbe />+ <TourStep targetRef={aRef} heading="First">+ First body+ </TourStep>+ <TourStep targetRef={bRef} heading="Second">+ Second body+ </TourStep>+ </Tour>+ </>+ );+ }++ it('resets to the first step in the same commit that deactivates the tour', () => {+ const frames: string[] = [];+ const onRender = () =>+ frames.push(screen.getByTestId('step-index').textContent ?? '');+ const ui = (isActive: boolean) => (+ <Profiler id="tour" onRender={onRender}>+ <Harness isActive={isActive} />+ </Profiler>+ );+ const {rerender} = render(ui(true));+ fireEvent.click(screen.getByText('Next'));+ expect(screen.getByTestId('step-index')).toHaveTextContent('1');++ frames.length = 0;+ rerender(ui(false));++ expect(frames.length).toBeGreaterThan(0);+ expect(frames).not.toContain('1');+ expect(screen.getByTestId('step-index')).toHaveTextContent('0');+ });+});diff --git a/packages/lab/src/Tour/Tour.tsx b/packages/lab/src/Tour/Tour.tsxindex 22d94fb37e..bbb23367ad 100644--- a/packages/lab/src/Tour/Tour.tsx+++ b/packages/lab/src/Tour/Tour.tsx@@ -29,7 +29,7 @@* - /packages/lab/src/Tour/index.ts (exports if types change)*/-import {useCallback, useEffect, useMemo, useState, type ReactNode} from 'react';+import {useCallback, useMemo, useState, type ReactNode} from 'react';import {TourContext,type TourDismissSource,@@ -108,13 +108,16 @@ export function Tour({};}, []);- // Reset to the first step whenever the tour is (re)started, so a dismissed- // tour begins from the top next time isActive flips back on.- useEffect(() => {+ // Reset to the first step when the tour is deactivated, so a dismissed tour+ // begins from the top next time isActive flips back on. Adjusted during+ // render, so no commit carries the old step past deactivation.+ const [wasActive, setWasActive] = useState(isActive);+ if (!Object.is(wasActive, isActive)) {+ setWasActive(isActive);if (!isActive) {setActiveStepIndex(0);}- }, [isActive]);+ }const stepCount = stepIds.length;diff --git a/packages/lab/src/TransferList/TransferListSelector.test.tsx b/packages/lab/src/TransferList/TransferListSelector.test.tsxindex 04ed210ea0..986329a31d 100644--- a/packages/lab/src/TransferList/TransferListSelector.test.tsx+++ b/packages/lab/src/TransferList/TransferListSelector.test.tsx@@ -9,7 +9,7 @@* SYNC: When TransferListSelector.tsx behavior changes, update this test.*/-import {useState} from 'react';+import {Profiler, useState} from 'react';import {afterAll, beforeEach, describe, expect, it, vi} from 'vitest';import {fireEvent,@@ -603,3 +603,42 @@ describe('TransferListSelector', () => {);});});++describe('TransferListSelector draft reset timing', () => {+ it('replaces a staged draft in the same commit as an external value change', async () => {+ const user = userEvent.setup();+ const frames: boolean[] = [];+ const onRender = () =>+ frames.push(+ screen.queryByRole('button', {name: 'Remove Owner', ...hidden}) != null,+ );+ const ui = (value: string[]) => (+ <Profiler id="selector" onRender={onRender}>+ <TransferListSelector+ label="Visible fields"+ options={OPTIONS}+ value={value}+ onChange={() => {}}+ commitBehavior="staged"+ />+ </Profiler>+ );+ const view = render(ui(['name', 'status']));+ await openSelector();+ await user.click(+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),+ );+ expect(+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),+ ).toBeInTheDocument();++ frames.length = 0;+ view.rerender(ui(['name']));++ expect(frames.length).toBeGreaterThan(0);+ expect(frames).not.toContain(true);+ expect(+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),+ ).toBeInTheDocument();+ });+});diff --git a/packages/lab/src/TransferList/TransferListSelector.tsx b/packages/lab/src/TransferList/TransferListSelector.tsxindex 1c19d31ce5..4d5f3d94be 100644--- a/packages/lab/src/TransferList/TransferListSelector.tsx+++ b/packages/lab/src/TransferList/TransferListSelector.tsx@@ -217,27 +217,24 @@ export function TransferListSelector<T extends string = string>({const cancelLabel =cancelLabelFromProps ?? t('@astryx.transferListSelector.cancel');const [draftValue, setDraftValue] = useState<readonly T[]>(value);- const previousAppliedValueRef = useRef<readonly T[]>([...value]);- const previousCommitBehaviorRef = useRef(commitBehavior);const resetDraft = useCallback(() => {setDraftValue([...value]);}, [value]);- useEffect(() => {- const previousAppliedValue = previousAppliedValueRef.current;- previousAppliedValueRef.current = [...value];- if (!areOrderedValuesEqual(previousAppliedValue, value)) {- resetDraft();- }- }, [resetDraft, value]);-- useEffect(() => {- if (previousCommitBehaviorRef.current !== commitBehavior) {- resetDraft();- }- previousCommitBehaviorRef.current = commitBehavior;- }, [commitBehavior, resetDraft]);+ // A changed applied value or commit behavior discards the staged draft.+ // Adjusted during render, so no commit paints the discarded draft.+ const [draftSource, setDraftSource] = useState(() => ({+ value: [...value],+ commitBehavior,+ }));+ if (+ !areOrderedValuesEqual(draftSource.value, value) ||+ !Object.is(draftSource.commitBehavior, commitBehavior)+ ) {+ setDraftSource({value: [...value], commitBehavior});+ setDraftValue([...value]);+ }const resolvedWidth =typeof width === 'number'