Skip to content

Commit 259f3cd

Browse files
committed
Focus wrap only if it's not focused
close ant-design/ant-design#8668
1 parent 7ef0b2e commit 259f3cd

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

examples/ant-design.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ class MyControl extends React.Component {
6969
mousePosition={this.state.mousePosition}
7070
destroyOnClose={this.state.destroyOnClose}
7171
>
72-
<input />
72+
<input autoFocus />
7373
<p>basic modal</p>
7474
<button onClick={this.changeWidth}>change width</button>
7575
<div style={{ height: 200 }} />

src/Dialog.tsx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as React from 'react';
22
import * as ReactDOM from 'react-dom';
33
import KeyCode from 'rc-util/lib/KeyCode';
4+
import contains from 'rc-util/lib/Dom/contains';
45
import Animate from 'rc-animate';
56
import LazyRenderBox from './LazyRenderBox';
67
import getScrollBarSize from 'rc-util/lib/getScrollBarSize';
@@ -81,9 +82,8 @@ export default class Dialog extends React.Component<IDialogPropTypes, any> {
8182
// first show
8283
if (!prevProps.visible) {
8384
this.openTime = Date.now();
84-
this.lastOutSideFocusNode = document.activeElement as HTMLElement;
8585
this.addScrollingEffect();
86-
this.wrap.focus();
86+
this.tryFocus();
8787
const dialogNode = ReactDOM.findDOMNode(this.dialog);
8888
if (mousePosition) {
8989
const elOffset = offset(dialogNode);
@@ -110,6 +110,14 @@ export default class Dialog extends React.Component<IDialogPropTypes, any> {
110110
this.removeScrollingEffect();
111111
}
112112
}
113+
114+
tryFocus() {
115+
if (!contains(this.wrap, document.activeElement)) {
116+
this.lastOutSideFocusNode = document.activeElement as HTMLElement;
117+
this.wrap.focus();
118+
}
119+
}
120+
113121
onAnimateLeave = () => {
114122
const { afterClose } = this.props;
115123
// need demo?

tests/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,4 +223,16 @@ describe('dialog', () => {
223223
expect($('.rc-dialog-footer').css('padding')).to.be('10px 20px');
224224
}]);
225225
});
226+
227+
it('support input autoFocus', () => {
228+
const d = ReactDOM.render(
229+
<DialogWrap><input autoFocus /></DialogWrap>,
230+
container
231+
);
232+
d.setState({
233+
visible: true
234+
});
235+
console.log(document.activeElement);
236+
expect(document.activeElement).to.be(document.querySelector('input'));
237+
});
226238
});

0 commit comments

Comments
 (0)