-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
open_context_menu.tsx
202 lines (183 loc) · 6.43 KB
/
open_context_menu.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import React from 'react';
import { EuiContextMenu, EuiContextMenuPanelDescriptor, EuiPopover } from '@elastic/eui';
import { EventEmitter } from 'events';
import ReactDOM from 'react-dom';
import { KibanaRenderContextProvider } from '@kbn/react-kibana-context-render';
import { getAnalytics, getI18n, getTheme, getUserProfile } from '../services';
let activeSession: ContextMenuSession | null = null;
const CONTAINER_ID = 'contextMenu-container';
/**
* Tries to find best position for opening context menu using mousemove and click event
* Returned position is relative to document
*/
export function createInteractionPositionTracker() {
let lastMouseX = 0;
let lastMouseY = 0;
const lastClicks: Array<{ el?: Element; mouseX: number; mouseY: number }> = [];
const MAX_LAST_CLICKS = 10;
/**
* Track both `mouseup` and `click`
* `mouseup` is for clicks and brushes with mouse
* `click` is a fallback for keyboard interactions
*/
document.addEventListener('mouseup', onClick, true);
document.addEventListener('click', onClick, true);
document.addEventListener('mousemove', onMouseUpdate, { passive: true });
document.addEventListener('mouseenter', onMouseUpdate, { passive: true });
function onClick(event: MouseEvent) {
lastClicks.push({
el: event.target as Element,
mouseX: event.clientX,
mouseY: event.clientY,
});
if (lastClicks.length > MAX_LAST_CLICKS) {
lastClicks.shift();
}
}
function onMouseUpdate(event: MouseEvent) {
lastMouseX = event.clientX;
lastMouseY = event.clientY;
}
return {
resolveLastPosition: (): { x: number; y: number } => {
const lastClick = [...lastClicks]
.reverse()
.find(({ el }) => el && document.body.contains(el));
if (!lastClick) {
// fallback to last mouse position
return {
x: lastMouseX,
y: lastMouseY,
};
}
const { top, left, bottom, right } = lastClick.el!.getBoundingClientRect();
const mouseX = lastClick.mouseX;
const mouseY = lastClick.mouseY;
if (top <= mouseY && bottom >= mouseY && left <= mouseX && right >= mouseX) {
// click was inside target element
return {
x: mouseX,
y: mouseY,
};
} else {
// keyboard edge case. no cursor position. use target element position instead
return {
x: left + (right - left) / 2,
y: bottom,
};
}
},
};
}
const { resolveLastPosition } = createInteractionPositionTracker();
function getOrCreateContainerElement() {
let container = document.getElementById(CONTAINER_ID);
let { x, y } = resolveLastPosition();
y = y + window.scrollY;
x = x + window.scrollX;
if (!container) {
container = document.createElement('div');
container.style.left = x + 'px';
container.style.top = y + 'px';
container.style.position = 'absolute';
// EUI tooltip uses 9000
// have to make it larger to display menu on top of tooltips from charts
container.style.zIndex = '9999';
container.id = CONTAINER_ID;
document.body.appendChild(container);
} else {
container.style.left = x + 'px';
container.style.top = y + 'px';
}
return container;
}
/**
* A FlyoutSession describes the session of one opened flyout panel. It offers
* methods to close the flyout panel again. If you open a flyout panel you should make
* sure you call {@link ContextMenuSession#close} when it should be closed.
* Since a flyout could also be closed without calling this method (e.g. because
* the user closes it), you must listen to the "closed" event on this instance.
* It will be emitted whenever the flyout will be closed and you should throw
* away your reference to this instance whenever you receive that event.
* @extends EventEmitter
*/
class ContextMenuSession extends EventEmitter {
/**
* Closes the opened flyout as long as it's still the open one.
* If this is not the active session, this method will do nothing.
* If this session was still active and a flyout was closed, the 'closed'
* event will be emitted on this FlyoutSession instance.
*/
public close(): void {
if (activeSession === this) {
const container = document.getElementById(CONTAINER_ID);
if (container) {
ReactDOM.unmountComponentAtNode(container);
this.emit('closed');
}
}
}
}
/**
* Opens a flyout panel with the given component inside. You can use
* {@link ContextMenuSession#close} on the return value to close the flyout.
*
* @param flyoutChildren - Mounts the children inside a fly out panel
* @return {FlyoutSession} The session instance for the opened flyout panel.
*/
export function openContextMenu(
panels: EuiContextMenuPanelDescriptor[],
props: {
closeButtonAriaLabel?: string;
onClose?: () => void;
'data-test-subj'?: string;
} = {}
): ContextMenuSession {
// If there is an active inspector session close it before opening a new one.
if (activeSession) {
activeSession.close();
}
const container = getOrCreateContainerElement();
const session = (activeSession = new ContextMenuSession());
const onClose = () => {
if (props.onClose) {
props.onClose();
}
session.close();
};
ReactDOM.render(
<KibanaRenderContextProvider
analytics={getAnalytics()}
i18n={getI18n()}
theme={getTheme()}
userProfile={getUserProfile()}
>
<EuiPopover
className="embPanel__optionsMenuPopover"
// @ts-expect-error @types/react@18 upgrade - Type 'HTMLElement' is not assignable to type 'NonNullable<ReactNode> | undefined'
button={container}
isOpen={true}
closePopover={onClose}
panelPaddingSize="none"
anchorPosition="downRight"
>
<EuiContextMenu
initialPanelId="mainMenu"
panels={panels}
data-test-subj={props['data-test-subj']}
/>
</EuiPopover>
</KibanaRenderContextProvider>,
container
);
return session;
}
export { ContextMenuSession };