format.tsx 4.4 KB

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