dom_element.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.serialize = exports.test = undefined;
  6. var _markup = require('./lib/markup');
  7. /**
  8. * Copyright (c) 2014-present, Facebook, Inc. 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. *
  14. */
  15. const ELEMENT_NODE = 1;
  16. const TEXT_NODE = 3;
  17. const COMMENT_NODE = 8;
  18. const FRAGMENT_NODE = 11;
  19. const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;
  20. const testNode = (nodeType, name) =>
  21. (nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) ||
  22. (nodeType === TEXT_NODE && name === 'Text') ||
  23. (nodeType === COMMENT_NODE && name === 'Comment') ||
  24. (nodeType === FRAGMENT_NODE && name === 'DocumentFragment');
  25. const test = (exports.test = val =>
  26. val &&
  27. val.constructor &&
  28. val.constructor.name &&
  29. testNode(val.nodeType, val.constructor.name));
  30. // Convert array of attribute objects to keys array and props object.
  31. const keysMapper = attribute => attribute.name;
  32. const propsReducer = (props, attribute) => {
  33. props[attribute.name] = attribute.value;
  34. return props;
  35. };
  36. const serialize = (exports.serialize = (
  37. node,
  38. config,
  39. indentation,
  40. depth,
  41. refs,
  42. printer
  43. ) => {
  44. if (node.nodeType === TEXT_NODE) {
  45. return (0, _markup.printText)(node.data, config);
  46. }
  47. if (node.nodeType === COMMENT_NODE) {
  48. return (0, _markup.printComment)(node.data, config);
  49. }
  50. const type =
  51. node.nodeType === FRAGMENT_NODE
  52. ? `DocumentFragment`
  53. : node.tagName.toLowerCase();
  54. if (++depth > config.maxDepth) {
  55. return (0, _markup.printElementAsLeaf)(type, config);
  56. }
  57. return (0, _markup.printElement)(
  58. type,
  59. (0, _markup.printProps)(
  60. Array.prototype.map.call(node.attributes || [], keysMapper).sort(),
  61. Array.prototype.reduce.call(node.attributes || [], propsReducer, {}),
  62. config,
  63. indentation + config.indent,
  64. depth,
  65. refs,
  66. printer
  67. ),
  68. (0, _markup.printChildren)(
  69. Array.prototype.slice.call(node.childNodes || node.children),
  70. config,
  71. indentation + config.indent,
  72. depth,
  73. refs,
  74. printer
  75. ),
  76. config,
  77. indentation
  78. );
  79. });
  80. exports.default = {serialize: serialize, test: test};