dom_element.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;
  19. const testNode = (nodeType, name) => nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name) || nodeType === TEXT_NODE && name === 'Text' || nodeType === COMMENT_NODE && name === 'Comment';
  20. const test = exports.test = val => val && val.constructor && val.constructor.name && testNode(val.nodeType, val.constructor.name);
  21. // Convert array of attribute objects to keys array and props object.
  22. const keysMapper = attribute => attribute.name;
  23. const propsReducer = (props, attribute) => {
  24. props[attribute.name] = attribute.value;
  25. return props;
  26. };
  27. const serialize = exports.serialize = (node, config, indentation, depth, refs, printer) => {
  28. if (node.nodeType === TEXT_NODE) {
  29. return (0, _markup.printText)(node.data, config);
  30. }
  31. if (node.nodeType === COMMENT_NODE) {
  32. return (0, _markup.printComment)(node.data, config);
  33. }
  34. const type = node.tagName.toLowerCase();
  35. if (++depth > config.maxDepth) {
  36. return (0, _markup.printElementAsLeaf)(type, config);
  37. }
  38. return (0, _markup.printElement)(type, (0, _markup.printProps)(Array.prototype.map.call(node.attributes, keysMapper).sort(), Array.prototype.reduce.call(node.attributes, propsReducer, {}), config, indentation + config.indent, depth, refs, printer), (0, _markup.printChildren)(Array.prototype.slice.call(node.childNodes), config, indentation + config.indent, depth, refs, printer), config, indentation);
  39. };
  40. exports.default = { serialize, test };