UNPKG

office-ui-fabric-react

Version:

Reusable React components for building experiences for Office 365.

583 lines • 33.4 kB
define(["require", "exports", "tslib", "react", "./Dropdown.types", "../../Checkbox", "../../Callout", "../../Label", "../../Button", "../../Panel", "../../Icon", "../../FocusZone", "../../utilities/decorators/withResponsiveMode", "../../Utilities", "../../utilities/selectableOption/SelectableOption.types", "./Dropdown.scss", "../Checkbox/Checkbox.styles", "../../Styling", "../../KeytipData"], function (require, exports, tslib_1, React, Dropdown_types_1, Checkbox_1, Callout_1, Label_1, Button_1, Panel_1, Icon_1, FocusZone_1, withResponsiveMode_1, Utilities_1, SelectableOption_types_1, stylesImport, Checkbox_styles_1, Styling_1, KeytipData_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var styles = stylesImport; var Dropdown = /** @class */ (function (_super) { tslib_1.__extends(Dropdown, _super); function Dropdown(props) { var _this = _super.call(this, props) || this; _this._host = Utilities_1.createRef(); _this._focusZone = Utilities_1.createRef(); _this._dropDown = Utilities_1.createRef(); _this._scrollIdleDelay = 250 /* ms */; // Render text in dropdown input _this._onRenderTitle = function (item) { var _a = _this.props.multiSelectDelimiter, multiSelectDelimiter = _a === void 0 ? ', ' : _a; var displayTxt = item.map(function (i) { return i.text; }).join(multiSelectDelimiter); return React.createElement("span", null, displayTxt); }; // Render placeHolder text in dropdown input _this._onRenderPlaceHolder = function (props) { if (!props.placeHolder) { return null; } return React.createElement("span", null, props.placeHolder); }; // Render Callout or Panel container and pass in list _this._onRenderContainer = function (props) { var _a = _this.props, _b = _a.onRenderList, onRenderList = _b === void 0 ? _this._onRenderList : _b, responsiveMode = _a.responsiveMode, calloutProps = _a.calloutProps, panelProps = _a.panelProps, dropdownWidth = _a.dropdownWidth; var isSmall = responsiveMode <= withResponsiveMode_1.ResponsiveMode.medium; return (isSmall ? (React.createElement(Panel_1.Panel, tslib_1.__assign({ className: Utilities_1.css('ms-Dropdown-panel', styles.panel, !!panelProps && panelProps.className), isOpen: true, isLightDismiss: true, onDismissed: _this._onDismiss, hasCloseButton: false }, panelProps), onRenderList(props, _this._onRenderList))) : (React.createElement(Callout_1.Callout, tslib_1.__assign({ isBeakVisible: false, gapSpace: 0, doNotLayer: false, directionalHintFixed: true, directionalHint: 4 /* bottomLeftEdge */ }, calloutProps, { className: Utilities_1.css('ms-Dropdown-callout', styles.callout, !!calloutProps && calloutProps.className), target: _this._dropDown.current, onDismiss: _this._onDismiss, onScroll: _this._onScroll, onPositioned: _this._onPositioned, calloutWidth: dropdownWidth || (_this._dropDown.current ? _this._dropDown.current.clientWidth : 0) }), onRenderList(props, _this._onRenderList)))); }; // Render Caret Down Icon _this._onRenderCaretDown = function (props) { return (React.createElement(Icon_1.Icon, { className: Utilities_1.css('ms-Dropdown-caretDown', styles.caretDown), iconName: 'ChevronDown' })); }; // Render List of items _this._onRenderList = function (props) { var _a = _this.props.onRenderItem, onRenderItem = _a === void 0 ? _this._onRenderItem : _a; var id = _this._id; var _b = _this.state.selectedIndices, selectedIndices = _b === void 0 ? [] : _b; return (React.createElement("div", { className: styles.listWrapper, onKeyDown: _this._onZoneKeyDown, ref: _this._host, tabIndex: 0 }, React.createElement(FocusZone_1.FocusZone, { ref: _this._focusZone, direction: FocusZone_1.FocusZoneDirection.vertical, defaultActiveElement: selectedIndices[0] !== undefined ? "#" + id + "-list" + selectedIndices[0] : undefined, id: id + '-list', className: Utilities_1.css('ms-Dropdown-items', styles.items), "aria-labelledby": id + '-label', role: 'listbox' }, _this.props.options.map(function (item, index) { return onRenderItem(tslib_1.__assign({}, item, { index: index }), _this._onRenderItem); })))); }; // Render items _this._onRenderItem = function (item) { switch (item.itemType) { case SelectableOption_types_1.SelectableOptionMenuItemType.Divider: return _this._renderSeparator(item); case SelectableOption_types_1.SelectableOptionMenuItemType.Header: return _this._renderHeader(item); default: return _this._renderOption(item); } }; // Render menu item _this._renderOption = function (item) { var _a = _this.props.onRenderOption, onRenderOption = _a === void 0 ? _this._onRenderOption : _a; var _b = _this.state.selectedIndices, selectedIndices = _b === void 0 ? [] : _b; var id = _this._id; var isItemSelected = item.index !== undefined && selectedIndices ? selectedIndices.indexOf(item.index) > -1 : false; var checkboxStyles = function () { return Checkbox_styles_1.getStyles({ theme: Styling_1.getTheme(), checked: isItemSelected, disabled: item.disabled }); }; return (!_this.props.multiSelect ? (React.createElement(Button_1.CommandButton, { id: id + '-list' + item.index, ref: Dropdown_1.Option + item.index, key: item.key, "data-index": item.index, "data-is-focusable": !item.disabled, disabled: item.disabled, className: Utilities_1.css('ms-Dropdown-item', styles.item, (_c = {}, _c['is-selected ' + styles.itemIsSelected] = isItemSelected, _c['is-disabled ' + styles.itemIsDisabled] = item.disabled === true, _c)), onClick: _this._onItemClick(item), onMouseEnter: _this._onItemMouseEnter.bind(_this, item), onMouseLeave: _this._onMouseItemLeave.bind(_this, item), onMouseMove: _this._onItemMouseMove.bind(_this, item), role: 'option', "aria-selected": isItemSelected ? 'true' : 'false', ariaLabel: item.ariaLabel || item.text }, onRenderOption(item, _this._onRenderOption))) : (React.createElement(Checkbox_1.Checkbox, { id: id + '-list' + item.index, key: item.key, "data-index": item.index, "data-is-focusable": !item.disabled, disabled: item.disabled, onChange: _this._onItemClick(item), inputProps: { onMouseEnter: _this._onItemMouseEnter.bind(_this, item), onMouseLeave: _this._onMouseItemLeave.bind(_this, item), onMouseMove: _this._onItemMouseMove.bind(_this, item) }, label: item.text, onRenderLabel: _this._onRenderLabel.bind(_this, item), className: Utilities_1.css('ms-ColumnManagementPanel-checkbox', styles.dropdownCheckbox, 'ms-Dropdown-item', styles.item, (_d = {}, _d['is-selected ' + styles.itemIsSelected] = isItemSelected, _d['is-disabled ' + styles.itemIsDisabled] = item.disabled, _d)), role: 'option', "aria-selected": isItemSelected ? 'true' : 'false', checked: isItemSelected, // Hover is being handled by focus styles // so clear out the explicit hover styles styles: checkboxStyles }))); var _c, _d; }; // Render content of item (i.e. text/icon inside of button) _this._onRenderOption = function (item) { return React.createElement("span", { className: Utilities_1.css('ms-Dropdown-optionText', styles.optionText) }, item.text); }; // Render custom label for drop down item _this._onRenderLabel = function (item) { var _a = _this.props.onRenderOption, onRenderOption = _a === void 0 ? _this._onRenderOption : _a; return onRenderOption(item, _this._onRenderOption); }; _this._onPositioned = function () { if (_this._focusZone.current) { // Focusing an element can trigger a reflow. Making this wait until there is an animation // frame can improve perf significantly. _this._async.requestAnimationFrame(function () { return _this._focusZone.current.focus(); }); } }; _this._onItemClick = function (item) { return function () { if (!item.disabled) { _this.setSelectedIndex(item.index); if (!_this.props.multiSelect) { // only close the callout when it's in single-select mode _this.setState({ isOpen: false }); } } }; }; /** * Scroll handler for the callout to make sure the mouse events * for updating focus are not interacting during scroll */ _this._onScroll = function () { if (!_this._isScrollIdle && _this._scrollIdleTimeoutId !== undefined) { _this._async.clearTimeout(_this._scrollIdleTimeoutId); _this._scrollIdleTimeoutId = undefined; } else { _this._isScrollIdle = false; } _this._scrollIdleTimeoutId = _this._async.setTimeout(function () { _this._isScrollIdle = true; }, _this._scrollIdleDelay); }; _this._onMouseItemLeave = function (item, ev) { if (!_this._isScrollIdle) { return; } /** * IE11 focus() method forces parents to scroll to top of element. * Edge and IE expose a setActive() function for focusable divs that * sets the page focus but does not scroll the parent element. */ if (_this._host.current) { if (_this._host.current.setActive) { _this._host.current.setActive(); } else { _this._host.current.focus(); } } }; _this._onDismiss = function () { _this.setState({ isOpen: false }); if (_this._dropDown.current) { _this._dropDown.current.focus(); } }; _this._onDropdownBlur = function (ev) { if (_this.state.isOpen) { // Do not onBlur when the callout is opened return; } if (_this.props.onBlur) { _this.props.onBlur(ev); } }; _this._onDropdownKeyDown = function (ev) { if (_this.props.onKeyDown) { _this.props.onKeyDown(ev); if (ev.defaultPrevented) { return; } } var newIndex; var selectedIndex = _this.state.selectedIndices.length ? _this.state.selectedIndices[0] : -1; switch (ev.which) { case 13 /* enter */: _this.setState({ isOpen: !_this.state.isOpen }); break; case 27 /* escape */: if (!_this.state.isOpen) { return; } _this.setState({ isOpen: false }); break; case 38 /* up */: if (_this.props.multiSelect) { _this.setState({ isOpen: true }); } else { newIndex = _this._moveIndex(-1, selectedIndex - 1, selectedIndex); } break; case 40 /* down */: if (ev.altKey || ev.metaKey || _this.props.multiSelect) { _this.setState({ isOpen: true }); } else { newIndex = _this._moveIndex(1, selectedIndex + 1, selectedIndex); } break; case 36 /* home */: if (!_this.props.multiSelect) { newIndex = _this._moveIndex(1, 0, selectedIndex); } break; case 35 /* end */: if (!_this.props.multiSelect) { newIndex = _this._moveIndex(-1, _this.props.options.length - 1, selectedIndex); } break; case 32 /* space */: // event handled in _onDropdownKeyUp break; default: if (ev.altKey || ev.metaKey) { _this.setState({ isOpen: false }); ev.stopPropagation(); ev.preventDefault(); } return; } if (newIndex !== selectedIndex) { ev.stopPropagation(); ev.preventDefault(); } }; _this._onDropdownKeyUp = function (ev) { if (_this.props.onKeyUp) { _this.props.onKeyUp(ev); if (ev.preventDefault) { return; } } switch (ev.which) { case 32 /* space */: _this.setState({ isOpen: !_this.state.isOpen }); break; default: return; } ev.stopPropagation(); ev.preventDefault(); }; _this._onZoneKeyDown = function (ev) { var elementToFocus; switch (ev.which) { case 38 /* up */: if (ev.altKey || ev.metaKey) { _this.setState({ isOpen: false }); } else { if (_this._host.current) { elementToFocus = Utilities_1.getLastFocusable(_this._host.current, _this._host.current.lastChild, true); } } break; // All directional keystrokes should be canceled when the zone is rendered. // This avoids the body scroll from reacting and thus dismissing the dropdown. case 36 /* home */: case 35 /* end */: case 33 /* pageUp */: case 34 /* pageDown */: break; case 40 /* down */: if (_this._host.current) { elementToFocus = Utilities_1.getFirstFocusable(_this._host.current, _this._host.current.firstChild, true); } break; case 27 /* escape */: _this.setState({ isOpen: false }); break; case 9 /* tab */: _this.setState({ isOpen: false }); return; default: if (ev.altKey || ev.metaKey) { _this.setState({ isOpen: false }); break; } return; } if (elementToFocus) { elementToFocus.focus(); } ev.stopPropagation(); ev.preventDefault(); }; _this._onDropdownClick = function (ev) { if (_this.props.onClick) { _this.props.onClick(ev); if (ev.preventDefault) { return; } } var disabled = _this.props.disabled; var isDisabled = _this.props.isDisabled; var isOpen = _this.state.isOpen; // Remove this deprecation workaround at 1.0.0 if (isDisabled !== undefined) { disabled = isDisabled; } if (!disabled) { _this.setState({ isOpen: !isOpen }); } }; props.options.forEach(function (option) { if (!option.itemType) { option.itemType = Dropdown_types_1.DropdownMenuItemType.Normal; } }); _this = _super.call(this, props) || this; _this._warnDeprecations({ 'isDisabled': 'disabled' }); _this._warnMutuallyExclusive({ 'defaultSelectedKey': 'selectedKey', 'defaultSelectedKeys': 'selectedKeys', 'selectedKeys': 'selectedKey', 'multiSelect': 'defaultSelectedKey', 'selectedKey': 'multiSelect' }); _this._id = props.id || Utilities_1.getId('Dropdown'); _this._isScrollIdle = true; _this.state = { isOpen: false }; if (_this.props.multiSelect) { var selectedKeys = props.defaultSelectedKeys !== undefined ? props.defaultSelectedKeys : props.selectedKeys; _this.state = { selectedIndices: _this._getSelectedIndexes(props.options, selectedKeys) }; } else { var selectedKey = props.defaultSelectedKey !== undefined ? props.defaultSelectedKey : props.selectedKey; _this.state = { selectedIndices: _this._getSelectedIndexes(props.options, selectedKey) }; } return _this; } Dropdown_1 = Dropdown; Dropdown.prototype.componentWillReceiveProps = function (newProps) { // In controlled component usage where selectedKey is provided, update the selectedIndex // state if the key or options change. var selectedKeyProp = this.props.multiSelect ? 'selectedKeys' : 'selectedKey'; if (newProps[selectedKeyProp] !== undefined && (newProps[selectedKeyProp] !== this.props[selectedKeyProp] || newProps.options !== this.props.options)) { this.setState({ selectedIndices: this._getSelectedIndexes(newProps.options, newProps[selectedKeyProp]) }); } }; Dropdown.prototype.componentDidUpdate = function (prevProps, prevState) { if (prevState.isOpen === true && this.state.isOpen === false) { if (this._dropDown.current) { this._dropDown.current.focus(); } if (this.props.onDismiss) { this.props.onDismiss(); } } }; // Primary Render Dropdown.prototype.render = function () { var _this = this; var id = this._id; var disabled = this.props.disabled; var _a = this.props, className = _a.className, label = _a.label, options = _a.options, isDisabled = _a.isDisabled, ariaLabel = _a.ariaLabel, required = _a.required, errorMessage = _a.errorMessage, keytipProps = _a.keytipProps, _b = _a.onRenderTitle, onRenderTitle = _b === void 0 ? this._onRenderTitle : _b, _c = _a.onRenderContainer, onRenderContainer = _c === void 0 ? this._onRenderContainer : _c, _d = _a.onRenderPlaceHolder, onRenderPlaceHolder = _d === void 0 ? this._onRenderPlaceHolder : _d, _e = _a.onRenderCaretDown, onRenderCaretDown = _e === void 0 ? this._onRenderCaretDown : _e; var _f = this.state, isOpen = _f.isOpen, _g = _f.selectedIndices, selectedIndices = _g === void 0 ? [] : _g; var selectedOptions = this._getAllSelectedOptions(options, selectedIndices); var divProps = Utilities_1.getNativeProps(this.props, Utilities_1.divProperties); // Remove this deprecation workaround at 1.0.0 if (isDisabled !== undefined) { disabled = isDisabled; } var describedBy = id + '-option'; return (React.createElement("div", { className: Utilities_1.css('ms-Dropdown-container') }, label && (React.createElement(Label_1.Label, { className: Utilities_1.css('ms-Dropdown-label'), id: id + '-label', htmlFor: id, required: required }, label)), React.createElement(KeytipData_1.KeytipData, { keytipProps: keytipProps, disabled: disabled }, function (keytipAttributes) { return (React.createElement("div", tslib_1.__assign({}, keytipAttributes, { "data-is-focusable": !disabled, ref: _this._dropDown, id: id, tabIndex: disabled ? -1 : 0, "aria-expanded": isOpen ? 'true' : 'false', role: 'listbox', "aria-live": disabled || isOpen ? 'off' : 'assertive', "aria-label": ariaLabel, "aria-describedby": describedBy + (keytipAttributes['aria-describedby'] || ''), "aria-activedescendant": isOpen && selectedIndices.length === 1 && selectedIndices[0] >= 0 ? (_this._id + '-list' + selectedIndices[0]) : undefined, "aria-disabled": disabled, "aria-owns": isOpen ? id + '-list' : undefined }, divProps, { className: Utilities_1.css('ms-Dropdown', styles.root, className, isOpen && 'is-open', disabled && ('is-disabled ' + styles.rootIsDisabled), required && 'is-required'), onBlur: _this._onDropdownBlur, onKeyDown: _this._onDropdownKeyDown, onKeyUp: _this._onDropdownKeyUp, onClick: _this._onDropdownClick }), React.createElement("span", { id: id + '-option', className: Utilities_1.css('ms-Dropdown-title', styles.title, !selectedOptions.length && 'ms-Dropdown-titleIsPlaceHolder', !selectedOptions.length && styles.titleIsPlaceHolder, (errorMessage && errorMessage.length > 0 ? styles.titleIsError : null)), "aria-atomic": true, role: 'listbox' }, // If option is selected render title, otherwise render the placeholder text selectedOptions.length ? (onRenderTitle(selectedOptions, _this._onRenderTitle)) : onRenderPlaceHolder(_this.props, _this._onRenderPlaceHolder)), React.createElement("span", { className: Utilities_1.css('ms-Dropdown-caretDownWrapper', styles.caretDownWrapper) }, onRenderCaretDown(_this.props, _this._onRenderCaretDown)))); }), isOpen && (onRenderContainer(this.props, this._onRenderContainer)), errorMessage && React.createElement("div", { className: Utilities_1.css(styles.errorMessage) }, errorMessage))); }; Dropdown.prototype.focus = function (shouldOpenOnFocus) { if (this._dropDown.current && this._dropDown.current.tabIndex !== -1) { this._dropDown.current.focus(); if (shouldOpenOnFocus) { this.setState({ isOpen: true }); } } }; Dropdown.prototype.setSelectedIndex = function (index) { var _a = this.props, onChanged = _a.onChanged, options = _a.options, selectedKey = _a.selectedKey, selectedKeys = _a.selectedKeys, multiSelect = _a.multiSelect; var _b = this.state.selectedIndices, selectedIndices = _b === void 0 ? [] : _b; var checked = selectedIndices ? selectedIndices.indexOf(index) > -1 : false; index = Math.max(0, Math.min(options.length - 1, index)); if (!multiSelect && index === selectedIndices[0]) { return; } else if (!multiSelect && selectedKey === undefined) { // Set the selected option if this is an uncontrolled component this.setState({ selectedIndices: [index] }); } else if (multiSelect && selectedKeys === undefined) { var newIndexes = selectedIndices ? this._copyArray(selectedIndices) : []; if (checked) { var position = newIndexes.indexOf(index); if (position > -1) { // unchecked the current one newIndexes.splice(position, 1); } } else { // add the new selected index into the existing one newIndexes.push(index); } this.setState({ selectedIndices: newIndexes }); } if (onChanged) { // for single-select, option passed in will always be selected. // for multi-select, flip the checked value var changedOpt = multiSelect ? tslib_1.__assign({}, options[index], { selected: !checked }) : options[index]; onChanged(changedOpt, index); } }; Dropdown.prototype._copyArray = function (array) { var newArray = []; for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var element = array_1[_i]; newArray.push(element); } return newArray; }; /** * Finds the next valid Dropdown option and sets the selected index to it. * @param stepValue Value of how many items the function should traverse. Should be -1 or 1. * @param index Index of where the search should start * @param selectedIndex The selectedIndex Dropdown's state * @returns The next valid dropdown option's index */ Dropdown.prototype._moveIndex = function (stepValue, index, selectedIndex) { var options = this.props.options; // Return selectedIndex if nothing has changed or options is empty if (selectedIndex === index || options.length === 0) { return selectedIndex; } // Set starting index to 0 if index is < 0 if (index < 0) { index = 0; } // Set starting index to last option index if greater than options.length if (index >= options.length) { index = options.length - 1; } var stepCounter = 0; // If current index is a header or divider, or disabled, increment by step while (options[index].itemType === Dropdown_types_1.DropdownMenuItemType.Header || options[index].itemType === Dropdown_types_1.DropdownMenuItemType.Divider || options[index].disabled) { // If stepCounter exceeds length of options, then return selectedIndex (-1) if (stepCounter >= options.length) { return selectedIndex; } // If index + stepValue is out of bounds, wrap around if (index + stepValue < 0) { index = options.length; } else if (index + stepValue >= options.length) { index = -1; } index = index + stepValue; stepCounter++; } this.setSelectedIndex(index); return index; }; // Render separator Dropdown.prototype._renderSeparator = function (item) { var index = item.index, key = item.key; if (index > 0) { return (React.createElement("div", { role: 'separator', key: key, className: Utilities_1.css('ms-Dropdown-divider', styles.divider) })); } return null; }; Dropdown.prototype._renderHeader = function (item) { var _a = this.props.onRenderOption, onRenderOption = _a === void 0 ? this._onRenderOption : _a; var key = item.key; return (React.createElement("div", { key: key, className: Utilities_1.css('ms-Dropdown-header', styles.header) }, onRenderOption(item, this._onRenderOption))); }; Dropdown.prototype._onItemMouseEnter = function (item, ev) { if (!this._isScrollIdle) { return; } var targetElement = ev.currentTarget; targetElement.focus(); }; Dropdown.prototype._onItemMouseMove = function (item, ev) { var targetElement = ev.currentTarget; if (!this._isScrollIdle || document.activeElement === targetElement) { return; } targetElement.focus(); }; // Get all selected indexes for multi-select mode Dropdown.prototype._getSelectedIndexes = function (options, selectedKey) { if (selectedKey === undefined) { if (this.props.multiSelect) { return this._getAllSelectedIndices(options); } var selectedIndex = this._getSelectedIndex(options, null); return selectedIndex !== -1 ? [selectedIndex] : []; } else if (!Array.isArray(selectedKey)) { return [this._getSelectedIndex(options, selectedKey)]; } var selectedIndices = []; for (var _i = 0, selectedKey_1 = selectedKey; _i < selectedKey_1.length; _i++) { var key = selectedKey_1[_i]; selectedIndices.push(this._getSelectedIndex(options, key)); } return selectedIndices; }; // Get all selected options for multi-select mode Dropdown.prototype._getAllSelectedOptions = function (options, selectedIndices) { var selectedOptions = []; for (var _i = 0, selectedIndices_1 = selectedIndices; _i < selectedIndices_1.length; _i++) { var index = selectedIndices_1[_i]; var option = options[index]; if (option) { selectedOptions.push(option); } } return selectedOptions; }; Dropdown.prototype._getAllSelectedIndices = function (options) { return options .map(function (option, index) { return option.selected ? index : -1; }) .filter(function (index) { return index !== -1; }); }; Dropdown.prototype._getSelectedIndex = function (options, selectedKey) { return Utilities_1.findIndex(options, (function (option) { // tslint:disable-next-line:triple-equals if (selectedKey != null) { return option.key === selectedKey; } else { return !!option.isSelected || !!option.selected; } })); }; Dropdown.defaultProps = { options: [] }; Dropdown.Option = 'option'; Dropdown = Dropdown_1 = tslib_1.__decorate([ withResponsiveMode_1.withResponsiveMode ], Dropdown); return Dropdown; var Dropdown_1; }(Utilities_1.BaseComponent)); exports.Dropdown = Dropdown; }); //# sourceMappingURL=Dropdown.js.map