parse.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.update = exports.getParse = void 0;
  4. var domutils_1 = require("domutils");
  5. var domhandler_1 = require("domhandler");
  6. /**
  7. * Get the parse function with options.
  8. *
  9. * @param parser - The parser function.
  10. * @returns The parse function with options.
  11. */
  12. function getParse(parser) {
  13. /**
  14. * Parse a HTML string or a node.
  15. *
  16. * @param content - The HTML string or node.
  17. * @param options - The parser options.
  18. * @param isDocument - If `content` is a document.
  19. * @param context - The context node in the DOM tree.
  20. * @returns The parsed document node.
  21. */
  22. return function parse(content, options, isDocument, context) {
  23. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) {
  24. content = content.toString();
  25. }
  26. if (typeof content === 'string') {
  27. return parser(content, options, isDocument, context);
  28. }
  29. var doc = content;
  30. if (!Array.isArray(doc) && (0, domhandler_1.isDocument)(doc)) {
  31. // If `doc` is already a root, just return it
  32. return doc;
  33. }
  34. // Add conent to new root element
  35. var root = new domhandler_1.Document([]);
  36. // Update the DOM using the root
  37. update(doc, root);
  38. return root;
  39. };
  40. }
  41. exports.getParse = getParse;
  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. var 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 (var i = 0; i < arr.length; i++) {
  61. var 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. exports.update = update;
  78. //# sourceMappingURL=parse.js.map