Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/Dialog/Content/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -37,10 +38,12 @@ const Content = React.forwardRef<ContentRef, ContentProps>((props, ref) => {
const panelRef = useRef<PanelRef>(null);

// ============================== Refs ==============================
// Delegate lazily: the handle may be created before the panel mounts
// (e.g. when restored from `<Activity>`), 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 ==============================
Expand All @@ -65,11 +68,20 @@ const Content = React.forwardRef<ContentRef, ContentProps>((props, ref) => {
);
}

// ============================= Motion =============================
const [motionAppear, onAppeared] = useMotionAppear(visible);

const onInternalVisibleChanged = (nextVisible: boolean) => {
onAppeared();
onVisibleChanged(nextVisible);
};

// ============================= Render =============================
return (
<CSSMotion
visible={visible}
onVisibleChanged={onVisibleChanged}
motionAppear={motionAppear}
onVisibleChanged={onInternalVisibleChanged}
onAppearPrepare={onPrepare}
onEnterPrepare={onPrepare}
forceRender={forceRender}
Expand Down
5 changes: 5 additions & 0 deletions src/Dialog/Mask.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';
import { clsx } from 'clsx';
import CSSMotion from '@rc-component/motion';
import useMotionAppear from '../hooks/useMotionAppear';

export type MaskProps = {
prefixCls: string;
Expand All @@ -13,10 +14,14 @@ export type MaskProps = {

const Mask: React.FC<MaskProps> = (props) => {
const { prefixCls, style, visible, maskProps, motionName, className } = props;
const [motionAppear, onAppeared] = useMotionAppear(visible);

return (
<CSSMotion
key="mask"
visible={visible}
motionAppear={motionAppear}
onVisibleChanged={onAppeared}
motionName={motionName}
leavedClassName={`${prefixCls}-mask-hidden`}
>
Expand Down
19 changes: 19 additions & 0 deletions src/hooks/useMotionAppear.ts
Original file line number Diff line number Diff line change
@@ -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 `<Activity>` 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;
}
115 changes: 115 additions & 0 deletions tests/activity.spec.tsx
Original file line number Diff line number Diff line change
@@ -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 }) => (
<React.StrictMode>
<Activity mode={mode}>
<Dialog visible={open} animation="zoom" maskAnimation="fade">
<input data-testid="input" />
</Dialog>
</Activity>
</React.StrictMode>
);

const getInput = () => document.querySelector<HTMLInputElement>('[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(<Demo mode="visible" open={!openLater} />);
if (openLater) {
await runFakeTimer();
rerender(<Demo mode="visible" open />);
}
await endMotion();
expectNoMotion();

const panel = document.querySelector('.rc-dialog');
fireEvent.change(getInput(), { target: { value: 'hello' } });

rerender(<Demo mode="hidden" />);
await runFakeTimer();

expect(() => rerender(<Demo mode="visible" />)).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(<Demo mode="visible" />);
await endMotion();

rerender(<Demo mode="hidden" />);
await runFakeTimer();
rerender(<Demo mode="visible" />);
await runFakeTimer();

rerender(<Demo mode="visible" open={false} />);
await runFakeTimer();
expect(document.querySelector('.rc-dialog')).toHaveClass('rc-dialog-zoom-leave');
await endMotion();

rerender(<Demo mode="visible" />);
await runFakeTimer();
expect(document.querySelector('.rc-dialog')).toHaveClass('rc-dialog-zoom-enter');
});
});
26 changes: 26 additions & 0 deletions tests/ref.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -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<ContentRef>();
const props = {
prefixCls: 'rc-dialog',
motionName: '',
ariaId: 'test',
onVisibleChanged: () => {},
};

const { rerender, container } = render(<Content {...props} ref={ref} visible={false} />);

// 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(<Content {...props} ref={ref} visible />);

handle.focus();
expect(container.querySelector('[role="dialog"]')).toBe(document.activeElement);
});
});
Loading