UNPKG

preact-context-menu

Version:
68 lines 2.55 kB
import { contextMenus, menuOffset } from "./menu"; var currentMouseCoords = { x: 0, y: 0 }; if (typeof window !== 'undefined') { document.addEventListener("mousemove", function (event) { return currentMouseCoords = { x: event.clientX, y: event.clientY }; }); } /** * Open a context menu by its ID. * @param id Context Menu ID * @param data Data to pass to callback function * @param coords Coordinates to place context menu at */ export var openContextMenu = function (id, data, coords) { var fn = contextMenus.get(id); if (fn === undefined) throw new Error("There is no ContextMenu with the ID " + id); fn(coords ? { x: coords.x - menuOffset, y: coords.y - menuOffset } : currentMouseCoords, data); }; var timeout = 0; var iOS = function () { return /(iPad|iPhone|iPod)/g.test(navigator.userAgent) || (navigator.userAgent.includes("Mac") && "ontouchend" in document); }; /** * Bind context menu events to a Ref. * @param ref Ref object * @param id Context Menu ID * @param data Data to pass to callback function * @param disabled Whether the context menu is disabled * @param touchTimeout Long press duration to show context menu */ export var useTriggerEvents = function (id, data, disabled, touchTimeout) { if (touchTimeout === void 0) { touchTimeout = 610; } if (iOS()) { // On iOS devices, we need to manually handle the touch events. var onTouchStart = function (event) { if (disabled === true) return; var touch = event.touches[0]; clearTimeout(timeout); timeout = setTimeout(function () { openContextMenu(id, data, { x: touch.clientX, y: touch.clientY }); }, touchTimeout); }; // Cancel context menu if we move, end or cancel the touch. var onTouchCancel = function () { clearTimeout(timeout); }; return { onTouchStart: onTouchStart, onTouchCancel: onTouchCancel, onTouchMove: onTouchCancel, onTouchEnd: onTouchCancel }; } else { // For most browsers, we can use onContextMenu. var onContextMenu = function (event) { if (disabled === true) return; openContextMenu(id, data, { x: event.clientX, y: event.clientY }); event.stopPropagation(); event.preventDefault(); }; return { onContextMenu: onContextMenu }; } }; //# sourceMappingURL=util.js.map