chartUtils.tsx 1.4 KB

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