All files / menu stateful-container.js

65.38% Statements 51/78
53.93% Branches 48/89
54.55% Functions 12/22
65.38% Lines 51/78

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                                                                        3x                                 9x 9x 9x                         9x 1x     9x       1x   1x 1x   1x         7x 7x   7x                           3x 3x       5x         2x 2x   3x 3x           2x 2x 2x   2x 1x 1x 1x     1x 1x 1x 1x                                   2x 2x                       3x 3x 3x         1x         5x 5x 5x 5x   5x 5x 5x           5x           1x 1x 1x                                                                                                                                   16x 16x                            
/*
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
import * as React from 'react';
// Files
import {STATE_CHANGE_TYPES, KEY_STRINGS} from './constants.js';
import {scrollItemIntoView} from './utils.js';
// Types
import type {
  StatefulContainerPropsT,
  StatefulContainerStateT,
  GetRequiredItemPropsFnT,
  RenderPropsT,
  StateReducerFnT,
} from './types.js';
 
export default class MenuStatefulContainer extends React.Component<
  StatefulContainerPropsT,
  StatefulContainerStateT,
> {
  static defaultProps = {
    initialState: {
      // Defaults to -1 so no item is highlighted
      highlightedIndex: -1,
      isFocused: false,
      activedescendantId: null,
    },
    stateReducer: (
      changeType: ?$PropertyType<StateReducerFnT, 'changeType'>,
      changes: $PropertyType<StateReducerFnT, 'changes'>,
    ) => changes,
    onItemSelect: () => {},
    getRequiredItemProps: () => ({}),
    children: () => null,
 
    // from nested-menus context
    addMenuToNesting: () => {},
    removeMenuFromNesting: () => {},
    getParentMenu: () => {},
    getChildMenu: () => {},
  };
 
  state: StatefulContainerStateT = {...this.props.initialState};
 
  // We need to have access to the root component user renders
  // to correctly facilitate keyboard scrolling behavior
  rootRef = (React.createRef(): {current: HTMLElement | null});
 
  componentDidMount() {
    const rootRef = this.props.rootRef ? this.props.rootRef : this.rootRef;
    Eif (__BROWSER__) {
      Iif (
        rootRef.current /** This condition added to satisfy Flow */ &&
        this.state.highlightedIndex > -1 &&
        this.refList[this.state.highlightedIndex]
      ) {
        scrollItemIntoView(
          this.refList[this.state.highlightedIndex].current,
          rootRef.current,
          this.state.highlightedIndex === 0,
          this.state.highlightedIndex === this.props.items.length - 1,
        );
      }
 
      if (this.state.isFocused) {
        document.addEventListener('keydown', this.onKeyDown);
      }
    }
    this.props.addMenuToNesting && this.props.addMenuToNesting(rootRef);
  }
 
  componentWillUnmount() {
    const rootRef = this.props.rootRef ? this.props.rootRef : this.rootRef;
 
    Eif (__BROWSER__) {
      document.removeEventListener('keydown', this.onKeyDown);
    }
    this.props.removeMenuFromNesting &&
      this.props.removeMenuFromNesting(rootRef);
  }
 
  componentDidUpdate(_: mixed, prevState: StatefulContainerStateT) {
    Eif (__BROWSER__) {
      Iif (!prevState.isFocused && this.state.isFocused) {
        document.addEventListener('keydown', this.onKeyDown);
      } else Iif (prevState.isFocused && !this.state.isFocused) {
        document.removeEventListener('keydown', this.onKeyDown);
      }
    }
  }
 
  // One array to hold all of list item refs
  refList: Array<React$ElementRef<*>> = [];
 
  // Internal set state function that will also invoke stateReducer
  internalSetState(
    changeType: $Keys<typeof STATE_CHANGE_TYPES>,
    changes: $Shape<StatefulContainerStateT>,
  ) {
    const {stateReducer} = this.props;
    this.setState(stateReducer(changeType, changes, this.state));
  }
 
  onKeyDown = (event: KeyboardEvent) => {
    switch (event.key) {
      case KEY_STRINGS.ArrowUp:
      case KEY_STRINGS.ArrowDown:
      case KEY_STRINGS.ArrowLeft:
      case KEY_STRINGS.ArrowRight:
        this.handleArrowKey(event);
        break;
      case KEY_STRINGS.Enter:
        this.handleEnterKey(event);
        break;
    }
  };
 
  // Handler for arrow keys
  handleArrowKey = (event: KeyboardEvent) => {
    const rootRef = this.props.rootRef ? this.props.rootRef : this.rootRef;
    const prevIndex = this.state.highlightedIndex;
    let nextIndex = prevIndex;
 
    if (event.key === KEY_STRINGS.ArrowUp) {
      event.preventDefault();
      nextIndex = Math.max(0, prevIndex - 1);
      this.internalSetState(STATE_CHANGE_TYPES.moveUp, {
        highlightedIndex: nextIndex,
      });
    } else Eif (event.key === KEY_STRINGS.ArrowDown) {
      event.preventDefault();
      nextIndex = Math.min(prevIndex + 1, this.props.items.length - 1);
      this.internalSetState(STATE_CHANGE_TYPES.moveDown, {
        highlightedIndex: nextIndex,
      });
    } else if (event.key === KEY_STRINGS.ArrowLeft) {
      if (this.props.getParentMenu) {
        const parent = this.props.getParentMenu(rootRef);
        if (parent && parent.current) {
          parent.current.focus();
        }
      }
    } else if (event.key === KEY_STRINGS.ArrowRight) {
      if (this.props.getChildMenu) {
        const child = this.props.getChildMenu(rootRef);
        if (child && child.current) {
          child.current.focus();
        }
      }
    }
    Eif (this.refList[nextIndex]) {
      scrollItemIntoView(
        this.refList[nextIndex].current,
        // $FlowFixMe
        rootRef.current,
        nextIndex === 0,
        nextIndex === this.props.items.length - 1,
      );
    }
  };
 
  // Handler for enter key
  handleEnterKey = (event: KeyboardEvent) => {
    const {items, onItemSelect} = this.props;
    const {highlightedIndex} = this.state;
    if (
      items[highlightedIndex] &&
      onItemSelect &&
      !items[highlightedIndex].disabled
    ) {
      onItemSelect({item: items[highlightedIndex], event});
    }
  };
 
  getRequiredItemProps: GetRequiredItemPropsFnT = (item, index) => {
    let itemRef = this.refList[index];
    Eif (!itemRef) {
      itemRef = React.createRef();
      this.refList[index] = itemRef;
    }
    const requiredItemProps = this.props.getRequiredItemProps(item, index);
    const activedescendantId = requiredItemProps.id || null;
    Iif (
      this.state.highlightedIndex === index &&
      this.state.activedescendantId !== activedescendantId
    ) {
      this.setState({activedescendantId});
    }
    return {
      disabled: !!item.disabled,
      ref: itemRef,
      isFocused: this.state.isFocused,
      isHighlighted: this.state.highlightedIndex === index,
      onClick: (event: SyntheticMouseEvent<HTMLElement>) => {
        Eif (this.props.onItemSelect && !item.disabled) {
          this.props.onItemSelect({item, event});
          this.internalSetState(STATE_CHANGE_TYPES.click, {
            highlightedIndex: index,
            activedescendantId,
          });
        }
      },
      onMouseEnter: () => {
        this.internalSetState(STATE_CHANGE_TYPES.mouseEnter, {
          highlightedIndex: index,
          activedescendantId,
        });
      },
      resetMenu: this.resetMenu,
      ...(this.state.highlightedIndex === index
        ? {id: activedescendantId}
        : {}),
      ...requiredItemProps,
    };
  };
 
  focusMenu = (event: FocusEvent | MouseEvent | KeyboardEvent) => {
    const rootRef = this.props.rootRef ? this.props.rootRef : this.rootRef;
 
    if (this.state.isFocused) {
      return;
    }
    // $FlowFixMe
    if (rootRef.current && rootRef.current.contains(event.target)) {
      if (this.state.highlightedIndex < 0) {
        this.internalSetState(STATE_CHANGE_TYPES.focus, {
          isFocused: true,
          highlightedIndex: 0,
        });
      } else {
        this.internalSetState(STATE_CHANGE_TYPES.focus, {isFocused: true});
      }
 
      rootRef.current.focus();
    }
  };
 
  unfocusMenu = () => {
    this.internalSetState(STATE_CHANGE_TYPES.focus, {isFocused: false});
  };
 
  resetMenu = () => {
    this.internalSetState(STATE_CHANGE_TYPES.reset, {
      isFocused: false,
      highlightedIndex: -1,
      activedescendantId: null,
    });
  };
 
  render() {
    // omit the stateful-container's props and don't pass it down
    // to the children (stateless menu)
    const {
      initialState,
      stateReducer,
      children,
      onItemSelect,
      addMenuToNesting,
      removeMenuFromNesting,
      getParentMenu,
      getChildMenu,
      ...restProps
    } = this.props;
    return this.props.children(
      ({
        ...restProps,
        rootRef: this.props.rootRef ? this.props.rootRef : this.rootRef,
        activedescendantId: this.state.activedescendantId,
        getRequiredItemProps: this.getRequiredItemProps,
        highlightedIndex: this.state.highlightedIndex,
        isFocused: this.state.isFocused,
        focusMenu: this.focusMenu,
        unfocusMenu: this.unfocusMenu,
      }: RenderPropsT),
    );
  }
}