parse.js 2.3 KB

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