UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

31 lines (30 loc) 1.07 kB
import { handleEventListener } from '../handle-event-listener/index.svelte.js'; import { defaultWindow } from '../__internal__/configurable.js'; import { onDestroy } from 'svelte'; /** * Tracks whether the window is focused or not. * @param options Additional options to customize the behavior. * @see https://svelte-librarian.github.io/sv-use/docs/core/is-window-focused */ export function isWindowFocused(options = {}) { const { window = defaultWindow, autoCleanup = true } = options; const cleanups = []; let _isFocused = $state(!!window && window.document.hasFocus()); if (window) { cleanups.push(handleEventListener('blur', () => (_isFocused = false), { passive: true, autoCleanup }), handleEventListener('focus', () => (_isFocused = true), { passive: true, autoCleanup })); } if (autoCleanup) { onDestroy(() => { cleanup(); }); } function cleanup() { cleanups.map((fn) => fn()); } return { get current() { return _isFocused; }, cleanup }; }