format.tsx 4.9 KB

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