dom_element.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.serialize = exports.test = undefined;
  2. var _markup = require('./lib/markup'); /**
  3. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. *
  9. */
  10. const ELEMENT_NODE = 1;
  11. const TEXT_NODE = 3;
  12. const COMMENT_NODE = 8;
  13. const ELEMENT_REGEXP = /^(HTML|SVG)\w*?Element$/;
  14. const testNode = (nodeType, name) =>
  15. nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name) ||
  16. nodeType === TEXT_NODE && name === 'Text' ||
  17. nodeType === COMMENT_NODE && name === 'Comment';
  18. const test = exports.test = val =>
  19. val &&
  20. val.constructor &&
  21. val.constructor.name &&
  22. testNode(val.nodeType, val.constructor.name);
  23. // Convert array of attribute objects to keys array and props object.
  24. const keysMapper = attribute => attribute.name;
  25. const propsReducer = (props, attribute) => {
  26. props[attribute.name] = attribute.value;
  27. return props;
  28. };
  29. const serialize = exports.serialize = (
  30. node,
  31. config,
  32. indentation,
  33. depth,
  34. refs,
  35. printer) =>
  36. {
  37. if (node.nodeType === TEXT_NODE) {
  38. return (0, _markup.printText)(node.data, config);
  39. }
  40. if (node.nodeType === COMMENT_NODE) {
  41. return (0, _markup.printComment)(node.data, config);
  42. }
  43. const type = node.tagName.toLowerCase();
  44. if (++depth > config.maxDepth) {
  45. return (0, _markup.printElementAsLeaf)(type, config);
  46. }
  47. return (0, _markup.printElement)(
  48. type,
  49. (0, _markup.printProps)(
  50. Array.prototype.map.call(node.attributes, keysMapper).sort(),
  51. Array.prototype.reduce.call(node.attributes, propsReducer, {}),
  52. config,
  53. indentation + config.indent,
  54. depth,
  55. refs,
  56. printer),
  57. (0, _markup.printChildren)(
  58. Array.prototype.slice.call(node.childNodes),
  59. config,
  60. indentation + config.indent,
  61. depth,
  62. refs,
  63. printer),
  64. config,
  65. indentation);
  66. };exports.default =
  67. { serialize, test };