All files / modal modal.js

86.81% Statements 79/91
75.34% Branches 55/73
88.46% Functions 23/26
86.81% Lines 79/91

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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342                                                                                                              8x       8x 8x 8x       10x 10x         8x 7x   1x           7x 7x         9x 9x         7x 7x 7x       9x 9x 9x 7x 7x                                           2x 1x   1x       1x       15x 1x   15x   7x           7x 7x       7x 7x 7x       7x   7x 7x     7x           1x 1x 1x 1x         2x 2x             7x       1x   1x 1x   1x         7x     7x 7x     7x                   7x 7x                     23x 23x         23x       7x 7x       28x 14x   28x       7x               7x   7x 7x   7x 7x 7x   7x 7x   7x     7x                                                                                                 18x 8x     10x 3x   7x                        
/*
Copyright (c) 2018-2019 Uber Technologies, Inc.
 
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
/* global document */
import * as React from 'react';
 
import {LocaleContext} from '../locale/index.js';
import {getOverride, getOverrideProps} from '../helpers/overrides.js';
import {Layer} from '../layer/index.js';
import {SIZE, ROLE, CLOSE_SOURCE} from './constants.js';
import {ownerDocument} from './utils.js';
import {
  Root as StyledRoot,
  Backdrop as StyledBackdrop,
  Dialog as StyledDialog,
  DialogContainer as StyledDialogContainer,
  Close as StyledClose,
} from './styled-components.js';
import {CloseIcon} from './close-icon.js';
 
import type {
  ModalPropsT,
  ModalStateT,
  SharedStylePropsArgT,
  CloseSourceT,
  ElementRefT,
} from './types.js';
 
class Modal extends React.Component<ModalPropsT, ModalStateT> {
  static defaultProps: $Shape<ModalPropsT> = {
    animate: true,
    autofocus: true,
    closeable: true,
    isOpen: false,
    overrides: {},
    role: ROLE.dialog,
    size: SIZE.default,
  };
 
  animateOutTimer: ?TimeoutID;
  animateStartTimer: ?AnimationFrameID;
  lastFocus: ?HTMLElement = null;
  lastMountNodeOverflowStyle: ?string = null;
  _refs: {[string]: ElementRefT} = {};
 
  state = {
    isVisible: false,
    mounted: false,
  };
 
  componentDidMount() {
    this.setState({mounted: true});
  }
 
  componentWillUnmount() {
    this.removeDomEvents();
    this.resetMountNodeScroll();
    this.clearTimers();
  }
 
  componentDidUpdate(prevProps: ModalPropsT, prevState: ModalStateT) {
    const {isOpen} = this.props;
    if (
      // If isOpen is changing *or* we just mounted and modal should be open
      isOpen !== prevProps.isOpen ||
      (isOpen && this.state.mounted && !prevState.mounted)
    ) {
      if (isOpen) {
        this.didOpen();
      } else {
        this.didClose();
      }
    }
  }
 
  addDomEvents() {
    Eif (__BROWSER__) {
      document.addEventListener('keyup', this.onDocumentKeyPress);
    }
  }
 
  removeDomEvents() {
    Eif (__BROWSER__) {
      document.removeEventListener('keyup', this.onDocumentKeyPress);
    }
  }
 
  disableMountNodeScroll() {
    const mountNode = this.getMountNode();
    this.lastMountNodeOverflowStyle = mountNode.style.overflow || '';
    mountNode.style.overflow = 'hidden';
  }
 
  resetMountNodeScroll() {
    const mountNode = this.getMountNode();
    const lastStyle = this.lastMountNodeOverflowStyle;
    if (mountNode && lastStyle !== null) {
      mountNode.style.overflow = lastStyle || '';
      this.lastMountNodeOverflowStyle = null;
    }
  }
 
  onDocumentKeyPress = (event: KeyboardEvent) => {
    if (event.key !== 'Escape') {
      return;
    }
 
    // Ignore events that have been `event.preventDefault()` marked.
    if (event.defaultPrevented) {
      return;
    }
 
    if (!this.props.closeable) {
      return;
    }
 
    this.triggerClose(CLOSE_SOURCE.escape);
  };
 
  onBackdropClick = () => {
    if (!this.props.closeable) {
      return;
    }
    this.triggerClose(CLOSE_SOURCE.backdrop);
  };
 
  onCloseClick = () => {
    this.triggerClose(CLOSE_SOURCE.closeButton);
  };
 
  clearTimers() {
    if (this.animateOutTimer) {
      clearTimeout(this.animateOutTimer);
    }
    if (this.animateStartTimer) {
      // eslint-disable-next-line cup/no-undef
      cancelAnimationFrame(this.animateStartTimer);
    }
  }
 
  didOpen() {
    // Store last focused item (we'll return focus after closing for a11y)
    this.captureLastFocus();
    this.autoFocus();
 
    // Sometimes scroll starts past zero, possibly due to animation
    // Reset scroll to 0 (other libraries do this as well)
    const rootRef = this.getRef('Root').current;
    Eif (rootRef) {
      rootRef.scrollTop = 0;
    }
 
    // Clear any existing timers (like previous animateOutTimer)
    this.clearTimers();
 
    this.addDomEvents();
    this.disableMountNodeScroll();
 
    // eslint-disable-next-line cup/no-undef
    this.animateStartTimer = requestAnimationFrame(() => {
      this.setState({isVisible: true});
    });
  }
 
  didClose() {
    this.removeDomEvents();
    this.resetMountNodeScroll();
    this.animateOutTimer = setTimeout(this.animateOutComplete, 500);
    this.restoreLastFocus();
  }
 
  triggerClose(source?: CloseSourceT) {
    // If there's no source, it just means the isOpen prop changed. No need to call onClose.
    Eif (this.props.onClose && source) {
      this.props.onClose({
        closeSource: source,
      });
    }
  }
 
  captureLastFocus = () => {
    this.lastFocus = ownerDocument(this.getMountNode()).activeElement;
  };
 
  restoreLastFocus = () => {
    Eif (this.lastFocus) {
      // Not all elements in IE11 can focus
      Eif (this.lastFocus.focus) {
        this.lastFocus.focus();
      }
      this.lastFocus = null;
    }
  };
 
  autoFocus = () => {
    Iif (!this.props.autofocus) {
      return;
    }
    const dialog = this.getRef('Dialog').current;
    Iif (!dialog) {
      return;
    }
    dialog.focus();
  };
 
  animateOutComplete = () => {
    this.setState({
      isVisible: false,
    });
  };
 
  getSharedProps(): $Diff<SharedStylePropsArgT, {children?: React.Node}> {
    const {animate, isOpen, size, role, closeable} = this.props;
    return {
      $animate: animate,
      $isVisible: this.state.isVisible,
      $isOpen: !!isOpen,
      $size: size,
      $role: role,
      $closeable: !!closeable,
    };
  }
 
  getMountNode(): HTMLElement {
    const {mountNode} = this.props;
    Iif (mountNode) {
      return mountNode;
    }
    // Flow thinks body could be null (cast through any)
    // eslint-disable-next-line flowtype/no-weak-types
    return ((document.body: any): HTMLBodyElement);
  }
 
  getChildren() {
    const {children} = this.props;
    return typeof children === 'function' ? children() : children;
  }
 
  getRef(component: string): ElementRefT {
    if (!this._refs[component]) {
      this._refs[component] = React.createRef();
    }
    return this._refs[component];
  }
 
  renderModal() {
    const {overrides = {}, closeable, role} = this.props;
 
    const {
      Root: RootOverride,
      Dialog: DialogOverride,
      DialogContainer: DialogContainerOverride,
      Backdrop: BackdropOverride,
      Close: CloseOverride,
    } = overrides;
 
    const Root = getOverride(RootOverride) || StyledRoot;
    const Backdrop = getOverride(BackdropOverride) || StyledBackdrop;
    const DialogContainer =
      getOverride(DialogContainerOverride) || StyledDialogContainer;
    const Dialog = getOverride(DialogOverride) || StyledDialog;
    const Close = getOverride(CloseOverride) || StyledClose;
 
    const sharedProps = this.getSharedProps();
    const children = this.getChildren();
 
    return (
      <LocaleContext.Consumer>
        {locale => (
          <Root
            data-baseweb="modal"
            ref={this.getRef('Root')}
            {...sharedProps}
            {...getOverrideProps(RootOverride)}
          >
            <Backdrop
              onClick={this.onBackdropClick}
              {...sharedProps}
              {...getOverrideProps(BackdropOverride)}
            />
            <DialogContainer
              {...sharedProps}
              {...getOverrideProps(DialogContainerOverride)}
            >
              <Dialog
                tabIndex={-1}
                aria-modal={
                  // aria-modal replaces the need to apply aria-hidden="true" to all other page
                  // content underneath the modal.
                  // https://www.w3.org/TR/wai-aria-practices-1.1/examples/dialog-modal/dialog.html
                  'true'
                }
                role={role}
                ref={this.getRef('Dialog')}
                {...sharedProps}
                {...getOverrideProps(DialogOverride)}
              >
                {closeable ? (
                  <Close
                    aria-label={locale.modal.close}
                    onClick={this.onCloseClick}
                    {...sharedProps}
                    {...getOverrideProps(CloseOverride)}
                  >
                    <CloseIcon />
                  </Close>
                ) : null}
                {children}
              </Dialog>
            </DialogContainer>
          </Root>
        )}
      </LocaleContext.Consumer>
    );
  }
 
  render() {
    // Only render modal on the browser (portals aren't supported server-side)
    if (!this.state.mounted) {
      return null;
    }
    // Only render the modal if its isOpen is passed, or isVisible is true (still animating)
    if (!this.props.isOpen && !this.state.isVisible) {
      return null;
    }
    return (
      <Layer
        mountNode={this.props.mountNode}
        {...(this.props.isOpen ? {onMount: this.autoFocus} : {})}
      >
        {this.renderModal()}
      </Layer>
    );
  }
}
 
export default Modal;