From ee172ed2ac86cd38df7d656c8d924ad3950ec920 Mon Sep 17 00:00:00 2001 From: Sbisson Date: Thu, 18 Jul 2024 14:16:47 -0400 Subject: [PATCH] Actively prevent navigation on preview links --- src/index.js | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/index.js b/src/index.js index 19c5a669..e6272d40 100644 --- a/src/index.js +++ b/src/index.js @@ -190,25 +190,29 @@ function init( { } ) } - const onPointerUp = ( pointerEvent ) => { - if ( pointerEvent.pointerType === 'touch' ) { - // This click event was triggered on a touch screen - showPopup( pointerEvent ) - } - } - const onPointerEnter = ( pointerEvent ) => { - if ( pointerEvent.pointerType === 'mouse' ) { - // This hover event was triggered by a mouse - showPopup( pointerEvent ) - } + showPopup( pointerEvent ) } const registerPreviewEvents = ( node ) => { - node.addEventListener( 'pointerup', onPointerUp ) node.addEventListener( 'pointerenter', onPointerEnter ) } + const preventTapFromNavigatingLink = ( node ) => { + // The click event still receives a MouseEvent instead of the newer PointerEvent + // in some browsers so we have to grab the pointerType from the preceding pointerdown event. + let currentPointerType = null + node.addEventListener( 'pointerdown', ( e ) => { + currentPointerType = e.pointerType + } ) + node.addEventListener( 'click', ( e ) => { + if ( currentPointerType === 'touch' ) { + e.preventDefault() + e.stopPropagation() + } + } ) + } + forEachRoot( root, ( localRoot ) => { Array.prototype.forEach.call( localRoot.querySelectorAll( selector ), @@ -233,6 +237,7 @@ function init( { node.setAttribute( 'data-wp-title', matches.title ) node.setAttribute( 'data-wp-lang', matches.lang ) registerPreviewEvents( node ) + preventTapFromNavigatingLink( node ) foundDetectLinks.push( { text: node.textContent,