parse5-adapter.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { isDocument, } from 'domhandler';
  2. import { parse as parseDocument, parseFragment, serializeOuter } from 'parse5';
  3. import { adapter as htmlparser2Adapter } from 'parse5-htmlparser2-tree-adapter';
  4. /**
  5. * Parse the content with `parse5` in the context of the given `ParentNode`.
  6. *
  7. * @param content - The content to parse.
  8. * @param options - A set of options to use to parse.
  9. * @param isDocument - Whether to parse the content as a full HTML document.
  10. * @param context - The context in which to parse the content.
  11. * @returns The parsed content.
  12. */
  13. export function parseWithParse5(content, options, isDocument, context) {
  14. var _a;
  15. (_a = options.treeAdapter) !== null && _a !== void 0 ? _a : (options.treeAdapter = htmlparser2Adapter);
  16. if (options.scriptingEnabled !== false) {
  17. options.scriptingEnabled = true;
  18. }
  19. return isDocument
  20. ? parseDocument(content, options)
  21. : parseFragment(context, content, options);
  22. }
  23. const renderOpts = { treeAdapter: htmlparser2Adapter };
  24. /**
  25. * Renders the given DOM tree with `parse5` and returns the result as a string.
  26. *
  27. * @param dom - The DOM tree to render.
  28. * @returns The rendered document.
  29. */
  30. export function renderWithParse5(dom) {
  31. /*
  32. * `dom-serializer` passes over the special "root" node and renders the
  33. * node's children in its place. To mimic this behavior with `parse5`, an
  34. * equivalent operation must be applied to the input array.
  35. */
  36. const nodes = 'length' in dom ? dom : [dom];
  37. for (let index = 0; index < nodes.length; index += 1) {
  38. const node = nodes[index];
  39. if (isDocument(node)) {
  40. Array.prototype.splice.call(nodes, index, 1, ...node.children);
  41. }
  42. }
  43. let result = '';
  44. for (let index = 0; index < nodes.length; index += 1) {
  45. const node = nodes[index];
  46. result += serializeOuter(node, renderOpts);
  47. }
  48. return result;
  49. }
  50. //# sourceMappingURL=parse5-adapter.js.map