format.tsx 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 ObjectInspector, {OnExpandCallback} from 'sentry/components/objectInspector';
  24. const formatRegExp = /%[csdj%]/g;
  25. interface FormatProps {
  26. args: any[];
  27. expandPaths?: string[];
  28. onExpand?: OnExpandCallback;
  29. }
  30. /**
  31. * Based on node's `util.format()`, returns a formatted "string" using the
  32. * first argument as a printf-like format string which can contain zero or more
  33. * format specifiers. Uses `<ObjectInspector>` to print objects.
  34. *
  35. * %c is ignored for now
  36. */
  37. export default function Format({onExpand, expandPaths, args}: FormatProps) {
  38. const f = args[0];
  39. if (typeof f !== 'string') {
  40. const objects: any[] = [];
  41. for (let i = 0; i < args.length; i++) {
  42. objects.push(
  43. <ObjectInspector
  44. key={i}
  45. data={args[i]}
  46. expandPaths={expandPaths}
  47. onExpand={onExpand}
  48. />
  49. );
  50. }
  51. return <Fragment>{objects}</Fragment>;
  52. }
  53. let i = 1;
  54. let styling: string | undefined;
  55. const len = args.length;
  56. const pieces: any[] = [];
  57. const str = String(f).replace(formatRegExp, function (x) {
  58. if (x === '%%') {
  59. return '%';
  60. }
  61. if (i >= len) {
  62. return x;
  63. }
  64. switch (x) {
  65. case '%c':
  66. styling = args[i++];
  67. return '';
  68. case '%s':
  69. const val = args[i++];
  70. try {
  71. return String(val);
  72. } catch {
  73. return 'toString' in val ? val.toString : JSON.stringify(val);
  74. }
  75. case '%d':
  76. return Number(args[i++]);
  77. case '%j':
  78. try {
  79. return JSON.stringify(args[i++]);
  80. } catch (_) {
  81. return '[Circular]';
  82. }
  83. default:
  84. return x;
  85. }
  86. });
  87. if (styling && typeof styling === 'string') {
  88. const tempEl = document.createElement('div');
  89. tempEl.setAttribute('style', styling);
  90. // Only allow certain CSS attributes, be careful of css properties that
  91. // accept `url()`
  92. //
  93. // See the section above https://developer.mozilla.org/en-US/docs/Web/API/console#using_groups_in_the_console
  94. // for the properties that Firefox supports.
  95. const styleObj = Object.fromEntries(
  96. [
  97. ['background-color', 'backgroundColor'],
  98. ['border-radius', 'borderRadius'],
  99. ['color', 'color'],
  100. ['font-size', 'fontSize'],
  101. ['font-style', 'fontStyle'],
  102. ['font-weight', 'fontWeight'],
  103. ['margin', 'margin'],
  104. ['padding', 'padding'],
  105. ['text-transform', 'textTransform'],
  106. ['writing-mode', 'writingMode'],
  107. ]
  108. .map(([attr, reactAttr]) => [reactAttr, tempEl.style.getPropertyValue(attr)])
  109. .filter(([, val]) => !!val)
  110. );
  111. styleObj.display = 'inline-block';
  112. pieces.push(
  113. <span key={`%c-${i - 1}`} style={styleObj}>
  114. {str}
  115. </span>
  116. );
  117. } else {
  118. pieces.push(str);
  119. }
  120. for (let x = args[i]; i < len; x = args[++i]) {
  121. if (x === null || typeof x !== 'object') {
  122. pieces.push(' ' + x);
  123. } else {
  124. pieces.push(' ');
  125. pieces.push(
  126. <ObjectInspector key={i} data={x} expandPaths={expandPaths} onExpand={onExpand} />
  127. );
  128. }
  129. }
  130. return <Fragment>{pieces}</Fragment>;
  131. }