pretty-dom.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.prettyDOM = prettyDOM;
  7. Object.defineProperty(exports, "prettyFormat", {
  8. enumerable: true,
  9. get: function () {
  10. return _prettyFormat.default;
  11. }
  12. });
  13. exports.logDOM = void 0;
  14. var _prettyFormat = _interopRequireDefault(require("pretty-format"));
  15. var _getUserCodeFrame = require("./get-user-code-frame");
  16. var _helpers = require("./helpers");
  17. function inCypress(dom) {
  18. const window = dom.ownerDocument && dom.ownerDocument.defaultView || undefined;
  19. return typeof global !== 'undefined' && global.Cypress || typeof window !== 'undefined' && window.Cypress;
  20. }
  21. const inNode = () => typeof process !== 'undefined' && process.versions !== undefined && process.versions.node !== undefined;
  22. const getMaxLength = dom => inCypress(dom) ? 0 : typeof process !== 'undefined' && process.env.DEBUG_PRINT_LIMIT || 7000;
  23. const {
  24. DOMElement,
  25. DOMCollection
  26. } = _prettyFormat.default.plugins;
  27. function prettyDOM(dom, maxLength, options) {
  28. if (!dom) {
  29. dom = (0, _helpers.getDocument)().body;
  30. }
  31. if (typeof maxLength !== 'number') {
  32. maxLength = getMaxLength(dom);
  33. }
  34. if (maxLength === 0) {
  35. return '';
  36. }
  37. if (dom.documentElement) {
  38. dom = dom.documentElement;
  39. }
  40. let domTypeName = typeof dom;
  41. if (domTypeName === 'object') {
  42. domTypeName = dom.constructor.name;
  43. } else {
  44. // To don't fall with `in` operator
  45. dom = {};
  46. }
  47. if (!('outerHTML' in dom)) {
  48. throw new TypeError(`Expected an element or document but got ${domTypeName}`);
  49. }
  50. const debugContent = (0, _prettyFormat.default)(dom, {
  51. plugins: [DOMElement, DOMCollection],
  52. printFunctionName: false,
  53. highlight: inNode(),
  54. ...options
  55. });
  56. return maxLength !== undefined && dom.outerHTML.length > maxLength ? `${debugContent.slice(0, maxLength)}...` : debugContent;
  57. }
  58. const logDOM = (...args) => {
  59. const userCodeFrame = (0, _getUserCodeFrame.getUserCodeFrame)();
  60. if (userCodeFrame) {
  61. console.log(`${prettyDOM(...args)}\n\n${userCodeFrame}`);
  62. } else {
  63. console.log(prettyDOM(...args));
  64. }
  65. };
  66. exports.logDOM = logDOM;