GraphContextMenuCtrl.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { FlotDataPoint } from '@grafana/data';
  2. import { MenuItemProps } from '@grafana/ui';
  3. export class GraphContextMenuCtrl {
  4. private source?: FlotDataPoint | null;
  5. private scope?: any;
  6. menuItemsSupplier?: () => MenuItemProps[];
  7. scrollContextElement: HTMLElement | null = null;
  8. position: {
  9. x: number;
  10. y: number;
  11. } = { x: 0, y: 0 };
  12. isVisible: boolean;
  13. constructor($scope: any) {
  14. this.isVisible = false;
  15. this.scope = $scope;
  16. }
  17. onClose = () => {
  18. if (this.scrollContextElement) {
  19. this.scrollContextElement.removeEventListener('scroll', this.onClose);
  20. }
  21. this.scope.$apply(() => {
  22. this.isVisible = false;
  23. });
  24. };
  25. toggleMenu = (event?: { pageX: number; pageY: number }) => {
  26. this.isVisible = !this.isVisible;
  27. if (this.isVisible && this.scrollContextElement) {
  28. this.scrollContextElement.addEventListener('scroll', this.onClose);
  29. }
  30. if (this.source) {
  31. this.position = {
  32. x: this.source.pageX,
  33. y: this.source.pageY,
  34. };
  35. } else {
  36. this.position = {
  37. x: event ? event.pageX : 0,
  38. y: event ? event.pageY : 0,
  39. };
  40. }
  41. };
  42. // Sets element which is considered as a scroll context of given context menu.
  43. // Having access to this element allows scroll event attachement for menu to be closed when user scrolls
  44. setScrollContextElement = (el: HTMLElement | null) => {
  45. this.scrollContextElement = el;
  46. };
  47. setSource = (source: FlotDataPoint | null) => {
  48. this.source = source;
  49. };
  50. getSource = () => {
  51. return this.source;
  52. };
  53. setMenuItemsSupplier = (menuItemsSupplier: () => MenuItemProps[]) => {
  54. this.menuItemsSupplier = menuItemsSupplier;
  55. };
  56. }