UNPKG

@solid-primitives/pointer

Version:

A collection of primitives, giving you a nicer API to handle pointer events in a reactive context.

53 lines (52 loc) 1.39 kB
import { pick } from "@solid-primitives/utils/immutable"; /** * A non-reactive helper function. It turns a position relative to the screen/window, to be relative to an element. * @param poz object containing `x` & `y` * @param el element to calculate the position of * @returns the `poz` with `x` and `y` changed, and `isInside` added */ export const getPositionToElement = (poz, el) => { const { top, left, width, height } = el.getBoundingClientRect(), x = poz.x - left, y = poz.y - top; return { ...poz, x, y, isInside: x >= 0 && y >= 0 && x <= width && y <= height, }; }; const parseOnEventName = (name) => name.substring(2).toLowerCase(); export const parseHandlersMap = (handlers) => { const result = {}; Object.entries(handlers).forEach(([name, fn]) => (result[parseOnEventName(name)] = fn)); return result; }; const pointerStateKeys = [ "x", "y", "pointerId", "pressure", "tiltX", "tiltY", "width", "height", "twist", "pointerType", ]; export const toState = (e) => pick(e, ...pointerStateKeys); export const toStateActive = (e, isActive) => ({ ...toState(e), isActive, }); export const DEFAULT_STATE = { x: 0, y: 0, pointerId: 0, pressure: 0, tiltX: 0, tiltY: 0, width: 0, height: 0, twist: 0, pointerType: null, isActive: false, };