Files
TheGame/packages/web/utils/stateFromHTML.ts
Michiel Quellhorst 1d74d7beea Quest Editor Implemented (#760)
* added WYSIWYG Editor for quest description
rebased

* remove console output

* completed quest editor

* removed html-to-draftjs

* fix: file directory updates

* feat: js-dom added
rebase

* fix: fixed UI bugs

* fix: toast error message added for insufficient pSEED

* fix: replaced text with Box

* fix: limit description to 4 lines

* fix: removed incorrect condition from useUser hook

* fix: webpack 5 added in next.config

* fix: next.config webpack bug and rebased

* chore: remove comment

Co-authored-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>
2021-12-01 15:57:32 -05:00

38 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,
);
}