fennec-fe/src/commons/editor/vditor.tsx

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-04-18 11:18:29 +08:00
import { createStyles, FormControl, FormHelperText, FormLabel, makeStyles } from '@material-ui/core';
import { FieldHookConfig, useField } from 'formik';
import React, { FC, useEffect, useRef, useState } from 'react';
import Vditor from 'vditor';
import 'vditor/src/assets/scss/index.scss';
type Props = (FieldHookConfig<string>) & {
label?: string;
className?: string;
};
const useStyles = makeStyles((theme) =>
createStyles({
formControl: {
width: '100%',
},
})
);
export const Editor: FC<Props> = ({ label, className, ...props }) => {
const [field, meta, helpers] = useField(props);
const editor = useRef<HTMLDivElement>(null);
const [instance, setInstance] = useState<Vditor | null>(() => null);
const [containerKey] = useState(() => Math.random().toString(36).slice(2, 8));
useEffect(() => {
if (!editor.current) {
return;
}
const _instance = new Vditor(editor.current, {
cache: {
id: containerKey,
},
fullscreen: {
index: 1500,
},
value: meta.initialValue,
input: (val) => helpers.setValue(val),
blur: () => helpers.setTouched(true),
});
setInstance(_instance);
return () => {
instance?.destroy();
};
}, []);
const classes = useStyles();
return (
<FormControl className={classes.formControl}>
<FormLabel>{label}</FormLabel>
<div className={className} ref={editor} key={containerKey}></div>
{meta.error && <FormHelperText error={true}>{meta.error}</FormHelperText>}
</FormControl>
);
};