You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

editOnFocus.js.flow 1.7 KiB

3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow strict-local
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. import type DraftEditor from "./DraftEditor.react";
  13. const EditorState = require("./EditorState");
  14. const UserAgent = require("fbjs/lib/UserAgent");
  15. function editOnFocus(editor: DraftEditor, e: SyntheticFocusEvent<>): void {
  16. const editorState = editor._latestEditorState;
  17. const currentSelection = editorState.getSelection();
  18. if (currentSelection.getHasFocus()) {
  19. return;
  20. }
  21. const selection = currentSelection.set('hasFocus', true);
  22. editor.props.onFocus && editor.props.onFocus(e); // When the tab containing this text editor is hidden and the user does a
  23. // find-in-page in a _different_ tab, Chrome on Mac likes to forget what the
  24. // selection was right after sending this focus event and (if you let it)
  25. // moves the cursor back to the beginning of the editor, so we force the
  26. // selection here instead of simply accepting it in order to preserve the
  27. // old cursor position. See https://crbug.com/540004.
  28. // But it looks like this is fixed in Chrome 60.0.3081.0.
  29. // Other browsers also don't have this bug, so we prefer to acceptSelection
  30. // when possible, to ensure that unfocusing and refocusing a Draft editor
  31. // doesn't preserve the selection, matching how textareas work.
  32. if (UserAgent.isBrowser('Chrome < 60.0.3081.0')) {
  33. editor.update(EditorState.forceSelection(editorState, selection));
  34. } else {
  35. editor.update(EditorState.acceptSelection(editorState, selection));
  36. }
  37. }
  38. module.exports = editOnFocus;