Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

202 строки
8.3 KiB

  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. *
  9. * @emails oncall+draft_js
  10. */
  11. 'use strict';
  12. var DraftModifier = require("./DraftModifier");
  13. var EditorState = require("./EditorState");
  14. var UserAgent = require("fbjs/lib/UserAgent");
  15. var getEntityKeyForSelection = require("./getEntityKeyForSelection");
  16. var isEventHandled = require("./isEventHandled");
  17. var isSelectionAtLeafStart = require("./isSelectionAtLeafStart");
  18. var nullthrows = require("fbjs/lib/nullthrows");
  19. var setImmediate = require("fbjs/lib/setImmediate"); // When nothing is focused, Firefox regards two characters, `'` and `/`, as
  20. // commands that should open and focus the "quickfind" search bar. This should
  21. // *never* happen while a contenteditable is focused, but as of v28, it
  22. // sometimes does, even when the keypress event target is the contenteditable.
  23. // This breaks the input. Special case these characters to ensure that when
  24. // they are typed, we prevent default on the event to make sure not to
  25. // trigger quickfind.
  26. var FF_QUICKFIND_CHAR = "'";
  27. var FF_QUICKFIND_LINK_CHAR = '/';
  28. var isFirefox = UserAgent.isBrowser('Firefox');
  29. function mustPreventDefaultForCharacter(character) {
  30. return isFirefox && (character == FF_QUICKFIND_CHAR || character == FF_QUICKFIND_LINK_CHAR);
  31. }
  32. /**
  33. * Replace the current selection with the specified text string, with the
  34. * inline style and entity key applied to the newly inserted text.
  35. */
  36. function replaceText(editorState, text, inlineStyle, entityKey, forceSelection) {
  37. var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), text, inlineStyle, entityKey);
  38. return EditorState.push(editorState, contentState, 'insert-characters', forceSelection);
  39. }
  40. /**
  41. * When `onBeforeInput` executes, the browser is attempting to insert a
  42. * character into the editor. Apply this character data to the document,
  43. * allowing native insertion if possible.
  44. *
  45. * Native insertion is encouraged in order to limit re-rendering and to
  46. * preserve spellcheck highlighting, which disappears or flashes if re-render
  47. * occurs on the relevant text nodes.
  48. */
  49. function editOnBeforeInput(editor, e) {
  50. if (editor._pendingStateFromBeforeInput !== undefined) {
  51. editor.update(editor._pendingStateFromBeforeInput);
  52. editor._pendingStateFromBeforeInput = undefined;
  53. }
  54. var editorState = editor._latestEditorState;
  55. var chars = e.data; // In some cases (ex: IE ideographic space insertion) no character data
  56. // is provided. There's nothing to do when this happens.
  57. if (!chars) {
  58. return;
  59. } // Allow the top-level component to handle the insertion manually. This is
  60. // useful when triggering interesting behaviors for a character insertion,
  61. // Simple examples: replacing a raw text ':)' with a smile emoji or image
  62. // decorator, or setting a block to be a list item after typing '- ' at the
  63. // start of the block.
  64. if (editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(chars, editorState, e.timeStamp))) {
  65. e.preventDefault();
  66. return;
  67. } // If selection is collapsed, conditionally allow native behavior. This
  68. // reduces re-renders and preserves spellcheck highlighting. If the selection
  69. // is not collapsed, we will re-render.
  70. var selection = editorState.getSelection();
  71. var selectionStart = selection.getStartOffset();
  72. var anchorKey = selection.getAnchorKey();
  73. if (!selection.isCollapsed()) {
  74. e.preventDefault();
  75. editor.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()), true));
  76. return;
  77. }
  78. var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()), false); // Bunch of different cases follow where we need to prevent native insertion.
  79. var mustPreventNative = false;
  80. if (!mustPreventNative) {
  81. // Browsers tend to insert text in weird places in the DOM when typing at
  82. // the start of a leaf, so we'll handle it ourselves.
  83. mustPreventNative = isSelectionAtLeafStart(editor._latestCommittedEditorState);
  84. }
  85. if (!mustPreventNative) {
  86. // Let's say we have a decorator that highlights hashtags. In many cases
  87. // we need to prevent native behavior and rerender ourselves --
  88. // particularly, any case *except* where the inserted characters end up
  89. // anywhere except exactly where you put them.
  90. //
  91. // Using [] to denote a decorated leaf, some examples:
  92. //
  93. // 1. 'hi #' and append 'f'
  94. // desired rendering: 'hi [#f]'
  95. // native rendering would be: 'hi #f' (incorrect)
  96. //
  97. // 2. 'x [#foo]' and insert '#' before 'f'
  98. // desired rendering: 'x #[#foo]'
  99. // native rendering would be: 'x [##foo]' (incorrect)
  100. //
  101. // 3. '[#foobar]' and insert ' ' between 'foo' and 'bar'
  102. // desired rendering: '[#foo] bar'
  103. // native rendering would be: '[#foo bar]' (incorrect)
  104. //
  105. // 4. '[#foo]' and delete '#' [won't use this beforeinput codepath though]
  106. // desired rendering: 'foo'
  107. // native rendering would be: '[foo]' (incorrect)
  108. //
  109. // 5. '[#foo]' and append 'b'
  110. // desired rendering: '[#foob]'
  111. // native rendering would be: '[#foob]'
  112. // (native insertion here would be ok for decorators like simple spans,
  113. // but not more complex decorators. To be safe, we need to prevent it.)
  114. //
  115. // It is safe to allow native insertion if and only if the full list of
  116. // decorator ranges matches what we expect native insertion to give, and
  117. // the range lengths have not changed. We don't need to compare the content
  118. // because the only possible mutation to consider here is inserting plain
  119. // text and decorators can't affect text content.
  120. var oldBlockTree = editorState.getBlockTree(anchorKey);
  121. var newBlockTree = newEditorState.getBlockTree(anchorKey);
  122. mustPreventNative = oldBlockTree.size !== newBlockTree.size || oldBlockTree.zip(newBlockTree).some(function (_ref) {
  123. var oldLeafSet = _ref[0],
  124. newLeafSet = _ref[1];
  125. // selectionStart is guaranteed to be selectionEnd here
  126. var oldStart = oldLeafSet.get('start');
  127. var adjustedStart = oldStart + (oldStart >= selectionStart ? chars.length : 0);
  128. var oldEnd = oldLeafSet.get('end');
  129. var adjustedEnd = oldEnd + (oldEnd >= selectionStart ? chars.length : 0);
  130. var newStart = newLeafSet.get('start');
  131. var newEnd = newLeafSet.get('end');
  132. var newDecoratorKey = newLeafSet.get('decoratorKey');
  133. return (// Different decorators
  134. oldLeafSet.get('decoratorKey') !== newDecoratorKey || // Different number of inline styles
  135. oldLeafSet.get('leaves').size !== newLeafSet.get('leaves').size || // Different effective decorator position
  136. adjustedStart !== newStart || adjustedEnd !== newEnd || // Decorator already existed and its length changed
  137. newDecoratorKey != null && newEnd - newStart !== oldEnd - oldStart
  138. );
  139. });
  140. }
  141. if (!mustPreventNative) {
  142. mustPreventNative = mustPreventDefaultForCharacter(chars);
  143. }
  144. if (!mustPreventNative) {
  145. mustPreventNative = nullthrows(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows(editorState.getDirectionMap()).get(anchorKey);
  146. }
  147. if (mustPreventNative) {
  148. e.preventDefault();
  149. newEditorState = EditorState.set(newEditorState, {
  150. forceSelection: true
  151. });
  152. editor.update(newEditorState);
  153. return;
  154. } // We made it all the way! Let the browser do its thing and insert the char.
  155. newEditorState = EditorState.set(newEditorState, {
  156. nativelyRenderedContent: newEditorState.getCurrentContent()
  157. }); // The native event is allowed to occur. To allow user onChange handlers to
  158. // change the inserted text, we wait until the text is actually inserted
  159. // before we actually update our state. That way when we rerender, the text
  160. // we see in the DOM will already have been inserted properly.
  161. editor._pendingStateFromBeforeInput = newEditorState;
  162. setImmediate(function () {
  163. if (editor._pendingStateFromBeforeInput !== undefined) {
  164. editor.update(editor._pendingStateFromBeforeInput);
  165. editor._pendingStateFromBeforeInput = undefined;
  166. }
  167. });
  168. }
  169. module.exports = editOnBeforeInput;