Guest User

Untitled

a guest
May 16th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import { Component } from 'react';
  2. const { AtomicBlockUtils, EditorState, SelectionState, Modifier } = window.DraftJS
  3.  
  4.  
  5. // The source gathers data for new entities that are being added in the Draftail editor
  6. // It is invoked only when an new embed is inserted by the user
  7. export class TextSource extends Component {
  8.  
  9. componentDidMount() {
  10. const { editorState, entityType, onComplete } = this.props;
  11.  
  12. const content = editorState.getCurrentContent();
  13. const contentWithEntity = content.createEntity(entityType.type, 'MUTABLE', {
  14. text: '',
  15. });
  16. const entityKey = contentWithEntity.getLastCreatedEntityKey();
  17. const nextState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' ');
  18. onComplete(nextState);
  19. }
  20.  
  21. render() {
  22. return null;
  23. }
  24. }
  25.  
  26.  
  27. // The block is used to render the entity in the editor
  28. // It may receive props:
  29. // * from the source component when first created
  30. // * from the server side when reloaded from the database
  31. export class TextBlock extends Component {
  32. constructor(props) {
  33. super(props)
  34. const data = props.blockProps.entity.getData()
  35. this.state = {
  36. text: data.text,
  37. }
  38. }
  39.  
  40. handleTextChange = e => {
  41. const { text } = this.state
  42. this.setState({
  43. text: e.target.value
  44. })
  45. }
  46.  
  47. saveText = e => {
  48. // Update editor ContentState
  49. const { block, blockProps } = this.props
  50. const { editorState, onChange } = blockProps
  51. onChange(updateBlockEntity(editorState, block, {
  52. text: this.state.text,
  53. }))
  54. }
  55.  
  56. render() {
  57. const data = this.props.blockProps.entity.getData()
  58. const { text } = this.state
  59. return (
  60. <div>
  61. <p>Saved text is "{ data.text }"</p>
  62. <input
  63. name="title"
  64. type="text"
  65. onChange={this.handleTextChange}
  66. value={text}
  67. />
  68. <button onClick={this.saveText}>Submit</button>
  69. </div>
  70. )
  71. }
  72. }
  73.  
  74.  
  75. // Update a block's data in the WYSIWYG editor, nicked from DraftUtils source code
  76. const updateBlockEntity = (editorState, block, data) => {
  77. const content = editorState.getCurrentContent();
  78. let nextContent = content.mergeEntityData(block.getEntityAt(0), data);
  79. nextContent = Modifier.mergeBlockData(
  80. nextContent,
  81. new SelectionState({
  82. anchorKey: block.getKey(),
  83. anchorOffset: 0,
  84. focusKey: block.getKey(),
  85. focusOffset: block.getLength(),
  86. }),
  87. {},
  88. );
  89. return EditorState.push(editorState, nextContent, 'apply-entity');
  90. }
Add Comment
Please, Sign In to add comment