From e83f16f16c3e984984538b0af72933a8cc92de45 Mon Sep 17 00:00:00 2001 From: Pavel Zastavnitskiy Date: Fri, 28 Aug 2020 22:34:20 +0200 Subject: [PATCH] Fix: Fire events on elements with mousetrap class in Shadow Dom --- mousetrap.js | 17 ++++++++--------- tests/test.mousetrap.js | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/mousetrap.js b/mousetrap.js index ab71d582..82f30fd2 100644 --- a/mousetrap.js +++ b/mousetrap.js @@ -973,15 +973,6 @@ Mousetrap.prototype.stopCallback = function(e, element) { var self = this; - // if the element has the class "mousetrap" then no need to stop - if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { - return false; - } - - if (_belongsTo(element, self.target)) { - return false; - } - // Events originating from a shadow DOM are re-targetted and `e.target` is the shadow host, // not the initial event target in the shadow tree. Note that not all events cross the // shadow boundary. @@ -995,7 +986,15 @@ element = initialEventTarget; } } + + // if the element has the class "mousetrap" then no need to stop + if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { + return false; + } + if (_belongsTo(element, self.target)) { + return false; + } // stop for input, select, and textarea return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; }; diff --git a/tests/test.mousetrap.js b/tests/test.mousetrap.js index e2c1d147..ae03fa85 100644 --- a/tests/test.mousetrap.js +++ b/tests/test.mousetrap.js @@ -104,6 +104,28 @@ describe('Mousetrap.bind', function () { expect(spy.callCount).to.equal(0, 'callback should not have fired'); }); + it("z key does fire when inside an input element with mousetrap class in an open shadow dom", function () { + var spy = sinon.spy(); + var shadowHost = document.createElement("div"); + var shadowRoot = shadowHost.attachShadow({ mode: "open" }); + document.body.appendChild(shadowHost); + + var inputElement = document.createElement("input"); + inputElement.className = 'mousetrap'; + shadowRoot.appendChild(inputElement); + expect(shadowHost.shadowRoot).to.equal( + shadowRoot, + "shadow root accessible" + ); + + Mousetrap.bind("z", spy); + KeyEvent.simulate("Z".charCodeAt(0), 90, [], inputElement, 1, { + shadowHost: shadowHost, + }); + document.body.removeChild(shadowHost); + expect(spy.callCount).to.equal(1, "callback should have fired once"); + }); + it('z key does fire when inside an input element in a closed shadow dom', function() { var spy = sinon.spy();