UNPKG

terra-list

Version:

The Terra List is a structural component to arrange content within list/listitems.

380 lines (379 loc) 19.8 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _bind = _interopRequireDefault(require("classnames/bind")); var _reactIntl = require("react-intl"); var _terraThemeContext = _interopRequireDefault(require("terra-theme-context")); var KeyCode = _interopRequireWildcard(require("keycode-js")); var _reactBeautifulDnd = require("react-beautiful-dnd"); var _ListModule = _interopRequireDefault(require("./List.module.scss")); var _excluded = ["ariaDescribedBy", "ariaDescription", "ariaDetails", "children", "intl", "dividerStyle", "paddingStyle", "refCallback", "role", "ariaSelectionStyle", "isDraggable", "isTabFocusDisabled", "onDragEnd", "zIndex"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; } var cx = _bind.default.bind(_ListModule.default); var propTypes = { /** * References a visible or visually hidden text element * on the page that conveys information about the list * and how to interact with it. Maps to [aria-describedby](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). * Because `aria-describedby` has the most comprehensive * screen reader support of `aria-describedby`, `aria-description`, and * `aria-details`, it should be the first choice for conveying * List instructions to screen readers. (Note: In some screen readers, * including JAWS, `aria-describedby` is not supported for non-interactable * elements. In these cases, use `aria-details`.) */ ariaDescribedBy: _propTypes.default.string, /** * String that provides information about the list and how to interact * with it. Maps to [aria-description](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-description). * When used with the `ariaDescribedBy` prop, `ariaDescribedBy` * takes precedence in defining the accessible description property. * Because `aria-description` still has limited screen reader support * compared to `aria-describedby`, this prop should only be used in cases where * `aria-describedby` is not sufficient. */ ariaDescription: _propTypes.default.string, /** * References a visible or visually hidden text element * on the page that conveys information about the list * and how to interact with it. Maps to * [aria-details](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details). * Can be used alongside `ariaDescribedBy` or `ariaDescription`. * `aria-details` is not supported in all screen reader/browser * combinations. Consumers should test for different screen * reader/browser combinations to ensure that instructions * are consistently read. */ ariaDetails: _propTypes.default.string, /** * The children list items passed to the component. */ children: _propTypes.default.node, /** * @private * The intl object to be injected for translations. */ intl: _propTypes.default.shape({ formatMessage: _propTypes.default.func }), /** * Whether or not the list's child items should have a border color applied. * One of `'none'`, `'standard'`, `'bottom-only'`. */ dividerStyle: _propTypes.default.oneOf(['none', 'standard', 'bottom-only']), /** * The padding styling to apply to the child list item content. * One of `'none'`, `'standard'`, `'compact'`. */ paddingStyle: _propTypes.default.oneOf(['none', 'standard', 'compact']), /** * Function callback for the ref of the ul. */ refCallback: _propTypes.default.func, /** * Accessibility role of the list, defaults to 'none'. */ role: _propTypes.default.string, /** * Sets the role to `'listbox'` and provides an aria-description of whether its a single or multi-select list. * For multi-select lists, it sets aria-multiselectable to true. * One of `'none'`, `'single-select'`, `'multi-select'`. */ ariaSelectionStyle: _propTypes.default.oneOf(['none', 'single-select', 'multi-select']), /** * Whether or not the list item is draggable. List Item is draggable only when it is selectable. */ isDraggable: _propTypes.default.bool, /** * ![IMPORTANT](https://badgen.net/badge/UX/Accessibility/blue) * Whether or not the list item is focusable with Tab key. Ensure alternative way of focusing list item when set to true for best accessibility experience. */ isTabFocusDisabled: _propTypes.default.bool, /** * Function callback when the Item is dropped. Parameters: * @param {Object} result result * @param {Object} provided provided */ onDragEnd: _propTypes.default.func, /** * z-index value for the list item (li element). Defaults to 6001 which is greater value than terra-modal-manager z-index value. */ zIndex: _propTypes.default.number }; var defaultProps = { ariaSelectionStyle: 'none', children: [], dividerStyle: 'none', isTabFocusDisabled: false, paddingStyle: 'none', role: 'none', zIndex: 6001 }; var List = function List(_ref) { var ariaDescribedBy = _ref.ariaDescribedBy, ariaDescription = _ref.ariaDescription, ariaDetails = _ref.ariaDetails, children = _ref.children, intl = _ref.intl, dividerStyle = _ref.dividerStyle, paddingStyle = _ref.paddingStyle, refCallback = _ref.refCallback, role = _ref.role, ariaSelectionStyle = _ref.ariaSelectionStyle, isDraggable = _ref.isDraggable, isTabFocusDisabled = _ref.isTabFocusDisabled, onDragEnd = _ref.onDragEnd, zIndex = _ref.zIndex, customProps = _objectWithoutProperties(_ref, _excluded); var theme = (0, _react.useContext)(_terraThemeContext.default); var _useState = (0, _react.useState)([]), _useState2 = _slicedToArray(_useState, 2), listItem = _useState2[0], setlistItem = _useState2[1]; var listNode = (0, _react.useRef)(); var isListItemDropped = (0, _react.useRef)(); var draggedItemindex = (0, _react.useRef)(); (0, _react.useEffect)(function () { if (Array.isArray(children)) { setlistItem(children); } else if (children) { setlistItem([children]); } }, [children]); (0, _react.useEffect)(function () { if (isListItemDropped.current) { var listItems = listNode && listNode.querySelectorAll('[data-item-show-focus]'); if (listItems[draggedItemindex.current]) { listItems[draggedItemindex.current].focus(); } isListItemDropped.current = false; } }, [listItem]); var listClassNames = (0, _classnames.default)(cx('list', { 'padding-standard': paddingStyle === 'standard' }, { 'padding-compact': paddingStyle === 'compact' }, { 'divider-standard': dividerStyle === 'standard' }, { 'divider-bottom-only': dividerStyle === 'bottom-only' }, theme.className), customProps.className); var handleListRef = function handleListRef(node) { if (refCallback) { refCallback(node); } listNode = node; }; var handleKeyDown = function handleKeyDown(event) { var listItems = listNode.querySelectorAll('[data-item-show-focus]'); var currentIndex = Array.from(listItems).indexOf(event.target); var lastIndex = listItems.length - 1; switch (event.nativeEvent.keyCode) { case KeyCode.KEY_END: event.preventDefault(); listItems[listItems.length - 1].focus(); break; case KeyCode.KEY_HOME: event.preventDefault(); listItems[0].focus(); break; case KeyCode.KEY_UP: { event.preventDefault(); var previousIndex = currentIndex > 0 ? currentIndex - 1 : lastIndex; if (listItems[previousIndex]) { listItems[previousIndex].focus(); } break; } case KeyCode.KEY_DOWN: { event.preventDefault(); var nextIndex = currentIndex < lastIndex ? currentIndex + 1 : 0; if (listItems[nextIndex]) { listItems[nextIndex].focus(); } break; } default: break; } }; var attrSpread = {}; attrSpread.role = 'list'; // Explicitly set role='list' as it's missing in Safari if (role && role.length > 0 && role !== 'none') { attrSpread.role = role; } if (ariaSelectionStyle === 'single-select') { attrSpread.role = 'listbox'; attrSpread['aria-label'] = intl.formatMessage({ id: 'Terra.list.singleSelect' }); } if (ariaSelectionStyle === 'multi-select') { attrSpread.role = 'listbox'; attrSpread['aria-multiselectable'] = true; attrSpread['aria-label'] = intl.formatMessage({ id: 'Terra.list.multiSelect' }); } var reorderListItems = function reorderListItems(list, startIndex, endIndex) { var result = Array.from(list); var _result$splice = result.splice(startIndex, 1), _result$splice2 = _slicedToArray(_result$splice, 1), removed = _result$splice2[0]; result.splice(endIndex, 0, removed); return result; }; var handleDragEnd = function handleDragEnd(result, provided) { // dropped outside the list if (!result.destination) { provided.announce(intl.formatMessage({ id: 'Terra.list.cancelDrag' }, { startPosition: result.source.index + 1 })); return; } var items = reorderListItems(listItem, result.source.index, result.destination.index); setlistItem(items); draggedItemindex.current = result.destination.index; provided.announce(intl.formatMessage({ id: 'Terra.list.drop' }, { startPosition: result.source.index + 1, endPosition: result.destination.index + 1 })); if (onDragEnd) { onDragEnd(result, provided); } }; var handleDragStart = function handleDragStart(start, provided) { isListItemDropped.current = true; provided.announce(intl.formatMessage({ id: 'Terra.list.lift' }, { startPosition: start.source.index + 1 })); }; var handleDragUpdate = function handleDragUpdate(update, provided) { if (update.destination) { provided.announce(intl.formatMessage({ id: 'Terra.list.drag' }, { startPosition: update.source.index + 1, endPosition: update.destination.index + 1 })); } }; var getStyleforDrag = function getStyleforDrag(ListItem, snapshot, provider) { var _provider$draggablePr; var styleProperties = provider === null || provider === void 0 || (_provider$draggablePr = provider.draggableProps) === null || _provider$draggablePr === void 0 ? void 0 : _provider$draggablePr.style; if (styleProperties && snapshot && snapshot.isDragging) { if (styleProperties.zIndex && styleProperties.zIndex !== zIndex) { styleProperties.zIndex = zIndex; } } return styleProperties; }; var cloneListItem = function cloneListItem(ListItem, provider, snapshot) { var _ListItem$props; return /*#__PURE__*/_react.default.cloneElement(ListItem, _objectSpread(_objectSpread(_objectSpread({ isDraggable: ListItem === null || ListItem === void 0 || (_ListItem$props = ListItem.props) === null || _ListItem$props === void 0 ? void 0 : _ListItem$props.isSelectable, isTabFocusDisabled: isTabFocusDisabled, refCallback: provider.innerRef }, provider.draggableProps), provider.dragHandleProps), {}, { style: getStyleforDrag(ListItem, snapshot, provider) })); }; var clone = function clone(object) { return _react.default.Children.map(object, function (listitem) { return ( /*#__PURE__*/_react.default.isValidElement(listitem)) ? /*#__PURE__*/_react.default.cloneElement(listitem, { isTabFocusDisabled: isTabFocusDisabled }) : null; }); }; var renderListDom = function renderListDom() { return ( /*#__PURE__*/ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/role-supports-aria-props _react.default.createElement("ul", _extends({}, customProps, attrSpread, { "aria-describedby": ariaDescribedBy // eslint-disable-next-line jsx-a11y/aria-props , "aria-description": ariaDescription, "aria-details": ariaDetails, className: listClassNames, ref: handleListRef, onKeyDown: handleKeyDown }), clone(children)) ); }; window['__react-beautiful-dnd-disable-dev-warnings'] = true; var renderDraggableListDom = function renderDraggableListDom() { return /*#__PURE__*/_react.default.createElement(_reactBeautifulDnd.DragDropContext, { onDragEnd: handleDragEnd, onDragStart: handleDragStart, onDragUpdate: handleDragUpdate }, /*#__PURE__*/_react.default.createElement(_reactBeautifulDnd.Droppable, { droppableId: "ListItem", renderClone: function renderClone(provided, snapshot, rubric) { return cloneListItem(listItem[rubric.source.index], provided, snapshot); } }, function (provided) { return ( /*#__PURE__*/ /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/role-supports-aria-props */ _react.default.createElement("ul", _extends({}, provided.droppableProps, customProps, attrSpread, { "aria-describedby": ariaDescribedBy // eslint-disable-next-line jsx-a11y/aria-props , "aria-description": ariaDescription, "aria-details": ariaDetails, className: listClassNames, ref: function ref(refobj) { provided.innerRef(refobj); handleListRef(refobj); }, onKeyDown: handleKeyDown }), listItem.map(function (item, index) { var _item$props; return /*#__PURE__*/_react.default.createElement(_reactBeautifulDnd.Draggable, { isDragDisabled: !(item !== null && item !== void 0 && (_item$props = item.props) !== null && _item$props !== void 0 && _item$props.isSelectable), key: item.key, draggableId: item.key, index: index }, function (provider, snapshot) { return cloneListItem(item, provider, snapshot); }); }), provided.placeholder) ); })); }; return isDraggable ? renderDraggableListDom() : renderListDom(); }; List.propTypes = propTypes; List.defaultProps = defaultProps; var _default = exports.default = (0, _reactIntl.injectIntl)(List);