@sv-use/core
Version:
A collection of Svelte 5 utilities.
43 lines (42 loc) • 1.34 kB
JavaScript
import { onDestroy } from 'svelte';
import { handleEventListener } from '../handle-event-listener/index.svelte.js';
import { defaultWindow } from '../__internal__/configurable.js';
/**
* Whether the mouse has left the page or not.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/has-left-page
*/
export function hasLeftPage(options = {}) {
const { autoCleanup = true, window = defaultWindow } = options;
const cleanups = [];
let _current = $state(false);
const handler = (event) => {
if (!window)
return;
event = event || window.event;
// @ts-expect-error missing types
const from = event.relatedTarget || event.toElement;
_current = !from;
};
if (window) {
cleanups.push(handleEventListener(window, 'mouseout', handler, {
autoCleanup,
passive: true
}), handleEventListener(document, ['mouseleave', 'mouseenter'], handler, {
autoCleanup,
passive: true
}));
}
if (autoCleanup) {
onDestroy(() => cleanup());
}
function cleanup() {
cleanups.forEach((cleanup) => cleanup());
}
return {
get current() {
return _current;
},
cleanup
};
}