parse.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { removeElement } from 'domutils';
  2. import { Document, isDocument as checkIsDocument, } from 'domhandler';
  3. /**
  4. * Get the parse function with options.
  5. *
  6. * @param parser - The parser function.
  7. * @returns The parse function with options.
  8. */
  9. export function getParse(parser) {
  10. /**
  11. * Parse a HTML string or a node.
  12. *
  13. * @param content - The HTML string or node.
  14. * @param options - The parser options.
  15. * @param isDocument - If `content` is a document.
  16. * @param context - The context node in the DOM tree.
  17. * @returns The parsed document node.
  18. */
  19. return function parse(content, options, isDocument, context) {
  20. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) {
  21. content = content.toString();
  22. }
  23. if (typeof content === 'string') {
  24. return parser(content, options, isDocument, context);
  25. }
  26. const doc = content;
  27. if (!Array.isArray(doc) && checkIsDocument(doc)) {
  28. // If `doc` is already a root, just return it
  29. return doc;
  30. }
  31. // Add conent to new root element
  32. const root = new Document([]);
  33. // Update the DOM using the root
  34. update(doc, root);
  35. return root;
  36. };
  37. }
  38. /**
  39. * Update the dom structure, for one changed layer.
  40. *
  41. * @param newChilds - The new children.
  42. * @param parent - The new parent.
  43. * @returns The parent node.
  44. */
  45. export function update(newChilds, parent) {
  46. // Normalize
  47. const arr = Array.isArray(newChilds) ? newChilds : [newChilds];
  48. // Update parent
  49. if (parent) {
  50. parent.children = arr;
  51. }
  52. else {
  53. parent = null;
  54. }
  55. // Update neighbors
  56. for (let i = 0; i < arr.length; i++) {
  57. const node = arr[i];
  58. // Cleanly remove existing nodes from their previous structures.
  59. if (node.parent && node.parent.children !== arr) {
  60. removeElement(node);
  61. }
  62. if (parent) {
  63. node.prev = arr[i - 1] || null;
  64. node.next = arr[i + 1] || null;
  65. }
  66. else {
  67. node.prev = node.next = null;
  68. }
  69. node.parent = parent;
  70. }
  71. return parent;
  72. }
  73. //# sourceMappingURL=parse.js.map