diff --git a/src/hooks/useNextFrame.ts b/src/hooks/useNextFrame.ts index 5125f19..0dc7210 100644 --- a/src/hooks/useNextFrame.ts +++ b/src/hooks/useNextFrame.ts @@ -9,6 +9,9 @@ export default (): [ function cancelNextFrame() { raf.cancel(nextFrameRef.current); + // A frame may already be waiting for an asynchronous prepare callback. + // Invalidate it as well, so resolving after cleanup cannot advance the queue. + nextFrameRef.current = null; } function nextFrame( diff --git a/src/hooks/useStatus.ts b/src/hooks/useStatus.ts index aad729d..32b129b 100644 --- a/src/hooks/useStatus.ts +++ b/src/hooks/useStatus.ts @@ -63,6 +63,7 @@ export default function useStatus( const currentStatus = getStatus(); + // This tracks the component instance, not whether its effects are connected. const mountedRef = useRef(false); const deadlineRef = useRef(null); @@ -201,16 +202,21 @@ export default function useStatus( // ============================ Status ============================ const visibleRef = useRef(null); + const pendingVisibleChangeRef = useRef(false); // Update with new status useIsomorphicLayoutEffect(() => { - // When use Suspense, the `visible` will repeat trigger, - // But not real change of the `visible`, we need to skip it. - // https://github.com/ant-design/ant-design/issues/44379 + // Activity and Suspense reconnect effects without creating a new instance. + // Keep settled content intact. Restart interrupted motion on the same node + // so its frame queue, end listeners and deadline can be connected again. if (mountedRef.current && visibleRef.current === visible) { + if (getStatus() !== STATUS_NONE) { + startStep(); + } return; } + pendingVisibleChangeRef.current = true; setAsyncVisible(visible); const isMounted = mountedRef.current; @@ -271,7 +277,6 @@ export default function useStatus( useEffect( () => () => { - mountedRef.current = false; clearTimeout(deadlineRef.current); }, [], @@ -285,14 +290,23 @@ export default function useStatus( firstMountChangeRef.current = true; } - if (asyncVisible !== undefined && currentStatus === STATUS_NONE) { + // Consume each visibility transition once. Activity can reconnect this effect + // without a new transition. Read the live status to avoid notifying an old + // render when a layout effect has already started the next motion. + if ( + pendingVisibleChangeRef.current && + asyncVisible !== undefined && + asyncVisible === visibleRef.current && + getStatus() === STATUS_NONE + ) { + pendingVisibleChangeRef.current = false; // Skip first render is invisible since it's nothing changed if (firstMountChangeRef.current || asyncVisible) { onVisibleChanged?.(asyncVisible); } firstMountChangeRef.current = true; } - }, [asyncVisible, currentStatus]); + }, [asyncVisible, currentStatus, getStatus, onVisibleChanged]); // ============================ Styles ============================ let mergedStyle = style[0]; @@ -318,8 +332,8 @@ export default function useStatus( motionAppear ? 'NONE' : // Enter or Leave check - step === STEP_START || step === STEP_ACTIVE - ? styleStep === step - : true, + step === STEP_START || step === STEP_ACTIVE + ? styleStep === step + : true, ]; } diff --git a/src/hooks/useStepQueue.ts b/src/hooks/useStepQueue.ts index 5b3fefd..f30b2c5 100644 --- a/src/hooks/useStepQueue.ts +++ b/src/hooks/useStepQueue.ts @@ -1,4 +1,3 @@ -import { useState } from '@rc-component/util'; import * as React from 'react'; import type { MotionStatus, StepStatus } from '../interface'; import { @@ -37,12 +36,14 @@ export default ( step: StepStatus, ) => Promise | void | typeof SkipStep | typeof DoStep, ): [() => void, StepStatus] => { - const [step, setStep] = useState(STEP_NONE); + const [step, setStep] = React.useState(STEP_NONE); const [nextFrame, cancelNextFrame] = useNextFrame(); function startQueue() { - setStep(STEP_PREPARE, true); + // Effect reconnection runs layout effects before passive effects. A passive + // "destroyed" flag would discard this restart even though the instance lives. + setStep(STEP_PREPARE); } const STEP_QUEUE = prepareOnly ? SIMPLE_STEP_QUEUE : FULL_STEP_QUEUE; @@ -56,7 +57,7 @@ export default ( if (result === SkipStep) { // Skip when no needed - setStep(nextStep, true); + setStep(nextStep); } else if (nextStep) { // Do as frame for step update nextFrame(info => { @@ -64,7 +65,7 @@ export default ( // Skip since current queue is ood if (info.isCanceled()) return; - setStep(nextStep, true); + setStep(nextStep); } if (result === true) { diff --git a/tests/Activity.spec.tsx b/tests/Activity.spec.tsx new file mode 100644 index 0000000..e83539b --- /dev/null +++ b/tests/Activity.spec.tsx @@ -0,0 +1,357 @@ +import { act, fireEvent, render } from '@testing-library/react'; +import React from 'react'; +import { genCSSMotion, type CSSMotionProps } from '../src/CSSMotion'; + +const CSSMotion = genCSSMotion({ transitionSupport: true }); + +function Demo({ + mode = 'visible', + strict = false, + ...props +}: CSSMotionProps & { mode?: 'visible' | 'hidden'; strict?: boolean }) { + const content = ( + + + {({ className, style }, ref) => ( +
+ +
+ )} +
+
+ ); + return strict ? {content} : content; +} + +function advance() { + act(() => jest.runAllTimers()); +} + +function finish(panel: HTMLElement) { + advance(); + fireEvent.transitionEnd(panel); + advance(); +} + +describe.each([false, true])('Activity (StrictMode=%s)', strict => { + beforeEach(() => jest.useFakeTimers()); + afterEach(() => { + jest.clearAllTimers(); + jest.useRealTimers(); + }); + + it.each([true, false])( + 'notifies once per completed visibility change (motion=%s)', + motion => { + const onVisibleChanged = jest.fn(); + const props = { + strict, + onVisibleChanged, + motionName: motion ? 'test' : undefined, + }; + const { getByTestId, rerender } = render(); + finish(getByTestId('panel')); + expect(onVisibleChanged.mock.calls).toEqual([[true]]); + + for (const visible of [true, false, true]) { + rerender(); + if (motion && visible === false) finish(getByTestId('panel')); + else if (visible) finish(getByTestId('panel')); + const calls = [...onVisibleChanged.mock.calls]; + for (let index = 0; index < 2; index += 1) { + rerender(); + advance(); + rerender(); + advance(); + expect(onVisibleChanged.mock.calls).toEqual(calls); + } + } + expect(onVisibleChanged.mock.calls).toEqual([[true], [false], [true]]); + }, + ); + + it('uses the latest callback without replaying a completed notification', () => { + const firstCallback = jest.fn(); + const latestCallback = jest.fn(); + const replacementCallback = jest.fn(); + const { getByTestId, rerender } = render( + , + ); + const panel = getByTestId('panel'); + advance(); + rerender(); + finish(panel); + expect(firstCallback).not.toHaveBeenCalled(); + expect(latestCallback.mock.calls).toEqual([[true]]); + + rerender(); + rerender( + , + ); + rerender(); + advance(); + expect(replacementCallback).not.toHaveBeenCalled(); + + rerender( + , + ); + finish(panel); + expect(replacementCallback.mock.calls).toEqual([[false]]); + }); + + it('keeps an initially closed instance silent across restores', () => { + const onVisibleChanged = jest.fn(); + const props = { strict, onVisibleChanged, visible: false }; + const { rerender } = render(); + rerender(); + rerender(); + advance(); + expect(onVisibleChanged).not.toHaveBeenCalled(); + }); + + it('notifies a completed enter after an interrupted leave even with the same last notified value', () => { + const onVisibleChanged = jest.fn(); + const props = { strict, onVisibleChanged }; + const { getByTestId, rerender } = render(); + const panel = getByTestId('panel'); + finish(panel); + rerender(); + advance(); + rerender(); + advance(); + rerender(); + rerender(); + finish(panel); + expect(onVisibleChanged.mock.calls).toEqual([[true], [true]]); + }); + + it('preserves the settled panel and input across repeated restores', () => { + const onAppearStart = jest.fn(); + const props = { strict, onAppearStart }; + const { getByTestId, rerender } = render(); + const panel = getByTestId('panel'); + finish(panel); + const input = panel.querySelector('input'); + fireEvent.change(input, { target: { value: 'edited' } }); + onAppearStart.mockClear(); + + for (let index = 0; index < 3; index += 1) { + rerender(); + advance(); + rerender(); + advance(); + expect(getByTestId('panel')).toBe(panel); + expect(panel.querySelector('input')).toBe(input); + expect(input.value).toBe('edited'); + expect(panel).not.toHaveClass('test-appear'); + } + expect(onAppearStart).not.toHaveBeenCalled(); + }); + + it.each([ + ['appear', 'start'], + ['appear', 'active'], + ['enter', 'start'], + ['enter', 'active'], + ['leave', 'start'], + ['leave', 'active'], + ] as const)( + 'finishes interrupted %s at %s and preserves the panel until leave completes', + (motion, phase) => { + const onVisibleChanged = jest.fn(); + const props = { strict, onVisibleChanged }; + const { getByTestId, queryByTestId, rerender } = render( + , + ); + if (motion === 'leave') finish(getByTestId('panel')); + const visible = motion !== 'leave'; + rerender(); + if (phase === 'active') advance(); + const panel = getByTestId('panel'); + expect(panel).toHaveClass(`test-${motion}-${phase}`); + fireEvent.change(panel.querySelector('input'), { + target: { value: 'edited' }, + }); + onVisibleChanged.mockClear(); + + rerender(); + advance(); + rerender(); + advance(); + expect(getByTestId('panel')).toBe(panel); + expect(panel.querySelector('input').value).toBe('edited'); + expect(panel).toHaveClass(`test-${motion}-active`); + finish(panel); + expect(onVisibleChanged.mock.calls).toEqual([[visible]]); + if (visible) expect(panel).not.toHaveClass(`test-${motion}`); + else expect(queryByTestId('panel')).toBeNull(); + }, + ); + + it.each([true, false])( + 'uses the latest visibility when it changes while hidden (motion=%s)', + motion => { + const onVisibleChanged = jest.fn(); + const props = { + strict, + onVisibleChanged, + motionName: motion ? 'test' : undefined, + }; + const { getByTestId, queryByTestId, rerender } = render( + , + ); + const panel = getByTestId('panel'); + finish(panel); + rerender(); + rerender(); + rerender(); + finish(panel); + expect(queryByTestId('panel')).toBeNull(); + expect(onVisibleChanged.mock.calls).toEqual([[true], [false]]); + rerender(); + rerender(); + rerender(); + finish(getByTestId('panel')); + expect(onVisibleChanged.mock.calls).toEqual([[true], [false], [true]]); + }, + ); + + it('restarts the deadline for an interrupted active motion', () => { + const onAppearEnd = jest.fn(); + const props = { strict, motionDeadline: 1000, onAppearEnd }; + const { getByTestId, rerender } = render(); + act(() => jest.advanceTimersByTime(100)); + const panel = getByTestId('panel'); + expect(panel).toHaveClass('test-appear-active'); + rerender(); + advance(); + expect(onAppearEnd).not.toHaveBeenCalled(); + rerender(); + advance(); + advance(); + expect(getByTestId('panel')).toBe(panel); + expect(onAppearEnd).toHaveBeenCalledTimes(1); + expect(panel).not.toHaveClass('test-appear'); + }); + + it('ignores a prepare promise resolved while disconnected', async () => { + const resolvers: (() => void)[] = []; + const onAppearPrepare = jest.fn( + () => new Promise(resolve => resolvers.push(resolve)), + ); + const onAppearStart = jest.fn(); + const props = { strict, onAppearPrepare, onAppearStart }; + const { getByTestId, rerender } = render(); + advance(); + const panel = getByTestId('panel'); + rerender(); + await act(async () => resolvers.forEach(resolve => resolve())); + advance(); + rerender(); + advance(); + expect(getByTestId('panel')).toBe(panel); + expect(panel).toHaveClass('test-appear-prepare'); + expect(onAppearStart).not.toHaveBeenCalled(); + await act(async () => resolvers[resolvers.length - 1]()); + finish(panel); + expect(panel).not.toHaveClass('test-appear'); + }); + + it('allows a fresh appear after a real unmount', () => { + const onAppearStart = jest.fn(); + const props = { strict, onAppearStart }; + const first = render(); + const firstPanel = first.getByTestId('panel'); + finish(firstPanel); + first.unmount(); + onAppearStart.mockClear(); + const second = render(); + const secondPanel = second.getByTestId('panel'); + expect(secondPanel).not.toBe(firstPanel); + expect(secondPanel).toHaveClass('test-appear-start'); + expect(onAppearStart).toHaveBeenCalled(); + finish(secondPanel); + expect(secondPanel).not.toHaveClass('test-appear'); + }); + + it('releases pending animation work on a real unmount', async () => { + let resolvePrepare: () => void; + const onAppearPrepare = () => + new Promise(resolve => { + resolvePrepare = resolve; + }); + const onAppearStart = jest.fn(); + const onVisibleChanged = jest.fn(); + const { unmount } = render( + , + ); + advance(); + unmount(); + await act(async () => resolvePrepare()); + advance(); + expect(onAppearStart).not.toHaveBeenCalled(); + expect(onVisibleChanged).not.toHaveBeenCalled(); + expect(jest.getTimerCount()).toBe(0); + }); + + it.each([false, true])( + 'preserves content through Suspense (settled=%s)', + async settled => { + let resolve: () => void; + let suspended = false; + const pending = new Promise(done => { + resolve = done; + }); + function Suspend() { + if (suspended) throw pending; + return null; + } + const onAppearStart = jest.fn(); + function SuspenseDemo() { + return ( + Loading}> + + + + ); + } + const { getByTestId, rerender, queryByText } = render(); + const panel = getByTestId('panel'); + if (settled) finish(panel); + else advance(); + fireEvent.change(panel.querySelector('input'), { + target: { value: 'edited' }, + }); + onAppearStart.mockClear(); + suspended = true; + rerender(); + expect(queryByText('Loading')).toBeInTheDocument(); + suspended = false; + await act(async () => resolve()); + expect(queryByText('Loading')).toBeNull(); + expect(getByTestId('panel')).toBe(panel); + expect(panel.querySelector('input').value).toBe('edited'); + if (settled) expect(onAppearStart).not.toHaveBeenCalled(); + finish(panel); + expect(panel).not.toHaveClass('test-appear'); + }, + ); +}); diff --git a/tests/useNextFrame.spec.tsx b/tests/useNextFrame.spec.tsx new file mode 100644 index 0000000..20d484a --- /dev/null +++ b/tests/useNextFrame.spec.tsx @@ -0,0 +1,62 @@ +import { act, renderHook } from '@testing-library/react'; +import useNextFrame from '../src/hooks/useNextFrame'; + +describe('useNextFrame cancellation', () => { + beforeEach(() => jest.useFakeTimers()); + afterEach(() => { + jest.clearAllTimers(); + jest.useRealTimers(); + }); + + it.each(['cancel', 'unmount'] as const)( + 'invalidates an already dispatched asynchronous task on %s', + async action => { + const { result, unmount } = renderHook(useNextFrame); + let resolve: () => void; + const prepared = new Promise(done => { + resolve = done; + }); + const onComplete = jest.fn(); + const onFrame = jest.fn(info => { + prepared.then(() => { + if (!info.isCanceled()) onComplete(); + }); + }); + act(() => { + result.current[0](onFrame); + jest.runAllTimers(); + }); + expect(onFrame).toHaveBeenCalledTimes(1); + if (action === 'unmount') unmount(); + else act(() => result.current[1]()); + await act(async () => resolve()); + act(() => jest.runAllTimers()); + expect(onComplete).not.toHaveBeenCalled(); + expect(jest.getTimerCount()).toBe(0); + }, + ); + + it('runs a new task after cancellation and ignores the superseded task', async () => { + const { result } = renderHook(useNextFrame); + let resolve: () => void; + const prepared = new Promise(done => { + resolve = done; + }); + const onComplete = jest.fn(); + act(() => { + result.current[0](info => { + prepared.then(() => { + if (!info.isCanceled()) onComplete('old'); + }); + }); + jest.runAllTimers(); + result.current[1](); + result.current[0](info => { + if (!info.isCanceled()) onComplete('new'); + }); + jest.runAllTimers(); + }); + await act(async () => resolve()); + expect(onComplete.mock.calls).toEqual([['new']]); + }); +});