UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

50 lines (49 loc) 1.69 kB
import { handleEventListener } from '../handle-event-listener/index.svelte.js'; import { noop, normalizeValue } from '../__internal__/utils.svelte.js'; export function onHover(element, callbackOrOptions, optionsOrNever) { let callback = noop; let options = { delay: undefined, onLeave: noop, dirty: false }; if (callbackOrOptions && typeof callbackOrOptions === 'function') { callback = callbackOrOptions; options = { ...options, ...(optionsOrNever ?? {}) }; } else if (callbackOrOptions && typeof callbackOrOptions === 'object') { options = { ...options, ...(callbackOrOptions ?? {}) }; } let timeout; let isHovering = $state(false); const _element = $derived(normalizeValue(element)); $effect(() => { if (_element) { handleEventListener(_element, options.dirty ? 'mouseover' : 'mouseenter', (event) => { clearTimeout(timeout); if (options.delay) { timeout = setTimeout(() => { isHovering = true; callback(event); }, options.delay); } else { isHovering = true; callback(event); } }); handleEventListener(_element, options.dirty ? 'mouseout' : 'mouseleave', (event) => { clearTimeout(timeout); isHovering = false; options.onLeave?.(event); }); } }); return { get current() { return isHovering; } }; }