updateSelectionOnFocus.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import '../../utils/dataTransfer/Clipboard.js';
  2. import { getContentEditable } from '../../utils/edit/isContentEditable.js';
  3. import { hasOwnSelection } from '../../utils/focus/selection.js';
  4. // The browser implementation seems to have changed.
  5. // When focus is inside <input type="text"/>,
  6. // Chrome updates Selection to be collapsed at the position of the input element.
  7. // TODO: update implementation to match that of current browsers
  8. /**
  9. * Reset the Document Selection when moving focus into an element
  10. * with own selection implementation.
  11. */ function updateSelectionOnFocus(element) {
  12. const selection = element.ownerDocument.getSelection();
  13. /* istanbul ignore if */ if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) {
  14. return;
  15. }
  16. // If the focus moves inside an element with own selection implementation,
  17. // the document selection will be this element.
  18. // But if the focused element is inside a contenteditable,
  19. // 1) a collapsed selection will be retained.
  20. // 2) other selections will be replaced by a cursor
  21. // 2.a) at the start of the first child if it is a text node
  22. // 2.b) at the start of the contenteditable.
  23. if (hasOwnSelection(element)) {
  24. const contenteditable = getContentEditable(selection.focusNode);
  25. if (contenteditable) {
  26. if (!selection.isCollapsed) {
  27. var _contenteditable_firstChild;
  28. const focusNode = ((_contenteditable_firstChild = contenteditable.firstChild) === null || _contenteditable_firstChild === undefined ? undefined : _contenteditable_firstChild.nodeType) === 3 ? contenteditable.firstChild : contenteditable;
  29. selection.setBaseAndExtent(focusNode, 0, focusNode, 0);
  30. }
  31. } else {
  32. selection.setBaseAndExtent(element, 0, element, 0);
  33. }
  34. }
  35. }
  36. export { updateSelectionOnFocus };