Debian Codegraph @

node/@patternfly/react-core/src/deprecated/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 Omit<React.HTMLProps<HTMLDivElement>, 'title'>, OUIAProps {
11 /** Action buttons to add to the standard modal footer. Ignored if the footer property
12 * is passed in.
13 */
14 actions?: any;
15 /** The parent container to append the modal to. Defaults to "document.body". */
16 appendTo?: HTMLElement | (() => HTMLElement);
17 /** Id to use for the modal box descriptor. */
18 'aria-describedby'?: string;
19 /** Accessible descriptor of the modal. */
20 'aria-label'?: string;
21 /** Id to use for the modal box label. */
22 'aria-labelledby'?: string;
23 /** Accessible label applied to the modal box body. This should be used to communicate
24 * important information about the modal box body div element if needed, such as that it
25 * is scrollable.
26 */
27 bodyAriaLabel?: string;
28 /** Accessible role applied to the modal box body. This will default to "region" if the
29 * bodyAriaLabel property is passed in. Set to a more appropriate role as applicable
30 * based on the modal content and context.
31 */
32 bodyAriaRole?: string;
33 /** Content rendered inside the modal. */
34 children: React.ReactNode;
35 /** Additional classes added to the modal. */
36 className?: string;
37 /** Description of the modal. */
38 description?: React.ReactNode;
39 /** Flag to disable focus trap. */
40 disableFocusTrap?: boolean;
41 /** The element to focus when the modal opens. By default the first
42 * focusable element will receive focus.
43 */
44 elementToFocus?: HTMLElement | SVGElement | string;
45 /** Custom footer. */
46 footer?: React.ReactNode;
47 /** Flag indicating if modal content should be placed in a modal box body wrapper. */
48 hasNoBodyWrapper?: boolean;
49 /** Complex header (more than just text), supersedes the title property for header content. */
50 header?: React.ReactNode;
51 /** Optional help section for the modal header. */
52 help?: React.ReactNode;
53 /** An id to use for the modal box container. */
54 id?: string;
55 /** Flag to show the modal. */
56 isOpen?: boolean;
57 /** A callback for when the close button is clicked. */
58 onClose?: (event: KeyboardEvent | React.MouseEvent) => void;
59 /** Modal handles pressing of the escape key and closes the modal. If you want to handle
60 * this yourself you can use this callback function. */
61 onEscapePress?: (event: KeyboardEvent) => void;
62 /** Position of the modal. By default a modal will be positioned vertically and horizontally centered. */
63 position?: 'default' | 'top';
64 /** Offset from alternate position. Can be any valid CSS length/percentage. */
65 positionOffset?: string;
66 /** Flag to show the close button in the header area of the modal. */
67 showClose?: boolean;
68 /** Text content of the modal header. */
69 title?: React.ReactNode;
70 /** Optional alert icon (or other) to show before the title of the modal header. When the
71 * predefined alert types are used the default styling will be automatically applied.
72 */
73 titleIconVariant?: 'success' | 'danger' | 'warning' | 'info' | 'custom' | React.ComponentType<any>;
74 /** Optional title label text for screen readers. */
75 titleLabel?: string;
76 /** Variant of the modal. */
77 variant?: 'small' | 'medium' | 'large' | 'default';
78 /** Default width of the modal. */
79 width?: number | string;
80 /** Maximum width of the modal. */
81 maxWidth?: number | string;
82 /** Value to overwrite the randomly generated data-ouia-component-id.*/
83 ouiaId?: number | string;
84 /** 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. */
85 ouiaSafe?: boolean;
86 }
87
88 export enum ModalVariant {
89 small = 'small',
90 medium = 'medium',
91 large = 'large',
92 default = 'default'
93 }
94
95 interface ModalState {
96 mounted: boolean;
97 }
98
99 class Modal extends Component<ModalProps, ModalState> {
100 static displayName = 'Modal';
101 static currentId = 0;
102 boxId = '';
103 labelId = '';
104 descriptorId = '';
105 backdropId = '';
106
107 static defaultProps: PickOptional<ModalProps> = {
108 className: '',
109 isOpen: false,
110 title: '',
111 titleIconVariant: null,
112 titleLabel: '',
113 'aria-label': '',
114 showClose: true,
115 'aria-describedby': '',
116 'aria-labelledby': '',
117 id: undefined,
118 actions: [] as any[],
119 onClose: () => undefined as any,
120 variant: 'default',
121 hasNoBodyWrapper: false,
122 appendTo: () => document.body,
123 ouiaSafe: true,
124 position: 'default'
125 };
126
127 constructor(props: ModalProps) {
128 super(props);
129 const boxIdNum = Modal.currentId++;
130 const labelIdNum = boxIdNum + 1;
131 const descriptorIdNum = boxIdNum + 2;
132 const backdropIdNum = boxIdNum + 3;
133 this.boxId = props.id || `pf-modal-part-${boxIdNum}`;
134 this.labelId = `pf-modal-part-${labelIdNum}`;
135 this.descriptorId = `pf-modal-part-${descriptorIdNum}`;
136 this.backdropId = `pf-modal-part-${backdropIdNum}`;
137
138 this.state = {
139 mounted: false
140 };
141 }
142
143 handleEscKeyClick = (event: KeyboardEvent): void => {
144 const { onEscapePress } = this.props;
145 if (event.key === KeyTypes.Escape && this.props.isOpen) {
146 onEscapePress ? onEscapePress(event) : this.props.onClose?.(event);
147 }
148 };
149
150 getElement = (appendTo: HTMLElement | (() => HTMLElement)) => {
151 if (typeof appendTo === 'function') {
152 return appendTo();
153 }
154 return appendTo || document.body;
155 };
156
157 toggleSiblingsFromScreenReaders = (hide: boolean) => {
158 const { appendTo } = this.props;
159 const target: HTMLElement = this.getElement(appendTo);
160 const bodyChildren = target.children;
161 for (const child of Array.from(bodyChildren)) {
162 if (child.id !== this.backdropId) {
163 hide ? child.setAttribute('aria-hidden', '' + hide) : child.removeAttribute('aria-hidden');
164 }
165 }
166 };
167
168 isEmpty = (value: string | null | undefined) => value === null || value === undefined || value === '';
169
170 componentDidMount() {
171 this.setState({ mounted: true });
172 const {
173 appendTo,
174 title,
175 'aria-label': ariaLabel,
176 'aria-labelledby': ariaLabelledby,
177 hasNoBodyWrapper,
178 header
179 } = this.props;
180 const target: HTMLElement = this.getElement(appendTo);
181 target.addEventListener('keydown', this.handleEscKeyClick, false);
182
183 if (this.props.isOpen) {
184 target.classList.add(css(styles.backdropOpen));
185 this.toggleSiblingsFromScreenReaders(true);
186 }
187
188 if (!title && this.isEmpty(ariaLabel) && this.isEmpty(ariaLabelledby)) {
189 // eslint-disable-next-line no-console
190 console.error('Modal: Specify at least one of: title, aria-label, aria-labelledby.');
191 }
192
193 if (this.isEmpty(ariaLabel) && this.isEmpty(ariaLabelledby) && (hasNoBodyWrapper || header)) {
194 // eslint-disable-next-line no-console
195 console.error(
196 'Modal: When using hasNoBodyWrapper or setting a custom header, ensure you assign an accessible name to the the modal container with aria-label or aria-labelledby.'
197 );
198 }
199 }
200
201 componentDidUpdate(prevProps: ModalProps) {
202 const { appendTo } = this.props;
203 const target: HTMLElement = this.getElement(appendTo);
204 if (this.props.isOpen) {
205 target.classList.add(css(styles.backdropOpen));
206 this.toggleSiblingsFromScreenReaders(true);
207 } else {
208 if (prevProps.isOpen !== this.props.isOpen) {
209 target.classList.remove(css(styles.backdropOpen));
210 this.toggleSiblingsFromScreenReaders(false);
211 }
212 }
213 }
214
215 componentWillUnmount() {
216 const { appendTo } = this.props;
217 const target: HTMLElement = this.getElement(appendTo);
218 target.removeEventListener('keydown', this.handleEscKeyClick, false);
219 target.classList.remove(css(styles.backdropOpen));
220 this.toggleSiblingsFromScreenReaders(false);
221 }
222
223 render() {
224 const {
225 appendTo,
226 // eslint-disable-next-line @typescript-eslint/no-unused-vars
227 onEscapePress,
228 'aria-labelledby': ariaLabelledby,
229 'aria-label': ariaLabel,
230 'aria-describedby': ariaDescribedby,
231 bodyAriaLabel,
232 bodyAriaRole,
233 title,
234 titleIconVariant,
235 titleLabel,
236 ouiaId,
237 ouiaSafe,
238 position,
239 elementToFocus,
240 ...props
241 } = this.props;
242
243 if (!this.state.mounted || !canUseDOM || !this.getElement(appendTo)) {
244 return null;
245 }
246
247 return (
248 <SSRSafeIds prefix="pf-" ouiaComponentType={`Modal${this.props.variant ? `-${this.props.variant}` : ''}`}>
249 {(_, generatedOuiaId) =>
250 ReactDOM.createPortal(
251 <ModalContent
252 {...props}
253 boxId={this.boxId}
254 labelId={this.labelId}
255 descriptorId={this.descriptorId}
256 backdropId={this.backdropId}
257 title={title}
258 titleIconVariant={titleIconVariant}
259 titleLabel={titleLabel}
260 aria-label={ariaLabel}
261 aria-describedby={ariaDescribedby}
262 aria-labelledby={ariaLabelledby}
263 bodyAriaLabel={bodyAriaLabel}
264 bodyAriaRole={bodyAriaRole}
265 ouiaId={ouiaId !== undefined ? ouiaId : generatedOuiaId}
266 ouiaSafe={ouiaSafe}
267 position={position}
268 elementToFocus={elementToFocus}
269 />,
270 this.getElement(appendTo)
271 ) as React.ReactElement<any>
272 }
273 </SSRSafeIds>
274 );
275 }
276 }
277
278 export { Modal };