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.

DraftEditorBlockNode.react.js 13 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. * This file is a fork of DraftEditorBlock.react.js and DraftEditorContents.react.js
  12. *
  13. * This is unstable and not part of the public API and should not be used by
  14. * production systems. This file may be update/removed without notice.
  15. */
  16. 'use strict';
  17. var _assign = require("object-assign");
  18. function _extends() { _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  19. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  20. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  21. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
  22. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  23. var DraftEditorNode = require("./DraftEditorNode.react");
  24. var DraftOffsetKey = require("./DraftOffsetKey");
  25. var React = require("react");
  26. var Scroll = require("fbjs/lib/Scroll");
  27. var Style = require("fbjs/lib/Style");
  28. var getElementPosition = require("fbjs/lib/getElementPosition");
  29. var getScrollPosition = require("fbjs/lib/getScrollPosition");
  30. var getViewportDimensions = require("fbjs/lib/getViewportDimensions");
  31. var Immutable = require("immutable");
  32. var invariant = require("fbjs/lib/invariant");
  33. var isHTMLElement = require("./isHTMLElement");
  34. var SCROLL_BUFFER = 10;
  35. var List = Immutable.List; // we should harden up the bellow flow types to make them more strict
  36. /**
  37. * Return whether a block overlaps with either edge of the `SelectionState`.
  38. */
  39. var isBlockOnSelectionEdge = function isBlockOnSelectionEdge(selection, key) {
  40. return selection.getAnchorKey() === key || selection.getFocusKey() === key;
  41. };
  42. /**
  43. * We will use this helper to identify blocks that need to be wrapped but have siblings that
  44. * also share the same wrapper element, this way we can do the wrapping once the last sibling
  45. * is added.
  46. */
  47. var shouldNotAddWrapperElement = function shouldNotAddWrapperElement(block, contentState) {
  48. var nextSiblingKey = block.getNextSiblingKey();
  49. return nextSiblingKey ? contentState.getBlockForKey(nextSiblingKey).getType() === block.getType() : false;
  50. };
  51. var applyWrapperElementToSiblings = function applyWrapperElementToSiblings(wrapperTemplate, Element, nodes) {
  52. var wrappedSiblings = []; // we check back until we find a sibbling that does not have same wrapper
  53. var _iteratorNormalCompletion = true;
  54. var _didIteratorError = false;
  55. var _iteratorError = undefined;
  56. try {
  57. for (var _iterator = nodes.reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  58. var sibling = _step.value;
  59. if (sibling.type !== Element) {
  60. break;
  61. }
  62. wrappedSiblings.push(sibling);
  63. } // we now should remove from acc the wrappedSiblings and add them back under same wrap
  64. } catch (err) {
  65. _didIteratorError = true;
  66. _iteratorError = err;
  67. } finally {
  68. try {
  69. if (!_iteratorNormalCompletion && _iterator["return"] != null) {
  70. _iterator["return"]();
  71. }
  72. } finally {
  73. if (_didIteratorError) {
  74. throw _iteratorError;
  75. }
  76. }
  77. }
  78. nodes.splice(nodes.indexOf(wrappedSiblings[0]), wrappedSiblings.length + 1);
  79. var childrenIs = wrappedSiblings.reverse();
  80. var key = childrenIs[0].key;
  81. nodes.push(React.cloneElement(wrapperTemplate, {
  82. key: "".concat(key, "-wrap"),
  83. 'data-offset-key': DraftOffsetKey.encode(key, 0, 0)
  84. }, childrenIs));
  85. return nodes;
  86. };
  87. var getDraftRenderConfig = function getDraftRenderConfig(block, blockRenderMap) {
  88. var configForType = blockRenderMap.get(block.getType()) || blockRenderMap.get('unstyled');
  89. var wrapperTemplate = configForType.wrapper;
  90. var Element = configForType.element || blockRenderMap.get('unstyled').element;
  91. return {
  92. Element: Element,
  93. wrapperTemplate: wrapperTemplate
  94. };
  95. };
  96. var getCustomRenderConfig = function getCustomRenderConfig(block, blockRendererFn) {
  97. var customRenderer = blockRendererFn(block);
  98. if (!customRenderer) {
  99. return {};
  100. }
  101. var CustomComponent = customRenderer.component,
  102. customProps = customRenderer.props,
  103. customEditable = customRenderer.editable;
  104. return {
  105. CustomComponent: CustomComponent,
  106. customProps: customProps,
  107. customEditable: customEditable
  108. };
  109. };
  110. var getElementPropsConfig = function getElementPropsConfig(block, editorKey, offsetKey, blockStyleFn, customConfig, ref) {
  111. var elementProps = {
  112. 'data-block': true,
  113. 'data-editor': editorKey,
  114. 'data-offset-key': offsetKey,
  115. key: block.getKey(),
  116. ref: ref
  117. };
  118. var customClass = blockStyleFn(block);
  119. if (customClass) {
  120. elementProps.className = customClass;
  121. }
  122. if (customConfig.customEditable !== undefined) {
  123. elementProps = _objectSpread({}, elementProps, {
  124. contentEditable: customConfig.customEditable,
  125. suppressContentEditableWarning: true
  126. });
  127. }
  128. return elementProps;
  129. };
  130. var DraftEditorBlockNode =
  131. /*#__PURE__*/
  132. function (_React$Component) {
  133. _inheritsLoose(DraftEditorBlockNode, _React$Component);
  134. function DraftEditorBlockNode() {
  135. var _this;
  136. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  137. args[_key] = arguments[_key];
  138. }
  139. _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
  140. _defineProperty(_assertThisInitialized(_this), "wrapperRef", React.createRef());
  141. return _this;
  142. }
  143. var _proto = DraftEditorBlockNode.prototype;
  144. _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  145. var _this$props = this.props,
  146. block = _this$props.block,
  147. direction = _this$props.direction,
  148. tree = _this$props.tree;
  149. var isContainerNode = !block.getChildKeys().isEmpty();
  150. var blockHasChanged = block !== nextProps.block || tree !== nextProps.tree || direction !== nextProps.direction || isBlockOnSelectionEdge(nextProps.selection, nextProps.block.getKey()) && nextProps.forceSelection; // if we have children at this stage we always re-render container nodes
  151. // else if its a root node we avoid re-rendering by checking for block updates
  152. return isContainerNode || blockHasChanged;
  153. }
  154. /**
  155. * When a block is mounted and overlaps the selection state, we need to make
  156. * sure that the cursor is visible to match native behavior. This may not
  157. * be the case if the user has pressed `RETURN` or pasted some content, since
  158. * programatically creating these new blocks and setting the DOM selection
  159. * will miss out on the browser natively scrolling to that position.
  160. *
  161. * To replicate native behavior, if the block overlaps the selection state
  162. * on mount, force the scroll position. Check the scroll state of the scroll
  163. * parent, and adjust it to align the entire block to the bottom of the
  164. * scroll parent.
  165. */
  166. ;
  167. _proto.componentDidMount = function componentDidMount() {
  168. var selection = this.props.selection;
  169. var endKey = selection.getEndKey();
  170. if (!selection.getHasFocus() || endKey !== this.props.block.getKey()) {
  171. return;
  172. }
  173. var blockNode = this.wrapperRef.current;
  174. if (!blockNode) {
  175. // This Block Node was rendered without a wrapper element.
  176. return;
  177. }
  178. var scrollParent = Style.getScrollParent(blockNode);
  179. var scrollPosition = getScrollPosition(scrollParent);
  180. var scrollDelta;
  181. if (scrollParent === window) {
  182. var nodePosition = getElementPosition(blockNode);
  183. var nodeBottom = nodePosition.y + nodePosition.height;
  184. var viewportHeight = getViewportDimensions().height;
  185. scrollDelta = nodeBottom - viewportHeight;
  186. if (scrollDelta > 0) {
  187. window.scrollTo(scrollPosition.x, scrollPosition.y + scrollDelta + SCROLL_BUFFER);
  188. }
  189. } else {
  190. !isHTMLElement(blockNode) ? process.env.NODE_ENV !== "production" ? invariant(false, 'blockNode is not an HTMLElement') : invariant(false) : void 0;
  191. var htmlBlockNode = blockNode;
  192. var blockBottom = htmlBlockNode.offsetHeight + htmlBlockNode.offsetTop;
  193. var scrollBottom = scrollParent.offsetHeight + scrollPosition.y;
  194. scrollDelta = blockBottom - scrollBottom;
  195. if (scrollDelta > 0) {
  196. Scroll.setTop(scrollParent, Scroll.getTop(scrollParent) + scrollDelta + SCROLL_BUFFER);
  197. }
  198. }
  199. };
  200. _proto.render = function render() {
  201. var _this2 = this;
  202. var _this$props2 = this.props,
  203. block = _this$props2.block,
  204. blockRenderMap = _this$props2.blockRenderMap,
  205. blockRendererFn = _this$props2.blockRendererFn,
  206. blockStyleFn = _this$props2.blockStyleFn,
  207. contentState = _this$props2.contentState,
  208. decorator = _this$props2.decorator,
  209. editorKey = _this$props2.editorKey,
  210. editorState = _this$props2.editorState,
  211. customStyleFn = _this$props2.customStyleFn,
  212. customStyleMap = _this$props2.customStyleMap,
  213. direction = _this$props2.direction,
  214. forceSelection = _this$props2.forceSelection,
  215. selection = _this$props2.selection,
  216. tree = _this$props2.tree;
  217. var children = null;
  218. if (block.children.size) {
  219. children = block.children.reduce(function (acc, key) {
  220. var offsetKey = DraftOffsetKey.encode(key, 0, 0);
  221. var child = contentState.getBlockForKey(key);
  222. var customConfig = getCustomRenderConfig(child, blockRendererFn);
  223. var Component = customConfig.CustomComponent || DraftEditorBlockNode;
  224. var _getDraftRenderConfig = getDraftRenderConfig(child, blockRenderMap),
  225. Element = _getDraftRenderConfig.Element,
  226. wrapperTemplate = _getDraftRenderConfig.wrapperTemplate;
  227. var elementProps = getElementPropsConfig(child, editorKey, offsetKey, blockStyleFn, customConfig, null);
  228. var childProps = _objectSpread({}, _this2.props, {
  229. tree: editorState.getBlockTree(key),
  230. blockProps: customConfig.customProps,
  231. offsetKey: offsetKey,
  232. block: child
  233. });
  234. acc.push(React.createElement(Element, elementProps, React.createElement(Component, childProps)));
  235. if (!wrapperTemplate || shouldNotAddWrapperElement(child, contentState)) {
  236. return acc;
  237. } // if we are here it means we are the last block
  238. // that has a wrapperTemplate so we should wrap itself
  239. // and all other previous siblings that share the same wrapper
  240. applyWrapperElementToSiblings(wrapperTemplate, Element, acc);
  241. return acc;
  242. }, []);
  243. }
  244. var blockKey = block.getKey();
  245. var offsetKey = DraftOffsetKey.encode(blockKey, 0, 0);
  246. var customConfig = getCustomRenderConfig(block, blockRendererFn);
  247. var Component = customConfig.CustomComponent;
  248. var blockNode = Component != null ? React.createElement(Component, _extends({}, this.props, {
  249. tree: editorState.getBlockTree(blockKey),
  250. blockProps: customConfig.customProps,
  251. offsetKey: offsetKey,
  252. block: block
  253. })) : React.createElement(DraftEditorNode, {
  254. block: block,
  255. children: children,
  256. contentState: contentState,
  257. customStyleFn: customStyleFn,
  258. customStyleMap: customStyleMap,
  259. decorator: decorator,
  260. direction: direction,
  261. forceSelection: forceSelection,
  262. hasSelection: isBlockOnSelectionEdge(selection, blockKey),
  263. selection: selection,
  264. tree: tree
  265. });
  266. if (block.getParentKey()) {
  267. return blockNode;
  268. }
  269. var _getDraftRenderConfig2 = getDraftRenderConfig(block, blockRenderMap),
  270. Element = _getDraftRenderConfig2.Element;
  271. var elementProps = getElementPropsConfig(block, editorKey, offsetKey, blockStyleFn, customConfig, this.wrapperRef); // root block nodes needs to be wrapped
  272. return React.createElement(Element, elementProps, blockNode);
  273. };
  274. return DraftEditorBlockNode;
  275. }(React.Component);
  276. module.exports = DraftEditorBlockNode;