(target: FocusableElement | null)
| 119 | * using a capturing listener on the window and stopping propagation. |
| 120 | */ |
| 121 | export function preventFocus(target: FocusableElement | null): (() => void) | undefined { |
| 122 | // The browser will focus the nearest focusable ancestor of our target. |
| 123 | while (target && !isFocusable(target, {skipVisibilityCheck: true})) { |
| 124 | target = target.parentElement; |
| 125 | } |
| 126 | |
| 127 | let ownerWindow = getOwnerWindow(target); |
| 128 | let activeElement = getActiveElement(ownerWindow.document) as FocusableElement | null; |
| 129 | if (!activeElement || activeElement === target) { |
| 130 | return; |
| 131 | } |
| 132 | |
| 133 | // Listen on the target's root (document or shadow root) so we catch focus events inside |
| 134 | // shadow DOM; they do not reach the main window. |
| 135 | let targetRoot = target?.getRootNode(); |
| 136 | let root = targetRoot != null && isShadowRoot(targetRoot) ? targetRoot : getOwnerWindow(target); |
| 137 | |
| 138 | // Focus is "moving to target" when it moves to the button or to a descendant of the button |
| 139 | // (e.g. SVG icon) |
| 140 | let isFocusMovingToTarget = (focusTarget: Element | null) => |
| 141 | focusTarget === target || (isNode(focusTarget) && nodeContains(target, focusTarget)); |
| 142 | // Blur/focusout events have their target as the element losing focus. Stop propagation when |
| 143 | // that is the previously focused element (activeElement) or a descendant (e.g. in shadow DOM). |
| 144 | let isBlurFromActiveElement = (eventTarget: Element | null) => |
| 145 | eventTarget === activeElement || |
| 146 | (activeElement != null && isNode(eventTarget) && nodeContains(activeElement, eventTarget)); |
| 147 | |
| 148 | ignoreFocusEvent = true; |
| 149 | let isRefocusing = false; |
| 150 | let onBlur: EventListener = e => { |
| 151 | if (isBlurFromActiveElement(getEventTarget(e) as Element) || isRefocusing) { |
| 152 | e.stopImmediatePropagation(); |
| 153 | } |
| 154 | }; |
| 155 | |
| 156 | let onFocusOut: EventListener = e => { |
| 157 | if (isBlurFromActiveElement(getEventTarget(e) as Element) || isRefocusing) { |
| 158 | e.stopImmediatePropagation(); |
| 159 | |
| 160 | // If there was no focusable ancestor, we don't expect a focus event. |
| 161 | // Re-focus the original active element here. |
| 162 | if (!target && !isRefocusing) { |
| 163 | isRefocusing = true; |
| 164 | focusWithoutScrolling(activeElement); |
| 165 | cleanup(); |
| 166 | } |
| 167 | } |
| 168 | }; |
| 169 | |
| 170 | let onFocus: EventListener = e => { |
| 171 | if (isFocusMovingToTarget(getEventTarget(e) as Element) || isRefocusing) { |
| 172 | e.stopImmediatePropagation(); |
| 173 | } |
| 174 | }; |
| 175 | |
| 176 | let onFocusIn: EventListener = e => { |
| 177 | if (isFocusMovingToTarget(getEventTarget(e) as Element) || isRefocusing) { |
| 178 | e.stopImmediatePropagation(); |
no test coverage detected