testing-library / user-event

🐕 Simulate user events
https://testing-library.com/user-event
MIT License
2.19k stars 249 forks source link

fix/feat: dispatch clipboard events without active selection #1190

Open tommie-lie opened 10 months ago

tommie-lie commented 10 months ago

What:

Make the copy()and cut() functions more compatible with actual browser behaviour by always dispatching the respective events with an empty clipboardData event member and only adding the default behaviour iff the event was not preventDefault()ed.

Why:

At $WORK we are implementing custom copy and paste handlers on elements that are neither editable in the classic sense (e.g. not an <input> element) nor require classic selection (marking text with the cursor). These handlers convert a rich datastructure to different MIME types and add the data to the event's clipboardData. When pasting in our web application, we can read a custom MIME type and restore the rich data structure. When pasting externally to an application that only understands text, a reduced text version is pasted. This works perfectly in browsers!

Without this PR, user.copy() does not dispatch a copy event, because it only dispatches the event if there is text selected. This is not in conformance with browser behavior and also not in conformance with the Clipboard API and events spec.

How:

This pull request changes the implementation of copy() and paste() functions according to the Clipboard API and events spec. Specifically, the following changes were made:

Checklist:

Additional Notes: Unfortunately, this breaks existing behaviour :-/ I doubt users rely on this, because it does not match the browser's behavior and relying that the event is not dispatched if nothing is selected or that it has the current selection content already set would break the event handlers in a real environment. Still I want to mention that this is not really backwards compatible.

codesandbox-ci[bot] commented 10 months ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 9cfa857aab8b2abda3f4157f42d0fc0f15e4df22:

Sandbox Source
userEvent-dom Configuration
userEvent-react Configuration