|
| 1 | +import classNames from "classnames"; |
| 2 | +import styles from "./styles/index.module.scss"; |
| 3 | +import React, { useCallback, useMemo, useState } from "react"; |
| 4 | +import { ModalContext, type ModalContextProps, type ModalContextValue } from "./context"; |
| 5 | +import { Card } from "@react-ck/card"; |
| 6 | +import { Overlay } from "@react-ck/overlay"; |
| 7 | +import { Icon } from "@react-ck/icon"; |
| 8 | +import { Button } from "@react-ck/button"; |
| 9 | +import { Text } from "@react-ck/text"; |
| 10 | +import { Layer } from "@react-ck/layers"; |
| 11 | + |
| 12 | +interface ModalProps extends React.HTMLAttributes<HTMLDivElement> {} |
| 13 | + |
| 14 | +// TODO: add annotation |
| 15 | +// TODO: add a11y https://react.dev/reference/react-dom/createPortal#rendering-a-modal-dialog-with-a-portal |
| 16 | + |
| 17 | +/** |
| 18 | + * @param props - {@link React.HTMLAttributes} |
| 19 | + * @returns a React element |
| 20 | + */ |
| 21 | + |
| 22 | +export const Modal = ({ |
| 23 | + children, |
| 24 | + className, |
| 25 | + ...otherProps |
| 26 | +}: Readonly<ModalProps>): React.ReactElement => { |
| 27 | + const [props, setProps] = useState<ModalContextValue>({ |
| 28 | + header: undefined, |
| 29 | + footer: undefined, |
| 30 | + }); |
| 31 | + |
| 32 | + const setContextValue = useCallback<ModalContextProps["setValue"]>((value) => { |
| 33 | + setProps((v) => ({ ...v, ...value })); |
| 34 | + }, []); |
| 35 | + |
| 36 | + const contextProps = useMemo<ModalContextProps>( |
| 37 | + () => ({ |
| 38 | + setValue: setContextValue, |
| 39 | + }), |
| 40 | + [setContextValue], |
| 41 | + ); |
| 42 | + |
| 43 | + return ( |
| 44 | + <Layer elevation="overlay"> |
| 45 | + <div {...otherProps} className={classNames(styles.root, className)}> |
| 46 | + <Overlay /> |
| 47 | + <Card className={styles.card}> |
| 48 | + <ModalContext.Provider value={contextProps}> |
| 49 | + {props.header && ( |
| 50 | + <header |
| 51 | + {...props.header} |
| 52 | + className={classNames(styles.header, props.header.className)}> |
| 53 | + <Text type="h3" as="p" margin={false}> |
| 54 | + {props.header.heading} |
| 55 | + </Text> |
| 56 | + |
| 57 | + <Button skin="ghost" icon={<Icon name="close" />} /> |
| 58 | + </header> |
| 59 | + )} |
| 60 | + <main className={styles.content}>{children}</main> |
| 61 | + {props.footer && ( |
| 62 | + <footer |
| 63 | + {...props.footer} |
| 64 | + className={classNames(styles.footer, props.footer.className)} |
| 65 | + /> |
| 66 | + )} |
| 67 | + </ModalContext.Provider> |
| 68 | + </Card> |
| 69 | + </div> |
| 70 | + </Layer> |
| 71 | + ); |
| 72 | +}; |
0 commit comments