Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import { withRouter, RouteComponentProps } from 'react-router-dom';
- import Typography from '@material-ui/core/Typography';
- import { createStyles, Theme, makeStyles } from '@material-ui/core/styles';
- import { Editor as DraftEditor } from 'draft-js';
- import { EditorState as DraftEditorState } from 'draft-js';
- import { convertToRaw, convertFromRaw } from 'draft-js';
- import * as types from '../../common/types';
- import * as api from '../../common/api';
- const useStyles = makeStyles((theme: Theme) =>
- createStyles({
- root: {
- flexGrow: 1,
- paddingTop: theme.spacing(3),
- paddingLeft: '10%',
- paddingRight: '10%',
- paddingBottom: theme.spacing(3),
- fontSize: '16px'
- },
- title: {
- textAlign: 'center',
- },
- titleSpacing: {
- minHeight: '16px',
- },
- }),
- );
- interface IProps extends RouteComponentProps<{}> {
- section: types.ISection;
- }
- const UPDATE_TIMER = 1;
- const getTimestamp = function() {
- return Math.floor(Date.now() / 1000);
- }
- const useEditor() {
- const [lastUpdate, setLastUpdate] = React.useState(getTimestamp());
- const [editorState, setEditorState] = React.useState(DraftEditorState.createEmpty());
- const updateContent = () => {
- const contentState = editorState.getCurrentContent();
- const rawContent = convertToRaw(contentState);
- api.updateContent(props.section.content.id, rawContent);
- }
- React.useEffect(() => updateContent);
- const update = (editorState: DraftEditorState) => {
- setEditorState(editorState);
- if(getTimestamp() > lastUpdate + UPDATE_TIMER) {
- updateContent();
- setLastUpdate(getTimestamp());
- }
- }
- return [editorState, update];
- }
- const Editor: React.FC<IProps> = (props: IProps) => {
- const classes = useStyles();
- const [editorState, updateEditor] = useEditor();
- return (
- <div className={classes.root}>
- <Typography className={classes.title} variant="h5">{props.section.name}</Typography>
- <div className={classes.titleSpacing} />
- <DraftEditor editorState={editorState} onChange={updateEditor} />
- </div>
- );
- }
- export default withRouter(Editor);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement