Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

13.8 KB
Raw Blame
import { useState, useEffect, useCallback, useRef } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import update from 'immutability-helper';
import { toLower as lodashToLower } from 'lodash';
import {
  Modal, ModalBody, ModalHeader, ModalFooter,
} from 'reactstrap';
import { Resizable } from 'react-resizable';
import { onToggle as onToggleAction } from '../modules/modal/actions';
import ErrorBoundary from './error-boundary';
import DetectOuterClick from '../components/util/detect-outer-click';
import usePrevious from '../util/customHooks';

const InteractionWrap = ({
  condition,
  wrapper, children,
}) => (condition ? wrapper(children) : children);
const toggleWithClose = (onToggle, onClose, isOpen) => {
  if (onClose && isOpen) {
    return () => {
      onToggle();
      onClose();
    };
  }
  return onToggle;
};

function ModalContainer(props) {
  const {
    isCustom,
    id,
    isOpen,
    customProps,
    isMobile,
    screenHeight,
    screenWidth,
    isEmbedModeActive,
    isTemplateModal,
  } = props;

  const {
    width: propsWidth,
    height: propsHeight,
    offsetLeft: propsOffsetLeft,
    offsetTop: propsOffsetTop,
    offsetRight: propsOffsetRight,
    mobileFullScreen,
    autoSetWidth,
    autoSetHeight,
  } = customProps;

  const [width, setWidth] = useState(propsWidth);
  const [height, setHeight] = useState(propsHeight);
  const [offsetLeft, setOffsetLeft] = useState(propsOffsetLeft);
  const [offsetTop, setOffsetTop] = useState(propsOffsetTop);
  const [offsetRight] = useState(propsOffsetRight);
  const [isDragging, setIsDragging] = useState(false);
  const measuredElementRef = useRef();
  const widthRef = useRef(width);
  const heightRef = useRef(height);
  const dragStartRef = useRef({
    x: 0,
    y: 0,
    left: 0,
    top: 0,
    width: 0,
    height: 0,
    stayOnscreen: false,
  });
  const prevScreenHeight = usePrevious(screenHeight);
  const prevScreenWidth = usePrevious(screenWidth);
  const prevWidth = usePrevious(width);
  const prevHeight = usePrevious(height);
  const prevMeasuredElement = usePrevious(measuredElementRef.current);
  const prevMeasuredWidth = usePrevious(measuredElementRef.current?.getBoundingClientRect().width);
  const prevMeasuredHeight = usePrevious(
    measuredElementRef.current?.getBoundingClientRect().height);

  const beginDrag = useCallback((e, { dragHandle, stayOnscreen }) => {
    if (!e || e.button !== 0) return;
    if (!dragHandle) return;
    if (!e.target?.closest?.(dragHandle)) return;
    if (e.target?.closest?.('button, a, input, select, textarea')) return;

    const rect = measuredElementRef.current?.getBoundingClientRect?.();
    const startLeft = typeof offsetLeft === 'number' ? offsetLeft : (rect?.left || 0);
    const startTop = typeof offsetTop === 'number' ? offsetTop : (rect?.top || 0);
    const elWidth = widthRef.current || width || rect?.width || 0;
    const elHeight = heightRef.current || height || rect?.height || 0;

    dragStartRef.current = {
      x: e.clientX,
      y: e.clientY,
      left: startLeft,
      top: startTop,
      width: elWidth,
      height: elHeight,
      stayOnscreen: !!stayOnscreen,
    };

    setIsDragging(true);
  }, [measuredElementRef.current, offsetLeft, offsetTop, width, height]);

  useEffect(() => {
    if (!isDragging) return undefined;

    const onMove = (e) => {
      const start = dragStartRef.current;
      const dx = e.clientX - start.x;
      const dy = e.clientY - start.y;

      let nextLeft = start.left + dx;
      let nextTop = start.top + dy;

      if (start.stayOnscreen && widthRef.current && heightRef.current) {
        const maxLeft = Math.max(0, screenWidth - widthRef.current);
        const maxTop = Math.max(0, screenHeight - heightRef.current - 2.5);
        nextLeft = Math.min(Math.max(0, nextLeft), maxLeft);
        nextTop = Math.min(Math.max(0, nextTop), maxTop);
      }

      setOffsetLeft(nextLeft);
      setOffsetTop(nextTop);
    };

    const onUp = () => {
      setIsDragging(false);
    };

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);

    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, [isDragging, screenWidth, screenHeight]);

  useEffect(() => {
    widthRef.current = width;
  }, [width]);

  useEffect(() => {
    heightRef.current = height;
  }, [height]);

  const onParamChange = (e, { size }) => {
    if (e) {
      e.stopPropagation();
    }
    const elWidth = autoSetWidth && measuredElementRef.current
      ? measuredElementRef.current.getBoundingClientRect().width
      : size.width;
    const elHeight = autoSetHeight && measuredElementRef.current
      ? measuredElementRef.current.getBoundingClientRect().height
      : size.height;
    setWidth(elWidth);
    setHeight(elHeight);
    if (size.stayOnscreen) {
      const maxLeft = Math.max(0, screenWidth - elWidth);
      const maxTop = Math.max(0, screenHeight - elHeight - 2.5);
      if (measuredElementRef.current?.getBoundingClientRect().left > maxLeft) {
        setOffsetLeft(maxLeft);
      }
      if (measuredElementRef.current?.getBoundingClientRect().top > maxTop) {
        setOffsetTop(maxTop);
      }
    }
  };

  const onResize = (e, { size }) => {
    if (e) {
      e.stopPropagation();
    }
    setWidth(size.width);
    setHeight(size.height);
  };

  useEffect(() => {
    const newProps = isCustom && id ? update(props, { $merge: customProps }) : props;
    const {
      onToggle,
      onClose,
      desktopOnly,
    } = newProps;

    const screenHeightChanged = screenHeight !== prevScreenHeight;
    const screenWidthChanged = screenWidth !== prevScreenWidth;
    const modalWidthChanged = propsWidth !== prevWidth;
    const modalHeightChanged = propsHeight !== prevHeight;
    const measuredElementChanged = (autoSetWidth || autoSetHeight) &&
      measuredElementRef.current !== prevMeasuredElement;
    const measuredWidthChanged = autoSetWidth &&
      measuredElementRef.current?.getBoundingClientRect().width !== prevMeasuredWidth;
    const measuredHeightChanged = autoSetHeight &&
      measuredElementRef.current?.getBoundingClientRect().height !== prevMeasuredHeight;
    const measureChange = measuredElementChanged || measuredWidthChanged || measuredHeightChanged;
    const toggleFunction = toggleWithClose(onToggle, onClose, isOpen);
    if ((modalWidthChanged || modalHeightChanged || measureChange) && isOpen) {
      onParamChange(null, { size: customProps });
    }
    if (isMobile && isOpen) {
      if (desktopOnly) {
        toggleFunction();
      }
      if (mobileFullScreen && (screenHeightChanged || screenWidthChanged)) {
        const isPortrait = screenHeight > screenWidth;

        // Values below match the request made in ol-vector-interactions
        const sizeObj = {
          width: isPortrait ? screenWidth : 445,
          height: isPortrait ? screenHeight - 106 : 300,
        };

        onResize(null, { size: sizeObj });
      }
    }
  });

  function getStyle() {
    const mobileTopOffset = 106;
    const top = isMobile && mobileFullScreen ? mobileTopOffset : offsetTop;
    const margin = isMobile ? 0 : '0.5rem auto';
    return {
      left: offsetLeft,
      right: offsetRight,
      top,
      width,
      height,
      maxHeight: height,
      margin,
    };
  }

  function getTemplateBody() {
    const { bodyTemplate } = props;
    return bodyTemplate.isLoading
      ? (
        <span> Loading </span>
      )
      : (
        <div
          id="template-content"
          dangerouslySetInnerHTML={{ __html: bodyTemplate.response }}
        />
      );
  }

  const handleCreateChildren = (children) => {
    const newProps = isCustom && id ? update(props, { $merge: customProps }) : props;
    const {
      isResizable,
    } = newProps;
    const maybeResizableChildren = isResizable
      ? (
        <Resizable
          className="resize-box"
          resizeHandles={['se']}
          width={width || newProps.width}
          height={height || newProps.height}
          minConstraints={[250, 250]}
          maxConstraints={[495, screenHeight]}
          handleSize={[8, 8]}
          onResize={onResize}
          draggableOpts={{ disabled: !isResizable }}
        >
          {children}
        </Resizable>
      )
      : children;

    // Manual dragging is handled via mouse events on the modal content wrapper.
    return maybeResizableChildren;
  };

  const newProps = isCustom && id ? update(props, { $merge: customProps }) : props;
  const {
    autoFocus,
    backdrop,
    bodyComponent,
    bodyComponentProps,
    bodyHeader,
    bodyText,
    dragHandle,
    stayOnscreen,
    footer,
    clickableBehindModal,
    CompletelyCustomModal,
    desktopOnly,
    headerComponent,
    headerText,
    isDraggable,
    isResizable,
    mobileOnly,
    modalClassName,
    onClose,
    onToggle,
    size,
    timeout,
    type,
    wrapClassName,
  } = newProps;

  const customPropsWithoutKey = { ...(customProps || {}) };
  delete customPropsWithoutKey.key;

  const handleModalMouseDown = useCallback((e) => {
    if (!isDraggable) return;
    beginDrag(e, { dragHandle, stayOnscreen });
  }, [beginDrag, dragHandle, isDraggable, stayOnscreen]);

  const isRestrictedDisplay = (isMobile && desktopOnly) ||
    (!isMobile && mobileOnly) ||
    (isEmbedModeActive && size === 'lg' && !id.includes('LAYER_INFO_MODAL'));
  if (isRestrictedDisplay) {
    return null;
  }
  const style = getStyle();
  const lowerCaseId = lodashToLower(id);
  const BodyComponent = bodyComponent || '';
  const allowOuterClick = !isOpen || type === 'selection' || clickableBehindModal;
  const modalWrapClass = clickableBehindModal ? `clickable-behind-modal ${wrapClassName}` : wrapClassName;
  const toggleFunction = toggleWithClose(onToggle, onClose, isOpen);
  const closeBtn = (
    <button className="modal-close-btn" onClick={toggleFunction} type="button">
      &times;
    </button>
  );
  const renderModalBodyText = isTemplateModal ? getTemplateBody() : (<p>{bodyText}</p>) || '';
  return (
    <ErrorBoundary>
      <InteractionWrap
        condition={isDraggable || isResizable}
        wrapper={handleCreateChildren}
      >
        <Modal
          isOpen={isOpen}
          toggle={toggleFunction}
          backdrop={backdrop}
          id={lowerCaseId}
          size={size}
          className={`${isTemplateModal ? 'template-modal' : modalClassName || 'default-modal'}${isDraggable ? ' draggable-modal' : ''}`}
          autoFocus={autoFocus || false}
          style={style}
          wrapClassName={`${modalWrapClass} ${lowerCaseId}`}
          modalTransition={{ timeout: isDraggable ? 0 : timeout || 100 }}
          fade={!isDraggable}
        >
          <div ref={measuredElementRef} onMouseDown={handleModalMouseDown} style={{ height: '100%' }}>
            {CompletelyCustomModal
              ? (
                <CompletelyCustomModal
                  key={customProps?.dialogKey ? `custom_${lowerCaseId}_${customProps.dialogKey}` : `custom_${lowerCaseId}`}
                  modalHeight={height || newProps.height}
                  modalWidth={width || newProps.width}
                  // eslint-disable-next-line react/jsx-props-no-spreading
                  {...customPropsWithoutKey}
                  toggleWithClose={toggleFunction}
                />
              )
              : (
                <DetectOuterClick
                  onClick={toggleFunction}
                  disabled={allowOuterClick}
                >
                  {(headerComponent || headerText) && (
                    <ModalHeader toggle={toggleFunction} close={closeBtn}>
                      {headerComponent ? <headerComponent /> : headerText || ''}
                    </ModalHeader>
                  )}
                  <ModalBody>
                    {bodyHeader && <h3>{bodyHeader}</h3>}
                    {BodyComponent
                      ? (
                        <BodyComponent
                        // eslint-disable-next-line react/jsx-props-no-spreading
                          {...bodyComponentProps}
                          parentId={id}
                          screenHeight={screenHeight}
                          closeModal={toggleFunction}
                        />
                      )
                      : renderModalBodyText}
                  </ModalBody>
                  {footer && (<ModalFooter />)}
                </DetectOuterClick>
              )}
          </div>
        </Modal>
      </InteractionWrap>
    </ErrorBoundary>
  );
}

function mapStateToProps(state) {
  const { embed, modal, screenSize } = state;
  const {
    bodyText,
    headerText,
    isCustom,
    id,
    isOpen,
    template,
    customProps,
  } = modal;
  let bodyTemplate;
  let isTemplateModal = false;
  if (template) {
    bodyTemplate = state[template];
    isTemplateModal = true;
  }
  const {
    screenHeight, screenWidth, orientation, isMobileDevice,
  } = screenSize;
  const isMobile = isMobileDevice;
  const { isEmbedModeActive } = embed;
  return {
    bodyTemplate,
    bodyText,
    customProps,
    headerText,
    id,
    isCustom,
    isEmbedModeActive,
    isMobile,
    isOpen,
    isTemplateModal,
    orientation,
    screenHeight,
    screenWidth,
  };
}
const mapDispatchToProps = (dispatch) => ({
  onToggle: () => {
    dispatch(onToggleAction());
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ModalContainer);

ModalContainer.defaultProps = {
  customProps: {},
};

ModalContainer.propTypes = {
  bodyTemplate: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
  customProps: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),
  id: PropTypes.string,
  isCustom: PropTypes.bool,
  isEmbedModeActive: PropTypes.bool,
  isMobile: PropTypes.bool,
  isOpen: PropTypes.bool,
  isTemplateModal: PropTypes.bool,
  screenHeight: PropTypes.number,
  screenWidth: PropTypes.number,
};