charts.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import {t} from 'sentry/locale';
  2. import {defined} from 'sentry/utils';
  3. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  4. import {
  5. DAY,
  6. formatAbbreviatedNumber,
  7. formatPercentage,
  8. getDuration,
  9. HOUR,
  10. MINUTE,
  11. SECOND,
  12. WEEK,
  13. } from 'sentry/utils/formatters';
  14. /**
  15. * Formatter for chart tooltips that handle a variety of discover and metrics result values.
  16. * If the result is metric values, the value can be of type number or null
  17. */
  18. export function tooltipFormatter(value: number | null, seriesName: string = ''): string {
  19. if (!defined(value)) {
  20. return '\u2014';
  21. }
  22. switch (aggregateOutputType(seriesName)) {
  23. case 'integer':
  24. case 'number':
  25. return value.toLocaleString();
  26. case 'percentage':
  27. return formatPercentage(value, 2);
  28. case 'duration':
  29. return getDuration(value / 1000, 2, true);
  30. default:
  31. return value.toString();
  32. }
  33. }
  34. /**
  35. * Formatter for chart axis labels that handle a variety of discover result values
  36. * This function is *very similar* to tooltipFormatter but outputs data with less precision.
  37. */
  38. export function axisLabelFormatter(
  39. value: number,
  40. seriesName: string,
  41. abbreviation: boolean = false
  42. ): string {
  43. switch (aggregateOutputType(seriesName)) {
  44. case 'integer':
  45. case 'number':
  46. return abbreviation ? formatAbbreviatedNumber(value) : value.toLocaleString();
  47. case 'percentage':
  48. return formatPercentage(value, 0);
  49. case 'duration':
  50. return axisDuration(value);
  51. default:
  52. return value.toString();
  53. }
  54. }
  55. /**
  56. * Specialized duration formatting for axis labels.
  57. * In that context we are ok sacrificing accuracy for more
  58. * consistent sizing.
  59. *
  60. * @param value Number of milliseconds to format.
  61. */
  62. export function axisDuration(value: number): string {
  63. if (value === 0) {
  64. return '0';
  65. }
  66. if (value >= WEEK) {
  67. const label = (value / WEEK).toFixed(0);
  68. return t('%swk', label);
  69. }
  70. if (value >= DAY) {
  71. const label = (value / DAY).toFixed(0);
  72. return t('%sd', label);
  73. }
  74. if (value >= HOUR) {
  75. const label = (value / HOUR).toFixed(0);
  76. return t('%shr', label);
  77. }
  78. if (value >= MINUTE) {
  79. const label = (value / MINUTE).toFixed(0);
  80. return t('%smin', label);
  81. }
  82. if (value >= SECOND) {
  83. const label = (value / SECOND).toFixed(0);
  84. return t('%ss', label);
  85. }
  86. const label = value.toFixed(0);
  87. return t('%sms', label);
  88. }