prepareDocument.js 1.7 KB

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