parse.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.update = void 0;
  4. var htmlparser2_1 = require("htmlparser2");
  5. var htmlparser2_adapter_1 = require("./parsers/htmlparser2-adapter");
  6. var parse5_adapter_1 = require("./parsers/parse5-adapter");
  7. var domhandler_1 = require("domhandler");
  8. /*
  9. * Parser
  10. */
  11. function parse(content, options, isDocument) {
  12. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) {
  13. content = content.toString();
  14. }
  15. if (typeof content === 'string') {
  16. return options.xmlMode || options._useHtmlParser2
  17. ? htmlparser2_adapter_1.parse(content, options)
  18. : parse5_adapter_1.parse(content, options, isDocument);
  19. }
  20. var doc = content;
  21. if (!Array.isArray(doc) && domhandler_1.isDocument(doc)) {
  22. // If `doc` is already a root, just return it
  23. return doc;
  24. }
  25. // Add conent to new root element
  26. var root = new domhandler_1.Document([]);
  27. // Update the DOM using the root
  28. update(doc, root);
  29. return root;
  30. }
  31. exports.default = parse;
  32. /**
  33. * Update the dom structure, for one changed layer.
  34. *
  35. * @param newChilds - The new children.
  36. * @param parent - The new parent.
  37. * @returns The parent node.
  38. */
  39. function update(newChilds, parent) {
  40. // Normalize
  41. var arr = Array.isArray(newChilds) ? newChilds : [newChilds];
  42. // Update parent
  43. if (parent) {
  44. parent.children = arr;
  45. }
  46. else {
  47. parent = null;
  48. }
  49. // Update neighbors
  50. for (var i = 0; i < arr.length; i++) {
  51. var node = arr[i];
  52. // Cleanly remove existing nodes from their previous structures.
  53. if (node.parent && node.parent.children !== arr) {
  54. htmlparser2_1.DomUtils.removeElement(node);
  55. }
  56. if (parent) {
  57. node.prev = arr[i - 1] || null;
  58. node.next = arr[i + 1] || null;
  59. }
  60. else {
  61. node.prev = node.next = null;
  62. }
  63. node.parent = parent;
  64. }
  65. return parent;
  66. }
  67. exports.update = update;