diff --git a/packages/components/config-provider/config-provider.en-US.md b/packages/components/config-provider/config-provider.en-US.md index ac44484f05..f4d4ef02ce 100644 --- a/packages/components/config-provider/config-provider.en-US.md +++ b/packages/components/config-provider/config-provider.en-US.md @@ -201,6 +201,8 @@ closeOnEscKeydown | Boolean | true | trigger dialog close on `ESC` keydown | N closeOnOverlayClick | Boolean | true | \- | N confirm | Object | - | Typescript: `string \| ButtonProps` | N confirmBtnTheme | Object | - | Typescript: `{ default: string; info: string; warning: string; danger: string; success: string; }` | N +confirmOnEnter | Boolean | false | Whether to trigger the confirm event when Enter is pressed | N +focusable | Object | - | Dialog focus control. Typescript: `Partial` | N placement | String | top | options: top/center | N zIndex | Number | - | \- | N diff --git a/packages/components/config-provider/config-provider.md b/packages/components/config-provider/config-provider.md index dc0a8ed9e4..b091c1b579 100644 --- a/packages/components/config-provider/config-provider.md +++ b/packages/components/config-provider/config-provider.md @@ -201,6 +201,8 @@ closeOnEscKeydown | Boolean | true | 按下 ESC 时是否触发对话框关闭 closeOnOverlayClick | Boolean | true | 点击蒙层时是否触发关闭事件 | N confirm | Object | - | 确认按钮风格。TS 类型:`string \| ButtonProps` | N confirmBtnTheme | Object | - | 确认按钮主题色,即 Dialog 的 `theme` 和 确认按钮的 `theme` 映射关系。示例:{ danger: 'danger' }。TS 类型:`{ default: string; info: string; warning: string; danger: string; success: string; }` | N +confirmOnEnter | Boolean | false | 是否在按下回车键时触发确认事件 | N +focusable | Object | - | 对话框焦点控制。TS 类型:`Partial` | N placement | String | top | 全局配置的对话框位置,垂直水平居中显示 和 靠近顶部(top:20%)显示。可选项:top/center | N zIndex | Number | - | 对话框层级,默认为 2500 | N diff --git a/packages/components/config-provider/type.ts b/packages/components/config-provider/type.ts index e2fd0bcfaf..5fedc41e93 100644 --- a/packages/components/config-provider/type.ts +++ b/packages/components/config-provider/type.ts @@ -12,6 +12,7 @@ import type { ImageProps } from '../image'; import type { LoadingProps } from '../loading'; import type { MessageOptions } from '../message'; import type { TNode, TElement, SizeEnum, AttachNode } from '../common'; +import type { DialogFocusable } from '../dialog/type'; export interface TdConfigProviderProps { /** @@ -462,6 +463,14 @@ export interface DialogConfig { * 确认按钮主题色,即 Dialog 的 `theme` 和 确认按钮的 `theme` 映射关系。示例:{ danger: 'danger' } */ confirmBtnTheme?: { default: string; info: string; warning: string; danger: string; success: string }; + /** + * 是否在按下回车键时触发确认事件 + */ + confirmOnEnter?: boolean; + /** + * 对话框焦点控制 + */ + focusable?: Partial; /** * 全局配置的对话框位置,垂直水平居中显示 和 靠近顶部(top:20%)显示 * @default top diff --git a/packages/components/dialog/Dialog.tsx b/packages/components/dialog/Dialog.tsx index 2fd027b743..3eb183a98d 100644 --- a/packages/components/dialog/Dialog.tsx +++ b/packages/components/dialog/Dialog.tsx @@ -2,36 +2,64 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } f import { CSSTransition } from 'react-transition-group'; import classNames from 'classnames'; import { isUndefined, omit } from 'lodash-es'; -import log from '@tdesign/common-js/log/index'; import { pxCompat } from '@tdesign/common-js/utils/helper'; import Portal from '../common/Portal'; import useAttach from '../hooks/useAttach'; import useConfig from '../hooks/useConfig'; import useDefaultProps from '../hooks/useDefaultProps'; +import useOverlayManager from '../hooks/useOverlayManager'; import useSetState from '../hooks/useSetState'; import { useLocaleReceiver } from '../locale/LocalReceiver'; import { dialogDefaultProps } from './defaultProps'; import DialogCard from './DialogCard'; import useDialogDrag from './hooks/useDialogDrag'; -import useDialogEsc from './hooks/useDialogEsc'; +import useDialogFocus from './hooks/useDialogFocus'; import useDialogPosition from './hooks/useDialogPosition'; import useLockStyle from './hooks/useLockStyle'; import type { StyledProps } from '../common'; import type { DialogInstance, TdDialogProps } from './type'; +function shouldSkipConfirmOnEnter(event: React.KeyboardEvent, confirmLoading?: boolean) { + if (confirmLoading) return true; + const { nativeEvent } = event; + if (nativeEvent.isComposing || nativeEvent.keyCode === 229) return true; + const { target } = event; + if (!(target instanceof HTMLElement)) return false; + if (target.tagName === 'TEXTAREA') return true; + if (target.isContentEditable) return true; + const editable = target.closest('[contenteditable]'); + return editable !== null && editable.getAttribute('contenteditable') !== 'false'; +} + export interface DialogProps extends TdDialogProps, StyledProps { isPlugin?: boolean; // 是否以插件形式调用 + /** @internal */ + onUnhandledKeyDown?: React.KeyboardEventHandler; } const Dialog = forwardRef((originalProps, ref) => { const { classPrefix, dialog: globalDialogConfig } = useConfig(); - const props = useDefaultProps(originalProps, { - ...dialogDefaultProps, - placement: globalDialogConfig?.placement ?? dialogDefaultProps.placement, - zIndex: globalDialogConfig?.zIndex, - }); + const globalFocusable = globalDialogConfig?.focusable; + const props = useDefaultProps( + { + ...originalProps, + confirmOnEnter: originalProps.confirmOnEnter ?? globalDialogConfig?.confirmOnEnter, + focusable: + globalFocusable || originalProps.focusable + ? ({ + ...globalFocusable, + ...originalProps.focusable, + } as DialogProps['focusable']) + : undefined, + }, + { + ...dialogDefaultProps, + placement: globalDialogConfig?.placement ?? dialogDefaultProps.placement, + zIndex: globalDialogConfig?.zIndex, + }, + ); const { children } = props; const isPlugin = originalProps.isPlugin ?? false; @@ -52,6 +80,7 @@ const Dialog = forwardRef((originalProps, ref) => { const { className, dialogClassName, + dialogStyle, style, width, mode, @@ -80,17 +109,32 @@ const Dialog = forwardRef((originalProps, ref) => { lazy, top, placement, + focusable, + onUnhandledKeyDown, ...restState } = mergedState; const isModeless = mode === 'modeless'; + const isNormal = mode === 'normal'; const isFullScreen = mode === 'full-screen'; const dialogAttach = useAttach('dialog', attach); const [dialogAnimationVisible, setDialogAnimationVisible] = useState(false); + const [dialogContainerVisible, setDialogContainerVisible] = useState(visible); useLockStyle({ preventScrollThrough, visible, mode, showInAttachedElement }); - const { activateDialog } = useDialogEsc(visible, wrapRef); + const { isTopOverlay } = useOverlayManager('dialog', { + visible, + getElement: () => wrapRef.current, + }); + const { focusDialog, restoreTriggerFocus } = useDialogFocus({ + visible, + classPrefix, + dialogRef: wrapRef, + dialogCardRef, + focusable, + isTop: isTopOverlay, + }); const { applyTransform } = useDialogPosition(dialogCardRef); const { isInputInteracting } = useDialogDrag({ dialogCardRef, @@ -102,8 +146,8 @@ const Dialog = forwardRef((originalProps, ref) => { dialogCardRef.current.style.display = dialogAnimationVisible ? 'block' : 'none'; if (dialogAnimationVisible) { - activateDialog(); - applyTransform(); + if (!isNormal) applyTransform(); + focusDialog(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [dialogAnimationVisible]); @@ -126,12 +170,6 @@ const Dialog = forwardRef((originalProps, ref) => { }, })); - // @ts-ignore 兼容旧版本 2.0 移除 - if (props.mode === 'normal') { - log.error('Dialog', 'mode="normal" is not supported, please use DialogCard.'); - return ; - } - const onMaskClick = (e: React.MouseEvent) => { if (!showOverlay || isModeless || isInputInteracting.current) return; // 判断点击事件初次点击是否为内容区域 @@ -159,6 +197,8 @@ const Dialog = forwardRef((originalProps, ref) => { }; const handleKeyDown = (e: React.KeyboardEvent) => { + if (!isTopOverlay()) return; + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode if (e.key === 'Escape') { e.stopPropagation(); @@ -169,21 +209,23 @@ const Dialog = forwardRef((originalProps, ref) => { } else if (e.key === 'Enter' || e.key === 'NumpadEnter') { // 回车键触发点击确认事件 e.stopPropagation(); - confirmOnEnter && onConfirm?.({ e }); + if (!confirmOnEnter || shouldSkipConfirmOnEnter(e, mergedState.confirmLoading)) return; + onConfirm?.({ e }); + } else { + onUnhandledKeyDown?.(e); } }; // Portal Animation const onAnimateStart = () => { onBeforeOpen?.(); - if (!wrapRef.current) return; - wrapRef.current.style.display = 'block'; + setDialogContainerVisible(true); }; const onAnimateLeave = () => { + restoreTriggerFocus(); onClosed?.(); - if (!wrapRef.current) return; - wrapRef.current.style.display = 'none'; + setDialogContainerVisible(false); }; // Dialog Animation @@ -213,6 +255,73 @@ const Dialog = forwardRef((originalProps, ref) => { ) : null; }; + const renderDialogCard = () => ( + + + {children} + + + ); + + const renderDialog = () => ( +
+ {renderMask()} + {isNormal ? ( + renderDialogCard() + ) : ( +
+
+ {renderDialogCard()} +
+
+ )} +
+ ); + + const transitionNodeRef = isNormal ? wrapRef : portalRef; + return ( ((originalProps, ref) => { timeout={300} mountOnEnter={isUndefined(forceRender) ? lazy : !forceRender} unmountOnExit={destroyOnClose} - nodeRef={portalRef} + nodeRef={transitionNodeRef} onEnter={onAnimateStart} onEntered={onOpened} onExit={onBeforeClose} onExited={onAnimateLeave} > - -
- {renderMask()} -
-
- - - {children} - - -
-
-
-
+ {isNormal ? ( + renderDialog() + ) : ( + + {renderDialog()} + + )}
); }); diff --git a/packages/components/dialog/DialogCard.tsx b/packages/components/dialog/DialogCard.tsx index 034faed6d2..51ba10f57f 100644 --- a/packages/components/dialog/DialogCard.tsx +++ b/packages/components/dialog/DialogCard.tsx @@ -41,7 +41,7 @@ const renderDialogButton = (btn: DialogCardProps['cancelBtn'], defaultProps: But }; const DialogCard = forwardRef((props, ref) => { - const { classPrefix } = useConfig(); + const { classPrefix, dialog: globalDialogConfig } = useConfig(); const componentCls = `${classPrefix}-dialog`; const { CloseIcon, InfoCircleFilledIcon, CheckCircleFilledIcon } = useGlobalIcon({ CloseIcon: TdCloseIcon, @@ -131,7 +131,7 @@ const DialogCard = forwardRef((props, ref) => { className: classNames(`${componentCls}__cancel`, cancelBtn?.props?.className), }); const renderConfirmBtn = renderDialogButton(confirmBtn, { - theme: 'primary', + theme: (globalDialogConfig?.confirmBtnTheme?.[theme] || 'primary') as ButtonProps['theme'], loading: confirmLoading, onClick: (e: React.MouseEvent) => onConfirm?.({ e }), className: classNames(`${componentCls}__confirm`, confirmBtn?.className), diff --git a/packages/components/dialog/__tests__/dialog.test.tsx b/packages/components/dialog/__tests__/dialog.test.tsx index de9b378308..b51137e161 100644 --- a/packages/components/dialog/__tests__/dialog.test.tsx +++ b/packages/components/dialog/__tests__/dialog.test.tsx @@ -54,6 +54,133 @@ describe('Dialog', () => { expect(container.querySelector('.t-dialog__header')).toBeNull(); }); + + test('lazy[boolean]', () => { + const { unmount } = render( + +

This is a dialog

+
, + ); + + expect(document.querySelector('.t-dialog')).not.toBeInTheDocument(); + unmount(); + + render( + +

This is a dialog

+
, + ); + + expect(document.querySelector('.t-dialog')).toBeInTheDocument(); + expect(document.querySelector('.t-dialog__ctx')).toHaveStyle({ + display: 'none', + }); + }); + + test('mode[normal]', () => { + const { container, rerender } = render(); + expect(container.querySelector('.t-dialog__normal')).not.toBeInTheDocument(); + + rerender(); + + const dialog = container.querySelector('.t-dialog__normal'); + expect(dialog).toBeInTheDocument(); + expect(dialog).not.toHaveClass('t-dialog__ctx--fixed'); + expect(dialog?.querySelector('.t-dialog__mask')).not.toBeInTheDocument(); + expect(dialog?.querySelector('.t-dialog__position')).not.toBeInTheDocument(); + expect(document.querySelector('.t-portal-wrapper .t-dialog__normal')).not.toBeInTheDocument(); + }); + + describe('focusable', () => { + (['confirm-button', 'cancel-button'] as const).forEach((defaultFocus) => { + test(`defaultFocus[${defaultFocus}]`, () => { + render(); + + const className = defaultFocus === 'confirm-button' ? 't-dialog__confirm' : 't-dialog__cancel'; + expect(document.activeElement).toHaveClass(className); + }); + }); + + test('defaultFocus[function]', () => { + render( + document.querySelector('#custom-dialog-focus'), + focusTriggerAfterClose: false, + }} + > + + , + ); + + expect(document.activeElement).toHaveAttribute('id', 'custom-dialog-focus'); + }); + + test('defaultFocus[null]', () => { + const opener = document.createElement('button'); + document.body.appendChild(opener); + opener.focus(); + + render(); + + expect(document.activeElement).toBe(opener); + opener.remove(); + }); + + test('focusTrap', async () => { + render( + <> + + + + + , + ); + + expect(document.activeElement).toHaveClass('t-dialog__confirm'); + await user.tab(); + expect(document.activeElement).toHaveAttribute('data-testid', 'body-focus'); + + document.querySelector('[data-testid="outside-focus"]').focus(); + expect(document.activeElement).not.toHaveAttribute('data-testid', 'outside-focus'); + expect(document.querySelector('.t-dialog')).toContainElement(document.activeElement as HTMLElement); + }); + + test('focusTriggerAfterClose', async () => { + function FocusRestoreDemo() { + const [visible, setVisible] = useState(false); + return ( + <> + + setVisible(false)} + /> + + ); + } + + const { getByText } = render(); + const opener = getByText('Open focus dialog'); + await user.click(opener); + expect(document.activeElement).toHaveClass('t-dialog__confirm'); + + fireEvent.click(document.querySelector('.t-dialog__close')); + await mockTimeout(() => expect(document.activeElement).toBe(opener), 400); + }); + }); }); describe('events', () => { @@ -66,64 +193,212 @@ describe('Dialog', () => { expect(onEscKeydown).toHaveBeenCalled(); }); - test('onConfirm', async () => { - const onConfirm = vi.fn(); - const { getByText } = render(); + describe('onConfirm', () => { + test('triggers on Enter', async () => { + const onConfirm = vi.fn(); + const { getByText } = render(); - fireEvent.click(getByText('Open Dialog Modal')); - await user.keyboard('{Enter}'); - expect(onConfirm).toHaveBeenCalled(); + fireEvent.click(getByText('Open Dialog Modal')); + await user.keyboard('{Enter}'); + expect(onConfirm).toHaveBeenCalled(); + }); + + test('confirmOnEnter should ignore textarea, contentEditable, IME and confirmLoading', () => { + const onConfirm = vi.fn(); + const { getByPlaceholderText, rerender } = render( + +