chartUtils.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import type {RefObject} from 'react';
  2. import moment from 'moment';
  3. import type {ReactEchartsRef} from 'sentry/types/echarts';
  4. import {
  5. SAMPLES_X_AXIS_ID,
  6. SAMPLES_Y_AXIS_ID,
  7. } from 'sentry/views/metrics/chart/useMetricChartSamples';
  8. export type ValueRect = {
  9. xMax: number;
  10. xMin: number;
  11. yMax: number;
  12. yMin: number;
  13. };
  14. const DEFAULT_VALUE_RECT = {
  15. xMin: -Infinity,
  16. xMax: Infinity,
  17. yMin: 0,
  18. yMax: Infinity,
  19. };
  20. export function fitToValueRect(x: number, y: number, rect: ValueRect | undefined) {
  21. if (!rect) {
  22. return [x, y];
  23. }
  24. const xValue = x <= rect.xMin ? rect.xMin : x >= rect.xMax ? rect.xMax : x;
  25. const yValue = y <= rect.yMin ? rect.yMin : y >= rect.yMax ? rect.yMax : y;
  26. return [xValue, yValue];
  27. }
  28. export function getValueRect(chartRef?: RefObject<ReactEchartsRef>): ValueRect {
  29. const chartInstance = chartRef?.current?.getEchartsInstance();
  30. if (!chartInstance) {
  31. return DEFAULT_VALUE_RECT;
  32. }
  33. const finder = {xAxisId: SAMPLES_X_AXIS_ID, yAxisId: SAMPLES_Y_AXIS_ID};
  34. const topLeft = chartInstance.convertFromPixel(finder, [0, 0]);
  35. const bottomRight = chartInstance.convertFromPixel(finder, [
  36. chartInstance.getWidth(),
  37. chartInstance.getHeight(),
  38. ]);
  39. if (!topLeft || !bottomRight) {
  40. return DEFAULT_VALUE_RECT;
  41. }
  42. const xMin = moment(topLeft[0]).valueOf();
  43. const xMax = moment(bottomRight[0]).valueOf();
  44. const yMin = Math.max(0, bottomRight[1]);
  45. const yMax = topLeft[1];
  46. return {
  47. xMin,
  48. xMax,
  49. yMin,
  50. yMax,
  51. };
  52. }