DOMElement.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = exports.serialize = exports.test = void 0;
  6. var _markup = require('./lib/markup');
  7. /**
  8. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  9. *
  10. * This source code is licensed under the MIT license found in the
  11. * LICENSE file in the root directory of this source tree.
  12. */
  13. const ELEMENT_NODE = 1;
  14. const TEXT_NODE = 3;
  15. const COMMENT_NODE = 8;
  16. const FRAGMENT_NODE = 11;
  17. const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;
  18. const testNode = (nodeType, name) =>
  19. (nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) ||
  20. (nodeType === TEXT_NODE && name === 'Text') ||
  21. (nodeType === COMMENT_NODE && name === 'Comment') ||
  22. (nodeType === FRAGMENT_NODE && name === 'DocumentFragment');
  23. const test = val =>
  24. val &&
  25. val.constructor &&
  26. val.constructor.name &&
  27. testNode(val.nodeType, val.constructor.name);
  28. exports.test = test;
  29. function nodeIsText(node) {
  30. return node.nodeType === TEXT_NODE;
  31. }
  32. function nodeIsComment(node) {
  33. return node.nodeType === COMMENT_NODE;
  34. }
  35. function nodeIsFragment(node) {
  36. return node.nodeType === FRAGMENT_NODE;
  37. }
  38. const serialize = (node, config, indentation, depth, refs, printer) => {
  39. if (nodeIsText(node)) {
  40. return (0, _markup.printText)(node.data, config);
  41. }
  42. if (nodeIsComment(node)) {
  43. return (0, _markup.printComment)(node.data, config);
  44. }
  45. const type = nodeIsFragment(node)
  46. ? `DocumentFragment`
  47. : node.tagName.toLowerCase();
  48. if (++depth > config.maxDepth) {
  49. return (0, _markup.printElementAsLeaf)(type, config);
  50. }
  51. return (0, _markup.printElement)(
  52. type,
  53. (0, _markup.printProps)(
  54. nodeIsFragment(node)
  55. ? []
  56. : Array.from(node.attributes)
  57. .map(attr => attr.name)
  58. .sort(),
  59. nodeIsFragment(node)
  60. ? []
  61. : Array.from(node.attributes).reduce((props, attribute) => {
  62. props[attribute.name] = attribute.value;
  63. return props;
  64. }, {}),
  65. config,
  66. indentation + config.indent,
  67. depth,
  68. refs,
  69. printer
  70. ),
  71. (0, _markup.printChildren)(
  72. Array.prototype.slice.call(node.childNodes || node.children),
  73. config,
  74. indentation + config.indent,
  75. depth,
  76. refs,
  77. printer
  78. ),
  79. config,
  80. indentation
  81. );
  82. };
  83. exports.serialize = serialize;
  84. const plugin = {
  85. serialize,
  86. test
  87. };
  88. var _default = plugin;
  89. exports.default = _default;