-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathSessionWrapperModal.tsx
More file actions
531 lines (496 loc) · 16.3 KB
/
SessionWrapperModal.tsx
File metadata and controls
531 lines (496 loc) · 16.3 KB
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
/* eslint-disable no-unneeded-ternary */
import styled from 'styled-components';
import useKey from 'react-use/lib/useKey';
import clsx from 'clsx';
import type { CSSProperties } from 'styled-components';
import { ReactNode, useState, useRef, type SessionDataTestId } from 'react';
import { Flex } from './basic/Flex';
import { SpacerLG } from './basic/Text';
import { SessionLucideIconButton } from './icon/SessionIconButton';
import { SessionFocusTrap } from './SessionFocusTrap';
import { useHTMLDirection } from '../util/i18n/rtlSupport';
import { StyledRootDialog } from './dialog/StyledRootDialog';
import { LUCIDE_ICONS_UNICODE } from './icon/lucide';
import { IsModalScrolledContext, useIsModalScrolled } from '../contexts/IsModalScrolledContext';
import { OnModalCloseContext, useOnModalClose } from '../contexts/OnModalCloseContext';
import { SessionButton, SessionButtonColor, SessionButtonType } from './basic/SessionButton';
import type { ModalId } from '../state/ducks/modalDialog';
import { useIsTopModal } from '../state/selectors/modal';
import {
ModalHasActionButtonContext,
useModalHasActionButtonContext,
} from '../contexts/ModalHasActionButtonContext';
import { isEscapeKey } from '../util/keyboardShortcuts';
type WithExtraLeftButton = {
/**
* A button to be displayed on the left side of the header title.
* If all you want is a close button, use showExitIcon instead.
* Check other usages to use the correct icon size and styling.
*/
extraLeftButton?: ReactNode;
};
type WithExtraRightButton = {
/**
* A button to be displayed on the right side of the header title.
* Check other usages to use the correct icon size and styling.
*/
extraRightButton?: ReactNode;
};
type WithShowExitIcon = { showExitIcon?: boolean };
const StyledModalHeader = styled(Flex)<{
$bigHeader?: boolean;
$scrolled: boolean;
$floatingHeader?: boolean;
}>`
position: ${props => (props.$floatingHeader ? 'absolute' : 'relative')};
font-family: var(--font-default);
font-size: ${props => (props.$bigHeader ? 'var(--font-size-h4)' : 'var(--font-size-xl)')};
font-weight: 500;
text-align: center;
line-height: 18px;
background-color: ${props =>
props.$floatingHeader && !props.$scrolled
? 'var(--transparent-color)'
: 'var(--modal-background-content-color)'};
width: ${props => (props.$floatingHeader ? '-webkit-fill-available' : 'auto')};
transition-duration: var(--default-duration);
z-index: 3;
&::after {
content: '';
position: absolute;
left: 0;
bottom: -16px; // bottom and height have to match for the border to be correctly placed
height: 16px; // bottom and height have to match for the border to be correctly placed
width: 100%;
transition-duration: var(--default-duration);
background: linear-gradient(to bottom, var(--modal-shadow-color), transparent);
pointer-events: none;
opacity: ${props => (!props.$scrolled ? '0' : '1')};
}
`;
export enum WrapperModalWidth {
narrow = '350px',
normal = '420px',
wide = '500px',
debug = '75%',
}
const StyledModal = styled.div<{
$contentMaxWidth?: WrapperModalWidth;
$contentMinWidth?: WrapperModalWidth;
$padding?: string;
$topAnchor: ModalTopAnchor;
}>`
position: absolute;
top: ${props => (props.$topAnchor === 'center' ? 'auto' : props.$topAnchor)};
max-height: ${props =>
`calc(100vh - ${props.$topAnchor === 'center' ? '10vh' : `2 * ${props.$topAnchor}`})`}; // 2* to have the modal centered vertically, if it overflows
animation: fadein var(--default-duration);
z-index: 150;
max-width: ${props =>
props.$contentMaxWidth ? props.$contentMaxWidth : WrapperModalWidth.normal};
min-width: ${props =>
props.$contentMinWidth ? props.$contentMinWidth : WrapperModalWidth.normal};
box-sizing: border-box;
font-family: var(--font-default);
background-color: var(--modal-background-content-color);
color: var(--text-primary-color);
border: var(--default-borders);
border-radius: 13px;
box-shadow: var(--modal-drop-shadow);
margin: auto auto;
padding: ${props =>
props.$padding
? props.$padding
: // Note: no padding by default as it depends on what is rendered, see the ModalMap before you change something here
'0'};
overflow: hidden;
display: flex;
flex-direction: column;
&__centered {
display: flex;
flex-direction: column;
align-items: center;
// to allow new lines
white-space: pre-wrap;
}
&__text-highlight {
@include text-highlight(var(--primary-color));
color: var(--black-color);
font-family: var(--font-mono);
font-style: normal;
font-size: var(--font-size-xs);
}
`;
const StyledModalBody = styled.div<{ $shouldOverflow: boolean; $removeScrollbarGutter?: boolean }>`
${props => (!props.$removeScrollbarGutter ? 'scrollbar-gutter: stable;' : '')}
margin: 0;
font-family: var(--font-default);
font-size: var(--font-size-md);
height: 100%;
overflow-y: ${props => (props.$shouldOverflow ? 'auto' : 'hidden')};
overflow-x: hidden;
.message {
text-align: center;
}
`;
const StyledTitle = styled.div<{ $bigHeader?: boolean }>`
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
padding: ${props =>
props.$bigHeader ? 'var(--margins-sm)' : 'var(--margins-xs) var(--margins-sm)'};
`;
export const ModalActionsContainer = ({
children,
maxWidth,
style = {},
buttonType,
}: {
children: ReactNode;
style?: CSSProperties;
maxWidth?: string;
/**
* Depending on the button type, the margin block is different.
*/
buttonType: SessionButtonType;
}) => {
return (
<Flex
$container={true}
width={'100%'}
$justifyContent="space-evenly"
$maxWidth={maxWidth || '300px'}
$alignItems="center"
$flexGap="var(--margins-md)"
height="unset"
style={{
justifySelf: 'center',
marginBlock:
buttonType === SessionButtonType.Simple ? 'var(--margins-sm)' : 'var(--margins-lg)',
...style,
}}
data-testid="modal-actions-container"
>
{children}
</Flex>
);
};
/**
* In the modal, the bottom actions sometimes have a border.
* When they do, they all share the same styling (minWidth --modal-actions-outline-min-width) so this component is here to reuse that logic.
*/
export function ModalBottomButtonWithBorder({
text,
onClick,
buttonColor,
dataTestId,
buttonType,
disabled,
}: {
text: string;
onClick: () => void | Promise<void>;
disabled?: boolean;
buttonColor?: SessionButtonColor;
dataTestId?: SessionDataTestId;
buttonType?: SessionButtonType;
}) {
return (
<SessionButton
text={text}
onClick={onClick}
disabled={disabled}
buttonColor={buttonColor}
buttonType={buttonType}
dataTestId={dataTestId}
style={{ minWidth: 'var(--modal-actions-outline-min-width)' }}
/>
);
}
export type ModalTopAnchor = '5vh' | 'center';
type SessionWrapperModalType = {
headerChildren?: ReactNode;
// Moves the header to be inside the modals body but outside the content Flex, including it in the scrollable content and preserving body padding.
moveHeaderIntoScrollableBody?: boolean;
children: ReactNode;
/**
* *Should* be some SessionButtons enclosed in a ModalActionsContainer
*/
buttonChildren?: ReactNode;
$contentMaxWidth?: WrapperModalWidth;
$contentMinWidth?: WrapperModalWidth;
shouldOverflow?: boolean;
padding?: string;
classes?: string;
allowOutsideClick?: boolean;
removeScrollbarGutter?: boolean;
modalDataTestId?: SessionDataTestId;
/**
* Instead of centering the modal (and having layout shifts on height change), we can use this to anchor the modal to a % from the top of the screen.
* Defaults to 'center' to keep the modal centered (should only be used for modals that doesn't have height changes)
*/
topAnchor?: ModalTopAnchor;
$flexGap?: string;
style?: Omit<CSSProperties, 'maxWidth' | 'minWidth' | 'padding' | 'border'>;
modalId: ModalId;
clickOutsideDeactivates?: boolean;
showFloatingCloseButton?: boolean;
};
const useNeedsSpacerOnSide = ({
extraLeftButton,
extraRightButton,
showExitIcon,
}: WithShowExitIcon & WithExtraRightButton & WithExtraLeftButton) => {
const buttonsLeft = extraLeftButton ? 1 : 0;
const buttonsRight = (extraRightButton ? 1 : 0) + (showExitIcon ? 1 : 0);
const extraButtonsOnRightSide = buttonsRight - buttonsLeft;
return {
count: Math.abs(extraButtonsOnRightSide),
side: extraButtonsOnRightSide === 0 ? 'none' : extraButtonsOnRightSide > 0 ? 'left' : 'right',
};
};
function ExtraSpacerLeft(props: WithShowExitIcon & WithExtraRightButton & WithExtraLeftButton) {
const extraOn = useNeedsSpacerOnSide(props);
if (extraOn.side !== 'left' || extraOn.count === 0) {
return null;
}
if (extraOn.count === 1) {
return <SpacerLG />;
}
if (extraOn.count === 2) {
return (
<>
<SpacerLG />
<SpacerLG />
</>
);
}
throw new Error('ExtraSpacerLeft: not handled case for extraOn.count');
}
function ExtraSpacerRight(props: WithShowExitIcon & WithExtraRightButton & WithExtraLeftButton) {
const extraOn = useNeedsSpacerOnSide(props);
if (extraOn.side !== 'right' || extraOn.count === 0) {
return null;
}
if (extraOn.count === 1) {
return <SpacerLG />;
}
if (extraOn.count === 2) {
return (
<>
<SpacerLG />
<SpacerLG />
</>
);
}
throw new Error('ExtraSpacerRight: not handled case for extraOn.count');
}
/**
* A basic modal header with a title, an optional left button and/or exit icon.
* To be used as `headerChildren` prop as part of SessionWrapperModal.
*/
export const ModalBasicHeader = ({
showExitIcon,
extraLeftButton,
title,
bigHeader,
modalHeaderDataTestId,
extraRightButton,
floatingHeader,
}: WithShowExitIcon &
WithExtraRightButton &
WithExtraLeftButton & {
title?: ReactNode;
bigHeader?: boolean;
floatingHeader?: boolean;
modalHeaderDataTestId?: SessionDataTestId;
}) => {
const onClose = useOnModalClose();
const scrolled = useIsModalScrolled();
const hasActionButton = useModalHasActionButtonContext();
return (
<StyledModalHeader
data-testid={modalHeaderDataTestId}
$container={true}
$flexDirection={'row'}
$justifyContent={'space-between'}
$alignItems={'center'}
$padding={'var(--margins-lg) var(--margins-lg) var(--margins-sm) var(--margins-lg)'}
$bigHeader={bigHeader}
$floatingHeader={floatingHeader}
$scrolled={scrolled}
>
<Flex
$container={true}
$flexDirection={'row'}
$alignItems={'center'}
$padding={'0'}
$margin={'0'}
>
{extraLeftButton}
{/* Note: this is just here to keep the title centered, no matter the buttons we have */}
<ExtraSpacerLeft
showExitIcon={showExitIcon}
extraLeftButton={extraLeftButton}
extraRightButton={extraRightButton}
/>
</Flex>
<StyledTitle
$bigHeader={bigHeader}
// Make the title clickable (needed for the focus trap to work),
// when it appears that we do have buttons in the modal
tabIndex={!showExitIcon && !extraLeftButton && !hasActionButton ? 0 : undefined}
data-testid="modal-heading"
>
{title}
</StyledTitle>
<Flex
$container={true}
$flexDirection={'row'}
$alignItems={'center'}
$padding={'0'}
$margin={'0'}
>
{/* Note: this is just here to keep the title centered, no matter the buttons we have */}
<ExtraSpacerRight
showExitIcon={showExitIcon}
extraLeftButton={extraLeftButton}
extraRightButton={extraRightButton}
/>
{extraRightButton}
{showExitIcon ? (
<SessionLucideIconButton
unicode={LUCIDE_ICONS_UNICODE.X}
// don't ask me why, but the X icon on lucide has more padding than the others.
// So we need to use one size bigger than the other icons we use on the header.
iconSize={'huge'}
onClick={onClose ?? undefined}
padding={'0'}
margin={'0 var(--margins-xs) 0 var(--margins-xs)'}
dataTestId="modal-close-button"
iconColor="var(--text-primary-color)"
/>
) : null}
</Flex>
</StyledModalHeader>
);
};
const StyledFloatingCloseButtonContainer = styled.div`
position: absolute;
top: var(--margins-md);
right: var(--margins-md);
padding: var(--margins-xs);
border-radius: 100%;
background-color: var(--background-tertiary-color);
`;
function FloatingCloseButton({ onClick }: { onClick?: () => void }) {
return (
<StyledFloatingCloseButtonContainer>
<SessionLucideIconButton
unicode={LUCIDE_ICONS_UNICODE.X}
onClick={onClick}
iconSize="large"
iconColor="var(--text-primary-color)"
/>
</StyledFloatingCloseButtonContainer>
);
}
/**
* A generic modal component that is constructed from a provided header, body and some actions.
*/
export const SessionWrapperModal = (props: SessionWrapperModalType & { onClose?: () => void }) => {
const {
$contentMinWidth,
$contentMaxWidth,
shouldOverflow = false,
padding,
classes,
allowOutsideClick,
modalDataTestId,
style,
removeScrollbarGutter,
onClose,
topAnchor,
$flexGap,
modalId,
moveHeaderIntoScrollableBody,
buttonChildren,
// TODO: make this work with the focus trap
clickOutsideDeactivates = true,
showFloatingCloseButton = false,
} = props;
const [scrolled, setScrolled] = useState(false);
const modalRef = useRef<HTMLDivElement>(null);
const htmlDirection = useHTMLDirection();
const isTopModal = useIsTopModal(modalId);
useKey((event: KeyboardEvent) => {
if (!isTopModal) {
return false;
}
return isEscapeKey(event);
}, onClose);
const handleClick = (e: any) => {
if (clickOutsideDeactivates && !modalRef.current?.contains(e.target)) {
onClose?.();
}
};
const handleScroll = (e: any) => {
const { scrollTop } = e.target;
setScrolled(!!scrollTop);
};
const separateHeader =
props.headerChildren && !moveHeaderIntoScrollableBody ? props.headerChildren : null;
const bodyHeader =
props.headerChildren && moveHeaderIntoScrollableBody ? props.headerChildren : null;
return (
<SessionFocusTrap
focusTrapId="SessionWrapperModal"
allowOutsideClick={allowOutsideClick}
initialFocus={() => modalRef.current}
>
<IsModalScrolledContext.Provider value={scrolled}>
<ModalHasActionButtonContext.Provider value={!!buttonChildren}>
<OnModalCloseContext.Provider value={onClose ?? null}>
<StyledRootDialog
$shouldOverflow={shouldOverflow}
className={clsx('modal', classes)}
onMouseDown={handleClick}
role="dialog"
data-testid={modalDataTestId}
dir={htmlDirection}
>
<StyledModal
$contentMaxWidth={$contentMaxWidth}
$contentMinWidth={$contentMinWidth}
$padding={padding}
style={style}
$topAnchor={topAnchor ?? 'center'}
ref={modalRef}
data-modal-id={modalId}
>
{separateHeader}
<StyledModalBody
onScroll={handleScroll}
$shouldOverflow={shouldOverflow}
$removeScrollbarGutter={removeScrollbarGutter}
>
{bodyHeader}
<Flex
$container={true}
$alignItems="center"
$flexDirection="column"
$paddingInline="var(--margins-lg)" // add the padding here so that the rest of the modal isn't affected (including buttonChildren/ModalHeader)
$flexGap={$flexGap}
>
{props.children}
</Flex>
{buttonChildren ? buttonChildren : <SpacerLG />}
</StyledModalBody>
{showFloatingCloseButton ? <FloatingCloseButton onClick={onClose} /> : null}
</StyledModal>
</StyledRootDialog>
</OnModalCloseContext.Provider>
</ModalHasActionButtonContext.Provider>
</IsModalScrolledContext.Provider>
</SessionFocusTrap>
);
};