focus.js 1.3 KB

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