Files
TheGame/packages/web/utils/stateFromHTML.ts
δυς f5295c3242 Reading and Writing Profile Info From Ceramic (#943)
This is being merged for further testing so as to not block the progress of `develop` & not require more rebases.
2022-01-25 16:51:53 -05:00

37 lines
1.1 KiB
TypeScript

import { ContentState, convertFromHTML } from 'draft-js';
async function serverDOMBuilder(): Promise<(html: string) => HTMLBodyElement> {
const jsdom = await import('jsdom');
const { JSDOM } = jsdom;
const {
document: jsdomDocument,
HTMLElement,
HTMLAnchorElement,
Node,
} = new JSDOM(`<!DOCTYPE html>`).window;
global.HTMLElement = HTMLElement;
global.HTMLAnchorElement = HTMLAnchorElement;
global.Node = Node;
const doc = jsdomDocument.implementation.createHTMLDocument('foo');
return (html: string) => {
doc.documentElement.innerHTML = html;
return doc.getElementsByTagName('body')[0];
};
}
export async function stateFromHTML(html: string): Promise<ContentState> {
// if DOMBuilder is undefined convertFromHTML will use the browser dom,
// hence we set DOMBuilder to undefined when document exist
const DOMBuilder =
typeof document === 'undefined' ? await serverDOMBuilder() : undefined;
const blocksFromHTML = convertFromHTML(html, DOMBuilder);
return ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap,
);
}