-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathContextMenu.jsx
481 lines (431 loc) · 15.3 KB
/
ContextMenu.jsx
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**
* @component {./docs.md}
*/
import classNames from 'clsx';
import PropTypes from 'prop-types';
import React, {
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import Bubble from '../../react-chayns-bubble/component/Bubble';
import Icon from '../../react-chayns-icon/component/Icon';
import TextString from '../../react-chayns-textstring/component/TextString';
/**
* Gives people access to additional functionality related to onscreen items
* without cluttering the interface.
*/
const ContextMenu = React.forwardRef(
(
{
parent,
position: userPosition = null,
minWidth,
maxWidth,
className,
items = [],
stopPropagation = false,
childrenStyle,
childrenClassName,
showTriggerBackground = false,
children = <Icon icon="ts-ellipsis_v" />,
style,
onChildrenClick,
disableDialog = false,
onLayerClick,
onShow,
onHide,
removeParentSpace = false,
coordinates,
positionOnChildren = 1,
arrowDistance = 0,
},
ref
) => {
const bubbleRef = useRef();
const childrenRef = useRef();
const [isBubbleShown, setIsBubbleShown] = useState(false);
const [position, setPosition] = useState(null);
const [x, setX] = useState(0);
const [y, setY] = useState(0);
const itemsHaveIcons = items.some(({ icon }) =>
typeof icon === 'string' ? icon : icon?.iconName
);
/**
* Sync bubble with `isBubbleShown` state
*/
useEffect(() => {
if (!bubbleRef.current) return;
if (isBubbleShown) {
bubbleRef.current.show();
onShow?.();
} else {
bubbleRef.current.hide();
onHide?.();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isBubbleShown]);
/**
* Update position of the bubble
*/
useEffect(() => {
let newX = coordinates?.x || 0;
let top = coordinates?.y || 0;
let bottom = coordinates?.y || 0;
if (!coordinates && childrenRef.current) {
const rect = childrenRef.current.getBoundingClientRect();
if (
positionOnChildren === ContextMenu.positionOnChildren.LEFT
) {
newX = rect.left + arrowDistance;
} else if (
positionOnChildren === ContextMenu.positionOnChildren.CENTER
) {
newX = rect.left + rect.width / 2;
} else if (
positionOnChildren === ContextMenu.positionOnChildren.RIGHT
) {
newX = rect.left + rect.width - arrowDistance;
}
top = rect.top;
bottom = rect.bottom;
}
let newPosition = userPosition;
if (newPosition === null) {
const shouldBeLeft = newX > window.innerWidth / 2;
const shouldBeTop =
(top + bottom) / 2 >
(document.body.offsetHeight || window.innerHeight) / 2;
if (shouldBeLeft && shouldBeTop) {
newPosition = ContextMenu.position.TOP_LEFT;
} else if (!shouldBeLeft && shouldBeTop) {
newPosition = ContextMenu.position.TOP_RIGHT;
} else if (shouldBeLeft && !shouldBeTop) {
newPosition = ContextMenu.position.BOTTOM_LEFT;
} else {
newPosition = ContextMenu.position.BOTTOM_RIGHT;
}
}
let newY = Bubble.isPositionBottom(newPosition) ? bottom : top;
if (removeParentSpace) {
const parentRect = (
parent ||
document.getElementsByClassName('tapp')[0] ||
document.body
).getBoundingClientRect();
newX -= parentRect.left;
newY -= parentRect.top;
}
if (chayns.env.isApp) {
chayns.getWindowMetrics().then(({ pageYOffset }) => {
setPosition(newPosition);
setX(newX);
setY(newY + pageYOffset);
});
} else {
setPosition(newPosition);
setX(newX);
setY(newY);
}
}, [
arrowDistance,
coordinates,
parent,
positionOnChildren,
removeParentSpace,
userPosition,
isBubbleShown,
]);
/**
* Show the menu, either by opening a dialog or by showing the bubble.
*/
const show = useCallback(async () => {
if (
!disableDialog &&
(chayns.env.isMobile || chayns.env.isTablet)
) {
const iconFallback = items.some(({ icon }) =>
typeof icon === 'string' ? icon : icon?.iconName
)
? ' '
: '';
const { buttonType, selection } = await chayns.dialog.select({
type: 2,
list: items.map(({ text, icon, stringName }, index) => ({
// eslint-disable-next-line no-nested-ternary
name: stringName
? TextString.getTextString(stringName, null, text)
: React.isValidElement(text)
? renderToStaticMarkup(text)
: text,
value: index,
icon:
(typeof icon === 'string'
? icon
: icon?.iconName && `fa-${icon?.iconName}`) ||
iconFallback,
})),
buttons: [],
});
if (buttonType === 1 && selection?.[0]) {
items[selection[0].value].onClick();
} else if (buttonType === -1 && onLayerClick) {
onLayerClick();
}
} else {
setIsBubbleShown(true);
}
}, [disableDialog, items, onLayerClick]);
const hide = useCallback(() => {
setIsBubbleShown(false);
}, []);
/**
* Expose the `show` and `hide` methods via ref.
*/
useImperativeHandle(ref, () => ({ show, hide }), [hide, show]);
useEffect(() => {
window.addEventListener('blur', hide);
return () => {
window.removeEventListener('blur', hide);
};
}, [hide]);
/**
* Hides the bubble when is it opened and the page is clicked.
*/
// eslint-disable-next-line consistent-return
useEffect(() => {
if (isBubbleShown) {
const handleLayerClick = (event) => {
if (isBubbleShown) {
if (onLayerClick) {
onLayerClick(event);
} else {
hide();
}
}
};
document.addEventListener('click', handleLayerClick, true);
return () =>
document.removeEventListener(
'click',
handleLayerClick,
true
);
}
}, [hide, isBubbleShown, onLayerClick]);
function handleChildrenClick(event) {
if (onChildrenClick) {
onChildrenClick(event);
} else {
show();
}
if (stopPropagation) {
event.stopPropagation();
}
}
return (
<>
<Bubble
coordinates={{ x, y }}
parent={parent}
position={position}
style={{
minWidth,
maxWidth,
...style,
}}
key="bubble"
ref={bubbleRef}
className={className}
>
<ul>
{items.map((item, index) => (
<li
className={classNames(
'context-menu__item',
item.className
)}
onClick={(e) => {
if (stopPropagation) {
e.stopPropagation();
}
item.onClick(e);
}}
key={
// eslint-disable-next-line react/no-array-index-key
item.stringName ||
(item.text.props &&
item.text.props.stringName
? item.text.props.stringName
: item.text) + index
}
>
{item.icon || itemsHaveIcons ? (
<div className="context-menu__item__icon">
{item.icon && <Icon icon={item.icon} />}
</div>
) : null}
{item.stringName ? (
<TextString stringName={item.stringName}>
<div className="context-menu__item__text">
{item.text}
</div>
</TextString>
) : (
<div className="context-menu__item__text">
{item.text}
</div>
)}
</li>
))}
</ul>
</Bubble>
{!coordinates && (
<div
key="cc__contextMenu__children"
ref={childrenRef}
onClick={handleChildrenClick}
style={childrenStyle}
className={classNames(
childrenClassName,
'accordion--no-trigger',
'context-menu__children',
{ 'image-tool': showTriggerBackground }
)}
>
{children}
</div>
)}
</>
);
}
);
ContextMenu.position = Bubble.position;
ContextMenu.positionOnChildren = {
LEFT: 0,
CENTER: 1,
RIGHT: 2,
};
ContextMenu.propTypes = {
/**
* This callback will be called when the `ContextMenu` is shown and the user
* clicks away from it.
*/
onLayerClick: PropTypes.func,
/**
* This callback will be called when the context menu becomes visible
*/
onShow: PropTypes.func,
/**
* This callback will be called when the `ContextMenu` hides
*/
onHide: PropTypes.func,
/**
* The coordinates at which the context menu will get rendered.
*/
coordinates: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
/**
* The action items inside of the context menu. Their shape should look like
* this: `{ className: <string>, onClick: <function>, text: <string>,
* icon: <string> }, stringName: <string>`.
*/
items: PropTypes.arrayOf(
PropTypes.shape({
className: PropTypes.string,
onClick: PropTypes.func,
text: PropTypes.oneOfType([PropTypes.string, PropTypes.node])
.isRequired,
stringName: PropTypes.string,
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.instanceOf(Object),
]),
})
),
/**
* This specifies where the menu will appear relative to the components
* provided in the `children`-prop. Possible values are: `0` for top left,
* `1` for bottom left, `2` for bottom right, `3` for top right, `4` for top
* center and `5` for bottom center.
*/
position: PropTypes.number,
/**
* The position of the arrow relative to the children. Possible values are
* `0` for left, `1` for center and `2` for right.
*/
positionOnChildren: PropTypes.number,
/**
* Specifies the DOM node the context menu will be rendered into.
*/
parent:
typeof Element !== 'undefined'
? PropTypes.instanceOf(Element)
: () => {},
/**
* The React node that the context menu refers to.
*/
children: PropTypes.node,
/**
* Called when the `onclick`-event is triggered on the children.
*/
onChildrenClick: PropTypes.func,
/**
* A React style object that will be applied to the children wrapper.
*/
childrenStyle: PropTypes.objectOf(
PropTypes.oneOfType([PropTypes.string, PropTypes.number])
),
/**
* A classname string that will be applied to the children wrapper.
*/
childrenClassName: PropTypes.string,
/**
* Wether to stop propagation of click events on the children elements.
*/
stopPropagation: PropTypes.bool,
/**
* The minimum width of the context menu.
*/
minWidth: PropTypes.number,
/**
* The maximum width of the context menu.
*/
maxWidth: PropTypes.number,
/**
* Adds a white background to the children wrapper, for when it would
* otherwise be difficult to view (e.g. on images or video).
*/
showTriggerBackground: PropTypes.bool,
/**
* A classname string applied to the Bubble component.
*/
className: PropTypes.string,
/**
* A React style object that is applied to the Bubble component.
*/
// eslint-disable-next-line react/forbid-prop-types
style: PropTypes.object,
/**
* Removes the parent padding to the page borders from the context menu
* position. This is needed when the parent is padded and relatively
* positioned.
*/
removeParentSpace: PropTypes.bool,
/**
* Disables the use of a dialog on mobile.
*/
disableDialog: PropTypes.bool,
/**
* Adjust the distance of the arrow and the end of the children. This only
* applies if `positionOnChildren` is set to left (`0`) or right (`2`).
*/
arrowDistance: PropTypes.number,
};
ContextMenu.displayName = 'ContextMenu';
export default ContextMenu;