Skip to content

Commit

Permalink
fix(Dialog): autoFocus for v2
Browse files Browse the repository at this point in the history
  • Loading branch information
bindoon authored and youluna committed Oct 15, 2021
1 parent a3f9690 commit 8eafba7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
4 changes: 2 additions & 2 deletions docs/dialog/demo/accessibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Set the `aria-label` attribute via `okProps` and `cancelProps`, The screen reade

````jsx

import { Button, Dialog } from '@alifd/next';
import { Button, Dialog, Input } from '@alifd/next';

class Demo extends React.Component {
state = {
Expand Down Expand Up @@ -47,7 +47,7 @@ class Demo extends React.Component {
onClose={this.onClose.bind(this, 'cancelClick')}
cancelProps={{'aria-label':'cancel'}}
okProps={{'aria-label':'ok'}}>
<p tabIndex="0"> Start your business here by searching a popular product</p>
<Input placeholder="should autofocus here"/>
</Dialog>
</div>
);
Expand Down
23 changes: 21 additions & 2 deletions src/dialog/dialog-v2.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import classNames from 'classnames';
import Inner from './inner';
import Animate from '../animate';
import zhCN from '../locale/zh-cn';
import { log, func, dom } from '../util';
import { log, func, dom, focus } from '../util';

const noop = func.noop;

Expand Down Expand Up @@ -66,6 +66,7 @@ const Dialog = props => {
const dialogRef = useRef(null);
const wrapperRef = useRef(null);
const originStyle = useRef('');
const lastFocus = useRef(null);

let canCloseByEsc = false;
let canCloseByMask = false;
Expand Down Expand Up @@ -178,17 +179,34 @@ const Dialog = props => {
handleClose(e.triggerType, e);
};

const handleEnter = e => {
const handleEnter = () => {
markAnimationEnd(false);
dom.setStyle(wrapperRef.current, 'display', '');
};
const handleEntered = () => {
if (autoFocus && dialogRef.current && dialogRef.current.bodyNode) {
const focusableNodes = focus.getFocusNodeList(dialogRef.current.bodyNode);
if (focusableNodes.length > 0 && focusableNodes[0]) {
lastFocus.current = document.activeElement;
focusableNodes[0].focus();
}
}
};
const handleExiting = () => {
setTimeout(() => document.body.setAttribute('style', originStyle.current || ''), animation === null ? 0 : 100);
};

const handleExited = () => {
markAnimationEnd(true);
dom.setStyle(wrapperRef.current, 'display', 'none');
if (autoFocus && lastFocus.current) {
try {
lastFocus.current.focus();
} finally {
// ignore ...
}
lastFocus.current = null;
}
afterClose();
};

Expand Down Expand Up @@ -231,6 +249,7 @@ const Dialog = props => {
exit: 500,
}}
onEnter={handleEnter}
onEntered={handleEntered}
onExiting={handleExiting}
onExited={handleExited}
>
Expand Down

0 comments on commit 8eafba7

Please sign in to comment.