saleor-dashboard/src/components/RichTextEditor/RichTextEditorContent.tsx

97 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-11-05 16:30:38 +00:00
import EditorJS, {
2020-11-20 09:44:50 +00:00
LogLevels,
2020-11-05 16:30:38 +00:00
OutputData,
ToolConstructable,
ToolSettings
} from "@editorjs/editorjs";
import Embed from "@editorjs/embed";
2020-11-05 16:30:38 +00:00
import Header from "@editorjs/header";
import List from "@editorjs/list";
import Paragraph from "@editorjs/paragraph";
2020-11-05 16:30:38 +00:00
import Quote from "@editorjs/quote";
import strikethroughIcon from "@saleor/icons/StrikethroughIcon";
import classNames from "classnames";
import createGenericInlineTool from "editorjs-inline-tool";
import React from "react";
import useStyles from "./styles";
export interface RichTextEditorContentProps {
className?: string;
data: OutputData;
onReady?: () => void;
}
const inlineToolbar = ["link", "bold", "italic", "strikethrough"];
2020-11-05 16:30:38 +00:00
export const tools: Record<string, ToolConstructable | ToolSettings> = {
embed: Embed,
2020-11-05 16:30:38 +00:00
header: {
class: Header,
config: {
defaultLevel: 1,
levels: [1, 2, 3]
},
inlineToolbar
},
list: {
class: List,
inlineToolbar
},
quote: {
class: Quote,
inlineToolbar
},
paragraph: {
class: Paragraph,
inlineToolbar
2020-11-05 16:30:38 +00:00
},
strikethrough: createGenericInlineTool({
sanitize: {
s: {}
},
shortcut: "CMD+S",
tagName: "s",
toolboxIcon: strikethroughIcon
})
};
const RichTextEditorContent: React.FC<RichTextEditorContentProps> = ({
className,
data,
onReady
}) => {
const classes = useStyles({});
const editor = React.useRef<EditorJS>();
const editorContainer = React.useRef<HTMLDivElement>();
React.useEffect(
() => {
if (data) {
editor.current = new EditorJS({
data,
holder: editorContainer.current,
2020-11-20 09:44:50 +00:00
logLevel: "ERROR" as LogLevels,
2020-11-05 16:30:38 +00:00
onReady,
readOnly: true,
tools
});
}
return editor.current?.destroy;
},
// Rerender editor only if changed from undefined to defined state
[data === undefined]
);
return (
<div
className={classNames(classes.editor, className)}
ref={editorContainer}
/>
);
};
RichTextEditorContent.displayName = "RichTextEditorContent";
export default RichTextEditorContent;