GraphContextMenuCtrl.ts 1.8 KB

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