forked from vueuse/vueuse
/
index.ts
33 lines (28 loc) · 1.03 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { computedWithControl } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import type { ConfigurableDocumentOrShadowRoot, ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export interface UseActiveElementOptions extends ConfigurableWindow, ConfigurableDocumentOrShadowRoot {}
/**
* Reactive `document.activeElement`
*
* @see https://vueuse.org/useActiveElement
* @param options
*/
export function useActiveElement<T extends HTMLElement>(options: UseActiveElementOptions = {}) {
const { window = defaultWindow } = options
const document = options.document ?? window?.document
const activeElement = computedWithControl(
() => null,
() => document?.activeElement as T | null | undefined,
)
if (window) {
useEventListener(window, 'blur', (event) => {
if (event.relatedTarget === null)
return
activeElement.trigger()
}, true)
useEventListener(window, 'focus', activeElement.trigger, true)
}
return activeElement
}