Skip to content

Instantly share code, notes, and snippets.

@zhujinxuan
Created December 25, 2017 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhujinxuan/1ddaf3bea314f6cc5c04ecdb9c99830c to your computer and use it in GitHub Desktop.
Save zhujinxuan/1ddaf3bea314f6cc5c04ecdb9c99830c to your computer and use it in GitHub Desktop.
A naive solution for paste html to slatejs: convert classNames to inline style and wrap everything inside a div
import mergeStyle from "./mergeStyle/index.js";
/**
* A default parseHTML by Slate
*
* @param {String} html
* @return {Object}
*/
function slateDOMParser(html) {
if (typeof DOMParser === "undefined") {
throw new Error(
"The native `DOMParser` global which the `Html` serializer uses by default is not present in this environment. You must supply the `options.parseHtml` function instead."
);
}
return new DOMParser().parseFromString(html, "text/html");
}
/**
*
* A Parse with simple normalization
*
* @param {String} html
* @return {Object}
*/
function parseHTML(html) {
const parsed = slateDOMParser(html);
normalize(parsed);
return parsed.body;
}
function normalize(parsed) {
normalizeForInlineStyles(parsed);
normalizeInsideDIV(parsed);
}
function normalizeForInlineStyles(parsed) {
const { head, body } = parsed;
if (!head) {
return;
}
const styles = head.querySelectorAll("head>style");
for (let index = 0; index < styles.length; index++) {
const cssRules = Array.from(styles[index].sheet.cssRules).reverse();
cssRules.forEach(rule => {
console.log(rule);
const { selectorText, style } = rule;
if (selectorText) {
const selectedNodes = Array.from(body.querySelectorAll(selectorText));
selectedNodes.forEach(el => mergeStyle(el, style));
}
});
}
}
function normalizeInsideDIV(parsed) {
const body = parsed.body;
const bodyChildNodes = Array.from(body.childNodes);
bodyChildNodes.forEach(child => body.removeChild(child));
const div = parsed.createElement("div");
bodyChildNodes.forEach(child => div.appendChild(child));
body.appendChild(div);
}
export default parseHTML;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment