-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathDialog.js
759 lines (630 loc) · 25.8 KB
/
Dialog.js
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import * as React from 'react';
import PrimeReact, { PrimeReactContext, localeOption } from '../api/Api';
import { useHandleStyle } from '../componentbase/ComponentBase';
import { CSSTransition } from '../csstransition/CSSTransition';
import { ESC_KEY_HANDLING_PRIORITIES, useDisplayOrder, useEventListener, useGlobalOnEscapeKey, useMergeProps, useMountEffect, useUnmountEffect, useUpdateEffect } from '../hooks/Hooks';
import { TimesIcon } from '../icons/times';
import { WindowMaximizeIcon } from '../icons/windowmaximize';
import { WindowMinimizeIcon } from '../icons/windowminimize';
import { Portal } from '../portal/Portal';
import { Ripple } from '../ripple/Ripple';
import { DomHandler, IconUtils, ObjectUtils, UniqueComponentId, ZIndexUtils, classNames } from '../utils/Utils';
import { DialogBase } from './DialogBase';
export const Dialog = React.forwardRef((inProps, ref) => {
const mergeProps = useMergeProps();
const context = React.useContext(PrimeReactContext);
const props = DialogBase.getProps(inProps, context);
const uniqueId = props.id ? props.id : UniqueComponentId();
const [idState, setIdState] = React.useState(uniqueId);
const [maskVisibleState, setMaskVisibleState] = React.useState(false);
const [visibleState, setVisibleState] = React.useState(false);
const [maximizedState, setMaximizedState] = React.useState(props.maximized);
const dialogRef = React.useRef(null);
const maskRef = React.useRef(null);
const pointerRef = React.useRef(null);
const contentRef = React.useRef(null);
const headerRef = React.useRef(null);
const footerRef = React.useRef(null);
const closeRef = React.useRef(null);
const dragging = React.useRef(false);
const resizing = React.useRef(false);
const lastPageX = React.useRef(null);
const lastPageY = React.useRef(null);
const styleElement = React.useRef(null);
const attributeSelector = React.useRef(uniqueId);
const focusElementOnHide = React.useRef(null);
const maximized = props.onMaximize ? props.maximized : maximizedState;
const shouldBlockScroll = visibleState && (props.blockScroll || (props.maximizable && maximized));
const isCloseOnEscape = props.closable && props.closeOnEscape && visibleState;
const displayOrder = useDisplayOrder('dialog', isCloseOnEscape);
const { ptm, cx, sx, isUnstyled } = DialogBase.setMetaData({
props,
...props.__parentMetadata,
state: {
id: idState,
maximized: maximized,
containerVisible: maskVisibleState
}
});
useHandleStyle(DialogBase.css.styles, isUnstyled, { name: 'dialog' });
useGlobalOnEscapeKey({
callback: (event) => {
onClose(event);
},
when: isCloseOnEscape && displayOrder,
priority: [ESC_KEY_HANDLING_PRIORITIES.DIALOG, displayOrder]
});
const [bindDocumentKeyDownListener, unbindDocumentKeyDownListener] = useEventListener({ type: 'keydown', listener: (event) => onKeyDown(event) });
const [bindDocumentResizeListener, unbindDocumentResizeListener] = useEventListener({ type: 'mousemove', target: () => window.document, listener: (event) => onResize(event) });
const [bindDocumentResizeEndListener, unbindDocumentResizEndListener] = useEventListener({ type: 'mouseup', target: () => window.document, listener: (event) => onResizeEnd(event) });
const [bindDocumentDragListener, unbindDocumentDragListener] = useEventListener({ type: 'mousemove', target: () => window.document, listener: (event) => onDrag(event) });
const [bindDocumentDragEndListener, unbindDocumentDragEndListener] = useEventListener({ type: 'mouseup', target: () => window.document, listener: (event) => onDragEnd(event) });
const onClose = (event) => {
props.onHide();
event.preventDefault();
};
const focus = () => {
let activeElement = document.activeElement;
let isActiveElementInDialog = activeElement && dialogRef.current && dialogRef.current.contains(activeElement);
if (!isActiveElementInDialog && props.closable && props.showHeader && closeRef.current) {
closeRef.current.focus();
}
};
const onDialogPointerDown = (event) => {
pointerRef.current = event.target;
props.onPointerDown && props.onPointerDown(event);
};
const onMaskPointerUp = (event) => {
if (props.dismissableMask && props.modal && maskRef.current === event.target && !pointerRef.current) {
onClose(event);
}
props.onMaskClick && props.onMaskClick(event);
pointerRef.current = null;
};
const toggleMaximize = (event) => {
if (props.onMaximize) {
props.onMaximize({
originalEvent: event,
maximized: !maximized
});
} else {
setMaximizedState((prevMaximized) => !prevMaximized);
}
event.preventDefault();
};
const onKeyDown = (event) => {
const currentTarget = event.currentTarget;
if (!currentTarget || !currentTarget.primeDialogParams) {
return;
}
const params = currentTarget.primeDialogParams;
const paramLength = params.length;
const dialogId = params[paramLength - 1] ? params[paramLength - 1].id : undefined;
if (dialogId !== idState) {
return;
}
const dialog = document.getElementById(dialogId);
if (event.key === 'Tab') {
event.preventDefault();
const focusableElements = DomHandler.getFocusableElements(dialog);
if (focusableElements && focusableElements.length > 0) {
if (!document.activeElement) {
focusableElements[0].focus();
} else {
const focusedIndex = focusableElements.indexOf(document.activeElement);
if (event.shiftKey) {
if (focusedIndex === -1 || focusedIndex === 0) {
focusableElements[focusableElements.length - 1].focus();
} else {
focusableElements[focusedIndex - 1].focus();
}
} else if (focusedIndex === -1 || focusedIndex === focusableElements.length - 1) {
focusableElements[0].focus();
} else {
focusableElements[focusedIndex + 1].focus();
}
}
}
}
};
const onDragStart = (event) => {
if (DomHandler.hasClass(event.target, 'p-dialog-header-icon') || DomHandler.hasClass(event.target.parentElement, 'p-dialog-header-icon')) {
return;
}
if (props.draggable) {
dragging.current = true;
lastPageX.current = event.pageX;
lastPageY.current = event.pageY;
dialogRef.current.style.margin = '0';
DomHandler.addClass(document.body, 'p-unselectable-text');
props.onDragStart && props.onDragStart(event);
}
};
const onDrag = (event) => {
if (dragging.current) {
const width = DomHandler.getOuterWidth(dialogRef.current);
const height = DomHandler.getOuterHeight(dialogRef.current);
const deltaX = event.pageX - lastPageX.current;
const deltaY = event.pageY - lastPageY.current;
const offset = dialogRef.current.getBoundingClientRect();
const leftPos = offset.left + deltaX;
const topPos = offset.top + deltaY;
const viewport = DomHandler.getViewport();
const computedStyle = getComputedStyle(dialogRef.current);
const leftMargin = parseFloat(computedStyle.marginLeft);
const topMargin = parseFloat(computedStyle.marginTop);
dialogRef.current.style.position = 'fixed';
if (props.keepInViewport) {
if (leftPos >= props.minX && leftPos + width < viewport.width) {
lastPageX.current = event.pageX;
dialogRef.current.style.left = leftPos - leftMargin + 'px';
}
if (topPos >= props.minY && topPos + height < viewport.height) {
lastPageY.current = event.pageY;
dialogRef.current.style.top = topPos - topMargin + 'px';
}
} else {
lastPageX.current = event.pageX;
dialogRef.current.style.left = leftPos - leftMargin + 'px';
lastPageY.current = event.pageY;
dialogRef.current.style.top = topPos - topMargin + 'px';
}
props.onDrag && props.onDrag(event);
}
};
const onDragEnd = (event) => {
if (dragging.current) {
dragging.current = false;
DomHandler.removeClass(document.body, 'p-unselectable-text');
props.onDragEnd && props.onDragEnd(event);
}
};
const onResizeStart = (event) => {
if (props.resizable) {
resizing.current = true;
lastPageX.current = event.pageX;
lastPageY.current = event.pageY;
DomHandler.addClass(document.body, 'p-unselectable-text');
props.onResizeStart && props.onResizeStart(event);
}
};
const convertToPx = (value, property, viewport) => {
!viewport && (viewport = DomHandler.getViewport());
const val = parseInt(value);
if (/^(\d+|(\.\d+))(\.\d+)?%$/.test(value)) {
return val * (viewport[property] / 100);
}
return val;
};
const onResize = (event) => {
if (resizing.current) {
const deltaX = event.pageX - lastPageX.current;
const deltaY = event.pageY - lastPageY.current;
const width = DomHandler.getOuterWidth(dialogRef.current);
const height = DomHandler.getOuterHeight(dialogRef.current);
const offset = dialogRef.current.getBoundingClientRect();
const viewport = DomHandler.getViewport();
const hasBeenDragged = !parseInt(dialogRef.current.style.top) || !parseInt(dialogRef.current.style.left);
const minWidth = convertToPx(dialogRef.current.style.minWidth, 'width', viewport);
const minHeight = convertToPx(dialogRef.current.style.minHeight, 'height', viewport);
let newWidth = width + deltaX;
let newHeight = height + deltaY;
if (hasBeenDragged) {
newWidth = newWidth + deltaX;
newHeight = newHeight + deltaY;
}
if ((!minWidth || newWidth > minWidth) && offset.left + newWidth < viewport.width) {
dialogRef.current.style.width = newWidth + 'px';
}
if ((!minHeight || newHeight > minHeight) && offset.top + newHeight < viewport.height) {
dialogRef.current.style.height = newHeight + 'px';
}
lastPageX.current = event.pageX;
lastPageY.current = event.pageY;
props.onResize && props.onResize(event);
}
};
const onResizeEnd = (event) => {
if (resizing.current) {
resizing.current = false;
DomHandler.removeClass(document.body, 'p-unselectable-text');
props.onResizeEnd && props.onResizeEnd(event);
}
};
const resetPosition = () => {
dialogRef.current.style.position = '';
dialogRef.current.style.left = '';
dialogRef.current.style.top = '';
dialogRef.current.style.margin = '';
};
const onEnter = () => {
dialogRef.current.setAttribute(attributeSelector.current, '');
};
const onEntered = () => {
props.onShow && props.onShow();
if (props.focusOnShow) {
focus();
}
enableDocumentSettings();
};
const onExiting = () => {
if (props.modal) {
!isUnstyled() && DomHandler.addClass(maskRef.current, 'p-component-overlay-leave');
}
};
const onExited = () => {
dragging.current = false;
ZIndexUtils.clear(maskRef.current);
setMaskVisibleState(false);
disableDocumentSettings();
// return focus to element before dialog was open
DomHandler.focus(focusElementOnHide.current);
focusElementOnHide.current = null;
};
const enableDocumentSettings = () => {
bindGlobalListeners();
};
const disableDocumentSettings = () => {
unbindGlobalListeners();
};
const updateScrollBlocker = () => {
// Scroll should be unblocked if there is at least one dialog that blocks scrolling:
const isThereAnyDialogThatBlocksScrolling = document.primeDialogParams && document.primeDialogParams.some((i) => i.hasBlockScroll);
if (isThereAnyDialogThatBlocksScrolling) {
DomHandler.blockBodyScroll();
} else {
DomHandler.unblockBodyScroll();
}
};
const updateGlobalDialogsRegistry = (isMounted) => {
// Update current dialog info in global registry if it is mounted and visible:
if (isMounted && visibleState) {
const newParam = { id: idState, hasBlockScroll: shouldBlockScroll };
// Create registry if not yet created:
if (!document.primeDialogParams) {
document.primeDialogParams = [];
}
const currentDialogIndexInRegistry = document.primeDialogParams.findIndex((dialogInRegistry) => dialogInRegistry.id === idState);
if (currentDialogIndexInRegistry === -1) {
document.primeDialogParams = [...document.primeDialogParams, newParam];
} else {
document.primeDialogParams = document.primeDialogParams.toSpliced(currentDialogIndexInRegistry, 1, newParam);
}
}
// Or remove it from global registry if unmounted or invisible:
else {
document.primeDialogParams = document.primeDialogParams && document.primeDialogParams.filter((param) => param.id !== idState);
}
// Always update scroll blocker after dialog registry - this way we ensure that
// p-overflow-hidden class is properly added/removed:
updateScrollBlocker();
};
const bindGlobalListeners = () => {
if (props.draggable) {
bindDocumentDragListener();
bindDocumentDragEndListener();
}
if (props.resizable) {
bindDocumentResizeListener();
bindDocumentResizeEndListener();
}
bindDocumentKeyDownListener();
};
const unbindGlobalListeners = () => {
unbindDocumentDragListener();
unbindDocumentDragEndListener();
unbindDocumentResizeListener();
unbindDocumentResizEndListener();
unbindDocumentKeyDownListener();
};
const createStyle = () => {
styleElement.current = DomHandler.createInlineStyle((context && context.nonce) || PrimeReact.nonce, context && context.styleContainer);
let innerHTML = '';
for (let breakpoint in props.breakpoints) {
innerHTML =
innerHTML +
`
@media screen and (max-width: ${breakpoint}) {
[data-pc-name="dialog"][${attributeSelector.current}] {
width: ${props.breakpoints[breakpoint]} !important;
}
}
`;
}
styleElement.current.innerHTML = innerHTML;
};
const destroyStyle = () => {
styleElement.current = DomHandler.removeInlineStyle(styleElement.current);
};
useMountEffect(() => {
updateGlobalDialogsRegistry(true);
if (props.visible) {
setMaskVisibleState(true);
}
});
React.useEffect(() => {
if (props.breakpoints) {
createStyle();
}
return () => {
destroyStyle();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.breakpoints]);
useUpdateEffect(() => {
if (props.visible && !maskVisibleState) {
setMaskVisibleState(true);
}
if (props.visible !== visibleState && maskVisibleState) {
setVisibleState(props.visible);
}
if (props.visible) {
// Remember the focused element before we opened the dialog
// so we can return focus to it once we close the dialog.
focusElementOnHide.current = document.activeElement;
}
}, [props.visible, maskVisibleState]);
useUpdateEffect(() => {
if (maskVisibleState) {
ZIndexUtils.set('modal', maskRef.current, (context && context.autoZIndex) || PrimeReact.autoZIndex, props.baseZIndex || (context && context.zIndex.modal) || PrimeReact.zIndex.modal);
setVisibleState(true);
}
}, [maskVisibleState]);
useUpdateEffect(() => {
updateGlobalDialogsRegistry(true);
}, [shouldBlockScroll, visibleState]);
useUnmountEffect(() => {
disableDocumentSettings();
updateGlobalDialogsRegistry(false);
DomHandler.removeInlineStyle(styleElement.current);
ZIndexUtils.clear(maskRef.current);
});
React.useImperativeHandle(ref, () => ({
props,
resetPosition,
getElement: () => dialogRef.current,
getMask: () => maskRef.current,
getContent: () => contentRef.current,
getHeader: () => headerRef.current,
getFooter: () => footerRef.current,
getCloseButton: () => closeRef.current
}));
const createCloseIcon = () => {
if (props.closable) {
const ariaLabel = props.ariaCloseIconLabel || localeOption('close');
const closeButtonIconProps = mergeProps(
{
className: cx('closeButtonIcon'),
'aria-hidden': true
},
ptm('closeButtonIcon')
);
const icon = props.closeIcon || <TimesIcon {...closeButtonIconProps} />;
const headerCloseIcon = IconUtils.getJSXIcon(icon, { ...closeButtonIconProps }, { props });
const closeButtonProps = mergeProps(
{
ref: closeRef,
type: 'button',
className: cx('closeButton'),
'aria-label': ariaLabel,
onClick: onClose
},
ptm('closeButton')
);
return (
<button {...closeButtonProps}>
{headerCloseIcon}
<Ripple />
</button>
);
}
return null;
};
const createMaximizeIcon = () => {
let icon;
const maximizableIconProps = mergeProps(
{
className: cx('maximizableIcon')
},
ptm('maximizableIcon')
);
if (!maximized) {
icon = props.maximizeIcon || <WindowMaximizeIcon {...maximizableIconProps} />;
} else {
icon = props.minimizeIcon || <WindowMinimizeIcon {...maximizableIconProps} />;
}
const toggleIcon = IconUtils.getJSXIcon(icon, maximizableIconProps, { props });
if (props.maximizable) {
const maximizableButtonProps = mergeProps(
{
type: 'button',
className: cx('maximizableButton'),
onClick: toggleMaximize
},
ptm('maximizableButton')
);
return (
<button {...maximizableButtonProps}>
{toggleIcon}
<Ripple />
</button>
);
}
return null;
};
const createHeader = () => {
if (props.showHeader) {
const closeIcon = createCloseIcon();
const maximizeIcon = createMaximizeIcon();
const icons = ObjectUtils.getJSXElement(props.icons, props);
const header = ObjectUtils.getJSXElement(props.header, props);
const headerId = idState + '_header';
const headerProps = mergeProps(
{
ref: headerRef,
style: props.headerStyle,
className: cx('header'),
onMouseDown: onDragStart
},
ptm('header')
);
const headerTitleProps = mergeProps(
{
id: headerId,
className: cx('headerTitle')
},
ptm('headerTitle')
);
const headerIconsProps = mergeProps(
{
className: cx('headerIcons')
},
ptm('headerIcons')
);
return (
<div {...headerProps}>
<div {...headerTitleProps}>{header}</div>
<div {...headerIconsProps}>
{icons}
{maximizeIcon}
{closeIcon}
</div>
</div>
);
}
return null;
};
const createContent = () => {
const contentId = idState + '_content';
const contentProps = mergeProps(
{
id: contentId,
ref: contentRef,
style: props.contentStyle,
className: cx('content')
},
ptm('content')
);
return <div {...contentProps}>{props.children}</div>;
};
const createFooter = () => {
const footer = ObjectUtils.getJSXElement(props.footer, props);
const footerProps = mergeProps(
{
ref: footerRef,
className: cx('footer')
},
ptm('footer')
);
return footer && <div {...footerProps}>{footer}</div>;
};
const createResizer = () => {
if (props.resizable) {
return <span className="p-resizable-handle" style={{ zIndex: 90 }} onMouseDown={onResizeStart} />;
}
return null;
};
const findMessageProperty = (obj) => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === 'message') {
return obj[key];
} else if (typeof obj[key] === 'object') {
const result = findMessageProperty(obj[key]);
if (result !== undefined) {
return result;
}
}
}
}
return undefined;
};
const createTemplateElement = ({ maskProps, rootProps, transitionProps }) => {
const messageProps = {
header: props.header,
content: props.message,
message: props?.children?.[1]?.props?.children
};
const templateElementProps = { headerRef, contentRef, footerRef, closeRef, hide: onClose, message: messageProps };
return (
<div {...maskProps}>
<CSSTransition nodeRef={dialogRef} {...transitionProps}>
<div {...rootProps}>{ObjectUtils.getJSXElement(inProps.content, templateElementProps)}</div>
</CSSTransition>
</div>
);
};
const createElement = ({ maskProps, rootProps, transitionProps }) => {
const header = createHeader();
const content = createContent();
const footer = createFooter();
const resizer = createResizer();
return (
<div {...maskProps}>
<CSSTransition nodeRef={dialogRef} {...transitionProps}>
<div {...rootProps}>
{header}
{content}
{footer}
{resizer}
</div>
</CSSTransition>
</div>
);
};
const createDialog = () => {
const headerId = idState + '_header';
const contentId = idState + '_content';
const transitionTimeout = {
enter: props.position === 'center' ? 150 : 300,
exit: props.position === 'center' ? 150 : 300
};
const maskProps = mergeProps(
{
ref: maskRef,
style: sx('mask'),
className: cx('mask'),
onPointerUp: onMaskPointerUp
},
ptm('mask')
);
const rootProps = mergeProps(
{
ref: dialogRef,
id: idState,
className: classNames(props.className, cx('root', { props, maximized, context })),
style: props.style,
onClick: props.onClick,
role: 'dialog',
'aria-labelledby': headerId,
'aria-describedby': contentId,
'aria-modal': props.modal,
onPointerDown: onDialogPointerDown
},
DialogBase.getOtherProps(props),
ptm('root')
);
const transitionProps = mergeProps(
{
classNames: cx('transition'),
timeout: transitionTimeout,
in: visibleState,
options: props.transitionOptions,
unmountOnExit: true,
onEnter: onEnter,
onEntered: onEntered,
onExiting: onExiting,
onExited: onExited
},
ptm('transition')
);
if (inProps?.content) {
const templateElement = createTemplateElement({ maskProps, rootProps, transitionProps });
return <Portal element={templateElement} appendTo={props.appendTo} visible />;
}
const element = createElement({ maskProps, rootProps, transitionProps });
return <Portal element={element} appendTo={props.appendTo} visible />;
};
return maskVisibleState && createDialog();
});
Dialog.displayName = 'Dialog';