Last active
May 17, 2016 09:10
-
-
Save alexeygolev/72a21e5ea9dd092289d83b90a4926989 to your computer and use it in GitHub Desktop.
convertFromHtml in node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jsdom = require('jsdom').jsdom | |
const fs = require('fs') | |
const path = require('path') | |
const { | |
ContentState, | |
convertToRaw, | |
convertFromRaw, | |
} = require('draft-js') | |
const React = fs.readFileSync(path.join(__dirname, '../node_modules/react/dist/react.js')) | |
const ReactDOM = fs.readFileSync(path.join(__dirname, '../node_modules/react-dom/dist/react-dom.js')) | |
const Immutable = fs.readFileSync(path.join(__dirname, '../node_modules/immutable/dist/immutable.js')) | |
const Draft = fs.readFileSync(path.join(__dirname, '../node_modules/draft-js/dist/Draft.js')) | |
const browser = fs.readFileSync(path.join(__dirname, '../node_modules/babel-core/lib/api/browser.js')) | |
function convertFromHtml(x: string): Promise<Array<Object>> { | |
return new Promise((resolve, reject) => { | |
return jsdom.env({ | |
html: '<html><head><meta charset="utf-8" /></head><body></body></html>', | |
src: [ React, ReactDOM, Immutable, browser, Draft ], | |
done: (err: Error, window) => { | |
if(err) reject(err) | |
const { convertFromHTML, ContentState, convertToRaw } = window.Draft | |
const htmlBody = convertFromHTML(x) | |
const contentState = ContentState.createFromBlockArray(htmlBody) | |
const raw = convertToRaw(contentState) | |
resolve(raw) | |
}, | |
}) | |
}) | |
} | |
function transform(): Promise<Array<Object>> { | |
const body = `<b><span style="color: #00aeef;"> <h2><span style="color: #0076a4;">NEWS</span></h2> </span></b> <h3><span style="color: #111111;">Facebook makes U-turn on nudes after Paris ruling</span></h3> <a href="http://google.com">M</a> <h2><span style="color: #0076a4;">NEWS</span></h2> ` | |
return convertFromHtml(body) | |
.then(raw => { | |
return { | |
body: raw | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment