diff --git a/examples/simple.js b/examples/simple.js index b804dd8..651b9bc 100644 --- a/examples/simple.js +++ b/examples/simple.js @@ -5,11 +5,30 @@ import ReactDOM from 'react-dom'; class Test extends Component { state = { monitor: true, + random: false, + randomWidth: 100, align: { points: ['cc', 'cc'], }, }; + componentDidMount() { + this.id = setInterval(() => { + const { random } = this.state; + if (random) { + this.setState({ + randomWidth: 60 + 40 * Math.random(), + }, () => { + this.forceAlign(); + }); + } + }, 1000); + } + + componentWillUnmount() { + clearInterval(this.id); + } + getTarget = () => { if (!this.$container) { // parent ref not attached @@ -32,11 +51,19 @@ class Test extends Component { }); } + toggleRandom = () => { + this.setState({ + random: !this.state.random, + }); + } + forceAlign = () => { this.$align.forceAlign(); } render() { + const { random, randomWidth } = this.state; + return (
+

- source +
diff --git a/src/Align.jsx b/src/Align.jsx index 585f2ff..fba3751 100644 --- a/src/Align.jsx +++ b/src/Align.jsx @@ -4,7 +4,7 @@ import ReactDOM from 'react-dom'; import { alignElement, alignPoint } from 'dom-align'; import addEventListener from 'rc-util/lib/Dom/addEventListener'; -import { isWindow, buffer, isSamePoint, isSimilarValue } from './util'; +import { isWindow, buffer, isSamePoint, isSimilarValue, restoreFocus } from './util'; function getElement(func) { if (typeof func !== 'function' || !func) return null; @@ -133,12 +133,20 @@ class Align extends Component { const element = getElement(target); const point = getPoint(target); + // IE lose focus after element realign + // We should record activeElement and restore later + const activeElement = document.activeElement; + if (element) { result = alignElement(source, element, align); } else if (point) { result = alignPoint(source, point, align); } + if (activeElement && activeElement !== document.activeElement) { + restoreFocus(activeElement, source); + } + if (onAlign) { onAlign(source, result); } diff --git a/src/util.js b/src/util.js index 2df1827..3f51b0b 100644 --- a/src/util.js +++ b/src/util.js @@ -42,3 +42,18 @@ export function isSimilarValue(val1, val2) { const int2 = Math.floor(val2); return Math.abs(int1 - int2) <= 1; } + +export function restoreFocus(activeElement, container) { + let currentElement = activeElement; + while (currentElement) { + if (currentElement === container) { + break; + } + currentElement = currentElement.parentNode; + } + + // Focus back if is in the container + if (currentElement) { + activeElement.focus(); + } +}