format.tsx 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // This is based on https://github.com/browserify/node-util/blob/master/util.js
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. import {Fragment} from 'react';
  23. import isObject from 'lodash/isObject';
  24. import ObjectInspector, {OnExpandCallback} from 'sentry/components/objectInspector';
  25. const formatRegExp = /%[csdj%]/g;
  26. function isNull(arg: unknown) {
  27. return arg === null;
  28. }
  29. interface FormatProps {
  30. args: any[];
  31. expandPaths?: string[];
  32. onExpand?: OnExpandCallback;
  33. }
  34. /**
  35. * Based on node's `util.format()`, returns a formatted "string" using the
  36. * first argument as a printf-like format string which can contain zero or more
  37. * format specifiers. Uses `<ObjectInspector>` to print objects.
  38. *
  39. * %c is ignored for now
  40. */
  41. export default function Format({onExpand, expandPaths, args}: FormatProps) {
  42. const f = args[0];
  43. if (typeof f !== 'string') {
  44. const objects: any[] = [];
  45. for (let i = 0; i < args.length; i++) {
  46. objects.push(
  47. <ObjectInspector
  48. key={i}
  49. data={args[i]}
  50. expandPaths={expandPaths}
  51. onExpand={onExpand}
  52. />
  53. );
  54. }
  55. return <Fragment>{objects}</Fragment>;
  56. }
  57. let i = 1;
  58. let styling: string | undefined;
  59. const len = args.length;
  60. const pieces: any[] = [];
  61. const str = String(f).replace(formatRegExp, function (x) {
  62. if (x === '%%') {
  63. return '%';
  64. }
  65. if (i >= len) {
  66. return x;
  67. }
  68. switch (x) {
  69. case '%c':
  70. styling = args[i++];
  71. return '';
  72. case '%s':
  73. const val = args[i++];
  74. try {
  75. return String(val);
  76. } catch {
  77. return 'toString' in val ? val.toString : JSON.stringify(val);
  78. }
  79. case '%d':
  80. return Number(args[i++]);
  81. case '%j':
  82. try {
  83. return JSON.stringify(args[i++]);
  84. } catch (_) {
  85. return '[Circular]';
  86. }
  87. default:
  88. return x;
  89. }
  90. });
  91. if (styling && typeof styling === 'string') {
  92. const tempEl = document.createElement('div');
  93. tempEl.setAttribute('style', styling);
  94. // Only allow certain CSS attributes, be careful of css properties that
  95. // accept `url()`
  96. //
  97. // See the section above https://developer.mozilla.org/en-US/docs/Web/API/console#using_groups_in_the_console
  98. // for the properties that Firefox supports.
  99. const styleObj = Object.fromEntries(
  100. [
  101. ['background-color', 'backgroundColor'],
  102. ['border-radius', 'borderRadius'],
  103. ['color', 'color'],
  104. ['font-size', 'fontSize'],
  105. ['font-style', 'fontStyle'],
  106. ['font-weight', 'fontWeight'],
  107. ['margin', 'margin'],
  108. ['padding', 'padding'],
  109. ['text-transform', 'textTransform'],
  110. ['writing-mode', 'writingMode'],
  111. ]
  112. .map(([attr, reactAttr]) => [reactAttr, tempEl.style.getPropertyValue(attr)])
  113. .filter(([, val]) => !!val)
  114. );
  115. styleObj.display = 'inline-block';
  116. pieces.push(
  117. <span key={`%c-${i - 1}`} style={styleObj}>
  118. {str}
  119. </span>
  120. );
  121. } else {
  122. pieces.push(str);
  123. }
  124. for (let x = args[i]; i < len; x = args[++i]) {
  125. if (isNull(x) || !isObject(x)) {
  126. pieces.push(' ' + x);
  127. } else {
  128. pieces.push(' ');
  129. pieces.push(
  130. <ObjectInspector key={i} data={x} expandPaths={expandPaths} onExpand={onExpand} />
  131. );
  132. }
  133. }
  134. return <Fragment>{pieces}</Fragment>;
  135. }