Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import { withRouter, RouteComponentProps } from 'react-router-dom';
  3.  
  4. import Typography from '@material-ui/core/Typography';
  5. import { createStyles, Theme, makeStyles } from '@material-ui/core/styles';
  6. import { Editor as DraftEditor } from 'draft-js';
  7. import { EditorState as DraftEditorState } from 'draft-js';
  8. import { convertToRaw, convertFromRaw } from 'draft-js';
  9.  
  10. import * as types from '../../common/types';
  11. import * as api from '../../common/api';
  12.  
  13. const useStyles = makeStyles((theme: Theme) =>
  14.   createStyles({
  15.     root: {
  16.       flexGrow: 1,
  17.       paddingTop: theme.spacing(3),
  18.       paddingLeft: '10%',
  19.       paddingRight: '10%',
  20.       paddingBottom: theme.spacing(3),
  21.       fontSize: '16px'
  22.     },
  23.     title: {
  24.       textAlign: 'center',
  25.     },
  26.     titleSpacing: {
  27.       minHeight: '16px',
  28.     },
  29.   }),
  30. );
  31.  
  32. interface IProps extends RouteComponentProps<{}> {
  33.   section: types.ISection;
  34. }
  35.  
  36. const UPDATE_TIMER = 1;
  37.  
  38. const getTimestamp = function() {
  39.   return Math.floor(Date.now() / 1000);
  40. }
  41.  
  42. const useEditor() {
  43.   const [lastUpdate, setLastUpdate] = React.useState(getTimestamp());
  44.   const [editorState, setEditorState] = React.useState(DraftEditorState.createEmpty());
  45.  
  46.   const updateContent = () => {
  47.     const contentState = editorState.getCurrentContent();
  48.     const rawContent = convertToRaw(contentState);
  49.     api.updateContent(props.section.content.id, rawContent);
  50.   }
  51.  
  52.   React.useEffect(() => updateContent);
  53.  
  54.   const update = (editorState: DraftEditorState) => {
  55.     setEditorState(editorState);
  56.  
  57.     if(getTimestamp() > lastUpdate + UPDATE_TIMER) {
  58.       updateContent();
  59.       setLastUpdate(getTimestamp());
  60.     }
  61.   }
  62.   return [editorState, update];
  63. }
  64.  
  65. const Editor: React.FC<IProps> = (props: IProps) => {
  66.   const classes = useStyles();
  67.   const [editorState, updateEditor] = useEditor();
  68.  
  69.   return (
  70.     <div className={classes.root}>
  71.       <Typography className={classes.title} variant="h5">{props.section.name}</Typography>
  72.       <div className={classes.titleSpacing} />
  73.       <DraftEditor editorState={editorState} onChange={updateEditor} />
  74.     </div>
  75.   );
  76. }
  77.  
  78. export default withRouter(Editor);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement