All files / lib/List index.js

92.55% Statements 87/94
85.11% Branches 80/94
90.48% Functions 19/21
92.55% Lines 87/94
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 343 344 345 346 347 348 349 350 351 352                                                  80x 11x 14x         37x   37x         36x     72x         36x       11x 11x   11x   11x 10x     1x               1x     1x       60x       2x           1x   1x       3x       3x       3x                         1x       14x   14x 14x 14x 14x   14x 14x 14x 2x 12x 2x     10x     14x 14x   14x         14x 1x     14x     1x 1x                       1x   1x 1x       2x 2x 2x 2x       6x 6x 6x 6x       2x 2x 2x       2x 2x 2x   1x 1x 1x   1x     14x 14x 14x                               96x         96x 96x   96x   96x 220x   220x     151x             59x     47x           15x                       5x                   17x       96x     96x                                       89x                                                           89x                             89x       89x      
import React from 'react';
import PropTypes from 'prop-types';
import { omit, uniqueId } from 'lodash';
/**
 * List is container component used to help group list items.
 * @category containers
 * @component list-item
 * @variations collab-ui-react
 */
 
class List extends React.Component {
 
  static childContextTypes = {
    setSelected: PropTypes.func,
    handleListKeyDown: PropTypes.func
  };
 
  state = {
    activeIndex: null,
    focus: null,
    id: this.props.id || uniqueId('cui-list-'),
    last: 0,
  };
 
  getChildContext = () => {
    return {
      setSelected: (e, idx, value, label) => this.setSelected(e, idx, value, label),
      handleListKeyDown: (e, idx) => this.handleListKeyDown(e, idx)
    };
  }
 
  componentDidMount() {
    const { focusFirst } =  this.props;
 
    focusFirst
      && this.determineInitialFocus();
  }
 
  determineInitialFocus = () => {
    const nonDisabledIndex = React.Children
      .toArray(this.props.children)
      .reduceRight((agg, child, idx) => (
        (!child.props.disabled && !child.props.isReadOnly)
          ? idx
          : agg
      ), null);
 
    this.setFocus(nonDisabledIndex);
  }
 
  setSelected = (e, index, value, label) => {
    const { children, onSelect } = this.props;
    const { activeIndex } = this.state;
 
    this.setFocus(index);
    // Don't do anything if onSelect Event Handler is present
    if (onSelect) {
      return onSelect(e, value, index, label);
    }
    // Don't do anything if index is the same or outside of the bounds
    Iif (
      index === activeIndex ||
      index < 0 ||
      index >= children.length
    )
    return;
 
    // Keep reference to last index for event handler
    const last = activeIndex;
 
    // Call change event handler
    this.setState({ activeIndex: index, last });
  };
 
  setFocus = index => {
    this.setState({ focus: index });
  };
 
  getIncludesFirstCharacter = (str, char) =>
    str
      .charAt(0)
      .toLowerCase()
      .includes(char);
 
  setFocusByFirstCharacter = (char, currentIdx, length) => {
    const { children } = this.props;
 
    const newIndex = React.Children
      .toArray(children)
      .reduce((agg, child, idx, arr) => {
 
        const index = currentIdx + idx + 1 > length
          ? Math.abs(currentIdx + idx - length)
          : currentIdx + idx + 1;
 
        const label = arr[index].props.role === 'listItem' || arr[index].type.displayName === 'SelectOption'
          ? arr[index].props.label
          : arr[index].props.header;
 
        return (
          !agg.length
          && !arr[index].props.disabled
          && !arr[index].props.isReadOnly
          && !['ListSeparator'].includes(arr[index].type.displayName)
          && this.getIncludesFirstCharacter(label, char)
        )
          ? agg.concat(index)
          : agg;
      },
      []
    );
 
    !isNaN(newIndex[0]) && this.setFocus(newIndex[0]);
  };
 
  handleListKeyDown = (e, idx) => {
    const {children} = this.props;
    let newIndex, clickEvent;
    const tgt = e.currentTarget;
    const char = e.key;
    let flag = false;
    const length = React.Children.toArray(children).length - 1;
 
    const getNewIndex = (currentIndex, change) => {
      const getPossibleIndex = () => {
        if (currentIndex + change < 0) {
          return length;
        } else if (currentIndex + change > length) {
          return 0;
        }
 
        return currentIndex + change;
      };
 
      const possibleIndex = getPossibleIndex();
      const potentialTarget = React.Children.toArray(this.props.children)[possibleIndex];
 
      return (potentialTarget.props.disabled || potentialTarget.props.isReadOnly || potentialTarget.type.displayName === "ListSeparator")
        ? getNewIndex(possibleIndex, change)
        : possibleIndex;
    };
 
    const isPrintableCharacter = str => {
      return str.length === 1 && str.match(/\S/);
    };
 
    switch (e.which) {
      case 32:
      case 13:
        try {
          clickEvent = new MouseEvent('click', {
            view: window,
            bubbles: true,
            cancelable: true,
          });
        } catch (err) {
          if (document.createEvent) {
            // DOM Level 3 for IE 9+
            clickEvent = document.createEvent('MouseEvents');
            clickEvent.initEvent('click', true, true);
          }
        }
        tgt.dispatchEvent(clickEvent);
 
        flag = true;
        break;
 
      case 38:
      case 37:
        newIndex = getNewIndex(idx, -1);
        this.setFocus(newIndex);
        flag = true;
        break;
 
      case 39:
      case 40:
        newIndex = getNewIndex(idx, 1);
        this.setFocus(newIndex);
        flag = true;
        break;
 
      case 33:
      case 36:
        this.setFocus(0);
        flag = true;
        break;
 
      case 34:
      case 35:
        this.setFocus(length);
        flag = true;
        break;
      default:
        Eif (isPrintableCharacter(char)) {
          this.setFocusByFirstCharacter(char, idx, length);
          flag = true;
        }
        break;
    }
 
    Eif (flag) {
      e.stopPropagation();
      e.preventDefault();
    }
  };
 
  render() {
    const {
      active,
      children,
      className,
      isMulti,
      itemRole,
      role,
      tabType,
      type,
      wrap,
      ...props
    } = this.props;
    const {
      activeIndex,
      focus,
      id
    } = this.state;
    const { visibleClass } = this.context;
 
    const otherProps = omit({...props}, ['focusFirst']);
 
    const setListItems = React.Children.map(children, (child, idx) => {
      const activeIndicator = (typeof active === 'number' || Array.isArray(active)) ? active : activeIndex;
 
      switch (child.type.displayName) {
        case 'ListItem':
        case 'ListItemMeeting':
          return React.cloneElement(child, {
            active: idx === activeIndicator,
            ...type && {type: type},
            focus: focus === idx,
            itemIndex: idx,
            role: itemRole,
            id: `${id}__list-item`,
            ...focus === idx && { ref: ref => this.activeChild = ref }
          });
        case 'SpaceListItem':
          return React.cloneElement(child, {
            active: idx === activeIndicator,
            focus: focus === idx,
            itemIndex: idx,
            role: itemRole,
            id: `${id}__sl-item`,
            ...focus === idx && { ref: ref => this.activeChild = ref }
          });
        case 'SpaceListMeeting':
          return React.cloneElement(child, {
            active: idx === activeIndicator,
            focus: focus === idx,
            itemIndex: idx,
            role: itemRole,
            id: `${id}__sl-item`,
            ...focus === idx && { ref: ref => this.activeChild = ref }
          });
        case 'SelectOption':
          return React.cloneElement(child, {
            active: Array.isArray(activeIndicator) ? activeIndicator.includes(idx) : idx === activeIndicator,
            focus: focus === idx,
            itemIndex: idx,
            role: itemRole,
            isMulti: isMulti,
            id: `${id}__so-item`,
            ...focus === idx && { ref: ref => this.activeChild = ref }
          });
        default:
          return child;
      }
    });
 
    const ActiveDescendantId = this.activeChild && this.activeChild.id;
 
    /* eslint-disable jsx-a11y/aria-activedescendant-has-tabindex */
    return (
      <div
        className={
          'cui-list' +
          ` cui-list${tabType && `--${tabType}` || ''}` +
          ` cui-list${wrap && `--wrap` || ''}` +
          `${(visibleClass && ` ${visibleClass}`) || ''}` +
          `${(className && ` ${className}`) || ''}`
        }
        role={role}
        aria-activedescendant={ActiveDescendantId}
        {...otherProps}
      >
        {setListItems}
      </div>
    );
    /* eslint-enable*/
  }
}
 
List.propTypes = {
  /** @prop Optional active prop to pass active prop to children | null */
  active: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.array
  ]),
  /** @prop Children nodes to render inside List | null */
  children: PropTypes.node,
  /** @prop Optional css class string | '' */
  className: PropTypes.string,
  /** @prop Sets first List item to have focus | true */
  focusFirst: PropTypes.bool,
  /** @prop Optional ID value of List | null */
  id: PropTypes.string,
  /** @prop Optional prop to know if multiple children can be active | false */
  isMulti: PropTypes.bool,
  /** @prop Optional tabType prop type to manually set child role | 'listItem' */
  itemRole: PropTypes.string,
  /** @prop Callback function invoked by user selecting an interactive item within List | null */
  onSelect: PropTypes.func,
  /** @prop Sets the ARIA role for the Nav, in the context of a TabContainer | 'list' */
  role: PropTypes.string,
  /** @prop Sets the orientation of the List | 'vertical' */
  tabType: PropTypes.oneOf(['vertical', 'horizontal']),
  /** @prop Sets List size | null */
  type: PropTypes.oneOf(['small', 'large', 'space', 'xlarge']),
  /** @prop Optional wrap prop type to wrap items to next row */
  wrap: PropTypes.bool
};
 
List.defaultProps = {
  active: null,
  children: null,
  className: '',
  id: null,
  isMulti: false,
  itemRole: 'listItem',
  focusFirst: true,
  onSelect: null,
  role: 'list',
  tabType: 'vertical',
  type: null,
  wrap: false,
};
 
List.contextTypes = {
  visibleClass: PropTypes.string
};
 
List.displayName = 'List';
 
export default List;