Adds right-click support to long-press directive

This commit is contained in:
Alicia Sykes 2022-04-03 15:59:07 +01:00
parent f0cb8fe4f2
commit edad7fde41
1 changed files with 22 additions and 7 deletions

View File

@ -6,8 +6,11 @@
*/ */
const LONG_PRESS_DEFAULT_DELAY = 750; const LONG_PRESS_DEFAULT_DELAY = 750;
const TRIGGER_FOR_RIGHT_CLICK = true;
const longPressEvent = new CustomEvent('long-press'); const longPressEvent = new CustomEvent('long-press');
let startTime = null;
export default { export default {
bind(element, binding, vnode) { bind(element, binding, vnode) {
const el = element; const el = element;
@ -16,12 +19,17 @@ export default {
const swallowClick = (e) => { const swallowClick = (e) => {
el.removeEventListener('click', swallowClick); el.removeEventListener('click', swallowClick);
if (!el.dataset.elapsed) return true; if (!el.dataset.elapsed) return true;
e.preventDefault(); const totalTime = Date.now() - startTime;
e.stopPropagation(); // If was long press, then cancel original action
if (totalTime > LONG_PRESS_DEFAULT_DELAY) {
e.preventDefault();
e.stopPropagation();
}
return false; return false;
}; };
const complete = () => { /* Emit event to component */
const triggerEvent = () => {
if (vnode.componentInstance) vnode.componentInstance.$emit('long-press'); if (vnode.componentInstance) vnode.componentInstance.$emit('long-press');
else el.dispatchEvent(longPressEvent); else el.dispatchEvent(longPressEvent);
el.dataset.elapsed = true; el.dataset.elapsed = true;
@ -32,19 +40,26 @@ export default {
document.removeEventListener('pointerup', onPointerUp); document.removeEventListener('pointerup', onPointerUp);
}; };
const onPointerDown = () => { const onPointerDown = (e) => {
// If event was right-click, then immediately trigger
if (e.button === 2) {
if (TRIGGER_FOR_RIGHT_CLICK) triggerEvent();
else return;
}
startTime = Date.now();
document.addEventListener('pointerup', onPointerUp); document.addEventListener('pointerup', onPointerUp);
el.addEventListener('click', swallowClick); el.addEventListener('click', swallowClick);
const timeoutDuration = binding.value || LONG_PRESS_DEFAULT_DELAY; const timeoutDuration = LONG_PRESS_DEFAULT_DELAY;
const timeout = setTimeout(complete, timeoutDuration); const timeout = setTimeout(triggerEvent, timeoutDuration);
el.dataset.elapsed = false; el.dataset.elapsed = false;
el.dataset.longPressTimeout = timeout; el.dataset.longPressTimeout = timeout;
e.preventDefault();
}; };
el.$longPressHandler = onPointerDown; el.$longPressHandler = onPointerDown;
el.addEventListener('pointerdown', onPointerDown); el.addEventListener('pointerdown', onPointerDown);
}, },
unbind(el) { unbind(el) {
startTime = null;
clearTimeout(parseInt(el.dataset.longPressTimeout, 10)); clearTimeout(parseInt(el.dataset.longPressTimeout, 10));
el.removeEventListener('pointerdown', el.$longPressHandler); el.removeEventListener('pointerdown', el.$longPressHandler);
}, },