No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

hace 3 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 DraftOffsetKey = require("./DraftOffsetKey");
  14. var EditorState = require("./EditorState");
  15. var UserAgent = require("fbjs/lib/UserAgent");
  16. var _require = require("./draftKeyUtils"),
  17. notEmptyKey = _require.notEmptyKey;
  18. var findAncestorOffsetKey = require("./findAncestorOffsetKey");
  19. var keyCommandPlainBackspace = require("./keyCommandPlainBackspace");
  20. var nullthrows = require("fbjs/lib/nullthrows");
  21. var isGecko = UserAgent.isEngine('Gecko');
  22. var DOUBLE_NEWLINE = '\n\n';
  23. function onInputType(inputType, editorState) {
  24. switch (inputType) {
  25. case 'deleteContentBackward':
  26. return keyCommandPlainBackspace(editorState);
  27. }
  28. return editorState;
  29. }
  30. /**
  31. * This function serves two purposes
  32. *
  33. * 1. To update the editorState and call onChange method with the new
  34. * editorState. This editorState is calculated in editOnBeforeInput but the
  35. * onChange method is not called with the new state until this method does it.
  36. * It is done to handle a specific case where certain character inputs might
  37. * be replaced with something else. E.g. snippets ('rc' might be replaced
  38. * with boilerplate code for react component). More information on the
  39. * exact problem can be found here -
  40. * https://github.com/facebook/draft-js/commit/07892ba479bd4dfc6afd1e0ed179aaf51cd138b1
  41. *
  42. * 2. intended to handle spellcheck and autocorrect changes,
  43. * which occur in the DOM natively without any opportunity to observe or
  44. * interpret the changes before they occur.
  45. *
  46. * The `input` event fires in contentEditable elements reliably for non-IE
  47. * browsers, immediately after changes occur to the editor DOM. Since our other
  48. * handlers override or otherwise handle cover other varieties of text input,
  49. * the DOM state should match the model in all controlled input cases. Thus,
  50. * when an `input` change leads to a DOM/model mismatch, the change should be
  51. * due to a spellcheck change, and we can incorporate it into our model.
  52. */
  53. function editOnInput(editor, e) {
  54. if (editor._pendingStateFromBeforeInput !== undefined) {
  55. editor.update(editor._pendingStateFromBeforeInput);
  56. editor._pendingStateFromBeforeInput = undefined;
  57. } // at this point editor is not null for sure (after input)
  58. var castedEditorElement = editor.editor;
  59. var domSelection = castedEditorElement.ownerDocument.defaultView.getSelection();
  60. var anchorNode = domSelection.anchorNode,
  61. isCollapsed = domSelection.isCollapsed;
  62. var isNotTextOrElementNode = (anchorNode === null || anchorNode === void 0 ? void 0 : anchorNode.nodeType) !== Node.TEXT_NODE && (anchorNode === null || anchorNode === void 0 ? void 0 : anchorNode.nodeType) !== Node.ELEMENT_NODE;
  63. if (isNotTextOrElementNode) {
  64. // TODO: (t16149272) figure out context for this change
  65. return;
  66. }
  67. if (anchorNode.nodeType === Node.TEXT_NODE && (anchorNode.previousSibling !== null || anchorNode.nextSibling !== null)) {
  68. // When typing at the beginning of a visual line, Chrome splits the text
  69. // nodes into two. Why? No one knows. This commit is suspicious:
  70. // https://chromium.googlesource.com/chromium/src/+/a3b600981286b135632371477f902214c55a1724
  71. // To work around, we'll merge the sibling text nodes back into this one.
  72. var span = anchorNode.parentNode;
  73. anchorNode.nodeValue = span.textContent;
  74. for (var child = span.firstChild; child !== null; child = child.nextSibling) {
  75. if (child !== anchorNode) {
  76. span.removeChild(child);
  77. }
  78. }
  79. }
  80. var domText = anchorNode.textContent;
  81. var editorState = editor._latestEditorState;
  82. var offsetKey = nullthrows(findAncestorOffsetKey(anchorNode));
  83. var _DraftOffsetKey$decod = DraftOffsetKey.decode(offsetKey),
  84. blockKey = _DraftOffsetKey$decod.blockKey,
  85. decoratorKey = _DraftOffsetKey$decod.decoratorKey,
  86. leafKey = _DraftOffsetKey$decod.leafKey;
  87. var _editorState$getBlock = editorState.getBlockTree(blockKey).getIn([decoratorKey, 'leaves', leafKey]),
  88. start = _editorState$getBlock.start,
  89. end = _editorState$getBlock.end;
  90. var content = editorState.getCurrentContent();
  91. var block = content.getBlockForKey(blockKey);
  92. var modelText = block.getText().slice(start, end); // Special-case soft newlines here. If the DOM text ends in a soft newline,
  93. // we will have manually inserted an extra soft newline in DraftEditorLeaf.
  94. // We want to remove this extra newline for the purpose of our comparison
  95. // of DOM and model text.
  96. if (domText.endsWith(DOUBLE_NEWLINE)) {
  97. domText = domText.slice(0, -1);
  98. } // No change -- the DOM is up to date. Nothing to do here.
  99. if (domText === modelText) {
  100. // This can be buggy for some Android keyboards because they don't fire
  101. // standard onkeydown/pressed events and only fired editOnInput
  102. // so domText is already changed by the browser and ends up being equal
  103. // to modelText unexpectedly.
  104. // Newest versions of Android support the dom-inputevent-inputtype
  105. // and we can use the `inputType` to properly apply the state changes.
  106. /* $FlowFixMe inputType is only defined on a draft of a standard.
  107. * https://w3c.github.io/input-events/#dom-inputevent-inputtype */
  108. var inputType = e.nativeEvent.inputType;
  109. if (inputType) {
  110. var newEditorState = onInputType(inputType, editorState);
  111. if (newEditorState !== editorState) {
  112. editor.restoreEditorDOM();
  113. editor.update(newEditorState);
  114. return;
  115. }
  116. }
  117. return;
  118. }
  119. var selection = editorState.getSelection(); // We'll replace the entire leaf with the text content of the target.
  120. var targetRange = selection.merge({
  121. anchorOffset: start,
  122. focusOffset: end,
  123. isBackward: false
  124. });
  125. var entityKey = block.getEntityAt(start);
  126. var entity = notEmptyKey(entityKey) ? content.getEntity(entityKey) : null;
  127. var entityType = entity != null ? entity.getMutability() : null;
  128. var preserveEntity = entityType === 'MUTABLE'; // Immutable or segmented entities cannot properly be handled by the
  129. // default browser undo, so we have to use a different change type to
  130. // force using our internal undo method instead of falling through to the
  131. // native browser undo.
  132. var changeType = preserveEntity ? 'spellcheck-change' : 'apply-entity';
  133. var newContent = DraftModifier.replaceText(content, targetRange, domText, block.getInlineStyleAt(start), preserveEntity ? block.getEntityAt(start) : null);
  134. var anchorOffset, focusOffset, startOffset, endOffset;
  135. if (isGecko) {
  136. // Firefox selection does not change while the context menu is open, so
  137. // we preserve the anchor and focus values of the DOM selection.
  138. anchorOffset = domSelection.anchorOffset;
  139. focusOffset = domSelection.focusOffset;
  140. startOffset = start + Math.min(anchorOffset, focusOffset);
  141. endOffset = startOffset + Math.abs(anchorOffset - focusOffset);
  142. anchorOffset = startOffset;
  143. focusOffset = endOffset;
  144. } else {
  145. // Browsers other than Firefox may adjust DOM selection while the context
  146. // menu is open, and Safari autocorrect is prone to providing an inaccurate
  147. // DOM selection. Don't trust it. Instead, use our existing SelectionState
  148. // and adjust it based on the number of characters changed during the
  149. // mutation.
  150. var charDelta = domText.length - modelText.length;
  151. startOffset = selection.getStartOffset();
  152. endOffset = selection.getEndOffset();
  153. anchorOffset = isCollapsed ? endOffset + charDelta : startOffset;
  154. focusOffset = endOffset + charDelta;
  155. } // Segmented entities are completely or partially removed when their
  156. // text content changes. For this case we do not want any text to be selected
  157. // after the change, so we are not merging the selection.
  158. var contentWithAdjustedDOMSelection = newContent.merge({
  159. selectionBefore: content.getSelectionAfter(),
  160. selectionAfter: selection.merge({
  161. anchorOffset: anchorOffset,
  162. focusOffset: focusOffset
  163. })
  164. });
  165. editor.update(EditorState.push(editorState, contentWithAdjustedDOMSelection, changeType));
  166. }
  167. module.exports = editOnInput;