focus.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. require('../utils/dataTransfer/Clipboard.js');
  3. var getActiveElement = require('../utils/focus/getActiveElement.js');
  4. var isFocusable = require('../utils/focus/isFocusable.js');
  5. var findClosest = require('../utils/misc/findClosest.js');
  6. var updateSelectionOnFocus = require('./selection/updateSelectionOnFocus.js');
  7. var wrapEvent = require('./wrapEvent.js');
  8. // Browsers do not dispatch FocusEvent if the document does not have focus.
  9. // TODO: simulate FocusEvent in browsers
  10. /**
  11. * Focus closest focusable element.
  12. */ function focusElement(element) {
  13. const target = findClosest.findClosest(element, isFocusable.isFocusable);
  14. const activeElement = getActiveElement.getActiveElement(element.ownerDocument);
  15. if ((target !== null && target !== undefined ? target : element.ownerDocument.body) === activeElement) {
  16. return;
  17. } else if (target) {
  18. wrapEvent.wrapEvent(()=>target.focus());
  19. } else {
  20. wrapEvent.wrapEvent(()=>activeElement === null || activeElement === undefined ? undefined : activeElement.blur());
  21. }
  22. updateSelectionOnFocus.updateSelectionOnFocus(target !== null && target !== undefined ? target : element.ownerDocument.body);
  23. }
  24. function blurElement(element) {
  25. if (!isFocusable.isFocusable(element)) return;
  26. const wasActive = getActiveElement.getActiveElement(element.ownerDocument) === element;
  27. if (!wasActive) return;
  28. wrapEvent.wrapEvent(()=>element.blur());
  29. }
  30. exports.blurElement = blurElement;
  31. exports.focusElement = focusElement;