├── .babelrc ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── config └── webpack.config.js ├── dist └── html-to-draftjs.js ├── package-lock.json ├── package.json ├── public ├── favicon.ico └── index.html ├── report.html ├── src ├── index.js ├── lib.js ├── library │ ├── __tests__ │ │ ├── .eslintrc │ │ └── mainTest.js │ ├── chunkBuilder.js │ ├── getAtomicEntities.js │ ├── getBlockData.js │ ├── getBlockTypeForTag.js │ ├── getEntityId.js │ ├── getSafeBodyFromHTML.js │ ├── index.js │ └── processInlineTag.js └── styles.css └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"], 3 | "plugins": [["transform-flow-strip-types"]] 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | node_modules 5 | 6 | # testing 7 | coverage 8 | 9 | # misc 10 | .DS_Store 11 | .env 12 | npm-debug.log 13 | 14 | #IntelliJ 15 | .idea 16 | 17 | stats.json -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | config 2 | src 3 | node_modules 4 | .babelrc 5 | .gitignore 6 | .npmignore 7 | yarn.lock 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Jyoti Puri 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HTML To DraftJS 2 | 3 | A library for converting plain HTML to DraftJS Editor content. 4 | Build for use with **[react-draft-wysiwyg](https://github.com/jpuri/react-draft-wysiwyg)**. 5 | 6 | ## Installation 7 | 8 | ``` 9 | npm install html-to-draftjs --save 10 | ``` 11 | 12 | ## Usage 13 | 14 | ``` 15 | import { EditorState, ContentState } from 'draft-js'; 16 | import htmlToDraft from 'html-to-draftjs'; 17 | 18 | const blocksFromHtml = htmlToDraft(this.props.content); 19 | const { contentBlocks, entityMap } = blocksFromHtml; 20 | const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap); 21 | const editorState = EditorState.createWithContent(contentState); 22 | ``` 23 | 24 | ### (optional) customChunkRenderer 25 | Use to define additional html nodes. Only supports atomic blocks. 26 | 27 | * _nodeName: string_ - the name of the node, in lowercase 28 | * _node: HTMLElement_ - the parsed node itself 29 | 30 | This renderer function is executed before any other html to draft conversion. 31 | Return nothing (or something falsy) to continue with the normal translation. 32 | 33 | Example: 34 | 35 | ``` 36 | htmlToDraft('
', (nodeName, node) => { 37 | if (nodeName === 'hr') { 38 | return { 39 | type: 'HORIZONTAL_RULE', 40 | mutability: 'MUTABLE', 41 | data: {} 42 | }; 43 | } 44 | }) 45 | ``` 46 | 47 | 48 | **Take Care:** Plz not use version `1.2.0` it has build issues. 49 | -------------------------------------------------------------------------------- /config/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); 4 | 5 | module.exports = { 6 | devtool: "source-map", 7 | entry: ["./src/library/index.js"], 8 | output: { 9 | path: path.join(__dirname, "../dist"), 10 | filename: "html-to-draftjs.js", 11 | library: "htmlToDraftjs", 12 | libraryTarget: "umd" 13 | }, 14 | optimization: { 15 | minimizer: [new UglifyJsPlugin()] 16 | }, 17 | externals: { 18 | "draft-js": "draft-js", 19 | immutable: "immutable" 20 | }, 21 | plugins: [ 22 | new webpack.DefinePlugin({ 23 | "process.env": { 24 | NODE_ENV: JSON.stringify("production") 25 | } 26 | }) 27 | ], 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.js$/, 32 | use: [{ loader: "babel-loader" }] 33 | } 34 | ] 35 | }, 36 | resolve: { 37 | extensions: [".js", ".json"] 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /dist/html-to-draftjs.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("immutable"),require("draft-js")):"function"==typeof define&&define.amd?define(["immutable","draft-js"],t):"object"==typeof exports?exports.htmlToDraftjs=t(require("immutable"),require("draft-js")):e.htmlToDraftjs=t(e.immutable,e["draft-js"])}(window,function(n,r){return o={},i.m=a=[function(e,t){e.exports=n},function(e,t){e.exports=r},function(e,t,n){e.exports=n(3)},function(e,t,n){"use strict";n.r(t);var v=n(1),u=n(0),s=function(e){var t,n=null;return document.implementation&&document.implementation.createHTMLDocument&&((t=document.implementation.createHTMLDocument("foo")).documentElement.innerHTML=e,n=t.getElementsByTagName("body")[0]),n},x=function(e,t,n){var r,i=e.textContent;return""===i.trim()?{chunk:(r=n,{text:" ",inlines:[new u.OrderedSet],entities:[r],blocks:[]})}:{chunk:{text:i,inlines:Array(i.length).fill(t),entities:Array(i.length).fill(n),blocks:[]}}},M=function(){return{text:"\n",inlines:[new u.OrderedSet],entities:new Array(1),blocks:[]}},k=function(){return{text:"",inlines:[],entities:[],blocks:[]}},E=function(e,t){return{text:"",inlines:[],entities:[],blocks:[{type:e,depth:0,data:t||new u.Map({})}]}},w=function(e,t,n){return{text:"\r",inlines:[],entities:[],blocks:[{type:e,depth:Math.max(0,Math.min(4,t)),data:n||new u.Map({})}]}},T=function(e){return{text:"\r ",inlines:[new u.OrderedSet],entities:[e],blocks:[{type:"atomic",depth:0,data:new u.Map({})}]}},L=function(e,t){return{text:e.text+t.text,inlines:e.inlines.concat(t.inlines),entities:e.entities.concat(t.entities),blocks:e.blocks.concat(t.blocks)}},A=new u.Map({"header-one":{element:"h1"},"header-two":{element:"h2"},"header-three":{element:"h3"},"header-four":{element:"h4"},"header-five":{element:"h5"},"header-six":{element:"h6"},"unordered-list-item":{element:"li",wrapper:"ul"},"ordered-list-item":{element:"li",wrapper:"ol"},blockquote:{element:"blockquote"},code:{element:"pre"},atomic:{element:"figure"},unstyled:{element:"p",aliasedElements:["div"]}});var O={code:"CODE",del:"STRIKETHROUGH",em:"ITALIC",strong:"BOLD",ins:"UNDERLINE",sub:"SUBSCRIPT",sup:"SUPERSCRIPT"};function S(e){return e.style.textAlign?new u.Map({"text-align":e.style.textAlign}):e.style.marginLeft?new u.Map({"margin-left":e.style.marginLeft}):void 0}var _=function(e){var t=void 0;if(e instanceof HTMLAnchorElement){var n={};t=e.dataset&&void 0!==e.dataset.mention?(n.url=e.href,n.text=e.innerHTML,n.value=e.dataset.value,v.Entity.__create("MENTION","IMMUTABLE",n)):(n.url=e.getAttribute&&e.getAttribute("href")||e.href,n.title=e.innerHTML,n.targetOption=e.target,v.Entity.__create("LINK","MUTABLE",n))}return t};n.d(t,"default",function(){return r});var d=" ",f=new RegExp(" ","g"),j=!0;function I(e,t,n,r,i,a){var o=e.nodeName.toLowerCase();if(a){var l=a(o,e);if(l){var c=v.Entity.__create(l.type,l.mutability,l.data||{});return{chunk:T(c)}}}if("#text"===o&&"\n"!==e.textContent)return x(e,t,i);if("br"===o)return{chunk:M()};if("img"===o&&e instanceof HTMLImageElement){var u={};u.src=e.getAttribute&&e.getAttribute("src")||e.src,u.alt=e.alt,u.height=e.style.height,u.width=e.style.width,e.style.float&&(u.alignment=e.style.float);var s=v.Entity.__create("IMAGE","MUTABLE",u);return{chunk:T(s)}}if("video"===o&&e instanceof HTMLVideoElement){var d={};d.src=e.getAttribute&&e.getAttribute("src")||e.src,d.alt=e.alt,d.height=e.style.height,d.width=e.style.width,e.style.float&&(d.alignment=e.style.float);var f=v.Entity.__create("VIDEO","MUTABLE",d);return{chunk:T(f)}}if("iframe"===o&&e instanceof HTMLIFrameElement){var m={};m.src=e.getAttribute&&e.getAttribute("src")||e.src,m.height=e.height,m.width=e.width;var p=v.Entity.__create("EMBEDDED_LINK","MUTABLE",m);return{chunk:T(p)}}var h,y=function(t,n){var e=A.filter(function(e){return e.element===t&&(!e.wrapper||e.wrapper===n)||e.wrapper===t||e.aliasedElements&&-1 2 | 3 | 4 | 5 | 6 | 7 | 16 | React App 17 | 18 | 19 |
20 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /report.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Webpack Bundle Analyzer 7 | 8 | 9 | 10 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { Editor } from 'react-draft-wysiwyg'; 4 | import { convertToRaw, ContentState, EditorState } from 'draft-js'; 5 | import draftToHtml from 'draftjs-to-html'; 6 | import htmlToDraft from './library'; 7 | import '../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; 8 | import './styles.css'; 9 | 10 | // in constructor, I use your code above, but I change outputEditorState to inputEditorState 11 | // in the first Editor, I use this.state.inputEditorState as editorState 12 | 13 | class Playground extends Component { 14 | 15 | // state = { 16 | // outputEditorState: undefined, 17 | // } 18 | 19 | constructor(props) { 20 | super(props) 21 | const html = ''; 22 | const contentBlock = htmlToDraft(html); 23 | if (contentBlock) { 24 | const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks, contentBlock.entityMap); 25 | const inputEditorState = EditorState.createWithContent(contentState); 26 | this.state = { 27 | inputEditorState, 28 | }; 29 | } 30 | } 31 | 32 | onInputEditorChange = (inputEditorState) => { 33 | console.log('into onInputEditorChange') 34 | // console.log('*****', inputEditorState.getCurrentContent()) 35 | const rawContent = convertToRaw(inputEditorState.getCurrentContent()); 36 | const html = draftToHtml(rawContent); 37 | console.log('html', html) 38 | const contentBlock = htmlToDraft(html); 39 | // console.log('1', contentBlock) 40 | // console.log('2', convertFromHTML(html) && convertFromHTML(html)) 41 | if (contentBlock) { 42 | const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks); 43 | const outputEditorState = EditorState.createWithContent(contentState); 44 | this.setState({ 45 | inputEditorState, 46 | outputEditorState, 47 | }); 48 | // console.log('1', inputEditorState.getCurrentContent().getBlocksAsArray()) 49 | // console.log('2', contentBlock.contentBlocks) 50 | } 51 | } 52 | 53 | render() { 54 | // console.log('*****', this.state.inputEditorState.getCurrentContent()) 55 | // value={this.state.inputEditorState && draftToHtml(convertToRaw(this.state.inputEditorState.getCurrentContent()))} 56 | return ( 57 |
58 |
59 | 76 |
77 |
78 |