prepareDocument.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { dispatchDOMEvent } from '../event/dispatchEvent.js';
  2. import { isElementType } from '../utils/misc/isElementType.js';
  3. import '../utils/dataTransfer/Clipboard.js';
  4. import { getInitialValue, clearInitialValue } from './UI.js';
  5. import '@testing-library/dom';
  6. import { prepareValueInterceptor, prepareSelectionInterceptor, prepareRangeTextInterceptor } from './interceptor.js';
  7. const isPrepared = Symbol('Node prepared with document state workarounds');
  8. function prepareDocument(document) {
  9. if (document[isPrepared]) {
  10. return;
  11. }
  12. document.addEventListener('focus', (e)=>{
  13. const el = e.target;
  14. prepareElement(el);
  15. }, {
  16. capture: true,
  17. passive: true
  18. });
  19. // Our test environment defaults to `document.body` as `activeElement`.
  20. // In other environments this might be `null` when preparing.
  21. // istanbul ignore else
  22. if (document.activeElement) {
  23. prepareElement(document.activeElement);
  24. }
  25. document.addEventListener('blur', (e)=>{
  26. const el = e.target;
  27. const initialValue = getInitialValue(el);
  28. if (initialValue !== undefined) {
  29. if (el.value !== initialValue) {
  30. dispatchDOMEvent(el, 'change');
  31. }
  32. clearInitialValue(el);
  33. }
  34. }, {
  35. capture: true,
  36. passive: true
  37. });
  38. document[isPrepared] = isPrepared;
  39. }
  40. function prepareElement(el) {
  41. if (el[isPrepared]) {
  42. return;
  43. }
  44. if (isElementType(el, [
  45. 'input',
  46. 'textarea'
  47. ])) {
  48. prepareValueInterceptor(el);
  49. prepareSelectionInterceptor(el);
  50. prepareRangeTextInterceptor(el);
  51. }
  52. el[isPrepared] = isPrepared;
  53. }
  54. export { prepareDocument };