wix-style-react
Version:
369 lines (310 loc) • 17.7 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BulkSelection = exports.BulkSelectionContextPropTypes = exports.ChangeType = exports.BulkSelectionState = exports.BulkSelectionContext = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var BulkSelectionContext = /*#__PURE__*/_react["default"].createContext();
exports.BulkSelectionContext = BulkSelectionContext;
var BulkSelectionState = Object.freeze({
ALL: 'ALL',
NONE: 'NONE',
SOME: 'SOME'
});
exports.BulkSelectionState = BulkSelectionState;
var ChangeType = Object.freeze({
ALL: 'ALL',
NONE: 'NONE',
SINGLE_TOGGLE: 'SINGLE_TOGGLE'
});
/** Helper for PropTypes for component which consume the BulkSelection context */
exports.ChangeType = ChangeType;
var BulkSelectionContextPropTypes = {
isSelected: _propTypes["default"].func,
selectedCount: _propTypes["default"].number,
getSelectedIds: _propTypes["default"].func,
getNotSelectedIds: _propTypes["default"].func,
infiniteBulkSelected: _propTypes["default"].bool,
bulkSelectionState: _propTypes["default"].string,
toggleSelectionById: _propTypes["default"].func,
deselectRowsByDefault: _propTypes["default"].bool,
toggleAll: _propTypes["default"].func,
selectAll: _propTypes["default"].func,
deselectAll: _propTypes["default"].func,
setSelectedIds: _propTypes["default"].func,
selectionDisabled: _propTypes["default"].oneOfType([_propTypes["default"].bool, _propTypes["default"].func])
};
/**
* BulkSelection manages the state and logic of bulk selection.
* Given an array of selectable items, it manages a bulk selection state (ALL, SOME, NONE),
* and provides helper methods for modifying the state.
*
* toggleBulkSelection(): changes the bulk state according to these state changes: ALL->NONE, SOME->ALL, NONE->ALL
*/
exports.BulkSelectionContextPropTypes = BulkSelectionContextPropTypes;
var BulkSelection = /*#__PURE__*/function (_React$Component) {
(0, _inherits2["default"])(BulkSelection, _React$Component);
var _super = _createSuper(BulkSelection);
function BulkSelection(_props) {
var _this;
(0, _classCallCheck2["default"])(this, BulkSelection);
_this = _super.call(this, _props);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleAll", function (enable, origin) {
if (enable) {
if (_this.props.hasMoreInBulkSelection) {
_this.setNotSelectedIds([], {
type: ChangeType.ALL,
origin: origin
});
} else {
_this.setSelectedIds(_this.props.allIds, {
type: ChangeType.ALL,
origin: origin
});
}
} else {
_this.setSelectedIds([], {
type: ChangeType.NONE,
origin: origin
});
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleBulkSelection", function (deselectRowsByDefault, origin) {
var bulkSelectionState = _this.state.helpers.bulkSelectionState;
if (bulkSelectionState === BulkSelectionState.SOME) {
_this.toggleAll(!deselectRowsByDefault, origin);
} else if (bulkSelectionState === BulkSelectionState.ALL) {
_this.toggleAll(false, origin);
} else {
_this.toggleAll(true, origin);
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleSelectionById", function (id, origin) {
var newSelectionValue = !_this.state.helpers.isSelected(id);
var change = {
type: ChangeType.SINGLE_TOGGLE,
id: id,
value: newSelectionValue,
origin: origin
};
if (_this.state.selectedIds) {
_this.setSelectedIds(newSelectionValue ? _this.state.selectedIds.concat(id) : _this.state.selectedIds.filter(function (_id) {
return _id !== id;
}), change);
} else {
_this.setNotSelectedIds(newSelectionValue ? _this.state.notSelectedIds.filter(function (_id) {
return _id !== id;
}) : _this.state.notSelectedIds.concat(id), change);
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setSelectedIds", function (selectedIds, change, props) {
if (!Array.isArray(selectedIds)) {
throw new Error('selectedIds must be an array');
}
if (!props) {
props = _this.props;
}
var notSelectedIds = null;
_this.setState({
selectedIds: selectedIds,
notSelectedIds: notSelectedIds,
helpers: _this.createHelpers(_objectSpread(_objectSpread({}, props), {}, {
selectedIds: selectedIds,
notSelectedIds: notSelectedIds
}))
}, function () {
_this.props.onSelectionChanged && _this.props.onSelectionChanged(selectedIds.slice(), change);
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setNotSelectedIds", function (notSelectedIds, change, props) {
if (!Array.isArray(notSelectedIds)) {
throw new Error('notSelectedIds must be an array');
}
if (!props) {
props = _this.props;
}
var selectedIds = null;
_this.setState({
selectedIds: selectedIds,
notSelectedIds: notSelectedIds,
helpers: _this.createHelpers(_objectSpread(_objectSpread({}, props), {}, {
selectedIds: selectedIds,
notSelectedIds: notSelectedIds
}))
}, function () {
_this.props.onSelectionChanged && _this.props.onSelectionChanged(null, change);
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "areSelectedIdsEqual", function (selectedIds1, selectedIds2) {
if (selectedIds1 === selectedIds2) {
return true;
}
return Array.isArray(selectedIds1) && Array.isArray(selectedIds2) && selectedIds1.length === selectedIds2.length && selectedIds1.every(function (item, index) {
return item === selectedIds2[index];
});
});
var _selectedIds = (_props.selectedIds || []).slice();
var _notSelectedIds = null;
_this.state = {
selectedIds: _selectedIds,
// not exposed to context consumers
notSelectedIds: _notSelectedIds,
// not exposed to context consumers
helpers: _this.createHelpers(_objectSpread(_objectSpread({}, _props), {}, {
selectedIds: _selectedIds,
notSelectedIds: _notSelectedIds
}))
};
return _this;
}
(0, _createClass2["default"])(BulkSelection, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var _this2 = this;
if (nextProps.selectedIds && !this.areSelectedIdsEqual(nextProps.selectedIds, this.state.selectedIds)) {
this.setSelectedIds(nextProps.selectedIds.slice(), undefined, nextProps);
} else if (this.state.selectedIds && this.state.helpers.bulkSelectionState === BulkSelectionState.ALL && !this.areSelectedIdsEqual(nextProps.allIds, this.props.allIds)) {
// change bulkSelectionState after load more
this.setSelectedIds(this.state.selectedIds, undefined, nextProps);
} else if (this.state.notSelectedIds && !nextProps.hasMoreInBulkSelection) {
// cancel infinite bulk selection mode if it is no longer relevant (e.g. when done loading)
var selectedIds = nextProps.allIds.filter(function (id) {
return !_this2.state.notSelectedIds.includes(id);
});
this.setSelectedIds(selectedIds, undefined, nextProps);
} else if (this.props.selectionDisabled !== nextProps.selectionDisabled || !this.areSelectedIdsEqual(this.props.allIds, nextProps.allIds)) {
var _this$state = this.state,
_selectedIds2 = _this$state.selectedIds,
notSelectedIds = _this$state.notSelectedIds;
var nextSelectedIds = _selectedIds2 && _selectedIds2.filter(function (id) {
return nextProps.allIds.includes(id);
});
var nextNotSelectedIds = notSelectedIds && notSelectedIds.filter(function (id) {
return nextProps.allIds.includes(id);
});
this.setState({
selectedIds: nextSelectedIds,
notSelectedIds: nextNotSelectedIds,
helpers: this.createHelpers(_objectSpread(_objectSpread({}, nextProps), {}, {
selectedIds: nextSelectedIds,
notSelectedIds: nextNotSelectedIds
}))
});
}
}
}, {
key: "createHelpers",
value: function createHelpers(_ref) {
var _this3 = this;
var selectedIds = _ref.selectedIds,
notSelectedIds = _ref.notSelectedIds,
allIds = _ref.allIds,
selectionDisabled = _ref.selectionDisabled,
deselectRowsByDefault = _ref.deselectRowsByDefault,
_ref$totalCount = _ref.totalCount,
totalCount = _ref$totalCount === void 0 ? 0 : _ref$totalCount;
var selectedCount = selectedIds ? selectedIds.length : totalCount - notSelectedIds.length;
var selectedIdsBulkState = selectedCount === 0 ? BulkSelectionState.NONE : selectedCount === allIds.length ? BulkSelectionState.ALL : BulkSelectionState.SOME;
var notSelectedIdsBulkState = notSelectedIds && notSelectedIds.length === 0 ? BulkSelectionState.ALL : BulkSelectionState.SOME;
var bulkSelectionState = selectedIds ? selectedIdsBulkState : notSelectedIdsBulkState;
return {
// Getters
/** Is the item with the given id selected. (id comes from the rowData.id if exists, if not then it is the rowIndex)
* Note: `selectedIds` and `notSelectedIds` are mutually exclusive and only one of them is defined.
* `notSelectedIds` is defined when `hasMoreInBulkSelection` is selected and user did bulk selection. Otherwise, selectedIds is defined. */
isSelected: function isSelected(id) {
return selectedIds ? selectedIds.includes(id) : !notSelectedIds.includes(id);
},
/** Number of selected items */
selectedCount: selectedCount,
/** Get a copy (array) of selected ids when `infiniteBulkSelected` is `false`.
* If `infiniteBulkSelected` is true, returns `null` */
getSelectedIds: function getSelectedIds() {
return selectedIds && selectedIds.slice();
},
/** Get a copy (array) of ids that were deselected after bulk selection was done, when `infiniteBulkSelected` is `true`.
* If `infiniteBulkSelected` is `false`, returns `null`. */
getNotSelectedIds: function getNotSelectedIds() {
return notSelectedIds && notSelectedIds.slice();
},
/** Indicates whether bulk selection was done by the user and `hasMoreInBulkSelection` is `true` */
infiniteBulkSelected: selectedIds === null,
/** A string representing the BulkSelection state (not a React state).
* Possible values: ALL, SOME, NONE
*/
bulkSelectionState: bulkSelectionState,
/** Indicates the `toggleAll` behaviour when some rows are selected. `true` means SOME -> NONE, `false` means SOME -> ALL */
deselectRowsByDefault: deselectRowsByDefault,
/** Can be either a boolean or a function.
* A boolean affects selection of all table rows.
* A function will be called for every row in `data` to specify if its checkbox should be disabled. */
selectionDisabled: selectionDisabled === true || allIds.length === 0 || typeof selectionDisabled === 'function' && selectionDisabled,
// Modifiers
/** Toggle the selection state (selected/not-selected) of an item by id */
toggleSelectionById: this.toggleSelectionById,
/** Toggles the bulk selection state: NONE -> ALL, SOME -> ALL, ALL -> NONE */
toggleAll: this.toggleBulkSelection,
/** Select all items */
selectAll: function selectAll(origin) {
return _this3.toggleAll(true, origin);
},
/** Deselect all items (clear selection) */
deselectAll: function deselectAll(origin) {
return _this3.toggleAll(false, origin);
},
/** Set the selection.
* An optional `change` argument will be passed "as is" to the Table's onSelectionChanged callback.
*/
setSelectedIds: this.setSelectedIds
};
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/_react["default"].createElement(BulkSelectionContext.Provider, {
value: this.state.helpers
}, this.props.children);
}
}]);
return BulkSelection;
}(_react["default"].Component);
exports.BulkSelection = BulkSelection;
BulkSelection.propTypes = {
/** Array of item selection boolean states. Should correspond in length to the data prop */
selectedIds: _propTypes["default"].oneOfType([_propTypes["default"].arrayOf(_propTypes["default"].string), _propTypes["default"].arrayOf(_propTypes["default"].number)]),
/** An array of all selectable item ids (string ids) */
allIds: _propTypes["default"].oneOfType([_propTypes["default"].arrayOf(_propTypes["default"].string), _propTypes["default"].arrayOf(_propTypes["default"].number)]).isRequired,
/** Called when item selection changes.
* Receives 2 arguments, the updated selectedIds array, and a `change` object.
* The `change` object has a `type` property with the following possible values: 'ALL', 'NONE', 'SINGLE_TOGGLE'.
* In case of 'SINGLE_TOGGLE' the `change` object will also include an `id` prop with the item's id,
* and a `value` prop with the new boolean selection state of the item.
* The `change` object also contains an `origin` property which indicates what initiated the selection change.
* The `origin` property can be set when selection is updated using a `SelectionContext` method.
* In case `totalSelectableCount` is set and the list is not fully loaded, and the user did bulk selection ("Select All"), the first parameter (selectedIds) will be null.
* You can use the selection context's getNotSelectedIds() method to get the items that the user unselected after selecting all items. */
onSelectionChanged: _propTypes["default"].func,
/** Can be either a boolean or a function.
* If passed a boolean, affects selection for all table rows.
* If passed a function, it will be called for every row in `data` to specify if its checkbox should be disabled. Example: `isRowSelectionDisabled={(rowData) => !rowData.isSelectable}` */
selectionDisabled: _propTypes["default"].oneOfType([_propTypes["default"].bool, _propTypes["default"].func]),
/** Indicates whether the table is in infinite bulk selection mode (`infiniteScroll` and `totalSelectableCount` props are set) and there are more items to load (`hasMore` prop is `true`) */
hasMoreInBulkSelection: _propTypes["default"].bool,
/** The table's `totalSelectableCount` prop */
totalCount: _propTypes["default"].number,
/** Any - can consume the BulkSelectionProvider context */
children: _propTypes["default"].any
};