aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/molecules/modals/modal/modal.tsx
blob: ed554888854ef0b0087752af79795120824ee62e (plain)
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
import {
  type ForwardRefRenderFunction,
  type HTMLAttributes,
  type ReactNode,
  forwardRef,
} from 'react';
import { Button, Icon } from '../../../atoms';
import styles from './modal.module.scss';

export type ModalProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * The modal body.
   */
  children: ReactNode;
  /**
   * The close button label.
   */
  closeBtnLabel?: string;
  /**
   * The modal title.
   */
  heading?: ReactNode;
  /**
   * Define an icon to illustrate the modal.
   */
  icon?: ReactNode;
  /**
   * The modal kind.
   *
   * @default 'primary'
   */
  kind?: 'primary' | 'secondary';
  /**
   * A callback function to handle close button action.
   */
  onClose?: () => void;
};

const ModalWithRef: ForwardRefRenderFunction<HTMLDivElement, ModalProps> = (
  {
    children,
    className = '',
    closeBtnLabel,
    heading,
    icon,
    kind = 'primary',
    onClose,
    ...props
  },
  ref
) => {
  const hasHeader = !!heading || !!icon || !!closeBtnLabel;
  const modalClass = [
    styles.modal,
    styles[hasHeader ? 'modal--has-header' : ''],
    styles[closeBtnLabel ? 'modal--has-btn' : ''],
    styles[`modal--${kind}`],
    className,
  ].join(' ');

  return (
    <div {...props} className={modalClass} ref={ref}>
      {hasHeader ? (
        <div className={styles.header}>
          {icon ? (
            <div aria-hidden className={styles.icon}>
              {icon}
            </div>
          ) : null}
          {heading ? <div className={styles.title}>{heading}</div> : null}
          {closeBtnLabel ? (
            <Button
              aria-label={closeBtnLabel}
              className={styles.btn}
              onClick={onClose}
              // eslint-disable-next-line react/jsx-no-literals
              kind="neutral"
              // eslint-disable-next-line react/jsx-no-literals
              shape="initial"
            >
              <Icon
                aria-hidden
                className={styles.icon}
                // eslint-disable-next-line react/jsx-no-literals
                shape="cross"
                // eslint-disable-next-line react/jsx-no-literals
                size="xs"
              />
            </Button>
          ) : null}
        </div>
      ) : null}
      {children}
    </div>
  );
};

/**
 * Modal component
 *
 * Render a modal component.
 */
export const Modal = forwardRef(ModalWithRef);