parse5-adapter.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. const opts = {
  15. scriptingEnabled: typeof options.scriptingEnabled === 'boolean'
  16. ? options.scriptingEnabled
  17. : true,
  18. treeAdapter: htmlparser2Adapter,
  19. sourceCodeLocationInfo: options.sourceCodeLocationInfo,
  20. };
  21. return isDocument
  22. ? parseDocument(content, opts)
  23. : parseFragment(context, content, opts);
  24. }
  25. const renderOpts = { treeAdapter: htmlparser2Adapter };
  26. /**
  27. * Renders the given DOM tree with `parse5` and returns the result as a string.
  28. *
  29. * @param dom - The DOM tree to render.
  30. * @returns The rendered document.
  31. */
  32. export function renderWithParse5(dom) {
  33. /*
  34. * `dom-serializer` passes over the special "root" node and renders the
  35. * node's children in its place. To mimic this behavior with `parse5`, an
  36. * equivalent operation must be applied to the input array.
  37. */
  38. const nodes = 'length' in dom ? dom : [dom];
  39. for (let index = 0; index < nodes.length; index += 1) {
  40. const node = nodes[index];
  41. if (isDocument(node)) {
  42. Array.prototype.splice.call(nodes, index, 1, ...node.children);
  43. }
  44. }
  45. let result = '';
  46. for (let index = 0; index < nodes.length; index += 1) {
  47. const node = nodes[index];
  48. result += serializeOuter(node, renderOpts);
  49. }
  50. return result;
  51. }
  52. //# sourceMappingURL=parse5-adapter.js.map