utils.tsx 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import moment from 'moment-timezone';
  2. import {parseStatsPeriod} from 'sentry/components/organizations/pageFilters/parse';
  3. import type {DataCategoryInfo, IntervalPeriod} from 'sentry/types/core';
  4. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  5. import {formatUsageWithUnits} from '../utils';
  6. /**
  7. * Avoid changing "MMM D" format as X-axis labels on UsageChart are naively
  8. * truncated by date.slice(0, 6). This avoids "..." when truncating by ECharts.
  9. */
  10. export const FORMAT_DATETIME_DAILY = 'MMM D';
  11. export const FORMAT_DATETIME_HOURLY = 'MMM D LT';
  12. /**
  13. * Used to generate X-axis data points and labels for UsageChart
  14. * Ensure that this method is idempotent and doesn't change the moment object
  15. * that is passed in
  16. *
  17. * Use the `useUtc` parameter to get the UTC date for the provided
  18. * moment instance.
  19. */
  20. export function getDateFromMoment(
  21. m: moment.Moment,
  22. interval: IntervalPeriod = '1d',
  23. useUtc: boolean = false
  24. ) {
  25. const days = parsePeriodToHours(interval) / 24;
  26. if (days >= 1) {
  27. return useUtc
  28. ? moment.utc(m).format(FORMAT_DATETIME_DAILY)
  29. : m.format(FORMAT_DATETIME_DAILY);
  30. }
  31. const parsedInterval = parseStatsPeriod(interval);
  32. const datetime = useUtc ? moment(m).utc() : moment(m).local();
  33. return parsedInterval
  34. ? `${datetime.format(FORMAT_DATETIME_HOURLY)} - ${datetime
  35. .add(parsedInterval.period as any, parsedInterval.periodLength as any)
  36. .format('LT (Z)')}`
  37. : datetime.format(FORMAT_DATETIME_HOURLY);
  38. }
  39. export function getDateFromUnixTimestamp(timestamp: number) {
  40. const date = moment.unix(timestamp);
  41. return getDateFromMoment(date);
  42. }
  43. export function getXAxisDates(
  44. dateStart: moment.MomentInput,
  45. dateEnd: moment.MomentInput,
  46. dateUtc: boolean = false,
  47. interval: IntervalPeriod = '1d'
  48. ): string[] {
  49. const range: string[] = [];
  50. const start = moment(dateStart).startOf('h');
  51. const end = moment(dateEnd).startOf('h');
  52. if (!start.isValid() || !end.isValid()) {
  53. return range;
  54. }
  55. const {period, periodLength} = parseStatsPeriod(interval) ?? {
  56. period: 1,
  57. periodLength: 'd',
  58. };
  59. while (!start.isAfter(end)) {
  60. range.push(getDateFromMoment(start, interval, dateUtc));
  61. start.add(period as any, periodLength as any); // FIXME(ts): Something odd with momentjs types
  62. }
  63. return range;
  64. }
  65. export function getTooltipFormatter(dataCategory: DataCategoryInfo['plural']) {
  66. return (val: number = 0) =>
  67. formatUsageWithUnits(val, dataCategory, {useUnitScaling: true});
  68. }
  69. const MAX_NUMBER_OF_LABELS = 10;
  70. /**
  71. * Determines which X-axis labels should be visible based on data period and intervals.
  72. *
  73. * @param dataPeriod - Quantity of hours covered by the data
  74. * @param intervals - Intervals to be displayed on the X-axis
  75. * @returns An object containing an array indicating visibility of each X-axis label
  76. */
  77. export function getXAxisLabelVisibility(dataPeriod: number, intervals: string[]) {
  78. if (dataPeriod <= 24) {
  79. return {
  80. xAxisLabelVisibility: Array(intervals.length).fill(false),
  81. };
  82. }
  83. const uniqueLabels: Set<string> = new Set();
  84. const labelToPositionMap: Map<string, number> = new Map();
  85. const labelVisibility: boolean[] = new Array(intervals.length).fill(false);
  86. // Collect unique labels and their positions
  87. intervals.forEach((label, index) => {
  88. if (index === 0 || label.slice(0, 6) !== intervals[index - 1].slice(0, 6)) {
  89. uniqueLabels.add(label);
  90. labelToPositionMap.set(label, index);
  91. }
  92. });
  93. const totalUniqueLabels = uniqueLabels.size;
  94. // Determine which labels should be visible
  95. if (totalUniqueLabels <= MAX_NUMBER_OF_LABELS) {
  96. uniqueLabels.forEach(label => {
  97. const position = labelToPositionMap.get(label);
  98. if (position !== undefined) {
  99. labelVisibility[position] = true;
  100. }
  101. });
  102. return {xAxisLabelVisibility: labelVisibility};
  103. }
  104. const interval = Math.floor(totalUniqueLabels / MAX_NUMBER_OF_LABELS);
  105. let i = 0;
  106. uniqueLabels.forEach(label => {
  107. if (i % interval === 0) {
  108. const position = labelToPositionMap.get(label);
  109. if (position !== undefined) {
  110. labelVisibility[position] = true;
  111. }
  112. }
  113. i++;
  114. });
  115. return {xAxisLabelVisibility: labelVisibility};
  116. }