UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

74 lines (73 loc) 2.6 kB
import { onDestroy } from 'svelte'; import { handleEventListener } from '../handle-event-listener/index.svelte.js'; import { defaultWindow } from '../__internal__/configurable.js'; /** * Reactive values for mouse/touch/drag pressing state. * @param options Additional options to customize the behavior. * @see https://svelte-librarian.github.io/sv-use/docs/core/get-mouse-pressed */ export function getMousePressed(options = {}) { const { autoCleanup = true, target = defaultWindow, enableTouch = true, enableDrag = true, onPressed = () => { }, onReleased = () => { } } = options; const cleanups = []; let _isPressed = $state(false); let _type = $state(null); if (target) { cleanups.push(handleEventListener(target, 'mousedown', _onPressed('mouse'), { passive: true }), handleEventListener(window, 'mouseleave', _onReleased, { autoCleanup, passive: true }), handleEventListener(window, 'mouseup', _onReleased, { autoCleanup, passive: true })); if (enableDrag) { cleanups.push(handleEventListener(target, 'dragstart', _onPressed('mouse'), { passive: true }), handleEventListener(window, 'drop', _onReleased, { autoCleanup, passive: true }), handleEventListener(window, 'dragend', _onReleased, { autoCleanup, passive: true })); } if (enableTouch) { cleanups.push(handleEventListener(target, 'touchstart', _onPressed('touch'), { passive: true }), handleEventListener(window, 'touchend', _onReleased, { autoCleanup, passive: true }), handleEventListener(window, 'touchcancel', _onReleased, { autoCleanup, passive: true })); } } if (autoCleanup) { onDestroy(() => cleanup()); } function _onPressed(type) { return function (event) { _isPressed = true; _type = type; // @ts-expect-error TS types not resolved correctly onPressed(event); }; } function _onReleased(event) { _isPressed = false; _type = null; // @ts-expect-error TS types not resolved correctly onReleased(event); } function cleanup() { cleanups.forEach((fn) => fn()); } return { get isPressed() { return _isPressed; }, get type() { return _type; }, cleanup }; }