Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from "react";
- import { convertToRaw, convertFromRaw } from "draft-js";
- import { convertFromHTML, convertToHTML } from "draft-convert";
- import {
- DraftailEditor,
- BLOCK_TYPE,
- INLINE_STYLE,
- ENTITY_TYPE
- } from "draftail";
- import "draft-js/dist/Draft.css";
- import "draftail/dist/draftail.css";
- class HTMLEditorComponent extends Component {
- exporterConfig = {
- blockToHTML: block => {
- if (block.type === BLOCK_TYPE.BLOCKQUOTE) {
- return <blockquote />;
- }
- // Discard atomic blocks, as they get converted based on their entity.
- if (block.type === BLOCK_TYPE.ATOMIC) {
- return {
- start: "",
- end: ""
- };
- }
- return null;
- },
- entityToHTML: (entity, originalText) => {
- if (entity.type === ENTITY_TYPE.LINK) {
- return <a href={entity.data.url}>{originalText}</a>;
- }
- if (entity.type === ENTITY_TYPE.IMAGE) {
- return <img src={entity.data.src} alt={entity.data.alt} />;
- }
- if (entity.type === ENTITY_TYPE.HORIZONTAL_RULE) {
- return <hr />;
- }
- return originalText;
- }
- };
- importerConfig = {
- htmlToEntity: (nodeName, node, createEntity) => {
- // a tags will become LINK entities, marked as mutable, with only the URL as data.
- if (nodeName === "a") {
- return createEntity(ENTITY_TYPE.LINK, "MUTABLE", {
- url: node.href
- });
- }
- if (nodeName === "img") {
- return createEntity(ENTITY_TYPE.IMAGE, "IMMUTABLE", {
- src: node.src
- });
- }
- if (nodeName === "hr") {
- return createEntity(
- ENTITY_TYPE.HORIZONTAL_RULE,
- "IMMUTABLE",
- {}
- );
- }
- return null;
- },
- htmlToBlock: nodeName => {
- if (nodeName === "hr" || nodeName === "img") {
- // "atomic" blocks is how Draft.js structures block-level entities.
- return "atomic";
- }
- return null;
- }
- };
- fromHTML = html => convertToRaw(convertFromHTML(this.importerConfig)(html));
- toHTML = raw =>
- raw ? convertToHTML(this.exporterConfig)(convertFromRaw(raw)) : "";
- onSave = content => {
- this.props.handleSave(this.props.fieldName, this.toHTML(content));
- };
- render() {
- return (
- <DraftailEditor
- rawContentState={this.fromHTML(this.props.contentValue) || null}
- onSave={this.onSave}
- blockTypes={[
- { type: BLOCK_TYPE.ORDERED_LIST_ITEM },
- { type: BLOCK_TYPE.UNORDERED_LIST_ITEM }
- ]}
- inlineStyles={[
- { type: INLINE_STYLE.BOLD },
- { type: INLINE_STYLE.ITALIC },
- { type: INLINE_STYLE.UNDERLINE }
- ]}
- // entityTypes={[{ type: ENTITY_TYPE.HORIZONTAL_RULE }]}
- />
- );
- }
- }
- export default HTMLEditorComponent;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement