diff --git a/src/Dialog/Content/index.tsx b/src/Dialog/Content/index.tsx index 178b4804..dfb23ef8 100644 --- a/src/Dialog/Content/index.tsx +++ b/src/Dialog/Content/index.tsx @@ -3,6 +3,7 @@ import { useRef } from 'react'; import { clsx } from 'clsx'; import CSSMotion from '@rc-component/motion'; import type { CSSMotionRef } from '@rc-component/motion'; +import useMotionAppear from '../../hooks/useMotionAppear'; import { offset } from '../../util'; import type { PanelProps, PanelRef } from './Panel'; import Panel from './Panel'; @@ -37,10 +38,12 @@ const Content = React.forwardRef((props, ref) => { const panelRef = useRef(null); // ============================== Refs ============================== + // Delegate lazily: the handle may be created before the panel mounts + // (e.g. when restored from ``), so do not snapshot the refs. React.useImperativeHandle(ref, () => ({ - ...panelRef.current, - inMotion: dialogRef.current.inMotion, - enableMotion: dialogRef.current.enableMotion, + focus: () => panelRef.current?.focus(), + inMotion: () => dialogRef.current?.inMotion(), + enableMotion: () => dialogRef.current?.enableMotion(), })); // ============================= Style ============================== @@ -65,11 +68,20 @@ const Content = React.forwardRef((props, ref) => { ); } + // ============================= Motion ============================= + const [motionAppear, onAppeared] = useMotionAppear(visible); + + const onInternalVisibleChanged = (nextVisible: boolean) => { + onAppeared(); + onVisibleChanged(nextVisible); + }; + // ============================= Render ============================= return ( = (props) => { const { prefixCls, style, visible, maskProps, motionName, className } = props; + const [motionAppear, onAppeared] = useMotionAppear(visible); + return ( diff --git a/src/hooks/useMotionAppear.ts b/src/hooks/useMotionAppear.ts new file mode 100644 index 00000000..53343b10 --- /dev/null +++ b/src/hooks/useMotionAppear.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +/** + * `CSSMotion` treats every effect re-mount as a first mount, so the `appear` + * motion starts over and the children are not rendered until it is prepared. + * React `` re-runs effects when it goes from `hidden` back to + * `visible`, which would remount the panel (losing its state) and replay the + * motion. `appear` only makes sense for the very first show, so turn it off + * once the first visible change is done (or right away if mounted hidden). + */ +export default function useMotionAppear(visible: boolean) { + const [motionAppear, setMotionAppear] = React.useState(visible); + + const onAppeared = React.useCallback(() => { + setMotionAppear(false); + }, []); + + return [motionAppear, onAppeared] as const; +} diff --git a/tests/activity.spec.tsx b/tests/activity.spec.tsx new file mode 100644 index 00000000..bae64500 --- /dev/null +++ b/tests/activity.spec.tsx @@ -0,0 +1,115 @@ +import { act, fireEvent, render } from '@testing-library/react'; +import React from 'react'; +import Dialog from '../src'; + +// Run with real motion status (jsdom has no transition support by default) +jest.mock('@rc-component/motion', () => { + const origin = jest.requireActual('@rc-component/motion'); + return { + ...origin, + __esModule: true, + default: origin.genCSSMotion({ transitionSupport: true }), + }; +}); + +const { Activity } = React as any; + +describe('Dialog in Activity', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.clearAllTimers(); + jest.useRealTimers(); + }); + + async function runFakeTimer() { + for (let i = 0; i < 20; i += 1) { + await act(async () => { + jest.advanceTimersByTime(100); + await Promise.resolve(); + }); + } + } + + // Finish the running motions of panel & mask + async function endMotion() { + await runFakeTimer(); + ['.rc-dialog', '.rc-dialog-mask'].forEach((selector) => { + const element = document.querySelector(selector); + if (element) { + act(() => { + element.dispatchEvent(new Event('transitionend')); + }); + } + }); + await runFakeTimer(); + } + + const Demo = ({ mode, open = true }: { mode: 'visible' | 'hidden'; open?: boolean }) => ( + + + + + + + + ); + + const getInput = () => document.querySelector('[data-testid="input"]'); + + function expectNoMotion() { + expect(document.querySelector('.rc-dialog').className).toBe('rc-dialog'); + expect(document.querySelector('.rc-dialog-mask').className).toBe('rc-dialog-mask'); + } + + it.each([ + ['open on mount', false], + ['open later', true], + ])('keeps panel when restored from hidden (%s)', async (_, openLater) => { + const { rerender } = render(); + if (openLater) { + await runFakeTimer(); + rerender(); + } + await endMotion(); + expectNoMotion(); + + const panel = document.querySelector('.rc-dialog'); + fireEvent.change(getInput(), { target: { value: 'hello' } }); + + rerender(); + await runFakeTimer(); + + expect(() => rerender()).not.toThrow(); + + // Panel is not destroyed and motion is not replayed + expect(document.querySelector('.rc-dialog')).toBe(panel); + expectNoMotion(); + expect(getInput().value).toBe('hello'); + + await runFakeTimer(); + expect(document.querySelector('.rc-dialog')).toBe(panel); + expect(getInput().value).toBe('hello'); + }); + + it('still plays motion when opened again after restore', async () => { + const { rerender } = render(); + await endMotion(); + + rerender(); + await runFakeTimer(); + rerender(); + await runFakeTimer(); + + rerender(); + await runFakeTimer(); + expect(document.querySelector('.rc-dialog')).toHaveClass('rc-dialog-zoom-leave'); + await endMotion(); + + rerender(); + await runFakeTimer(); + expect(document.querySelector('.rc-dialog')).toHaveClass('rc-dialog-zoom-enter'); + }); +}); diff --git a/tests/ref.spec.tsx b/tests/ref.spec.tsx index 368846f6..dba3ec7c 100644 --- a/tests/ref.spec.tsx +++ b/tests/ref.spec.tsx @@ -3,6 +3,8 @@ import { render } from '@testing-library/react'; import { Provider } from '@rc-component/motion'; import React from 'react'; import Dialog from '../src'; +import Content from '../src/Dialog/Content'; +import type { ContentRef } from '../src/Dialog/Content'; describe('Dialog.ref', () => { beforeEach(() => { @@ -26,3 +28,27 @@ describe('Dialog.ref', () => { expect(panelRef.current).toHaveClass('rc-dialog'); }); }); + +describe('Dialog.Content ref', () => { + it('handle created before panel mounts should still focus the panel', () => { + const ref = React.createRef(); + const props = { + prefixCls: 'rc-dialog', + motionName: '', + ariaId: 'test', + onVisibleChanged: () => {}, + }; + + const { rerender, container } = render(); + + // Keep the handle created while the panel was not mounted + const handle = ref.current; + expect(typeof handle.focus).toBe('function'); + expect(() => handle.focus()).not.toThrow(); + + rerender(); + + handle.focus(); + expect(container.querySelector('[role="dialog"]')).toBe(document.activeElement); + }); +});