UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

47 lines (46 loc) 1.39 kB
import { onDestroy } from 'svelte'; import { BROWSER } from 'esm-env'; import { handleEventListener } from '../handle-event-listener/index.svelte.js'; /** * Returns the element within the DOM that currently has focus. * @see https://svelte-librarian.github.io/sv-use/docs/core/get-active-element */ export function getActiveElement(options = {}) { const { autoCleanup = true, searchInShadow = true } = options; const cleanups = []; let _current = $state(null); if (BROWSER) { cleanups.push(handleEventListener('blur', onBlur, { autoCleanup, capture: true }), handleEventListener('focus', onFocus, { autoCleanup, capture: true })); } if (autoCleanup) { onDestroy(() => { cleanup(); }); } function getDeepActiveElement() { let element = document?.activeElement; if (searchInShadow) { while (element?.shadowRoot) { element = element?.shadowRoot?.activeElement; } } return element; } function onFocus() { _current = getDeepActiveElement(); } function onBlur(event) { if (event.relatedTarget !== null) return; onFocus(); } function cleanup() { cleanups.forEach((fn) => fn()); } return { get current() { return _current; }, cleanup }; }