format.tsx 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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: any, path: any) => {
  41. onExpand(path, Object.fromEntries(expandedPaths.map((item: any) => [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. }
  83. case '%d':
  84. return Number(args[i++]);
  85. case '%j':
  86. try {
  87. return JSON.stringify(args[i++]);
  88. } catch (_) {
  89. return '[Circular]';
  90. }
  91. default:
  92. return x;
  93. }
  94. });
  95. if (styling && typeof styling === 'string') {
  96. const tempEl = document.createElement('div');
  97. tempEl.setAttribute('style', styling);
  98. // Only allow certain CSS attributes, be careful of css properties that
  99. // accept `url()`
  100. //
  101. // See the section above https://developer.mozilla.org/en-US/docs/Web/API/console#using_groups_in_the_console
  102. // for the properties that Firefox supports.
  103. const styleObj = Object.fromEntries(
  104. [
  105. ['background-color', 'backgroundColor'],
  106. ['border-radius', 'borderRadius'],
  107. ['color', 'color'],
  108. ['font-size', 'fontSize'],
  109. ['font-style', 'fontStyle'],
  110. ['font-weight', 'fontWeight'],
  111. ['margin', 'margin'],
  112. ['padding', 'padding'],
  113. ['text-transform', 'textTransform'],
  114. ['writing-mode', 'writingMode'],
  115. ]
  116. .map(([attr, reactAttr]) => [reactAttr, tempEl.style.getPropertyValue(attr!)])
  117. .filter(([, val]) => !!val)
  118. );
  119. styleObj.display = 'inline-block';
  120. pieces.push(
  121. <span key={`%c-${i - 1}`} style={styleObj}>
  122. {str}
  123. </span>
  124. );
  125. } else {
  126. pieces.push(str);
  127. }
  128. for (let x = args[i]; i < len; x = args[++i]) {
  129. if (x === null || typeof x !== 'object') {
  130. pieces.push(' ' + x);
  131. } else {
  132. pieces.push(' ');
  133. pieces.push(
  134. <Wrapper key={i}>
  135. <StructuredEventData
  136. key={i}
  137. data={x}
  138. initialExpandedPaths={expandPaths ?? []}
  139. onToggleExpand={onToggleExpand}
  140. />
  141. </Wrapper>
  142. );
  143. }
  144. }
  145. return <Fragment>{pieces}</Fragment>;
  146. }
  147. const Wrapper = styled('div')`
  148. pre {
  149. margin: 0;
  150. background: none;
  151. font-size: inherit;
  152. }
  153. `;