rect.tsx 1.5 KB

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