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.flow 11 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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
  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. import type { BlockNodeRecord } from "./BlockNodeRecord";
  18. import type ContentState from "./ContentState";
  19. import type { DraftBlockRenderMap } from "./DraftBlockRenderMap";
  20. import type { DraftDecoratorType } from "./DraftDecoratorType";
  21. import type { DraftInlineStyle } from "./DraftInlineStyle";
  22. import type EditorState from "./EditorState";
  23. import type SelectionState from "./SelectionState";
  24. import type { BidiDirection } from "fbjs/lib/UnicodeBidiDirection";
  25. const DraftEditorNode = require("./DraftEditorNode.react");
  26. const DraftOffsetKey = require("./DraftOffsetKey");
  27. const React = require("react");
  28. const Scroll = require("fbjs/lib/Scroll");
  29. const Style = require("fbjs/lib/Style");
  30. const getElementPosition = require("fbjs/lib/getElementPosition");
  31. const getScrollPosition = require("fbjs/lib/getScrollPosition");
  32. const getViewportDimensions = require("fbjs/lib/getViewportDimensions");
  33. const Immutable = require("immutable");
  34. const invariant = require("fbjs/lib/invariant");
  35. const isHTMLElement = require("./isHTMLElement");
  36. const SCROLL_BUFFER = 10;
  37. const {
  38. List
  39. } = Immutable; // we should harden up the bellow flow types to make them more strict
  40. type CustomRenderConfig = Object;
  41. type DraftRenderConfig = Object;
  42. type BlockRenderFn = (block: BlockNodeRecord) => ?Object;
  43. type BlockStyleFn = (block: BlockNodeRecord) => string;
  44. type Props = {
  45. block: BlockNodeRecord,
  46. blockProps?: Object,
  47. blockRenderMap: DraftBlockRenderMap,
  48. blockRendererFn: BlockRenderFn,
  49. blockStyleFn: BlockStyleFn,
  50. contentState: ContentState,
  51. customStyleFn: (style: DraftInlineStyle, block: BlockNodeRecord) => ?Object,
  52. customStyleMap: Object,
  53. decorator: ?DraftDecoratorType,
  54. direction: BidiDirection,
  55. editorKey: string,
  56. editorState: EditorState,
  57. forceSelection: boolean,
  58. selection: SelectionState,
  59. startIndent?: boolean,
  60. tree: List<any>,
  61. ...
  62. };
  63. /**
  64. * Return whether a block overlaps with either edge of the `SelectionState`.
  65. */
  66. const isBlockOnSelectionEdge = (selection: SelectionState, key: string): boolean => {
  67. return selection.getAnchorKey() === key || selection.getFocusKey() === key;
  68. };
  69. /**
  70. * We will use this helper to identify blocks that need to be wrapped but have siblings that
  71. * also share the same wrapper element, this way we can do the wrapping once the last sibling
  72. * is added.
  73. */
  74. const shouldNotAddWrapperElement = (block: BlockNodeRecord, contentState: ContentState): boolean => {
  75. const nextSiblingKey = block.getNextSiblingKey();
  76. return nextSiblingKey ? contentState.getBlockForKey(nextSiblingKey).getType() === block.getType() : false;
  77. };
  78. const applyWrapperElementToSiblings = (wrapperTemplate: *, Element: string, nodes: Array<React.Node>): Array<React.Node> => {
  79. const wrappedSiblings = []; // we check back until we find a sibbling that does not have same wrapper
  80. for (const sibling: any of nodes.reverse()) {
  81. if (sibling.type !== Element) {
  82. break;
  83. }
  84. wrappedSiblings.push(sibling);
  85. } // we now should remove from acc the wrappedSiblings and add them back under same wrap
  86. nodes.splice(nodes.indexOf(wrappedSiblings[0]), wrappedSiblings.length + 1);
  87. const childrenIs = wrappedSiblings.reverse();
  88. const key = childrenIs[0].key;
  89. nodes.push(React.cloneElement(wrapperTemplate, {
  90. key: `${key}-wrap`,
  91. 'data-offset-key': DraftOffsetKey.encode(key, 0, 0)
  92. }, childrenIs));
  93. return nodes;
  94. };
  95. const getDraftRenderConfig = (block: BlockNodeRecord, blockRenderMap: DraftBlockRenderMap): DraftRenderConfig => {
  96. const configForType = blockRenderMap.get(block.getType()) || blockRenderMap.get('unstyled');
  97. const wrapperTemplate = configForType.wrapper;
  98. const Element = configForType.element || blockRenderMap.get('unstyled').element;
  99. return {
  100. Element,
  101. wrapperTemplate
  102. };
  103. };
  104. const getCustomRenderConfig = (block: BlockNodeRecord, blockRendererFn: BlockRenderFn): CustomRenderConfig => {
  105. const customRenderer = blockRendererFn(block);
  106. if (!customRenderer) {
  107. return {};
  108. }
  109. const {
  110. component: CustomComponent,
  111. props: customProps,
  112. editable: customEditable
  113. } = customRenderer;
  114. return {
  115. CustomComponent,
  116. customProps,
  117. customEditable
  118. };
  119. };
  120. const getElementPropsConfig = (block: BlockNodeRecord, editorKey: string, offsetKey: string, blockStyleFn: BlockStyleFn, customConfig: *, ref: null | {|
  121. current: null | Element
  122. |}): Object => {
  123. let elementProps: Object = {
  124. 'data-block': true,
  125. 'data-editor': editorKey,
  126. 'data-offset-key': offsetKey,
  127. key: block.getKey(),
  128. ref
  129. };
  130. const customClass = blockStyleFn(block);
  131. if (customClass) {
  132. elementProps.className = customClass;
  133. }
  134. if (customConfig.customEditable !== undefined) {
  135. elementProps = { ...elementProps,
  136. contentEditable: customConfig.customEditable,
  137. suppressContentEditableWarning: true
  138. };
  139. }
  140. return elementProps;
  141. };
  142. class DraftEditorBlockNode extends React.Component<Props> {
  143. wrapperRef: {|
  144. current: null | Element
  145. |} = React.createRef<Element>();
  146. shouldComponentUpdate(nextProps: Props): boolean {
  147. const {
  148. block,
  149. direction,
  150. tree
  151. } = this.props;
  152. const isContainerNode = !block.getChildKeys().isEmpty();
  153. const 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
  154. // else if its a root node we avoid re-rendering by checking for block updates
  155. return isContainerNode || blockHasChanged;
  156. }
  157. /**
  158. * When a block is mounted and overlaps the selection state, we need to make
  159. * sure that the cursor is visible to match native behavior. This may not
  160. * be the case if the user has pressed `RETURN` or pasted some content, since
  161. * programatically creating these new blocks and setting the DOM selection
  162. * will miss out on the browser natively scrolling to that position.
  163. *
  164. * To replicate native behavior, if the block overlaps the selection state
  165. * on mount, force the scroll position. Check the scroll state of the scroll
  166. * parent, and adjust it to align the entire block to the bottom of the
  167. * scroll parent.
  168. */
  169. componentDidMount(): void {
  170. const selection = this.props.selection;
  171. const endKey = selection.getEndKey();
  172. if (!selection.getHasFocus() || endKey !== this.props.block.getKey()) {
  173. return;
  174. }
  175. const blockNode = this.wrapperRef.current;
  176. if (!blockNode) {
  177. // This Block Node was rendered without a wrapper element.
  178. return;
  179. }
  180. const scrollParent = Style.getScrollParent(blockNode);
  181. const scrollPosition = getScrollPosition(scrollParent);
  182. let scrollDelta;
  183. if (scrollParent === window) {
  184. const nodePosition = getElementPosition(blockNode);
  185. const nodeBottom = nodePosition.y + nodePosition.height;
  186. const viewportHeight = getViewportDimensions().height;
  187. scrollDelta = nodeBottom - viewportHeight;
  188. if (scrollDelta > 0) {
  189. window.scrollTo(scrollPosition.x, scrollPosition.y + scrollDelta + SCROLL_BUFFER);
  190. }
  191. } else {
  192. invariant(isHTMLElement(blockNode), 'blockNode is not an HTMLElement');
  193. const htmlBlockNode: HTMLElement = (blockNode: any);
  194. const blockBottom = htmlBlockNode.offsetHeight + htmlBlockNode.offsetTop;
  195. const scrollBottom = scrollParent.offsetHeight + scrollPosition.y;
  196. scrollDelta = blockBottom - scrollBottom;
  197. if (scrollDelta > 0) {
  198. Scroll.setTop(scrollParent, Scroll.getTop(scrollParent) + scrollDelta + SCROLL_BUFFER);
  199. }
  200. }
  201. }
  202. render(): React.Node {
  203. const {
  204. block,
  205. blockRenderMap,
  206. blockRendererFn,
  207. blockStyleFn,
  208. contentState,
  209. decorator,
  210. editorKey,
  211. editorState,
  212. customStyleFn,
  213. customStyleMap,
  214. direction,
  215. forceSelection,
  216. selection,
  217. tree
  218. } = this.props;
  219. let children = null;
  220. if (block.children.size) {
  221. children = block.children.reduce((acc, key) => {
  222. const offsetKey = DraftOffsetKey.encode(key, 0, 0);
  223. const child = contentState.getBlockForKey(key);
  224. const customConfig = getCustomRenderConfig(child, blockRendererFn);
  225. const Component = customConfig.CustomComponent || DraftEditorBlockNode;
  226. const {
  227. Element,
  228. wrapperTemplate
  229. } = getDraftRenderConfig(child, blockRenderMap);
  230. const elementProps = getElementPropsConfig(child, editorKey, offsetKey, blockStyleFn, customConfig, null);
  231. const childProps = { ...this.props,
  232. tree: editorState.getBlockTree(key),
  233. blockProps: customConfig.customProps,
  234. offsetKey,
  235. block: child
  236. };
  237. acc.push(React.createElement(Element, elementProps, <Component {...childProps} />));
  238. if (!wrapperTemplate || shouldNotAddWrapperElement(child, contentState)) {
  239. return acc;
  240. } // if we are here it means we are the last block
  241. // that has a wrapperTemplate so we should wrap itself
  242. // and all other previous siblings that share the same wrapper
  243. applyWrapperElementToSiblings(wrapperTemplate, Element, acc);
  244. return acc;
  245. }, []);
  246. }
  247. const blockKey = block.getKey();
  248. const offsetKey = DraftOffsetKey.encode(blockKey, 0, 0);
  249. const customConfig = getCustomRenderConfig(block, blockRendererFn);
  250. const Component = customConfig.CustomComponent;
  251. const blockNode = Component != null ? <Component {...this.props} tree={editorState.getBlockTree(blockKey)} blockProps={customConfig.customProps} offsetKey={offsetKey} block={block} /> : <DraftEditorNode block={block} children={children} contentState={contentState} customStyleFn={customStyleFn} customStyleMap={customStyleMap} decorator={decorator} direction={direction} forceSelection={forceSelection} hasSelection={isBlockOnSelectionEdge(selection, blockKey)} selection={selection} tree={tree} />;
  252. if (block.getParentKey()) {
  253. return blockNode;
  254. }
  255. const {
  256. Element
  257. } = getDraftRenderConfig(block, blockRenderMap);
  258. const elementProps = getElementPropsConfig(block, editorKey, offsetKey, blockStyleFn, customConfig, this.wrapperRef); // root block nodes needs to be wrapped
  259. return React.createElement(Element, elementProps, blockNode);
  260. }
  261. }
  262. module.exports = DraftEditorBlockNode;