/
index.ts
43 lines (36 loc) · 1.21 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
34
35
36
37
38
39
40
41
42
43
import type { MaybeRef } from '@vueuse/shared'
import { computedWithControl } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export interface UseActiveElementOptions extends ConfigurableWindow {
ignoreBody?: MaybeRef<boolean>
}
/**
* Reactive `document.activeElement`
*
* @see https://vueuse.org/useActiveElement
* @param options
*/
export function useActiveElement<T extends HTMLElement>(options: UseActiveElementOptions = {}) {
const { window = defaultWindow, ignoreBody } = options
const activeElement = computedWithControl(
() => null,
() => window?.document.activeElement as T | null | undefined,
)
if (window) {
useEventListener(window, 'blur', (event) => {
if (event.relatedTarget === null)
return
if (ignoreBody && window?.document.activeElement?.tagName === 'BODY')
return
activeElement.trigger()
}, true)
useEventListener(window, 'focus', () => {
if (ignoreBody && window?.document.activeElement?.tagName === 'BODY')
return
activeElement.trigger()
}, true)
}
return activeElement
}