From 6eb0edcafcc9815a31048e11bb6a3da3d186dd74 Mon Sep 17 00:00:00 2001 From: Andrew Duthie Date: Mon, 2 Mar 2020 16:04:22 -0500 Subject: [PATCH] Rich Text: Avoid activeElement focus call (#20594) * Rich Text: Avoid activeElement focus call * Rich Text: Restore focus, accounting for null activeElement * Rich Text: Verify activeElement instanceof HTMLElement --- packages/rich-text/src/to-dom.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/rich-text/src/to-dom.js b/packages/rich-text/src/to-dom.js index 2e5c54e769b1e..0a63e94a95e3a 100644 --- a/packages/rich-text/src/to-dom.js +++ b/packages/rich-text/src/to-dom.js @@ -302,5 +302,24 @@ export function applySelection( { startPath, endPath }, current ) { } selection.addRange( range ); - activeElement.focus(); + + // This function is not intended to cause a shift in focus. Since the above + // selection manipulations may shift focus, ensure that focus is restored to + // its previous state. `activeElement` can be `null` or the body element if + // there is no focus, which is accounted for here in the explicit `blur` to + // restore to a state of non-focus. + if ( activeElement !== document.activeElement ) { + // The `instanceof` checks protect against edge cases where the focused + // element is not of the interface HTMLElement (does not have a `focus` + // or `blur` property). + // + // See: https://github.com/Microsoft/TypeScript/issues/5901#issuecomment-431649653 + if ( activeElement ) { + if ( activeElement instanceof window.HTMLElement ) { + activeElement.focus(); + } + } else if ( document.activeElement instanceof window.HTMLElement ) { + document.activeElement.blur(); + } + } }