Debian Codegraph @

node/@patternfly/react-core/src/components/Modal/Modal.tsx

raw
1 import { Component } from 'react';
2 import * as ReactDOM from 'react-dom';
3 import { canUseDOM, KeyTypes, PickOptional } from '../../helpers';
4 import { css } from '@patternfly/react-styles';
5 import styles from '@patternfly/react-styles/css/components/Backdrop/backdrop';
6 import { ModalContent } from './ModalContent';
7 import { OUIAProps } from '../../helpers';
8 import { SSRSafeIds } from '../../helpers/SSRSafeIds/SSRSafeIds';
9
10 export interface ModalProps extends React.HTMLProps<HTMLDivElement>, OUIAProps {
11 /** The parent container to append the modal to. Defaults to "document.body". */
12 appendTo?: HTMLElement | (() => HTMLElement);
13 /** Id to use for the modal box description. This should match the ModalHeader labelId or descriptorId. */
14 'aria-describedby'?: string;
15 /** Adds an accessible name to the modal when there is no title in the ModalHeader. */
16 'aria-label'?: string;
17 /** Id to use for the modal box label. This should include the ModalHeader labelId. */
18 'aria-labelledby'?: string;
19 /** Content rendered inside the modal. */
20 children: React.ReactNode;
21 /** Additional classes added to the modal. */
22 className?: string;
23 /** Additional classes added to the modal backdrop. */
24 backdropClassName?: string;
25 /** Flag to disable focus trap. */
26 disableFocusTrap?: boolean;
27 /** The element to focus when the modal opens. By default the first
28 * focusable element will receive focus.
29 */
30 elementToFocus?: HTMLElement | SVGElement | string;
31 /** Id of the focus trap in the ModalContent component */
32 focusTrapId?: string;
33 /** An id to use for the modal box container. */
34 id?: string;
35 /** Flag to show the modal. */
36 isOpen?: boolean;
37 /** Add callback for when the close button is clicked. This prop needs to be passed to render the close button */
38 onClose?: (event: KeyboardEvent | React.MouseEvent) => void;
39 /** Modal handles pressing of the escape key and closes the modal. If you want to handle
40 * this yourself you can use this callback function. */
41 onEscapePress?: (event: KeyboardEvent) => void;
42 /** Position of the modal. By default a modal will be positioned vertically and horizontally centered. */
43 position?: 'default' | 'top';
44 /** Offset from alternate position. Can be any valid CSS length/percentage. */
45 positionOffset?: string;
46 /** Variant of the modal. */
47 variant?: 'small' | 'medium' | 'large' | 'default';
48 /** Default width of the modal. */
49 width?: number | string;
50 /** Maximum width of the modal. */
51 maxWidth?: number | string;
52 /** Value to overwrite the randomly generated data-ouia-component-id.*/
53 ouiaId?: number | string;
54 /** Set the value of data-ouia-safe. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */
55 ouiaSafe?: boolean;
56 }
57
58 export enum ModalVariant {
59 small = 'small',
60 medium = 'medium',
61 large = 'large',
62 default = 'default'
63 }
64
65 interface ModalState {
66 mounted: boolean;
67 }
68
69 class Modal extends Component<ModalProps, ModalState> {
70 static displayName = 'Modal';
71 static currentId = 0;
72 boxId = '';
73 backdropId = '';
74
75 static defaultProps: PickOptional<ModalProps> = {
76 isOpen: false,
77 variant: 'default',
78 appendTo: () => document.body,
79 ouiaSafe: true,
80 position: 'default'
81 };
82
83 constructor(props: ModalProps) {
84 super(props);
85 const boxIdNum = Modal.currentId++;
86 const backdropId = boxIdNum + 1;
87 this.boxId = props.id || `pf-modal-part-${boxIdNum}`;
88 this.backdropId = `pf-modal-part-${backdropId}`;
89
90 this.state = {
91 mounted: false
92 };
93 }
94
95 handleEscKeyClick = (event: KeyboardEvent): void => {
96 const { onEscapePress } = this.props;
97 if (event.key === KeyTypes.Escape && this.props.isOpen) {
98 onEscapePress ? onEscapePress(event) : this.props.onClose?.(event);
99 }
100 };
101
102 getElement = (appendTo: HTMLElement | (() => HTMLElement)) => {
103 if (typeof appendTo === 'function') {
104 return appendTo();
105 }
106 return appendTo || document.body;
107 };
108
109 toggleSiblingsFromScreenReaders = (hide: boolean) => {
110 const { appendTo } = this.props;
111 const target: HTMLElement = this.getElement(appendTo);
112 const bodyChildren = target.children;
113 for (const child of Array.from(bodyChildren)) {
114 if (child.id !== this.backdropId) {
115 hide ? child.setAttribute('aria-hidden', '' + hide) : child.removeAttribute('aria-hidden');
116 }
117 }
118 };
119
120 isEmpty = (value: string | null | undefined) => value === null || value === undefined || value === '';
121
122 componentDidMount() {
123 this.setState({ mounted: true });
124 const { appendTo } = this.props;
125 const target: HTMLElement = this.getElement(appendTo);
126 target.addEventListener('keydown', this.handleEscKeyClick, false);
127
128 if (this.props.isOpen) {
129 target.classList.add(css(styles.backdropOpen));
130 this.toggleSiblingsFromScreenReaders(true);
131 }
132 }
133
134 componentDidUpdate(prevProps: ModalProps) {
135 const { appendTo } = this.props;
136 const target: HTMLElement = this.getElement(appendTo);
137 if (this.props.isOpen) {
138 target.classList.add(css(styles.backdropOpen));
139 this.toggleSiblingsFromScreenReaders(true);
140 } else {
141 if (prevProps.isOpen !== this.props.isOpen) {
142 target.classList.remove(css(styles.backdropOpen));
143 this.toggleSiblingsFromScreenReaders(false);
144 }
145 }
146 }
147
148 componentWillUnmount() {
149 const { appendTo } = this.props;
150 const target: HTMLElement = this.getElement(appendTo);
151 target.removeEventListener('keydown', this.handleEscKeyClick, false);
152 target.classList.remove(css(styles.backdropOpen));
153 this.toggleSiblingsFromScreenReaders(false);
154 }
155
156 render() {
157 const {
158 appendTo,
159 // eslint-disable-next-line @typescript-eslint/no-unused-vars
160 onEscapePress,
161 'aria-labelledby': ariaLabelledby,
162 'aria-label': ariaLabel,
163 'aria-describedby': ariaDescribedby,
164 ouiaId,
165 ouiaSafe,
166 position,
167 elementToFocus,
168 ...props
169 } = this.props;
170
171 if (!this.state.mounted || !canUseDOM || !this.getElement(appendTo)) {
172 return null;
173 }
174
175 return (
176 <SSRSafeIds prefix="pf-" ouiaComponentType={`Modal${this.props.variant ? `-${this.props.variant}` : ''}`}>
177 {(_, generatedOuiaId) =>
178 ReactDOM.createPortal(
179 <ModalContent
180 boxId={this.boxId}
181 backdropId={this.backdropId}
182 aria-label={ariaLabel}
183 aria-describedby={ariaDescribedby}
184 aria-labelledby={ariaLabelledby}
185 ouiaId={ouiaId !== undefined ? ouiaId : generatedOuiaId}
186 ouiaSafe={ouiaSafe}
187 position={position}
188 elementToFocus={elementToFocus}
189 backdropClassName={props.backdropClassName}
190 {...props}
191 />,
192 this.getElement(appendTo)
193 ) as React.ReactElement<any>
194 }
195 </SSRSafeIds>
196 );
197 }
198 }
199
200 export { Modal };