Skip to content

Not touched, and not clicked component gets a ghost mousedown event #11530

Closed

Description

@baharev

The deployed (minimal, trimmed down) app is at:

http://www.baharev.info/sandbox/eventbug/

and the entire source code is at:

https://github.com/baharev/eventbug

Clicking or touching either square should make the clicked / touched square disappear, but only that square. Everything works as intended on my desktop machine both in Chrome and in Firefox. It also shows the correct behavior in Safari on iOS (and I don't care about IE or Edge).

The following triggers the bug in Chrome, either on an Android tablet, or on my desktop machine when emulating a hand-held device. Reload the app, and touch or click the top (blue) square: Both squares disappear, and in the console log I see that the not clicked, and not touched bottom green square received a spurious mousedown event (which then deleted it).

There is touch-action: none; in the app.css applied on the squares. If I didn't use it, I would get the following warning in Chrome when emulating a hand-held device:

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See: https://www.chromestatus.com/features/5093566007214080

With touch-action: none; (the way it is in the deployed app), this warning goes away.

  1. Is the ghost mousedown event due to a bug in my code?
  2. Or is it a bug in React?
  3. Or is it a bug in Chrome?
  4. How can I resolve this issue? (I am looking for a workaround if the bug is not in my code.)

Activity

  1. gaearon commented on Nov 12, 2017

    @gaearon
    Collaborator

    Have you tried to write similar code without React to determine if this is reproducible with just DOM APIs?

  2. baharev commented on Nov 12, 2017

    @baharev
    Author

    No, sorry, I haven't. I am a beginner, just learning these things in my free time.

  3. bonusrk commented on Nov 13, 2017

    @bonusrk

    I can try to handle it, if nobody do it before.

  4. gaearon commented on Nov 13, 2017

    @gaearon
    Collaborator

    @bonusrk

    If you'd like to help please try to create a reproducing case without React. Then we can see if it's React causing the issue or not.

  5. baharev commented on Nov 13, 2017

    @baharev
    Author

    @gaearon I already asked the same question at StackOverflow. Someone has tried to reproduce the bug with jQuery only, although all attempts have failed so far.

    https://jsfiddle.net/3efsgd8z/3/

    However, I am not sure whether the two approaches are comparable; failing to reproduce this bug with jQuery only does not mean the bug is not in Chrome.

  6. gaearon commented on Nov 13, 2017

    @gaearon
    Collaborator

    We should try to repro with vanilla DOM API.

  7. bonusrk commented on Nov 13, 2017

    @bonusrk

    So here it is:
    https://github.com/bonusrk/nonReact-test

    Thats what i've found:
    Chrome 61.0.3163.100
    Win10 (also can try on Mac, if needed)
    Chrome Dev Tools for mobile

    As our issue starter made 2 functions, i also made them seperate
    As we know, ontouchstart invokes before click and mousedown events.

    As i investigated mousedown invokes very fast after ontouchstart, and this second event invokes on current mouse position, so if we move mouse pretty fast from the block, the second block will not be deleted.

    If we just touch first block, we can se in console, that second event invokes on the same coords, where the newblock appears at that time, so mousedown event get it as his target(and delete)

    e.preventDefault on function onMouseDown(e) prevent this situation (and every other actions in onMouseDown function as well, so i cant say, that it is a solution)

    Anyway this stuff happens in vanilla js.

    As our issue starter said he is new to all this, i've made maximum basic code:

    const boxes = document.getElementsByClassName('box')
    console.log(boxes)
    
    //click handler
    function onMouseDown(e) {
      e.preventDefault()//this wont stop double delete
      console.log('I am CLICK target Id===>', e.target.id)
      //click event info
      console.log('EVENT TYPE ===>', e.type, ', EVENT X ===>', e.clientX, ', EVENT Y ===>', e.clientY)
      const id = e.target.id
      //as we do not have any more link to element, this will delete it
      document.getElementById(id).remove()
    }
    
    //ontouchstart handler
    function onTouchStart(e) {
      // e.preventDefault()  //This stops double delete
    
      //Use 'touches' object to get touch event data
      console.log('I am TOUCHSTART target ID ===>', e.touches[0].target.id)
      console.log('EVENT TYPE ===>', e.type, ', EVENT X ===>', e.touches[0].pageX, ', EVENT Y ===>', e.touches[0].pageX)
      const id = e.touches[0].target.id
    
      //delete for touch events
      document.getElementById(id).remove()
    }
    
    //Add eventListener for click
    Array.from(boxes).forEach(function (item, i, arr) {
      item.addEventListener('mousedown', onMouseDown)
    })
    
    // Add eventListener for touch
    Array.from(boxes).forEach(function (item, i, arr) {
      item.addEventListener('touchstart', onTouchStart)
    })
    
  8. gaearon commented on Nov 13, 2017

    @gaearon
    Collaborator

    Seems like it's not a React bug then?

  9. bonusrk commented on Nov 13, 2017

    @bonusrk

    Yes and i can assume even more-it is chrome specific problem, i think.

  10. baharev commented on Nov 13, 2017

    @baharev
    Author

    This vanilla JS solution behaves differently in Safari (on iPhone) than the React solution: Both squares disappear in Safari with this JS implementation whereas the React solution works the way I wanted it to work. Strange.

  11. bonusrk commented on Nov 13, 2017

    @bonusrk

    It is well known safari event flow-you need to use both prevenDefault and stopPropagation to make safari make thing in your way. And it is also seems to be browser-specific problem.

  12. baharev commented on Nov 13, 2017

    @baharev
    Author

    @bonusrk I am sorry, I am completely lost at this point. Why is this line:

    https://github.com/bonusrk/nonReact-test/blob/7675c19a97bd9cc6d8d8b7dcefef0d9f2c99f42b/script.js#L30

    in comment?

    In my React code I do call e.preventDefault() on touch start. And if I move that line out of comments in your code, then the bug disappears too. Sorry, I am afraid I do not understand something here: As I see it, in the equivalent vanilla JS code, that line should not be in comments, and then the bug would no longer be reproducible in vanilla JS.

  13. bonusrk commented on Nov 13, 2017

    @bonusrk

    I've commented it to let this bug happens, to show that bug appears in vanilla js. And yes, if uncomment lines bug will disappear.

  14. 18 remaining items

  15. gaearon commented on Aug 16, 2018

    @gaearon
    Collaborator

    @baharev It was quite confusing that you pushed the workaround to master. I cloned your repository and it took a while to figure out that I need to roll a few commits back to reproduce. :-)

  16. baharev commented on Aug 16, 2018

    @baharev
    Author

    @gaearon I am very sorry for that. :( My apologies.

    So, what's the verdict with this issue?

  17. gaearon commented on Aug 16, 2018

    @gaearon
    Collaborator

    The issue appears to be caused by React using event delegation. (Which is better for performance than attaching every handler.)

    Here's an example with addEventListener on the nodes themselves:

    <!DOCTYPE html>
    <html lang="en">
      <style>
        html, body {
          width: 100%;
          height: 100%;
        }
        .box {
          width: 100px;
          height: 100px;
          margin: 10px;
          touch-action: none;
        }
      </style>
      <body>
        <div>
          <div class="tile">
            <div class="box" style="background-color: blue"></div>
          </div>
          <div class="tile">
            <div class="box" style="background-color: green"></div>
          </div>
        </div>
      </body>
      <script>
        const tiles = document.querySelectorAll('.tile');
        tiles.forEach((tile) => {
          tile.addEventListener('touchstart', e => {
            e.preventDefault();
            tile.remove();
          });
          tile.addEventListener('mousedown', e => {
            tile.remove();
          });
        })
      </script>
    </html>

    You can see that Chrome respects e.preventDefault() on the touchstart event handler.

    Here's the same example with using event delegation:

    <!DOCTYPE html>
    <html lang="en">
      <style>
        html, body {
          width: 100%;
          height: 100%;
        }
    
        .box {
          width: 100px;
          height: 100px;
          margin: 10px;
          touch-action: none;
        }
      </style>
      <body>
        <div>
          <div class="tile">
            <div class="box" style="background-color: blue"></div>
          </div>
          <div class="tile">
            <div class="box" style="background-color: green"></div>
          </div>
        </div>
      </body>
      <script>
        document.addEventListener('touchstart', e => {
          e.preventDefault();
          e.target.remove();
        });
        document.addEventListener('mousedown', e => {
          e.target.remove();
        });
      </script>
    </html>

    You can see that Chrome doesn't respect e.preventDefault() in touchstart when it's attached to the document. This might be a Chrome bug — please feel free to file another report with these reproducing cases. Or maybe this is intentional (is #1254 related?). I don't fully understand what the browser's intended behavior is.

    What's interesting to me is that attaching to document.body.firstChild appears to be sufficient. So this will probably get resolved by itself when we do #2043.


    Regardless, the workaround is to attach a local event listener manually. #11530 (comment) is right in spirit but I don't understand why it needs to be so complicated. In React, when you want to touch the DOM manually, you can use a ref. Here's an example fix using React 16.3+ ref API:

    --- a/src/components/App.js
    +++ b/src/components/App.js
    @@ -9,12 +9,17 @@ const swallow = (e) => {
     }
     
     class Tile extends PureComponent {
    +  node = React.createRef();
     
       constructor(props) {
         super(props)
         this.toggle = this.toggle.bind(this)
       }
     
    +  componentDidMount() {
    +    this.node.current.ontouchstart = this.toggle;
    +  }
    +
       toggle(e) {
         swallow(e)
         console.log('id: ', this.props.id)
    @@ -27,8 +32,8 @@ class Tile extends PureComponent {
       render() {
         return (
           <div className={`tile`}
    +        ref={this.node}
             onMouseDown={this.toggle}
    -        onTouchStart={this.toggle}
             onTouchEnd={swallow}>
             <div className="box" style={{backgroundColor: this.props.id}}> </div>
           </div>

    (Note I reused toggle but it might be confusing that sometimes it receives a native and sometimes a synthetic event. In real code I'd probably duplicate it or extract common logic outside.)

    Hope this helps! I'll close because there's nothing directly actionable for us, and the workaround is simple enough.

  18. baharev commented on Aug 17, 2018

    @baharev
    Author

    @gaearon Perfect, thank you very much for the detailed explanation!

  19. gaearon commented on Aug 10, 2020

    @gaearon
    Collaborator

    We're changing React to attach events to roots in 17 which should fix it.

  20. baharev commented on Aug 10, 2020

    @baharev
    Author

    @gaearon That would be great, thanks for the info! This issue is still causing me a lot of pain in my projects, even with the workaround. It would be great to have a proper solution.

  21. gaearon commented on Aug 10, 2020

    @gaearon
    Collaborator

    react@next and react-dom@next have the new behavior so please give it a try (and let us know if doesn't work as expected).

  22. baharev commented on Aug 11, 2020

    @baharev
    Author

    @gaearon I did not report it, but your workaround also solved another issue on iOS with double tap zoom. (So another issue in a different browser.)

    I only have preliminary results so far. I have tested React 17.0 Release Candidate in:

    • Chrome 84 on Android 6,
    • Safari 12.1.2 on iOS 12.4.6,
    • in a large, non-trivial React project,
    • thorough manual testing, natively, on the physical device.

    Obviously, this testing goes way beyond this issue, but I would like to know whether React 17 will break anything in my projects.

    All seems fine so far.

    However, please wait for the results on iOS 9.3.6. I have run into two very painful to debug issues in that environment. I won't have access to this particular device before Friday.

    Could you give a rough estimate when you plan to release React 17, please?

    I greatly appreciate your help.

  23. gaearon commented on Aug 11, 2020

    @gaearon
    Collaborator

    I was thinking in a week or so.

  24. baharev commented on Aug 13, 2020

    @baharev
    Author

    @gaearon Manually tested the same large, non-trivial React project on:

    • iOS 9.3.6 (a really old iPad),
    • IE 11 (desktop),
    • Edge 18 (desktop).

    All seems fine.

    Many thanks for your help, and for letting me know that this issue has been resolved.

  25. gaearon commented on Aug 13, 2020

    @gaearon
    Collaborator

    Thanks for verifying!

  26. baharev commented on Nov 3, 2020

    @baharev
    Author

    @gaearon This is embarrassing: One thing I did not test in August was the original, minimal example, and guess what, it still shows the old, buggy behaviour. Please consider re-opening this issue.

    I did test some of my projects in August, but not all of them. The old bugs re-appeared after I removed your workaround in all of my projects.

    The latest source code of the minimal example with React 17 is here:

    https://github.com/baharev/ghost-click

    The deployment of this code, showing the buggy behaviour, is here:

    https://www.baharev.info/sandbox/ghost-click/index.html

    Expected behaviour: Clicking or touching either square should make the clicked / touched square disappear, but only that square.

    The following triggers the bug in Chrome, either on an Android tablet, or on my desktop machine when emulating a hand-held device. Reload the app, and touch or click the top (blue) square: Both squares disappear, which should not happen.

    New since 2017: I cannot get rid of the following error message in Chrome:

    Unable to preventDefault inside passive event listener invocation.

    Adding touch-action: none; back then made this error message disappear. As of today, I cannot get rid of this error message.

    Tried in index.js:

    const root = document.getElementById('root')
    root.addEventListener("touchstart", () => {}, {passive: false});
    

    and also in app.css:

    #root {
      touch-action: none;
    }
    

    but they seem to have no effect; this error message persists. (I double-checked in DevTools that the event listener is there, and the CSS style is also being applied.)

    Any help is greatly appreciated.

  27. baharev commented on Nov 3, 2020

    @baharev
    Author

    @gaearon I grabbed your second code snippet from 2018, reproducing the issue with the vanilla DOM API.

    The only notable change is that I pass {passive: false} as the third argument to document.addEventListener('touchstart', ...) call and ta-dah: Problem solved, the code behaves at it should. It was sort of documented in 2019 here.

    The touch-action: none; does not seem to work with respect to the blocking/passive event listeners, or I am doing something wrong. In any case, I deleted it from the CSS.

    So, your slightly modified code from 2018 is below. Try changing {passive: false} to {passive: true} and you will get the bad behaviour:

    <!DOCTYPE html>
    <html lang="en">
      <style>
        html, body {
          background-color: lightgrey;
          width: 100%;
          height: 100%;
        }
        .box {
          width: 100px;
          height: 100px;
          margin: 10px;
        }
      </style>
      <body>
        <div>
          <div class="tile">
            <div class="box" style="background-color: blue"></div>
          </div>
          <div class="tile">
            <div class="box" style="background-color: green"></div>
          </div>
        </div>
      </body>
      <script>
        document.addEventListener('touchstart', e => {
          e.preventDefault();
          e.target.remove();
        }, {passive: false});
        document.addEventListener('mousedown', e => {
          e.preventDefault();
          e.target.remove();
        });
      </script>
    </html>

    How can I achieve something like this in React, without a ref to the underlying DOM node?

    In other words, how do I fix the React code, linked in my previous comment?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions