utils.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import moment from 'moment';
  2. import BaseChart from 'sentry/components/charts/baseChart';
  3. import {DateTimeObject} from 'sentry/components/charts/utils';
  4. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  5. import type {SeriesDataUnit} from 'sentry/types/echarts';
  6. /**
  7. * Buckets a week of sequential days into one data unit
  8. */
  9. export function sortSeriesByDay(data: SeriesDataUnit[]): SeriesDataUnit[] {
  10. return data.sort((a, b) => new Date(a.name).getTime() - new Date(b.name).getTime());
  11. }
  12. /**
  13. * Convert an object with date as the key to a series
  14. */
  15. export function convertDayValueObjectToSeries(
  16. data: Record<string, number>
  17. ): SeriesDataUnit[] {
  18. return Object.entries(data).map(([bucket, count]) => ({
  19. value: count,
  20. name: new Date(bucket).getTime(),
  21. }));
  22. }
  23. /**
  24. * Takes a sorted array of trend items and groups them by worst/better/no chagne
  25. */
  26. export function groupByTrend<T extends {trend: number}>(data: T[]): T[] {
  27. const worseItems = data.filter(x => Math.round(x.trend) < 0);
  28. const betterItems = data.filter(x => Math.round(x.trend) > 0);
  29. const zeroItems = data.filter(x => Math.round(x.trend) === 0);
  30. return [...worseItems, ...betterItems, ...zeroItems];
  31. }
  32. export const barAxisLabel = (): React.ComponentProps<typeof BaseChart>['xAxis'] => {
  33. return {
  34. type: 'category',
  35. axisTick: {
  36. alignWithLabel: true,
  37. },
  38. axisLabel: {
  39. formatter: (date: string) => {
  40. return moment(new Date(Number(date))).format('MMM D');
  41. },
  42. },
  43. };
  44. };
  45. const INSIGHTS_DEFAULT_STATS_PERIOD = '8w';
  46. export function dataDatetime(
  47. query: Parameters<typeof normalizeDateTimeParams>[0]
  48. ): DateTimeObject {
  49. const {
  50. start,
  51. end,
  52. statsPeriod,
  53. utc: utcString,
  54. } = normalizeDateTimeParams(query, {
  55. allowEmptyPeriod: true,
  56. allowAbsoluteDatetime: true,
  57. allowAbsolutePageDatetime: true,
  58. });
  59. if (!statsPeriod && !start && !end) {
  60. return {period: INSIGHTS_DEFAULT_STATS_PERIOD};
  61. }
  62. // Following getParams, statsPeriod will take priority over start/end
  63. if (statsPeriod) {
  64. return {period: statsPeriod};
  65. }
  66. const utc = utcString === 'true';
  67. if (start && end) {
  68. return utc
  69. ? {
  70. start: moment.utc(start).format(),
  71. end: moment.utc(end).format(),
  72. utc,
  73. }
  74. : {
  75. start: moment(start).utc().format(),
  76. end: moment(end).utc().format(),
  77. utc,
  78. };
  79. }
  80. return {period: INSIGHTS_DEFAULT_STATS_PERIOD};
  81. }