datocms-html-to-structured-text
Version:
Convert HTML (or a `hast` syntax tree) to a valid DatoCMS Structured Text `dast` document
59 lines • 2.28 kB
JavaScript
import minify from 'rehype-minify-whitespace';
import visitNode from './visit-node.js';
import visitChildren from './visit-children.js';
import { handlers } from './handlers.js';
import { fromParse5 } from 'hast-util-from-parse5';
import { fromDom } from 'hast-util-from-dom';
import { defaultMarks, } from 'datocms-structured-text-utils';
export async function htmlToStructuredText(html, options = {}) {
if (typeof DOMParser === 'undefined') {
throw new Error('DOMParser is not available. Consider using `parse5ToStructuredText` instead!');
}
const document = new DOMParser().parseFromString(html, 'text/html');
const tree = fromDom(document);
return hastToStructuredText(tree, options);
}
export async function parse5ToStructuredText(document, options = {}) {
const tree = fromParse5(document);
return hastToStructuredText(tree, options);
}
export async function hastToStructuredText(tree, options = {}) {
minify({ newlines: options.newlines === true })(tree);
const createNode = (type, props) => {
return { type, ...props };
};
if (typeof options.preprocess === 'function') {
options.preprocess(tree);
}
const rootNode = await visitNode(createNode, tree, {
parentNodeType: 'root',
parentNode: null,
defaultHandlers: handlers,
handlers: Object.assign({}, handlers, options.handlers || {}),
wrapText: true,
allowedBlocks: Array.isArray(options.allowedBlocks)
? options.allowedBlocks
: ['blockquote', 'code', 'heading', 'link', 'list'],
allowedMarks: Array.isArray(options.allowedMarks)
? options.allowedMarks
: defaultMarks,
allowedHeadingLevels: Array.isArray(options.allowedHeadingLevels)
? options.allowedHeadingLevels
: [1, 2, 3, 4, 5, 6],
global: {
baseUrl: null,
baseUrlFound: false,
...(options.shared || {}),
},
});
if (rootNode && !Array.isArray(rootNode) && rootNode.type === 'root') {
return {
schema: 'dast',
document: rootNode,
};
}
return null;
}
export { visitNode, visitChildren };
export * from './types.js';
//# sourceMappingURL=index.js.map