├── .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('
test
'); 10 | console.log('contentBlocks', contentBlocks); 11 | 12 | contentBlocks = htmlToDraft('testlink
'); 25 | console.log('contentBlocks', contentBlocks); 26 | 27 | contentBlocks = htmlToDraft(`bold`); 28 | console.log('contentBlocks', contentBlocks); 29 | 30 | contentBlocks = htmlToDraft(`underline`); 31 | console.log('contentBlocks', contentBlocks); 32 | 33 | contentBlocks = htmlToDraft(`italic`); 34 | console.log('contentBlocks', contentBlocks); 35 | 36 | assert.equal(true, true); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /src/library/chunkBuilder.js: -------------------------------------------------------------------------------- 1 | import { OrderedSet, Map } from 'immutable'; 2 | 3 | const SPACE = ' '; 4 | const MAX_DEPTH = 4; 5 | 6 | export const getWhitespaceChunk = (entityId: ?string): Object => { 7 | return { 8 | text: SPACE, 9 | inlines: [new OrderedSet()], 10 | entities: [entityId], 11 | blocks: [], 12 | }; 13 | }; 14 | 15 | export const createTextChunk = (node: Object, inlineStyle: OrderedSet, entityId: number): Object => { 16 | const text = node.textContent; 17 | if (text.trim() === '') { 18 | return { chunk: getWhitespaceChunk(entityId) }; 19 | } 20 | return { 21 | chunk: { 22 | text, 23 | inlines: Array(text.length).fill(inlineStyle), 24 | entities: Array(text.length).fill(entityId), 25 | blocks: [], 26 | }, 27 | }; 28 | }; 29 | 30 | export const getSoftNewlineChunk = (): Object => { 31 | return { 32 | text: '\n', 33 | inlines: [new OrderedSet()], 34 | entities: new Array(1), 35 | blocks: [], 36 | }; 37 | }; 38 | 39 | export const getEmptyChunk = (): Object => { 40 | return { 41 | text: '', 42 | inlines: [], 43 | entities: [], 44 | blocks: [], 45 | }; 46 | }; 47 | 48 | export const getFirstBlockChunk = (blockType: string, data: Object): Object => { 49 | return { 50 | text: '', 51 | inlines: [], 52 | entities: [], 53 | blocks: [{ 54 | type: blockType, 55 | depth: 0, 56 | data: data || new Map({}), 57 | }], 58 | }; 59 | }; 60 | 61 | export const getBlockDividerChunk = (blockType: string, depth: number, data: Object): Object => { 62 | return { 63 | text: '\r', 64 | inlines: [], 65 | entities: [], 66 | blocks: [{ 67 | type: blockType, 68 | depth: Math.max(0, Math.min(MAX_DEPTH, depth)), 69 | data: data || new Map({}), 70 | }], 71 | }; 72 | }; 73 | 74 | export const getAtomicBlockChunk = (entityId: number): Object => { 75 | return { 76 | text: '\r ', 77 | inlines: [new OrderedSet()], 78 | entities: [entityId], 79 | blocks: [{ 80 | type: 'atomic', 81 | depth: 0, 82 | data: new Map({}) 83 | }], 84 | }; 85 | }; 86 | 87 | export const joinChunks = (A: Object, B: Object): Object => { 88 | return { 89 | text: A.text + B.text, 90 | inlines: A.inlines.concat(B.inlines), 91 | entities: A.entities.concat(B.entities), 92 | blocks: A.blocks.concat(B.blocks), 93 | }; 94 | } 95 | -------------------------------------------------------------------------------- /src/library/getAtomicEntities.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpuri/html-to-draftjs/b91ba0be2cb8b4c5a635335641d499725ce181cc/src/library/getAtomicEntities.js -------------------------------------------------------------------------------- /src/library/getBlockData.js: -------------------------------------------------------------------------------- 1 | import { Map } from 'immutable'; 2 | 3 | export default function getBlockData( 4 | node: Object 5 | ): Object { 6 | if (node.style.textAlign) { 7 | return new Map({ 8 | 'text-align': node.style.textAlign, 9 | }) 10 | } else if (node.style.marginLeft) { 11 | return new Map({ 12 | 'margin-left': node.style.marginLeft, 13 | }) 14 | } 15 | return undefined; 16 | } 17 | -------------------------------------------------------------------------------- /src/library/getBlockTypeForTag.js: -------------------------------------------------------------------------------- 1 | import { Map } from 'immutable'; 2 | 3 | const blockRenderMap = new Map({ 4 | 'header-one': { 5 | element: 'h1', 6 | }, 7 | 'header-two': { 8 | element: 'h2', 9 | }, 10 | 'header-three': { 11 | element: 'h3', 12 | }, 13 | 'header-four': { 14 | element: 'h4', 15 | }, 16 | 'header-five': { 17 | element: 'h5', 18 | }, 19 | 'header-six': { 20 | element: 'h6', 21 | }, 22 | 'unordered-list-item': { 23 | element: 'li', 24 | wrapper: 'ul', 25 | }, 26 | 'ordered-list-item': { 27 | element: 'li', 28 | wrapper: 'ol', 29 | }, 30 | blockquote: { 31 | element: 'blockquote', 32 | }, 33 | code: { 34 | element: 'pre', 35 | }, 36 | atomic: { 37 | element: 'figure', 38 | }, 39 | unstyled: { 40 | element: 'p', 41 | aliasedElements: ['div'] 42 | }, 43 | }); 44 | 45 | export default function getBlockTypeForTag( 46 | tag: string, 47 | lastList: ?string 48 | ): Object { 49 | const matchedTypes = blockRenderMap 50 | .filter(draftBlock => { 51 | return ( 52 | (draftBlock.element === tag && 53 | (!draftBlock.wrapper || draftBlock.wrapper === lastList)) || 54 | draftBlock.wrapper === tag || 55 | (draftBlock.aliasedElements && draftBlock.aliasedElements.indexOf(tag) > -1) 56 | )}) 57 | .keySeq() 58 | .toSet() 59 | .toArray(); 60 | 61 | if (matchedTypes.length === 1) { 62 | return matchedTypes[0]; 63 | } 64 | return undefined; 65 | } 66 | -------------------------------------------------------------------------------- /src/library/getEntityId.js: -------------------------------------------------------------------------------- 1 | import { Entity } from 'draft-js'; 2 | 3 | const getEntityId = (node) => { 4 | let entityId = undefined; 5 | if ( 6 | node instanceof HTMLAnchorElement 7 | ) { 8 | const entityConfig = {}; 9 | if (node.dataset && node.dataset.mention !== undefined) { 10 | entityConfig.url = node.href; 11 | entityConfig.text = node.innerHTML; 12 | entityConfig.value = node.dataset.value; 13 | entityId = Entity.__create( 14 | 'MENTION', 15 | 'IMMUTABLE', 16 | entityConfig, 17 | ); 18 | } else { 19 | entityConfig.url = node.getAttribute ? node.getAttribute('href') || node.href : node.href; 20 | entityConfig.title = node.innerHTML; 21 | entityConfig.targetOption = node.target; 22 | entityId = Entity.__create( 23 | 'LINK', 24 | 'MUTABLE', 25 | entityConfig, 26 | ); 27 | } 28 | } 29 | return entityId; 30 | } 31 | 32 | export default getEntityId; 33 | -------------------------------------------------------------------------------- /src/library/getSafeBodyFromHTML.js: -------------------------------------------------------------------------------- 1 | const getSafeBodyFromHTML = (html: string): ?Element => { 2 | var doc; 3 | var root = null; 4 | if ( 5 | document.implementation && 6 | document.implementation.createHTMLDocument 7 | ) { 8 | doc = document.implementation.createHTMLDocument('foo'); 9 | doc.documentElement.innerHTML = html; 10 | root = doc.getElementsByTagName('body')[0]; 11 | } 12 | return root; 13 | } 14 | 15 | export default getSafeBodyFromHTML; 16 | -------------------------------------------------------------------------------- /src/library/index.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | import { CharacterMetadata, ContentBlock, genKey, Entity } from 'draft-js'; 4 | import { Map, List, OrderedMap, OrderedSet } from 'immutable'; 5 | import getSafeBodyFromHTML from './getSafeBodyFromHTML'; 6 | import { 7 | createTextChunk, 8 | getSoftNewlineChunk, 9 | getEmptyChunk, 10 | getBlockDividerChunk, 11 | getFirstBlockChunk, 12 | getAtomicBlockChunk, 13 | joinChunks, 14 | } from './chunkBuilder'; 15 | import getBlockTypeForTag from './getBlockTypeForTag'; 16 | import processInlineTag from './processInlineTag'; 17 | import getBlockData from './getBlockData'; 18 | import getEntityId from './getEntityId'; 19 | 20 | const SPACE = ' '; 21 | const REGEX_NBSP = new RegExp(' ', 'g'); 22 | 23 | let firstBlock = true; 24 | 25 | type CustomChunkGenerator = (nodeName: string, node: HTMLElement) => ?{type: string, mutability: string, data: {}}; 26 | 27 | function genFragment( 28 | node: Object, 29 | inlineStyle: OrderedSet, 30 | depth: number, 31 | lastList: string, 32 | inEntity: number, 33 | customChunkGenerator: ?CustomChunkGenerator, 34 | ): Object { 35 | const nodeName = node.nodeName.toLowerCase(); 36 | 37 | if (customChunkGenerator) { 38 | const value = customChunkGenerator(nodeName, node); 39 | if (value) { 40 | const entityId = Entity.__create( 41 | value.type, 42 | value.mutability, 43 | value.data || {}, 44 | ); 45 | return { chunk: getAtomicBlockChunk(entityId) }; 46 | } 47 | } 48 | 49 | if (nodeName === '#text' && node.textContent !== '\n') { 50 | return createTextChunk(node, inlineStyle, inEntity); 51 | } 52 | 53 | if (nodeName === 'br') { 54 | return { chunk: getSoftNewlineChunk() }; 55 | } 56 | 57 | if ( 58 | nodeName === 'img' && 59 | node instanceof HTMLImageElement 60 | ) { 61 | const entityConfig = {}; 62 | entityConfig.src = node.getAttribute ? node.getAttribute('src') || node.src : node.src; 63 | entityConfig.alt = node.alt; 64 | entityConfig.height = node.style.height; 65 | entityConfig.width = node.style.width; 66 | if (node.style.float) { 67 | entityConfig.alignment = node.style.float; 68 | } 69 | const entityId = Entity.__create( 70 | 'IMAGE', 71 | 'MUTABLE', 72 | entityConfig, 73 | ); 74 | return { chunk: getAtomicBlockChunk(entityId) }; 75 | } 76 | 77 | if ( 78 | nodeName === 'video' && 79 | node instanceof HTMLVideoElement 80 | ) { 81 | const entityConfig = {}; 82 | entityConfig.src = node.getAttribute ? node.getAttribute('src') || node.src : node.src; 83 | entityConfig.alt = node.alt; 84 | entityConfig.height = node.style.height; 85 | entityConfig.width = node.style.width; 86 | if (node.style.float) { 87 | entityConfig.alignment = node.style.float; 88 | } 89 | const entityId = Entity.__create( 90 | 'VIDEO', 91 | 'MUTABLE', 92 | entityConfig, 93 | ); 94 | return { chunk: getAtomicBlockChunk(entityId) }; 95 | } 96 | 97 | if ( 98 | nodeName === 'iframe' && 99 | node instanceof HTMLIFrameElement 100 | ) { 101 | const entityConfig = {}; 102 | entityConfig.src = node.getAttribute ? node.getAttribute('src') || node.src : node.src; 103 | entityConfig.height = node.height; 104 | entityConfig.width = node.width; 105 | const entityId = Entity.__create( 106 | 'EMBEDDED_LINK', 107 | 'MUTABLE', 108 | entityConfig, 109 | ); 110 | return { chunk: getAtomicBlockChunk(entityId) }; 111 | } 112 | 113 | const blockType = getBlockTypeForTag(nodeName, lastList); 114 | 115 | let chunk; 116 | if (blockType) { 117 | if (nodeName === 'ul' || nodeName === 'ol') { 118 | lastList = nodeName; 119 | depth += 1; 120 | } else { 121 | if ( 122 | blockType !== 'unordered-list-item' && 123 | blockType !== 'ordered-list-item' 124 | ) { 125 | lastList = ''; 126 | depth = -1; 127 | } 128 | if (!firstBlock) { 129 | chunk = getBlockDividerChunk( 130 | blockType, 131 | depth, 132 | getBlockData(node) 133 | ); 134 | } else { 135 | chunk = getFirstBlockChunk( 136 | blockType, 137 | getBlockData(node) 138 | ); 139 | firstBlock = false; 140 | } 141 | } 142 | } 143 | if (!chunk) { 144 | chunk = getEmptyChunk(); 145 | } 146 | 147 | inlineStyle = processInlineTag(nodeName, node, inlineStyle); 148 | 149 | let child = node.firstChild; 150 | while (child) { 151 | const entityId = getEntityId(child); 152 | const { chunk: generatedChunk } = genFragment(child, inlineStyle, depth, lastList, (entityId || inEntity), customChunkGenerator); 153 | chunk = joinChunks(chunk, generatedChunk); 154 | const sibling = child.nextSibling; 155 | child = sibling; 156 | } 157 | return { chunk }; 158 | } 159 | 160 | function getChunkForHTML(html: string, customChunkGenerator: ?CustomChunkGenerator): Object { 161 | const sanitizedHtml = html.trim().replace(REGEX_NBSP, SPACE); 162 | const safeBody = getSafeBodyFromHTML(sanitizedHtml); 163 | if (!safeBody) { 164 | return null; 165 | } 166 | firstBlock = true; 167 | const { chunk } = genFragment(safeBody, new OrderedSet(), -1, '', undefined, customChunkGenerator); 168 | return { chunk }; 169 | } 170 | 171 | export default function htmlToDraft(html: string, customChunkGenerator: ?CustomChunkGenerator): Object { 172 | const chunkData = getChunkForHTML(html, customChunkGenerator); 173 | if (chunkData) { 174 | const { chunk } = chunkData; 175 | let entityMap = new OrderedMap({}); 176 | chunk.entities && chunk.entities.forEach(entity => { 177 | if (entity) { 178 | entityMap = entityMap.set(entity, Entity.__get(entity)); 179 | } 180 | }); 181 | let start = 0; 182 | return { 183 | contentBlocks: chunk.text.split('\r') 184 | .map( 185 | (textBlock, ii) => { 186 | const end = start + textBlock.length; 187 | const inlines = chunk && chunk.inlines.slice(start, end); 188 | const entities = chunk && chunk.entities.slice(start, end); 189 | const characterList = new List( 190 | inlines.map((style, index) => { 191 | const data = { style, entity: null }; 192 | if (entities[index]) { 193 | data.entity = entities[index]; 194 | } 195 | return CharacterMetadata.create(data); 196 | }), 197 | ); 198 | start = end; 199 | return new ContentBlock({ 200 | key: genKey(), 201 | type: (chunk && chunk.blocks[ii] && chunk.blocks[ii].type) || 'unstyled', 202 | depth: chunk && chunk.blocks[ii] && chunk.blocks[ii].depth, 203 | data: (chunk && chunk.blocks[ii] && chunk.blocks[ii].data) || new Map({}), 204 | text: textBlock, 205 | characterList, 206 | }); 207 | }, 208 | ), 209 | entityMap, 210 | }; 211 | } 212 | return null; 213 | } 214 | -------------------------------------------------------------------------------- /src/library/processInlineTag.js: -------------------------------------------------------------------------------- 1 | const inlineTags = { 2 | code: 'CODE', 3 | del: 'STRIKETHROUGH', 4 | em: 'ITALIC', 5 | strong: 'BOLD', 6 | ins: 'UNDERLINE', 7 | sub: 'SUBSCRIPT', 8 | sup: 'SUPERSCRIPT', 9 | }; 10 | 11 | export default function processInlineTag( 12 | tag: string, 13 | node: Object, 14 | currentStyle: Object 15 | ): Object { 16 | const styleToCheck = inlineTags[tag]; 17 | let inlineStyle; 18 | if (styleToCheck) { 19 | inlineStyle = currentStyle.add(styleToCheck).toOrderedSet(); 20 | } else if (node instanceof HTMLElement) { 21 | inlineStyle = currentStyle; 22 | const htmlElement = node; 23 | inlineStyle = inlineStyle.withMutations((style) => { 24 | const color = htmlElement.style.color; 25 | const backgroundColor = htmlElement.style.backgroundColor; 26 | const fontSize = htmlElement.style.fontSize; 27 | const fontFamily = htmlElement.style.fontFamily.replace(/^"|"$/g, ''); 28 | const fontWeight = htmlElement.style.fontWeight; 29 | const textDecoration = htmlElement.style.textDecoration; 30 | const fontStyle = htmlElement.style.fontStyle; 31 | if (color) { 32 | style.add(`color-${color.replace(/ /g, '')}`); 33 | } 34 | if (backgroundColor) { 35 | style.add(`bgcolor-${backgroundColor.replace(/ /g, '')}`); 36 | } 37 | if (fontSize) { 38 | style.add(`fontsize-${fontSize.replace(/px$/g, '')}`); 39 | } 40 | if (fontFamily) { 41 | style.add(`fontfamily-${fontFamily}`); 42 | } 43 | if(fontWeight === 'bold'){ 44 | style.add(inlineTags.strong) 45 | } 46 | if(textDecoration === 'underline'){ 47 | style.add(inlineTags.ins) 48 | } 49 | if(fontStyle === 'italic'){ 50 | style.add(inlineTags.em) 51 | } 52 | }).toOrderedSet(); 53 | } 54 | return inlineStyle; 55 | } 56 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | height: 100%; 3 | width: 100%; 4 | margin: 0; 5 | padding: 0; 6 | } 7 | .root { 8 | height: 100%; 9 | } 10 | .demo-content { 11 | height: 200px; 12 | width: 500px; 13 | } 14 | --------------------------------------------------------------------------------