Skip to content

Commit

Permalink
feat(useActiveElement): search deeply in shadow dom (#3208)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
duoduoObama and antfu committed Jul 30, 2023
1 parent ac88fd7 commit 296dcc5
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions packages/core/useActiveElement/index.ts
Expand Up @@ -3,27 +3,48 @@ import { useEventListener } from '../useEventListener'
import type { ConfigurableDocumentOrShadowRoot, ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'

export interface UseActiveElementOptions extends ConfigurableWindow, ConfigurableDocumentOrShadowRoot {}
export interface UseActiveElementOptions extends ConfigurableWindow, ConfigurableDocumentOrShadowRoot {
/**
* Search active element deeply inside shadow dom
*
* @default true
*/
deep?: boolean
}

/**
* Reactive `document.activeElement`
*
* @see https://vueuse.org/useActiveElement
* @param options
*/
export function useActiveElement<T extends HTMLElement>(options: UseActiveElementOptions = {}) {
const { window = defaultWindow } = options
export function useActiveElement<T extends HTMLElement>(
options: UseActiveElementOptions = {},
) {
const {
window = defaultWindow,
deep = true,
} = options
const document = options.document ?? window?.document

const getDeepActiveElement = () => {
let element = document?.activeElement
if (deep) {
while (element?.shadowRoot)
element = element?.shadowRoot?.activeElement
}
return element
}

const activeElement = computedWithControl(
() => null,
() => document?.activeElement as T | null | undefined,
() => getDeepActiveElement() as T | null | undefined,
)

if (window) {
useEventListener(window, 'blur', (event) => {
if (event.relatedTarget !== null)
return

activeElement.trigger()
}, true)
useEventListener(window, 'focus', activeElement.trigger, true)
Expand Down

0 comments on commit 296dcc5

Please sign in to comment.