All files / packages/sds-subsystems/.storybook/addons/theme-builder/src/components Modal.jsx

0% Statements 0/23
0% Branches 0/23
0% Functions 0/3
0% Lines 0/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                       
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import SvgIcon from './SvgIcon';
import Button from './Button';
 
/**
 * SLDS Modal (Base) implementation
 * Reference: https://v1.lightningdesignsystem.com/components/modals/#Base
 */
const Modal = ({
  isOpen,
  onRequestClose,
  heading,
  tagline,
  size = 'medium',
  closeLabel = 'Close',
  children,
  containerProps = {},
  contentProps = {},
  footerProps = {},
  headerProps = {},
  id,
  // Footer controls
  onPrimary,
  onSecondary,
  primaryClassName,
  secondaryClassName,
  primaryLabel,
  secondaryLabel,
}) => {
  const headerId = id ? `${id}-heading` : undefined;
  const modalRef = useRef(null);
  const primaryInFlightRef = useRef(false);
 
  // Handle ESC to close
  useEffect(() => {
    if (!isOpen) return;
 
    const onKeyDown = (e) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        onRequestClose && onRequestClose(e);
      }
    };
 
    document.addEventListener('keydown', onKeyDown);
    // Lock body scroll per SLDS guidance
    document.body.classList.add('slds-modal-open');
 
    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.classList.remove('slds-modal-open');
    };
  }, [isOpen, onRequestClose]);
 
  if (!isOpen) return null;
 
  const modalSizeClass =
    {
      small: 'slds-modal_small',
      medium: '',
      large: 'slds-modal_large',
    }[size] || '';
 
  const handleBackdropClick = (e) => {
    // Close if click outside the modal container
    if (modalRef.current && !modalRef.current.contains(e.target)) {
      onRequestClose && onRequestClose(e);
    }
  };
 
  const handlePrimaryClick = async (e) => {
    if (!onPrimary || primaryInFlightRef.current) {
      return onRequestClose && onRequestClose(e);
    }
    try {
      primaryInFlightRef.current = true;
      const result = onPrimary(e);
      const resolved = result && typeof result.then === 'function' ? await result : result;
      // Close unless the handler explicitly returns false
      if (resolved !== false) {
        onRequestClose && onRequestClose(e);
      }
    } catch (err) {
      // swallow to keep modal open on error
      // Optionally log
      // console.error('Modal primary action failed:', err);
    } finally {
      primaryInFlightRef.current = false;
    }
  };
 
  return (
    <div>
      {/* Backdrop */}
      <div className={classNames('slds-backdrop', 'slds-backdrop_open')} />
 
      {/* Modal */}
      <section
        className={classNames('slds-modal', 'slds-fade-in-open', modalSizeClass)}
        aria-hidden={!isOpen}
        role="dialog"
        aria-modal="true"
        aria-labelledby={headerId}
        onMouseDown={handleBackdropClick}
      >
        <div className="slds-modal__container" ref={modalRef} {...containerProps}>
          {/* Close button */}
          <Button
            className={classNames('slds-modal__close')}
            variant="icon"
            iconName="close"
            title={closeLabel}
            onClick={onRequestClose}
            iconSize="large"
          >
            <span className="slds-assistive-text">{closeLabel}</span>
          </Button>
          {/* Header */}
          <header className="slds-modal__header" {...headerProps}>
            {tagline ? <p className="slds-modal__header-empty" /> : null}
 
            {heading ? (
              <h2 id={headerId} className="slds-text-heading_medium slds-hyphenate">
                {heading}
              </h2>
            ) : null}
 
            {tagline ? (
              <p className="slds-m-top_x-small slds-text-body_small slds-m-bottom_xx-small">{tagline}</p>
            ) : null}
          </header>
 
          {/* Content */}
          <div className="slds-modal__content slds-p-around_medium" {...contentProps}>
            {children}
          </div>
 
          {/* Footer with internal action buttons */}
          <footer className="slds-modal__footer" {...footerProps}>
            <div className="slds-grid slds-grid_align-end slds-gutters_small slds-m-right_x-small">
              <Button
                className={secondaryClassName}
                variant="neutral"
                label={secondaryLabel || 'Cancel'}
                onClick={onSecondary || onRequestClose}
              />
              <Button
                className={primaryClassName}
                variant="brand"
                label={primaryLabel || 'Done'}
                onClick={handlePrimaryClick}
              />
            </div>
          </footer>
        </div>
      </section>
    </div>
  );
};
 
Modal.propTypes = {
  /** Controls visibility */
  isOpen: PropTypes.bool.isRequired,
  /** Close handler for ESC, backdrop, and X button */
  onRequestClose: PropTypes.func,
  /** Modal heading text */
  heading: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  /** Optional tagline text above heading */
  tagline: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  /** small | medium | large */
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  /** Accessible label for close button */
  closeLabel: PropTypes.string,
  /** Optional id to wire aria-labelledby */
  id: PropTypes.string,
  /** Children (modal body) */
  children: PropTypes.node,
  /** Primary button label */
  primaryLabel: PropTypes.string,
  /** Secondary button label */
  secondaryLabel: PropTypes.string,
  /** Advanced: pass-through props to internal elements */
  containerProps: PropTypes.object,
  contentProps: PropTypes.object,
  footerProps: PropTypes.object,
  headerProps: PropTypes.object,
  /** Footer action handlers and classes */
  onPrimary: PropTypes.func,
  onSecondary: PropTypes.func,
  primaryClassName: PropTypes.string,
  secondaryClassName: PropTypes.string,
};
 
export default Modal;