utils.tsx 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. let startOfUnit: moment.unitOfTime.StartOf = 'h';
  51. if (interval <= '6h') {
  52. startOfUnit = 'm';
  53. }
  54. const start = moment(dateStart).startOf(startOfUnit);
  55. const end = moment(dateEnd).startOf(startOfUnit);
  56. if (!start.isValid() || !end.isValid()) {
  57. return range;
  58. }
  59. const {period, periodLength} = parseStatsPeriod(interval) ?? {
  60. period: 1,
  61. periodLength: 'd',
  62. };
  63. while (!start.isAfter(end)) {
  64. range.push(getDateFromMoment(start, interval, dateUtc));
  65. start.add(period as any, periodLength as any); // FIXME(ts): Something odd with momentjs types
  66. }
  67. return range;
  68. }
  69. export function getTooltipFormatter(dataCategory: DataCategoryInfo['plural']) {
  70. return (val: number = 0) =>
  71. formatUsageWithUnits(val, dataCategory, {useUnitScaling: true});
  72. }
  73. const MAX_NUMBER_OF_LABELS = 10;
  74. /**
  75. * Determines which X-axis labels should be visible based on data period and intervals.
  76. *
  77. * @param dataPeriod - Quantity of hours covered by the data
  78. * @param intervals - Intervals to be displayed on the X-axis
  79. * @returns An object containing an array indicating visibility of each X-axis label
  80. */
  81. export function getXAxisLabelVisibility(dataPeriod: number, intervals: string[]) {
  82. if (dataPeriod <= 24) {
  83. return {
  84. xAxisLabelVisibility: Array(intervals.length).fill(false),
  85. };
  86. }
  87. const uniqueLabels: Set<string> = new Set();
  88. const labelToPositionMap: Map<string, number> = new Map();
  89. const labelVisibility: boolean[] = new Array(intervals.length).fill(false);
  90. // Collect unique labels and their positions
  91. intervals.forEach((label, index) => {
  92. if (index === 0 || label.slice(0, 6) !== intervals[index - 1].slice(0, 6)) {
  93. uniqueLabels.add(label);
  94. labelToPositionMap.set(label, index);
  95. }
  96. });
  97. const totalUniqueLabels = uniqueLabels.size;
  98. // Determine which labels should be visible
  99. if (totalUniqueLabels <= MAX_NUMBER_OF_LABELS) {
  100. uniqueLabels.forEach(label => {
  101. const position = labelToPositionMap.get(label);
  102. if (position !== undefined) {
  103. labelVisibility[position] = true;
  104. }
  105. });
  106. return {xAxisLabelVisibility: labelVisibility};
  107. }
  108. const interval = Math.floor(totalUniqueLabels / MAX_NUMBER_OF_LABELS);
  109. let i = 0;
  110. uniqueLabels.forEach(label => {
  111. if (i % interval === 0) {
  112. const position = labelToPositionMap.get(label);
  113. if (position !== undefined) {
  114. labelVisibility[position] = true;
  115. }
  116. }
  117. i++;
  118. });
  119. return {xAxisLabelVisibility: labelVisibility};
  120. }