. ' + 'Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs');
if (!previousRef) {
// When there is no ref on the element, use the new ref directly
return React$1.cloneElement(element, {
ref: newRef
});
} else {
return React$1.cloneElement(element, {
ref: function ref(node) {
setRef(previousRef, node);
setRef(newRef, node);
}
});
}
}
function _typeof$5(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$5 = function _typeof(obj) { return typeof obj; }; } else { _typeof$5 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$5(obj); }
function isRef(obj) {
return (// eslint-disable-next-line no-prototype-builtins
obj !== null && _typeof$5(obj) === 'object' && Object.prototype.hasOwnProperty.call(obj, 'current')
);
}
function shallowEqual(objA, objB, compare, compareContext) {
var compareResult = compare ? compare.call(compareContext, objA, objB) : void 0;
if (compareResult !== void 0) {
return !!compareResult;
}
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || !objA || typeof objB !== 'object' || !objB) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); // Test for A's keys different from B.
for (var idx = 0; idx < keysA.length; idx++) {
var key = keysA[idx];
if (!bHasOwnProperty(key)) {
return false;
}
var valueA = objA[key];
var valueB = objB[key];
compareResult = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if (compareResult === false || compareResult === void 0 && valueA !== valueB) {
return false;
}
}
return true;
}
function _classCallCheck$d(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$d(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$d(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$d(Constructor.prototype, protoProps); if (staticProps) _defineProperties$d(Constructor, staticProps); return Constructor; }
var SourceConnector = /*#__PURE__*/function () {
function SourceConnector(backend) {
var _this = this;
_classCallCheck$d(this, SourceConnector);
this.hooks = wrapConnectorHooks({
dragSource: function dragSource(node, options) {
_this.clearDragSource();
_this.dragSourceOptions = options || null;
if (isRef(node)) {
_this.dragSourceRef = node;
} else {
_this.dragSourceNode = node;
}
_this.reconnectDragSource();
},
dragPreview: function dragPreview(node, options) {
_this.clearDragPreview();
_this.dragPreviewOptions = options || null;
if (isRef(node)) {
_this.dragPreviewRef = node;
} else {
_this.dragPreviewNode = node;
}
_this.reconnectDragPreview();
}
});
this.handlerId = null; // The drop target may either be attached via ref or connect function
this.dragSourceRef = null;
this.dragSourceOptionsInternal = null; // The drag preview may either be attached via ref or connect function
this.dragPreviewRef = null;
this.dragPreviewOptionsInternal = null;
this.lastConnectedHandlerId = null;
this.lastConnectedDragSource = null;
this.lastConnectedDragSourceOptions = null;
this.lastConnectedDragPreview = null;
this.lastConnectedDragPreviewOptions = null;
this.backend = backend;
}
_createClass$d(SourceConnector, [{
key: "receiveHandlerId",
value: function receiveHandlerId(newHandlerId) {
if (this.handlerId === newHandlerId) {
return;
}
this.handlerId = newHandlerId;
this.reconnect();
}
}, {
key: "connectTarget",
get: function get() {
return this.dragSource;
}
}, {
key: "dragSourceOptions",
get: function get() {
return this.dragSourceOptionsInternal;
},
set: function set(options) {
this.dragSourceOptionsInternal = options;
}
}, {
key: "dragPreviewOptions",
get: function get() {
return this.dragPreviewOptionsInternal;
},
set: function set(options) {
this.dragPreviewOptionsInternal = options;
}
}, {
key: "reconnect",
value: function reconnect() {
this.reconnectDragSource();
this.reconnectDragPreview();
}
}, {
key: "reconnectDragSource",
value: function reconnectDragSource() {
var dragSource = this.dragSource; // if nothing has changed then don't resubscribe
var didChange = this.didHandlerIdChange() || this.didConnectedDragSourceChange() || this.didDragSourceOptionsChange();
if (didChange) {
this.disconnectDragSource();
}
if (!this.handlerId) {
return;
}
if (!dragSource) {
this.lastConnectedDragSource = dragSource;
return;
}
if (didChange) {
this.lastConnectedHandlerId = this.handlerId;
this.lastConnectedDragSource = dragSource;
this.lastConnectedDragSourceOptions = this.dragSourceOptions;
this.dragSourceUnsubscribe = this.backend.connectDragSource(this.handlerId, dragSource, this.dragSourceOptions);
}
}
}, {
key: "reconnectDragPreview",
value: function reconnectDragPreview() {
var dragPreview = this.dragPreview; // if nothing has changed then don't resubscribe
var didChange = this.didHandlerIdChange() || this.didConnectedDragPreviewChange() || this.didDragPreviewOptionsChange();
if (didChange) {
this.disconnectDragPreview();
}
if (!this.handlerId) {
return;
}
if (!dragPreview) {
this.lastConnectedDragPreview = dragPreview;
return;
}
if (didChange) {
this.lastConnectedHandlerId = this.handlerId;
this.lastConnectedDragPreview = dragPreview;
this.lastConnectedDragPreviewOptions = this.dragPreviewOptions;
this.dragPreviewUnsubscribe = this.backend.connectDragPreview(this.handlerId, dragPreview, this.dragPreviewOptions);
}
}
}, {
key: "didHandlerIdChange",
value: function didHandlerIdChange() {
return this.lastConnectedHandlerId !== this.handlerId;
}
}, {
key: "didConnectedDragSourceChange",
value: function didConnectedDragSourceChange() {
return this.lastConnectedDragSource !== this.dragSource;
}
}, {
key: "didConnectedDragPreviewChange",
value: function didConnectedDragPreviewChange() {
return this.lastConnectedDragPreview !== this.dragPreview;
}
}, {
key: "didDragSourceOptionsChange",
value: function didDragSourceOptionsChange() {
return !shallowEqual(this.lastConnectedDragSourceOptions, this.dragSourceOptions);
}
}, {
key: "didDragPreviewOptionsChange",
value: function didDragPreviewOptionsChange() {
return !shallowEqual(this.lastConnectedDragPreviewOptions, this.dragPreviewOptions);
}
}, {
key: "disconnectDragSource",
value: function disconnectDragSource() {
if (this.dragSourceUnsubscribe) {
this.dragSourceUnsubscribe();
this.dragSourceUnsubscribe = undefined;
}
}
}, {
key: "disconnectDragPreview",
value: function disconnectDragPreview() {
if (this.dragPreviewUnsubscribe) {
this.dragPreviewUnsubscribe();
this.dragPreviewUnsubscribe = undefined;
this.dragPreviewNode = null;
this.dragPreviewRef = null;
}
}
}, {
key: "dragSource",
get: function get() {
return this.dragSourceNode || this.dragSourceRef && this.dragSourceRef.current;
}
}, {
key: "dragPreview",
get: function get() {
return this.dragPreviewNode || this.dragPreviewRef && this.dragPreviewRef.current;
}
}, {
key: "clearDragSource",
value: function clearDragSource() {
this.dragSourceNode = null;
this.dragSourceRef = null;
}
}, {
key: "clearDragPreview",
value: function clearDragPreview() {
this.dragPreviewNode = null;
this.dragPreviewRef = null;
}
}]);
return SourceConnector;
}();
function _classCallCheck$c(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$c(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$c(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$c(Constructor.prototype, protoProps); if (staticProps) _defineProperties$c(Constructor, staticProps); return Constructor; }
var TargetConnector = /*#__PURE__*/function () {
function TargetConnector(backend) {
var _this = this;
_classCallCheck$c(this, TargetConnector);
this.hooks = wrapConnectorHooks({
dropTarget: function dropTarget(node, options) {
_this.clearDropTarget();
_this.dropTargetOptions = options;
if (isRef(node)) {
_this.dropTargetRef = node;
} else {
_this.dropTargetNode = node;
}
_this.reconnect();
}
});
this.handlerId = null; // The drop target may either be attached via ref or connect function
this.dropTargetRef = null;
this.dropTargetOptionsInternal = null;
this.lastConnectedHandlerId = null;
this.lastConnectedDropTarget = null;
this.lastConnectedDropTargetOptions = null;
this.backend = backend;
}
_createClass$c(TargetConnector, [{
key: "connectTarget",
get: function get() {
return this.dropTarget;
}
}, {
key: "reconnect",
value: function reconnect() {
// if nothing has changed then don't resubscribe
var didChange = this.didHandlerIdChange() || this.didDropTargetChange() || this.didOptionsChange();
if (didChange) {
this.disconnectDropTarget();
}
var dropTarget = this.dropTarget;
if (!this.handlerId) {
return;
}
if (!dropTarget) {
this.lastConnectedDropTarget = dropTarget;
return;
}
if (didChange) {
this.lastConnectedHandlerId = this.handlerId;
this.lastConnectedDropTarget = dropTarget;
this.lastConnectedDropTargetOptions = this.dropTargetOptions;
this.unsubscribeDropTarget = this.backend.connectDropTarget(this.handlerId, dropTarget, this.dropTargetOptions);
}
}
}, {
key: "receiveHandlerId",
value: function receiveHandlerId(newHandlerId) {
if (newHandlerId === this.handlerId) {
return;
}
this.handlerId = newHandlerId;
this.reconnect();
}
}, {
key: "dropTargetOptions",
get: function get() {
return this.dropTargetOptionsInternal;
},
set: function set(options) {
this.dropTargetOptionsInternal = options;
}
}, {
key: "didHandlerIdChange",
value: function didHandlerIdChange() {
return this.lastConnectedHandlerId !== this.handlerId;
}
}, {
key: "didDropTargetChange",
value: function didDropTargetChange() {
return this.lastConnectedDropTarget !== this.dropTarget;
}
}, {
key: "didOptionsChange",
value: function didOptionsChange() {
return !shallowEqual(this.lastConnectedDropTargetOptions, this.dropTargetOptions);
}
}, {
key: "disconnectDropTarget",
value: function disconnectDropTarget() {
if (this.unsubscribeDropTarget) {
this.unsubscribeDropTarget();
this.unsubscribeDropTarget = undefined;
}
}
}, {
key: "dropTarget",
get: function get() {
return this.dropTargetNode || this.dropTargetRef && this.dropTargetRef.current;
}
}, {
key: "clearDropTarget",
value: function clearDropTarget() {
this.dropTargetRef = null;
this.dropTargetNode = null;
}
}]);
return TargetConnector;
}();
function registerTarget(type, target, manager) {
var registry = manager.getRegistry();
var targetId = registry.addTarget(type, target);
return [targetId, function () {
return registry.removeTarget(targetId);
}];
}
function registerSource(type, source, manager) {
var registry = manager.getRegistry();
var sourceId = registry.addSource(type, source);
return [sourceId, function () {
return registry.removeSource(sourceId);
}];
}
function _typeof$4(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$4 = function _typeof(obj) { return typeof obj; }; } else { _typeof$4 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$4(obj); }
function getDecoratedComponent(instanceRef) {
var currentRef = instanceRef.current;
if (currentRef == null) {
return null;
} else if (currentRef.decoratedRef) {
// go through the private field in decorateHandler to avoid the invariant hit
return currentRef.decoratedRef.current;
} else {
return currentRef;
}
}
function isClassComponent(Component) {
return Component && Component.prototype && typeof Component.prototype.render === 'function';
}
function isRefForwardingComponent(C) {
var _item$$$typeof;
var item = C;
return (item === null || item === void 0 ? void 0 : (_item$$$typeof = item.$$typeof) === null || _item$$$typeof === void 0 ? void 0 : _item$$$typeof.toString()) === 'Symbol(react.forward_ref)';
}
function isRefable(C) {
return isClassComponent(C) || isRefForwardingComponent(C);
}
function checkDecoratorArguments(functionName, signature) {
{
for (var i = 0; i < (arguments.length <= 2 ? 0 : arguments.length - 2); i++) {
var arg = i + 2 < 2 || arguments.length <= i + 2 ? undefined : arguments[i + 2];
if (arg && arg.prototype && arg.prototype.render) {
// eslint-disable-next-line no-console
console.error('You seem to be applying the arguments in the wrong order. ' + "It should be ".concat(functionName, "(").concat(signature, ")(Component), not the other way around. ") + 'Read more: http://react-dnd.github.io/react-dnd/docs/troubleshooting#you-seem-to-be-applying-the-arguments-in-the-wrong-order');
return;
}
}
}
}
function isFunction$1(input) {
return typeof input === 'function';
}
function noop$g() {// noop
}
function isObjectLike(input) {
return _typeof$4(input) === 'object' && input !== null;
}
function isPlainObject(input) {
if (!isObjectLike(input)) {
return false;
}
if (Object.getPrototypeOf(input) === null) {
return true;
}
var proto = input;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(input) === proto;
}
function isValidType(type, allowArray) {
return typeof type === 'string' || _typeof$4(type) === 'symbol' || !!allowArray && Array.isArray(type) && type.every(function (t) {
return isValidType(t, false);
});
}
function _classCallCheck$b(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$b(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$b(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$b(Constructor.prototype, protoProps); if (staticProps) _defineProperties$b(Constructor, staticProps); return Constructor; }
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} action Action to run during the first call to dispose.
* The action is guaranteed to be run at most once.
*/
var Disposable = /*#__PURE__*/function () {
function Disposable(action) {
_classCallCheck$b(this, Disposable);
this.isDisposed = false;
this.action = isFunction$1(action) ? action : noop$g;
}
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
_createClass$b(Disposable, [{
key: "dispose",
value:
/** Performs the task of cleaning up resources. */
function dispose() {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
}
}], [{
key: "isDisposable",
value: function isDisposable(d) {
return Boolean(d && isFunction$1(d.dispose));
}
}, {
key: "_fixup",
value: function _fixup(result) {
return Disposable.isDisposable(result) ? result : Disposable.empty;
}
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose.
* The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
}, {
key: "create",
value: function create(action) {
return new Disposable(action);
}
}]);
return Disposable;
}();
/**
* Gets the disposable that does nothing when disposed.
*/
Disposable.empty = {
dispose: noop$g
};
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = /*#__PURE__*/function () {
function CompositeDisposable() {
_classCallCheck$b(this, CompositeDisposable);
this.isDisposed = false;
for (var _len = arguments.length, disposables = new Array(_len), _key = 0; _key < _len; _key++) {
disposables[_key] = arguments[_key];
}
this.disposables = disposables;
}
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Any} item Disposable to add.
*/
_createClass$b(CompositeDisposable, [{
key: "add",
value: function add(item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
}
}
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Any} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
}, {
key: "remove",
value: function remove(item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
item.dispose();
}
}
return shouldDispose;
}
/**
* Disposes all disposables in the group and removes them from the group but
* does not dispose the CompositeDisposable.
*/
}, {
key: "clear",
value: function clear() {
if (!this.isDisposed) {
var len = this.disposables.length;
var currentDisposables = new Array(len);
for (var i = 0; i < len; i++) {
currentDisposables[i] = this.disposables[i];
}
this.disposables = [];
for (var _i = 0; _i < len; _i++) {
currentDisposables[_i].dispose();
}
}
}
/**
* Disposes all disposables in the group and removes them from the group.
*/
}, {
key: "dispose",
value: function dispose() {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length;
var currentDisposables = new Array(len);
for (var i = 0; i < len; i++) {
currentDisposables[i] = this.disposables[i];
}
this.disposables = [];
for (var _i2 = 0; _i2 < len; _i2++) {
currentDisposables[_i2].dispose();
}
}
}
}]);
return CompositeDisposable;
}();
/**
* Represents a disposable resource whose underlying disposable resource can
* be replaced by another disposable resource, causing automatic disposal of
* the previous underlying disposable resource.
*/
var SerialDisposable = /*#__PURE__*/function () {
function SerialDisposable() {
_classCallCheck$b(this, SerialDisposable);
this.isDisposed = false;
}
/**
* Gets the underlying disposable.
* @returns {Any} the underlying disposable.
*/
_createClass$b(SerialDisposable, [{
key: "getDisposable",
value: function getDisposable() {
return this.current;
}
}, {
key: "setDisposable",
value: function setDisposable(value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
if (old) {
old.dispose();
}
}
if (shouldDispose && value) {
value.dispose();
}
}
/** Performs the task of cleaning up resources. */
}, {
key: "dispose",
value: function dispose() {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = undefined;
if (old) {
old.dispose();
}
}
}
}]);
return SerialDisposable;
}();
/** @license React v16.8.4
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
});
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty$3 = Object.defineProperty;
var getOwnPropertyNames$2 = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor$4 = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames$2(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor$4(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty$3(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
function _typeof$3(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); }
function _slicedToArray$5(arr, i) { return _arrayWithHoles$5(arr) || _iterableToArrayLimit$5(arr, i) || _unsupportedIterableToArray$5(arr, i) || _nonIterableRest$5(); }
function _nonIterableRest$5() { 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$5(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$5(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$5(o, minLen); }
function _arrayLikeToArray$5(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$5(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$5(arr) { if (Array.isArray(arr)) return arr; }
function _classCallCheck$a(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$a(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$a(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$a(Constructor.prototype, protoProps); if (staticProps) _defineProperties$a(Constructor, staticProps); return Constructor; }
function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf$1(subClass, superClass); }
function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); }
function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }
function _possibleConstructorReturn$1(self, call) { if (call && (_typeof$3(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized$2(self); }
function _assertThisInitialized$2(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct$b() { 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; } }
function _getPrototypeOf$1(o) { _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf$1(o); }
function decorateHandler(_ref) {
var DecoratedComponent = _ref.DecoratedComponent,
createHandler = _ref.createHandler,
createMonitor = _ref.createMonitor,
createConnector = _ref.createConnector,
registerHandler = _ref.registerHandler,
containerDisplayName = _ref.containerDisplayName,
getType = _ref.getType,
collect = _ref.collect,
options = _ref.options;
var _options$arePropsEqua = options.arePropsEqual,
arePropsEqual = _options$arePropsEqua === void 0 ? shallowEqual : _options$arePropsEqua;
var Decorated = DecoratedComponent;
var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component';
var DragDropContainer = /*#__PURE__*/function (_Component) {
_inherits$1(DragDropContainer, _Component);
var _super = _createSuper$b(DragDropContainer);
function DragDropContainer(props) {
var _this;
_classCallCheck$a(this, DragDropContainer);
_this = _super.call(this, props);
_this.decoratedRef = React$1.createRef();
_this.handleChange = function () {
var nextState = _this.getCurrentState();
if (!shallowEqual(nextState, _this.state)) {
_this.setState(nextState);
}
};
_this.disposable = new SerialDisposable();
_this.receiveProps(props);
_this.dispose();
return _this;
}
_createClass$a(DragDropContainer, [{
key: "getHandlerId",
value: function getHandlerId() {
return this.handlerId;
}
}, {
key: "getDecoratedComponentInstance",
value: function getDecoratedComponentInstance() {
invariant(this.decoratedRef.current, 'In order to access an instance of the decorated component, it must either be a class component or use React.forwardRef()');
return this.decoratedRef.current;
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
return !arePropsEqual(nextProps, this.props) || !shallowEqual(nextState, this.state);
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.disposable = new SerialDisposable();
this.currentType = undefined;
this.receiveProps(this.props);
this.handleChange();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!arePropsEqual(this.props, prevProps)) {
this.receiveProps(this.props);
this.handleChange();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.dispose();
}
}, {
key: "receiveProps",
value: function receiveProps(props) {
if (!this.handler) {
return;
}
this.handler.receiveProps(props);
this.receiveType(getType(props));
}
}, {
key: "receiveType",
value: function receiveType(type) {
if (!this.handlerMonitor || !this.manager || !this.handlerConnector) {
return;
}
if (type === this.currentType) {
return;
}
this.currentType = type;
var _registerHandler = registerHandler(type, this.handler, this.manager),
_registerHandler2 = _slicedToArray$5(_registerHandler, 2),
handlerId = _registerHandler2[0],
unregister = _registerHandler2[1];
this.handlerId = handlerId;
this.handlerMonitor.receiveHandlerId(handlerId);
this.handlerConnector.receiveHandlerId(handlerId);
var globalMonitor = this.manager.getMonitor();
var unsubscribe = globalMonitor.subscribeToStateChange(this.handleChange, {
handlerIds: [handlerId]
});
this.disposable.setDisposable(new CompositeDisposable(new Disposable(unsubscribe), new Disposable(unregister)));
}
}, {
key: "dispose",
value: function dispose() {
this.disposable.dispose();
if (this.handlerConnector) {
this.handlerConnector.receiveHandlerId(null);
}
}
}, {
key: "getCurrentState",
value: function getCurrentState() {
if (!this.handlerConnector) {
return {};
}
var nextState = collect(this.handlerConnector.hooks, this.handlerMonitor, this.props);
{
invariant(isPlainObject(nextState), 'Expected `collect` specified as the second argument to ' + '%s for %s to return a plain object of props to inject. ' + 'Instead, received %s.', containerDisplayName, displayName, nextState);
}
return nextState;
}
}, {
key: "render",
value: function render() {
var _this2 = this;
return jsxRuntime.jsx(DndContext.Consumer, {
children: function children(_ref2) {
var dragDropManager = _ref2.dragDropManager;
_this2.receiveDragDropManager(dragDropManager);
if (typeof requestAnimationFrame !== 'undefined') {
requestAnimationFrame(function () {
var _this2$handlerConnect;
return (_this2$handlerConnect = _this2.handlerConnector) === null || _this2$handlerConnect === void 0 ? void 0 : _this2$handlerConnect.reconnect();
});
}
return jsxRuntime.jsx(Decorated, Object.assign({}, _this2.props, _this2.getCurrentState(), {
// NOTE: if Decorated is a Function Component, decoratedRef will not be populated unless it's a refforwarding component.
ref: isRefable(Decorated) ? _this2.decoratedRef : null
}), void 0);
}
}, void 0);
}
}, {
key: "receiveDragDropManager",
value: function receiveDragDropManager(dragDropManager) {
if (this.manager !== undefined) {
return;
}
invariant(dragDropManager !== undefined, 'Could not find the drag and drop manager in the context of %s. ' + 'Make sure to render a DndProvider component in your top-level component. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/troubleshooting#could-not-find-the-drag-and-drop-manager-in-the-context', displayName, displayName);
if (dragDropManager === undefined) {
return;
}
this.manager = dragDropManager;
this.handlerMonitor = createMonitor(dragDropManager);
this.handlerConnector = createConnector(dragDropManager.getBackend());
this.handler = createHandler(this.handlerMonitor, this.decoratedRef);
}
}]);
return DragDropContainer;
}(React$1.Component);
DragDropContainer.DecoratedComponent = DecoratedComponent;
DragDropContainer.displayName = "".concat(containerDisplayName, "(").concat(displayName, ")");
return hoistNonReactStatics_cjs(DragDropContainer, DecoratedComponent);
}
function _classCallCheck$9(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$9(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$9(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$9(Constructor.prototype, protoProps); if (staticProps) _defineProperties$9(Constructor, staticProps); return Constructor; }
var ALLOWED_SPEC_METHODS$1 = ['canDrag', 'beginDrag', 'isDragging', 'endDrag'];
var REQUIRED_SPEC_METHODS = ['beginDrag'];
var SourceImpl = /*#__PURE__*/function () {
function SourceImpl(spec, monitor, ref) {
var _this = this;
_classCallCheck$9(this, SourceImpl);
this.props = null;
this.beginDrag = function () {
if (!_this.props) {
return;
}
var item = _this.spec.beginDrag(_this.props, _this.monitor, _this.ref.current);
{
invariant(isPlainObject(item), 'beginDrag() must return a plain object that represents the dragged item. ' + 'Instead received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', item);
}
return item;
};
this.spec = spec;
this.monitor = monitor;
this.ref = ref;
}
_createClass$9(SourceImpl, [{
key: "receiveProps",
value: function receiveProps(props) {
this.props = props;
}
}, {
key: "canDrag",
value: function canDrag() {
if (!this.props) {
return false;
}
if (!this.spec.canDrag) {
return true;
}
return this.spec.canDrag(this.props, this.monitor);
}
}, {
key: "isDragging",
value: function isDragging(globalMonitor, sourceId) {
if (!this.props) {
return false;
}
if (!this.spec.isDragging) {
return sourceId === globalMonitor.getSourceId();
}
return this.spec.isDragging(this.props, this.monitor);
}
}, {
key: "endDrag",
value: function endDrag() {
if (!this.props) {
return;
}
if (!this.spec.endDrag) {
return;
}
this.spec.endDrag(this.props, this.monitor, getDecoratedComponent(this.ref));
}
}]);
return SourceImpl;
}();
function createSourceFactory(spec) {
Object.keys(spec).forEach(function (key) {
invariant(ALLOWED_SPEC_METHODS$1.indexOf(key) > -1, 'Expected the drag source specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', ALLOWED_SPEC_METHODS$1.join(', '), key);
invariant(typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', key, key, spec[key]);
});
REQUIRED_SPEC_METHODS.forEach(function (key) {
invariant(typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', key, key, spec[key]);
});
return function createSource(monitor, ref) {
return new SourceImpl(spec, monitor, ref);
};
}
/**
* Decorates a component as a dragsource
* @param type The dragsource type
* @param spec The drag source specification
* @param collect The props collector function
* @param options DnD options
*/
function DragSource(type, spec, collect) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
checkDecoratorArguments('DragSource', 'type, spec, collect[, options]', type, spec, collect, options);
var getType = type;
if (typeof type !== 'function') {
invariant(isValidType(type), 'Expected "type" provided as the first argument to DragSource to be ' + 'a string, or a function that returns a string given the current props. ' + 'Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', type);
getType = function getType() {
return type;
};
}
invariant(isPlainObject(spec), 'Expected "spec" provided as the second argument to DragSource to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', spec);
var createSource = createSourceFactory(spec);
invariant(typeof collect === 'function', 'Expected "collect" provided as the third argument to DragSource to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', collect);
invariant(isPlainObject(options), 'Expected "options" provided as the fourth argument to DragSource to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source', collect);
return function decorateSource(DecoratedComponent) {
return decorateHandler({
containerDisplayName: 'DragSource',
createHandler: createSource,
registerHandler: registerSource,
createConnector: function createConnector(backend) {
return new SourceConnector(backend);
},
createMonitor: function createMonitor(manager) {
return new DragSourceMonitorImpl(manager);
},
DecoratedComponent: DecoratedComponent,
getType: getType,
collect: collect,
options: options
});
};
}
function _classCallCheck$8(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$8(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$8(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$8(Constructor.prototype, protoProps); if (staticProps) _defineProperties$8(Constructor, staticProps); return Constructor; }
var ALLOWED_SPEC_METHODS = ['canDrop', 'hover', 'drop'];
var TargetImpl = /*#__PURE__*/function () {
function TargetImpl(spec, monitor, ref) {
_classCallCheck$8(this, TargetImpl);
this.props = null;
this.spec = spec;
this.monitor = monitor;
this.ref = ref;
}
_createClass$8(TargetImpl, [{
key: "receiveProps",
value: function receiveProps(props) {
this.props = props;
}
}, {
key: "receiveMonitor",
value: function receiveMonitor(monitor) {
this.monitor = monitor;
}
}, {
key: "canDrop",
value: function canDrop() {
if (!this.spec.canDrop) {
return true;
}
return this.spec.canDrop(this.props, this.monitor);
}
}, {
key: "hover",
value: function hover() {
if (!this.spec.hover || !this.props) {
return;
}
this.spec.hover(this.props, this.monitor, getDecoratedComponent(this.ref));
}
}, {
key: "drop",
value: function drop() {
if (!this.spec.drop) {
return undefined;
}
var dropResult = this.spec.drop(this.props, this.monitor, this.ref.current);
{
invariant(typeof dropResult === 'undefined' || isPlainObject(dropResult), 'drop() must either return undefined, or an object that represents the drop result. ' + 'Instead received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', dropResult);
}
return dropResult;
}
}]);
return TargetImpl;
}();
function createTargetFactory(spec) {
Object.keys(spec).forEach(function (key) {
invariant(ALLOWED_SPEC_METHODS.indexOf(key) > -1, 'Expected the drop target specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', ALLOWED_SPEC_METHODS.join(', '), key);
invariant(typeof spec[key] === 'function', 'Expected %s in the drop target specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', key, key, spec[key]);
});
return function createTarget(monitor, ref) {
return new TargetImpl(spec, monitor, ref);
};
}
/**
* @param type The accepted target type
* @param spec The DropTarget specification
* @param collect The props collector function
* @param options Options
*/
function DropTarget(type, spec, collect) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
checkDecoratorArguments('DropTarget', 'type, spec, collect[, options]', type, spec, collect, options);
var getType = type;
if (typeof type !== 'function') {
invariant(isValidType(type, true), 'Expected "type" provided as the first argument to DropTarget to be ' + 'a string, an array of strings, or a function that returns either given ' + 'the current props. Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', type);
getType = function getType() {
return type;
};
}
invariant(isPlainObject(spec), 'Expected "spec" provided as the second argument to DropTarget to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', spec);
var createTarget = createTargetFactory(spec);
invariant(typeof collect === 'function', 'Expected "collect" provided as the third argument to DropTarget to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', collect);
invariant(isPlainObject(options), 'Expected "options" provided as the fourth argument to DropTarget to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target', collect);
return function decorateTarget(DecoratedComponent) {
return decorateHandler({
containerDisplayName: 'DropTarget',
createHandler: createTarget,
registerHandler: registerTarget,
createMonitor: function createMonitor(manager) {
return new DropTargetMonitorImpl(manager);
},
createConnector: function createConnector(backend) {
return new TargetConnector(backend);
},
DecoratedComponent: DecoratedComponent,
getType: getType,
collect: collect,
options: options
});
};
}
var useIsomorphicLayoutEffect$1 = typeof window !== 'undefined' ? React$1.useLayoutEffect : React$1.useEffect;
function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
function _classCallCheck$7(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$7(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$7(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$7(Constructor.prototype, protoProps); if (staticProps) _defineProperties$7(Constructor, staticProps); return Constructor; }
var DragSourceImpl = /*#__PURE__*/function () {
function DragSourceImpl(spec, monitor, connector) {
_classCallCheck$7(this, DragSourceImpl);
this.spec = spec;
this.monitor = monitor;
this.connector = connector;
}
_createClass$7(DragSourceImpl, [{
key: "beginDrag",
value: function beginDrag() {
var _result;
var spec = this.spec;
var monitor = this.monitor;
var result = null;
if (_typeof$2(spec.item) === 'object') {
result = spec.item;
} else if (typeof spec.item === 'function') {
result = spec.item(monitor);
} else {
result = {};
}
return (_result = result) !== null && _result !== void 0 ? _result : null;
}
}, {
key: "canDrag",
value: function canDrag() {
var spec = this.spec;
var monitor = this.monitor;
if (typeof spec.canDrag === 'boolean') {
return spec.canDrag;
} else if (typeof spec.canDrag === 'function') {
return spec.canDrag(monitor);
} else {
return true;
}
}
}, {
key: "isDragging",
value: function isDragging(globalMonitor, target) {
var spec = this.spec;
var monitor = this.monitor;
var isDragging = spec.isDragging;
return isDragging ? isDragging(monitor) : target === globalMonitor.getSourceId();
}
}, {
key: "endDrag",
value: function endDrag() {
var spec = this.spec;
var monitor = this.monitor;
var connector = this.connector;
var end = spec.end;
if (end) {
end(monitor.getItem(), monitor);
}
connector.reconnect();
}
}]);
return DragSourceImpl;
}();
function useDragSource(spec, monitor, connector) {
var handler = React$1.useMemo(function () {
return new DragSourceImpl(spec, monitor, connector);
}, [monitor, connector]);
React$1.useEffect(function () {
handler.spec = spec;
}, [spec]);
return handler;
}
/**
* A hook to retrieve the DragDropManager from Context
*/
function useDragDropManager() {
var _useContext = React$1.useContext(DndContext),
dragDropManager = _useContext.dragDropManager;
invariant(dragDropManager != null, 'Expected drag drop context');
return dragDropManager;
}
function useDragType(spec) {
return React$1.useMemo(function () {
var result = spec.type;
invariant(result != null, 'spec.type must be defined');
return result;
}, [spec]);
}
function _slicedToArray$4(arr, i) { return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i) || _unsupportedIterableToArray$4(arr, i) || _nonIterableRest$4(); }
function _nonIterableRest$4() { 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$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(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$4(o, minLen); }
function _arrayLikeToArray$4(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$4(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$4(arr) { if (Array.isArray(arr)) return arr; }
function useRegisteredDragSource(spec, monitor, connector) {
var manager = useDragDropManager();
var handler = useDragSource(spec, monitor, connector);
var itemType = useDragType(spec);
useIsomorphicLayoutEffect$1(function registerDragSource() {
if (itemType != null) {
var _registerSource = registerSource(itemType, handler, manager),
_registerSource2 = _slicedToArray$4(_registerSource, 2),
handlerId = _registerSource2[0],
unregister = _registerSource2[1];
monitor.receiveHandlerId(handlerId);
connector.receiveHandlerId(handlerId);
return unregister;
}
}, [manager, monitor, connector, handler, itemType]);
}
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$3(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(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$3(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$3(arr); }
function _arrayLikeToArray$3(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 useOptionalFactory(arg, deps) {
var memoDeps = _toConsumableArray(deps || []);
if (deps == null && typeof arg !== 'function') {
memoDeps.push(arg);
}
return React$1.useMemo(function () {
return typeof arg === 'function' ? arg() : arg;
}, memoDeps);
}
function useDragSourceMonitor() {
var manager = useDragDropManager();
return React$1.useMemo(function () {
return new DragSourceMonitorImpl(manager);
}, [manager]);
}
function useDragSourceConnector(dragSourceOptions, dragPreviewOptions) {
var manager = useDragDropManager();
var connector = React$1.useMemo(function () {
return new SourceConnector(manager.getBackend());
}, [manager]);
useIsomorphicLayoutEffect$1(function () {
connector.dragSourceOptions = dragSourceOptions || null;
connector.reconnect();
}, [connector, dragSourceOptions]);
useIsomorphicLayoutEffect$1(function () {
connector.dragPreviewOptions = dragPreviewOptions || null;
connector.reconnect();
}, [connector, dragPreviewOptions]);
return connector;
}
// do not edit .js files directly - edit src/index.jst
var fastDeepEqual = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
function _slicedToArray$3(arr, i) { return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$3(); }
function _nonIterableRest$3() { 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$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(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$2(o, minLen); }
function _arrayLikeToArray$2(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$3(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$3(arr) { if (Array.isArray(arr)) return arr; }
/**
*
* @param monitor The monitor to collect state from
* @param collect The collecting function
* @param onUpdate A method to invoke when updates occur
*/
function useCollector(monitor, collect, onUpdate) {
var _useState = React$1.useState(function () {
return collect(monitor);
}),
_useState2 = _slicedToArray$3(_useState, 2),
collected = _useState2[0],
setCollected = _useState2[1];
var updateCollected = React$1.useCallback(function () {
var nextValue = collect(monitor); // This needs to be a deep-equality check because some monitor-collected values
// include XYCoord objects that may be equivalent, but do not have instance equality.
if (!fastDeepEqual(collected, nextValue)) {
setCollected(nextValue);
if (onUpdate) {
onUpdate();
}
}
}, [collected, monitor, onUpdate]); // update the collected properties after react renders.
// Note that the "Dustbin Stress Test" fails if this is not
// done when the component updates
useIsomorphicLayoutEffect$1(updateCollected);
return [collected, updateCollected];
}
function _slicedToArray$2(arr, i) { return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$2(); }
function _nonIterableRest$2() { 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$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(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$1(o, minLen); }
function _arrayLikeToArray$1(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$2(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$2(arr) { if (Array.isArray(arr)) return arr; }
function useMonitorOutput(monitor, collect, onCollect) {
var _useCollector = useCollector(monitor, collect, onCollect),
_useCollector2 = _slicedToArray$2(_useCollector, 2),
collected = _useCollector2[0],
updateCollected = _useCollector2[1];
useIsomorphicLayoutEffect$1(function subscribeToMonitorStateChange() {
var handlerId = monitor.getHandlerId();
if (handlerId == null) {
return;
}
return monitor.subscribeToStateChange(updateCollected, {
handlerIds: [handlerId]
});
}, [monitor, updateCollected]);
return collected;
}
function useCollectedProps(collector, monitor, connector) {
return useMonitorOutput(monitor, collector || function () {
return {};
}, function () {
return connector.reconnect();
});
}
function useConnectDragSource(connector) {
return React$1.useMemo(function () {
return connector.hooks.dragSource();
}, [connector]);
}
function useConnectDragPreview(connector) {
return React$1.useMemo(function () {
return connector.hooks.dragPreview();
}, [connector]);
}
/**
* useDragSource hook
* @param sourceSpec The drag source specification (object or function, function preferred)
* @param deps The memoization deps array to use when evaluating spec changes
*/
function useDrag(specArg, deps) {
var spec = useOptionalFactory(specArg, deps);
invariant(!spec.begin, "useDrag::spec.begin was deprecated in v14. Replace spec.begin() with spec.item(). (see more here - https://react-dnd.github.io/react-dnd/docs/api/use-drag)");
var monitor = useDragSourceMonitor();
var connector = useDragSourceConnector(spec.options, spec.previewOptions);
useRegisteredDragSource(spec, monitor, connector);
return [useCollectedProps(spec.collect, monitor, connector), useConnectDragSource(connector), useConnectDragPreview(connector)];
}
/**
* Internal utility hook to get an array-version of spec.accept.
* The main utility here is that we aren't creating a new array on every render if a non-array spec.accept is passed in.
* @param spec
*/
function useAccept(spec) {
var accept = spec.accept;
return React$1.useMemo(function () {
invariant(spec.accept != null, 'accept must be defined');
return Array.isArray(accept) ? accept : [accept];
}, [accept]);
}
function _classCallCheck$6(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$6(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$6(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$6(Constructor.prototype, protoProps); if (staticProps) _defineProperties$6(Constructor, staticProps); return Constructor; }
var DropTargetImpl = /*#__PURE__*/function () {
function DropTargetImpl(spec, monitor) {
_classCallCheck$6(this, DropTargetImpl);
this.spec = spec;
this.monitor = monitor;
}
_createClass$6(DropTargetImpl, [{
key: "canDrop",
value: function canDrop() {
var spec = this.spec;
var monitor = this.monitor;
return spec.canDrop ? spec.canDrop(monitor.getItem(), monitor) : true;
}
}, {
key: "hover",
value: function hover() {
var spec = this.spec;
var monitor = this.monitor;
if (spec.hover) {
spec.hover(monitor.getItem(), monitor);
}
}
}, {
key: "drop",
value: function drop() {
var spec = this.spec;
var monitor = this.monitor;
if (spec.drop) {
return spec.drop(monitor.getItem(), monitor);
}
}
}]);
return DropTargetImpl;
}();
function useDropTarget(spec, monitor) {
var dropTarget = React$1.useMemo(function () {
return new DropTargetImpl(spec, monitor);
}, [monitor]);
React$1.useEffect(function () {
dropTarget.spec = spec;
}, [spec]);
return dropTarget;
}
function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest$1(); }
function _nonIterableRest$1() { 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$1(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; }
function useRegisteredDropTarget(spec, monitor, connector) {
var manager = useDragDropManager();
var dropTarget = useDropTarget(spec, monitor);
var accept = useAccept(spec);
useIsomorphicLayoutEffect$1(function registerDropTarget() {
var _registerTarget = registerTarget(accept, dropTarget, manager),
_registerTarget2 = _slicedToArray$1(_registerTarget, 2),
handlerId = _registerTarget2[0],
unregister = _registerTarget2[1];
monitor.receiveHandlerId(handlerId);
connector.receiveHandlerId(handlerId);
return unregister;
}, [manager, monitor, dropTarget, connector, accept.map(function (a) {
return a.toString();
}).join('|')]);
}
function useDropTargetMonitor() {
var manager = useDragDropManager();
return React$1.useMemo(function () {
return new DropTargetMonitorImpl(manager);
}, [manager]);
}
function useDropTargetConnector(options) {
var manager = useDragDropManager();
var connector = React$1.useMemo(function () {
return new TargetConnector(manager.getBackend());
}, [manager]);
useIsomorphicLayoutEffect$1(function () {
connector.dropTargetOptions = options || null;
connector.reconnect();
}, [options]);
return connector;
}
function useConnectDropTarget(connector) {
return React$1.useMemo(function () {
return connector.hooks.dropTarget();
}, [connector]);
}
/**
* useDropTarget Hook
* @param spec The drop target specification (object or function, function preferred)
* @param deps The memoization deps array to use when evaluating spec changes
*/
function useDrop(specArg, deps) {
var spec = useOptionalFactory(specArg, deps);
var monitor = useDropTargetMonitor();
var connector = useDropTargetConnector(spec.options);
useRegisteredDropTarget(spec, monitor, connector);
return [useCollectedProps(spec.collect, monitor, connector), useConnectDropTarget(connector)];
}
var iotPrefix$2j = settings$1.iotPrefix;
var ColumnHeaderSelect = function ColumnHeaderSelect(_ref) {
var connectDragSource = _ref.connectDragSource,
connectDropTarget = _ref.connectDropTarget,
columnId = _ref.columnId,
isHidden = _ref.isHidden,
children = _ref.children,
_onClick = _ref.onClick,
isOver = _ref.isOver,
isDisabled = _ref.isDisabled;
return /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: classnames$1('column-header__btn', "".concat(iotPrefix$2j, "--column-header"), 'column-header__select', {
'column-header__select--hidden': isHidden,
'column-header__select--isOver': isOver
}),
disabled: isDisabled,
kind: "secondary",
key: columnId,
onClick: function onClick() {
return _onClick();
},
role: "button",
"data-ishidden": isHidden,
renderIcon: iconsReact.Draggable16,
size: "small",
ref: function ref(instance) {
if (!isDisabled) {
connectDragSource(instance);
connectDropTarget(instance);
}
}
}, children);
};
ColumnHeaderSelect.propTypes = {
columnId: PropTypes__default['default'].string.isRequired,
isHidden: PropTypes__default['default'].bool,
children: PropTypes__default['default'].oneOfType([PropTypes__default['default'].array, PropTypes__default['default'].node]),
onClick: PropTypes__default['default'].func.isRequired,
connectDragSource: PropTypes__default['default'].func.isRequired,
connectDropTarget: PropTypes__default['default'].func.isRequired,
isDisabled: PropTypes__default['default'].bool,
/* these props come from react-dnd */
index: PropTypes__default['default'].number.isRequired,
// eslint-disable-line react/no-unused-prop-types
isOver: PropTypes__default['default'].bool.isRequired,
// eslint-disable-line react/no-unused-prop-types
moveItem: PropTypes__default['default'].func.isRequired // eslint-disable-line react/no-unused-prop-types
};
ColumnHeaderSelect.defaultProps = {
isHidden: false,
isDisabled: false,
children: []
};
var cardSource = {
/**
* Implements the drag source contract.
*/
beginDrag: function beginDrag(props) {
return {
id: props.columnId,
index: props.index
};
}
};
var cardTarget = {
drop: function drop(props, monitor) {
var dragIndex = monitor.getItem().index;
var hoverIndex = props.index; // Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
props.moveItem(dragIndex, hoverIndex);
monitor.getItem().index = hoverIndex; // eslint-disable-line no-param-reassign
}
};
var ds$1 = DragSource('ColumnHeaderSelect', cardSource, function (connect) {
return {
connectDragSource: connect.dragSource()
};
});
var dt$1 = DropTarget('ColumnHeaderSelect', cardTarget, function (connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
};
});
ColumnHeaderSelect.displayName = 'ColumnHeaderSelect';
ColumnHeaderSelect.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ColumnHeaderSelect",
"props": {
"isHidden": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"isDisabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"children": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "array"
}, {
"name": "node"
}]
},
"required": false,
"description": ""
},
"columnId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"onClick": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"connectDragSource": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"connectDropTarget": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"index": {
"type": {
"name": "number"
},
"required": true,
"description": ""
},
"isOver": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"moveItem": {
"type": {
"name": "func"
},
"required": true,
"description": ""
}
}
};
var ColumnHeaderSelect$1 = ds$1(dt$1(ColumnHeaderSelect));
// cheap lodash replacements
function memoize(fn) {
var result = null;
var memoized = function memoized() {
if (result == null) {
result = fn();
}
return result;
};
return memoized;
}
/**
* drop-in replacement for _.without
*/
function without(items, item) {
return items.filter(function (i) {
return i !== item;
});
}
function union(itemsA, itemsB) {
var set = new Set();
var insertItem = function insertItem(item) {
return set.add(item);
};
itemsA.forEach(insertItem);
itemsB.forEach(insertItem);
var result = [];
set.forEach(function (key) {
return result.push(key);
});
return result;
}
function _classCallCheck$5(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$5(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$5(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$5(Constructor.prototype, protoProps); if (staticProps) _defineProperties$5(Constructor, staticProps); return Constructor; }
var EnterLeaveCounter = /*#__PURE__*/function () {
function EnterLeaveCounter(isNodeInDocument) {
_classCallCheck$5(this, EnterLeaveCounter);
this.entered = [];
this.isNodeInDocument = isNodeInDocument;
}
_createClass$5(EnterLeaveCounter, [{
key: "enter",
value: function enter(enteringNode) {
var _this = this;
var previousLength = this.entered.length;
var isNodeEntered = function isNodeEntered(node) {
return _this.isNodeInDocument(node) && (!node.contains || node.contains(enteringNode));
};
this.entered = union(this.entered.filter(isNodeEntered), [enteringNode]);
return previousLength === 0 && this.entered.length > 0;
}
}, {
key: "leave",
value: function leave(leavingNode) {
var previousLength = this.entered.length;
this.entered = without(this.entered.filter(this.isNodeInDocument), leavingNode);
return previousLength > 0 && this.entered.length === 0;
}
}, {
key: "reset",
value: function reset() {
this.entered = [];
}
}]);
return EnterLeaveCounter;
}();
var isFirefox = memoize(function () {
return /firefox/i.test(navigator.userAgent);
});
var isSafari$1 = memoize(function () {
return Boolean(window.safari);
});
function _classCallCheck$4(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$4(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$4(Constructor.prototype, protoProps); if (staticProps) _defineProperties$4(Constructor, staticProps); return Constructor; }
var MonotonicInterpolant = /*#__PURE__*/function () {
function MonotonicInterpolant(xs, ys) {
_classCallCheck$4(this, MonotonicInterpolant);
var length = xs.length; // Rearrange xs and ys so that xs is sorted
var indexes = [];
for (var i = 0; i < length; i++) {
indexes.push(i);
}
indexes.sort(function (a, b) {
return xs[a] < xs[b] ? -1 : 1;
}); // Get consecutive differences and slopes
var dxs = [];
var ms = [];
var dx;
var dy;
for (var _i = 0; _i < length - 1; _i++) {
dx = xs[_i + 1] - xs[_i];
dy = ys[_i + 1] - ys[_i];
dxs.push(dx);
ms.push(dy / dx);
} // Get degree-1 coefficients
var c1s = [ms[0]];
for (var _i2 = 0; _i2 < dxs.length - 1; _i2++) {
var m2 = ms[_i2];
var mNext = ms[_i2 + 1];
if (m2 * mNext <= 0) {
c1s.push(0);
} else {
dx = dxs[_i2];
var dxNext = dxs[_i2 + 1];
var common = dx + dxNext;
c1s.push(3 * common / ((common + dxNext) / m2 + (common + dx) / mNext));
}
}
c1s.push(ms[ms.length - 1]); // Get degree-2 and degree-3 coefficients
var c2s = [];
var c3s = [];
var m;
for (var _i3 = 0; _i3 < c1s.length - 1; _i3++) {
m = ms[_i3];
var c1 = c1s[_i3];
var invDx = 1 / dxs[_i3];
var _common = c1 + c1s[_i3 + 1] - m - m;
c2s.push((m - c1 - _common) * invDx);
c3s.push(_common * invDx * invDx);
}
this.xs = xs;
this.ys = ys;
this.c1s = c1s;
this.c2s = c2s;
this.c3s = c3s;
}
_createClass$4(MonotonicInterpolant, [{
key: "interpolate",
value: function interpolate(x) {
var xs = this.xs,
ys = this.ys,
c1s = this.c1s,
c2s = this.c2s,
c3s = this.c3s; // The rightmost point in the dataset should give an exact result
var i = xs.length - 1;
if (x === xs[i]) {
return ys[i];
} // Search for the interval x is in, returning the corresponding y if x is one of the original xs
var low = 0;
var high = c3s.length - 1;
var mid;
while (low <= high) {
mid = Math.floor(0.5 * (low + high));
var xHere = xs[mid];
if (xHere < x) {
low = mid + 1;
} else if (xHere > x) {
high = mid - 1;
} else {
return ys[mid];
}
}
i = Math.max(0, high); // Interpolate
var diff = x - xs[i];
var diffSq = diff * diff;
return ys[i] + c1s[i] * diff + c2s[i] * diffSq + c3s[i] * diff * diffSq;
}
}]);
return MonotonicInterpolant;
}();
var ELEMENT_NODE = 1;
function getNodeClientOffset(node) {
var el = node.nodeType === ELEMENT_NODE ? node : node.parentElement;
if (!el) {
return null;
}
var _el$getBoundingClient = el.getBoundingClientRect(),
top = _el$getBoundingClient.top,
left = _el$getBoundingClient.left;
return {
x: left,
y: top
};
}
function getEventClientOffset(e) {
return {
x: e.clientX,
y: e.clientY
};
}
function isImageNode(node) {
var _document$documentEle;
return node.nodeName === 'IMG' && (isFirefox() || !((_document$documentEle = document.documentElement) !== null && _document$documentEle !== void 0 && _document$documentEle.contains(node)));
}
function getDragPreviewSize(isImage, dragPreview, sourceWidth, sourceHeight) {
var dragPreviewWidth = isImage ? dragPreview.width : sourceWidth;
var dragPreviewHeight = isImage ? dragPreview.height : sourceHeight; // Work around @2x coordinate discrepancies in browsers
if (isSafari$1() && isImage) {
dragPreviewHeight /= window.devicePixelRatio;
dragPreviewWidth /= window.devicePixelRatio;
}
return {
dragPreviewWidth: dragPreviewWidth,
dragPreviewHeight: dragPreviewHeight
};
}
function getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint, offsetPoint) {
// The browsers will use the image intrinsic size under different conditions.
// Firefox only cares if it's an image, but WebKit also wants it to be detached.
var isImage = isImageNode(dragPreview);
var dragPreviewNode = isImage ? sourceNode : dragPreview;
var dragPreviewNodeOffsetFromClient = getNodeClientOffset(dragPreviewNode);
var offsetFromDragPreview = {
x: clientOffset.x - dragPreviewNodeOffsetFromClient.x,
y: clientOffset.y - dragPreviewNodeOffsetFromClient.y
};
var sourceWidth = sourceNode.offsetWidth,
sourceHeight = sourceNode.offsetHeight;
var anchorX = anchorPoint.anchorX,
anchorY = anchorPoint.anchorY;
var _getDragPreviewSize = getDragPreviewSize(isImage, dragPreview, sourceWidth, sourceHeight),
dragPreviewWidth = _getDragPreviewSize.dragPreviewWidth,
dragPreviewHeight = _getDragPreviewSize.dragPreviewHeight;
var calculateYOffset = function calculateYOffset() {
var interpolantY = new MonotonicInterpolant([0, 0.5, 1], [// Dock to the top
offsetFromDragPreview.y, // Align at the center
offsetFromDragPreview.y / sourceHeight * dragPreviewHeight, // Dock to the bottom
offsetFromDragPreview.y + dragPreviewHeight - sourceHeight]);
var y = interpolantY.interpolate(anchorY); // Work around Safari 8 positioning bug
if (isSafari$1() && isImage) {
// We'll have to wait for @3x to see if this is entirely correct
y += (window.devicePixelRatio - 1) * dragPreviewHeight;
}
return y;
};
var calculateXOffset = function calculateXOffset() {
// Interpolate coordinates depending on anchor point
// If you know a simpler way to do this, let me know
var interpolantX = new MonotonicInterpolant([0, 0.5, 1], [// Dock to the left
offsetFromDragPreview.x, // Align at the center
offsetFromDragPreview.x / sourceWidth * dragPreviewWidth, // Dock to the right
offsetFromDragPreview.x + dragPreviewWidth - sourceWidth]);
return interpolantX.interpolate(anchorX);
}; // Force offsets if specified in the options.
var offsetX = offsetPoint.offsetX,
offsetY = offsetPoint.offsetY;
var isManualOffsetX = offsetX === 0 || offsetX;
var isManualOffsetY = offsetY === 0 || offsetY;
return {
x: isManualOffsetX ? offsetX : calculateXOffset(),
y: isManualOffsetY ? offsetY : calculateYOffset()
};
}
var FILE$1 = '__NATIVE_FILE__';
var URL$1 = '__NATIVE_URL__';
var TEXT = '__NATIVE_TEXT__';
var HTML = '__NATIVE_HTML__';
var NativeTypes = /*#__PURE__*/Object.freeze({
__proto__: null,
FILE: FILE$1,
URL: URL$1,
TEXT: TEXT,
HTML: HTML
});
function getDataFromDataTransfer(dataTransfer, typesToTry, defaultValue) {
var result = typesToTry.reduce(function (resultSoFar, typeToTry) {
return resultSoFar || dataTransfer.getData(typeToTry);
}, '');
return result != null ? result : defaultValue;
}
var _nativeTypesConfig;
function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var nativeTypesConfig = (_nativeTypesConfig = {}, _defineProperty$4(_nativeTypesConfig, FILE$1, {
exposeProperties: {
files: function files(dataTransfer) {
return Array.prototype.slice.call(dataTransfer.files);
},
items: function items(dataTransfer) {
return dataTransfer.items;
}
},
matchesTypes: ['Files']
}), _defineProperty$4(_nativeTypesConfig, HTML, {
exposeProperties: {
html: function html(dataTransfer, matchesTypes) {
return getDataFromDataTransfer(dataTransfer, matchesTypes, '');
}
},
matchesTypes: ['Html', 'text/html']
}), _defineProperty$4(_nativeTypesConfig, URL$1, {
exposeProperties: {
urls: function urls(dataTransfer, matchesTypes) {
return getDataFromDataTransfer(dataTransfer, matchesTypes, '').split('\n');
}
},
matchesTypes: ['Url', 'text/uri-list']
}), _defineProperty$4(_nativeTypesConfig, TEXT, {
exposeProperties: {
text: function text(dataTransfer, matchesTypes) {
return getDataFromDataTransfer(dataTransfer, matchesTypes, '');
}
},
matchesTypes: ['Text', 'text/plain']
}), _nativeTypesConfig);
function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$3(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); return Constructor; }
var NativeDragSource = /*#__PURE__*/function () {
function NativeDragSource(config) {
_classCallCheck$3(this, NativeDragSource);
this.config = config;
this.item = {};
this.initializeExposedProperties();
}
_createClass$3(NativeDragSource, [{
key: "initializeExposedProperties",
value: function initializeExposedProperties() {
var _this = this;
Object.keys(this.config.exposeProperties).forEach(function (property) {
Object.defineProperty(_this.item, property, {
configurable: true,
enumerable: true,
get: function get() {
// eslint-disable-next-line no-console
console.warn("Browser doesn't allow reading \"".concat(property, "\" until the drop event."));
return null;
}
});
});
}
}, {
key: "loadDataTransfer",
value: function loadDataTransfer(dataTransfer) {
var _this2 = this;
if (dataTransfer) {
var newProperties = {};
Object.keys(this.config.exposeProperties).forEach(function (property) {
newProperties[property] = {
value: _this2.config.exposeProperties[property](dataTransfer, _this2.config.matchesTypes),
configurable: true,
enumerable: true
};
});
Object.defineProperties(this.item, newProperties);
}
}
}, {
key: "canDrag",
value: function canDrag() {
return true;
}
}, {
key: "beginDrag",
value: function beginDrag() {
return this.item;
}
}, {
key: "isDragging",
value: function isDragging(monitor, handle) {
return handle === monitor.getSourceId();
}
}, {
key: "endDrag",
value: function endDrag() {// empty
}
}]);
return NativeDragSource;
}();
function createNativeDragSource(type, dataTransfer) {
var result = new NativeDragSource(nativeTypesConfig[type]);
result.loadDataTransfer(dataTransfer);
return result;
}
function matchNativeItemType(dataTransfer) {
if (!dataTransfer) {
return null;
}
var dataTransferTypes = Array.prototype.slice.call(dataTransfer.types || []);
return Object.keys(nativeTypesConfig).filter(function (nativeItemType) {
var matchesTypes = nativeTypesConfig[nativeItemType].matchesTypes;
return matchesTypes.some(function (t) {
return dataTransferTypes.indexOf(t) > -1;
});
})[0] || null;
}
function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$2(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); return Constructor; }
var OptionsReader = /*#__PURE__*/function () {
function OptionsReader(globalContext, options) {
_classCallCheck$2(this, OptionsReader);
this.ownerDocument = null;
this.globalContext = globalContext;
this.optionsArgs = options;
}
_createClass$2(OptionsReader, [{
key: "window",
get: function get() {
if (this.globalContext) {
return this.globalContext;
} else if (typeof window !== 'undefined') {
return window;
}
return undefined;
}
}, {
key: "document",
get: function get() {
var _this$globalContext;
if ((_this$globalContext = this.globalContext) !== null && _this$globalContext !== void 0 && _this$globalContext.document) {
return this.globalContext.document;
} else if (this.window) {
return this.window.document;
} else {
return undefined;
}
}
}, {
key: "rootElement",
get: function get() {
var _this$optionsArgs;
return ((_this$optionsArgs = this.optionsArgs) === null || _this$optionsArgs === void 0 ? void 0 : _this$optionsArgs.rootElement) || this.window;
}
}]);
return OptionsReader;
}();
function ownKeys$2c(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$2c(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2c(Object(source), true).forEach(function (key) { _defineProperty$3(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2c(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }
var HTML5BackendImpl = /*#__PURE__*/function () {
function HTML5BackendImpl(manager, globalContext, options) {
var _this = this;
_classCallCheck$1(this, HTML5BackendImpl);
this.sourcePreviewNodes = new Map();
this.sourcePreviewNodeOptions = new Map();
this.sourceNodes = new Map();
this.sourceNodeOptions = new Map();
this.dragStartSourceIds = null;
this.dropTargetIds = [];
this.dragEnterTargetIds = [];
this.currentNativeSource = null;
this.currentNativeHandle = null;
this.currentDragSourceNode = null;
this.altKeyPressed = false;
this.mouseMoveTimeoutTimer = null;
this.asyncEndDragFrameId = null;
this.dragOverTargetIds = null;
this.getSourceClientOffset = function (sourceId) {
var source = _this.sourceNodes.get(sourceId);
return source && getNodeClientOffset(source) || null;
};
this.endDragNativeItem = function () {
if (!_this.isDraggingNativeItem()) {
return;
}
_this.actions.endDrag();
if (_this.currentNativeHandle) {
_this.registry.removeSource(_this.currentNativeHandle);
}
_this.currentNativeHandle = null;
_this.currentNativeSource = null;
};
this.isNodeInDocument = function (node) {
// Check the node either in the main document or in the current context
return Boolean(node && _this.document && _this.document.body && document.body.contains(node));
};
this.endDragIfSourceWasRemovedFromDOM = function () {
var node = _this.currentDragSourceNode;
if (node == null || _this.isNodeInDocument(node)) {
return;
}
if (_this.clearCurrentDragSourceNode() && _this.monitor.isDragging()) {
_this.actions.endDrag();
}
};
this.handleTopDragStartCapture = function () {
_this.clearCurrentDragSourceNode();
_this.dragStartSourceIds = [];
};
this.handleTopDragStart = function (e) {
if (e.defaultPrevented) {
return;
}
var dragStartSourceIds = _this.dragStartSourceIds;
_this.dragStartSourceIds = null;
var clientOffset = getEventClientOffset(e); // Avoid crashing if we missed a drop event or our previous drag died
if (_this.monitor.isDragging()) {
_this.actions.endDrag();
} // Don't publish the source just yet (see why below)
_this.actions.beginDrag(dragStartSourceIds || [], {
publishSource: false,
getSourceClientOffset: _this.getSourceClientOffset,
clientOffset: clientOffset
});
var dataTransfer = e.dataTransfer;
var nativeType = matchNativeItemType(dataTransfer);
if (_this.monitor.isDragging()) {
if (dataTransfer && typeof dataTransfer.setDragImage === 'function') {
// Use custom drag image if user specifies it.
// If child drag source refuses drag but parent agrees,
// use parent's node as drag image. Neither works in IE though.
var sourceId = _this.monitor.getSourceId();
var sourceNode = _this.sourceNodes.get(sourceId);
var dragPreview = _this.sourcePreviewNodes.get(sourceId) || sourceNode;
if (dragPreview) {
var _this$getCurrentSourc = _this.getCurrentSourcePreviewNodeOptions(),
anchorX = _this$getCurrentSourc.anchorX,
anchorY = _this$getCurrentSourc.anchorY,
offsetX = _this$getCurrentSourc.offsetX,
offsetY = _this$getCurrentSourc.offsetY;
var anchorPoint = {
anchorX: anchorX,
anchorY: anchorY
};
var offsetPoint = {
offsetX: offsetX,
offsetY: offsetY
};
var dragPreviewOffset = getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint, offsetPoint);
dataTransfer.setDragImage(dragPreview, dragPreviewOffset.x, dragPreviewOffset.y);
}
}
try {
// Firefox won't drag without setting data
dataTransfer === null || dataTransfer === void 0 ? void 0 : dataTransfer.setData('application/json', {});
} catch (err) {// IE doesn't support MIME types in setData
} // Store drag source node so we can check whether
// it is removed from DOM and trigger endDrag manually.
_this.setCurrentDragSourceNode(e.target); // Now we are ready to publish the drag source.. or are we not?
var _this$getCurrentSourc2 = _this.getCurrentSourcePreviewNodeOptions(),
captureDraggingState = _this$getCurrentSourc2.captureDraggingState;
if (!captureDraggingState) {
// Usually we want to publish it in the next tick so that browser
// is able to screenshot the current (not yet dragging) state.
//
// It also neatly avoids a situation where render() returns null
// in the same tick for the source element, and browser freaks out.
setTimeout(function () {
return _this.actions.publishDragSource();
}, 0);
} else {
// In some cases the user may want to override this behavior, e.g.
// to work around IE not supporting custom drag previews.
//
// When using a custom drag layer, the only way to prevent
// the default drag preview from drawing in IE is to screenshot
// the dragging state in which the node itself has zero opacity
// and height. In this case, though, returning null from render()
// will abruptly end the dragging, which is not obvious.
//
// This is the reason such behavior is strictly opt-in.
_this.actions.publishDragSource();
}
} else if (nativeType) {
// A native item (such as URL) dragged from inside the document
_this.beginDragNativeItem(nativeType);
} else if (dataTransfer && !dataTransfer.types && (e.target && !e.target.hasAttribute || !e.target.hasAttribute('draggable'))) {
// Looks like a Safari bug: dataTransfer.types is null, but there was no draggable.
// Just let it drag. It's a native type (URL or text) and will be picked up in
// dragenter handler.
return;
} else {
// If by this time no drag source reacted, tell browser not to drag.
e.preventDefault();
}
};
this.handleTopDragEndCapture = function () {
if (_this.clearCurrentDragSourceNode() && _this.monitor.isDragging()) {
// Firefox can dispatch this event in an infinite loop
// if dragend handler does something like showing an alert.
// Only proceed if we have not handled it already.
_this.actions.endDrag();
}
};
this.handleTopDragEnterCapture = function (e) {
_this.dragEnterTargetIds = [];
var isFirstEnter = _this.enterLeaveCounter.enter(e.target);
if (!isFirstEnter || _this.monitor.isDragging()) {
return;
}
var dataTransfer = e.dataTransfer;
var nativeType = matchNativeItemType(dataTransfer);
if (nativeType) {
// A native item (such as file or URL) dragged from outside the document
_this.beginDragNativeItem(nativeType, dataTransfer);
}
};
this.handleTopDragEnter = function (e) {
var dragEnterTargetIds = _this.dragEnterTargetIds;
_this.dragEnterTargetIds = [];
if (!_this.monitor.isDragging()) {
// This is probably a native item type we don't understand.
return;
}
_this.altKeyPressed = e.altKey; // If the target changes position as the result of `dragenter`, `dragover` might still
// get dispatched despite target being no longer there. The easy solution is to check
// whether there actually is a target before firing `hover`.
if (dragEnterTargetIds.length > 0) {
_this.actions.hover(dragEnterTargetIds, {
clientOffset: getEventClientOffset(e)
});
}
var canDrop = dragEnterTargetIds.some(function (targetId) {
return _this.monitor.canDropOnTarget(targetId);
});
if (canDrop) {
// IE requires this to fire dragover events
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = _this.getCurrentDropEffect();
}
}
};
this.handleTopDragOverCapture = function () {
_this.dragOverTargetIds = [];
};
this.handleTopDragOver = function (e) {
var dragOverTargetIds = _this.dragOverTargetIds;
_this.dragOverTargetIds = [];
if (!_this.monitor.isDragging()) {
// This is probably a native item type we don't understand.
// Prevent default "drop and blow away the whole document" action.
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'none';
}
return;
}
_this.altKeyPressed = e.altKey;
_this.actions.hover(dragOverTargetIds || [], {
clientOffset: getEventClientOffset(e)
});
var canDrop = (dragOverTargetIds || []).some(function (targetId) {
return _this.monitor.canDropOnTarget(targetId);
});
if (canDrop) {
// Show user-specified drop effect.
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = _this.getCurrentDropEffect();
}
} else if (_this.isDraggingNativeItem()) {
// Don't show a nice cursor but still prevent default
// "drop and blow away the whole document" action.
e.preventDefault();
} else {
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'none';
}
}
};
this.handleTopDragLeaveCapture = function (e) {
if (_this.isDraggingNativeItem()) {
e.preventDefault();
}
var isLastLeave = _this.enterLeaveCounter.leave(e.target);
if (!isLastLeave) {
return;
}
if (_this.isDraggingNativeItem()) {
setTimeout(function () {
return _this.endDragNativeItem();
}, 0);
}
};
this.handleTopDropCapture = function (e) {
_this.dropTargetIds = [];
if (_this.isDraggingNativeItem()) {
var _this$currentNativeSo;
e.preventDefault();
(_this$currentNativeSo = _this.currentNativeSource) === null || _this$currentNativeSo === void 0 ? void 0 : _this$currentNativeSo.loadDataTransfer(e.dataTransfer);
}
_this.enterLeaveCounter.reset();
};
this.handleTopDrop = function (e) {
var dropTargetIds = _this.dropTargetIds;
_this.dropTargetIds = [];
_this.actions.hover(dropTargetIds, {
clientOffset: getEventClientOffset(e)
});
_this.actions.drop({
dropEffect: _this.getCurrentDropEffect()
});
if (_this.isDraggingNativeItem()) {
_this.endDragNativeItem();
} else if (_this.monitor.isDragging()) {
_this.actions.endDrag();
}
};
this.handleSelectStart = function (e) {
var target = e.target; // Only IE requires us to explicitly say
// we want drag drop operation to start
if (typeof target.dragDrop !== 'function') {
return;
} // Inputs and textareas should be selectable
if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
return;
} // For other targets, ask IE
// to enable drag and drop
e.preventDefault();
target.dragDrop();
};
this.options = new OptionsReader(globalContext, options);
this.actions = manager.getActions();
this.monitor = manager.getMonitor();
this.registry = manager.getRegistry();
this.enterLeaveCounter = new EnterLeaveCounter(this.isNodeInDocument);
}
/**
* Generate profiling statistics for the HTML5Backend.
*/
_createClass$1(HTML5BackendImpl, [{
key: "profile",
value: function profile() {
var _this$dragStartSource, _this$dragOverTargetI;
return {
sourcePreviewNodes: this.sourcePreviewNodes.size,
sourcePreviewNodeOptions: this.sourcePreviewNodeOptions.size,
sourceNodeOptions: this.sourceNodeOptions.size,
sourceNodes: this.sourceNodes.size,
dragStartSourceIds: ((_this$dragStartSource = this.dragStartSourceIds) === null || _this$dragStartSource === void 0 ? void 0 : _this$dragStartSource.length) || 0,
dropTargetIds: this.dropTargetIds.length,
dragEnterTargetIds: this.dragEnterTargetIds.length,
dragOverTargetIds: ((_this$dragOverTargetI = this.dragOverTargetIds) === null || _this$dragOverTargetI === void 0 ? void 0 : _this$dragOverTargetI.length) || 0
};
} // public for test
}, {
key: "window",
get: function get() {
return this.options.window;
}
}, {
key: "document",
get: function get() {
return this.options.document;
}
/**
* Get the root element to use for event subscriptions
*/
}, {
key: "rootElement",
get: function get() {
return this.options.rootElement;
}
}, {
key: "setup",
value: function setup() {
var root = this.rootElement;
if (root === undefined) {
return;
}
if (root.__isReactDndBackendSetUp) {
throw new Error('Cannot have two HTML5 backends at the same time.');
}
root.__isReactDndBackendSetUp = true;
this.addEventListeners(root);
}
}, {
key: "teardown",
value: function teardown() {
var root = this.rootElement;
if (root === undefined) {
return;
}
root.__isReactDndBackendSetUp = false;
this.removeEventListeners(this.rootElement);
this.clearCurrentDragSourceNode();
if (this.asyncEndDragFrameId) {
var _this$window;
(_this$window = this.window) === null || _this$window === void 0 ? void 0 : _this$window.cancelAnimationFrame(this.asyncEndDragFrameId);
}
}
}, {
key: "connectDragPreview",
value: function connectDragPreview(sourceId, node, options) {
var _this2 = this;
this.sourcePreviewNodeOptions.set(sourceId, options);
this.sourcePreviewNodes.set(sourceId, node);
return function () {
_this2.sourcePreviewNodes.delete(sourceId);
_this2.sourcePreviewNodeOptions.delete(sourceId);
};
}
}, {
key: "connectDragSource",
value: function connectDragSource(sourceId, node, options) {
var _this3 = this;
this.sourceNodes.set(sourceId, node);
this.sourceNodeOptions.set(sourceId, options);
var handleDragStart = function handleDragStart(e) {
return _this3.handleDragStart(e, sourceId);
};
var handleSelectStart = function handleSelectStart(e) {
return _this3.handleSelectStart(e);
};
node.setAttribute('draggable', 'true');
node.addEventListener('dragstart', handleDragStart);
node.addEventListener('selectstart', handleSelectStart);
return function () {
_this3.sourceNodes.delete(sourceId);
_this3.sourceNodeOptions.delete(sourceId);
node.removeEventListener('dragstart', handleDragStart);
node.removeEventListener('selectstart', handleSelectStart);
node.setAttribute('draggable', 'false');
};
}
}, {
key: "connectDropTarget",
value: function connectDropTarget(targetId, node) {
var _this4 = this;
var handleDragEnter = function handleDragEnter(e) {
return _this4.handleDragEnter(e, targetId);
};
var handleDragOver = function handleDragOver(e) {
return _this4.handleDragOver(e, targetId);
};
var handleDrop = function handleDrop(e) {
return _this4.handleDrop(e, targetId);
};
node.addEventListener('dragenter', handleDragEnter);
node.addEventListener('dragover', handleDragOver);
node.addEventListener('drop', handleDrop);
return function () {
node.removeEventListener('dragenter', handleDragEnter);
node.removeEventListener('dragover', handleDragOver);
node.removeEventListener('drop', handleDrop);
};
}
}, {
key: "addEventListeners",
value: function addEventListeners(target) {
// SSR Fix (https://github.com/react-dnd/react-dnd/pull/813
if (!target.addEventListener) {
return;
}
target.addEventListener('dragstart', this.handleTopDragStart);
target.addEventListener('dragstart', this.handleTopDragStartCapture, true);
target.addEventListener('dragend', this.handleTopDragEndCapture, true);
target.addEventListener('dragenter', this.handleTopDragEnter);
target.addEventListener('dragenter', this.handleTopDragEnterCapture, true);
target.addEventListener('dragleave', this.handleTopDragLeaveCapture, true);
target.addEventListener('dragover', this.handleTopDragOver);
target.addEventListener('dragover', this.handleTopDragOverCapture, true);
target.addEventListener('drop', this.handleTopDrop);
target.addEventListener('drop', this.handleTopDropCapture, true);
}
}, {
key: "removeEventListeners",
value: function removeEventListeners(target) {
// SSR Fix (https://github.com/react-dnd/react-dnd/pull/813
if (!target.removeEventListener) {
return;
}
target.removeEventListener('dragstart', this.handleTopDragStart);
target.removeEventListener('dragstart', this.handleTopDragStartCapture, true);
target.removeEventListener('dragend', this.handleTopDragEndCapture, true);
target.removeEventListener('dragenter', this.handleTopDragEnter);
target.removeEventListener('dragenter', this.handleTopDragEnterCapture, true);
target.removeEventListener('dragleave', this.handleTopDragLeaveCapture, true);
target.removeEventListener('dragover', this.handleTopDragOver);
target.removeEventListener('dragover', this.handleTopDragOverCapture, true);
target.removeEventListener('drop', this.handleTopDrop);
target.removeEventListener('drop', this.handleTopDropCapture, true);
}
}, {
key: "getCurrentSourceNodeOptions",
value: function getCurrentSourceNodeOptions() {
var sourceId = this.monitor.getSourceId();
var sourceNodeOptions = this.sourceNodeOptions.get(sourceId);
return _objectSpread$2c({
dropEffect: this.altKeyPressed ? 'copy' : 'move'
}, sourceNodeOptions || {});
}
}, {
key: "getCurrentDropEffect",
value: function getCurrentDropEffect() {
if (this.isDraggingNativeItem()) {
// It makes more sense to default to 'copy' for native resources
return 'copy';
}
return this.getCurrentSourceNodeOptions().dropEffect;
}
}, {
key: "getCurrentSourcePreviewNodeOptions",
value: function getCurrentSourcePreviewNodeOptions() {
var sourceId = this.monitor.getSourceId();
var sourcePreviewNodeOptions = this.sourcePreviewNodeOptions.get(sourceId);
return _objectSpread$2c({
anchorX: 0.5,
anchorY: 0.5,
captureDraggingState: false
}, sourcePreviewNodeOptions || {});
}
}, {
key: "isDraggingNativeItem",
value: function isDraggingNativeItem() {
var itemType = this.monitor.getItemType();
return Object.keys(NativeTypes).some(function (key) {
return NativeTypes[key] === itemType;
});
}
}, {
key: "beginDragNativeItem",
value: function beginDragNativeItem(type, dataTransfer) {
this.clearCurrentDragSourceNode();
this.currentNativeSource = createNativeDragSource(type, dataTransfer);
this.currentNativeHandle = this.registry.addSource(type, this.currentNativeSource);
this.actions.beginDrag([this.currentNativeHandle]);
}
}, {
key: "setCurrentDragSourceNode",
value: function setCurrentDragSourceNode(node) {
var _this5 = this;
this.clearCurrentDragSourceNode();
this.currentDragSourceNode = node; // A timeout of > 0 is necessary to resolve Firefox issue referenced
// See:
// * https://github.com/react-dnd/react-dnd/pull/928
// * https://github.com/react-dnd/react-dnd/issues/869
var MOUSE_MOVE_TIMEOUT = 1000; // Receiving a mouse event in the middle of a dragging operation
// means it has ended and the drag source node disappeared from DOM,
// so the browser didn't dispatch the dragend event.
//
// We need to wait before we start listening for mousemove events.
// This is needed because the drag preview needs to be drawn or else it fires an 'mousemove' event
// immediately in some browsers.
//
// See:
// * https://github.com/react-dnd/react-dnd/pull/928
// * https://github.com/react-dnd/react-dnd/issues/869
//
this.mouseMoveTimeoutTimer = setTimeout(function () {
var _this5$rootElement;
return (_this5$rootElement = _this5.rootElement) === null || _this5$rootElement === void 0 ? void 0 : _this5$rootElement.addEventListener('mousemove', _this5.endDragIfSourceWasRemovedFromDOM, true);
}, MOUSE_MOVE_TIMEOUT);
}
}, {
key: "clearCurrentDragSourceNode",
value: function clearCurrentDragSourceNode() {
if (this.currentDragSourceNode) {
this.currentDragSourceNode = null;
if (this.rootElement) {
var _this$window2;
(_this$window2 = this.window) === null || _this$window2 === void 0 ? void 0 : _this$window2.clearTimeout(this.mouseMoveTimeoutTimer || undefined);
this.rootElement.removeEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true);
}
this.mouseMoveTimeoutTimer = null;
return true;
}
return false;
}
}, {
key: "handleDragStart",
value: function handleDragStart(e, sourceId) {
if (e.defaultPrevented) {
return;
}
if (!this.dragStartSourceIds) {
this.dragStartSourceIds = [];
}
this.dragStartSourceIds.unshift(sourceId);
}
}, {
key: "handleDragEnter",
value: function handleDragEnter(e, targetId) {
this.dragEnterTargetIds.unshift(targetId);
}
}, {
key: "handleDragOver",
value: function handleDragOver(e, targetId) {
if (this.dragOverTargetIds === null) {
this.dragOverTargetIds = [];
}
this.dragOverTargetIds.unshift(targetId);
}
}, {
key: "handleDrop",
value: function handleDrop(e, targetId) {
this.dropTargetIds.unshift(targetId);
}
}]);
return HTML5BackendImpl;
}();
var HTML5Backend = function createBackend(manager, context, options) {
return new HTML5BackendImpl(manager, context, options);
};
function useDNDProviderElement(props) {
var children = props.children; // eslint-disable-line react/prop-types
if (!children) return null;
return /*#__PURE__*/React__default['default'].createElement(DndProvider, {
backend: HTML5Backend
}, children);
}
useDNDProviderElement.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "useDNDProviderElement"
};
var DropLocation = {
Above: 'above',
Below: 'below',
Nested: 'nested'
};
var EditingStyle = {
Single: 'single',
Multiple: 'multiple',
SingleNesting: 'single-nesting',
MultipleNesting: 'multiple-nesting'
};
/**
* Returns true if a passed in editing style is multiple rather than single
* @param {EditingStyle} editingStyle current editing style
*/
var editingStyleIsMultiple = function editingStyleIsMultiple(editingStyle) {
return editingStyle === EditingStyle.MultipleNesting || editingStyle === EditingStyle.Multiple;
};
/**
* Returns a set of items that match the set of ids
* @param {Array
} items full set of items
* @param {Array[string]} ids selected ids from the set of items
*/
var searchDraggedItem = function searchDraggedItem(items, ids) {
var draggedItems = [];
items.forEach(function (item) {
if (ids.some(function (id) {
return item.id === id;
})) {
draggedItems.push(item);
} else if (item.children) {
draggedItems = [].concat(toConsumableArray(draggedItems), toConsumableArray(searchDraggedItem(item.children, ids)));
}
});
return draggedItems;
};
/**
* Helper function that returns a new list with the dragged items moved to the specified location
* @param {Array} items original list of ListItems
* @param {Array} draggedItems items to be moved
* @param {string} dropId the id of the drop location
* @param {DropLocation} location Where the drop will occur, above or below the specified id or as the first child of the specified id
* @param {boolean} dropped flag stating if the drop has already occured in case there are duplicate ids in the list
*/
var updateList = function updateList(items, draggedItems, dropId, location) {
var _draggedItems$, _draggedItems$$childr;
var dropped = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var finalList = [];
var itemDropped = dropped; // Protects against dupe ids and multiple drops
if (items && !((_draggedItems$ = draggedItems[0]) !== null && _draggedItems$ !== void 0 && (_draggedItems$$childr = _draggedItems$.children) !== null && _draggedItems$$childr !== void 0 && _draggedItems$$childr.some(function (x) {
return x.id === dropId;
}))) {
items.forEach(function (item) {
var _children;
// Insert dragged items in before location
if (!itemDropped && item.id === dropId && location === DropLocation.Above) {
finalList = [].concat(toConsumableArray(finalList), toConsumableArray(draggedItems));
itemDropped = true;
}
var _item$children = item.children,
children = _item$children === void 0 ? [] : _item$children; // Insert dragged items in nested location
if (!itemDropped && location === DropLocation.Nested && dropId === item.id) {
itemDropped = true;
children = draggedItems.concat(updateList(children, draggedItems, dropId, location, itemDropped));
} else if ((_children = children) !== null && _children !== void 0 && _children.length) {
children = updateList(children, draggedItems, dropId, location, itemDropped);
} // Add item into final list if it isn't a dragged item
if (!draggedItems.find(function (drag) {
return drag.id === item.id;
})) {
item.children = children; // eslint-disable-line no-param-reassign
finalList.push(item);
} // Insert dragged items in after location
if (!itemDropped && item.id === dropId && location === DropLocation.Below) {
finalList = [].concat(toConsumableArray(finalList), toConsumableArray(draggedItems));
}
});
return finalList;
}
return items;
};
/**
* Returns a new list with the dragged items moved to the specified location
* @param {Array} items original list of ListItems
* @param {Array} draggedItems items to be moved
* @param {string} dropId the id of the drop location
* @param {DropLocation} location Where the drop will occur, above or below the specified id or as the first child of the specified id
*/
var moveItemsInList = function moveItemsInList(items, dragIds, dropId, location) {
var draggedItems = searchDraggedItem(items, dragIds.filter(function (id) {
return id !== dropId;
}));
return updateList(items, draggedItems, dropId, location);
};
/**
* Returns every child id from the ListItem and their children's ids
* @param {ListItem} listItem
*/
var getAllChildIds = function getAllChildIds(listItem) {
var lockedIds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var childIds = [];
if (listItem.children) {
listItem.children.forEach(function (child) {
if (!lockedIds.includes(child.id)) {
childIds.push(child.id);
}
childIds = [].concat(toConsumableArray(childIds), toConsumableArray(getAllChildIds(child)));
});
}
return childIds;
};
/**
* Handles adding and removing items to a list to determine which list items are selected or deselected
* @param {Array} list original list of ListItems
* @param {Array} currentSelection current selection of ListItems as ids
* @param {string} id the id of an item that has been selected or deselected
* @param {string} parentId the parent id of the selected or deselected item - if unselected, the parent is also unselected
*/
var handleEditModeSelect = function handleEditModeSelect(list, currentSelection, id, parentId, lockedIds) {
var newSelection = [];
if (currentSelection.filter(function (editId) {
return editId === id;
}).length > 0) {
var _ref, _selectedItem$childre;
var selectedItem = list.find(function (item) {
return item.id === id;
});
var hasChildren = (_ref = (selectedItem === null || selectedItem === void 0 ? void 0 : (_selectedItem$childre = selectedItem.children) === null || _selectedItem$childre === void 0 ? void 0 : _selectedItem$childre.length) > 0) !== null && _ref !== void 0 ? _ref : false;
var selectedItemChildrenIds = hasChildren ? selectedItem.children.map(function (child) {
return child.id;
}) : [];
newSelection = currentSelection.filter(function (selected) {
var notCurrentOrParent = selected !== id && selected !== parentId;
return hasChildren ? !selectedItemChildrenIds.includes(selected) && notCurrentOrParent : notCurrentOrParent;
});
} else {
list.forEach(function (editItem) {
if (editItem.id === id) {
newSelection.push(id);
newSelection = [].concat(toConsumableArray(newSelection), toConsumableArray(getAllChildIds(editItem, lockedIds)));
} else if (editItem.children) {
newSelection = [].concat(toConsumableArray(newSelection), toConsumableArray(handleEditModeSelect(editItem.children, currentSelection, id, parentId, lockedIds)));
}
if (currentSelection.some(function (selectionId) {
return selectionId === editItem.id;
})) {
newSelection.push(editItem.id);
} // if there is a parentId, list is simply the current items siblings here, because of the
// recursive call if the else if above.
if (parentId && list.every(function (sibling) {
return newSelection.includes(sibling.id);
})) {
newSelection.push(parentId);
}
});
}
return newSelection;
};
/**
* checks if the given child id is selected.
*
* @param {array} selectedIds an array of selected ids
* @returns function used in some/every calls in handleEditModeIndeterminateIds below
*/
var childIsSelected = function childIsSelected(selectedIds) {
return function (childId) {
return selectedIds.includes(childId);
};
};
/**
*
* @param {array} list aray of list objects
* @param {array} editModeSelectedIds an array of the selected ids
* @returns an array of ids of the indeterminate rows
*/
var handleEditModeIndeterminateIds = function handleEditModeIndeterminateIds(list, editModeSelectedIds) {
var indeterminateIds = [];
if (!editModeSelectedIds.length) {
return indeterminateIds;
}
list.forEach(function (item) {
var childIds = getAllChildIds(item);
var allSelected = childIds.every(childIsSelected(editModeSelectedIds));
if (!allSelected && childIds.some(childIsSelected(editModeSelectedIds))) {
indeterminateIds = [].concat(toConsumableArray(indeterminateIds), [item.id]);
}
});
return indeterminateIds;
};
function DragAndDrop(props) {
var DNDElement = useDNDProviderElement(props);
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, DNDElement);
}
/**
* Allows the merging of multiple refs when a components needs to handle more than one,
* e.g. when combining a map and a (drag and) drop target reference for the same element.
* @param {...any} refs Refs that should be merged are passed as separate parameters
* @returns A function that will update the current property or call the ref function of all merged refs
*/
var mergeRefs = function mergeRefs() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
var filteredRefs = refs.filter(Boolean);
return !filteredRefs.length ? null : filteredRefs.length === 1 ? filteredRefs[0] : function (currentInstance) {
filteredRefs.forEach(function (ref) {
if (typeof ref === 'function') {
ref(currentInstance);
} else if (ref) {
ref.current = currentInstance; // eslint-disable-line no-param-reassign
}
});
};
};
DragAndDrop.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "DragAndDrop"
};
function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$a() { 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 iotPrefix$2i = settings$1.iotPrefix;
var ColumnHeaderRow = /*#__PURE__*/function (_Component) {
inherits(ColumnHeaderRow, _Component);
var _super = _createSuper$a(ColumnHeaderRow);
function ColumnHeaderRow() {
var _this;
classCallCheck(this, ColumnHeaderRow);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty$d(assertThisInitialized(_this), "reorderColumn", function (srcIndex, destIndex) {
var _this$props = _this.props,
ordering = _this$props.ordering,
onChangeOrdering = _this$props.onChangeOrdering;
ordering.splice(destIndex, 0, ordering.splice(srcIndex, 1)[0]);
onChangeOrdering(ordering);
});
defineProperty$d(assertThisInitialized(_this), "toggleColumn", function (id) {
var _this$props2 = _this.props,
ordering = _this$props2.ordering,
onColumnToggle = _this$props2.onColumnToggle;
onColumnToggle(id, ordering.map(function (i) {
return {
columnId: i.columnId,
isHidden: i.columnId === id ? !i.isHidden : i.isHidden
};
}));
});
return _this;
}
createClass(ColumnHeaderRow, [{
key: "render",
value: function render() {
var _this2 = this;
var _this$props3 = this.props,
columns = _this$props3.columns,
ordering = _this$props3.ordering,
_this$props3$options = _this$props3.options,
hasRowSelection = _this$props3$options.hasRowSelection,
hasRowExpansion = _this$props3$options.hasRowExpansion,
hasRowActions = _this$props3$options.hasRowActions,
hasColumnSelectionConfig = _this$props3$options.hasColumnSelectionConfig,
onColumnSelectionConfig = _this$props3.onColumnSelectionConfig,
columnSelectionConfigText = _this$props3.columnSelectionConfigText,
isDisabled = _this$props3.isDisabled,
testId = _this$props3.testId,
showExpanderColumn = _this$props3.showExpanderColumn,
hasDragAndDrop = _this$props3.hasDragAndDrop;
var visibleColumns = columns.filter(function (c) {
return !(ordering.find(function (o) {
return o.columnId === c.id;
}) || {
isHidden: false
}).isHidden;
});
return /*#__PURE__*/React__default['default'].createElement(DragAndDrop, null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
"data-testid": testId,
className: "".concat(iotPrefix$2i, "--column-header-row--table-row")
}, hasDragAndDrop ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2i, "--column-header-row--table-header")
}) : null, hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2i, "--column-header-row--table-header")
}) : null, hasRowExpansion ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2i, "--column-header-row--table-header")
}) : null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2i, "--column-header-row--table-header"),
colSpan: visibleColumns.length + (hasRowActions ? 1 : 0) + (showExpanderColumn ? 1 : 0),
scope: "col"
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$2i, "--column-header-row--select-wrapper")
}, ordering.map(function (c, idx) {
return /*#__PURE__*/React__default['default'].createElement(ColumnHeaderSelect$1, {
key: "".concat(idx, "-item"),
index: idx,
columnId: c.columnId,
isHidden: c.isHidden,
moveItem: function moveItem(srcIndex, destIndex) {
return _this2.reorderColumn(srcIndex, destIndex);
},
onClick: function onClick() {
return _this2.toggleColumn(c.columnId);
},
isDisabled: isDisabled
}, columns.find(function (i) {
return c.columnId === i.id;
}).name);
})), hasColumnSelectionConfig ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Button, {
disabled: isDisabled,
className: "column-header__btn",
kind: "ghost",
size: "small",
renderIcon: iconsReact.Settings16,
onClick: function onClick() {
return onColumnSelectionConfig();
}
}, columnSelectionConfigText) : null)));
}
}]);
return ColumnHeaderRow;
}(React$1.Component);
defineProperty$d(ColumnHeaderRow, "propTypes", {
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string.isRequired,
name: PropTypes__default['default'].string.isRequired
})).isRequired,
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
options: PropTypes__default['default'].shape({
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasColumnSelectionConfig: PropTypes__default['default'].bool,
hasRowActions: PropTypes__default['default'].bool
}).isRequired,
onChangeOrdering: PropTypes__default['default'].func.isRequired,
onColumnToggle: PropTypes__default['default'].func.isRequired,
onColumnSelectionConfig: PropTypes__default['default'].func,
columnSelectionConfigText: PropTypes__default['default'].string,
isDisabled: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool.isRequired,
/** Set to true if the table support drag and drop. Inserts a cell in the "darg handle" column
* for spacing. */
hasDragAndDrop: PropTypes__default['default'].bool
});
defineProperty$d(ColumnHeaderRow, "defaultProps", {
onColumnSelectionConfig: defaultFunction('actions.table.onColumnSelectionConfig'),
columnSelectionConfigText: defaultI18NPropTypes.columnSelectionConfig,
isDisabled: false,
testId: '',
hasDragAndDrop: false
});
ColumnHeaderRow.__docgenInfo = {
"description": "",
"methods": [{
"name": "reorderColumn",
"docblock": null,
"modifiers": [],
"params": [{
"name": "srcIndex",
"type": null
}, {
"name": "destIndex",
"type": null
}],
"returns": null
}, {
"name": "toggleColumn",
"docblock": null,
"modifiers": [],
"params": [{
"name": "id",
"type": null
}],
"returns": null
}],
"displayName": "ColumnHeaderRow",
"props": {
"onColumnSelectionConfig": {
"defaultValue": {
"value": "defaultFunction('actions.table.onColumnSelectionConfig')",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"columnSelectionConfigText": {
"defaultValue": {
"value": "defaultI18NPropTypes.columnSelectionConfig",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"isDisabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"hasDragAndDrop": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Set to true if the table support drag and drop. Inserts a cell in the \"darg handle\" column\nfor spacing."
},
"columns": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": true
},
"name": {
"name": "string",
"required": true
}
}
}
},
"required": true,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"options": {
"type": {
"name": "shape",
"value": {
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"hasRowExpansion": {
"name": "bool",
"required": false
},
"hasColumnSelectionConfig": {
"name": "bool",
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
}
}
},
"required": true,
"description": ""
},
"onChangeOrdering": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onColumnToggle": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"showExpanderColumn": {
"type": {
"name": "bool"
},
"required": true,
"description": "shows an additional column that can expand/shrink as the table is resized"
}
}
};
var PROPER_FUNCTION_NAME$1 = functionName.PROPER;
var non = '\u200B\u0085\u180E';
// check that a method works with the correct list
// of whitespaces and has a correct name
var stringTrimForced = function (METHOD_NAME) {
return fails(function () {
return !!whitespaces[METHOD_NAME]()
|| non[METHOD_NAME]() !== non
|| (PROPER_FUNCTION_NAME$1 && whitespaces[METHOD_NAME].name !== METHOD_NAME);
});
};
var $trim = stringTrim.trim;
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
_export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, {
trim: function trim() {
return $trim(this);
}
});
var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f;
// eslint-disable-next-line es/no-string-prototype-startswith -- safe
var nativeStartsWith = functionUncurryThisClause(''.startsWith);
var stringSlice$4 = functionUncurryThisClause(''.slice);
var min$7 = Math.min;
var CORRECT_IS_REGEXP_LOGIC$1 = correctIsRegexpLogic('startsWith');
// https://github.com/zloirock/core-js/pull/702
var MDN_POLYFILL_BUG$1 = !CORRECT_IS_REGEXP_LOGIC$1 && !!function () {
var descriptor = getOwnPropertyDescriptor$3(String.prototype, 'startsWith');
return descriptor && !descriptor.writable;
}();
// `String.prototype.startsWith` method
// https://tc39.es/ecma262/#sec-string.prototype.startswith
_export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG$1 && !CORRECT_IS_REGEXP_LOGIC$1 }, {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = toString$1(requireObjectCoercible(this));
notARegexp(searchString);
var index = toLength(min$7(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = toString$1(searchString);
return nativeStartsWith
? nativeStartsWith(that, search, index)
: stringSlice$4(that, index, index + search.length) === search;
}
});
var keyboardKeys = {
BACKSPACE: 'Backspace',
CONTROL: 'Control',
DELETE: 'Delete',
DOWN: 'ArrowDown',
END: 'End',
ENTER: 'Enter',
ESCAPE: 'Escape',
HOME: 'Home',
LEFT: 'ArrowLeft',
PAGEDOWN: 'Page Down',
PAGEUP: 'Page Up',
RIGHT: 'ArrowRight',
SPACE: ' ',
TAB: 'Tab',
UP: 'ArrowUp'
};
function ownKeys$2b(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$2b(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2b(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2b(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$2h = settings$1.iotPrefix;
var propTypes$2o = _objectSpread$2b(_objectSpread$2b({}, carbonComponentsReact.ComboBox.propTypes), {}, {
loading: PropTypes__default['default'].bool,
// Callback that is called with the value of the input on change
onChange: PropTypes__default['default'].func.isRequired,
// Optional classname to be applied to wrapper
wrapperClassName: PropTypes__default['default'].string,
// String to pass to input field option
editOptionText: PropTypes__default['default'].string,
// String to pass for tags close button aria-label. Will be prepended to value name
closeButtonText: PropTypes__default['default'].string,
// Allow custom onBlur function to be passed to the combobox textinput
onBlur: PropTypes__default['default'].func,
// Bit that will allow mult value and tag feature
hasMultiValue: PropTypes__default['default'].bool,
// On submit/enter, new items should be added to the listbox
addToList: PropTypes__default['default'].bool,
// If true the menu will expand in width to fit the content
menuFitContent: PropTypes__default['default'].bool,
// The horizontal offset direction of the menu. Relevant if menuFitContent is active.
// Default is 'end' whit means that it expands to the right in normal LTR mode
horizontalDirection: PropTypes__default['default'].oneOf(['start', 'end']),
testId: PropTypes__default['default'].string
});
var defaultProps$2u = _objectSpread$2b(_objectSpread$2b({}, carbonComponentsReact.ComboBox.defaultProps), {}, {
loading: false,
wrapperClassName: null,
closeButtonText: 'Close',
editOptionText: 'Create',
hasMultiValue: false,
addToList: false,
items: [],
onInputChange: null,
onBlur: null,
testId: 'combo',
menuFitContent: false,
horizontalDirection: 'end'
});
var ComboBox = /*#__PURE__*/React__default['default'].forwardRef(function (_ref, ref) {
var _classnames;
var loading = _ref.loading,
wrapperClassName = _ref.wrapperClassName,
closeButtonText = _ref.closeButtonText,
editOptionText = _ref.editOptionText,
hasMultiValue = _ref.hasMultiValue,
onChange = _ref.onChange,
items = _ref.items,
className = _ref.className,
disabled = _ref.disabled,
id = _ref.id,
itemToString = _ref.itemToString,
size = _ref.size,
onInputChange = _ref.onInputChange,
addToList = _ref.addToList,
helperText = _ref.helperText,
shouldFilterItem = _ref.shouldFilterItem,
onBlur = _ref.onBlur,
testId = _ref.testId,
menuFitContent = _ref.menuFitContent,
horizontalDirection = _ref.horizontalDirection,
rest = objectWithoutProperties$1(_ref, ["loading", "wrapperClassName", "closeButtonText", "editOptionText", "hasMultiValue", "onChange", "items", "className", "disabled", "id", "itemToString", "size", "onInputChange", "addToList", "helperText", "shouldFilterItem", "onBlur", "testId", "menuFitContent", "horizontalDirection"]);
// Ref for the combobox input
var comboRef = ref || /*#__PURE__*/React__default['default'].createRef(); // Input value that is added to list
var _useState = React$1.useState(''),
_useState2 = slicedToArray$2(_useState, 2),
inputValue = _useState2[0],
setInputValue = _useState2[1]; // Array that populates list
var _useState3 = React$1.useState(items),
_useState4 = slicedToArray$2(_useState3, 2),
listItems = _useState4[0],
setListItems = _useState4[1]; // Array that populates tags
var _useState5 = React$1.useState([]),
_useState6 = slicedToArray$2(_useState5, 2),
tagItems = _useState6[0],
setTagItems = _useState6[1]; // Array that populates tags
var prevTagAndListCount = React$1.useRef(items.length + tagItems.length); // Handle focus after adding new tags or list items
React$1.useEffect(function () {
var currentTagAndListCount = tagItems.length + listItems.length; // only focus input if the tags or list have increased
if (prevTagAndListCount.current < currentTagAndListCount) {
comboRef.current.focus();
} // Store the value for the next render
prevTagAndListCount.current = currentTagAndListCount;
}, [tagItems, listItems, comboRef]);
/**
* List to the blur event and trigger parent onBlur
* @param {event} e
*/
var handleOnBlur = function handleOnBlur(e) {
if (onBlur) {
onBlur(inputValue, e);
}
};
var handleOnClose = function handleOnClose(e) {
var _e$currentTarget$pare, _e$currentTarget$pare2, _e$currentTarget$pare3, _e$currentTarget$pare4, _e$currentTarget$pare5, _e$currentTarget$pare6, _e$currentTarget$pare7, _e$currentTarget$pare8;
// Get close target's text
var closedValue = (_e$currentTarget$pare = e.currentTarget.parentNode) === null || _e$currentTarget$pare === void 0 ? void 0 : (_e$currentTarget$pare2 = _e$currentTarget$pare.children[0]) === null || _e$currentTarget$pare2 === void 0 ? void 0 : _e$currentTarget$pare2.textContent; // If there is a tag with the same value then remove from tag array
tagItems.forEach(function (item, idx) {
if (itemToString(item) === closedValue) {
tagItems.splice(idx, 1);
setTagItems(toConsumableArray(tagItems));
}
}); // Send new value to users onChange callback
onChange(toConsumableArray(tagItems)); // eslint-disable-next-line no-unused-expressions
(_e$currentTarget$pare3 = e.currentTarget.parentNode) === null || _e$currentTarget$pare3 === void 0 ? void 0 : (_e$currentTarget$pare4 = _e$currentTarget$pare3.parentNode) === null || _e$currentTarget$pare4 === void 0 ? void 0 : (_e$currentTarget$pare5 = _e$currentTarget$pare4.parentNode) === null || _e$currentTarget$pare5 === void 0 ? void 0 : (_e$currentTarget$pare6 = _e$currentTarget$pare5.firstChild) === null || _e$currentTarget$pare6 === void 0 ? void 0 : (_e$currentTarget$pare7 = _e$currentTarget$pare6.children[0]) === null || _e$currentTarget$pare7 === void 0 ? void 0 : (_e$currentTarget$pare8 = _e$currentTarget$pare7.children[1]) === null || _e$currentTarget$pare8 === void 0 ? void 0 : _e$currentTarget$pare8.focus();
};
var handleOnChange = function handleOnChange(_ref2) {
var downShiftSelectedItem = _ref2.selectedItem;
var newItem = downShiftSelectedItem && Object.keys(downShiftSelectedItem).reduce(function (acc, currentId) {
var value = downShiftSelectedItem[currentId];
return _objectSpread$2b(_objectSpread$2b({}, acc), {}, defineProperty$d({}, currentId, typeof value === 'string' ? value.trim() : value));
}, {});
var currentValue = itemToString(newItem); // Check that there is no existing tag
var hasNoExistingTag = tagItems.filter(function (x) {
return itemToString(x) === currentValue;
}).length < 1; // Check if value is part of items array
var isInList = listItems.filter(function (x) {
return itemToString(x).trim() === currentValue;
})[0];
if (hasMultiValue) {
// If tags array does not contain new value
if (newItem && hasNoExistingTag) {
// Add new value to tags array
setTagItems(function (inputValues) {
return [].concat(toConsumableArray(inputValues), [newItem]);
}); // pass the combobox value to user's onChange callback
onChange([].concat(toConsumableArray(tagItems), [newItem]));
}
} else {
onChange(newItem);
}
if ((addToList || hasMultiValue) && typeof (newItem === null || newItem === void 0 ? void 0 : newItem.id) === 'string' && newItem !== null && newItem !== void 0 && newItem.id.startsWith("".concat(iotPrefix$2h, "-input-")) && !isInList) {
// Add new item to items array
setListItems(function (currentList) {
return [newItem].concat(toConsumableArray(currentList));
});
}
setInputValue(null);
}; // If the input text doesn't match something in the list, the CarbonComboBox does not call the onChange handler
// https://github.com/carbon-design-system/carbon/issues/6613
var handleOnKeypress = function handleOnKeypress(evt) {
// Current value of input
var currentValue = comboRef.current.value.trim();
if (evt.key === keyboardKeys.ENTER && currentValue) {
var newItem = {
id: "".concat(iotPrefix$2h, "-input-").concat(currentValue.split(' ').join('-'), "-").concat(currentValue.length),
text: currentValue
};
handleOnChange({
selectedItem: newItem
});
}
};
var handleInputChange = function handleInputChange(e) {
var matchedItem = listItems.filter(function (x) {
return itemToString(x) === e;
})[0];
if ((onBlur || addToList || hasMultiValue) && e && e !== '' && !matchedItem) {
setInputValue({
id: "".concat(iotPrefix$2h, "-input-").concat(e.split(' ').join('-'), "-").concat(e.length),
text: e
});
} else {
setInputValue(null);
} // Pass on to user callbacks
if (typeof onInputChange === 'function') {
onInputChange(e);
}
};
var combinedItems = React$1.useMemo(function () {
return inputValue ? [inputValue].concat(toConsumableArray(listItems)) : listItems;
}, [inputValue, listItems]);
var shouldFilterItemForTags = function shouldFilterItemForTags(_ref3) {
var _itemToString2;
var item = _ref3.item,
_itemToString = _ref3.itemToString,
_inputValue = _ref3.inputValue;
return (_itemToString2 = _itemToString(item)) === null || _itemToString2 === void 0 ? void 0 : _itemToString2.includes(_inputValue);
};
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$2h, "--combobox"), (_classnames = {}, defineProperty$d(_classnames, wrapperClassName, wrapperClassName), defineProperty$d(_classnames, "".concat(iotPrefix$2h, "--combobox-add"), inputValue), defineProperty$d(_classnames, "".concat(iotPrefix$2h, "--combobox-size-").concat(size), size), defineProperty$d(_classnames, "".concat(iotPrefix$2h, "--combobox-helper-text"), helperText), defineProperty$d(_classnames, "".concat(iotPrefix$2h, "--combobox__menu--fit-content"), menuFitContent), defineProperty$d(_classnames, "".concat(iotPrefix$2h, "--combobox__menu--flip-horizontal"), horizontalDirection === 'start'), _classnames)),
onKeyDown: handleOnKeypress,
onBlur: handleOnBlur,
"data-testid": "".concat(testId, "-wrapper"),
"data-edit-option-text": editOptionText
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.ComboBox, _extends_1$1({
"data-testid": "".concat(testId, "-box"),
id: id,
key: "tags:".concat(tagItems.length, " listItems:").concat(listItems.length),
size: size,
ref: comboRef,
items: combinedItems,
itemToString: itemToString,
onChange: handleOnChange,
onInputChange: handleInputChange,
className: classnames$1(className, "".concat(iotPrefix$2h, "--combobox-input")),
disabled: disabled || loading !== undefined && loading !== false,
helperText: helperText,
shouldFilterItem: hasMultiValue || addToList ? shouldFilterItemForTags : shouldFilterItem
}, pick(rest, 'ariaLabel', 'direction', 'downshiftProps', 'initialSelectedItem', 'invalid', 'invalidText', 'itemToElement', 'light', 'onToggleClick', 'placeholder', 'selectedItem', 'titleText', 'translateWithId', 'type', 'warn', 'warnText'), filterValidAttributes(rest))), hasMultiValue ? /*#__PURE__*/React__default['default'].createElement("ul", {
"data-testid": "".concat(testId, "-tags"),
className: "".concat(iotPrefix$2h, "--combobox-tags")
}, tagItems.map(function (item, idx) {
return /*#__PURE__*/React__default['default'].createElement("li", {
key: "li-".concat(item === null || item === void 0 ? void 0 : item.id, "-").concat(idx)
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tag, {
key: "tag-".concat(item === null || item === void 0 ? void 0 : item.id, "-").concat(idx),
filter: true,
onClose: function onClose(e) {
return handleOnClose(e);
},
title: closeButtonText
}, itemToString(item)));
})) : null)
);
});
ComboBox.propTypes = propTypes$2o;
ComboBox.defaultProps = defaultProps$2u;
ComboBox.__docgenInfo = {
"description": "",
"methods": [],
"props": {
"loading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"wrapperClassName": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"closeButtonText": {
"defaultValue": {
"value": "'Close'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"editOptionText": {
"defaultValue": {
"value": "'Create'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"hasMultiValue": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"addToList": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"items": {
"defaultValue": {
"value": "[]",
"computed": false
},
"required": false
},
"onInputChange": {
"defaultValue": {
"value": "null",
"computed": false
},
"required": false
},
"onBlur": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'combo'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"menuFitContent": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"horizontalDirection": {
"defaultValue": {
"value": "'end'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'start'",
"computed": false
}, {
"value": "'end'",
"computed": false
}]
},
"required": false,
"description": ""
},
"onChange": {
"type": {
"name": "func"
},
"required": true,
"description": ""
}
},
"composes": ["carbon-components-react"]
};
var defineProperty$2 = objectDefineProperty.f;
var NativeSymbol = global$2.Symbol;
var SymbolPrototype = NativeSymbol && NativeSymbol.prototype;
if (descriptors && isCallable(NativeSymbol) && (!('description' in SymbolPrototype) ||
// Safari 12 bug
NativeSymbol().description !== undefined
)) {
var EmptyStringDescriptionStore = {};
// wrap Symbol constructor for correct work with undefined description
var SymbolWrapper = function Symbol() {
var description = arguments.length < 1 || arguments[0] === undefined ? undefined : toString$1(arguments[0]);
var result = objectIsPrototypeOf(SymbolPrototype, this)
? new NativeSymbol(description)
// in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
: description === undefined ? NativeSymbol() : NativeSymbol(description);
if (description === '') EmptyStringDescriptionStore[result] = true;
return result;
};
copyConstructorProperties(SymbolWrapper, NativeSymbol);
SymbolWrapper.prototype = SymbolPrototype;
SymbolPrototype.constructor = SymbolWrapper;
var NATIVE_SYMBOL = String(NativeSymbol('test')) == 'Symbol(test)';
var thisSymbolValue = functionUncurryThis(SymbolPrototype.valueOf);
var symbolDescriptiveString = functionUncurryThis(SymbolPrototype.toString);
var regexp = /^Symbol\((.*)\)[^)]+$/;
var replace$4 = functionUncurryThis(''.replace);
var stringSlice$3 = functionUncurryThis(''.slice);
defineProperty$2(SymbolPrototype, 'description', {
configurable: true,
get: function description() {
var symbol = thisSymbolValue(this);
if (hasOwnProperty_1(EmptyStringDescriptionStore, symbol)) return '';
var string = symbolDescriptiveString(symbol);
var desc = NATIVE_SYMBOL ? stringSlice$3(string, 7, -1) : replace$4(string, regexp, '$1');
return desc === '' ? undefined : desc;
}
});
_export({ global: true, constructor: true, forced: true }, {
Symbol: SymbolWrapper
});
}
var iotPrefix$2g = settings$1.iotPrefix,
prefix$w = settings$1.prefix;
var propTypes$2n = {
onClick: PropTypes__default['default'].func.isRequired,
testId: PropTypes__default['default'].string.isRequired,
renderIcon: PropTypes__default['default'].object.isRequired,
// eslint-disable-line react/forbid-prop-types
description: PropTypes__default['default'].node.isRequired,
/** is the button currently 'toggled' active, used for column filters */
isActive: PropTypes__default['default'].bool,
/** is the button disabled */
disabled: PropTypes__default['default'].bool,
tooltipAlignment: PropTypes__default['default'].oneOf(['start', 'center', 'end']),
tooltipPosition: PropTypes__default['default'].oneOf(['top', 'right', 'bottom', 'left']),
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl'])
};
var defaultProps$2t = {
isActive: false,
disabled: false,
tooltipAlignment: 'center',
tooltipPosition: 'bottom',
langDir: 'ltr'
};
/**
* Toolbar button that renders an icon only button
*/
var TableToolbarSVGButton = function TableToolbarSVGButton(_ref) {
var onClick = _ref.onClick,
testId = _ref.testId,
className = _ref.className,
description = _ref.description,
isActive = _ref.isActive,
tooltipAlignment = _ref.tooltipAlignment,
tooltipPosition = _ref.tooltipPosition,
langDir = _ref.langDir,
rest = objectWithoutProperties$1(_ref, ["onClick", "testId", "className", "description", "isActive", "tooltipAlignment", "tooltipPosition", "langDir"]);
var _useState = React$1.useState(tooltipAlignment),
_useState2 = slicedToArray$2(_useState, 2),
adjustedTooltipAlignment = _useState2[0],
setAdjustedTooltipAlignment = _useState2[1];
return /*#__PURE__*/React__default['default'].createElement(Button$1, _extends_1$1({}, rest, {
ref: function ref(node) {
/* istanbul ignore else */
if (node) {
var tooltip = node.querySelector(".".concat(prefix$w, "--assistive-text"));
if (!tooltip) {
return;
}
var childRect = tooltip.getBoundingClientRect();
var parentRect = node.parentElement.getBoundingClientRect();
/* istanbul ignore else */
if (langDir === 'ltr' && childRect.left + childRect.width > parentRect.left + parentRect.width) {
setAdjustedTooltipAlignment('end');
return;
}
/* istanbul ignore else */
if (langDir === 'rtl' && childRect.left < parentRect.left) {
setAdjustedTooltipAlignment('start');
}
}
},
className: classnames$1("".concat(prefix$w, "--btn--icon-only"), "".concat(iotPrefix$2g, "--tooltip-svg-wrapper"), className, defineProperty$d({}, "".concat(iotPrefix$2g, "--table-toolbar-button-active"), isActive)),
kind: "icon-selection",
onClick: onClick,
iconDescription: description,
testId: testId,
tooltipAlignment: adjustedTooltipAlignment,
tooltipPosition: tooltipPosition
}));
};
TableToolbarSVGButton.propTypes = propTypes$2n;
TableToolbarSVGButton.defaultProps = defaultProps$2t;
TableToolbarSVGButton.__docgenInfo = {
"description": "Toolbar button that renders an icon only button",
"methods": [],
"displayName": "TableToolbarSVGButton",
"props": {
"isActive": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the button currently 'toggled' active, used for column filters"
},
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the button disabled"
},
"tooltipAlignment": {
"defaultValue": {
"value": "'center'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'start'",
"computed": false
}, {
"value": "'center'",
"computed": false
}, {
"value": "'end'",
"computed": false
}]
},
"required": false,
"description": ""
},
"tooltipPosition": {
"defaultValue": {
"value": "'bottom'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'top'",
"computed": false
}, {
"value": "'right'",
"computed": false
}, {
"value": "'bottom'",
"computed": false
}, {
"value": "'left'",
"computed": false
}]
},
"required": false,
"description": ""
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": ""
},
"onClick": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"testId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"renderIcon": {
"type": {
"name": "object"
},
"required": true,
"description": ""
},
"description": {
"type": {
"name": "node"
},
"required": true,
"description": ""
}
}
};
function ownKeys$2a(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$2a(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2a(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$9() { 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 iotPrefix$2f = settings$1.iotPrefix,
prefix$v = settings$1.prefix;
var getFilterForState = function getFilterForState(filters, col) {
var appliedFilter = filters.find(function (i) {
return i.columnId === col.id;
});
if (appliedFilter && col.options && isEmptyString(appliedFilter.value)) {
return FILTER_EMPTY_STRING;
}
if (appliedFilter && !isNil(appliedFilter.value)) {
return appliedFilter.value;
}
return '';
};
var FilterHeaderRow = /*#__PURE__*/function (_Component) {
inherits(FilterHeaderRow, _Component);
var _super = _createSuper$9(FilterHeaderRow);
function FilterHeaderRow(props) {
var _this;
classCallCheck(this, FilterHeaderRow);
_this = _super.call(this, props);
defineProperty$d(assertThisInitialized(_this), "state", {
dropdownMaxHeight: 'unset',
filterValues: _this.props.columns.reduce(function (acc, curr) {
return _objectSpread$2a(_objectSpread$2a({}, acc), {}, defineProperty$d({}, curr.id, getFilterForState(_this.props.filters, curr)));
}, {}),
filterIconTopOffset: 96
});
defineProperty$d(assertThisInitialized(_this), "updateDropdownHeight", function () {
if (_this.rowRef.current) {
var tableContainer = _this.rowRef.current.closest(".".concat(prefix$v, "--data-table-content"));
var tableHead = _this.rowRef.current.closest("thead");
if (tableContainer) {
var _tableContainer$getBo = tableContainer.getBoundingClientRect(),
containerHeight = _tableContainer$getBo.height;
var _tableHead$getBoundin = tableHead.getBoundingClientRect(),
headHeight = _tableHead$getBoundin.height;
var height = containerHeight - headHeight - 16;
_this.setState({
dropdownMaxHeight: "".concat(height, "px")
});
}
}
});
defineProperty$d(assertThisInitialized(_this), "updateFilterIconPosition", function () {
/* istanbul ignore else */
if (!_this.props.tableOptions.hasFilterRowIcon) {
return;
}
/* istanbul ignore next */
if (_this.filterCellRef.current) {
var siblingTopOffset = _this.filterCellRef.current.getBoundingClientRect().top;
var tableTopOffset = _this.filterCellRef.current.closest(".".concat(iotPrefix$2f, "--table-container")).getBoundingClientRect().top;
_this.setState(function (prevState) {
if (_this.props.pinHeaderAndFooter) {
// Subtract 48px of toolbar height
return _objectSpread$2a(_objectSpread$2a({}, prevState), {}, {
filterIconTopOffset: siblingTopOffset - tableTopOffset - 48
});
}
return _objectSpread$2a(_objectSpread$2a({}, prevState), {}, {
filterIconTopOffset: siblingTopOffset - tableTopOffset
});
});
}
});
defineProperty$d(assertThisInitialized(_this), "setFirstFilterableRef", function (node) {
if (!_this.firstFilterableRef.current && node) {
_this.firstFilterableRef.current = node;
}
});
defineProperty$d(assertThisInitialized(_this), "updateFocus", function () {
if (_this.firstFilterableRef.current) {
if (typeof _this.firstFilterableRef.current.focus === 'function') {
_this.firstFilterableRef.current.focus();
} else if (typeof _this.firstFilterableRef.current.textInput.current.focus === 'function') {
_this.firstFilterableRef.current.textInput.current.focus();
}
}
});
defineProperty$d(assertThisInitialized(_this), "handleApplyFilter", function () {
var onApplyFilter = _this.props.onApplyFilter;
var filterValues = _this.state.filterValues;
onApplyFilter(filterValues);
});
defineProperty$d(assertThisInitialized(_this), "handleClearFilter", function (event, column) {
_this.setState(function (state) {
return {
filterValues: _objectSpread$2a(_objectSpread$2a({}, state.filterValues), {}, defineProperty$d({}, column.id, ''))
};
}, _this.handleApplyFilter);
});
defineProperty$d(assertThisInitialized(_this), "handleTranslation", function (idToTranslate) {
var _this$props = _this.props,
clearSelectionText = _this$props.clearSelectionText,
openMenuText = _this$props.openMenuText,
closeMenuText = _this$props.closeMenuText;
switch (idToTranslate) {
default:
return '';
case 'clear.selection':
return clearSelectionText;
case 'clear.all':
return clearSelectionText;
case 'open.menu':
return openMenuText;
case 'close.menu':
return closeMenuText;
}
});
_this.rowRef = /*#__PURE__*/React__default['default'].createRef();
_this.firstFilterableRef = /*#__PURE__*/React__default['default'].createRef();
_this.filterCellRef = /*#__PURE__*/React__default['default'].createRef();
return _this;
}
createClass(FilterHeaderRow, [{
key: "componentDidMount",
value: function componentDidMount() {
this.updateDropdownHeight();
this.updateFocus();
this.updateFilterIconPosition();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var dropdownMaxHeight = this.state.dropdownMaxHeight;
var size = this.props.size;
if (dropdownMaxHeight !== prevState.dropdownMaxHeight || size !== prevProps.size) {
this.updateDropdownHeight();
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props2 = this.props,
columns = _this$props2.columns,
ordering = _this$props2.ordering,
clearFilterText = _this$props2.clearFilterText,
filterText = _this$props2.filterText,
_this$props2$tableOpt = _this$props2.tableOptions,
hasRowSelection = _this$props2$tableOpt.hasRowSelection,
hasRowExpansion = _this$props2$tableOpt.hasRowExpansion,
hasRowNesting = _this$props2$tableOpt.hasRowNesting,
hasRowActions = _this$props2$tableOpt.hasRowActions,
useRadioButtonSingleSelect = _this$props2$tableOpt.useRadioButtonSingleSelect,
hasFilterRowIcon = _this$props2$tableOpt.hasFilterRowIcon,
hasResize = _this$props2$tableOpt.hasResize,
isVisible = _this$props2.isVisible,
lightweight = _this$props2.lightweight,
isDisabled = _this$props2.isDisabled,
hasFastFilter = _this$props2.hasFastFilter,
testId = _this$props2.testId,
showExpanderColumn = _this$props2.showExpanderColumn,
langDir = _this$props2.langDir,
showColumnGroups = _this$props2.showColumnGroups,
filterRowIcon = _this$props2.filterRowIcon,
filterRowIconDescription = _this$props2.filterRowIconDescription,
onFilterRowIconClick = _this$props2.onFilterRowIconClick,
hasDragAndDrop = _this$props2.hasDragAndDrop;
var _this$state = this.state,
dropdownMaxHeight = _this$state.dropdownMaxHeight,
filterValues = _this$state.filterValues,
filterIconTopOffset = _this$state.filterIconTopOffset;
var visibleColumns = ordering.filter(function (c) {
return !c.isHidden;
});
return isVisible ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
"data-testid": testId,
style: {
'--filter-header-dropdown-max-height': dropdownMaxHeight
}
}, hasDragAndDrop && /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2f, "--filter-header-row--header")
}), hasRowSelection === 'multi' || hasRowSelection === 'single' && useRadioButtonSingleSelect ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2f, "--filter-header-row--header"),
ref: this.rowRef
}) : null, hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2f, "--filter-header-row--header")
}) : null, visibleColumns.map(function (c, i) {
var _classnames3, _classnames4;
var column = columns.find(function (item) {
return c.columnId === item.id;
});
var columnStateValue = filterValues[column.id]; // eslint-disable-line react/destructuring-assignment
var filterColumnOptions = function filterColumnOptions(options) {
options.sort(function (a, b) {
return a.text.localeCompare(b.text, {
sensitivity: 'base'
});
});
return options;
};
var memoizeColumnOptions = memoize$1(filterColumnOptions); // TODO: this memoize isn't really working, should refactor to a higher column level
var isLastColumn = visibleColumns.length - 1 === i;
var lastVisibleColumn = visibleColumns.slice(-1)[0];
var isLastVisibleColumn = column.id === lastVisibleColumn.columnId; // undefined check has the effect of making isFilterable default to true
// if unspecified
var headerContent = column.isFilterable !== undefined && !column.isFilterable ? /*#__PURE__*/React__default['default'].createElement("div", null) : column.options ? column.isMultiselect ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.FilterableMultiSelect, {
ref: _this2.setFirstFilterableRef,
key: columnStateValue,
className: classnames$1("".concat(iotPrefix$2f, "--filterheader-multiselect"), "".concat(iotPrefix$2f, "--filterheader-multiselect__menu--fit-content"), defineProperty$d({}, "".concat(iotPrefix$2f, "--filterheader-multiselect__menu--flip-horizontal"), isLastColumn)),
id: "column-".concat(i),
"aria-label": filterText,
placeholder: column.placeholderText || 'Choose an option',
translateWithId: _this2.handleTranslation,
items: memoizeColumnOptions(column.options),
label: column.placeholderText || 'Choose an option',
itemToString: function itemToString(item) {
return item.text;
},
initialSelectedItems: getMultiSelectItems(column, columnStateValue),
onChange: function onChange(evt) {
_this2.setState(function (state) {
return {
filterValues: _objectSpread$2a(_objectSpread$2a({}, state.filterValues), {}, defineProperty$d({}, column.id, evt.selectedItems.map(getMultiselectFilterValue)))
};
}, _this2.handleApplyFilter);
},
light: true,
disabled: isDisabled
}) : /*#__PURE__*/React__default['default'].createElement(ComboBox, {
ref: _this2.setFirstFilterableRef,
menuFitContent: true,
horizontalDirection: isLastColumn ? 'start' : 'end',
key: columnStateValue,
className: "".concat(iotPrefix$2f, "--filterheader-combo"),
id: "column-".concat(i),
"aria-label": filterText,
translateWithId: _this2.handleTranslation,
items: memoizeColumnOptions(column.options),
itemToString: function itemToString(item) {
return item ? item.text : '';
},
initialSelectedItem: {
id: columnStateValue,
text: getAppliedFilterText(column, columnStateValue)
},
placeholder: column.placeholderText || 'Choose an option',
onChange: function onChange(selectedItem) {
_this2.setState(function (state) {
return {
filterValues: _objectSpread$2a(_objectSpread$2a({}, state.filterValues), {}, defineProperty$d({}, column.id, getFilterValue(selectedItem)))
};
}, _this2.handleApplyFilter);
},
light: lightweight,
disabled: isDisabled
}) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.FormItem, {
className: "".concat(iotPrefix$2f, "--filter-header-row--form-item")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TextInput, {
ref: _this2.setFirstFilterableRef,
id: column.id,
labelText: column.id,
hideLabel: true,
light: lightweight,
placeholder: column.placeholderText || 'Type and hit enter to apply',
title: filterValues[column.id] || column.placeholderText // eslint-disable-line react/destructuring-assignment
,
onChange: function onChange(event) {
event.persist();
_this2.setState(function (state) {
return {
filterValues: _objectSpread$2a(_objectSpread$2a({}, state.filterValues), {}, defineProperty$d({}, column.id, event.target.value))
};
}, hasFastFilter ? debounce(_this2.handleApplyFilter, 150) : null // only apply the filter at debounced interval
);
},
onKeyDown: !hasFastFilter ? function (event) {
return handleEnterKeyDown(event, _this2.handleApplyFilter);
} : null // if fast filter off, then filter on key press
,
onBlur: !hasFastFilter ? _this2.handleApplyFilter : null // if fast filter off, then filter on blur
,
value: filterValues[column.id] // eslint-disable-line react/destructuring-assignment
,
disabled: isDisabled
}), filterValues[column.id] ?
/*#__PURE__*/
// eslint-disable-line react/destructuring-assignment
React__default['default'].createElement("div", {
role: "button",
className: classnames$1("".concat(prefix$v, "--list-box__selection"), defineProperty$d({}, "".concat(iotPrefix$2f, "--clear-filters-button--disabled"), isDisabled)),
tabIndex: isDisabled ? '-1' : '0',
onMouseDown: function onMouseDown(event) {
return event.preventDefault();
},
onClick: function onClick(event) {
if (!isDisabled) {
_this2.handleClearFilter(event, column);
}
},
onKeyDown: function onKeyDown(event) {
return handleEnterKeyDown(event, function () {
if (!isDisabled) {
_this2.handleClearFilter(event, column);
}
});
},
title: clearFilterText
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Close16, {
description: clearFilterText
})) : null);
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: classnames$1("".concat(iotPrefix$2f, "--tableheader-filter"), "".concat(iotPrefix$2f, "--filter-header-row--header"), (_classnames3 = {}, defineProperty$d(_classnames3, "".concat(iotPrefix$2f, "--filter-header-row--header-width"), column.width === undefined), defineProperty$d(_classnames3, "".concat(iotPrefix$2f, "--filter-header-row--last-column"), isLastVisibleColumn), defineProperty$d(_classnames3, "".concat(iotPrefix$2f, "--filter-header-row--with-icon"), isLastVisibleColumn && hasFilterRowIcon), defineProperty$d(_classnames3, "".concat(iotPrefix$2f, "--filter-header-row--with-margin"), isLastVisibleColumn && hasFilterRowIcon && (!showColumnGroups || !hasRowActions)), _classnames3)),
"data-column": column.id,
key: "FilterHeader".concat(column.id),
width: column.width,
ref: isLastVisibleColumn ? _this2.filterCellRef : undefined
}, headerContent, hasFilterRowIcon && isLastVisibleColumn ? /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
testId: "filter-row-icon",
className: classnames$1("".concat(iotPrefix$2f, "--filter-header-icon"), (_classnames4 = {}, defineProperty$d(_classnames4, "".concat(iotPrefix$2f, "--filter-header-icon--with-border"), hasResize && showColumnGroups && !hasRowActions), defineProperty$d(_classnames4, "".concat(iotPrefix$2f, "--filter-header-icon--with-margin"), hasRowActions), _classnames4)),
description: filterRowIconDescription,
onClick: onFilterRowIconClick,
renderIcon: filterRowIcon,
size: "field",
style: {
top: "".concat(filterIconTopOffset, "px")
},
tooltipAlignment: langDir === 'ltr' ? 'end' : 'start'
}), hasRowActions ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$2f, "--filter-header-row--icon-support"),
style: {
top: "".concat(filterIconTopOffset, "px")
}
}) : null) : null);
}), hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
className: "".concat(iotPrefix$2f, "--filter-header-row--header")
}) : null, showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHeader, {
"data-testid": "".concat(testId, "-expander-column"),
className: "".concat(iotPrefix$2f, "--filter-header-row--header")
}) : null) : null;
}
}], [{
key: "getDerivedStateFromProps",
value: // TODO: we should really do this through a useEffect hook when we refactor to functional component
function getDerivedStateFromProps(props, state) {
// If the filter props change from the outside, we need to reset the filterValues inside local state
if (!isEqual$1(props.filters, state.prevPropsFilters)) {
var newFilters = props.columns.reduce(function (acc, curr) {
return _objectSpread$2a(_objectSpread$2a({}, acc), {}, defineProperty$d({}, curr.id, getFilterForState(props.filters, curr)));
}, {});
if (!isEqual$1(newFilters, state.filterValues)) {
return {
filterValues: newFilters,
prevPropsFilters: props.filters
};
} // Need to store the updated filters from before
return {
prevPropsFilters: props.filters
};
}
return null;
}
}]);
return FilterHeaderRow;
}(React$1.Component);
defineProperty$d(FilterHeaderRow, "propTypes", {
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string,
/** When false, no filter shows */
isFilterable: PropTypes__default['default'].bool,
/** i18N text for translation */
placeholderText: PropTypes__default['default'].string,
/** if options is empty array, assume text input for filter */
options: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool]).isRequired,
text: PropTypes__default['default'].string.isRequired
})),
/** if isMultiselect and isFilterable are true, the table is filtered based on a multiselect */
isMultiselect: PropTypes__default['default'].bool
})).isRequired,
/** internationalized string */
filterText: PropTypes__default['default'].string,
clearFilterText: PropTypes__default['default'].string,
clearSelectionText: PropTypes__default['default'].string,
openMenuText: PropTypes__default['default'].string,
closeMenuText: PropTypes__default['default'].string,
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
filters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
value: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool, PropTypes__default['default'].arrayOf(PropTypes__default['default'].string)]).isRequired
})),
/** Callback when filter is applied sends object of keys and values with the filter values */
onApplyFilter: PropTypes__default['default'].func,
/** properties global to the table */
tableOptions: PropTypes__default['default'].shape({
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].bool,
hasRowActions: PropTypes__default['default'].bool,
useRadioButtonSingleSelect: PropTypes__default['default'].bool,
hasFilterRowIcon: PropTypes__default['default'].bool,
hasResize: PropTypes__default['default'].bool
}),
/** filter can be hidden by the user but filters will still apply to the table */
isVisible: PropTypes__default['default'].bool,
/** disabled filters are shown and active but cannot be modified */
isDisabled: PropTypes__default['default'].bool,
lightweight: PropTypes__default['default'].bool,
/** should we filter as the user types or after they press enter */
hasFastFilter: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool.isRequired,
/** Size prop from Carbon to shrink row height (and header height in some instances) */
size: function checkProps(props, propName, componentName) {
if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {
warning_1(false, "The value `".concat(props[propName], "` has been deprecated for the ") + "`".concat(propName, "` prop on the ").concat(componentName, " component. It will be removed in the next major ") + "release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.") ;
}
},
/** language direction for current table */
langDir: PropTypes__default['default'].oneOf(['rtl', 'ltr']),
/** indicator if columns have grouping */
showColumnGroups: PropTypes__default['default'].bool,
/** icon element for filter row icon */
filterRowIcon: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].object]),
/** tooltip text for filter row icon button */
filterRowIconDescription: PropTypes__default['default'].string,
/** call back function for when icon button in filter row is clicked (evt) => {} */
onFilterRowIconClick: PropTypes__default['default'].func.isRequired,
/** Freezes table header and footer */
pinHeaderAndFooter: PropTypes__default['default'].bool,
/** Set to true if the table support drag and drop. Inserts a cell in the "drag handle" column
* for spacing. */
hasDragAndDrop: PropTypes__default['default'].bool
});
defineProperty$d(FilterHeaderRow, "defaultProps", {
tableOptions: {
hasRowSelection: 'multi'
},
filters: [],
isVisible: true,
isDisabled: false,
onApplyFilter: defaultFunction,
filterText: 'Filter',
clearFilterText: 'Clear filter',
clearSelectionText: 'Clear selection',
openMenuText: 'Open menu',
closeMenuText: 'Close menu',
lightweight: false,
hasFastFilter: true,
testId: '',
size: undefined,
langDir: 'ltr',
showColumnGroups: false,
filterRowIcon: null,
filterRowIconDescription: 'Edit filters',
pinHeaderAndFooter: false,
hasDragAndDrop: false
});
FilterHeaderRow.__docgenInfo = {
"description": "",
"methods": [{
"name": "updateDropdownHeight",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "updateFilterIconPosition",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "setFirstFilterableRef",
"docblock": null,
"modifiers": [],
"params": [{
"name": "node",
"type": null
}],
"returns": null
}, {
"name": "updateFocus",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "handleApplyFilter",
"docblock": "take the state with the filter values and send to our listener",
"modifiers": [],
"params": [],
"returns": null,
"description": "take the state with the filter values and send to our listener"
}, {
"name": "handleClearFilter",
"docblock": null,
"modifiers": [],
"params": [{
"name": "event",
"type": null
}, {
"name": "column",
"type": null
}],
"returns": null
}, {
"name": "handleTranslation",
"docblock": null,
"modifiers": [],
"params": [{
"name": "idToTranslate",
"type": null
}],
"returns": null
}],
"displayName": "FilterHeaderRow",
"props": {
"tableOptions": {
"defaultValue": {
"value": "{ hasRowSelection: 'multi' }",
"computed": false
},
"type": {
"name": "shape",
"value": {
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"hasRowExpansion": {
"name": "bool",
"required": false
},
"hasRowNesting": {
"name": "bool",
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
},
"useRadioButtonSingleSelect": {
"name": "bool",
"required": false
},
"hasFilterRowIcon": {
"name": "bool",
"required": false
},
"hasResize": {
"name": "bool",
"required": false
}
}
},
"required": false,
"description": "properties global to the table"
},
"filters": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}, {
"name": "arrayOf",
"value": {
"name": "string"
}
}],
"required": true
}
}
}
},
"required": false,
"description": ""
},
"isVisible": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "filter can be hidden by the user but filters will still apply to the table"
},
"isDisabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "disabled filters are shown and active but cannot be modified"
},
"onApplyFilter": {
"defaultValue": {
"value": "defaultFunction",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback when filter is applied sends object of keys and values with the filter values"
},
"filterText": {
"defaultValue": {
"value": "'Filter'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized string"
},
"clearFilterText": {
"defaultValue": {
"value": "'Clear filter'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"clearSelectionText": {
"defaultValue": {
"value": "'Clear selection'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"openMenuText": {
"defaultValue": {
"value": "'Open menu'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"closeMenuText": {
"defaultValue": {
"value": "'Close menu'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"lightweight": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasFastFilter": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "should we filter as the user types or after they press enter"
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "function checkProps(props, propName, componentName) {\n if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {\n warning(\n false,\n `The value \\`${props[propName]}\\` has been deprecated for the ` +\n `\\`${propName}\\` prop on the ${componentName} component. It will be removed in the next major ` +\n `release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.`\n );\n }\n}"
},
"required": false,
"description": "Size prop from Carbon to shrink row height (and header height in some instances)"
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'rtl'",
"computed": false
}, {
"value": "'ltr'",
"computed": false
}]
},
"required": false,
"description": "language direction for current table"
},
"showColumnGroups": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "indicator if columns have grouping"
},
"filterRowIcon": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "object"
}]
},
"required": false,
"description": "icon element for filter row icon"
},
"filterRowIconDescription": {
"defaultValue": {
"value": "'Edit filters'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "tooltip text for filter row icon button"
},
"pinHeaderAndFooter": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Freezes table header and footer"
},
"hasDragAndDrop": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Set to true if the table support drag and drop. Inserts a cell in the \"drag handle\" column\nfor spacing."
},
"columns": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": false
},
"isFilterable": {
"name": "bool",
"description": "When false, no filter shows",
"required": false
},
"placeholderText": {
"name": "string",
"description": "i18N text for translation",
"required": false
},
"options": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}],
"required": true
},
"text": {
"name": "string",
"required": true
}
}
},
"description": "if options is empty array, assume text input for filter",
"required": false
},
"isMultiselect": {
"name": "bool",
"description": "if isMultiselect and isFilterable are true, the table is filtered based on a multiselect",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"showExpanderColumn": {
"type": {
"name": "bool"
},
"required": true,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"onFilterRowIconClick": {
"type": {
"name": "func"
},
"required": true,
"description": "call back function for when icon button in filter row is clicked (evt) => {}"
}
}
};
var _sortDirections;
function ownKeys$29(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$29(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$29(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$29(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var sortStates = {
NONE: 'NONE',
DESC: 'DESC',
ASC: 'ASC'
};
var prefix$u = settings$1.prefix,
iotPrefix$2e = settings$1.iotPrefix;
var translationKeys = {
iconDescription: 'carbon.table.header.icon.description'
};
var translateWithId = function translateWithId(key, _ref) {
var sortDirection = _ref.sortDirection,
isSortHeader = _ref.isSortHeader;
if (key === translationKeys.iconDescription) {
if (isSortHeader) {
// When transitioning, we know that the sequence of states is as follows:
// NONE -> ASC -> DESC -> NONE
if (sortDirection === sortStates.NONE) {
return 'Sort rows by this header in ascending order';
}
if (sortDirection === sortStates.ASC) {
return 'Sort rows by this header in descending order';
}
return 'Un sort rows by this header';
}
return 'Sort rows by this header in ascending order';
}
return '';
};
var sortDirections = (_sortDirections = {}, defineProperty$d(_sortDirections, sortStates.NONE, 'none'), defineProperty$d(_sortDirections, sortStates.ASC, 'ascending'), defineProperty$d(_sortDirections, sortStates.DESC, 'descending'), _sortDirections);
var TableHeader = /*#__PURE__*/React__default['default'].forwardRef(function TableHeader(_ref2, ref) {
var _classnames2;
var headerClassName = _ref2.className,
children = _ref2.children,
isSortable = _ref2.isSortable,
isSortHeader = _ref2.isSortHeader,
onClick = _ref2.onClick,
scope = _ref2.scope,
hasMultiSort = _ref2.hasMultiSort,
hasOverflow = _ref2.hasOverflow,
hasTooltip = _ref2.hasTooltip,
sortDirection = _ref2.sortDirection,
t = _ref2.translateWithId,
thStyle = _ref2.thStyle,
initialWidth = _ref2.initialWidth,
testId = _ref2.testId,
spanGroupRow = _ref2.spanGroupRow,
rowSpanProp = _ref2.rowSpan,
rest = objectWithoutProperties$1(_ref2, ["className", "children", "isSortable", "isSortHeader", "onClick", "scope", "hasMultiSort", "hasOverflow", "hasTooltip", "sortDirection", "translateWithId", "thStyle", "initialWidth", "testId", "spanGroupRow", "rowSpan"]);
var rowSpan = (rowSpanProp !== null && rowSpanProp !== void 0 ? rowSpanProp : spanGroupRow) ? '2' : undefined;
var headerClassNames = classnames$1(headerClassName, defineProperty$d({}, "".concat(iotPrefix$2e, "--table-header--span-group-row"), spanGroupRow));
if (!isSortable) {
return (
/*#__PURE__*/
// eslint-disable-next-line react/jsx-filename-extension
React__default['default'].createElement("th", _extends_1$1({}, rest, {
rowSpan: rowSpan,
"data-testid": testId,
width: initialWidth,
className: headerClassNames,
scope: scope,
ref: ref,
style: thStyle
}), !hasTooltip ? /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(prefix$u, "--table-header-label")
}, children) : children)
);
}
var className = classnames$1(headerClassName, (_classnames2 = {}, defineProperty$d(_classnames2, "".concat(prefix$u, "--table-sort"), true), defineProperty$d(_classnames2, "".concat(prefix$u, "--table-sort--active"), isSortHeader && sortDirection !== sortStates.NONE), defineProperty$d(_classnames2, "".concat(prefix$u, "--table-sort--ascending"), isSortHeader && sortDirection === sortStates.DESC), _classnames2));
var ariaSort = !isSortHeader ? 'none' : sortDirections[sortDirection];
var ButtonTag = hasMultiSort || hasOverflow ? "a" : "button";
var buttonProps = hasMultiSort || hasOverflow ? _objectSpread$29({
role: 'button',
tabIndex: 0,
className: className,
onClick: onClick,
onKeyDown: handleSpecificKeyDown(['Enter', 'Space'], onClick)
}, rest) : _objectSpread$29({
className: className,
onClick: onClick
}, rest);
return /*#__PURE__*/React__default['default'].createElement("th", {
rowSpan: rowSpan,
width: initialWidth,
scope: scope,
className: headerClassNames,
"aria-sort": ariaSort,
ref: ref,
style: thStyle,
"data-testid": testId
}, /*#__PURE__*/React__default['default'].createElement(ButtonTag, buttonProps, !hasTooltip ? /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(prefix$u, "--table-header-label")
}, children) : children, /*#__PURE__*/React__default['default'].createElement(iconsReact.ArrowUp16, {
className: "".concat(prefix$u, "--table-sort__icon"),
"aria-label": t('carbon.table.header.icon.description', {
header: children,
sortDirection: sortDirection,
isSortHeader: isSortHeader,
sortStates: sortStates
})
}), /*#__PURE__*/React__default['default'].createElement(iconsReact.ArrowsVertical16, {
className: "".concat(prefix$u, "--table-sort__icon-unsorted"),
"aria-label": t('carbon.table.header.icon.description', {
header: children,
sortDirection: sortDirection,
isSortHeader: isSortHeader,
sortStates: sortStates
})
})));
});
TableHeader.propTypes = {
/**
* Specify an optional className to be applied to the container node
*/
className: PropTypes__default['default'].string,
/**
* Pass in children that will be embedded in the table header label
*/
children: PropTypes__default['default'].node,
/**
* True if the header must span the column group row.
*/
spanGroupRow: PropTypes__default['default'].bool,
hasOverflow: PropTypes__default['default'].bool,
hasMultiSort: PropTypes__default['default'].bool,
/** does the header have a tooltip, if so do not truncate */
hasTooltip: PropTypes__default['default'].bool,
/**
* The initial width of the column when hasResize:true. The fixed width
* if hasResize:false. E.g. '200px'
*/
initialWidth: PropTypes__default['default'].string,
/**
* Specify whether this header is one through which a user can sort the table
*/
isSortable: PropTypes__default['default'].bool,
/**
* Specify whether this header is the header by which a table is being sorted
* by
*/
isSortHeader: PropTypes__default['default'].bool,
/**
* Hook that is invoked when the header is clicked
*/
onClick: PropTypes__default['default'].func,
/** Applies the HTML attribute rowspan with the number provided */
rowSpan: PropTypes__default['default'].number,
/**
* Specify the scope of this table header. You can find more info about this
* attribute at the following URL:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th#attr-scope
*/
scope: PropTypes__default['default'].string,
/**
* Specify which direction we are currently sorting by, should be one of DESC,
* NONE, or ASC.
*/
sortDirection: PropTypes__default['default'].oneOf(Object.values(sortStates)),
/**
* Supply a method to translate internal strings with your i18n tool of
* choice. Translation keys are available on the `translationKeys` field for
* this component.
*/
translateWithId: PropTypes__default['default'].func,
// eslint-disable-next-line react/forbid-prop-types
thStyle: PropTypes__default['default'].object,
testId: PropTypes__default['default'].string
};
/* istanbul ignore next: ignoring the default onClick */
TableHeader.defaultProps = {
className: '',
children: '',
spanGroupRow: false,
isSortHeader: false,
hasTooltip: false,
hasOverflow: false,
hasMultiSort: false,
isSortable: false,
rowSpan: undefined,
sortDirection: 'NONE',
onClick: function onClick(_onClick) {
return "".concat(_onClick);
},
scope: 'col',
translateWithId: translateWithId,
thStyle: {},
initialWidth: undefined,
testId: ''
};
TableHeader.translationKeys = Object.values(translationKeys);
TableHeader.displayName = 'TableHeader';
TableHeader.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableHeader",
"props": {
"className": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Specify an optional className to be applied to the container node"
},
"children": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "Pass in children that will be embedded in the table header label"
},
"spanGroupRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "True if the header must span the column group row."
},
"isSortHeader": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Specify whether this header is the header by which a table is being sorted\nby"
},
"hasTooltip": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "does the header have a tooltip, if so do not truncate"
},
"hasOverflow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasMultiSort": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"isSortable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Specify whether this header is one through which a user can sort the table"
},
"rowSpan": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "number"
},
"required": false,
"description": "Applies the HTML attribute rowspan with the number provided"
},
"sortDirection": {
"defaultValue": {
"value": "'NONE'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "\"ASC\"",
"computed": false
}, {
"value": "\"DESC\"",
"computed": false
}, {
"value": "\"NONE\"",
"computed": false
}]
},
"required": false,
"description": "Specify which direction we are currently sorting by, should be one of DESC,\nNONE, or ASC."
},
"onClick": {
"defaultValue": {
"value": "(onClick) => `${onClick}`",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Hook that is invoked when the header is clicked"
},
"scope": {
"defaultValue": {
"value": "'col'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Specify the scope of this table header. You can find more info about this\nattribute at the following URL:\nhttps://developer.mozilla.org/en-US/docs/Web/HTML/Element/th#attr-scope"
},
"translateWithId": {
"defaultValue": {
"value": "(key, { sortDirection, isSortHeader }) => {\n if (key === translationKeys.iconDescription) {\n if (isSortHeader) {\n // When transitioning, we know that the sequence of states is as follows:\n // NONE -> ASC -> DESC -> NONE\n if (sortDirection === sortStates.NONE) {\n return 'Sort rows by this header in ascending order';\n }\n if (sortDirection === sortStates.ASC) {\n return 'Sort rows by this header in descending order';\n }\n\n return 'Un sort rows by this header';\n }\n return 'Sort rows by this header in ascending order';\n }\n\n return '';\n}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Supply a method to translate internal strings with your i18n tool of\nchoice. Translation keys are available on the `translationKeys` field for\nthis component."
},
"thStyle": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "object"
},
"required": false,
"description": ""
},
"initialWidth": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "The initial width of the column when hasResize:true. The fixed width\nif hasResize:false. E.g. '200px'"
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
}
}
};
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys$1(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty$1.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol$2 ? Symbol$2.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/** `Object#toString` result references. */
var boolTag$1 = '[object Boolean]',
dateTag$1 = '[object Date]',
mapTag$2 = '[object Map]',
numberTag$1 = '[object Number]',
regexpTag$1 = '[object RegExp]',
setTag$2 = '[object Set]',
stringTag$1 = '[object String]',
symbolTag$1 = '[object Symbol]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
dataViewTag$1 = '[object DataView]',
float32Tag$1 = '[object Float32Array]',
float64Tag$1 = '[object Float64Array]',
int8Tag$1 = '[object Int8Array]',
int16Tag$1 = '[object Int16Array]',
int32Tag$1 = '[object Int32Array]',
uint8Tag$1 = '[object Uint8Array]',
uint8ClampedTag$1 = '[object Uint8ClampedArray]',
uint16Tag$1 = '[object Uint16Array]',
uint32Tag$1 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$1:
return cloneArrayBuffer(object);
case boolTag$1:
case dateTag$1:
return new Ctor(+object);
case dataViewTag$1:
return cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return cloneTypedArray(object, isDeep);
case mapTag$2:
return new Ctor;
case numberTag$1:
case stringTag$1:
return new Ctor(object);
case regexpTag$1:
return cloneRegExp(object);
case setTag$2:
return new Ctor;
case symbolTag$1:
return cloneSymbol(object);
}
}
/** `Object#toString` result references. */
var mapTag$1 = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike$1(value) && getTag$1(value) == mapTag$1;
}
/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/** `Object#toString` result references. */
var setTag$1 = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike$1(value) && getTag$1(value) == setTag$1;
}
/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$2 = 1,
CLONE_FLAT_FLAG$1 = 2,
CLONE_SYMBOLS_FLAG$2 = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG$2,
isFlat = bitmask & CLONE_FLAT_FLAG$1,
isFull = bitmask & CLONE_SYMBOLS_FLAG$2;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject$1(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag$1(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys$1);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1,
CLONE_SYMBOLS_FLAG$1 = 4;
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
}
var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
// eslint-disable-next-line es/no-string-prototype-endswith -- safe
var nativeEndsWith = functionUncurryThisClause(''.endsWith);
var slice$5 = functionUncurryThisClause(''.slice);
var min$6 = Math.min;
var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('endsWith');
// https://github.com/zloirock/core-js/pull/702
var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () {
var descriptor = getOwnPropertyDescriptor$2(String.prototype, 'endsWith');
return descriptor && !descriptor.writable;
}();
// `String.prototype.endsWith` method
// https://tc39.es/ecma262/#sec-string.prototype.endswith
_export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
endsWith: function endsWith(searchString /* , endPosition = @length */) {
var that = toString$1(requireObjectCoercible(this));
notARegexp(searchString);
var endPosition = arguments.length > 1 ? arguments[1] : undefined;
var len = that.length;
var end = endPosition === undefined ? len : min$6(toLength(endPosition), len);
var search = toString$1(searchString);
return nativeEndsWith
? nativeEndsWith(that, search, end)
: slice$5(that, end - search.length, end) === search;
}
});
// `Number.isNaN` method
// https://tc39.es/ecma262/#sec-number.isnan
_export({ target: 'Number', stat: true }, {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare -- NaN check
return number != number;
}
});
function ownKeys$28(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$28(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$28(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$28(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
* Utility functions related to the measurement and calculation
* of a table's column widths.
*/
// This width must be able to fit the elipsis of a truncated text + sort arrows + combobox dropdown (for filter)
var MIN_COLUMN_WIDTH = 120; // This width can be used when adding a new column without a width.
var DEFAULT_COLUMN_WIDTH = 150;
var isColumnVisible = function isColumnVisible(ordering, columnId) {
var orderedColumn = ordering.find(function (orderedCol) {
return orderedCol.columnId === columnId;
});
return orderedColumn && !orderedColumn.isHidden;
};
function getTotalWidth(cols) {
return cols.reduce(function (width, col) {
return width + col.width;
}, 0);
}
function createWidthsMap(ordering, columnWidths, adjustedCols) {
var newColumnWidths = {};
ordering.forEach(function (orderedColumn) {
var current = Array.isArray(columnWidths) ? columnWidths.find(function (col) {
return col.id === orderedColumn.columnId;
}) : columnWidths[orderedColumn.columnId];
newColumnWidths[orderedColumn.columnId] = {
width: current && current.width !== undefined ? parseInt(current.width, 10) : undefined,
id: orderedColumn.columnId
};
});
adjustedCols.forEach(function (col) {
newColumnWidths[col.id].width = col.width;
});
return newColumnWidths;
}
function getVisibleColumns(currentColumnWidths, ordering, excludeIDs) {
return Object.values(currentColumnWidths).filter(function (col) {
return col.width !== undefined && !excludeIDs.includes(col.id) && isColumnVisible(ordering, col.id);
});
}
var getOriginalWidthOfColumn = function getOriginalWidthOfColumn(origColumns, colId) {
var orginalWidth = origColumns.find(function (col) {
return col.id === colId;
}).width;
return orginalWidth ? parseInt(orginalWidth, 10) : undefined;
};
function getExistingColumnWidth(currentColumnWidths, origColumns, colId) {
var _currentColumnWidths$;
var currentColumnWidth = (_currentColumnWidths$ = currentColumnWidths[colId]) === null || _currentColumnWidths$ === void 0 ? void 0 : _currentColumnWidths$.width; // If the column to show was hidden on init it will not have a current width
// since it has not been rendered and measured. Then we try to get the original width.
return currentColumnWidth || getOriginalWidthOfColumn(origColumns, colId);
}
function getAverageVisibleColumnWidth(visibleColumns) {
var totalCurrentWidth = getTotalWidth(visibleColumns);
return totalCurrentWidth / visibleColumns.length;
}
function shrinkColumns(shrinkableColumns, widthOfColumnToShow) {
var availableWidth = getTotalWidth(shrinkableColumns);
var shrunkenColumns = shrinkableColumns.map(function (col) {
var preferredNewWidth = (availableWidth - widthOfColumnToShow) / shrinkableColumns.length;
var newWidth = preferredNewWidth >= MIN_COLUMN_WIDTH ? preferredNewWidth : MIN_COLUMN_WIDTH;
return {
id: col.id,
width: Math.round(newWidth)
};
});
return shrunkenColumns;
}
function adjustColumnsBelowMinWidth(measuredWidth) {
return measuredWidth.map(function (widthObj) {
return widthObj.width < MIN_COLUMN_WIDTH ? _objectSpread$28(_objectSpread$28({}, widthObj), {}, {
width: DEFAULT_COLUMN_WIDTH
}) : widthObj;
});
}
/**
* Warns the developer in DEV mode if a column width is of incorrect format.
* @param {array} columns The table column props
*/
var checkColumnWidthFormat = function checkColumnWidthFormat(columns) {
columns.forEach(function (col) {
if (col.hasOwnProperty('width') && col.width !== undefined) {
if (typeof col.width !== 'string' || !col.width.endsWith('px') || Number.isNaN(parseInt(col.width, 10))) {
warning_1(!("development" !== "production"), "Column width should be a string containing the width and the pixel unit\n e.g. '100px' or have the value undefined.") ;
}
}
});
};
/**
* Returns an array of the IDs of all columns that exists in the
* currentColumnWidths map but not in the ordering prop.
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {object} currentColumnWidths map of the current column IDs and widths
*/
var getIDsOfRemovedColumns = function getIDsOfRemovedColumns(ordering, currentColumnWidths) {
return Object.values(currentColumnWidths).filter(function (currCol) {
return !ordering.find(function (orderCol) {
return orderCol.columnId === currCol.id;
});
}).map(function (col) {
return col.id;
});
};
/**
* Returns an array of the IDs of all columns that exists in the
* ordering prop but not in the currentColumnWidths map.
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {object} currentColumnWidths map of the current column IDs and widths
*/
var getIDsOfAddedVisibleColumns = function getIDsOfAddedVisibleColumns(ordering, currentColumnWidths) {
return ordering.filter(function (col) {
return !col.isHidden;
}).filter(function (col) {
return !currentColumnWidths.hasOwnProperty(col.columnId);
}).map(function (col) {
return col.columnId;
});
};
/**
* Returns true if there are visible columns
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
*/
var hasVisibleColumns = function hasVisibleColumns(ordering) {
return ordering.some(function (col) {
return !col.isHidden;
});
};
/**
* Returns true if all visible columns have a width.
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {array} columns The table column props
*/
var visibleColumnsHaveWidth = function visibleColumnsHaveWidth(ordering, columns) {
return columns.filter(function (col) {
return isColumnVisible(ordering, col.id);
}).every(function (col) {
return col.hasOwnProperty('width') && col.width !== undefined;
});
};
var addDefaultWidthToNewVisibleColumns = function addDefaultWidthToNewVisibleColumns(ordering, columns, currentColumnWidths) {
if (!visibleColumnsHaveWidth(ordering, columns)) {
var addedVisibleColumnIDs = getIDsOfAddedVisibleColumns(ordering, currentColumnWidths);
return columns.map(function (column) {
var isNewVisibleColumn = addedVisibleColumnIDs.includes(column.id);
return _objectSpread$28(_objectSpread$28({}, column), {}, {
width: isNewVisibleColumn && column.width === undefined ? "".concat(DEFAULT_COLUMN_WIDTH, "px") : column.width
});
});
}
return columns;
};
function addCurrentlyRenderedWidths(columns, currentColumnWidths) {
return columns.map(function (col) {
var _currentColumnWidths$2;
var renderedWidth = (_currentColumnWidths$2 = currentColumnWidths[col.id]) === null || _currentColumnWidths$2 === void 0 ? void 0 : _currentColumnWidths$2.width;
var width = col.width === undefined && renderedWidth !== undefined ? "".concat(renderedWidth, "px") : col.width;
return _objectSpread$28(_objectSpread$28({}, col), {}, {
width: width
});
});
}
var addMissingColumnWidths = function addMissingColumnWidths(_ref) {
var ordering = _ref.ordering,
columns = _ref.columns,
currentColumnWidths = _ref.currentColumnWidths;
var modifiedColumns = addDefaultWidthToNewVisibleColumns(ordering, columns, currentColumnWidths);
return addCurrentlyRenderedWidths(modifiedColumns, currentColumnWidths);
};
/**
* Returns the new column widths map when one or more columns are shown or added.
* @param {object} currentColumnWidths map of the current column IDs and widths
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {array} colToShowIDs array of IDs of the columns to be shown/added
* @param {array} columns The table column props
*/
var calculateWidthOnShow = function calculateWidthOnShow(currentColumnWidths, ordering, colToShowIDs, columns) {
var visibleColumns = getVisibleColumns(currentColumnWidths, ordering, colToShowIDs);
var newWidthColumns = [];
var newColumnsToShow = colToShowIDs.map(function (colToShowId) {
var existingWidth = getExistingColumnWidth(currentColumnWidths, columns, colToShowId);
var widthOfColumnToShow = existingWidth || getAverageVisibleColumnWidth(visibleColumns) || MIN_COLUMN_WIDTH;
var newColumnToShow = {
id: colToShowId,
width: Math.round(widthOfColumnToShow)
};
if (!existingWidth) {
newWidthColumns.push(newColumnToShow);
}
return newColumnToShow;
});
var totalWidthNeeded = newColumnsToShow.reduce(function (acc, col) {
return acc + col.width;
}, 0);
var shrinkableColumns = [].concat(toConsumableArray(newColumnsToShow), toConsumableArray(visibleColumns)).filter(function (col) {
return col.width > MIN_COLUMN_WIDTH;
});
var adjustedCols = [].concat(newWidthColumns, toConsumableArray(shrinkColumns(shrinkableColumns, totalWidthNeeded)));
return createWidthsMap(ordering, currentColumnWidths, adjustedCols);
};
/**
* Calculates the new column widths when one ore more columns are hidden or deleted.
* @param {object} currentColumnWidths map of the current column IDs and widths
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {array} colToHideIDs Array with the IDs of one or more columns being hidden/deleted
*/
var calculateWidthOnHide = function calculateWidthOnHide(currentColumnWidths, ordering, colToHideIDs) {
var columnsToHide = colToHideIDs.map(function (hideId) {
var col = currentColumnWidths[hideId];
return Number.isNaN(parseInt(col.width, 10)) ? {
width: 0,
id: hideId
} : col;
});
var widthToDistribute = getTotalWidth(columnsToHide);
var visibleCols = Object.values(currentColumnWidths).filter(function (col) {
return isColumnVisible(ordering, col.id) && !colToHideIDs.includes(col.id);
});
var availableWidth = getTotalWidth(visibleCols);
var adjustedCols = visibleCols.map(function (col) {
var newWidth = col.width + col.width / availableWidth * widthToDistribute;
return {
id: col.id,
width: Math.round(newWidth)
};
});
return createWidthsMap(ordering, currentColumnWidths, adjustedCols);
};
function adjustLastColumnWidth(ordering, columns, measuredWidths) {
// This function adjusts the last column width to the initial width if that one is larger.
var visibleCols = ordering.filter(function (col) {
return !col.isHidden;
}); // If there are no visible columns there is nothing to adjust
if (!visibleCols.length) return measuredWidths;
var lastIndex = visibleCols.length - 1;
var lastColumn = columns.find(function (col) {
return col.id === visibleCols[lastIndex].columnId;
});
var fixedWidth = lastColumn.width ? parseInt(lastColumn.width, 10) : 0;
var measuredWidth = measuredWidths[lastIndex].width;
var result = measuredWidths;
if (measuredWidth < fixedWidth) {
result = cloneDeep(measuredWidths);
result[lastIndex].width = fixedWidth;
}
return result;
}
/**
* When the browser layout engine sets the widths dynamically we need to to make
* some adjustments to the last column width and also to column widths below
* the allowed minimum.
* @param {*} ordering
* @param {*} columns
* @param {*} measuredWidths
*/
var adjustInitialColumnWidths = function adjustInitialColumnWidths(ordering, columns, measuredWidths) {
// If the table isn't wide enough for all columns that has a defined width
// the browser will will shrink the last column instead of keeping its defined width.
// We therefore eadjust the column width to the initial width if that one is larger.
var adjustedWidths = adjustLastColumnWidth(ordering, columns, measuredWidths); // If the table-layout is fixed (prop useAutoTableLayoutForResize:false) and the
// the table container isn't wide enough to fully render all column header texts the
// browser will shrink the columns that don't have a defined width to make them all fit.
// It is possible that the new widths are shrunk below our minimum width and in that case
// we use the default width instead.
return adjustColumnsBelowMinWidth(adjustedWidths);
};
/**
* Creates a widths map based on current columns state + any changes in visibility or width
* @param {array} ordering defining the order, via the index, and visiblity of columns
* @param {object} currentColumnWidths map or object array of the current column IDs and widths
* @param {array} adjustedCols contains objects with ID and modified width
*/
var createNewWidthsMap = function createNewWidthsMap(ordering, currentColumnWidths) {
var adjustedCols = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
return createWidthsMap(ordering, currentColumnWidths, adjustedCols);
};
/**
* Calculates the new width of all columns when a column is toggled.
* @param {object} currentColumnWidths map of the current column IDs and widths
* @param {array} newOrdering defining the order, via the index, and visiblity of columns
* @param {string} columnId the id of the column to be hidden/shown
* @param {array} columns the orginal column definitions
*/
var calculateWidthsOnToggle = function calculateWidthsOnToggle(_ref2) {
var currentColumnWidths = _ref2.currentColumnWidths,
ordering = _ref2.newOrdering,
columnId = _ref2.columnId,
columns = _ref2.columns;
var hideColumn = ordering.find(function (col) {
return col.columnId === columnId;
}).isHidden;
return hideColumn ? calculateWidthOnHide(currentColumnWidths, ordering, [columnId]) : calculateWidthOnShow(currentColumnWidths, ordering, [columnId], columns);
};
var propTypes$2m = {
currentColumnWidths: PropTypes__default['default'].objectOf(PropTypes__default['default'].shape({
width: PropTypes__default['default'].number,
id: PropTypes__default['default'].string
})).isRequired,
columnId: PropTypes__default['default'].string.isRequired,
onResize: PropTypes__default['default'].func.isRequired,
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].object).isRequired,
paddingExtra: PropTypes__default['default'].number.isRequired,
preserveColumnWidths: PropTypes__default['default'].bool.isRequired,
showExpanderColumn: PropTypes__default['default'].bool.isRequired,
resizeColumnText: PropTypes__default['default'].string
};
var defaultProps$2s = {
resizeColumnText: 'Resize column'
};
var dragHandleWidth = 4;
var iotPrefix$2d = settings$1.iotPrefix;
var getColumnDragBounds = function getColumnDragBounds(_ref) {
var myColumn = _ref.myColumn,
affectedSiblingColumn = _ref.affectedSiblingColumn,
paddingExtra = _ref.paddingExtra,
preserveColumnWidths = _ref.preserveColumnWidths;
var minWidth = MIN_COLUMN_WIDTH + paddingExtra;
return {
minWidth: minWidth,
left: document.dir === 'rtl' ? preserveColumnWidths ? -Infinity : minWidth - affectedSiblingColumn.width : minWidth,
right: document.dir === 'rtl' ? myColumn.width - minWidth : preserveColumnWidths ? Infinity : myColumn.width + affectedSiblingColumn.width - minWidth
};
};
var getUpdatedColumnWidths = function getUpdatedColumnWidths(_ref2) {
var dropXPos = _ref2.dropXPos,
myColumn = _ref2.myColumn,
affectedSiblingColumn = _ref2.affectedSiblingColumn,
preserveColumnWidths = _ref2.preserveColumnWidths;
var myColumnNewWidth = document.dir === 'rtl' ? myColumn.width - dropXPos : dropXPos;
var updatedColumns = [{
id: myColumn.id,
width: myColumnNewWidth
}];
if (!affectedSiblingColumn.isExpanderColumn && !preserveColumnWidths) {
var newAffectedSiblingColumnWidth = document.dir === 'rtl' ? affectedSiblingColumn.width + dropXPos : affectedSiblingColumn.width + myColumn.width - dropXPos;
updatedColumns.push({
id: affectedSiblingColumn.id,
width: newAffectedSiblingColumnWidth
});
}
return updatedColumns;
};
var findNextVisibleSibling = function findNextVisibleSibling(_ref3) {
var _ordering$nextColInde;
var ordering = _ref3.ordering,
myColIndex = _ref3.myColIndex,
currentColumnWidths = _ref3.currentColumnWidths,
showExpanderColumn = _ref3.showExpanderColumn;
var nextColIndex = ordering.findIndex(function (col, i) {
return i > myColIndex && !col.isHidden;
});
var nextColId = (_ordering$nextColInde = ordering[nextColIndex]) === null || _ordering$nextColInde === void 0 ? void 0 : _ordering$nextColInde.columnId;
return nextColIndex === -1 && showExpanderColumn ? {
width: Infinity,
isExpanderColumn: true
} : currentColumnWidths[nextColId];
};
var ColumnResize = /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) {
var currentColumnWidths = props.currentColumnWidths,
columnId = props.columnId,
ordering = props.ordering,
paddingExtra = props.paddingExtra,
showExpanderColumn = props.showExpanderColumn,
preserveColumnWidths = props.preserveColumnWidths,
resizeColumnText = props.resizeColumnText;
var _useState = React$1.useState(0),
_useState2 = slicedToArray$2(_useState, 2),
startX = _useState2[0],
setStartX = _useState2[1];
var _useState3 = React$1.useState(0),
_useState4 = slicedToArray$2(_useState3, 2),
leftPosition = _useState4[0],
setLeftPosition = _useState4[1];
var _useState5 = React$1.useState(false),
_useState6 = slicedToArray$2(_useState5, 2),
columnIsBeingResized = _useState6[0],
setColumnIsBeingResized = _useState6[1];
var _useState7 = React$1.useState(),
_useState8 = slicedToArray$2(_useState7, 2),
myColumn = _useState8[0],
setMyColumn = _useState8[1];
var _useState9 = React$1.useState(),
_useState10 = slicedToArray$2(_useState9, 2),
affectedSiblingColumn = _useState10[0],
setAffectedSiblingColumn = _useState10[1];
var setAffectedColumns = function setAffectedColumns() {
var myCol = currentColumnWidths[columnId];
setMyColumn(myCol);
var myColIndex = ordering.findIndex(function (col) {
return col.columnId === columnId;
});
var siblingColumn = findNextVisibleSibling({
ordering: ordering,
myColIndex: myColIndex,
currentColumnWidths: currentColumnWidths,
showExpanderColumn: showExpanderColumn
});
setAffectedSiblingColumn(siblingColumn);
};
var _onMouseDown = function onMouseDown(e) {
var startingX = e.target.offsetLeft - e.clientX;
setStartX(startingX);
setLeftPosition(e.target.offsetLeft);
setColumnIsBeingResized(true);
setAffectedColumns();
};
var onMouseMove = function onMouseMove(e) {
if (columnIsBeingResized) {
var mousePosition = e.clientX + startX;
var bounds = getColumnDragBounds({
myColumn: myColumn,
affectedSiblingColumn: affectedSiblingColumn,
paddingExtra: paddingExtra,
preserveColumnWidths: preserveColumnWidths
});
if (mousePosition > bounds.left && mousePosition < bounds.right) {
setLeftPosition(mousePosition);
}
}
};
var onMouseUp = function onMouseUp() {
if (columnIsBeingResized) {
var dropXPos = leftPosition + (document.dir === 'rtl' ? 0 : dragHandleWidth);
var colWidths = getUpdatedColumnWidths({
dropXPos: dropXPos,
myColumn: myColumn,
affectedSiblingColumn: affectedSiblingColumn,
preserveColumnWidths: preserveColumnWidths
});
props.onResize(colWidths);
setColumnIsBeingResized(false);
setLeftPosition(0);
}
}; // We extend this instance with mouse move/up event forward functions which the parent
// component must call using forward referencing. We do this since the mouse move/up
// logic belongs to this component, but the events have to be captured by the parent
// component (with the larger HTML element surface). An alternative to this solution
// would have been to pass down the mouse coordinates via props, but that resulted in
// a sluggish rendering since the parent component would have to render for all events
// during the mouse move.
React$1.useImperativeHandle(ref, function () {
return {
forwardMouseEvent: function forwardMouseEvent(e) {
if (e.nativeEvent.type === 'mousemove') {
onMouseMove(e);
/* istanbul ignore else */
} else if (e.nativeEvent.type === 'mouseup') {
onMouseUp();
}
}
};
});
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/click-events-have-key-events
React__default['default'].createElement("div", {
role: "button",
tabIndex: "0",
"aria-label": resizeColumnText,
onClick: function onClick(e) {
return e.stopPropagation();
},
onMouseDown: function onMouseDown(e) {
return _onMouseDown(e);
},
style: {
width: dragHandleWidth,
left: leftPosition || (document.dir === 'rtl' ? 0 : 'auto')
},
className: classnames$1("".concat(iotPrefix$2d, "--column-resize-handle"), defineProperty$d({}, "".concat(iotPrefix$2d, "--column-resize-handle--dragging"), columnIsBeingResized))
})
);
});
ColumnResize.propTypes = propTypes$2m;
ColumnResize.defaultProps = defaultProps$2s;
ColumnResize.__docgenInfo = {
"description": "",
"methods": [],
"props": {
"resizeColumnText": {
"defaultValue": {
"value": "'Resize column'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"currentColumnWidths": {
"type": {
"name": "objectOf",
"value": {
"name": "shape",
"value": {
"width": {
"name": "number",
"required": false
},
"id": {
"name": "string",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"columnId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"onResize": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "object"
}
},
"required": true,
"description": ""
},
"paddingExtra": {
"type": {
"name": "number"
},
"required": true,
"description": ""
},
"preserveColumnWidths": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"showExpanderColumn": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
}
}
};
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop$f() {
// No operation performed.
}
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set$1 && (1 / setToArray(new Set$1([,-0]))[1]) == INFINITY$2) ? noop$f : function(values) {
return new Set$1(values);
};
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
function ownKeys$27(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$27(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$27(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$27(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$2c = settings$1.iotPrefix;
var propTypes$2l = {
/** Number of additional columns that have been added to the end of the table */
appendedColumns: PropTypes__default['default'].number,
/** Specify the properties of each column group in the table. Defaults to empty column. */
columnGroups: TableColumnGroupPropType.isRequired,
/** Specify the order, visibility and group belonging of the table columns */
ordering: TableOrderingPropType.isRequired,
/** Number of additional columns that have been added to the start of the table */
prependedColumns: PropTypes__default['default'].number,
testId: PropTypes__default['default'].string
};
var defaultProps$2r = {
appendedColumns: 0,
prependedColumns: 0,
testId: 'column-grouping-row'
};
var containsLastVisibleColumn = function containsLastVisibleColumn(groupId, visibleColumns) {
var lastColumnInGroup = visibleColumns.filter(function (_ref) {
var columnGroupId = _ref.columnGroupId;
return columnGroupId === groupId;
}).slice(-1)[0];
var lastColumn = visibleColumns.slice(-1)[0];
return lastColumnInGroup === lastColumn;
};
var ColumnGrouping = function ColumnGrouping(_ref2) {
var appendedColumns = _ref2.appendedColumns,
columnGroups = _ref2.columnGroups,
ordering = _ref2.ordering,
prependedColumns = _ref2.prependedColumns,
testId = _ref2.testId;
var visibleColumns = ordering.filter(function (col) {
return !col.isHidden;
});
var groups = uniqWith(visibleColumns.filter(function (col) {
return col.columnGroupId;
}).map(function (col) {
return _objectSpread$27(_objectSpread$27({}, columnGroups.find(function (colGroup) {
return colGroup.id === col.columnGroupId;
})), {}, {
colspan: visibleColumns.filter(function (_ref3) {
var columnGroupId = _ref3.columnGroupId;
return columnGroupId === col.columnGroupId;
}).length
});
}).filter(function (colGroupData) {
return colGroupData.hasOwnProperty('id');
}), isEqual$1);
var isLastGroup = groups.slice(-1)[0];
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
"data-testid": testId,
className: "".concat(iotPrefix$2c, "--table-header__group-row")
}, prependedColumns ? /*#__PURE__*/React__default['default'].createElement(TableHeader, {
key: "spacer-start",
colSpan: prependedColumns,
testId: "".concat(testId, "-prepended-column-group"),
className: "".concat(iotPrefix$2c, "--table-header__group-row-spacer")
}) : null, groups.map(function (colGroupData) {
return /*#__PURE__*/React__default['default'].createElement(TableHeader, {
title: colGroupData.name,
key: "column-group-".concat(colGroupData.id),
testId: "".concat(testId, "-column-group-").concat(colGroupData.id),
className: classnames$1("".concat(iotPrefix$2c, "--table-header__column-group"), defineProperty$d({}, "".concat(iotPrefix$2c, "--table-header__column-group--last-data-column"), colGroupData === isLastGroup && containsLastVisibleColumn(colGroupData.id, visibleColumns))),
colSpan: colGroupData.colspan
}, colGroupData.name);
}), appendedColumns ? /*#__PURE__*/React__default['default'].createElement(TableHeader, {
key: "spacer-end",
colSpan: appendedColumns,
testId: "".concat(testId, "-appended-column-group"),
className: "".concat(iotPrefix$2c, "--table-header__group-row-spacer")
}) : null);
};
ColumnGrouping.defaultProps = defaultProps$2r;
ColumnGrouping.propTypes = propTypes$2l;
ColumnGrouping.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ColumnGrouping",
"props": {
"appendedColumns": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "Number of additional columns that have been added to the end of the table"
},
"prependedColumns": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "Number of additional columns that have been added to the start of the table"
},
"testId": {
"defaultValue": {
"value": "'column-grouping-row'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"columnGroups": {
"type": {
"name": "custom",
"raw": "TableColumnGroupPropType.isRequired"
},
"required": false,
"description": "Specify the properties of each column group in the table. Defaults to empty column."
},
"ordering": {
"type": {
"name": "custom",
"raw": "TableOrderingPropType.isRequired"
},
"required": false,
"description": "Specify the order, visibility and group belonging of the table columns"
}
}
};
function ownKeys$26(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$26(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$26(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$26(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$2b = settings$1.iotPrefix;
var propTypes$2k = {
tableId: PropTypes__default['default'].string.isRequired,
/** Important table options that the head needs to know about */
options: PropTypes__default['default'].shape({
hasRowExpansion: PropTypes__default['default'].bool,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
useRadioButtonSingleSelect: PropTypes__default['default'].bool,
hasRowActions: PropTypes__default['default'].bool,
hasResize: PropTypes__default['default'].bool,
hasSingleRowEdit: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
wrapCellText: WrapCellTextPropTypes.isRequired,
truncateCellText: PropTypes__default['default'].bool.isRequired,
hasMultiSort: PropTypes__default['default'].bool,
useAutoTableLayoutForResize: PropTypes__default['default'].bool,
/** Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized. */
preserveColumnWidths: PropTypes__default['default'].bool,
hasFilterRowIcon: PropTypes__default['default'].bool,
hasDragAndDrop: PropTypes__default['default'].bool,
/** Freezes table header and footer */
pinHeaderAndFooter: PropTypes__default['default'].bool,
/** column to pin in the table */
pinColumn: PinColumnPropTypes
}),
/** List of columns */
columns: TableColumnsPropTypes.isRequired,
/** Specify the properties of each column group in the table. Defaults to empty column. */
columnGroups: TableColumnGroupPropType,
/** internationalized labels */
selectAllText: PropTypes__default['default'].string,
clearFilterText: PropTypes__default['default'].string,
filterText: PropTypes__default['default'].string,
clearSelectionText: PropTypes__default['default'].string,
openMenuText: PropTypes__default['default'].string,
closeMenuText: PropTypes__default['default'].string,
/** Current state of the table */
tableState: PropTypes__default['default'].shape({
/** is the tableHead currently disabled */
isDisabled: PropTypes__default['default'].bool,
/** Which toolbar is currently active */
activeBar: ActiveTableToolbarPropType,
/** What's currently selected in the table? */
selection: PropTypes__default['default'].shape({
isSelectAllIndeterminate: PropTypes__default['default'].bool,
isSelectAllSelected: PropTypes__default['default'].bool
}).isRequired,
/** What sorting is currently applied */
sort: PropTypes__default['default'].oneOfType([TableSortPropType, PropTypes__default['default'].arrayOf(TableSortPropType)]).isRequired,
/** Specify the order, visibility and group belonging of the table columns */
ordering: TableOrderingPropType.isRequired,
/** Optional list of applied column filters */
filters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
value: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool, PropTypes__default['default'].arrayOf(PropTypes__default['default'].string)]).isRequired
}))
}).isRequired,
actions: PropTypes__default['default'].shape({
onSelectAll: PropTypes__default['default'].func,
onChangeSort: PropTypes__default['default'].func,
onChangeOrdering: PropTypes__default['default'].func,
onColumnSelectionConfig: PropTypes__default['default'].func,
onApplyFilter: PropTypes__default['default'].func,
onColumnResize: PropTypes__default['default'].func,
onOverflowItemClicked: PropTypes__default['default'].func,
onFilterRowIconClick: PropTypes__default['default'].func
}).isRequired,
/** lightweight */
lightweight: PropTypes__default['default'].bool,
i18n: I18NPropTypes,
/** should we filter on each keypress */
hasFastFilter: PropTypes__default['default'].bool,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
testId: PropTypes__default['default'].string,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
/** Size prop from Carbon to shrink row height (and header height in some instances) */
size: function checkProps(props, propName, componentName) {
if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {
warning_1(false, "The value `".concat(props[propName], "` has been deprecated for the ") + "`".concat(propName, "` prop on the ").concat(componentName, " component. It will be removed in the next major ") + "release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.") ;
}
},
filterRowIcon: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].object]),
filterRowIconDescription: PropTypes__default['default'].string
};
var defaultProps$2q = {
columnGroups: [],
options: {},
lightweight: false,
selectAllText: 'Select all',
clearFilterText: 'Clear filter',
filterText: 'Filter',
clearSelectionText: 'Clear selection',
openMenuText: 'Open menu',
closeMenuText: 'Close menu',
i18n: _objectSpread$26({}, defaultI18NPropTypes),
hasFastFilter: true,
testId: '',
showExpanderColumn: false,
size: undefined,
filterRowIcon: iconsReact.FilterEdit16,
filterRowIconDescription: 'Edit filters'
};
var generateOrderedColumnRefs = function generateOrderedColumnRefs(ordering) {
return ordering.map(function (col) {
return col.columnId;
}).reduce(function (acc, id) {
return _objectSpread$26(_objectSpread$26({}, acc), {}, defineProperty$d({}, id, /*#__PURE__*/React$1.createRef()));
}, {});
}; // This increases the min width of columns when the overflow button and sort is present
var PADDING_WITH_OVERFLOW = 24;
var PADDING_WITH_OVERFLOW_AND_SORT = 58;
var TableHead = function TableHead(_ref) {
var _classnames2;
var testID = _ref.testID,
testId = _ref.testId,
tableId = _ref.tableId,
options = _ref.options,
_ref$options = _ref.options,
hasRowExpansion = _ref$options.hasRowExpansion,
hasRowSelection = _ref$options.hasRowSelection,
hasRowNesting = _ref$options.hasRowNesting,
hasResize = _ref$options.hasResize,
wrapCellText = _ref$options.wrapCellText,
truncateCellText = _ref$options.truncateCellText,
hasSingleRowEdit = _ref$options.hasSingleRowEdit,
hasMultiSort = _ref$options.hasMultiSort,
useAutoTableLayoutForResize = _ref$options.useAutoTableLayoutForResize,
preserveColumnWidths = _ref$options.preserveColumnWidths,
useRadioButtonSingleSelect = _ref$options.useRadioButtonSingleSelect,
hasDragAndDrop = _ref$options.hasDragAndDrop,
pinHeaderAndFooter = _ref$options.pinHeaderAndFooter,
pinColumn = _ref$options.pinColumn,
columns = _ref.columns,
columnGroups = _ref.columnGroups,
_ref$tableState = _ref.tableState,
_ref$tableState$selec = _ref$tableState.selection,
isSelectAllIndeterminate = _ref$tableState$selec.isSelectAllIndeterminate,
isSelectAllSelected = _ref$tableState$selec.isSelectAllSelected,
sort = _ref$tableState.sort,
activeBar = _ref$tableState.activeBar,
ordering = _ref$tableState.ordering,
filters = _ref$tableState.filters,
isDisabled = _ref$tableState.isDisabled,
_ref$actions = _ref.actions,
onSelectAll = _ref$actions.onSelectAll,
onChangeSort = _ref$actions.onChangeSort,
onApplyFilter = _ref$actions.onApplyFilter,
onChangeOrdering = _ref$actions.onChangeOrdering,
onColumnSelectionConfig = _ref$actions.onColumnSelectionConfig,
onColumnResize = _ref$actions.onColumnResize,
onOverflowItemClicked = _ref$actions.onOverflowItemClicked,
onFilterRowIconClick = _ref$actions.onFilterRowIconClick,
selectAllText = _ref.selectAllText,
clearFilterText = _ref.clearFilterText,
filterText = _ref.filterText,
clearSelectionText = _ref.clearSelectionText,
openMenuText = _ref.openMenuText,
closeMenuText = _ref.closeMenuText,
lightweight = _ref.lightweight,
i18n = _ref.i18n,
hasFastFilter = _ref.hasFastFilter,
showExpanderColumn = _ref.showExpanderColumn,
size = _ref.size,
filterRowIcon = _ref.filterRowIcon,
filterRowIconDescription = _ref.filterRowIconDescription;
var filterBarActive = activeBar === 'filter';
var initialColumnWidths = {};
var columnRef = generateOrderedColumnRefs(ordering);
var columnResizeRefs = generateOrderedColumnRefs(ordering);
var _useState = React$1.useState({}),
_useState2 = slicedToArray$2(_useState, 2),
currentColumnWidths = _useState2[0],
setCurrentColumnWidths = _useState2[1];
if (isEmpty(currentColumnWidths)) {
columns.forEach(function (col) {
initialColumnWidths[col.id] = col.width;
});
}
var forwardMouseEvent = function forwardMouseEvent(e) {
Object.entries(columnResizeRefs).forEach(function (_ref2) {
var _ref3 = slicedToArray$2(_ref2, 2),
ref = _ref3[1];
if (ref.current) {
ref.current.forwardMouseEvent(e);
}
});
};
var measureColumnWidths = React$1.useCallback(function () {
return ordering.filter(function (col) {
return !col.isHidden;
}).map(function (col) {
var ref = columnRef[col.columnId];
return {
id: col.columnId,
width: ref.current && ref.current.getBoundingClientRect().width
};
});
}, [ordering, columnRef]);
var updateColumnWidths = function updateColumnWidths(newColumnWidths) {
var updatedColumns = columns.map(function (col) {
return _objectSpread$26(_objectSpread$26({}, col), {}, {
width: newColumnWidths[col.id].width !== undefined ? "".concat(newColumnWidths[col.id].width, "px") : col.width
});
});
setCurrentColumnWidths(newColumnWidths);
if (onColumnResize) {
onColumnResize(updatedColumns);
}
};
var onManualColumnResize = function onManualColumnResize(modifiedColumnWidths) {
var newColumnWidths = createNewWidthsMap(ordering, currentColumnWidths, modifiedColumnWidths);
updateColumnWidths(newColumnWidths);
};
var onColumnToggle = function onColumnToggle(columnId, newOrdering) {
if (hasResize) {
if (preserveColumnWidths) {
var isToggleShow = isColumnVisible(newOrdering, columnId);
var columnHasNoWidth = getOriginalWidthOfColumn(columns, columnId) === undefined;
if (isToggleShow && columnHasNoWidth) {
var newColumnWidths = createNewWidthsMap(newOrdering, currentColumnWidths, [{
id: columnId,
width: DEFAULT_COLUMN_WIDTH
}]);
updateColumnWidths(newColumnWidths);
}
} else {
var _newColumnWidths = calculateWidthsOnToggle({
currentColumnWidths: currentColumnWidths,
newOrdering: newOrdering,
columnId: columnId,
columns: columns
});
updateColumnWidths(_newColumnWidths);
}
}
onChangeOrdering(newOrdering);
};
var handleOverflowItemClick = function handleOverflowItemClick(e, option) {
e.stopPropagation();
if (onOverflowItemClicked) {
onOverflowItemClicked(option.id, option.meta);
}
};
React$1.useLayoutEffect(function () {
var measureAndAdjustColumns = function measureAndAdjustColumns() {
if (hasResize && columns.length) {
var measuredWidths = measureColumnWidths();
var adjustedWidths = adjustInitialColumnWidths(ordering, columns, measuredWidths);
var newWidthsMap = createNewWidthsMap(ordering, currentColumnWidths, adjustedWidths);
setCurrentColumnWidths(newWidthsMap);
}
}; // An initial measuring is needed since there might not be an initial value from the columns prop
// which means that the layout engine will have to set the widths dynamically
// before we know what they are.
if (isEmpty(currentColumnWidths)) {
measureAndAdjustColumns();
} // For non fixed tables with resizable columns we need to recalculate the
// column widths after window resize.
var handleWindowResize = debounce(function () {
if (useAutoTableLayoutForResize) {
measureAndAdjustColumns();
}
}, 100);
window.addEventListener('resize', handleWindowResize);
return function () {
return window.removeEventListener('resize', handleWindowResize);
};
}, [hasResize, columns, ordering, currentColumnWidths, measureColumnWidths, useAutoTableLayoutForResize]); // Handle external modification of columns prop and ordering prop
var previousColumns = usePrevious(columns);
var previousOrdering = usePrevious(ordering);
React$1.useEffect(function () {
// We need to update the currentColumnWidths (state) after the initial render
// if the widths of the column prop are externally updated or if columns are added/removed.
var externallyModified = !isEqual$1(columns, previousColumns) || !isEqual$1(ordering, previousOrdering);
if (hasResize && columns.length && !isEmpty(currentColumnWidths) && externallyModified) {
checkColumnWidthFormat(columns); // PRESERVE WIDTHS
// Preserve column when possible widths when columns are externally modified
if (preserveColumnWidths) {
var columnPropInlcudingWidths = addMissingColumnWidths({
ordering: ordering,
columns: columns,
currentColumnWidths: currentColumnWidths
});
var newColumnWidths = createNewWidthsMap(ordering, columnPropInlcudingWidths);
if (!isEqual$1(currentColumnWidths, newColumnWidths)) {
setCurrentColumnWidths(newColumnWidths); // Notify the application if any columns were assigned the rendered or default widths
if (!isEqual$1(columnPropInlcudingWidths, columns)) {
onColumnResize(columnPropInlcudingWidths);
}
}
return;
} // MODIFY WIDTHS
// Modify existing columns widths when columns are externally modified
var removedColumnIDs = getIDsOfRemovedColumns(ordering, currentColumnWidths);
var addedVisibleColumnIDs = getIDsOfAddedVisibleColumns(ordering, currentColumnWidths);
var adjustedForRemoved = removedColumnIDs.length > 0 ? calculateWidthOnHide(currentColumnWidths, ordering, removedColumnIDs) : currentColumnWidths;
var adjustedForRemovedAndAdded = addedVisibleColumnIDs.length > 0 ? calculateWidthOnShow(adjustedForRemoved, ordering, addedVisibleColumnIDs, columns) : adjustedForRemoved;
if (addedVisibleColumnIDs.length > 0 || removedColumnIDs.length > 0) {
setCurrentColumnWidths(adjustedForRemovedAndAdded);
} else if (hasVisibleColumns(ordering) && visibleColumnsHaveWidth(ordering, columns)) {
var propsColumnWidths = createNewWidthsMap(ordering, columns);
if (!isEqual$1(currentColumnWidths, propsColumnWidths)) {
setCurrentColumnWidths(propsColumnWidths);
}
}
}
}, // We explicitly do NOT want to trigger this effect if currentColumnWidths is modified
// since it would be directly overridden by the column props. This effect can be removed
// with issue https://github.com/IBM/carbon-addons-iot-react/issues/1224
// eslint-disable-next-line react-hooks/exhaustive-deps
[hasResize, columns, ordering, previousColumns]);
var visibleColumns = ordering.filter(function (col) {
return !col.isHidden;
});
var lastVisibleColumn = visibleColumns.slice(-1)[0];
var showColumnGroups = columnGroups.some(function (_ref4) {
var id = _ref4.id;
return visibleColumns.find(function (_ref5) {
var columnGroupId = _ref5.columnGroupId;
return id === columnGroupId;
});
});
var langDir = useLangDirection_2();
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableHead, {
className: classnames$1(defineProperty$d({
lightweight: lightweight
}, "".concat(iotPrefix$2b, "--table-head--with-column-groups"), showColumnGroups), pinColumnClassNames({
pinColumn: pinColumn,
hasRowSelection: hasRowSelection,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting
})),
onMouseMove: hasResize ? forwardMouseEvent : null,
onMouseUp: hasResize ? forwardMouseEvent : null // TODO: remove deprecated 'testID' in v3
,
"data-testid": testID || testId
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
className: classnames$1((_classnames2 = {}, defineProperty$d(_classnames2, "".concat(iotPrefix$2b, "--table-header__column-row"), showColumnGroups), defineProperty$d(_classnames2, "".concat(iotPrefix$2b, "--table-header__column-row--prevent-small-sizes"), showColumnGroups), _classnames2))
}, hasDragAndDrop && /*#__PURE__*/React__default['default'].createElement(TableHeader, {
width: "2rem",
initialWidth: "2rem"
}), hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableExpandHeader, {
id: "".concat(tableId, "-expand") // TODO: remove deprecated 'testID' in v3
,
"data-testid": "".concat(testID || testId, "-row-expansion-column"),
className: classnames$1(defineProperty$d({}, "".concat(iotPrefix$2b, "--table-expand-resize"), hasResize))
}) : null, hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(TableHeader // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-row-selection-column"),
className: classnames$1("".concat(iotPrefix$2b, "--table-header-checkbox"), defineProperty$d({}, "".concat(iotPrefix$2b, "--table-header-checkbox-resize"), hasResize)),
translateWithId: function translateWithId() {
return tableTranslateWithId.apply(void 0, arguments);
}
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Checkbox, {
disabled: isDisabled,
id: "".concat(tableId, "-head"),
labelText: selectAllText,
hideLabel: true,
indeterminate: isSelectAllIndeterminate,
checked: isSelectAllSelected,
onChange: function onChange() {
return onSelectAll(!isSelectAllSelected);
}
})) : hasRowSelection === 'single' && useRadioButtonSingleSelect ? /*#__PURE__*/React__default['default'].createElement(TableHeader // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-row-selection-column"),
className: classnames$1("".concat(iotPrefix$2b, "--table-header-radiobutton"), defineProperty$d({}, "".concat(iotPrefix$2b, "--table-header-radiobutton-resize"), hasResize)),
translateWithId: function translateWithId() {
return tableTranslateWithId.apply(void 0, arguments);
}
}) : null, ordering.map(function (item, columnIndex) {
var _currentColumnWidths$, _classnames6;
var matchingColumnMeta = columns.find(function (column) {
return column.id === item.columnId;
});
var hasSingleSort = matchingColumnMeta && sort && sort.columnId === matchingColumnMeta.id;
var multiSortColumn = hasMultiSort && matchingColumnMeta && Array.isArray(sort) && sort.find(function (c) {
return c.columnId === matchingColumnMeta.id;
});
var hasSort = hasSingleSort || hasMultiSort;
var sortOrder = hasMultiSort && Array.isArray(sort) ? sort.findIndex(function (c) {
return c.columnId === matchingColumnMeta.id;
}) + 1 : -1;
var sortDirection = hasSingleSort ? sort.direction : hasMultiSort && multiSortColumn !== null && multiSortColumn !== void 0 && multiSortColumn.direction ? multiSortColumn.direction : 'NONE';
var align = matchingColumnMeta && matchingColumnMeta.align ? matchingColumnMeta.align : 'start';
var hasOverflow = Array.isArray(matchingColumnMeta === null || matchingColumnMeta === void 0 ? void 0 : matchingColumnMeta.overflowMenuItems); // Increases the minimum width of the Header when the overflow button is present
var paddingExtra = hasOverflow ? matchingColumnMeta.isSortable ? PADDING_WITH_OVERFLOW_AND_SORT : PADDING_WITH_OVERFLOW : 0;
var columnBelongsToExistingGroup = columnGroups.some(function (_ref6) {
var id = _ref6.id;
return id === item.columnGroupId;
});
var rightmostColumn = langDir === 'ltr' ? lastVisibleColumn : visibleColumns[0];
var flipTooltipDirection = rightmostColumn === item;
return !item.isHidden && matchingColumnMeta ? /*#__PURE__*/React__default['default'].createElement(TableHeader // TODO: remove deprecated 'testID' in v3
, {
spanGroupRow: showColumnGroups && !columnBelongsToExistingGroup,
testId: "".concat(testID || testId, "-column-").concat(matchingColumnMeta.id),
width: initialColumnWidths[matchingColumnMeta.id],
initialWidth: initialColumnWidths[matchingColumnMeta.id],
id: "column-".concat(matchingColumnMeta.id),
key: "column-".concat(matchingColumnMeta.id),
"data-column": matchingColumnMeta.id,
isSortable: matchingColumnMeta.isSortable && !isDisabled,
isSortHeader: hasSort,
hasTooltip: !!matchingColumnMeta.tooltip,
ref: columnRef[matchingColumnMeta.id],
hasMultiSort: hasMultiSort,
hasOverflow: hasOverflow,
thStyle: {
width: (_currentColumnWidths$ = currentColumnWidths[matchingColumnMeta.id]) === null || _currentColumnWidths$ === void 0 ? void 0 : _currentColumnWidths$.width
},
onClick: function onClick() {
if (matchingColumnMeta.isSortable && onChangeSort) {
onChangeSort(matchingColumnMeta.id);
}
},
translateWithId: function translateWithId() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return tableTranslateWithId.apply(void 0, [i18n].concat(args));
},
sortDirection: sortDirection,
align: align,
className: classnames$1("table-header-label-".concat(align), (_classnames6 = {}, defineProperty$d(_classnames6, "".concat(iotPrefix$2b, "--table-head--table-header"), initialColumnWidths !== undefined), defineProperty$d(_classnames6, 'table-header-sortable', matchingColumnMeta.isSortable && !isDisabled), defineProperty$d(_classnames6, "".concat(iotPrefix$2b, "--table-header-resize"), hasResize), defineProperty$d(_classnames6, "".concat(iotPrefix$2b, "--table-head--table-header--with-overflow"), hasOverflow || hasMultiSort && matchingColumnMeta.isSortable && !isDisabled), defineProperty$d(_classnames6, "".concat(iotPrefix$2b, "--table-header--last-data-column"), showColumnGroups && item === lastVisibleColumn), _classnames6)) // data-floating-menu-container is a work around for this carbon issue: https://github.com/carbon-design-system/carbon/issues/4755
,
"data-floating-menu-container": true
}, /*#__PURE__*/React__default['default'].createElement(TableCellRenderer, {
className: "".concat(iotPrefix$2b, "--table-head--text"),
wrapText: wrapCellText,
truncateCellText: truncateCellText,
allowTooltip: false,
tooltip: matchingColumnMeta.tooltip,
tooltipDirection: flipTooltipDirection ? 'end' : undefined
}, matchingColumnMeta.name), hasOverflow || hasMultiSort && matchingColumnMeta.isSortable && !isDisabled ? /*#__PURE__*/React__default['default'].createElement(OverflowMenu, {
size: "lg",
className: "".concat(iotPrefix$2b, "--table-head--overflow"),
direction: "bottom",
"data-testid": "table-head--overflow",
flipped: columnIndex === ordering.length - 1,
onClick: function onClick(e) {
return e.stopPropagation();
}
}, hasOverflow && matchingColumnMeta.overflowMenuItems.map(function (menuItem) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
"data-testid": "".concat(testID || testId, "-column-overflow-menu-item-").concat(menuItem.id),
itemText: menuItem.text,
key: "".concat(columnIndex, "--overflow-item-").concat(menuItem.id),
onClick: function onClick(e) {
return handleOverflowItemClick(e, menuItem);
}
});
}), hasMultiSort && /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
"data-testid": "".concat(testID || testId, "-column-overflow-menu-item-multi-sort"),
itemText: i18n.multiSortOverflowItem,
key: "".concat(columnIndex, "--overflow-item-multi-sort"),
onClick: function onClick(e) {
return handleOverflowItemClick(e, {
id: 'multi-sort',
meta: {
columnId: matchingColumnMeta.id
}
});
}
})) : null, sortOrder > 0 && !isDisabled && /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(iotPrefix$2b, "--table-header-label__sort-order")
}, sortOrder), hasResize && (item !== lastVisibleColumn || showExpanderColumn) ? /*#__PURE__*/React__default['default'].createElement(ColumnResize, {
showExpanderColumn: showExpanderColumn,
onResize: onManualColumnResize,
ref: columnResizeRefs[matchingColumnMeta.id],
currentColumnWidths: currentColumnWidths,
columnId: matchingColumnMeta.id,
ordering: ordering,
paddingExtra: paddingExtra,
preserveColumnWidths: preserveColumnWidths
}) : null) : null;
}), showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(TableHeader // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-expander-column"),
className: classnames$1("".concat(iotPrefix$2b, "--table-header-expander-column"))
}) : null, options.hasRowActions ? /*#__PURE__*/React__default['default'].createElement(TableHeader // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-row-actions-column"),
className: classnames$1("".concat(iotPrefix$2b, "--table-header-row-action-column"), defineProperty$d({}, "".concat(iotPrefix$2b, "--table-header-row-action-column--extra-wide"), hasSingleRowEdit))
}) : null), showColumnGroups ?
/*#__PURE__*/
// Column grouping should visually appear above the normal column headers but since we
// need the normal column headers to control the width of the columns, and since rowspan
// only works downward, we place the groups below the normal columns and then switch
// places using scss.
React__default['default'].createElement(ColumnGrouping, {
appendedColumns: +showExpanderColumn + !!options.hasRowActions,
testId: "".concat(testId, "-column-grouping"),
prependedColumns: +(hasRowSelection === 'multi') + !!(hasRowExpansion || hasRowNesting),
columnGroups: columnGroups,
ordering: ordering
}) : null, filterBarActive && /*#__PURE__*/React__default['default'].createElement(FilterHeaderRow // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-filter-header-row"),
key: !hasFastFilter && JSON.stringify(filters),
columns: columns.map(function (column) {
var _column$filter;
return _objectSpread$26(_objectSpread$26({}, column.filter), {}, {
id: column.id,
isFilterable: !isNil(column.filter),
isMultiselect: (_column$filter = column.filter) === null || _column$filter === void 0 ? void 0 : _column$filter.isMultiselect,
width: column.width
});
}),
hasFastFilter: hasFastFilter,
clearFilterText: clearFilterText,
filterText: filterText,
clearSelectionText: clearSelectionText,
openMenuText: openMenuText,
closeMenuText: closeMenuText,
ordering: ordering,
filters: filters,
tableOptions: options,
onApplyFilter: onApplyFilter,
lightweight: lightweight,
isDisabled: isDisabled,
showExpanderColumn: showExpanderColumn,
size: size,
langDir: langDir,
showColumnGroups: showColumnGroups,
filterRowIcon: filterRowIcon,
filterRowIconDescription: filterRowIconDescription,
onFilterRowIconClick: onFilterRowIconClick,
pinHeaderAndFooter: pinHeaderAndFooter,
hasDragAndDrop: hasDragAndDrop
}), activeBar === 'column' && /*#__PURE__*/React__default['default'].createElement(ColumnHeaderRow // TODO: remove deprecated 'testID' in v3
, {
testId: "".concat(testID || testId, "-column-header-row"),
columns: columns.map(function (column) {
return {
id: column.id,
name: column.name
};
}),
ordering: ordering,
options: options,
onChangeOrdering: onChangeOrdering,
onColumnToggle: onColumnToggle,
lightweight: lightweight,
onColumnSelectionConfig: onColumnSelectionConfig,
columnSelectionConfigText: i18n.columnSelectionConfig,
isDisabled: isDisabled,
showExpanderColumn: showExpanderColumn,
hasDragAndDrop: hasDragAndDrop
}));
};
TableHead.propTypes = propTypes$2k;
TableHead.defaultProps = defaultProps$2q;
TableHead.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableHead",
"props": {
"columnGroups": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableColumnGroupPropType"
},
"required": false,
"description": "Specify the properties of each column group in the table. Defaults to empty column."
},
"options": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"hasRowExpansion": {
"name": "bool",
"required": false
},
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"useRadioButtonSingleSelect": {
"name": "bool",
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
},
"hasResize": {
"name": "bool",
"required": false
},
"hasSingleRowEdit": {
"name": "bool",
"required": false
},
"hasRowNesting": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}],
"required": false
},
"wrapCellText": {
"name": "custom",
"raw": "WrapCellTextPropTypes.isRequired",
"required": true
},
"truncateCellText": {
"name": "bool",
"required": true
},
"hasMultiSort": {
"name": "bool",
"required": false
},
"useAutoTableLayoutForResize": {
"name": "bool",
"required": false
},
"preserveColumnWidths": {
"name": "bool",
"description": "Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized.",
"required": false
},
"hasFilterRowIcon": {
"name": "bool",
"required": false
},
"hasDragAndDrop": {
"name": "bool",
"required": false
},
"pinHeaderAndFooter": {
"name": "bool",
"description": "Freezes table header and footer",
"required": false
},
"pinColumn": {
"name": "custom",
"raw": "PinColumnPropTypes",
"description": "column to pin in the table",
"required": false
}
}
},
"required": false,
"description": "Important table options that the head needs to know about"
},
"lightweight": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "lightweight"
},
"selectAllText": {
"defaultValue": {
"value": "'Select all'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized labels"
},
"clearFilterText": {
"defaultValue": {
"value": "'Clear filter'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"filterText": {
"defaultValue": {
"value": "'Filter'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"clearSelectionText": {
"defaultValue": {
"value": "'Clear selection'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"openMenuText": {
"defaultValue": {
"value": "'Open menu'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"closeMenuText": {
"defaultValue": {
"value": "'Close menu'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n ...defaultI18NPropTypes,\n}",
"computed": false
},
"type": {
"name": "custom",
"raw": "I18NPropTypes"
},
"required": false,
"description": ""
},
"hasFastFilter": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "should we filter on each keypress"
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "function checkProps(props, propName, componentName) {\n if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {\n warning(\n false,\n `The value \\`${props[propName]}\\` has been deprecated for the ` +\n `\\`${propName}\\` prop on the ${componentName} component. It will be removed in the next major ` +\n `release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.`\n );\n }\n}"
},
"required": false,
"description": "Size prop from Carbon to shrink row height (and header height in some instances)"
},
"filterRowIcon": {
"defaultValue": {
"value": "FilterEdit16",
"computed": true
},
"type": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "object"
}]
},
"required": false,
"description": ""
},
"filterRowIconDescription": {
"defaultValue": {
"value": "'Edit filters'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"columns": {
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes.isRequired"
},
"required": false,
"description": "List of columns"
},
"tableState": {
"type": {
"name": "shape",
"value": {
"isDisabled": {
"name": "bool",
"description": "is the tableHead currently disabled",
"required": false
},
"activeBar": {
"name": "custom",
"raw": "ActiveTableToolbarPropType",
"description": "Which toolbar is currently active",
"required": false
},
"selection": {
"name": "shape",
"value": {
"isSelectAllIndeterminate": {
"name": "bool",
"required": false
},
"isSelectAllSelected": {
"name": "bool",
"required": false
}
},
"description": "What's currently selected in the table?",
"required": true
},
"sort": {
"name": "union",
"value": [{
"name": "custom",
"raw": "TableSortPropType"
}, {
"name": "arrayOf",
"value": {
"name": "custom",
"raw": "TableSortPropType"
}
}],
"description": "What sorting is currently applied",
"required": true
},
"ordering": {
"name": "custom",
"raw": "TableOrderingPropType.isRequired",
"description": "Specify the order, visibility and group belonging of the table columns",
"required": true
},
"filters": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}, {
"name": "arrayOf",
"value": {
"name": "string"
}
}],
"required": true
}
}
},
"description": "Optional list of applied column filters",
"required": false
}
}
},
"required": true,
"description": "Current state of the table"
},
"actions": {
"type": {
"name": "shape",
"value": {
"onSelectAll": {
"name": "func",
"required": false
},
"onChangeSort": {
"name": "func",
"required": false
},
"onChangeOrdering": {
"name": "func",
"required": false
},
"onColumnSelectionConfig": {
"name": "func",
"required": false
},
"onApplyFilter": {
"name": "func",
"required": false
},
"onColumnResize": {
"name": "func",
"required": false
},
"onOverflowItemClicked": {
"name": "func",
"required": false
},
"onFilterRowIconClick": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": ""
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
}
}
};
/**
* A helper hook to render overflow menu items from an array of pre-defined actions,
* or to render them dynamically from a callback on open. This can be used in the TableToolbar or
* eventually added to rowActions to render options dynamically there.
* @param {object} An object containing the follow properties
* className To applied to the OverflowMenuItem
* testId The testId prepended to the OverflowMenuItem
* isDisabled The isDisabled boolean for the whole toolbar
* onClick The callback to fire when the action is clicked
* actions The array of objects used to supply props to the OverflowMenuItem
* @returns Array An array containing the isOpen state, setIsOpen function and renderOverflowMenuItems function
*/
var useDynamicOverflowMenuItems = function useDynamicOverflowMenuItems(_ref) {
var className = _ref.className,
actions = _ref.actions,
testId = _ref.testId,
isDisabled = _ref.isDisabled,
_onClick = _ref.onClick;
var _useState = React$1.useState(false),
_useState2 = slicedToArray$2(_useState, 2),
isOpen = _useState2[0],
setIsOpen = _useState2[1];
/**
* allow dynamically rendering the extra items from a callback when the overflow menu is opened.
*/
var renderOverflowMenuItems = React$1.useCallback(function () {
var actionsArray = typeof actions === 'function' ? actions() : actions;
if (!(actionsArray !== null && actionsArray !== void 0 && actionsArray.length)) {
return null;
}
return actionsArray.filter(function (_ref2) {
var hidden = _ref2.hidden,
isOverflow = _ref2.isOverflow;
return hidden !== true && isOverflow === true;
}).map(function (action) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
"data-testid": "".concat(testId, "-toolbar-overflow-menu-item-").concat(action.id),
itemText: renderTableOverflowItemText({
action: action,
className: className
}),
key: "table-aggregations-overflow-item-".concat(action.id),
onClick: function onClick() {
setIsOpen(false);
_onClick(action);
},
requireTitle: !action.renderIcon,
disabled: isDisabled || action.disabled,
hasDivider: action.hasDivider,
isDelete: action.isDelete,
"aria-label": action.labelText
});
});
}, [actions, className, isDisabled, _onClick, testId]);
return [isOpen, setIsOpen, renderOverflowMenuItems];
};
function ownKeys$25(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$25(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$25(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$25(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var DIRECTION_BOTTOM = 'bottom';
var DIRECTION_LEFT = 'left';
var DIRECTION_RIGHT = 'right';
var DIRECTION_TOP = 'top';
/**
* @param {Element} menuBody The menu body with the menu arrow.
* @param {string} menuDirection Where the floating menu menu should be placed relative to the trigger button.
* @returns {FloatingMenu~offset} The adjustment of the floating menu position, upon the position of the menu arrow.
* @private
*/
var getTooltipMenuOffset = function getTooltipMenuOffset(menuBody, menuDirection) {
var _DIRECTION_LEFT$DIREC, _DIRECTION_LEFT$DIREC2;
var arrowStyle = menuBody.ownerDocument.defaultView.getComputedStyle(menuBody, ':before');
var arrowPositionProp = (_DIRECTION_LEFT$DIREC = {}, defineProperty$d(_DIRECTION_LEFT$DIREC, DIRECTION_LEFT, 'right'), defineProperty$d(_DIRECTION_LEFT$DIREC, DIRECTION_TOP, 'bottom'), defineProperty$d(_DIRECTION_LEFT$DIREC, DIRECTION_RIGHT, 'left'), defineProperty$d(_DIRECTION_LEFT$DIREC, DIRECTION_BOTTOM, 'top'), _DIRECTION_LEFT$DIREC)[menuDirection];
var menuPositionAdjustmentProp = (_DIRECTION_LEFT$DIREC2 = {}, defineProperty$d(_DIRECTION_LEFT$DIREC2, DIRECTION_LEFT, 'left'), defineProperty$d(_DIRECTION_LEFT$DIREC2, DIRECTION_TOP, 'top'), defineProperty$d(_DIRECTION_LEFT$DIREC2, DIRECTION_RIGHT, 'left'), defineProperty$d(_DIRECTION_LEFT$DIREC2, DIRECTION_BOTTOM, 'top'), _DIRECTION_LEFT$DIREC2)[menuDirection];
var values = [arrowPositionProp, 'border-bottom-width'].reduce(function (o, name) {
return _objectSpread$25(_objectSpread$25({}, o), {}, defineProperty$d({}, name, Number((/^([\d-]+)px$/.exec(arrowStyle.getPropertyValue(name)) || [])[1])));
}, {});
values[arrowPositionProp] = values[arrowPositionProp] || -6; // IE, etc.
if (Object.keys(values).every(function (name) {
return !Number.isNaN(values[name]);
})) {
var arrowPosition = values[arrowPositionProp],
borderBottomWidth = values['border-bottom-width'];
return defineProperty$d({
left: 0,
top: 0
}, menuPositionAdjustmentProp, Math.sqrt(Math.pow(borderBottomWidth, 2) * 2) - arrowPosition);
}
return {
top: 0,
left: 0
};
};
var Tooltip$2 = function Tooltip(_ref2) {
var direction = _ref2.direction,
menuOffset = _ref2.menuOffset,
useAutoPositioning = _ref2.useAutoPositioning,
testId = _ref2.testId,
props = objectWithoutProperties$1(_ref2, ["direction", "menuOffset", "useAutoPositioning", "testId"]);
var _usePopoverPositionin = usePopoverPositioning({
direction: direction,
menuOffset: menuOffset || getTooltipMenuOffset,
useAutoPositioning: useAutoPositioning
}),
_usePopoverPositionin2 = slicedToArray$2(_usePopoverPositionin, 2),
calculateMenuOffset = _usePopoverPositionin2[0],
adjustedDirection = _usePopoverPositionin2[1].adjustedDirection;
return /*#__PURE__*/React__namespace.createElement(carbonComponentsReact.Tooltip, _extends_1$1({
"data-testid": testId
}, props, {
menuOffset: calculateMenuOffset,
direction: adjustedDirection
}));
};
Tooltip$2.propTypes = _objectSpread$25(_objectSpread$25({}, carbonComponentsReact.Tooltip.propTypes), {}, {
useAutoPositioning: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string
});
Tooltip$2.defaultProps = _objectSpread$25(_objectSpread$25({}, carbonComponentsReact.Tooltip.defaultProps), {}, {
useAutoPositioning: false,
testId: 'tooltip'
});
Tooltip$2.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "Tooltip",
"props": {
"useAutoPositioning": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'tooltip'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
}
},
"composes": ["carbon-components-react"]
};
function ownKeys$24(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$24(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$24(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$24(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$2a = settings$1.iotPrefix;
var FlyoutMenuDirection = {
BottomStart: 'bottom-start',
BottomEnd: 'bottom-end',
TopStart: 'top-start',
TopEnd: 'top-end',
LeftStart: 'left-start',
LeftEnd: 'left-end',
RightStart: 'right-start',
RightEnd: 'right-end'
};
var getTooltipDirection = function getTooltipDirection(direction) {
switch (direction) {
case FlyoutMenuDirection.TopStart:
case FlyoutMenuDirection.TopEnd:
return 'top';
case FlyoutMenuDirection.RightStart:
case FlyoutMenuDirection.RightEnd:
return 'right';
case FlyoutMenuDirection.LeftStart:
case FlyoutMenuDirection.LeftEnd:
return 'left';
default:
return 'bottom';
}
}; // No need to do prop checks since these are alredy done in flyout
/* eslint-disable react/prop-types */
var DefaultFooter = function DefaultFooter(_ref) {
var setIsOpen = _ref.setIsOpen,
onCancel = _ref.onCancel,
onApply = _ref.onApply,
i18n = _ref.i18n;
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: "".concat(iotPrefix$2a, "--flyout-menu__cancel"),
kind: "secondary" // TODO: in v3 pass testId from parent and insert here to allow it to be configurable
// ie. `${testId}-menu-cancel`
,
testId: "flyout-menu-cancel",
onClick: function onClick() {
setIsOpen(false);
if (onCancel) {
onCancel();
}
},
"aria-label": i18n.cancelButtonText
}, i18n.cancelButtonText), /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: "".concat(iotPrefix$2a, "--flyout-menu__submit"),
"aria-label": i18n.applyButtonText // TODO: in v3 pass testId from parent and insert here to allow it to be configurable
// ie. `${testId}-menu-cancel`
,
testId: "flyout-menu-apply",
onClick: function onClick() {
setIsOpen(false);
if (onApply) {
onApply();
}
}
}, i18n.applyButtonText));
};
/* eslint-enable react/prop-types */
var FlyoutMenu = function FlyoutMenu(_ref2) {
var _classnames, _classnames2;
var buttonProps = _ref2.buttonProps,
buttonSize = _ref2.buttonSize,
direction = _ref2.direction,
menuOffset = _ref2.menuOffset,
defaultOpen = _ref2.defaultOpen,
iconDescription = _ref2.iconDescription,
children = _ref2.children,
disabled = _ref2.disabled,
i18n = _ref2.i18n,
light = _ref2.light,
renderIcon = _ref2.renderIcon,
testId = _ref2.testId,
tooltipId = _ref2.tooltipId,
triggerId = _ref2.triggerId,
tabIndex = _ref2.tabIndex,
tooltipClassName = _ref2.tooltipClassName,
tooltipContentClassName = _ref2.tooltipContentClassName,
passive = _ref2.passive,
tooltipFocusTrap = _ref2.tooltipFocusTrap,
hideTooltip = _ref2.hideTooltip,
CustomFooter = _ref2.customFooter,
onApply = _ref2.onApply,
onCancel = _ref2.onCancel,
useAutoPositioning = _ref2.useAutoPositioning,
onChange = _ref2.onChange,
isOpen = _ref2.isOpen,
renderInPortal = _ref2.renderInPortal,
style = _ref2.style;
var _useState = React$1.useState(defaultOpen),
_useState2 = slicedToArray$2(_useState, 2),
isControlledOpen = _useState2[0],
setIsOpen = _useState2[1];
var _useState3 = React$1.useState(getTooltipDirection(direction)),
_useState4 = slicedToArray$2(_useState3, 2),
tooltipDirection = _useState4[0],
setTooltipDirection = _useState4[1];
var buttonRef = React$1.useRef(null);
var updatedStyle = React$1.useMemo(function () {
var _style$zIndex;
return _objectSpread$24(_objectSpread$24({}, style), {}, {
'--zIndex': (_style$zIndex = style.zIndex) !== null && _style$zIndex !== void 0 ? _style$zIndex : 0,
'--top': style.scrollTop,
'--left': style.scrollLeft
});
}, [style]);
var getFlyoutMenuOffset = React__default['default'].useCallback(function (tooltipElement, flyoutDirection, tooltipButtonElement, flipped) {
var topOffset = 0;
var leftOffset = -2;
var caretWidth = 16;
var caretHeight = 12;
var borderWidth = 2;
var tooltipContent = tooltipElement.querySelector('[role="dialog"]');
var tooltipWidth = tooltipContent ? tooltipContent.getBoundingClientRect().width : 0;
var tooltipHeight = tooltipContent ? tooltipContent.getBoundingClientRect().height : 0;
var buttonWidth = buttonRef.current ? buttonRef.current.getBoundingClientRect().width : 0;
var rtlOffset = buttonWidth;
switch (flyoutDirection) {
case FlyoutMenuDirection.LeftStart:
topOffset = tooltipHeight / 2 - 2 * borderWidth - borderWidth;
rtlOffset = 0;
break;
// off
case FlyoutMenuDirection.LeftEnd:
topOffset = -tooltipHeight / 2 + 2 * caretHeight + caretWidth - (48 - buttonWidth) + borderWidth;
leftOffset = -caretWidth / 2;
rtlOffset = 0;
break;
case FlyoutMenuDirection.RightStart:
topOffset = tooltipHeight / 2 - caretHeight - 2 * borderWidth;
rtlOffset = -rtlOffset;
break;
// off
case FlyoutMenuDirection.RightEnd:
topOffset = -tooltipHeight / 2 + 2 * caretWidth + borderWidth;
rtlOffset = -rtlOffset;
break;
case FlyoutMenuDirection.TopStart:
leftOffset = tooltipWidth / 2;
topOffset = caretHeight;
break;
case FlyoutMenuDirection.TopEnd:
leftOffset = -tooltipWidth / 2 + buttonWidth;
topOffset = caretHeight - 2 * borderWidth;
break;
case FlyoutMenuDirection.BottomEnd:
topOffset = -caretHeight + 2 * borderWidth;
leftOffset = -tooltipWidth / 2 + buttonWidth;
break;
default:
// Bottom Start
leftOffset = tooltipWidth / 2;
topOffset = -caretHeight - 2 * borderWidth;
}
if (document.dir === 'rtl') {
leftOffset -= rtlOffset;
}
var propTop = 0;
var propLeft = 0;
if (typeof menuOffset === 'function') {
var _menuOffset = menuOffset(tooltipElement, flyoutDirection, tooltipButtonElement, flipped),
top = _menuOffset.top,
left = _menuOffset.left;
propTop = top;
propLeft = left;
} else if (_typeof_1$1(menuOffset) === 'object' && (menuOffset.hasOwnProperty('top') || menuOffset.hasOwnProperty('left'))) {
var _menuOffset$top = menuOffset.top,
_top = _menuOffset$top === void 0 ? 0 : _menuOffset$top,
_menuOffset$left = menuOffset.left,
_left = _menuOffset$left === void 0 ? 0 : _menuOffset$left;
propTop = _top;
propLeft = _left;
}
return {
top: topOffset + propTop,
left: leftOffset + propLeft
};
}, [menuOffset]);
var _usePopoverPositionin = usePopoverPositioning({
direction: direction,
menuOffset: getFlyoutMenuOffset,
useAutoPositioning: useAutoPositioning,
parenElementTop: menuOffset === null || menuOffset === void 0 ? void 0 : menuOffset.inputTop,
parentElementBottom: menuOffset === null || menuOffset === void 0 ? void 0 : menuOffset.inputBottom
}),
_usePopoverPositionin2 = slicedToArray$2(_usePopoverPositionin, 2),
calculateMenuOffset = _usePopoverPositionin2[0],
adjustedDirection = _usePopoverPositionin2[1].adjustedDirection;
React$1.useEffect(function () {
if (useAutoPositioning) {
setTooltipDirection(getTooltipDirection(adjustedDirection));
} else {
setTooltipDirection(getTooltipDirection(direction));
}
}, [adjustedDirection, direction, useAutoPositioning]);
var Footer = CustomFooter ? /*#__PURE__*/React__default['default'].createElement(CustomFooter, {
setIsOpen: setIsOpen,
isOpen: isControlledOpen
}) : /*#__PURE__*/React__default['default'].createElement(DefaultFooter, {
setIsOpen: setIsOpen,
onCancel: onCancel,
onApply: onApply,
i18n: i18n
});
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": "".concat(testId, "-container"),
style: {
'--tooltip-visibility': hideTooltip ? 'hidden' : 'visible'
},
ref: buttonRef,
className: classnames$1(["".concat(iotPrefix$2a, "--flyout-menu")], "".concat(iotPrefix$2a, "--flyout-menu__").concat(tooltipDirection), (_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$2a, "--flyout-menu__light"), light), defineProperty$d(_classnames, "".concat(iotPrefix$2a, "--flyout-menu__open"), isControlledOpen), _classnames))
}, /*#__PURE__*/React__default['default'].createElement(Button$1, _extends_1$1({}, buttonProps, {
"aria-label": iconDescription,
iconDescription: iconDescription,
className: classnames$1("".concat(iotPrefix$2a, "--flyout-menu--trigger-button"), buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.className),
disabled: disabled,
hasIconOnly: true,
kind: "ghost",
testId: "".concat(testId, "-button"),
size: buttonSize,
renderIcon: renderIcon,
onClick: function onClick() {
if (typeof buttonProps.onClick === 'function') {
buttonProps.onClick();
}
setIsOpen(!isControlledOpen);
}
})), /*#__PURE__*/React__default['default'].createElement("div", _extends_1$1({
className: "".concat(iotPrefix$2a, "--flyout-menu--tooltip-anchor")
}, !renderInPortal ? {
'data-floating-menu-container': true
} : {}), /*#__PURE__*/React__default['default'].createElement(Tooltip$2, {
disabled: disabled,
className: classnames$1(tooltipClassName, "".concat(iotPrefix$2a, "--flyout-menu--body"), "".concat(iotPrefix$2a, "--flyout-menu--body__").concat(useAutoPositioning ? adjustedDirection : direction), (_classnames2 = {}, defineProperty$d(_classnames2, "".concat(iotPrefix$2a, "--flyout-menu--body__light"), light), defineProperty$d(_classnames2, "".concat(iotPrefix$2a, "--flyout-menu--body__open"), typeof isOpen === 'boolean' ? isOpen : isControlledOpen), defineProperty$d(_classnames2, "".concat(iotPrefix$2a, "--flyout-menu--body__").concat(buttonSize), buttonSize !== 'default'), _classnames2)),
iconDescription: iconDescription,
"data-testid": testId,
showIcon: false,
focusTrap: tooltipFocusTrap,
open: typeof isOpen === 'boolean' ? isOpen : isControlledOpen,
direction: tooltipDirection,
menuOffset: calculateMenuOffset,
tooltipId: tooltipId,
id: tooltipId // https://github.com/carbon-design-system/carbon/pull/6744
,
triggerId: triggerId,
tabIndex: tabIndex,
useAutoPositioning: false,
onChange: onChange
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$2a, "--flyout-menu--content"), tooltipContentClassName),
style: updatedStyle
}, children), !passive && /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$2a, "--flyout-menu__bottom-container")
}, Footer))));
};
var propTypes$2j = {
tooltipId: PropTypes__default['default'].string,
/**
* The ID of the trigger button.
*/
triggerId: PropTypes__default['default'].string,
/**
* Optional starting value for uncontrolled state
*/
defaultOpen: PropTypes__default['default'].bool,
/**
* Contents to put into the flyout menu.
*/
children: PropTypes__default['default'].node,
/**
* The CSS class names of the flyout menu.
*/
tooltipClassName: PropTypes__default['default'].string,
/**
* The CSS class names of the tooltip content.
*/
tooltipContentClassName: PropTypes__default['default'].string,
/**
* whether to send focus to the tooltip when it's expanded
*/
tooltipFocusTrap: PropTypes__default['default'].bool,
/**
* Where to put the flyout menu, relative to the trigger UI.
*/
direction: PropTypes__default['default'].oneOf([FlyoutMenuDirection.BottomStart, FlyoutMenuDirection.BottomEnd, FlyoutMenuDirection.TopStart, FlyoutMenuDirection.TopEnd, FlyoutMenuDirection.LeftStart, FlyoutMenuDirection.LeftEnd, FlyoutMenuDirection.RightStart, FlyoutMenuDirection.RightEnd]),
/**
* The adjustment of the flyout position.
*/
menuOffset: PropTypes__default['default'].oneOfType([PropTypes__default['default'].shape({
top: PropTypes__default['default'].number,
left: PropTypes__default['default'].number,
inputTop: PropTypes__default['default'].number,
inputBottom: PropTypes__default['default'].number
}), PropTypes__default['default'].func]),
/**
* The description of the default flyout icon
*/
iconDescription: PropTypes__default['default'].string.isRequired,
/**
* Optional prop to specify the tabIndex of the Tooltip
*/
tabIndex: PropTypes__default['default'].number,
/**
* Optional prop to specify the test id of the flyout
*/
testId: PropTypes__default['default'].string,
/**
* Will not render a footer
*/
passive: PropTypes__default['default'].bool,
/**
* Whether to show the iconDescription tooltip on the trigger button
*/
hideTooltip: PropTypes__default['default'].bool,
/**
* Content to be rendered in place of the normal footer (ie. MyComponent).
*/
customFooter: PropTypes__default['default'].elementType,
/**
* On Cancel button callback
*/
onCancel: PropTypes__default['default'].func,
/**
* On Apply button callback
*/
onApply: PropTypes__default['default'].func,
/** Set of internationalized button names */
i18n: PropTypes__default['default'].shape({
cancelButtonText: PropTypes__default['default'].string,
applyButtonText: PropTypes__default['default'].string
}),
/**
* Define the icon render to be rendered.
* Can be a React component class
*/
renderIcon: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].object]),
/**
* Disable the button and tooltip
*/
disabled: PropTypes__default['default'].bool,
buttonSize: PropTypes__default['default'].string,
light: PropTypes__default['default'].bool,
useAutoPositioning: PropTypes__default['default'].bool,
onChange: PropTypes__default['default'].func,
/** classes that can be passed to the button used for the flyout menu */
buttonProps: PropTypes__default['default'].shape({
className: PropTypes__default['default'].string,
onClick: PropTypes__default['default'].func
}),
isOpen: PropTypes__default['default'].bool,
/** by default the flyout menu will render as a child, if you set this to true it will render outside of the current DOM in a portal */
renderInPortal: PropTypes__default['default'].bool,
style: PropTypes__default['default'].objectOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number]))
};
var defaultProps$2p = {
buttonProps: {},
renderIcon: iconsReact.SettingsAdjust16,
buttonSize: 'default',
tooltipId: 'flyout-tooltip',
triggerId: 'flyout-trigger-id',
defaultOpen: false,
children: undefined,
tooltipClassName: '',
tooltipContentClassName: '',
tooltipFocusTrap: true,
passive: false,
hideTooltip: true,
customFooter: null,
tabIndex: 0,
testId: 'flyout-menu',
direction: FlyoutMenuDirection.BottomStart,
menuOffset: {
top: 0,
left: 0,
inputTop: null,
inputBottom: null
},
i18n: {
cancelButtonText: 'Cancel',
applyButtonText: 'Apply'
},
isOpen: null,
onCancel: null,
onApply: null,
disabled: false,
light: true,
useAutoPositioning: false,
onChange: function onChange() {},
renderInPortal: false,
style: {}
};
FlyoutMenu.propTypes = propTypes$2j;
FlyoutMenu.defaultProps = defaultProps$2p;
FlyoutMenu.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "FlyoutMenu",
"props": {
"buttonProps": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"className": {
"name": "string",
"required": false
},
"onClick": {
"name": "func",
"required": false
}
}
},
"required": false,
"description": "classes that can be passed to the button used for the flyout menu"
},
"renderIcon": {
"defaultValue": {
"value": "SettingsAdjust",
"computed": true
},
"type": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "object"
}]
},
"required": false,
"description": "Define the icon render to be rendered.\nCan be a React component class"
},
"buttonSize": {
"defaultValue": {
"value": "'default'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"tooltipId": {
"defaultValue": {
"value": "'flyout-tooltip'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"triggerId": {
"defaultValue": {
"value": "'flyout-trigger-id'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The ID of the trigger button."
},
"defaultOpen": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Optional starting value for uncontrolled state"
},
"children": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "node"
},
"required": false,
"description": "Contents to put into the flyout menu."
},
"tooltipClassName": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The CSS class names of the flyout menu."
},
"tooltipContentClassName": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The CSS class names of the tooltip content."
},
"tooltipFocusTrap": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "whether to send focus to the tooltip when it's expanded"
},
"passive": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Will not render a footer"
},
"hideTooltip": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Whether to show the iconDescription tooltip on the trigger button"
},
"customFooter": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "elementType"
},
"required": false,
"description": "Content to be rendered in place of the normal footer (ie. MyComponent)."
},
"tabIndex": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "Optional prop to specify the tabIndex of the Tooltip"
},
"testId": {
"defaultValue": {
"value": "'flyout-menu'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Optional prop to specify the test id of the flyout"
},
"direction": {
"defaultValue": {
"value": "'bottom-start'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'bottom-start'",
"computed": false
}, {
"value": "'bottom-end'",
"computed": false
}, {
"value": "'top-start'",
"computed": false
}, {
"value": "'top-end'",
"computed": false
}, {
"value": "'left-start'",
"computed": false
}, {
"value": "'left-end'",
"computed": false
}, {
"value": "'right-start'",
"computed": false
}, {
"value": "'right-end'",
"computed": false
}]
},
"required": false,
"description": "Where to put the flyout menu, relative to the trigger UI."
},
"menuOffset": {
"defaultValue": {
"value": "{\n top: 0,\n left: 0,\n inputTop: null,\n inputBottom: null,\n}",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "shape",
"value": {
"top": {
"name": "number",
"required": false
},
"left": {
"name": "number",
"required": false
},
"inputTop": {
"name": "number",
"required": false
},
"inputBottom": {
"name": "number",
"required": false
}
}
}, {
"name": "func"
}]
},
"required": false,
"description": "The adjustment of the flyout position."
},
"i18n": {
"defaultValue": {
"value": "{\n cancelButtonText: 'Cancel',\n applyButtonText: 'Apply',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"cancelButtonText": {
"name": "string",
"required": false
},
"applyButtonText": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "Set of internationalized button names"
},
"isOpen": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"onCancel": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "On Cancel button callback"
},
"onApply": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "On Apply button callback"
},
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Disable the button and tooltip"
},
"light": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"useAutoPositioning": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"onChange": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"renderInPortal": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "by default the flyout menu will render as a child, if you set this to true it will render outside of the current DOM in a portal"
},
"style": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "objectOf",
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}]
}
},
"required": false,
"description": ""
},
"iconDescription": {
"type": {
"name": "string"
},
"required": true,
"description": "The description of the default flyout icon"
}
}
};
function ownKeys$23(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$23(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$23(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$23(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$29 = settings$1.iotPrefix,
prefix$t = settings$1.prefix;
var itemToString = function itemToString(key) {
return function (item) {
var _item$key;
return (_item$key = item === null || item === void 0 ? void 0 : item[key]) !== null && _item$key !== void 0 ? _item$key : '';
};
};
var propTypes$2i = {
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string,
/** When false, no filter shows */
isFilterable: PropTypes__default['default'].bool,
/** i18N text for translation */
placeholderText: PropTypes__default['default'].string,
/** if options is empty array, assume text input for filter */
options: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool]).isRequired,
text: PropTypes__default['default'].string.isRequired
})),
/** if dateOptions is empty array, assume a default format and locale */
dateOptions: PropTypes__default['default'].shape({
dateFormat: PropTypes__default['default'].string,
locale: PropTypes__default['default'].string
}),
/** if isMultiselect and isFilterable are true, the table is filtered based on a multiselect */
isMultiselect: PropTypes__default['default'].bool,
/** if isDate and isFilterable are true, the table is filtered base on a date picker */
isDate: PropTypes__default['default'].bool
})).isRequired,
tableState: PropTypes__default['default'].shape({
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
filters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
value: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool, PropTypes__default['default'].object, PropTypes__default['default'].arrayOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].object]))]).isRequired
})),
advancedFilters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** Unique id for particular filter */
filterId: PropTypes__default['default'].string.isRequired,
/** Text for main tilte of page */
filterTitleText: PropTypes__default['default'].string.isRequired
})),
advancedFilterFlyoutOpen: PropTypes__default['default'].bool,
selectedAdvancedFilterIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
isDisabled: PropTypes__default['default'].bool
}),
actions: PropTypes__default['default'].shape({
onApplyAdvancedFilter: PropTypes__default['default'].func,
onCancelAdvancedFilter: PropTypes__default['default'].func,
onCreateAdvancedFilter: PropTypes__default['default'].func,
onChangeAdvancedFilter: PropTypes__default['default'].func,
onToggleAdvancedFilter: PropTypes__default['default'].func
}),
i18n: PropTypes__default['default'].shape({
applyButtonText: PropTypes__default['default'].string,
cancelButtonText: PropTypes__default['default'].string,
advancedFilterLabelText: PropTypes__default['default'].string,
createNewAdvancedFilterText: PropTypes__default['default'].string,
advancedFilterPlaceholderText: PropTypes__default['default'].string,
simpleFiltersTabLabel: PropTypes__default['default'].string,
advancedFiltersTabLabel: PropTypes__default['default'].string,
clearAllFilters: PropTypes__default['default'].string,
filterAria: PropTypes__default['default'].string,
openMenuAria: PropTypes__default['default'].string,
closeMenuAria: PropTypes__default['default'].string,
clearSelectionAria: PropTypes__default['default'].string,
toolbarIconLabelText: PropTypes__default['default'].string
})
};
var reduceFilterState = function reduceFilterState(filters, selectedAdvancedFilterIds) {
var simple = {};
var advanced = {
filterIds: []
};
if (Array.isArray(filters) && filters.length) {
simple = filters.reduce(function (state, _ref) {
var columnId = _ref.columnId,
value = _ref.value;
return _objectSpread$23(_objectSpread$23({}, state), {}, defineProperty$d({}, columnId, value));
}, {});
}
if (Array.isArray(selectedAdvancedFilterIds) && selectedAdvancedFilterIds.length) {
advanced = {
filterIds: selectedAdvancedFilterIds
};
}
return {
simple: simple,
advanced: advanced
};
};
var defaultProps$2o = {
tableState: {
filters: [],
advancedFilters: [],
advancedFilterFlyoutOpen: false,
selectedAdvancedFilterIds: [],
isDisabled: false
},
actions: {
onApplyAdvancedFilter: defaultFunction('on AdvancedFilter'),
onCancelAdvancedFilter: defaultFunction('onCancelAdvancedFilter'),
onCreateAdvancedFilter: defaultFunction('onCreateAdvancedFilter'),
onChangeAdvancedFilter: defaultFunction('onChangeAdvancedFilter'),
onToggleAdvancedFilter: defaultFunction('onToggleAdvancedFilter')
},
i18n: {
applyButtonText: 'Apply filters',
cancelButtonText: 'Cancel',
advancedFilterLabelText: 'Select an existing filter or',
createNewAdvancedFilterText: 'create a new advanced filter',
advancedFilterPlaceholderText: 'Select a filter',
simpleFiltersTabLabel: 'Simple filters',
advancedFiltersTabLabel: 'Advanced filters',
filterAria: 'Filter',
openMenuAria: 'Open menu',
closeMenuAria: 'Close menu',
clearSelectionAria: 'Clear selection',
clearFilterAria: 'Clear filter',
toolbarIconLabelText: 'Toggle advanced filters'
}
};
var TableToolbarAdvancedFilterFlyout = function TableToolbarAdvancedFilterFlyout(_ref2) {
var columns = _ref2.columns,
_ref2$tableState = _ref2.tableState,
ordering = _ref2$tableState.ordering,
filters = _ref2$tableState.filters,
advancedFilters = _ref2$tableState.advancedFilters,
advancedFilterFlyoutOpen = _ref2$tableState.advancedFilterFlyoutOpen,
selectedAdvancedFilterIds = _ref2$tableState.selectedAdvancedFilterIds,
isDisabled = _ref2$tableState.isDisabled,
i18n = _ref2.i18n,
_ref2$actions = _ref2.actions,
onApplyAdvancedFilter = _ref2$actions.onApplyAdvancedFilter,
onCancelAdvancedFilter = _ref2$actions.onCancelAdvancedFilter,
onCreateAdvancedFilter = _ref2$actions.onCreateAdvancedFilter,
onChangeAdvancedFilter = _ref2$actions.onChangeAdvancedFilter,
onToggleAdvancedFilter = _ref2$actions.onToggleAdvancedFilter;
var _defaultProps$i18n = _objectSpread$23(_objectSpread$23({}, defaultProps$2o.i18n), i18n !== null && i18n !== void 0 ? i18n : {}),
applyButtonText = _defaultProps$i18n.applyButtonText,
cancelButtonText = _defaultProps$i18n.cancelButtonText,
advancedFilterLabelText = _defaultProps$i18n.advancedFilterLabelText,
createNewAdvancedFilterText = _defaultProps$i18n.createNewAdvancedFilterText,
advancedFilterPlaceholderText = _defaultProps$i18n.advancedFilterPlaceholderText,
simpleFiltersTabLabel = _defaultProps$i18n.simpleFiltersTabLabel,
advancedFiltersTabLabel = _defaultProps$i18n.advancedFiltersTabLabel,
filterAria = _defaultProps$i18n.filterAria,
openMenuAria = _defaultProps$i18n.openMenuAria,
closeMenuAria = _defaultProps$i18n.closeMenuAria,
clearSelectionAria = _defaultProps$i18n.clearSelectionAria,
clearFilterAria = _defaultProps$i18n.clearFilterAria,
toolbarIconLabelText = _defaultProps$i18n.toolbarIconLabelText;
var _useState = React$1.useState(reduceFilterState(filters, selectedAdvancedFilterIds)),
_useState2 = slicedToArray$2(_useState, 2),
filterState = _useState2[0],
setFilterState = _useState2[1];
var previousFilters = React$1.useRef(null);
React$1.useEffect(function () {
if (!isEqual$1(previousFilters.current, {
filters: filters,
selectedAdvancedFilterIds: selectedAdvancedFilterIds
})) {
var newState = reduceFilterState(filters, selectedAdvancedFilterIds);
if (!isEqual$1(newState, filterState)) {
setFilterState(newState);
onApplyAdvancedFilter(newState);
}
}
}, [filterState, filters, onApplyAdvancedFilter, selectedAdvancedFilterIds]);
React$1.useEffect(function () {
previousFilters.current = {
filters: filters,
selectedAdvancedFilterIds: selectedAdvancedFilterIds
};
});
var handleClearFilter = React$1.useCallback(function (event, _ref3) {
var id = _ref3.id;
setFilterState(function (prev) {
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
simple: _objectSpread$23(_objectSpread$23({}, prev.simple), {}, defineProperty$d({}, id, ''))
});
});
}, []);
var handleTranslation = React$1.useCallback(function (idToTranslate) {
switch (idToTranslate) {
default:
return '';
case 'clear.selection':
return clearSelectionAria;
case 'clear.all':
return clearSelectionAria;
case 'open.menu':
return openMenuAria;
case 'close.menu':
return closeMenuAria;
}
}, [clearSelectionAria, closeMenuAria, openMenuAria]);
return /*#__PURE__*/React__default['default'].createElement(FlyoutMenu, {
testId: "advanced-filter-flyout",
iconDescription: toolbarIconLabelText,
direction: FlyoutMenuDirection.BottomEnd,
disabled: isDisabled,
renderIcon: iconsReact.Filter20,
hideTooltip: false,
light: true,
isOpen: advancedFilterFlyoutOpen,
onApply: function onApply() {
onApplyAdvancedFilter(filterState);
},
onCancel: function onCancel() {
setFilterState(reduceFilterState(filters, selectedAdvancedFilterIds));
onCancelAdvancedFilter();
},
buttonProps: {
className: classnames$1("".concat(prefix$t, "--btn--icon-only"), "".concat(iotPrefix$29, "--tooltip-svg-wrapper"), "".concat(iotPrefix$29, "--table-toolbar__advanced-filters-button"), defineProperty$d({}, "".concat(iotPrefix$29, "--table-toolbar-button-active"), advancedFilterFlyoutOpen)),
onClick: onToggleAdvancedFilter,
tooltipPosition: 'bottom'
},
i18n: {
applyButtonText: applyButtonText,
cancelButtonText: cancelButtonText
}
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tabs, {
className: "".concat(iotPrefix$29, "--advanced-filter__tab-container")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tab, {
label: simpleFiltersTabLabel,
title: simpleFiltersTabLabel
}, ordering.filter(function (column) {
var fullColumn = columns.find(function (item) {
return column.columnId === item.id;
});
return !column.isHidden && (fullColumn === null || fullColumn === void 0 ? void 0 : fullColumn.isFilterable) === true;
}).reduce(function (chunks, item, index) {
var newChunks = toConsumableArray(chunks);
var chunkIndex = Math.floor(index / 2);
if (!chunks[chunkIndex]) {
newChunks[chunkIndex] = [];
}
newChunks[chunkIndex] = [].concat(toConsumableArray(newChunks[chunkIndex]), [item]);
return newChunks;
}, []).map(function (aRow, rowIndex) {
return /*#__PURE__*/React__default['default'].createElement("div", {
key: "simple-filter-row-".concat(rowIndex),
className: "".concat(iotPrefix$29, "--filter-flyout__simple-row")
}, aRow.map(function (aColumn, columnIndex) {
var _filterState$simple2, _filterState$simple3;
var column = columns.find(function (item) {
return aColumn.columnId === item.id;
});
var columnFilterValue = filterState === null || filterState === void 0 ? void 0 : filterState.simple[column.id];
var filterColumnOptions = function filterColumnOptions(options) {
options.sort(function (a, b) {
return a.text.localeCompare(b.text, {
sensitivity: 'base'
});
});
return options;
};
var memoizeColumnOptions = memoize$1(filterColumnOptions); // TODO: this memoize isn't really working, should refactor to a higher column level
if (column.isDate) {
var _column$dateOptions, _column$dateOptions2, _filterState$simple;
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.FormItem, {
key: "simple-filter-item-".concat(rowIndex, "-").concat(columnIndex),
className: "".concat(iotPrefix$29, "--filter-flyout__simple-field")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.DatePicker, {
key: "datepicker-".concat(rowIndex, "-").concat(columnIndex, "-").concat(columnFilterValue),
datePickerType: "single",
locale: (column === null || column === void 0 ? void 0 : (_column$dateOptions = column.dateOptions) === null || _column$dateOptions === void 0 ? void 0 : _column$dateOptions.locale) || 'en',
dateFormat: (column === null || column === void 0 ? void 0 : (_column$dateOptions2 = column.dateOptions) === null || _column$dateOptions2 === void 0 ? void 0 : _column$dateOptions2.dateFormat) || 'Y-m-d',
id: "column-".concat(rowIndex, "-").concat(columnIndex),
value: filterState === null || filterState === void 0 ? void 0 : (_filterState$simple = filterState.simple) === null || _filterState$simple === void 0 ? void 0 : _filterState$simple[column.id],
onChange: function onChange(evt) {
setFilterState(function (prev) {
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
simple: _objectSpread$23(_objectSpread$23({}, prev.simple), {}, defineProperty$d({}, column.id, evt[0]))
});
});
}
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.DatePickerInput, {
className: "".concat(iotPrefix$29, "--lelele"),
placeholder: column.placeholderText || 'enter a date',
labelText: column.name,
id: "column-".concat(rowIndex, "-").concat(columnIndex)
})));
}
if (column.options) {
if (column.isMultiselect) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.FilterableMultiSelect, {
className: "".concat(iotPrefix$29, "--filter-flyout__simple-field"),
key: "multiselect-".concat(rowIndex, "-").concat(columnIndex, "-").concat(columnFilterValue),
id: "column-".concat(rowIndex, "-").concat(columnIndex),
"aria-label": filterAria,
placeholder: column.placeholderText || 'Choose an option',
translateWithId: handleTranslation,
items: memoizeColumnOptions(column.options),
label: column.placeholderText || 'Choose an option',
itemToString: itemToString('text'),
titleText: column.name,
initialSelectedItems: getMultiSelectItems(column, columnFilterValue),
onChange: function onChange(evt) {
var selectedItems = evt.selectedItems;
setFilterState(function (prev) {
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
simple: _objectSpread$23(_objectSpread$23({}, prev.simple), {}, defineProperty$d({}, column.id, selectedItems.map(getMultiselectFilterValue)))
});
});
}
});
}
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.ComboBox, {
className: "".concat(iotPrefix$29, "--filter-flyout__simple-field"),
key: "combobox-".concat(rowIndex, "-").concat(columnIndex, "-").concat(columnFilterValue),
id: "column-".concat(columnIndex),
"aria-label": filterAria,
translateWithId: handleTranslation,
items: memoizeColumnOptions(column.options),
itemToString: itemToString('text'),
initialSelectedItem: {
id: columnFilterValue,
text: getAppliedFilterText(column, columnFilterValue)
},
placeholder: column.placeholderText || 'Choose an option',
titleText: column.name,
onChange: function onChange(evt) {
var selectedItem = evt.selectedItem;
setFilterState(function (prev) {
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
simple: _objectSpread$23(_objectSpread$23({}, prev.simple), {}, defineProperty$d({}, column.id, getFilterValue(selectedItem)))
});
});
}
});
}
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.FormItem, {
key: "simple-filter-item-".concat(rowIndex, "-").concat(columnIndex),
className: "".concat(iotPrefix$29, "--filter-flyout__simple-field")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TextInput, {
id: column.id,
labelText: column.name,
placeholder: column.placeholderText || 'Type and hit enter to apply',
title: (filterState === null || filterState === void 0 ? void 0 : filterState[column.id]) || column.placeholderText,
onChange: function onChange(event) {
var value = event.target.value;
setFilterState(function (prev) {
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
simple: _objectSpread$23(_objectSpread$23({}, prev.simple), {}, defineProperty$d({}, column.id, value))
});
});
},
defaultValue: filterState === null || filterState === void 0 ? void 0 : (_filterState$simple2 = filterState.simple) === null || _filterState$simple2 === void 0 ? void 0 : _filterState$simple2[column.id]
}), filterState !== null && filterState !== void 0 && (_filterState$simple3 = filterState.simple) !== null && _filterState$simple3 !== void 0 && _filterState$simple3[column.id] ? /*#__PURE__*/React__default['default'].createElement("div", {
role: "button",
className: classnames$1("".concat(prefix$t, "--list-box__selection"), defineProperty$d({}, "".concat(iotPrefix$29, "--clear-filters-button--disabled"), isDisabled)),
tabIndex: isDisabled ? '-1' : '0',
onClick: function onClick(event) {
if (!isDisabled) {
handleClearFilter(event, column);
}
},
onKeyDown: function onKeyDown(event) {
return handleEnterKeyDown(event, function () {
if (!isDisabled) {
handleClearFilter(event, column);
}
});
},
title: clearFilterAria
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Close16, {
description: clearFilterAria
})) : null);
}));
})), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tab, {
label: advancedFiltersTabLabel,
title: advancedFiltersTabLabel
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.MultiSelect, {
id: "advanced-filter-multiselect",
titleText: /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, advancedFilterLabelText, ' ', /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Button, {
className: "".concat(iotPrefix$29, "--advanced-filter__inline-button"),
kind: "ghost",
onClick: onCreateAdvancedFilter
}, createNewAdvancedFilterText)),
onChange: function onChange(e) {
onChangeAdvancedFilter(e);
setFilterState(function (prev) {
var _e$selectedItems$map, _e$selectedItems;
return _objectSpread$23(_objectSpread$23({}, prev), {}, {
advanced: {
filterIds: (_e$selectedItems$map = (_e$selectedItems = e.selectedItems) === null || _e$selectedItems === void 0 ? void 0 : _e$selectedItems.map(function (advFilter) {
return advFilter.filterId;
})) !== null && _e$selectedItems$map !== void 0 ? _e$selectedItems$map : []
}
});
});
},
itemToString: itemToString('filterTitleText'),
items: advancedFilters !== null && advancedFilters !== void 0 ? advancedFilters : [],
initialSelectedItems: advancedFilters === null || advancedFilters === void 0 ? void 0 : advancedFilters.filter(function (advFilter) {
return selectedAdvancedFilterIds.includes(advFilter.filterId);
}),
label: advancedFilterPlaceholderText
}))));
};
TableToolbarAdvancedFilterFlyout.propTypes = propTypes$2i;
TableToolbarAdvancedFilterFlyout.defaultProps = defaultProps$2o;
TableToolbarAdvancedFilterFlyout.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableToolbarAdvancedFilterFlyout",
"props": {
"tableState": {
"defaultValue": {
"value": "{\n filters: [],\n advancedFilters: [],\n advancedFilterFlyoutOpen: false,\n selectedAdvancedFilterIds: [],\n isDisabled: false,\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"ordering": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
},
"required": true
},
"filters": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}, {
"name": "object"
}, {
"name": "arrayOf",
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "object"
}]
}
}],
"required": true
}
}
},
"required": false
},
"advancedFilters": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"filterId": {
"name": "string",
"description": "Unique id for particular filter",
"required": true
},
"filterTitleText": {
"name": "string",
"description": "Text for main tilte of page",
"required": true
}
}
},
"required": false
},
"advancedFilterFlyoutOpen": {
"name": "bool",
"required": false
},
"selectedAdvancedFilterIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"required": false
},
"isDisabled": {
"name": "bool",
"required": false
}
}
},
"required": false,
"description": ""
},
"actions": {
"defaultValue": {
"value": "{\n onApplyAdvancedFilter: defaultFunction('on AdvancedFilter'),\n onCancelAdvancedFilter: defaultFunction('onCancelAdvancedFilter'),\n onCreateAdvancedFilter: defaultFunction('onCreateAdvancedFilter'),\n onChangeAdvancedFilter: defaultFunction('onChangeAdvancedFilter'),\n onToggleAdvancedFilter: defaultFunction('onToggleAdvancedFilter'),\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"onApplyAdvancedFilter": {
"name": "func",
"required": false
},
"onCancelAdvancedFilter": {
"name": "func",
"required": false
},
"onCreateAdvancedFilter": {
"name": "func",
"required": false
},
"onChangeAdvancedFilter": {
"name": "func",
"required": false
},
"onToggleAdvancedFilter": {
"name": "func",
"required": false
}
}
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n applyButtonText: 'Apply filters',\n cancelButtonText: 'Cancel',\n advancedFilterLabelText: 'Select an existing filter or',\n createNewAdvancedFilterText: 'create a new advanced filter',\n advancedFilterPlaceholderText: 'Select a filter',\n simpleFiltersTabLabel: 'Simple filters',\n advancedFiltersTabLabel: 'Advanced filters',\n filterAria: 'Filter',\n openMenuAria: 'Open menu',\n closeMenuAria: 'Close menu',\n clearSelectionAria: 'Clear selection',\n clearFilterAria: 'Clear filter',\n toolbarIconLabelText: 'Toggle advanced filters',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"applyButtonText": {
"name": "string",
"required": false
},
"cancelButtonText": {
"name": "string",
"required": false
},
"advancedFilterLabelText": {
"name": "string",
"required": false
},
"createNewAdvancedFilterText": {
"name": "string",
"required": false
},
"advancedFilterPlaceholderText": {
"name": "string",
"required": false
},
"simpleFiltersTabLabel": {
"name": "string",
"required": false
},
"advancedFiltersTabLabel": {
"name": "string",
"required": false
},
"clearAllFilters": {
"name": "string",
"required": false
},
"filterAria": {
"name": "string",
"required": false
},
"openMenuAria": {
"name": "string",
"required": false
},
"closeMenuAria": {
"name": "string",
"required": false
},
"clearSelectionAria": {
"name": "string",
"required": false
},
"toolbarIconLabelText": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": ""
},
"columns": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": false
},
"isFilterable": {
"name": "bool",
"description": "When false, no filter shows",
"required": false
},
"placeholderText": {
"name": "string",
"description": "i18N text for translation",
"required": false
},
"options": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}],
"required": true
},
"text": {
"name": "string",
"required": true
}
}
},
"description": "if options is empty array, assume text input for filter",
"required": false
},
"dateOptions": {
"name": "shape",
"value": {
"dateFormat": {
"name": "string",
"required": false
},
"locale": {
"name": "string",
"required": false
}
},
"description": "if dateOptions is empty array, assume a default format and locale",
"required": false
},
"isMultiselect": {
"name": "bool",
"description": "if isMultiselect and isFilterable are true, the table is filtered based on a multiselect",
"required": false
},
"isDate": {
"name": "bool",
"description": "if isDate and isFilterable are true, the table is filtered base on a date picker",
"required": false
}
}
}
},
"required": true,
"description": ""
}
}
};
function ownKeys$22(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$22(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$22(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$22(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$28 = settings$1.iotPrefix;
var propTypes$2h = {
/** id of table */
tableId: PropTypes__default['default'].string.isRequired,
/** global table options */
options: PropTypes__default['default'].shape({
/** If true, search is applied as typed. If false, only after 'Enter' is pressed */
hasFastSearch: PropTypes__default['default'].bool,
// True if use can save/load views
hasUserViewManagement: PropTypes__default['default'].bool
}).isRequired,
/** internationalized labels */
i18n: PropTypes__default['default'].shape({
clearAllFilters: PropTypes__default['default'].string,
columnSelectionButtonAria: PropTypes__default['default'].string,
filterButtonAria: PropTypes__default['default'].string,
editButtonAria: PropTypes__default['default'].string,
searchLabel: PropTypes__default['default'].string,
searchPlaceholder: PropTypes__default['default'].string,
batchCancel: PropTypes__default['default'].string,
itemsSelected: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func]),
itemSelected: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func]),
filterNone: PropTypes__default['default'].string,
filterAscending: PropTypes__default['default'].string,
filterDescending: PropTypes__default['default'].string,
toggleAggregations: PropTypes__default['default'].string,
toolbarLabelAria: PropTypes__default['default'].string,
rowCountInHeader: PropTypes__default['default'].func,
downloadIconDescription: PropTypes__default['default'].string,
/** aria-label applied to the tooltip in the toolbar (if given) */
toolbarTooltipLabel: PropTypes__default['default'].string,
/** button label for batch action overflow menu */
batchActionsOverflowMenuText: PropTypes__default['default'].string,
/** I18N label for search icon in toolbar */
toolbarSearchIconDescription: PropTypes__default['default'].string
}),
/**
* Action callbacks to update tableState
*/
actions: PropTypes__default['default'].shape({
onApplySearch: PropTypes__default['default'].func,
onSearchExpand: PropTypes__default['default'].func
}).isRequired,
/**
* Inbound tableState
*/
tableState: PropTypes__default['default'].shape({
/** is the toolbar currently disabled */
isDisabled: PropTypes__default['default'].bool,
search: TableSearchPropTypes
}).isRequired,
testId: PropTypes__default['default'].string,
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl']),
tooltipAlignment: PropTypes__default['default'].oneOf(['start', 'center', 'end'])
};
var defaultProps$2n = {
i18n: _objectSpread$22({}, defaultI18NPropTypes),
testId: '',
langDir: 'ltr',
tooltipAlignment: 'center'
};
var TableToolbarSearch = function TableToolbarSearch(_ref) {
var tableId = _ref.tableId,
i18n = _ref.i18n,
_ref$options = _ref.options,
hasFastSearch = _ref$options.hasFastSearch,
hasUserViewManagement = _ref$options.hasUserViewManagement,
_ref$actions = _ref.actions,
onApplySearch = _ref$actions.onApplySearch,
onSearchExpand = _ref$actions.onSearchExpand,
_ref$tableState = _ref.tableState,
searchProp = _ref$tableState.search,
isDisabled = _ref$tableState.isDisabled,
testId = _ref.testId,
langDir = _ref.langDir,
tooltipAlignment = _ref.tooltipAlignment;
/* istanbul ignore next */
var _ref2 = searchProp !== null && searchProp !== void 0 ? searchProp : {},
searchIsExpanded = _ref2.isExpanded,
_onExpand = _ref2.onExpand,
search = objectWithoutProperties$1(_ref2, ["isExpanded", "onExpand"]);
/**
* Needed to force update component if search input is cleared from outside of TableToolbar
* Reference: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate
*/
var _useState = React$1.useState(0),
_useState2 = slicedToArray$2(_useState, 2),
forceRenderCount = _useState2[0],
setForceRenderCount = _useState2[1];
var _useState3 = React$1.useState(false),
_useState4 = slicedToArray$2(_useState3, 2),
showSearchTooltip = _useState4[0],
setShowSearchTooltip = _useState4[1];
var _useState5 = React$1.useState(tooltipAlignment),
_useState6 = slicedToArray$2(_useState5, 2),
adjustedTooltipAlignment = _useState6[0],
setAdjustedTooltipAlignment = _useState6[1];
React$1.useEffect(function () {
var _document$activeEleme;
/* istanbul ignore else */
if (((_document$activeEleme = document.activeElement) === null || _document$activeEleme === void 0 ? void 0 : _document$activeEleme.tagName) === 'INPUT') {
return;
}
setForceRenderCount(function (prevValue) {
return prevValue + 1;
});
}, [search.defaultValue]);
/* istanbul ignore next */
var handleSearchMouseEnter = React$1.useCallback(function () {
setShowSearchTooltip(true);
}, []);
/* istanbul ignore next */
var handleSearchMouseLeave = React$1.useCallback(function () {
setShowSearchTooltip(false);
}, []);
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$28, "--table-toolbar__search-wrapper")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableToolbarSearch, _extends_1$1({}, search, {
onPointerEnter: handleSearchMouseEnter,
onPointerLeave: handleSearchMouseLeave,
key: // If hasUserViewManagement is active the whole table is regenerated when a new
// view is loaded so we probably don't need this key-gen fix to preset a search text.
// The userViewManagement also needs to be able to set the search.defaultValue
// while typing without loosing input focus.
hasUserViewManagement ? "table-toolbar-search-".concat(forceRenderCount) : "table-toolbar-search-user-view-".concat(forceRenderCount),
defaultValue: search.defaultValue || search.value,
className: "table-toolbar-search",
translateWithId: function translateWithId() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return tableTranslateWithId.apply(void 0, [i18n].concat(args));
},
id: "".concat(tableId, "-toolbar-search"),
onChange: function onChange(event, defaultValue) {
var _event$target;
var value = (event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.value) || (defaultValue !== null && defaultValue !== void 0 ? defaultValue : '');
/* istanbul ignore else */
if (hasFastSearch) {
onApplySearch(value);
}
},
onKeyDown: hasFastSearch ? undefined : handleSpecificKeyDown(['Enter'], function (e) {
return onApplySearch(e.target.value);
}),
onClear: function onClear() {
return onApplySearch('');
},
onBlur: !hasFastSearch ? function (e, handleExpand) {
var value = e.target.value;
onApplySearch(value);
if (!value) {
handleExpand(e, false);
}
} : undefined,
disabled: isDisabled // TODO: remove deprecated 'testID' in v3
,
"data-testid": "".concat(testId, "-search"),
expanded: searchIsExpanded || undefined,
onExpand: function onExpand() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
/* istanbul ignore if */
if (_onExpand) _onExpand(args); // Deprecated callback
/* istanbul ignore else */
if (onSearchExpand) onSearchExpand(args);
}
})), /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$28, "--table-toolbar__search-tooltip"), "".concat(iotPrefix$28, "--table-toolbar__search-tooltip--").concat(adjustedTooltipAlignment), defineProperty$d({}, "".concat(iotPrefix$28, "--table-toolbar__search-tooltip--hide"), !showSearchTooltip)),
ref: function ref(node) {
/* istanbul ignore if */
if (node && node.parentNode) {
var tooltipRect = node.getBoundingClientRect();
var toolbarRect = node.parentNode.parentNode.getBoundingClientRect();
/* istanbul ignore else */
if (langDir === 'ltr' && tooltipRect.left + tooltipRect.width > toolbarRect.left + toolbarRect.width) {
setAdjustedTooltipAlignment('end');
return;
}
/* istanbul ignore if */
if (langDir === 'rtl' && tooltipRect.left < toolbarRect.left) {
setAdjustedTooltipAlignment('start');
}
}
}
}, i18n.toolbarSearchIconDescription));
};
TableToolbarSearch.propTypes = propTypes$2h;
TableToolbarSearch.defaultProps = defaultProps$2n;
TableToolbarSearch.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableToolbarSearch",
"props": {
"i18n": {
"defaultValue": {
"value": "{\n ...defaultI18NPropTypes,\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"clearAllFilters": {
"name": "string",
"required": false
},
"columnSelectionButtonAria": {
"name": "string",
"required": false
},
"filterButtonAria": {
"name": "string",
"required": false
},
"editButtonAria": {
"name": "string",
"required": false
},
"searchLabel": {
"name": "string",
"required": false
},
"searchPlaceholder": {
"name": "string",
"required": false
},
"batchCancel": {
"name": "string",
"required": false
},
"itemsSelected": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}],
"required": false
},
"itemSelected": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}],
"required": false
},
"filterNone": {
"name": "string",
"required": false
},
"filterAscending": {
"name": "string",
"required": false
},
"filterDescending": {
"name": "string",
"required": false
},
"toggleAggregations": {
"name": "string",
"required": false
},
"toolbarLabelAria": {
"name": "string",
"required": false
},
"rowCountInHeader": {
"name": "func",
"required": false
},
"downloadIconDescription": {
"name": "string",
"required": false
},
"toolbarTooltipLabel": {
"name": "string",
"description": "aria-label applied to the tooltip in the toolbar (if given)",
"required": false
},
"batchActionsOverflowMenuText": {
"name": "string",
"description": "button label for batch action overflow menu",
"required": false
},
"toolbarSearchIconDescription": {
"name": "string",
"description": "I18N label for search icon in toolbar",
"required": false
}
}
},
"required": false,
"description": "internationalized labels"
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": ""
},
"tooltipAlignment": {
"defaultValue": {
"value": "'center'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'start'",
"computed": false
}, {
"value": "'center'",
"computed": false
}, {
"value": "'end'",
"computed": false
}]
},
"required": false,
"description": ""
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "id of table"
},
"options": {
"type": {
"name": "shape",
"value": {
"hasFastSearch": {
"name": "bool",
"description": "If true, search is applied as typed. If false, only after 'Enter' is pressed",
"required": false
},
"hasUserViewManagement": {
"name": "bool",
"required": false
}
}
},
"required": true,
"description": "global table options"
},
"actions": {
"type": {
"name": "shape",
"value": {
"onApplySearch": {
"name": "func",
"required": false
},
"onSearchExpand": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": "Action callbacks to update tableState"
},
"tableState": {
"type": {
"name": "shape",
"value": {
"isDisabled": {
"name": "bool",
"description": "is the toolbar currently disabled",
"required": false
},
"search": {
"name": "custom",
"raw": "TableSearchPropTypes",
"required": false
}
}
},
"required": true,
"description": "Inbound tableState"
}
}
};
function ownKeys$21(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$21(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$21(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$21(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$27 = settings$1.iotPrefix;
var propTypes$2g = {
/** id of table */
tableId: PropTypes__default['default'].string.isRequired,
secondaryTitle: PropTypes__default['default'].string,
tooltip: PropTypes__default['default'].node,
/** global table options */
options: PropTypes__default['default'].shape({
hasAdvancedFilter: PropTypes__default['default'].bool,
hasAggregations: PropTypes__default['default'].bool,
/* option to hide batch action toolbar */
hasBatchActionToolbar: PropTypes__default['default'].bool,
/** If true, search is applied as typed. If false, only after 'Enter' is pressed */
hasFastSearch: PropTypes__default['default'].bool,
hasFilter: PropTypes__default['default'].bool,
hasSearch: PropTypes__default['default'].bool,
hasColumnSelection: PropTypes__default['default'].bool,
hasRowEdit: PropTypes__default['default'].bool,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
onApplySearch: PropTypes__default['default'].func,
onDownloadCSV: PropTypes__default['default'].func,
onApplyAdvancedFilter: PropTypes__default['default'].func,
/** Optional boolean to render rowCount in header
* NOTE: Deprecated in favor of secondaryTitle for custom use
*/
hasRowCountInHeader: deprecate$2(PropTypes__default['default'].bool, '\n The prop `hasRowCountInHeader` has been deprecated in favor `secondaryTitle`'),
// True if use can save/load views
hasUserViewManagement: PropTypes__default['default'].bool
}).isRequired,
/** internationalized labels */
i18n: PropTypes__default['default'].shape({
clearAllFilters: PropTypes__default['default'].string,
columnSelectionButtonAria: PropTypes__default['default'].string,
filterButtonAria: PropTypes__default['default'].string,
editButtonAria: PropTypes__default['default'].string,
searchLabel: PropTypes__default['default'].string,
searchPlaceholder: PropTypes__default['default'].string,
batchCancel: PropTypes__default['default'].string,
itemsSelected: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func]),
itemSelected: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func]),
filterNone: PropTypes__default['default'].string,
filterAscending: PropTypes__default['default'].string,
filterDescending: PropTypes__default['default'].string,
toggleAggregations: PropTypes__default['default'].string,
toolbarLabelAria: PropTypes__default['default'].string,
rowCountInHeader: PropTypes__default['default'].func,
downloadIconDescription: PropTypes__default['default'].string,
/** aria-label applied to the tooltip in the toolbar (if given) */
toolbarTooltipLabel: PropTypes__default['default'].string,
/** button label for batch action overflow menu */
batchActionsOverflowMenuText: PropTypes__default['default'].string,
/** I18N label for search icon in toolbar */
toolbarSearchIconDescription: PropTypes__default['default'].string
}),
/**
* Action callbacks to update tableState
*/
actions: PropTypes__default['default'].shape({
onCancelBatchAction: PropTypes__default['default'].func,
onApplyBatchAction: PropTypes__default['default'].func,
onClearAllFilters: PropTypes__default['default'].func,
onToggleAggregations: PropTypes__default['default'].func,
onToggleColumnSelection: PropTypes__default['default'].func,
onToggleFilter: PropTypes__default['default'].func,
onToggleAdvancedFilter: PropTypes__default['default'].func,
onCreateAdvancedFilter: PropTypes__default['default'].func,
onChangeAdvancedFilter: PropTypes__default['default'].func,
onCancelAdvancedFilter: PropTypes__default['default'].func,
onApplyAdvancedFilter: PropTypes__default['default'].func,
onShowRowEdit: PropTypes__default['default'].func,
onApplySearch: PropTypes__default['default'].func,
onDownloadCSV: PropTypes__default['default'].func,
onApplyToolbarAction: PropTypes__default['default'].func,
onSearchExpand: PropTypes__default['default'].func
}).isRequired,
/**
* Inbound tableState
*/
tableState: PropTypes__default['default'].shape({
/** is the toolbar currently disabled */
isDisabled: PropTypes__default['default'].bool,
/** Which toolbar is currently active */
activeBar: ActiveTableToolbarPropType,
/** total number of selected rows */
totalSelected: PropTypes__default['default'].number,
totalItemsCount: PropTypes__default['default'].number,
advancedFilterFlyoutOpen: PropTypes__default['default'].bool,
totalFilters: PropTypes__default['default'].number,
filters: TableFiltersPropType,
columns: TableColumnsPropTypes,
ordering: TableOrderingPropType,
/** row selection option */
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
/** optional content to render inside the toolbar */
customToolbarContent: PropTypes__default['default'].node,
/** available batch actions */
batchActions: PropTypes__default['default'].arrayOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].shape(_objectSpread$21(_objectSpread$21({}, TableSharedActionPropTypes), {}, {
iconDescription: PropTypes__default['default'].string
})), PropTypes__default['default'].shape(_objectSpread$21(_objectSpread$21({}, TableSharedOverflowMenuPropTypes), {}, {
iconDescription: PropTypes__default['default'].string
}))])),
search: TableSearchPropTypes,
/** buttons to be shown with when activeBar is 'rowEdit' */
rowEditBarButtons: PropTypes__default['default'].node,
/** a stripped down version of the RuleBuilderFilterPropType */
advancedFilters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** Unique id for particular filter */
filterId: PropTypes__default['default'].string.isRequired,
/** Text for main title of page */
filterTitleText: PropTypes__default['default'].string.isRequired,
filterRules: RuleGroupPropType.isRequired
})),
/** currently selected advanced filters */
selectedAdvancedFilterIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** toolbar actions that can appear in an overflow menu in the toolbar (same menu as toggle aggregations) */
toolbarActions: TableToolbarActionsPropType,
/** force hide Clear all filters button in toolbar */
hideClearAllFiltersButton: PropTypes__default['default'].bool
}).isRequired,
/** Row value data for the body of the table */
data: TableRowsPropTypes.isRequired,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
testId: PropTypes__default['default'].string
};
var defaultProps$2m = {
i18n: _objectSpread$21({}, defaultI18NPropTypes),
secondaryTitle: null,
tooltip: null,
testId: ''
};
var TableToolbar = function TableToolbar(_ref) {
var tableId = _ref.tableId,
className = _ref.className,
i18n = _ref.i18n,
secondaryTitle = _ref.secondaryTitle,
tooltip = _ref.tooltip,
_ref$options = _ref.options,
hasAdvancedFilter = _ref$options.hasAdvancedFilter,
hasAggregations = _ref$options.hasAggregations,
hasColumnSelection = _ref$options.hasColumnSelection,
hasFastSearch = _ref$options.hasFastSearch,
hasFilter = _ref$options.hasFilter,
hasSearch = _ref$options.hasSearch,
hasRowSelection = _ref$options.hasRowSelection,
hasRowCountInHeader = _ref$options.hasRowCountInHeader,
hasRowEdit = _ref$options.hasRowEdit,
hasUserViewManagement = _ref$options.hasUserViewManagement,
hasBatchActionToolbar = _ref$options.hasBatchActionToolbar,
_ref$actions = _ref.actions,
onCancelBatchAction = _ref$actions.onCancelBatchAction,
onApplyBatchAction = _ref$actions.onApplyBatchAction,
onClearAllFilters = _ref$actions.onClearAllFilters,
onToggleAggregations = _ref$actions.onToggleAggregations,
onToggleColumnSelection = _ref$actions.onToggleColumnSelection,
onToggleFilter = _ref$actions.onToggleFilter,
onShowRowEdit = _ref$actions.onShowRowEdit,
onApplySearch = _ref$actions.onApplySearch,
onDownloadCSV = _ref$actions.onDownloadCSV,
onApplyAdvancedFilter = _ref$actions.onApplyAdvancedFilter,
onCancelAdvancedFilter = _ref$actions.onCancelAdvancedFilter,
onCreateAdvancedFilter = _ref$actions.onCreateAdvancedFilter,
onChangeAdvancedFilter = _ref$actions.onChangeAdvancedFilter,
onToggleAdvancedFilter = _ref$actions.onToggleAdvancedFilter,
onApplyToolbarAction = _ref$actions.onApplyToolbarAction,
onSearchExpand = _ref$actions.onSearchExpand,
_ref$tableState = _ref.tableState,
advancedFilterFlyoutOpen = _ref$tableState.advancedFilterFlyoutOpen,
advancedFilters = _ref$tableState.advancedFilters,
totalSelected = _ref$tableState.totalSelected,
totalFilters = _ref$tableState.totalFilters,
batchActions = _ref$tableState.batchActions,
searchProp = _ref$tableState.search,
activeBar = _ref$tableState.activeBar,
customToolbarContent = _ref$tableState.customToolbarContent,
isDisabled = _ref$tableState.isDisabled,
totalItemsCount = _ref$tableState.totalItemsCount,
rowEditBarButtons = _ref$tableState.rowEditBarButtons,
filters = _ref$tableState.filters,
selectedAdvancedFilterIds = _ref$tableState.selectedAdvancedFilterIds,
columns = _ref$tableState.columns,
ordering = _ref$tableState.ordering,
toolbarActions = _ref$tableState.toolbarActions,
hideClearAllFiltersButton = _ref$tableState.hideClearAllFiltersButton,
data = _ref.data,
testID = _ref.testID,
testId = _ref.testId;
var shouldShowBatchActions = hasRowSelection === 'multi' && totalSelected > 0;
var langDir = useLangDirection_2();
var _useDynamicOverflowMe = useDynamicOverflowMenuItems({
actions: toolbarActions,
className: "".concat(iotPrefix$27, "--table-toolbar-aggregations__overflow-menu-content"),
isDisabled: isDisabled,
onClick: onApplyToolbarAction,
testId: testID || testId
}),
_useDynamicOverflowMe2 = slicedToArray$2(_useDynamicOverflowMe, 3),
isOpen = _useDynamicOverflowMe2[0],
setIsOpen = _useDynamicOverflowMe2[1],
renderToolbarOverflowActions = _useDynamicOverflowMe2[2];
var actions = React$1.useMemo(function () {
var renderedActions = typeof toolbarActions === 'function' ? toolbarActions() : toolbarActions;
return renderedActions !== null && renderedActions !== void 0 && renderedActions.length ? renderedActions : [];
}, [toolbarActions]);
var hasToolbarOverflowActions = actions.filter(function (action) {
return action.isOverflow && action.hidden !== true;
}).length > 0;
var visibleToolbarActions = actions.filter(function (action) {
return !action.isOverflow && action.hidden !== true;
});
var visibleBatchActions = batchActions.filter(function (action) {
return !action.isOverflow && action.hidden !== true;
});
var visibleOverflowBatchActions = batchActions.filter(function (action) {
return action.isOverflow && action.hidden !== true;
});
var hasVisibleBatchActions = visibleBatchActions.length > 0;
var hasVisibleOverflowBatchActions = visibleOverflowBatchActions.length > 0;
var totalSelectedText = React$1.useMemo(function () {
if (totalSelected > 1) {
if (typeof i18n.itemsSelected === 'function') {
return i18n.itemsSelected(totalSelected);
}
return "".concat(totalSelected, " ").concat(i18n.itemsSelected);
}
if (typeof i18n.itemSelected === 'function') {
return i18n.itemSelected(totalSelected);
}
return "".concat(totalSelected, " ").concat(i18n.itemSelected);
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [i18n.itemSelected, i18n.itemsSelected, totalSelected]);
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableToolbar // TODO: remove deprecated 'testID' in v3
, {
"data-testid": testID || testId,
className: classnames$1("".concat(iotPrefix$27, "--table-toolbar"), className),
"aria-label": i18n.toolbarLabelAria
}, hasBatchActionToolbar ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableBatchActions // TODO: remove deprecated 'testID' in v3
, {
"data-testid": "".concat(testID || testId, "-batch-actions"),
className: "".concat(iotPrefix$27, "--table-batch-actions"),
onCancel: onCancelBatchAction,
shouldShowBatchActions: shouldShowBatchActions,
totalSelected: totalSelected,
translateWithId: function translateWithId() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return tableTranslateWithId.apply(void 0, [i18n].concat(args));
}
}, hasVisibleBatchActions && visibleBatchActions.map(function (_ref2) {
var id = _ref2.id,
labelText = _ref2.labelText,
disabled = _ref2.disabled,
others = objectWithoutProperties$1(_ref2, ["id", "labelText", "disabled"]);
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableBatchAction, _extends_1$1({
key: id,
onClick: function onClick() {
return onApplyBatchAction(id);
},
tabIndex: shouldShowBatchActions ? 0 : -1,
disabled: !shouldShowBatchActions || disabled
}, others), labelText);
}), hasVisibleOverflowBatchActions ? /*#__PURE__*/React__default['default'].createElement(OverflowMenu, {
"data-testid": "".concat(testID || testId, "-batch-actions-overflow-menu"),
className: "".concat(iotPrefix$27, "--table-overflow-batch-actions"),
flipped: langDir === 'ltr',
direction: "bottom",
onClick: function onClick(e) {
return e.stopPropagation();
},
renderIcon: iconsReact.OverflowMenuVertical20,
tabIndex: shouldShowBatchActions ? 0 : -1,
size: "lg",
menuOptionsClass: "".concat(iotPrefix$27, "--table-overflow-batch-actions__menu"),
withCarbonTooltip: true,
tooltipPosition: "bottom",
buttonLabel: i18n.batchActionsOverflowMenuText
}, visibleOverflowBatchActions.map(function (_ref3) {
var id = _ref3.id,
labelText = _ref3.labelText,
disabled = _ref3.disabled,
hasDivider = _ref3.hasDivider,
isDelete = _ref3.isDelete,
renderIcon = _ref3.renderIcon,
iconDescription = _ref3.iconDescription;
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
"data-testid": "".concat(testID || testId, "-batch-actions-overflow-menu-item-").concat(id),
itemText: renderTableOverflowItemText({
action: {
renderIcon: renderIcon,
labelText: labelText || iconDescription
},
className: "".concat(iotPrefix$27, "--table-toolbar-aggregations__overflow-menu-content")
}),
disabled: !shouldShowBatchActions || disabled,
onClick: function onClick() {
return onApplyBatchAction(id);
},
key: "table-batch-actions-overflow-menu-".concat(id),
requireTitle: !renderIcon,
hasDivider: hasDivider,
isDelete: isDelete,
"aria-label": labelText
});
})) : null) : null, secondaryTitle ?
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for
React__default['default'].createElement("label", {
className: "".concat(iotPrefix$27, "--table-toolbar-secondary-title")
}, secondaryTitle) : !hasBatchActionToolbar && shouldShowBatchActions ?
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for
React__default['default'].createElement("label", {
className: "".concat(iotPrefix$27, "--table-toolbar-secondary-title")
}, totalSelectedText) : null, // Deprecated in favor of secondaryTitle for a more general use-case
hasRowCountInHeader ?
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for
React__default['default'].createElement("label", {
className: "".concat(iotPrefix$27, "--table-toolbar-secondary-title")
}, i18n.rowCountInHeader(totalItemsCount)) : null, tooltip && /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$27, "--table-tooltip-container")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tooltip, {
triggerId: "card-tooltip-trigger-".concat(tableId),
tooltipId: "card-tooltip-".concat(tableId),
triggerText: "",
iconDescription: i18n.toolbarTooltipLabel
}, tooltip)), activeBar === 'rowEdit' ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$27, "--table-row-edit-actions")
}, rowEditBarButtons) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableToolbarContent // TODO: remove deprecated 'testID' in v3
, {
"data-testid": "".concat(testID || testId, "-content"),
className: "".concat(iotPrefix$27, "--table-toolbar-content")
}, hasSearch ? /*#__PURE__*/React__default['default'].createElement(TableToolbarSearch, {
tableId: tableId,
i18n: i18n,
options: {
hasFastSearch: hasFastSearch,
hasUserViewManagement: hasUserViewManagement
},
actions: {
onApplySearch: onApplySearch,
onSearchExpand: onSearchExpand
},
tableState: {
search: searchProp,
isDisabled: isDisabled
},
testId: testID || testId,
langDir: langDir
}) : null, totalFilters > 0 && !hideClearAllFiltersButton ? /*#__PURE__*/React__default['default'].createElement(Button$1, {
kind: "secondary",
onClick: onClearAllFilters,
disabled: isDisabled,
testId: "".concat(testId, "-clear-filters-button")
}, i18n.clearAllFilters) : null, onDownloadCSV ? /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
onClick: function onClick() {
// hand back the filtered data
onDownloadCSV(data);
},
description: i18n.downloadIconDescription,
testId: "download-button",
renderIcon: iconsReact.Download20,
disabled: isDisabled,
langDir: langDir
}) : null, hasColumnSelection ? /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
isActive: activeBar === 'column',
onClick: onToggleColumnSelection,
description: i18n.columnSelectionButtonAria,
testId: "column-selection-button",
renderIcon: iconsReact.Column20,
disabled: isDisabled,
langDir: langDir
}) : null, hasFilter ? /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
isActive: activeBar === 'filter',
onClick: onToggleFilter,
description: i18n.filterButtonAria,
testId: "filter-button",
renderIcon: iconsReact.Filter20,
disabled: isDisabled,
langDir: langDir
}) : null, hasAdvancedFilter ? /*#__PURE__*/React__default['default'].createElement(TableToolbarAdvancedFilterFlyout, {
actions: {
onApplyAdvancedFilter: onApplyAdvancedFilter,
onCancelAdvancedFilter: onCancelAdvancedFilter,
onCreateAdvancedFilter: onCreateAdvancedFilter,
onChangeAdvancedFilter: onChangeAdvancedFilter,
onToggleAdvancedFilter: onToggleAdvancedFilter
},
columns: columns.map(function (column) {
var _column$filter, _column$filter2;
return _objectSpread$21(_objectSpread$21({}, column.filter), {}, {
id: column.id,
name: column.name,
isDate: (_column$filter = column.filter) === null || _column$filter === void 0 ? void 0 : _column$filter.isDate,
isFilterable: !isNil(column.filter),
isMultiselect: (_column$filter2 = column.filter) === null || _column$filter2 === void 0 ? void 0 : _column$filter2.isMultiselect
});
}),
tableState: {
filters: filters,
advancedFilters: advancedFilters,
selectedAdvancedFilterIds: selectedAdvancedFilterIds,
advancedFilterFlyoutOpen: advancedFilterFlyoutOpen,
ordering: ordering,
hasFastFilter: hasAdvancedFilter === 'onKeyPress',
isDisabled: isDisabled
},
i18n: _objectSpread$21({}, pick(i18n, 'filterText', 'clearFilterText', 'clearSelectionText', 'openMenuText', 'closeMenuText', 'applyButtonText', 'cancelButtonText', 'advancedFilterLabelText', 'createNewAdvancedFilterText', 'advancedFilterPlaceholderText', 'simpleFiltersTabLabel', 'advancedFiltersTabLabel'))
}) : null, hasRowEdit ? /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
isActive: activeBar === 'rowEdit',
description: i18n.editButtonAria,
onClick: onShowRowEdit,
testId: "row-edit-button",
renderIcon: iconsReact.Edit20,
disabled: isDisabled,
langDir: langDir
}) : null, visibleToolbarActions.map(function (action) {
return /*#__PURE__*/React__default['default'].createElement(TableToolbarSVGButton, {
isActive: action.isActive,
description: action.labelText || action.iconDescription,
onClick: function onClick(e) {
e.stopPropagation();
onApplyToolbarAction(action);
},
testId: "".concat(tableId, "-toolbar-actions-button-").concat(action.id),
key: "".concat(tableId, "-toolbar-actions-button-").concat(action.id),
renderIcon: action.renderIcon,
disabled: isDisabled || action.disabled,
langDir: langDir
});
}), hasAggregations || hasToolbarOverflowActions ? /*#__PURE__*/React__default['default'].createElement(OverflowMenu, {
className: "".concat(iotPrefix$27, "--table-toolbar-aggregations__overflow-menu"),
direction: "bottom",
flipped: langDir === 'ltr',
"data-testid": "table-head--overflow",
onClick: function onClick(e) {
return e.stopPropagation();
},
renderIcon: iconsReact.OverflowMenuVertical20,
iconClass: "".concat(iotPrefix$27, "--table-toolbar-aggregations__overflow-icon"),
onOpen: function onOpen() {
return setIsOpen(true);
},
onClose: function onClose() {
return setIsOpen(false);
},
withCarbonTooltip: true,
tooltipPosition: "bottom"
}, hasAggregations && /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
"data-testid": "".concat(testID || testId, "-toolbar-overflow-menu-item-aggregations"),
itemText: i18n.toggleAggregations,
key: "table-aggregations-overflow-item",
onClick: function onClick() {
setIsOpen(false);
onToggleAggregations();
},
disabled: isDisabled
}), isOpen && renderToolbarOverflowActions(),
/**
* a placeholder node to ensure the menu will always open. If there are no children,
* the renderToolbarOverflowAction method above will never fire, because the
* OverflowMenu doesn't open properly if no children are provided.
*/
!isOpen && /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
itemText: "",
disabled: true
})) : null, // Default card header actions should be to the right of the table-specific actions
customToolbarContent || null));
};
TableToolbar.propTypes = propTypes$2g;
TableToolbar.defaultProps = defaultProps$2m;
TableToolbar.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableToolbar",
"props": {
"i18n": {
"defaultValue": {
"value": "{\n ...defaultI18NPropTypes,\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"clearAllFilters": {
"name": "string",
"required": false
},
"columnSelectionButtonAria": {
"name": "string",
"required": false
},
"filterButtonAria": {
"name": "string",
"required": false
},
"editButtonAria": {
"name": "string",
"required": false
},
"searchLabel": {
"name": "string",
"required": false
},
"searchPlaceholder": {
"name": "string",
"required": false
},
"batchCancel": {
"name": "string",
"required": false
},
"itemsSelected": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}],
"required": false
},
"itemSelected": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}],
"required": false
},
"filterNone": {
"name": "string",
"required": false
},
"filterAscending": {
"name": "string",
"required": false
},
"filterDescending": {
"name": "string",
"required": false
},
"toggleAggregations": {
"name": "string",
"required": false
},
"toolbarLabelAria": {
"name": "string",
"required": false
},
"rowCountInHeader": {
"name": "func",
"required": false
},
"downloadIconDescription": {
"name": "string",
"required": false
},
"toolbarTooltipLabel": {
"name": "string",
"description": "aria-label applied to the tooltip in the toolbar (if given)",
"required": false
},
"batchActionsOverflowMenuText": {
"name": "string",
"description": "button label for batch action overflow menu",
"required": false
},
"toolbarSearchIconDescription": {
"name": "string",
"description": "I18N label for search icon in toolbar",
"required": false
}
}
},
"required": false,
"description": "internationalized labels"
},
"secondaryTitle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"tooltip": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "id of table"
},
"options": {
"type": {
"name": "shape",
"value": {
"hasAdvancedFilter": {
"name": "bool",
"required": false
},
"hasAggregations": {
"name": "bool",
"required": false
},
"hasBatchActionToolbar": {
"name": "bool",
"required": false
},
"hasFastSearch": {
"name": "bool",
"description": "If true, search is applied as typed. If false, only after 'Enter' is pressed",
"required": false
},
"hasFilter": {
"name": "bool",
"required": false
},
"hasSearch": {
"name": "bool",
"required": false
},
"hasColumnSelection": {
"name": "bool",
"required": false
},
"hasRowEdit": {
"name": "bool",
"required": false
},
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"onApplySearch": {
"name": "func",
"required": false
},
"onDownloadCSV": {
"name": "func",
"required": false
},
"onApplyAdvancedFilter": {
"name": "func",
"required": false
},
"hasRowCountInHeader": {
"name": "custom",
"raw": "deprecate(\n PropTypes.bool,\n '\\n The prop `hasRowCountInHeader` has been deprecated in favor `secondaryTitle`'\n)",
"description": "Optional boolean to render rowCount in header\n NOTE: Deprecated in favor of secondaryTitle for custom use",
"required": false
},
"hasUserViewManagement": {
"name": "bool",
"required": false
}
}
},
"required": true,
"description": "global table options"
},
"actions": {
"type": {
"name": "shape",
"value": {
"onCancelBatchAction": {
"name": "func",
"required": false
},
"onApplyBatchAction": {
"name": "func",
"required": false
},
"onClearAllFilters": {
"name": "func",
"required": false
},
"onToggleAggregations": {
"name": "func",
"required": false
},
"onToggleColumnSelection": {
"name": "func",
"required": false
},
"onToggleFilter": {
"name": "func",
"required": false
},
"onToggleAdvancedFilter": {
"name": "func",
"required": false
},
"onCreateAdvancedFilter": {
"name": "func",
"required": false
},
"onChangeAdvancedFilter": {
"name": "func",
"required": false
},
"onCancelAdvancedFilter": {
"name": "func",
"required": false
},
"onApplyAdvancedFilter": {
"name": "func",
"required": false
},
"onShowRowEdit": {
"name": "func",
"required": false
},
"onApplySearch": {
"name": "func",
"required": false
},
"onDownloadCSV": {
"name": "func",
"required": false
},
"onApplyToolbarAction": {
"name": "func",
"required": false
},
"onSearchExpand": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": "Action callbacks to update tableState"
},
"tableState": {
"type": {
"name": "shape",
"value": {
"isDisabled": {
"name": "bool",
"description": "is the toolbar currently disabled",
"required": false
},
"activeBar": {
"name": "custom",
"raw": "ActiveTableToolbarPropType",
"description": "Which toolbar is currently active",
"required": false
},
"totalSelected": {
"name": "number",
"description": "total number of selected rows",
"required": false
},
"totalItemsCount": {
"name": "number",
"required": false
},
"advancedFilterFlyoutOpen": {
"name": "bool",
"required": false
},
"totalFilters": {
"name": "number",
"required": false
},
"filters": {
"name": "custom",
"raw": "TableFiltersPropType",
"required": false
},
"columns": {
"name": "custom",
"raw": "TableColumnsPropTypes",
"required": false
},
"ordering": {
"name": "custom",
"raw": "TableOrderingPropType",
"required": false
},
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"description": "row selection option",
"required": false
},
"customToolbarContent": {
"name": "node",
"description": "optional content to render inside the toolbar",
"required": false
},
"batchActions": {
"name": "arrayOf",
"value": {
"name": "union",
"value": [{
"name": "shape",
"value": {
"iconDescription": {
"name": "string",
"required": false
}
}
}, {
"name": "shape",
"value": {
"iconDescription": {
"name": "string",
"required": false
}
}
}]
},
"description": "available batch actions",
"required": false
},
"search": {
"name": "custom",
"raw": "TableSearchPropTypes",
"required": false
},
"rowEditBarButtons": {
"name": "node",
"description": "buttons to be shown with when activeBar is 'rowEdit'",
"required": false
},
"advancedFilters": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"filterId": {
"name": "string",
"description": "Unique id for particular filter",
"required": true
},
"filterTitleText": {
"name": "string",
"description": "Text for main title of page",
"required": true
},
"filterRules": {
"name": "custom",
"raw": "RuleGroupPropType.isRequired",
"required": true
}
}
},
"description": "a stripped down version of the RuleBuilderFilterPropType",
"required": false
},
"selectedAdvancedFilterIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"description": "currently selected advanced filters",
"required": false
},
"toolbarActions": {
"name": "custom",
"raw": "TableToolbarActionsPropType",
"description": "toolbar actions that can appear in an overflow menu in the toolbar (same menu as toggle aggregations)",
"required": false
},
"hideClearAllFiltersButton": {
"name": "bool",
"description": "force hide Clear all filters button in toolbar",
"required": false
}
}
},
"required": true,
"description": "Inbound tableState"
},
"data": {
"type": {
"name": "custom",
"raw": "TableRowsPropTypes.isRequired"
},
"required": false,
"description": "Row value data for the body of the table"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
}
}
};
var iotPrefix$26 = settings$1.iotPrefix;
var propTypes$2f = {
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].bool,
hasRowActions: PropTypes__default['default'].bool,
rowCount: PropTypes__default['default'].number,
/* used to show X number of loading skeletons when columns are unknown */
columnCount: PropTypes__default['default'].number,
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string.isRequired
})),
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
testId: PropTypes__default['default'].string,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool
};
var defaultProps$2l = {
hasRowSelection: false,
hasRowExpansion: false,
hasRowActions: false,
hasRowNesting: false,
rowCount: 10,
columnCount: 5,
columns: [],
testId: '',
showExpanderColumn: false
};
/** This component is exactly like the DataTableSkeleton component from carbon, but it shows your headers while it loads */
var TableSkeletonWithHeaders = function TableSkeletonWithHeaders(_ref) {
var hasRowSelection = _ref.hasRowSelection,
hasRowExpansion = _ref.hasRowExpansion,
hasRowActions = _ref.hasRowActions,
hasRowNesting = _ref.hasRowNesting,
columns = _ref.columns,
rowCount = _ref.rowCount,
columnCount = _ref.columnCount,
testID = _ref.testID,
testId = _ref.testId,
showExpanderColumn = _ref.showExpanderColumn;
var rows = toConsumableArray(Array(rowCount > 0 ? rowCount - 1 : 0));
var loadingColumns = columns.length ? columns : toConsumableArray(Array(columnCount > 0 ? columnCount : 1)).map(function (c, i) {
return {
id: i
};
});
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableBody, {
"data-testid": testID || testId
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
className: classnames$1("".concat(iotPrefix$26, "--table-skeleton-with-headers--table-row"), defineProperty$d({}, "".concat(iotPrefix$26, "--table-skeleton-with-headers--table-row--head"), !columns.length))
}, hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, loadingColumns.map(function (column) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "skeletonCol-".concat(column.id)
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, null));
}), showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
"data-testid": "".concat(testID || testId, "-expander-column")
}) : null, hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null), rows.map(function (row, rowIndex) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
key: "skeletonRow-".concat(rowIndex),
className: "".concat(iotPrefix$26, "--table-skeleton-with-headers--table-row")
}, hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, loadingColumns.map(function (v, colIndex) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "emptycell-".concat(colIndex)
}, rowIndex === 0 && !columns.length ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, null) : null);
}), showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
"data-testid": "".concat(testID || testId, "-skeletonRow-").concat(rowIndex, "-expander-column")
}) : null, hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null);
}));
};
TableSkeletonWithHeaders.propTypes = propTypes$2f;
TableSkeletonWithHeaders.defaultProps = defaultProps$2l;
TableSkeletonWithHeaders.__docgenInfo = {
"description": "This component is exactly like the DataTableSkeleton component from carbon, but it shows your headers while it loads",
"methods": [],
"displayName": "TableSkeletonWithHeaders",
"props": {
"hasRowSelection": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}]
},
"required": false,
"description": ""
},
"hasRowExpansion": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowActions": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowNesting": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"rowCount": {
"defaultValue": {
"value": "10",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"columnCount": {
"defaultValue": {
"value": "5",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"columns": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": true
}
}
}
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
}
}
};
// `Map` constructor
// https://tc39.es/ecma262/#sec-map-objects
collection('Map', function (init) {
return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong);
function ownKeys$20(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$20(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$20(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$20(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var observers$1 = new Map();
var removeObserver = function removeObserver(element) {
if (observers$1.has(element)) {
var observer = observers$1.get(element);
observer.disconnect();
observers$1.delete(element);
}
};
var getObserver = function getObserver(element, _ref) {
var setIsVisible = _ref.setIsVisible,
unobserveAfterVisible = _ref.unobserveAfterVisible,
options = objectWithoutProperties$1(_ref, ["setIsVisible", "unobserveAfterVisible"]);
if (!observers$1.has(element)) {
observers$1.set(element, new IntersectionObserver(function (_ref2, observer) {
var _ref3 = slicedToArray$2(_ref2, 1),
entry = _ref3[0];
setIsVisible(entry.isIntersecting);
if (unobserveAfterVisible && entry.isIntersecting) {
observer.unobserve(element);
removeObserver(element);
}
}, options));
}
return observers$1.get(element);
};
var defaultOptions = {
/** a callback that will be triggered when the ref element visibility changes */
// eslint-disable-next-line no-unused-vars
onChange: function onChange(_ref4) {
_ref4.isVisible;
},
/**
* what percentage of the element must be visible for onChange to be called (0.0 through 1.0)
* 0.0 means any pixel is visible
* 1.0 means all pixels are visible
* */
threshold: 0.0,
/**
* The element, relative to the element being observed, that determines if it is visible.
* For example, if this is left null the element is tracked against the window, but if a scrollable
* div is given, the visibility is checked against that scrollable area instead.
*/
container: null,
/**
* A string, in the form of a css margin (ie. `100px 0px 100px 0px`, units MUST be included), that
* sets the bounds of the visible area. If you want this to expand to trigger visibility outside
* of the root element, simply give it a large padding. In the example above, `100px 0px 100px 0`
* expands the visible area 100px above and below the container, so any elements that come within
* 100px of the top or bottom of the container will be treated as visible. This allows elements to
* be pre-loaded off screen as a user is scrolling.
*/
padding: '50% 0px 50% 0px',
/**
* If true, stop tracking the element after it has become visible otherwise, it will continue to
* track the element and trigger onChange each time it changes visibility
*/
unobserveAfterVisible: false
};
/**
* A simple hook to return a bool telling if the given element is visible on the screen. It can be
* used to load a single item or multiple items.
*
* @param {*} elementRef html element to check if it's visible
* @param {object} options see defaultOptions above
* @returns Array an array containing [isVisible: bool]
*/
var useVisibilityObserver = function useVisibilityObserver(elementRef, options) {
if (!browserSupports('IntersectionObserver')) {
warning_1(!("development" !== "production"), 'The current browser does not support IntersectionObserver. You will need to include a IntersectionObserver polyfill for this component to function properly.') ;
return [true];
}
var _defaultOptions$optio = _objectSpread$20(_objectSpread$20({}, defaultOptions), options),
onChange = _defaultOptions$optio.onChange,
threshold = _defaultOptions$optio.threshold,
container = _defaultOptions$optio.container,
padding = _defaultOptions$optio.padding,
unobserveAfterVisible = _defaultOptions$optio.unobserveAfterVisible;
/* eslint-disable react-hooks/rules-of-hooks */
var observerRef = React$1.useRef(null);
var _useState = React$1.useState(false),
_useState2 = slicedToArray$2(_useState, 2),
isVisible = _useState2[0],
setIsVisible = _useState2[1];
var previousIsVisible = usePrevious(isVisible, false);
React$1.useEffect(function () {
if (isVisible !== previousIsVisible) {
onChange({
isVisible: isVisible
});
}
}, [isVisible, onChange, previousIsVisible]);
React$1.useEffect(function () {
var elementToObserve = elementRef.current;
if (elementToObserve) {
observerRef.current = getObserver(elementToObserve, {
setIsVisible: setIsVisible,
unobserveAfterVisible: unobserveAfterVisible,
root: container,
rootMargin: padding,
threshold: threshold
});
observerRef.current.observe(elementToObserve);
}
return function () {
if (observerRef.current) {
removeObserver(elementToObserve);
}
};
}, [container, elementRef, padding, threshold, unobserveAfterVisible]);
/* eslint-enable react-hooks/rules-of-hooks */
return [isVisible];
};
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last$1(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last$1(path))];
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject$2(value) ? undefined : value;
}
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
var iotPrefix$25 = settings$1.iotPrefix;
var propTypes$2e = {
/** I18N label for action failed */
actionFailedText: PropTypes__default['default'].string,
/** I18N label for learn more */
learnMoreText: PropTypes__default['default'].string,
/** I18N label for dismiss */
dismissText: PropTypes__default['default'].string,
/** did an error occur */
rowActionsError: RowActionErrorPropTypes,
onClearError: PropTypes__default['default'].func
};
var defaultProps$2k = {
actionFailedText: 'Action failed',
learnMoreText: 'Learn more',
dismissText: 'Dismiss',
rowActionsError: null,
onClearError: null
};
var RowActionsError = function RowActionsError(_ref) {
var rowActionsError = _ref.rowActionsError,
actionFailedText = _ref.actionFailedText,
learnMoreText = _ref.learnMoreText,
dismissText = _ref.dismissText,
onClearError = _ref.onClearError;
if (!rowActionsError) {
return null;
}
var title = rowActionsError.title,
message = rowActionsError.message,
learnMoreURL = rowActionsError.learnMoreURL;
return /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tooltip, {
tabIndex: 0,
triggerText: "",
triggerId: "tooltip-error",
tooltipId: "tooltip",
renderIcon: /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) {
return /*#__PURE__*/React__default['default'].createElement(iconsReact.WarningAlt16, {
ref: ref
});
})
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$25, "--row-actions-error--tooltip")
}, /*#__PURE__*/React__default['default'].createElement("p", {
className: "".concat(iotPrefix$25, "--row-actions-error--title")
}, title), message, /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$25, "--row-actions-error--footer")
}, learnMoreURL ? /*#__PURE__*/React__default['default'].createElement("a", {
href: learnMoreURL,
target: "_blank",
rel: "noopener noreferrer"
}, learnMoreText) : /*#__PURE__*/React__default['default'].createElement("div", null), onClearError ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Button, {
onClick: function onClick(evt) {
onClearError(evt);
evt.stopPropagation();
}
}, dismissText) : null))), /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(iotPrefix$25, "--row-actions-error--span")
}, actionFailedText));
};
RowActionsError.propTypes = propTypes$2e;
RowActionsError.defaultProps = defaultProps$2k;
RowActionsError.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "RowActionsError",
"props": {
"actionFailedText": {
"defaultValue": {
"value": "'Action failed'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for action failed"
},
"learnMoreText": {
"defaultValue": {
"value": "'Learn more'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for learn more"
},
"dismissText": {
"defaultValue": {
"value": "'Dismiss'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for dismiss"
},
"rowActionsError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionErrorPropTypes"
},
"required": false,
"description": "did an error occur"
},
"onClearError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
}
}
};
function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$8() { 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 iotPrefix$24 = settings$1.iotPrefix;
var propTypes$2d = {
/** Unique id for each row, passed back for each click */
id: PropTypes__default['default'].string.isRequired,
/** Unique id for the table */
tableId: PropTypes__default['default'].string.isRequired,
/** Array with all the actions to render */
actions: RowActionPropTypes,
/** Callback called if a row action is clicked */
onApplyRowAction: PropTypes__default['default'].func.isRequired,
/** translated text for more actions */
overflowMenuAria: PropTypes__default['default'].string,
/** Is a row action actively running */
isRowActionRunning: PropTypes__default['default'].bool,
/** row action error out */
rowActionsError: RowActionErrorPropTypes,
onClearError: PropTypes__default['default'].func,
/** I18N label for in progress */
inProgressText: PropTypes__default['default'].string,
/** I18N label for action failed */
actionFailedText: PropTypes__default['default'].string,
// eslint-disable-line react/require-default-props
/** I18N label for learn more */
learnMoreText: PropTypes__default['default'].string,
// eslint-disable-line react/require-default-props
/** I18N label for dismiss */
dismissText: PropTypes__default['default'].string,
// eslint-disable-line react/require-default-props
/** `true` to make this menu item a divider. */
hasDivider: PropTypes__default['default'].bool,
/** `true` to make this menu item a "danger button". */
isDelete: PropTypes__default['default'].bool,
/** `true` hides all the normal actions/statuses and shows the singleRowEditButtons */
showSingleRowEditButtons: PropTypes__default['default'].bool,
singleRowEditButtons: PropTypes__default['default'].element,
/**
* Direction of document. Passed in at Table
*/
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl']),
/**
* the size passed to the table to set row height
*/
size: PropTypes__default['default'].oneOf(['xs', 'sm', 'md', 'lg', 'xl'])
};
var defaultProps$2j = {
actions: null,
isRowActionRunning: false,
rowActionsError: null,
overflowMenuAria: 'More actions',
inProgressText: 'In progress',
onClearError: null,
hasDivider: false,
isDelete: false,
showSingleRowEditButtons: false,
singleRowEditButtons: null,
langDir: 'ltr',
size: undefined
};
var RowActionsCell = /*#__PURE__*/function (_React$Component) {
inherits(RowActionsCell, _React$Component);
var _super = _createSuper$8(RowActionsCell);
function RowActionsCell() {
var _this;
classCallCheck(this, RowActionsCell);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty$d(assertThisInitialized(_this), "state", {
isOpen: false
});
defineProperty$d(assertThisInitialized(_this), "handleOpen", function () {
var isOpen = _this.state.isOpen;
if (!isOpen) {
_this.setState({
isOpen: true
});
}
});
defineProperty$d(assertThisInitialized(_this), "handleClose", function () {
var isOpen = _this.state.isOpen;
if (isOpen) {
_this.setState({
isOpen: false
});
}
});
defineProperty$d(assertThisInitialized(_this), "onClick", function (e, id, action, onApplyRowAction) {
onApplyRowAction(action, id);
e.preventDefault();
e.stopPropagation();
_this.handleClose();
});
return _this;
}
createClass(RowActionsCell, [{
key: "render",
value: function render() {
var _this2 = this;
var _this$props = this.props,
id = _this$props.id,
tableId = _this$props.tableId,
actions = _this$props.actions,
onApplyRowAction = _this$props.onApplyRowAction,
overflowMenuAria = _this$props.overflowMenuAria,
actionFailedText = _this$props.actionFailedText,
learnMoreText = _this$props.learnMoreText,
dismissText = _this$props.dismissText,
isRowActionRunning = _this$props.isRowActionRunning,
rowActionsError = _this$props.rowActionsError,
onClearError = _this$props.onClearError,
inProgressText = _this$props.inProgressText,
showSingleRowEditButtons = _this$props.showSingleRowEditButtons,
singleRowEditButtons = _this$props.singleRowEditButtons,
langDir = _this$props.langDir,
size = _this$props.size;
var isOpen = this.state.isOpen;
var visibleActions = actions ? actions.filter(function (action) {
return !action.hidden;
}) : [];
var overflowActions = visibleActions.filter(function (action) {
return action.isOverflow;
});
var hasOverflow = overflowActions.length > 0;
var firstSelectableItemIndex = overflowActions.findIndex(function (action) {
return !action.disabled;
});
return showSingleRowEditButtons ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "".concat(id, "-single-row-edit-buttons"),
className: "".concat(iotPrefix$24, "--row-actions-cell--table-cell")
}, singleRowEditButtons) : actions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "".concat(id, "-row-actions-cell"),
className: "".concat(iotPrefix$24, "--row-actions-cell--table-cell")
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$24, "--row-actions-container")
}, /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": "row-action-container-background",
className: classnames$1("".concat(iotPrefix$24, "--row-actions-container__background"), defineProperty$d({}, "".concat(iotPrefix$24, "--row-actions-container__background--overflow-menu-open"), isOpen)),
onClick: function onClick(evt) {
return evt.stopPropagation();
}
}, rowActionsError ? /*#__PURE__*/React__default['default'].createElement(RowActionsError, {
actionFailedText: actionFailedText,
learnMoreText: learnMoreText,
dismissText: dismissText,
rowActionsError: rowActionsError,
onClearError: onClearError
}) : isRowActionRunning ? /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Loading, {
small: true,
withOverlay: false
}), inProgressText) : /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, null, visibleActions.filter(function (action) {
return !action.isOverflow;
}).map(function (_ref) {
var actionId = _ref.id,
labelText = _ref.labelText,
iconDescription = _ref.iconDescription,
others = objectWithoutProperties$1(_ref, ["id", "labelText", "iconDescription"]);
return /*#__PURE__*/React__default['default'].createElement(Button$1, _extends_1$1({}, omit(others, ['isOverflow', 'isDelete', 'isEdit', 'hasDivider']), {
iconDescription: labelText || iconDescription,
key: "".concat(tableId, "-").concat(id, "-row-actions-button-").concat(actionId),
testId: "".concat(tableId, "-").concat(id, "-row-actions-button-").concat(actionId),
kind: "ghost",
hasIconOnly: !labelText,
tooltipPosition: "left",
tooltipAlignment: "end",
size: "small",
onClick: function onClick(e) {
return _this2.onClick(e, id, actionId, onApplyRowAction);
}
}), labelText);
}), hasOverflow ? /*#__PURE__*/React__default['default'].createElement(OverflowMenu, {
id: "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow"),
"data-testid": "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow"),
flipped: langDir === 'ltr',
ariaLabel: overflowMenuAria,
onClick: function onClick(event) {
return event.stopPropagation();
},
iconDescription: overflowMenuAria,
onOpen: this.handleOpen,
onClose: this.handleClose // compact or xs rows need the `sm` overflow menu, everything else is default (md)
,
size: ['compact', 'xs'].includes(size) ? 'sm' : 'md',
className: "".concat(iotPrefix$24, "--row-actions-cell--overflow-menu"),
selectorPrimaryFocus: ".".concat(iotPrefix$24, "--action-overflow-item--initialFocus"),
useAutoPositioning: true
}, overflowActions.map(function (action, actionIndex) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.OverflowMenuItem, {
className: classnames$1("".concat(iotPrefix$24, "--action-overflow-item"), defineProperty$d({}, "".concat(iotPrefix$24, "--action-overflow-item--initialFocus"), actionIndex === firstSelectableItemIndex)),
"data-testid": "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow-menu-item-").concat(action.id),
key: "".concat(id, "-row-actions-button-").concat(action.id),
onClick: function onClick(e) {
return _this2.onClick(e, id, action.id, onApplyRowAction);
},
requireTitle: !action.renderIcon,
hasDivider: action.hasDivider,
isDelete: action.isDelete,
itemText: renderTableOverflowItemText({
action: action,
className: "".concat(iotPrefix$24, "--row-actions-cell--overflow-menu-content")
}),
disabled: action.disabled
});
})) : null)))) : null;
}
}]);
return RowActionsCell;
}(React__default['default'].Component);
RowActionsCell.propTypes = propTypes$2d;
RowActionsCell.defaultProps = defaultProps$2j;
RowActionsCell.__docgenInfo = {
"description": "",
"methods": [{
"name": "handleOpen",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "handleClose",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "onClick",
"docblock": null,
"modifiers": [],
"params": [{
"name": "e",
"type": null
}, {
"name": "id",
"type": null
}, {
"name": "action",
"type": null
}, {
"name": "onApplyRowAction",
"type": null
}],
"returns": null
}],
"displayName": "RowActionsCell",
"props": {
"actions": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionPropTypes"
},
"required": false,
"description": "Array with all the actions to render"
},
"isRowActionRunning": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Is a row action actively running"
},
"rowActionsError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionErrorPropTypes"
},
"required": false,
"description": "row action error out"
},
"overflowMenuAria": {
"defaultValue": {
"value": "'More actions'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "translated text for more actions"
},
"inProgressText": {
"defaultValue": {
"value": "'In progress'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for in progress"
},
"onClearError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"hasDivider": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "`true` to make this menu item a divider."
},
"isDelete": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "`true` to make this menu item a \"danger button\"."
},
"showSingleRowEditButtons": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "`true` hides all the normal actions/statuses and shows the singleRowEditButtons"
},
"singleRowEditButtons": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": ""
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": "Direction of document. Passed in at Table"
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "enum",
"value": [{
"value": "'xs'",
"computed": false
}, {
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}, {
"value": "'xl'",
"computed": false
}]
},
"required": false,
"description": "the size passed to the table to set row height"
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": "Unique id for each row, passed back for each click"
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "Unique id for the table"
},
"onApplyRowAction": {
"type": {
"name": "func"
},
"required": true,
"description": "Callback called if a row action is clicked"
},
"actionFailedText": {
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for action failed"
},
"learnMoreText": {
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for learn more"
},
"dismissText": {
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for dismiss"
}
}
};
var prefix$s = settings$1.prefix,
iotPrefix$23 = settings$1.iotPrefix;
var propTypes$2c = {
/**
* Specify the string read by a voice reader when the expand trigger is
* focused
*/
ariaLabel: PropTypes__default['default'].string.isRequired,
children: PropTypes__default['default'].node,
className: PropTypes__default['default'].string,
/**
* The id of the matching th node in the table head. Addresses a11y concerns outlined here: https://www.ibm.com/able/guidelines/ci162/info_and_relationships.html and https://www.w3.org/TR/WCAG20-TECHS/H43
*/
expandHeaderId: PropTypes__default['default'].string,
/**
* The description of the chevron right icon, to be put in its SVG `` element.
*/
expandIconDescription: PropTypes__default['default'].string,
/**
* Specify whether this row is expanded or not. This helps coordinate data
* attributes so that `TableExpandRow` and `TableExpandedRow` work together
*/
isExpanded: PropTypes__default['default'].bool.isRequired,
/**
* Specify if the row is selected
*/
isSelected: PropTypes__default['default'].bool,
/**
* Hook for when a listener initiates a request to expand the given row
*/
onExpand: PropTypes__default['default'].func.isRequired,
/**
* Unique row id
*/
rowId: PropTypes__default['default'].string.isRequired,
/**
* direction of document
*/
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl'])
};
var defaultProps$2i = {
children: [],
className: '',
expandHeaderId: 'expand',
expandIconDescription: 'Click to expand content',
isSelected: false,
langDir: 'ltr'
};
var TableExpandRow = function TableExpandRow(_ref) {
var _classnames;
var ariaLabel = _ref.ariaLabel,
rowClassName = _ref.className,
children = _ref.children,
isExpanded = _ref.isExpanded,
onExpand = _ref.onExpand,
expandIconDescription = _ref.expandIconDescription,
isSelected = _ref.isSelected,
expandHeaderId = _ref.expandHeaderId,
rowId = _ref.rowId,
langDir = _ref.langDir,
rest = objectWithoutProperties$1(_ref, ["ariaLabel", "className", "children", "isExpanded", "onExpand", "expandIconDescription", "isSelected", "expandHeaderId", "rowId", "langDir"]);
var className = classnames$1((_classnames = {}, defineProperty$d(_classnames, "".concat(prefix$s, "--parent-row"), true), defineProperty$d(_classnames, "".concat(prefix$s, "--expandable-row"), isExpanded), defineProperty$d(_classnames, "".concat(prefix$s, "--data-table--selected"), isSelected), _classnames), rowClassName);
var previousValue = isExpanded ? 'collapsed' : undefined;
return /*#__PURE__*/React__default['default'].createElement("tr", _extends_1$1({}, rest, {
className: className,
"data-parent-row": true,
"data-testid": "expand-row-".concat(rowId)
}), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: "".concat(prefix$s, "--table-expand"),
"data-previous-value": previousValue,
headers: expandHeaderId
}, /*#__PURE__*/React__default['default'].createElement(Button$1, {
"aria-label": ariaLabel,
testId: "expand-icon-button-".concat(rowId),
className: classnames$1("".concat(prefix$s, "--table-expand__button"), "".concat(iotPrefix$23, "--table-expand__button"), "".concat(iotPrefix$23, "--tooltip-svg-wrapper"), defineProperty$d({}, "".concat(iotPrefix$23, "--table-expand__button--close"), isExpanded)),
onClick: onExpand,
iconDescription: expandIconDescription,
renderIcon: iconsReact.ChevronRight16,
size: "sm",
tooltipAlignment: langDir === 'ltr' ? 'start' : 'end',
tooltipPosition: "top",
kind: "icon-selection"
})), children);
};
TableExpandRow.propTypes = propTypes$2c;
TableExpandRow.defaultProps = defaultProps$2i;
TableExpandRow.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableExpandRow",
"props": {
"children": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": ""
},
"className": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"expandHeaderId": {
"defaultValue": {
"value": "'expand'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The id of the matching th node in the table head. Addresses a11y concerns outlined here: https://www.ibm.com/able/guidelines/ci162/info_and_relationships.html and https://www.w3.org/TR/WCAG20-TECHS/H43"
},
"expandIconDescription": {
"defaultValue": {
"value": "'Click to expand content'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The description of the chevron right icon, to be put in its SVG `` element."
},
"isSelected": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Specify if the row is selected"
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": "direction of document"
},
"ariaLabel": {
"type": {
"name": "string"
},
"required": true,
"description": "Specify the string read by a voice reader when the expand trigger is\nfocused"
},
"isExpanded": {
"type": {
"name": "bool"
},
"required": true,
"description": "Specify whether this row is expanded or not. This helps coordinate data\nattributes so that `TableExpandRow` and `TableExpandedRow` work together"
},
"onExpand": {
"type": {
"name": "func"
},
"required": true,
"description": "Hook for when a listener initiates a request to expand the given row"
},
"rowId": {
"type": {
"name": "string"
},
"required": true,
"description": "Unique row id"
}
}
};
var iotPrefix$22 = settings$1.iotPrefix;
var propTypes$2b = {
/**
* Callback when a user mouse downs on the handle. That can start a DnD operation. The
* `useTableDnd` does the real work of tracking the drag.
*/
onStartDrag: PropTypes__default['default'].func.isRequired,
/**
* The ID of the table row this handle is it. This is the row that will be dragged by this handle.
*/
rowId: PropTypes__default['default'].string.isRequired
};
/**
* Drag handle image the user needs to click and drag to start a drag and drop operation.
*/
var TableDragHandle = /*#__PURE__*/React$1.forwardRef(function TableDragHandle(_ref, ref) {
var onStartDrag = _ref.onStartDrag,
rowId = _ref.rowId;
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$22, "--table-drag-handle"),
ref: ref,
role: "presentation",
onMouseDown: function onMouseDown(e) {
e.preventDefault();
e.stopPropagation();
onStartDrag(e, rowId);
}
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Draggable16, null));
});
TableDragHandle.propTypes = propTypes$2b;
TableDragHandle.__docgenInfo = {
"description": "Drag handle image the user needs to click and drag to start a drag and drop operation.",
"methods": [],
"props": {
"onStartDrag": {
"type": {
"name": "func"
},
"required": true,
"description": "Callback when a user mouse downs on the handle. That can start a DnD operation. The\n`useTableDnd` does the real work of tracking the drag."
},
"rowId": {
"type": {
"name": "string"
},
"required": true,
"description": "The ID of the table row this handle is it. This is the row that will be dragged by this handle."
}
}
};
var prefix$r = settings$1.prefix,
iotPrefix$21 = settings$1.iotPrefix;
var propTypes$2a = {
/** What column ordering is currently applied to the table */
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool,
/** for each column you can register a render callback function that is called with this object payload
* {
* value: PropTypes.any (current cell value),
* columnId: PropTypes.string,
* rowId: PropTypes.string,
* row: PropTypes.object like this {col: value, col2: value}
* }, you should return the node that should render within that cell */
renderDataFunction: PropTypes__default['default'].func
})).isRequired,
/** internationalized label */
selectRowAria: PropTypes__default['default'].string,
/** internationalized label */
overflowMenuAria: PropTypes__default['default'].string,
/** internationalized label */
clickToExpandAria: PropTypes__default['default'].string,
/** internationalized label */
clickToCollapseAria: PropTypes__default['default'].string,
/** List of columns */
columns: TableColumnsPropTypes.isRequired,
/** table wide options */
options: PropTypes__default['default'].shape({
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasRowActions: PropTypes__default['default'].bool,
shouldExpandOnRowClick: PropTypes__default['default'].bool,
wrapCellText: WrapCellTextPropTypes.isRequired,
truncateCellText: PropTypes__default['default'].bool.isRequired,
/** use white-space: pre; css when true */
preserveCellWhiteSpace: PropTypes__default['default'].bool,
/** use radio button on single selection */
useRadioButtonSingleSelect: PropTypes__default['default'].bool,
hasDragAndDrop: PropTypes__default['default'].bool
}),
/** The unique row id */
id: PropTypes__default['default'].string.isRequired,
/** The unique id for the table */
tableId: PropTypes__default['default'].string.isRequired,
/** some columns might be hidden, so total columns has the overall total */
totalColumns: PropTypes__default['default'].number.isRequired,
/** contents of the row each object value is a render-able node keyed by column id */
values: PropTypes__default['default'].objectOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].bool, PropTypes__default['default'].object, PropTypes__default['default'].array])).isRequired,
/** is the row currently selected */
isSelected: PropTypes__default['default'].bool,
/** is the row currently in an indeterminate state, i.e. some but not all children are checked */
isIndeterminate: PropTypes__default['default'].bool,
/** is the row currently expanded */
isExpanded: PropTypes__default['default'].bool,
/** optional row details */
rowDetails: PropTypes__default['default'].node,
/** offset level if row is nested */
nestingLevel: PropTypes__default['default'].number,
/** number of child rows underneath this row */
nestingChildCount: PropTypes__default['default'].number,
/** tableActions */
tableActions: PropTypes__default['default'].shape({
onRowSelected: PropTypes__default['default'].func,
onRowClicked: PropTypes__default['default'].func,
onApplyRowAction: PropTypes__default['default'].func,
onRowExpanded: PropTypes__default['default'].func,
onClearRowError: PropTypes__default['default'].func
}).isRequired,
/** optional per-row actions */
rowActions: RowActionPropTypes,
/** Is a row action actively running */
isRowActionRunning: PropTypes__default['default'].bool,
/** has a row action errored out */
rowActionsError: RowActionErrorPropTypes,
/** I18N label for in progress */
inProgressText: PropTypes__default['default'].string,
/** I18N label for action failed */
actionFailedText: PropTypes__default['default'].string,
/** I18N label for learn more */
learnMoreText: PropTypes__default['default'].string,
/** I18N label for dismiss */
dismissText: PropTypes__default['default'].string,
locale: PropTypes__default['default'].string,
rowEditMode: PropTypes__default['default'].bool,
singleRowEditMode: PropTypes__default['default'].bool,
isSelectable: PropTypes__default['default'].bool,
singleRowEditButtons: PropTypes__default['default'].element,
/**
* direction of document
*/
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl']),
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
/**
* the size passed to the table to set row height
*/
size: PropTypes__default['default'].oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
/** True if this is the last child of a nested group */
isLastChild: PropTypes__default['default'].bool,
/** If this row supports drag and drop. Add space for a drag handle. */
hasDragAndDrop: PropTypes__default['default'].bool,
/** Callback when a drag of this row starts. */
onStartDrag: PropTypes__default['default'].func,
/** Callback when the mouse enters this row during a drag. */
onDragEnterRow: PropTypes__default['default'].func,
/** Callback when the mouse leaves this row during a drag. */
onDragLeaveRow: PropTypes__default['default'].func,
/** If this row can be dragged. Shows a drag handle. */
isDraggable: PropTypes__default['default'].bool,
/** If this row is being dragged. */
isDragRow: PropTypes__default['default'].bool,
/** If all drag handles should be hidden. This happens when an undraggable row is in the selection. */
hideDragHandles: PropTypes__default['default'].bool
};
var defaultProps$2h = {
isSelected: false,
isIndeterminate: false,
isExpanded: false,
selectRowAria: 'Select row',
overflowMenuAria: 'More actions',
clickToExpandAria: 'Click to expand.',
clickToCollapseAria: 'Click to collapse.',
rowActions: null,
rowDetails: null,
nestingLevel: 0,
nestingChildCount: 0,
options: {},
rowEditMode: false,
singleRowEditMode: false,
singleRowEditButtons: null,
isRowActionRunning: false,
rowActionsError: null,
learnMoreText: 'Learn more',
inProgressText: 'In progress',
dismissText: 'Dismiss',
actionFailedText: 'Action failed',
showExpanderColumn: false,
langDir: 'ltr',
locale: 'en',
isSelectable: undefined,
size: undefined,
isLastChild: false,
hasDragAndDrop: false,
hideDragHandles: false,
onStartDrag: null,
onDragEnterRow: null,
onDragLeaveRow: null,
isDraggable: false,
isDragRow: false
};
var TableBodyRow = function TableBodyRow(_ref) {
var _classnames3, _classnames4, _classnames5, _classnames6, _classnames7;
var id = _ref.id,
tableId = _ref.tableId,
langDir = _ref.langDir,
totalColumns = _ref.totalColumns,
ordering = _ref.ordering,
columns = _ref.columns,
locale = _ref.locale,
_ref$options = _ref.options,
hasRowSelection = _ref$options.hasRowSelection,
hasRowExpansion = _ref$options.hasRowExpansion,
hasRowActions = _ref$options.hasRowActions,
hasRowNesting = _ref$options.hasRowNesting,
shouldExpandOnRowClick = _ref$options.shouldExpandOnRowClick,
wrapCellText = _ref$options.wrapCellText,
truncateCellText = _ref$options.truncateCellText,
preserveCellWhiteSpace = _ref$options.preserveCellWhiteSpace,
useRadioButtonSingleSelect = _ref$options.useRadioButtonSingleSelect,
_ref$tableActions = _ref.tableActions,
onRowSelected = _ref$tableActions.onRowSelected,
onRowExpanded = _ref$tableActions.onRowExpanded,
onRowClicked = _ref$tableActions.onRowClicked,
onApplyRowAction = _ref$tableActions.onApplyRowAction,
onClearRowError = _ref$tableActions.onClearRowError,
isExpanded = _ref.isExpanded,
isSelected = _ref.isSelected,
isIndeterminate = _ref.isIndeterminate,
selectRowAria = _ref.selectRowAria,
overflowMenuAria = _ref.overflowMenuAria,
clickToExpandAria = _ref.clickToExpandAria,
clickToCollapseAria = _ref.clickToCollapseAria,
inProgressText = _ref.inProgressText,
actionFailedText = _ref.actionFailedText,
learnMoreText = _ref.learnMoreText,
dismissText = _ref.dismissText,
isSelectable = _ref.isSelectable,
values = _ref.values,
nestingLevel = _ref.nestingLevel,
nestingChildCount = _ref.nestingChildCount,
rowActions = _ref.rowActions,
isRowActionRunning = _ref.isRowActionRunning,
rowActionsError = _ref.rowActionsError,
rowDetails = _ref.rowDetails,
rowEditMode = _ref.rowEditMode,
singleRowEditMode = _ref.singleRowEditMode,
singleRowEditButtons = _ref.singleRowEditButtons,
showExpanderColumn = _ref.showExpanderColumn,
size = _ref.size,
isLastChild = _ref.isLastChild,
onStartDrag = _ref.onStartDrag,
onDragEnterRow = _ref.onDragEnterRow,
onDragLeaveRow = _ref.onDragLeaveRow,
isDragRow = _ref.isDragRow,
isDraggable = _ref.isDraggable,
hasDragAndDrop = _ref.hasDragAndDrop,
hideDragHandles = _ref.hideDragHandles;
var isEditMode = rowEditMode || singleRowEditMode;
var singleSelectionIndicatorWidth = hasRowSelection === 'single' ? 0 : 5;
var nestingLevelPixels = nestingLevel * 32; // if this a single hierarchy (i.e. only 1 level of nested children), do NOT show the gray offset
var nestingOffset = hasRowNesting !== null && hasRowNesting !== void 0 && hasRowNesting.hasSingleNestedHierarchy ? 0 : hasRowSelection === 'single' ? nestingLevelPixels - singleSelectionIndicatorWidth : nestingLevelPixels;
var rowSelectionCell = hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: "".concat(prefix$r, "--checkbox-table-cell"),
key: "".concat(id, "-row-selection-cell"),
onChange: isSelectable !== false ? function () {
return onRowSelected(id, !isSelected);
} : null,
onClick: function onClick(e) {
return e.stopPropagation();
}
}, /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(iotPrefix$21, "--table__cell__offset"),
style: {
'--row-nesting-offset': "".concat(nestingOffset, "px")
}
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Checkbox, {
id: "select-row-".concat(tableId, "-").concat(id),
labelText: selectRowAria,
hideLabel: true,
indeterminate: isIndeterminate,
checked: isSelected,
disabled: isSelectable === false
}))) : hasRowSelection === 'single' && useRadioButtonSingleSelect ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: "".concat(prefix$r, "--radiobutton-table-cell"),
key: "".concat(id, "-row-selection-cell"),
onClick: function onClick(e) {
return e.stopPropagation();
}
}, /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(iotPrefix$21, "--table__cell__offset"),
style: {
'--row-nesting-offset': "".concat(nestingOffset, "px")
}
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.RadioButton, {
id: "select-row-".concat(tableId, "-").concat(id),
name: "select-row-".concat(tableId, "-").concat(id),
hideLabel: true,
labelText: selectRowAria,
checked: isSelected,
onClick: isSelectable !== false ? function () {
return onRowSelected(id, !isSelected);
} : null,
disabled: isSelectable === false
}))) : null;
var dragHandleCell = !hasDragAndDrop ? null : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: "".concat(iotPrefix$21, "--table-grab-handle-cell")
}, !isDraggable || hideDragHandles ? null : /*#__PURE__*/React__default['default'].createElement(TableDragHandle, {
onStartDrag: onStartDrag,
rowId: id
}));
var firstVisibleColIndex = ordering.findIndex(function (col) {
return !col.isHidden;
});
var tableCells = /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, {
key: "".concat(tableId, "-").concat(id)
}, dragHandleCell, rowSelectionCell, ordering.map(function (col, idx) {
var _classnames, _col$filter;
var matchingColumnMeta = columns && columns.find(function (column) {
return column.id === col.columnId;
}); // initialColumnWidth for the table body cells is needed for tables that have fixed column widths
// and table-layout:auto combination so that cell content can be truncated
var initialColumnWidth = matchingColumnMeta && matchingColumnMeta.width; // if this a single hierarchy (i.e. only 1 level of nested children), do NOT show the gray offset
var offset = firstVisibleColIndex === idx ? nestingOffset : 0;
var align = matchingColumnMeta && matchingColumnMeta.align ? matchingColumnMeta.align : 'start';
var sortable = matchingColumnMeta && matchingColumnMeta.isSortable && matchingColumnMeta.align === 'end' ? matchingColumnMeta.isSortable : false;
return !col.isHidden ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
id: "cell-".concat(tableId, "-").concat(id, "-").concat(col.columnId),
key: col.columnId,
"data-column": col.columnId,
"data-offset": offset,
offset: offset,
align: align,
className: classnames$1("data-table-".concat(align), (_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$21, "--table__cell--truncate"), truncateCellText), defineProperty$d(_classnames, "".concat(iotPrefix$21, "--table__cell--sortable"), sortable), _classnames)),
width: initialColumnWidth
}, /*#__PURE__*/React__default['default'].createElement("span", {
className: classnames$1("".concat(iotPrefix$21, "--table__cell__offset"), defineProperty$d({}, "".concat(iotPrefix$21, "--table__cell__offset__expand"), wrapCellText === 'expand')),
style: {
'--row-nesting-offset': "".concat(offset, "px")
}
}, col.editDataFunction && isEditMode ? col.editDataFunction({
value: values[col.columnId],
columnId: col.columnId,
rowId: id,
row: values
}) : /*#__PURE__*/React__default['default'].createElement(TableCellRenderer, {
wrapText: wrapCellText,
truncateCellText: truncateCellText,
locale: locale,
renderDataFunction: col.renderDataFunction,
isSortable: col.isSortable,
sortFunction: col.sortFunction,
isFilterable: col.filter,
filterFunction: (_col$filter = col.filter) === null || _col$filter === void 0 ? void 0 : _col$filter.filterFunction,
columnId: col.columnId,
rowId: id,
row: values,
preserveCellWhiteSpace: preserveCellWhiteSpace
}, values[col.columnId]))) : null;
}), showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "".concat(tableId, "-").concat(id, "-row-expander-cell")
}) : null, hasRowActions && rowActions ? /*#__PURE__*/React__default['default'].createElement(RowActionsCell, {
id: id,
langDir: langDir,
tableId: tableId,
actions: rowActions,
isRowActionRunning: isRowActionRunning,
isRowExpanded: isExpanded && !hasRowNesting,
showSingleRowEditButtons: singleRowEditMode,
singleRowEditButtons: singleRowEditButtons,
overflowMenuAria: overflowMenuAria,
inProgressText: inProgressText,
actionFailedText: actionFailedText,
onApplyRowAction: onApplyRowAction,
learnMoreText: learnMoreText,
dismissText: dismissText,
rowActionsError: rowActionsError,
onClearError: onClearRowError ? function () {
return onClearRowError(id);
} : null,
size: size
}) : nestingLevel > 0 && hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "".concat(tableId, "-").concat(id, "-row-actions-cell")
}) : undefined);
var dragEnterLeaveHandlers = {
onMouseEnter: !onDragEnterRow ? undefined : function (e) {
onDragEnterRow(id, e.currentTarget);
},
onMouseLeave: !onDragLeaveRow ? undefined : function (e) {
onDragLeaveRow(id, e.currentTarget);
}
};
return hasRowExpansion || hasRowNesting ? isExpanded ? /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, {
key: id
}, /*#__PURE__*/React__default['default'].createElement(TableExpandRow, _extends_1$1({
expandHeaderId: "".concat(tableId, "-expand"),
className: classnames$1("".concat(iotPrefix$21, "--expandable-tablerow--expanded"), (_classnames3 = {}, defineProperty$d(_classnames3, "".concat(iotPrefix$21, "--expandable-tablerow--indented"), parseInt(nestingOffset, 10) > 0), defineProperty$d(_classnames3, "".concat(iotPrefix$21, "--expandable-tablerow--childless"), hasRowNesting && nestingChildCount === 0), defineProperty$d(_classnames3, "".concat(iotPrefix$21, "--table__row--dragging"), isDragRow), _classnames3)),
ariaLabel: clickToCollapseAria,
expandIconDescription: clickToCollapseAria,
isExpanded: true,
isSelected: isSelected,
hasRowSelection: hasRowSelection,
"data-row-nesting": hasRowNesting,
"data-nesting-offset": nestingOffset,
onExpand: function onExpand(evt) {
return stopPropagationAndCallback(evt, onRowExpanded, id, false);
},
onClick: function onClick() {
if (shouldExpandOnRowClick && (hasRowNesting && nestingChildCount || hasRowExpansion)) {
onRowExpanded(id, false);
}
if (hasRowSelection === 'single' && isSelectable !== false) {
onRowSelected(id, true);
}
if (isSelectable !== false) {
onRowClicked(id);
}
},
style: {
'--row-nesting-offset': "".concat(nestingOffset, "px")
},
rowId: id,
langDir: langDir
}, dragEnterLeaveHandlers), tableCells), !hasRowNesting && /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, _extends_1$1({
className: classnames$1("".concat(iotPrefix$21, "--expanded-tablerow"), (_classnames4 = {}, defineProperty$d(_classnames4, "".concat(iotPrefix$21, "--expanded-tablerow--singly-selected"), hasRowSelection === 'single' && isSelected && !useRadioButtonSingleSelect), defineProperty$d(_classnames4, "".concat(iotPrefix$21, "--table__row--dragging"), isDragRow), _classnames4))
}, dragEnterLeaveHandlers), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
colSpan: totalColumns
}, rowDetails))) : /*#__PURE__*/React__default['default'].createElement(TableExpandRow, _extends_1$1({
key: id,
expandHeaderId: "".concat(tableId, "-expand"),
className: classnames$1("".concat(iotPrefix$21, "--expandable-tablerow"), (_classnames5 = {}, defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--expandable-tablerow--parent"), hasRowNesting && (hasRowNesting === null || hasRowNesting === void 0 ? void 0 : hasRowNesting.hasSingleNestedHierarchy) && nestingChildCount > 0), defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--expandable-tablerow--childless"), hasRowNesting && nestingChildCount === 0), defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--expandable-tablerow--indented"), parseInt(nestingOffset, 10) > 0), defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--expandable-tablerow--singly-selected"), hasRowSelection === 'single' && isSelected && !useRadioButtonSingleSelect), defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--expandable-tablerow--last-child"), isLastChild), defineProperty$d(_classnames5, "".concat(iotPrefix$21, "--table__row--dragging"), isDragRow), _classnames5)),
"data-row-nesting": hasRowNesting,
"data-child-count": nestingChildCount,
"data-nesting-offset": nestingOffset,
ariaLabel: clickToExpandAria,
expandIconDescription: clickToExpandAria,
isExpanded: false,
isSelected: isSelected,
hasRowSelection: hasRowSelection,
onExpand: function onExpand(evt) {
return stopPropagationAndCallback(evt, onRowExpanded, id, true);
},
onClick: function onClick() {
if (shouldExpandOnRowClick && (hasRowNesting && nestingChildCount || hasRowExpansion)) {
onRowExpanded(id, true);
}
if (hasRowSelection === 'single' && isSelectable !== false) {
onRowSelected(id, true);
}
if (isSelectable !== false) {
onRowClicked(id);
}
},
style: {
'--row-nesting-offset': "".concat(nestingOffset, "px")
},
rowId: id,
langDir: langDir
}, dragEnterLeaveHandlers), tableCells) : hasRowSelection === 'single' && isSelected ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, _extends_1$1({
className: classnames$1("".concat(iotPrefix$21, "--table__row"), (_classnames6 = {}, defineProperty$d(_classnames6, "".concat(iotPrefix$21, "--table__row--singly-selected"), isSelected && !useRadioButtonSingleSelect), defineProperty$d(_classnames6, "".concat(iotPrefix$21, "--table__row--background"), isSelected), _classnames6)),
key: id,
onClick: function onClick() {
if (isSelectable !== false) {
onRowClicked(id);
if (hasRowSelection === 'single' && !useRadioButtonSingleSelect) {
onRowSelected(id, !isSelected);
}
}
}
}, dragEnterLeaveHandlers), tableCells) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, _extends_1$1({
className: classnames$1("".concat(iotPrefix$21, "--table__row"), (_classnames7 = {}, defineProperty$d(_classnames7, "".concat(iotPrefix$21, "--table__row--unselectable"), isSelectable === false), defineProperty$d(_classnames7, "".concat(iotPrefix$21, "--table__row--selectable"), isSelectable !== false), defineProperty$d(_classnames7, "".concat(iotPrefix$21, "--table__row--editing"), isEditMode), defineProperty$d(_classnames7, "".concat(iotPrefix$21, "--table__row--selected"), isSelected), defineProperty$d(_classnames7, "".concat(iotPrefix$21, "--table__row--dragging"), isDragRow), _classnames7)),
key: id,
onClick: function onClick() {
if (isSelectable !== false) {
if (hasRowSelection === 'single' && !useRadioButtonSingleSelect) {
onRowSelected(id, true);
}
onRowClicked(id);
}
}
}, dragEnterLeaveHandlers), tableCells);
};
TableBodyRow.propTypes = propTypes$2a;
TableBodyRow.defaultProps = defaultProps$2h;
TableBodyRow.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableBodyRow",
"props": {
"isSelected": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the row currently selected"
},
"isIndeterminate": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the row currently in an indeterminate state, i.e. some but not all children are checked"
},
"isExpanded": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the row currently expanded"
},
"selectRowAria": {
"defaultValue": {
"value": "'Select row'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"overflowMenuAria": {
"defaultValue": {
"value": "'More actions'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"clickToExpandAria": {
"defaultValue": {
"value": "'Click to expand.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"clickToCollapseAria": {
"defaultValue": {
"value": "'Click to collapse.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"rowActions": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionPropTypes"
},
"required": false,
"description": "optional per-row actions"
},
"rowDetails": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "optional row details"
},
"nestingLevel": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "offset level if row is nested"
},
"nestingChildCount": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "number of child rows underneath this row"
},
"options": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"hasRowExpansion": {
"name": "bool",
"required": false
},
"hasRowNesting": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}],
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
},
"shouldExpandOnRowClick": {
"name": "bool",
"required": false
},
"wrapCellText": {
"name": "custom",
"raw": "WrapCellTextPropTypes.isRequired",
"required": true
},
"truncateCellText": {
"name": "bool",
"required": true
},
"preserveCellWhiteSpace": {
"name": "bool",
"description": "use white-space: pre; css when true",
"required": false
},
"useRadioButtonSingleSelect": {
"name": "bool",
"description": "use radio button on single selection",
"required": false
},
"hasDragAndDrop": {
"name": "bool",
"required": false
}
}
},
"required": false,
"description": "table wide options"
},
"rowEditMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"singleRowEditMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"singleRowEditButtons": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": ""
},
"isRowActionRunning": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Is a row action actively running"
},
"rowActionsError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionErrorPropTypes"
},
"required": false,
"description": "has a row action errored out"
},
"learnMoreText": {
"defaultValue": {
"value": "'Learn more'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for learn more"
},
"inProgressText": {
"defaultValue": {
"value": "'In progress'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for in progress"
},
"dismissText": {
"defaultValue": {
"value": "'Dismiss'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for dismiss"
},
"actionFailedText": {
"defaultValue": {
"value": "'Action failed'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for action failed"
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": "direction of document"
},
"locale": {
"defaultValue": {
"value": "'en'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"isSelectable": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "enum",
"value": [{
"value": "'xs'",
"computed": false
}, {
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}, {
"value": "'xl'",
"computed": false
}]
},
"required": false,
"description": "the size passed to the table to set row height"
},
"isLastChild": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "True if this is the last child of a nested group"
},
"hasDragAndDrop": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If this row supports drag and drop. Add space for a drag handle."
},
"hideDragHandles": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If all drag handles should be hidden. This happens when an undraggable row is in the selection."
},
"onStartDrag": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback when a drag of this row starts."
},
"onDragEnterRow": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback when the mouse enters this row during a drag."
},
"onDragLeaveRow": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback when the mouse leaves this row during a drag."
},
"isDraggable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If this row can be dragged. Shows a drag handle."
},
"isDragRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If this row is being dragged."
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
},
"renderDataFunction": {
"name": "func",
"description": "for each column you can register a render callback function that is called with this object payload\n{\n value: PropTypes.any (current cell value),\n columnId: PropTypes.string,\n rowId: PropTypes.string,\n row: PropTypes.object like this {col: value, col2: value}\n}, you should return the node that should render within that cell",
"required": false
}
}
}
},
"required": true,
"description": "What column ordering is currently applied to the table"
},
"columns": {
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes.isRequired"
},
"required": false,
"description": "List of columns"
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique row id"
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id for the table"
},
"totalColumns": {
"type": {
"name": "number"
},
"required": true,
"description": "some columns might be hidden, so total columns has the overall total"
},
"values": {
"type": {
"name": "objectOf",
"value": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "bool"
}, {
"name": "object"
}, {
"name": "array"
}]
}
},
"required": true,
"description": "contents of the row each object value is a render-able node keyed by column id"
},
"tableActions": {
"type": {
"name": "shape",
"value": {
"onRowSelected": {
"name": "func",
"required": false
},
"onRowClicked": {
"name": "func",
"required": false
},
"onApplyRowAction": {
"name": "func",
"required": false
},
"onRowExpanded": {
"name": "func",
"required": false
},
"onClearRowError": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": "tableActions"
}
}
};
var propTypes$29 = {
/** The unique row id */
id: PropTypes__default['default'].string.isRequired,
/** The unique id for the table */
tableId: PropTypes__default['default'].string.isRequired,
/** The unique id for the table test */
testId: PropTypes__default['default'].string,
columns: TableColumnsPropTypes,
/** since some columns might not be currently visible */
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasRowActions: PropTypes__default['default'].bool,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
rowVisibilityRef: HtmlElementRefProp
};
var defaultProps$2g = {
testId: 'skeleton-row',
columns: [],
hasRowActions: false,
hasRowExpansion: false,
hasRowNesting: false,
hasRowSelection: false,
showExpanderColumn: false,
rowVisibilityRef: undefined
};
var SkeletonRow = function SkeletonRow(_ref) {
var id = _ref.id,
tableId = _ref.tableId,
testId = _ref.testId,
rowVisibilityRef = _ref.rowVisibilityRef,
hasRowActions = _ref.hasRowActions,
hasRowExpansion = _ref.hasRowExpansion,
hasRowNesting = _ref.hasRowNesting,
hasRowSelection = _ref.hasRowSelection,
showExpanderColumn = _ref.showExpanderColumn,
columns = _ref.columns;
return /*#__PURE__*/React__default['default'].createElement("tr", {
key: "lazy-row-".concat(id),
ref: rowVisibilityRef,
"data-testid": "".concat(tableId, "-").concat(testId)
}, hasRowSelection === 'multi' ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, columns.map(function (v, colIndex) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "empty-cell-".concat(colIndex)
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, null));
}), showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null);
};
SkeletonRow.defaultProps = defaultProps$2g;
SkeletonRow.propTypes = propTypes$29;
SkeletonRow.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "SkeletonRow",
"props": {
"testId": {
"defaultValue": {
"value": "'skeleton-row'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The unique id for the table test"
},
"columns": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes"
},
"required": false,
"description": ""
},
"hasRowActions": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowExpansion": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowNesting": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}]
},
"required": false,
"description": ""
},
"hasRowSelection": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}]
},
"required": false,
"description": "since some columns might not be currently visible"
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"rowVisibilityRef": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "HtmlElementRefProp"
},
"required": false,
"description": ""
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique row id"
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id for the table"
}
}
};
var iotPrefix$20 = settings$1.iotPrefix;
var propTypes$28 = {
/** The unique row id */
id: PropTypes__default['default'].string.isRequired,
/** The unique id for the table */
tableId: PropTypes__default['default'].string.isRequired,
/** The unique id for the table test */
testId: PropTypes__default['default'].string.isRequired,
/** total columns has the overall total */
totalColumns: PropTypes__default['default'].number.isRequired,
columns: TableColumnsPropTypes,
/** call back function for when load more row is clicked */
onRowLoadMore: PropTypes__default['default'].func.isRequired,
/** I18N label for load more */
loadMoreText: PropTypes__default['default'].string.isRequired,
/** boolean to decide if is in loading state or not */
isLoadingMore: PropTypes__default['default'].bool.isRequired,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasRowActions: PropTypes__default['default'].bool,
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
rowVisibilityRef: HtmlElementRefProp
};
var defaultProps$2f = {
columns: [],
hasRowActions: false,
hasRowExpansion: false,
hasRowNesting: false,
hasRowSelection: false,
showExpanderColumn: false,
rowVisibilityRef: undefined
};
var TableBodyLoadMoreRow = function TableBodyLoadMoreRow(_ref) {
var id = _ref.id,
tableId = _ref.tableId,
testId = _ref.testId,
rowVisibilityRef = _ref.rowVisibilityRef,
onRowLoadMore = _ref.onRowLoadMore,
loadMoreText = _ref.loadMoreText,
hasRowActions = _ref.hasRowActions,
hasRowExpansion = _ref.hasRowExpansion,
hasRowNesting = _ref.hasRowNesting,
hasRowSelection = _ref.hasRowSelection,
showExpanderColumn = _ref.showExpanderColumn,
columns = _ref.columns,
totalColumns = _ref.totalColumns,
isLoadingMore = _ref.isLoadingMore;
return isLoadingMore ? /*#__PURE__*/React__default['default'].createElement(SkeletonRow, {
id: id,
columns: columns,
rowVisibilityRef: rowVisibilityRef,
tableId: tableId,
testId: testId,
hasRowActions: hasRowActions,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting,
hasRowSelection: hasRowSelection,
showExpanderColumn: showExpanderColumn
}) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
isSelected: false
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
key: "".concat(tableId, "-").concat(id, "-row-load-more-cell"),
colSpan: totalColumns,
className: "".concat(iotPrefix$20, "--load-more-cell"),
"data-testid": "".concat(testId, "-").concat(id, "-load-more")
}, /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: "".concat(iotPrefix$20, "--load-more-cell--content"),
onClick: function onClick() {
return onRowLoadMore(id);
},
kind: "ghost",
loading: isLoadingMore
}, loadMoreText)));
};
TableBodyLoadMoreRow.defaultProps = defaultProps$2f;
TableBodyLoadMoreRow.propTypes = propTypes$28;
TableBodyLoadMoreRow.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableBodyLoadMoreRow",
"props": {
"columns": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes"
},
"required": false,
"description": ""
},
"hasRowActions": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowExpansion": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowNesting": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}]
},
"required": false,
"description": ""
},
"hasRowSelection": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}]
},
"required": false,
"description": ""
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"rowVisibilityRef": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "HtmlElementRefProp"
},
"required": false,
"description": ""
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique row id"
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id for the table"
},
"testId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id for the table test"
},
"totalColumns": {
"type": {
"name": "number"
},
"required": true,
"description": "total columns has the overall total"
},
"onRowLoadMore": {
"type": {
"name": "func"
},
"required": true,
"description": "call back function for when load more row is clicked"
},
"loadMoreText": {
"type": {
"name": "string"
},
"required": true,
"description": "I18N label for load more"
},
"isLoadingMore": {
"type": {
"name": "bool"
},
"required": true,
"description": "boolean to decide if is in loading state or not"
}
}
};
function ownKeys$1$(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$1$(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1$(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1$(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var propTypes$27 = {
/** The unique id of the table */
tableId: PropTypes__default['default'].string.isRequired,
expandedRows: ExpandedRowsPropTypes,
columns: TableColumnsPropTypes,
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** internationalized label */
selectRowAria: PropTypes__default['default'].string,
/** internationalized label */
overflowMenuAria: PropTypes__default['default'].string,
/** internationalized label */
clickToExpandAria: PropTypes__default['default'].string,
/** internationalized label */
clickToCollapseAria: PropTypes__default['default'].string,
/** I18N label for in progress */
inProgressText: PropTypes__default['default'].string,
/** I18N label for action failed */
actionFailedText: PropTypes__default['default'].string,
/** I18N label for learn more */
learnMoreText: PropTypes__default['default'].string,
/** I18N label for dismiss */
dismissText: PropTypes__default['default'].string,
/** I18N label for load more */
loadMoreText: PropTypes__default['default'].string,
/** since some columns might not be currently visible */
totalColumns: PropTypes__default['default'].number,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
/** show radio button on single selection */
useRadioButtonSingleSelect: PropTypes__default['default'].bool,
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasRowActions: PropTypes__default['default'].bool,
wrapCellText: WrapCellTextPropTypes.isRequired,
truncateCellText: PropTypes__default['default'].bool.isRequired,
/** the current state of the row actions */
rowActionsState: RowActionsStatePropTypes,
shouldExpandOnRowClick: PropTypes__default['default'].bool,
shouldLazyRender: PropTypes__default['default'].bool,
locale: PropTypes__default['default'].string,
actions: PropTypes__default['default'].shape({
onRowClicked: PropTypes__default['default'].func,
onRowSelected: PropTypes__default['default'].func,
onApplyRowActions: PropTypes__default['default'].func,
onRowExpanded: PropTypes__default['default'].func,
onRowLoadMore: PropTypes__default['default'].func
}).isRequired,
/** What column ordering is currently applied to the table */
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
rowEditMode: PropTypes__default['default'].bool,
singleRowEditButtons: PropTypes__default['default'].element,
/**
* direction of document
*/
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl']),
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string,
/** Array with rowIds that are with loading active */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** use white-space: pre; css when true */
preserveCellWhiteSpace: PropTypes__default['default'].bool,
/**
* the size passed to the table to set row height
*/
size: PropTypes__default['default'].oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
indeterminateSelectionIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
nestingLevel: PropTypes__default['default'].number,
someRowHasSingleRowEditMode: PropTypes__default['default'].bool,
row: TableRowPropTypes.isRequired,
rows: TableRowsPropTypes,
/** True if this row is the last child of a nested group */
isLastChild: PropTypes__default['default'].bool,
/** If room is reserved for drag handles at the start of the row.. */
hasDragAndDrop: PropTypes__default['default'].bool,
/** If all drag handles should be hidden. This happens when an undraggable row is in the selection. */
hideDragHandles: PropTypes__default['default'].bool,
/**
* The rows being dragged.
*/
dragRowIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/**
* The rows that can accept a dropped row at this time. Since rows can be nested, this needs to be
* passed all the way down so each row can decide if it accepts a drop or not.
*/
canDropRowIds: PropTypes__default['default'].instanceOf(Set),
/** Callback for when a drag handle is clicked. */
onStartDrag: PropTypes__default['default'].func,
/** Callback for when a row is entered during a drag. This is null when there is not drag. */
onDragEnterRow: PropTypes__default['default'].func,
/** Callback for when a row is left during a drag. This is null when there is not drag. */
onDragLeaveRow: PropTypes__default['default'].func
};
var defaultProps$2e = {
actionFailedText: 'Action failed',
clickToCollapseAria: 'Click to collapse.',
clickToExpandAria: 'Click to expand.',
columns: [],
dismissText: 'Dismiss',
expandedIds: [],
expandedRows: [],
hasRowActions: false,
hasRowExpansion: false,
hasRowNesting: false,
hasRowSelection: false,
useRadioButtonSingleSelect: false,
indeterminateSelectionIds: [],
inProgressText: 'In progress',
langDir: 'ltr',
learnMoreText: 'Learn more',
loadingMoreIds: [],
loadMoreText: 'Load more...',
locale: null,
nestingLevel: 0,
overflowMenuAria: 'More actions',
preserveCellWhiteSpace: false,
rowActionsState: [],
rowEditMode: false,
rows: [],
selectedIds: [],
selectRowAria: 'Select row',
shouldExpandOnRowClick: false,
shouldLazyRender: false,
showExpanderColumn: false,
singleRowEditButtons: null,
size: undefined,
someRowHasSingleRowEditMode: false,
testId: '',
totalColumns: 0,
isLastChild: false,
hasDragAndDrop: false,
hideDragHandles: false,
onStartDrag: null,
onDragEnterRow: null,
onDragLeaveRow: null,
dragRowIds: [],
canDropRowIds: []
};
var TableBodyRowRenderer = function TableBodyRowRenderer(props) {
var actionFailedText = props.actionFailedText,
actions = props.actions,
clickToCollapseAria = props.clickToCollapseAria,
clickToExpandAria = props.clickToExpandAria,
columns = props.columns,
dismissText = props.dismissText,
expandedIds = props.expandedIds,
expandedRows = props.expandedRows,
hasRowActions = props.hasRowActions,
hasRowExpansion = props.hasRowExpansion,
hasRowNesting = props.hasRowNesting,
hasRowSelection = props.hasRowSelection,
useRadioButtonSingleSelect = props.useRadioButtonSingleSelect,
indeterminateSelectionIds = props.indeterminateSelectionIds,
inProgressText = props.inProgressText,
langDir = props.langDir,
learnMoreText = props.learnMoreText,
loadingMoreIds = props.loadingMoreIds,
loadMoreText = props.loadMoreText,
locale = props.locale,
nestingLevel = props.nestingLevel,
ordering = props.ordering,
overflowMenuAria = props.overflowMenuAria,
preserveCellWhiteSpace = props.preserveCellWhiteSpace,
row = props.row,
rowActionsState = props.rowActionsState,
rowEditMode = props.rowEditMode,
selectedIds = props.selectedIds,
selectRowAria = props.selectRowAria,
shouldExpandOnRowClick = props.shouldExpandOnRowClick,
shouldLazyRender = props.shouldLazyRender,
showExpanderColumn = props.showExpanderColumn,
singleRowEditButtons = props.singleRowEditButtons,
size = props.size,
someRowHasSingleRowEditMode = props.someRowHasSingleRowEditMode,
tableId = props.tableId,
testId = props.testId,
totalColumns = props.totalColumns,
truncateCellText = props.truncateCellText,
wrapCellText = props.wrapCellText,
isLastChild = props.isLastChild,
hasDragAndDrop = props.hasDragAndDrop,
hideDragHandles = props.hideDragHandles,
onStartDrag = props.onStartDrag,
onDragLeaveRow = props.onDragLeaveRow,
onDragEnterRow = props.onDragEnterRow,
canDropRowIds = props.canDropRowIds,
dragRowIds = props.dragRowIds;
var isRowExpanded = expandedIds.includes(row.id);
var shouldShowChildren = hasRowNesting && isRowExpanded && row.children && row.children.length > 0;
var myRowActionState = rowActionsState.find(function (rowAction) {
return rowAction.rowId === row.id;
});
var rowHasSingleRowEditMode = !!(myRowActionState && myRowActionState.isEditMode);
var isSelectable = rowEditMode || someRowHasSingleRowEditMode ? false : row.isSelectable;
var rowVisibilityRef = React$1.useRef(null);
var _useVisibilityObserve = useVisibilityObserver(rowVisibilityRef, {
unobserveAfterVisible: true
}),
_useVisibilityObserve2 = slicedToArray$2(_useVisibilityObserve, 1),
isVisible = _useVisibilityObserve2[0];
if (shouldLazyRender && !isVisible) {
return /*#__PURE__*/React__default['default'].createElement(SkeletonRow, {
id: row.id,
tableId: tableId,
columns: columns,
rowVisibilityRef: rowVisibilityRef,
testId: "".concat(tableId, "-lazy-row-").concat(row.id),
hasRowActions: hasRowActions,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting,
hasRowSelection: hasRowSelection,
showExpanderColumn: showExpanderColumn
});
}
var canDrop = canDropRowIds.has(row.id);
var rowElement = !row.isLoadMoreRow ? /*#__PURE__*/React__default['default'].createElement(TableBodyRow, {
hasDragAndDrop: hasDragAndDrop,
hideDragHandles: hideDragHandles,
onStartDrag: onStartDrag,
onDragEnterRow: canDrop ? onDragEnterRow : null,
onDragLeaveRow: canDrop ? onDragLeaveRow : null,
isDragRow: dragRowIds.indexOf(row.id) !== -1,
langDir: langDir,
key: row.id,
isExpanded: isRowExpanded,
isSelectable: isSelectable,
isSelected: selectedIds.includes(row.id),
isIndeterminate: indeterminateSelectionIds.includes(row.id),
rowEditMode: rowEditMode,
singleRowEditMode: rowHasSingleRowEditMode,
singleRowEditButtons: singleRowEditButtons,
rowDetails: isRowExpanded && expandedRows.find(function (j) {
return j.rowId === row.id;
}) ? expandedRows.find(function (j) {
return j.rowId === row.id;
}).content : null,
rowActionsError: myRowActionState ? myRowActionState.error : null,
isRowActionRunning: myRowActionState ? myRowActionState.isRunning : null,
ordering: ordering,
selectRowAria: selectRowAria,
overflowMenuAria: overflowMenuAria,
clickToCollapseAria: clickToCollapseAria,
clickToExpandAria: clickToExpandAria,
inProgressText: inProgressText,
actionFailedText: actionFailedText,
learnMoreText: learnMoreText,
dismissText: dismissText,
columns: columns,
tableId: tableId,
id: row.id,
locale: locale,
totalColumns: totalColumns,
options: {
hasRowSelection: hasRowSelection,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting,
hasRowActions: hasRowActions,
shouldExpandOnRowClick: shouldExpandOnRowClick,
wrapCellText: wrapCellText,
truncateCellText: truncateCellText,
preserveCellWhiteSpace: preserveCellWhiteSpace,
useRadioButtonSingleSelect: useRadioButtonSingleSelect
},
nestingLevel: nestingLevel,
nestingChildCount: row.children ? row.children.length : 0,
tableActions: _objectSpread$1$({}, pick(actions, 'onApplyRowAction', 'onRowExpanded', 'onRowClicked', 'onClearRowError', 'onRowSelected')),
rowActions: row.rowActions,
values: row.values,
isDraggable: row.isDraggable,
showExpanderColumn: showExpanderColumn,
size: size,
isLastChild: isLastChild
}) : /*#__PURE__*/React__default['default'].createElement(TableBodyLoadMoreRow, {
id: row.id,
key: "".concat(row.id, "--load-more"),
tableId: tableId,
testId: testId,
rowVisibilityRef: rowVisibilityRef,
onRowLoadMore: actions === null || actions === void 0 ? void 0 : actions.onRowLoadMore,
loadMoreText: loadMoreText,
hasRowActions: hasRowActions,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting,
hasRowSelection: hasRowSelection,
showExpanderColumn: showExpanderColumn,
columns: columns,
totalColumns: totalColumns,
isLoadingMore: loadingMoreIds.includes(row.id)
});
return shouldShowChildren ? [rowElement].concat(row.children.map(function (childRow, i) {
return /*#__PURE__*/React__default['default'].createElement(TableBodyRowRenderer, _extends_1$1({
key: "child-row-".concat(childRow.id)
}, props, {
row: childRow,
nestingLevel: nestingLevel + 1,
isLastChild: i === row.children.length - 1,
hasDragAndDrop: hasDragAndDrop,
hideDragHandles: hideDragHandles,
onStartDrag: onStartDrag,
onDragLeaveRow: onDragLeaveRow,
onDragEnterRow: onDragEnterRow,
canDropRowIds: canDropRowIds,
dragRowIds: dragRowIds
}));
})).concat(row.hasLoadMore && row.children.length > 0 ? /*#__PURE__*/React__default['default'].createElement(TableBodyRowRenderer, _extends_1$1({}, props, {
key: "load-more-row-".concat(row.id),
row: {
id: row.id,
isLoadMoreRow: true
},
nestingLevel: nestingLevel,
onStartDrag: onStartDrag,
onDragLeaveRow: onDragLeaveRow,
onDragEnterRow: onDragEnterRow,
canDropRowIds: canDropRowIds
})) : []) : rowElement;
};
TableBodyRowRenderer.defaultProps = defaultProps$2e;
TableBodyRowRenderer.propTypes = propTypes$27;
TableBodyRowRenderer.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableBodyRowRenderer",
"props": {
"actionFailedText": {
"defaultValue": {
"value": "'Action failed'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for action failed"
},
"clickToCollapseAria": {
"defaultValue": {
"value": "'Click to collapse.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"clickToExpandAria": {
"defaultValue": {
"value": "'Click to expand.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"columns": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes"
},
"required": false,
"description": ""
},
"dismissText": {
"defaultValue": {
"value": "'Dismiss'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for dismiss"
},
"expandedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"expandedRows": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "ExpandedRowsPropTypes"
},
"required": false,
"description": ""
},
"hasRowActions": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowExpansion": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowNesting": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}]
},
"required": false,
"description": ""
},
"hasRowSelection": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}]
},
"required": false,
"description": ""
},
"useRadioButtonSingleSelect": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "show radio button on single selection"
},
"indeterminateSelectionIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"inProgressText": {
"defaultValue": {
"value": "'In progress'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for in progress"
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": "direction of document"
},
"learnMoreText": {
"defaultValue": {
"value": "'Learn more'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for learn more"
},
"loadingMoreIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "Array with rowIds that are with loading active"
},
"loadMoreText": {
"defaultValue": {
"value": "'Load more...'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for load more"
},
"locale": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"nestingLevel": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"overflowMenuAria": {
"defaultValue": {
"value": "'More actions'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"preserveCellWhiteSpace": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use white-space: pre; css when true"
},
"rowActionsState": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionsStatePropTypes"
},
"required": false,
"description": "the current state of the row actions"
},
"rowEditMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"rows": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableRowsPropTypes"
},
"required": false,
"description": ""
},
"selectedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"selectRowAria": {
"defaultValue": {
"value": "'Select row'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"shouldExpandOnRowClick": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"shouldLazyRender": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"singleRowEditButtons": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": ""
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "enum",
"value": [{
"value": "'xs'",
"computed": false
}, {
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}, {
"value": "'xl'",
"computed": false
}]
},
"required": false,
"description": "the size passed to the table to set row height"
},
"someRowHasSingleRowEditMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"totalColumns": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "since some columns might not be currently visible"
},
"isLastChild": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "True if this row is the last child of a nested group"
},
"hasDragAndDrop": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If room is reserved for drag handles at the start of the row.."
},
"hideDragHandles": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If all drag handles should be hidden. This happens when an undraggable row is in the selection."
},
"onStartDrag": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback for when a drag handle is clicked."
},
"onDragEnterRow": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback for when a row is entered during a drag. This is null when there is not drag."
},
"onDragLeaveRow": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback for when a row is left during a drag. This is null when there is not drag."
},
"dragRowIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "The rows being dragged."
},
"canDropRowIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "instanceOf",
"value": "Set"
},
"required": false,
"description": "The rows that can accept a dropped row at this time. Since rows can be nested, this needs to be\npassed all the way down so each row can decide if it accepts a drop or not."
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id of the table"
},
"wrapCellText": {
"type": {
"name": "custom",
"raw": "WrapCellTextPropTypes.isRequired"
},
"required": false,
"description": ""
},
"truncateCellText": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"actions": {
"type": {
"name": "shape",
"value": {
"onRowClicked": {
"name": "func",
"required": false
},
"onRowSelected": {
"name": "func",
"required": false
},
"onApplyRowActions": {
"name": "func",
"required": false
},
"onRowExpanded": {
"name": "func",
"required": false
},
"onRowLoadMore": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": "What column ordering is currently applied to the table"
},
"row": {
"type": {
"name": "custom",
"raw": "TableRowPropTypes.isRequired"
},
"required": false,
"description": ""
}
}
};
var iotPrefix$1$ = settings$1.iotPrefix;
/**
* During a drag and drop we want a border around the row we're about to drop on. We can't add a CSS
* border on the row since the cells already have borders on them. And if we alter them and change
* widths, the table shifts. Instead, we overlay a transparent element over the row and add the
* border to that. That is this overlay.
*
* @param {object} props
*/
var TableDropRowOverlay = /*#__PURE__*/React$1.forwardRef(function TableDropRowOverlay(_, ref) {
return /*#__PURE__*/ReactDOM.createPortal( /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1$, "--table-drop-row-overlay"),
ref: ref
}), document.body);
});
TableDropRowOverlay.__docgenInfo = {
"description": "During a drag and drop we want a border around the row we're about to drop on. We can't add a CSS\nborder on the row since the cells already have borders on them. And if we alter them and change\nwidths, the table shifts. Instead, we overlay a transparent element over the row and add the\nborder to that. That is this overlay.\n\n@param {object} props",
"methods": []
};
var iotPrefix$1_ = settings$1.iotPrefix;
var propTypes$26 = {
/**
* Any children to show in the avatar while dragging. Usually the row name and icon or similar.
*/
children: PropTypes__default['default'].node.isRequired,
/** CSS z-index for the avatar. */
zIndex: PropTypes__default['default'].number.isRequired
};
/**
* The drag avatar that shows a preview of what's being dragged. The caller provides the child
* "image" node (anything) to show, but this draws the bordered tile and around it. This must be
* absolutely positioned on the page via its ref.
*
* @param {object} props
* @param {ref} ref React ref to connect to the root dom node.
*
*/
var TableDragAvatar = /*#__PURE__*/React$1.forwardRef(function TableDragAvatar(_ref, ref) {
var zIndex = _ref.zIndex,
children = _ref.children;
return /*#__PURE__*/ReactDOM.createPortal( /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1_, "--table-drag-avatar"),
ref: ref,
style: {
zIndex: zIndex
}
}, children), document.body);
});
TableDragAvatar.propTypes = propTypes$26;
TableDragAvatar.__docgenInfo = {
"description": "The drag avatar that shows a preview of what's being dragged. The caller provides the child\n\"image\" node (anything) to show, but this draws the bordered tile and around it. This must be\nabsolutely positioned on the page via its ref.\n\n@param {object} props\n@param {ref} ref React ref to connect to the root dom node.",
"methods": [],
"props": {
"children": {
"type": {
"name": "node"
},
"required": true,
"description": "Any children to show in the avatar while dragging. Usually the row name and icon or similar."
},
"zIndex": {
"type": {
"name": "number"
},
"required": true,
"description": "CSS z-index for the avatar."
}
}
};
var prefix$q = settings$1.prefix,
iotPrefix$1Z = settings$1.iotPrefix;
/**
* This is similar to `useState` but pairs the value with a ref to the value. The benefit of this is
* that callback functions do not need to include refs in their dependency lists, but can access
* their most recent values safely.
*
* This is important for some data used in manually added event listeners, like for "mousemove". If
* listeners depend on normal state, they must be removed and added frequently to create a closure
* around the new state. But by using a ref they only need to close around the mutable ref, then use
* that to access the value they needs. For drag and drop, we need to ensure there are no
* dependencies that would cause the `setupDnd` effect to tear down and set up repeatedly since they
* will cause visual and performance problems.
*
* Note that this still returns a stateful value along with the ref. That normal state value should
* be used for any traditional reactive updates.
*
* @param {any} initialValue Initial value to set. Omit to start with `undefined`.
* @returns 3 item tuple of: reference to the value, the stateful value, and function to update both
* of them. The setter does trigger a state update and potential rerender.
*/
function useRefAndState(initialValue) {
var _useState = React$1.useState(initialValue),
_useState2 = slicedToArray$2(_useState, 2),
value = _useState2[0],
setValue = _useState2[1];
var ref = React$1.useRef(initialValue);
var setter = React$1.useCallback(function (newValue) {
ref.current = newValue;
setValue(newValue);
}, []);
return [ref, value, setter];
}
/**
* If there is a vertical scroll bar on the document and in RTL mode then this returns its width.
* Otherwise, returns 0.
*
* In RTL `getBoundingClientRect` is relative to the window edge, but pos:abs elements are relative
* to the left-side, vertical scrollbar (if there is one). That means the positioned elements might
* be shifted over by the vertical scrollbar width. This gets the width if relevant so it can be
* subtracted out in some values.
*/
function getRtlVerticalScrollbarWidth() {
/* istanbul ignore next */
// ignore rlt
return document.dir === 'rtl' ? window.innerWidth - document.documentElement.clientWidth : 0;
}
/**
* Event handlers to mix into the table and state variables about the current drag and drop
* operation.
*
* @typedef {Object} UseTableDndResult
* @property {boolean} isDragging If a drag is in progress.
* @property {ReactNode} dragPreview A element that must be rendered as a child of the page body.
* This is the image that's shown during a drag and follows the mouse.
* @property {string} activeDropRowId The row a drag is hovering over and might drop on.
* @property {Set} canDropRowIds The row IDs that can be dropped on. These were given by the
* caller from the `onDrag` callback.
* @property {string[]} dragRowIds The rows that are being dragged.
* @property {(MouseEvent) => void} handleEnterRow - Event handler that must be added as a
* "mouseenter" listener to the table rows.
* @property {(MouseEvent) => void} handleLeaveRow Event handler that must be added as a
* "mouseleave" listener to the table rows.
* @property {(MouseEvent) => void} handleStartPossibleDrag Event handler that must be added as a
* "mousedown" listener on the all drag handles of the table rows.
*/
/**
* Sets up a PAL table for drag and drop support.
*
* This is is hook purely to move this code into its own file. This is coupled with `TableBody` and
* only makes sense using it there.
*
* @param {object[]} rows The rows of the table we're dragging in.
* @param {string[]} selectedIds The currently selected row IDs or empty array.
* @param {number | undefined} Optional minimum z-index for the drag image. Required if the table is
* in a modal with a >0 z-index.
* @param {(object[]) -> {preview: ReactNode, dropIds: string[]}} onDrag Callback fires when a drag
* actually start. This passes the the table rows being dragged. It must return a tuple of a
* ReactNode to show as the drag image and a list of row IDs that can accept a drop from the given
* dragged row ID.
* @param {(string[], string) => void} onDrop Callback when a drop succeeds. Passes the IDs of the
* rows being dragged and the ID of the row being dropped on.
* @returns {UseTableDndResult} Values to mix into the table.
*/
function useTableDnd(rows, selectedIds, zIndex, onDrag, onDrop) {
// These are related. When the user "mousedown"s on a drag handle, we consider it a "possible"
// drag. At this point we add all the event listeners to track the drag. Put only after they move
// past some threshold do we actually set `isDragging`. At that point the drag is "real" and we'll
// fire the onDrag callback and draw the drag image.
var _useState3 = React$1.useState(false),
_useState4 = slicedToArray$2(_useState3, 2),
isPossibleDrag = _useState4[0],
setIsPossibleDrag = _useState4[1];
var _useRefAndState = useRefAndState(false),
_useRefAndState2 = slicedToArray$2(_useRefAndState, 3),
isDraggingRef = _useRefAndState2[0],
isDragging = _useRefAndState2[1],
setIsDragging = _useRefAndState2[2]; // The row being dragged
var _useRefAndState3 = useRefAndState([]),
_useRefAndState4 = slicedToArray$2(_useRefAndState3, 3),
dragRowIdsRef = _useRefAndState4[0],
dragRowIds = _useRefAndState4[1],
setDragRowIds = _useRefAndState4[2]; // The rows that CAN be dropped on, but we're not necessarily over them right now. The caller
// provides these from the onDrag callback.
var _useState5 = React$1.useState(new Set()),
_useState6 = slicedToArray$2(_useState5, 2),
canDropRowIds = _useState6[0],
setCanDropRowIds = _useState6[1]; // The drag preview we show under the cursors when dragging. The caller constructs this for use in
// the onDrag callback.
var _useState7 = React$1.useState(null),
_useState8 = slicedToArray$2(_useState7, 2),
dragPreview = _useState8[0],
setDragPreview = _useState8[1];
var avatarRef = React$1.useRef(null); // The row ID we're hovering over during a drag. Only if it accepts a drop. Note there is a state
// and ref for the same value. See setActiveDropRowId.
var activeDropRowIdRef = React$1.useRef(null); // The coords where a DnD starts from. Not a state change, just used later in response to mousemove.
var dragStartCoordsRef = React$1.useRef();
/**
* After a failed drag (canceled or not over a good row) this animates the avatar back into its
* original position to show that the drop did not succeed.
*/
function snapBackAvatar() {
if (avatarRef.current) {
/* istanbul ignore next */
avatarRef.current.ontransitionend = function () {
return setDragPreview(null);
};
avatarRef.current.style.transition = 'transform 200ms';
avatarRef.current.style.transform = "translate(".concat(document.documentElement.scrollLeft, "px, ").concat(document.documentElement.scrollTop, "px)");
}
}
var handleDrop = React$1.useCallback(
/**
* Called when a drop occurs. Ends the drag operations and fires the `onDrop` callback if over a
* row that can be dropped on.
*/
function handleDrop(e) {
e.stopPropagation();
if (activeDropRowIdRef.current == null) {
snapBackAvatar();
} else {
// Notify of success. Protect from caller errors.
onDrop(dragRowIds, activeDropRowIdRef.current);
setDragPreview(null);
}
setIsPossibleDrag(false);
}, [activeDropRowIdRef, onDrop, dragRowIds]);
var badMoveCountRef = React$1.useRef(0);
var handleDragMove = React$1.useCallback(
/**
* Event handler when the mouse moves during a drag. This actually starts the real drag once the
* mouse has moved past a threshold. Throughout the drag, updates the drag avatar position. This
* does not track what row we're over--`handleEnterRow` know that from onmouseenter events.
*
* @param {React.MouseEvent} e
*/
function handleDragMove(e) {
if (e.buttons === 0) {
badMoveCountRef.current += 1;
if (badMoveCountRef.current >= 10) {
// If the mouse goes outside the window and releases the button then the mouseup is missed
// and the drag is stuck. If we see a few moves without a mouse button down then that's
// probably the case. We don't do this on the first bad move since Safari and Firefox on
// macOS can fire a mousemove without buttons BEFORE a mouse up sometimes, which would
// cancel the drop too early. Waiting a few means this really is stuck, not just an
// unexpected event order.
setIsPossibleDrag(false);
}
}
var _dragStartCoordsRef$c = dragStartCoordsRef.current,
startX = _dragStartCoordsRef$c.startX,
startY = _dragStartCoordsRef$c.startY;
var diffX = e.clientX - startX + document.documentElement.scrollLeft;
var diffY = e.clientY - startY + document.documentElement.scrollTop;
if (!isDraggingRef.current && Math.abs(diffX) < 5 && Math.abs(diffY) < 5) {
// Reach minimum drag distance before showing avatar and really dragging.
return;
}
if (!isDraggingRef.current) {
// Convert from IDs to the real rows, even children
var draggedRows = [];
tableTraverser(rows, function (rowOrChildRow) {
if (dragRowIdsRef.current.includes(rowOrChildRow.id)) {
draggedRows.push(rowOrChildRow);
}
});
/* istanbul igore else */
if (draggedRows.length) {
// Notify of a drag starting and get the details about what this row does.
var _onDrag = onDrag(draggedRows),
preview = _onDrag.preview,
dropIds = _onDrag.dropIds;
setDragPreview(preview);
setCanDropRowIds(new Set(dropIds));
}
} // We've reach min drag threshold, so we're really dragging now. This will show the avatar and
// add onenter listeners to rows.
setIsDragging(true); // clientX is *always* relative to the top, left, so we can't just use logical properties. In
// RTL mode we want to position relative to the right side explicitly, which means the
// difference between the right vieport edge (doc width) and clientX.
/* istanbul ignore next */
var _ref = document.dir === 'rtl' ? {
right: "calc(".concat(document.documentElement.offsetWidth - startX + getRtlVerticalScrollbarWidth(), "px - 1.5rem)"),
left: 'auto'
} : {
left: "calc(".concat(startX, "px - 1.5rem)"),
right: 'auto'
},
left = _ref.left,
right = _ref.right;
if (avatarRef.current) {
// Update the style directly on the DOM node (not via React) since this is so much faster and
// we're doing this very frequently.
Object.assign(avatarRef.current.style, {
display: '',
top: "calc(".concat(startY, "px - 1.4rem)"),
// nudge over a bit, so the cursor is on the tile, not in the very corner.
left: left,
right: right,
transform: "translate(".concat(diffX, "px, ").concat(diffY, "px)")
});
}
}, [isDraggingRef, setIsDragging, rows, dragRowIdsRef, onDrag]);
var cancel = React$1.useCallback(
/**
* Cancels the drag. Tears down the events and snaps back avatar.
* @param {[event]} e Optional event to stop. Mostly for eating the escape key.
*/
function cancel(e) {
if (e) e.stopPropagation();
snapBackAvatar();
setIsPossibleDrag(false);
}, []);
React$1.useEffect(
/**
* Once a drag appears to start (user "mousedown"s on a drag handle) this adds the needed event
* listeners and classes to track the drag. This is the main setup method. We don't technically
* consider it a real DnD until the mouse has moved a certain threshold though. In that way, we
* don't set show a drag image (avatar) or update any rows if the user were to just click the
* drag handle--they need to really drag it a bit.
*
* The main dependency of this is `isPossibleDrag`, which is intended to setup the drag events
* when true, and tear them down when false. The others are just dependencies and not intended
* to fire this effect per set. In fact, we don't want the other to change while
* `isPossibleDrag` is true or the drag can be interrupted before it's done. While we can't
* control what props the caller actually changes, things like `rows` and `onDrop` are unlikely
* to change during a drag.
*/
function setupDnd() {
if (!isPossibleDrag) {
// Don't connect anything. Everything is torn down in the cleanup from when this this effect
// was last called.
cancel();
return undefined;
}
badMoveCountRef.current = 0;
function handleEscapeKey(e) {
if (e.key === 'Escape') {
cancel(e);
}
}
/**
* Stops an event. This is used to stop click event during drag and drop, otherwise the
* mouseup can trigger a click on the row and the row click handler will be invoked. For
* expandable rows, this might expand or collapse the row. We add this to the event capture
* phase to intercept the click before the row can see it.
* @param {event} e DOM event.
*/
function stopEvent(e) {
e.preventDefault();
e.stopPropagation();
}
document.body.addEventListener('click', stopEvent, true);
document.body.addEventListener('mouseup', handleDrop);
document.body.addEventListener('mousemove', handleDragMove);
document.body.addEventListener('keydown', handleEscapeKey); // If the user goes to another window, cancel the dnd.
window.addEventListener('blur', cancel); // Add global drag state class. This is mostly use to ensure the cursor is "grabbing", but can
// be used to disable non-drag related hover states. We add it here even though the cursor
// hasn't moved enough to start a real drag so the user can see a drag can be started from the
// cursor.
document.body.classList.add("".concat(iotPrefix$1Z, "--is-dragging"));
return function tearDown() {
// console.debug('Clean up table DnD');
document.body.removeEventListener('click', stopEvent, true);
document.body.removeEventListener('mouseup', handleDrop);
document.body.removeEventListener('mousemove', handleDragMove);
document.body.removeEventListener('keydown', handleEscapeKey);
window.removeEventListener('blur', cancel);
document.body.classList.remove("".concat(iotPrefix$1Z, "--is-dragging"));
setDragRowIds([]);
activeDropRowIdRef.current = null;
setCanDropRowIds(new Set());
setIsDragging(false);
};
}, [isPossibleDrag, handleDragMove, handleDrop, cancel, setIsDragging, setDragRowIds]);
var handleStartPossibleDrag = React$1.useCallback(
/**
* This is the callback when a user starts a possible drag with a mousedown on a drag handle. At
* this point we'll set up event listeners to track the mouse movement and decide if it's a real
* DnD or not. Until it moves past a threshold we don't show a drag image or change the table
* props yet.
*/
function handleStartPossibleDrag(e, rowId) {
dragStartCoordsRef.current = {
startX: e.clientX,
startY: e.clientY
};
if (selectedIds.includes(rowId)) {
// we're in the selected set, so drag all selected rows.
setDragRowIds(selectedIds);
} else {
// just drag this one
setDragRowIds([rowId]);
}
setIsPossibleDrag(true);
}, [setDragRowIds, selectedIds]);
/** Ref to the root DOM element of the row overlay. Used to directly update its style. */
var overlayRef = React$1.useRef(null);
var handleEnterRow = React$1.useCallback(
/**
* Callback when the mouse enters a table row. The table needs to add this as an onmouseenter
* handler.
* @param {string} rowId Row mouse is over.
* @returns
*/
function handleEnterRow(rowId, rowEl) {
/* istanbul ignore if */
if (!isPossibleDrag) {
// shouldn't happen
return;
} // The table can scroll in it container. In that case, the row overlay should not span the
// entire row width, only as wide as the container.
var scrollContainer = rowEl.closest(".".concat(prefix$q, "--data-table-content"));
var contentRect = scrollContainer.getBoundingClientRect();
var rowRect = rowEl.getBoundingClientRect();
var style = {
display: 'block',
top: "".concat(rowRect.top + document.documentElement.scrollTop, "px"),
left: "".concat(contentRect.left + document.documentElement.scrollLeft - getRtlVerticalScrollbarWidth(), "px"),
width: "".concat(contentRect.width, "px"),
height: "".concat(rowRect.height, "px"),
zIndex: zIndex + 1000
}; // istanbul ignore else
if (overlayRef.current) Object.assign(overlayRef.current.style, style);
rowEl.classList.add("".concat(iotPrefix$1Z, "--table__row--dropping"));
activeDropRowIdRef.current = rowId;
}, [isPossibleDrag, zIndex]);
var handleLeaveRow = React$1.useCallback(
/**
* Callback when the mouse leaves a table row. The table needs to add this as an onmouseenter
* handler.
* @param {string} rowId A row we are no longer over.
*/
function handleLeaveRow(rowId, rowEl) {
/* istanbul ignore else */
if (activeDropRowIdRef.current === rowId) {
activeDropRowIdRef.current = null; // istanbul ignore else
if (overlayRef.current) overlayRef.current.style.display = 'none';
rowEl.classList.remove("".concat(iotPrefix$1Z, "--table__row--dropping"));
}
}, []); // During a drag we show an avatar near the cursor and an overlay over the hovered row, if there
// is one. These needs to be added to the body element by the caller.
var dragPreviewAndOverlay = /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, isDragging && /*#__PURE__*/React__default['default'].createElement(TableDropRowOverlay, {
ref: overlayRef
}), dragPreview && /*#__PURE__*/React__default['default'].createElement(TableDragAvatar, {
zIndex: zIndex + 1001,
ref: avatarRef
}, dragPreview));
return {
isDragging: isDragging,
dragPreview: dragPreviewAndOverlay,
canDropRowIds: canDropRowIds,
dragRowIds: dragRowIds,
handleEnterRow: handleEnterRow,
handleLeaveRow: handleLeaveRow,
handleStartPossibleDrag: handleStartPossibleDrag
};
}
function ownKeys$1_(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$1_(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1_(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1_(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var propTypes$25 = {
/** The unique id of the table */
tableId: PropTypes__default['default'].string.isRequired,
rows: TableRowsPropTypes,
expandedRows: ExpandedRowsPropTypes,
columns: TableColumnsPropTypes,
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** internationalized label */
selectRowAria: PropTypes__default['default'].string,
/** internationalized label */
overflowMenuAria: PropTypes__default['default'].string,
/** internationalized label */
clickToExpandAria: PropTypes__default['default'].string,
/** internationalized label */
clickToCollapseAria: PropTypes__default['default'].string,
/** I18N label for in progress */
inProgressText: PropTypes__default['default'].string,
/** I18N label for action failed */
actionFailedText: PropTypes__default['default'].string,
/** I18N label for learn more */
learnMoreText: PropTypes__default['default'].string,
/** I18N label for dismiss */
dismissText: PropTypes__default['default'].string,
/** I18N label for load more */
loadMoreText: PropTypes__default['default'].string,
/** since some columns might not be currently visible */
totalColumns: PropTypes__default['default'].number,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
useRadioButtonSingleSelect: PropTypes__default['default'].bool,
hasRowExpansion: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasRowActions: PropTypes__default['default'].bool,
wrapCellText: WrapCellTextPropTypes.isRequired,
truncateCellText: PropTypes__default['default'].bool.isRequired,
/** the current state of the row actions */
rowActionsState: RowActionsStatePropTypes,
shouldExpandOnRowClick: PropTypes__default['default'].bool,
shouldLazyRender: PropTypes__default['default'].bool,
locale: PropTypes__default['default'].string,
actions: PropTypes__default['default'].shape({
onRowSelected: PropTypes__default['default'].func,
onRowClicked: PropTypes__default['default'].func,
onApplyRowActions: PropTypes__default['default'].func,
onRowExpanded: PropTypes__default['default'].func,
onRowLoadMore: PropTypes__default['default'].func,
onDrag: PropTypes__default['default'].func,
onDrop: PropTypes__default['default'].func
}).isRequired,
/** What column ordering is currently applied to the table */
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
rowEditMode: PropTypes__default['default'].bool,
singleRowEditButtons: PropTypes__default['default'].element,
/**
* direction of document
*/
langDir: PropTypes__default['default'].oneOf(['ltr', 'rtl']),
/** shows an additional column that can expand/shrink as the table is resized */
showExpanderColumn: PropTypes__default['default'].bool,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
testId: PropTypes__default['default'].string,
/** Array with rowIds that are with loading active */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** use white-space: pre; css when true */
preserveCellWhiteSpace: PropTypes__default['default'].bool,
/**
* the size passed to the table to set row height
*/
size: PropTypes__default['default'].oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
/** If room is reserved for drag handles at the start of rows. */
hasDragAndDrop: PropTypes__default['default'].bool,
/** If all drag handles should be hidden. This happens when an undraggable row is in the selection. */
hideDragHandles: PropTypes__default['default'].bool,
/** Optional base z-index for the drag image. See details on Table component. */
zIndex: PropTypes__default['default'].number,
/** column to pin in the table */
pinColumn: PinColumnPropTypes
};
var defaultProps$2d = {
expandedIds: [],
selectedIds: [],
loadingMoreIds: [],
selectRowAria: 'Select row',
overflowMenuAria: 'More actions',
clickToExpandAria: 'Click to expand.',
clickToCollapseAria: 'Click to collapse.',
locale: null,
rows: [],
expandedRows: [],
rowActionsState: [],
columns: [],
totalColumns: 0,
hasRowSelection: false,
useRadioButtonSingleSelect: false,
hasRowExpansion: false,
hasRowNesting: false,
hasRowActions: false,
shouldExpandOnRowClick: false,
shouldLazyRender: false,
rowEditMode: false,
singleRowEditButtons: null,
langDir: 'ltr',
showExpanderColumn: false,
testId: '',
preserveCellWhiteSpace: false,
loadMoreText: 'Load more...',
learnMoreText: 'Learn more',
inProgressText: 'In progress',
dismissText: 'Dismiss',
actionFailedText: 'Action failed',
size: undefined,
hasDragAndDrop: false,
hideDragHandles: false,
zIndex: 0,
pinColumn: PIN_COLUMN.NONE
};
var TableBody = function TableBody(_ref) {
var tableId = _ref.tableId,
rows = _ref.rows,
columns = _ref.columns,
expandedIds = _ref.expandedIds,
expandedRows = _ref.expandedRows,
selectedIds = _ref.selectedIds,
loadingMoreIds = _ref.loadingMoreIds,
selectRowAria = _ref.selectRowAria,
overflowMenuAria = _ref.overflowMenuAria,
clickToExpandAria = _ref.clickToExpandAria,
clickToCollapseAria = _ref.clickToCollapseAria,
inProgressText = _ref.inProgressText,
learnMoreText = _ref.learnMoreText,
dismissText = _ref.dismissText,
actionFailedText = _ref.actionFailedText,
loadMoreText = _ref.loadMoreText,
totalColumns = _ref.totalColumns,
actions = _ref.actions,
rowActionsState = _ref.rowActionsState,
hasRowActions = _ref.hasRowActions,
hasRowSelection = _ref.hasRowSelection,
useRadioButtonSingleSelect = _ref.useRadioButtonSingleSelect,
hasRowExpansion = _ref.hasRowExpansion,
hasRowNesting = _ref.hasRowNesting,
shouldExpandOnRowClick = _ref.shouldExpandOnRowClick,
shouldLazyRender = _ref.shouldLazyRender,
ordering = _ref.ordering,
wrapCellText = _ref.wrapCellText,
truncateCellText = _ref.truncateCellText,
locale = _ref.locale,
rowEditMode = _ref.rowEditMode,
singleRowEditButtons = _ref.singleRowEditButtons,
langDir = _ref.langDir,
testID = _ref.testID,
testId = _ref.testId,
showExpanderColumn = _ref.showExpanderColumn,
preserveCellWhiteSpace = _ref.preserveCellWhiteSpace,
size = _ref.size,
hasDragAndDrop = _ref.hasDragAndDrop,
hideDragHandles = _ref.hideDragHandles,
zIndex = _ref.zIndex,
pinColumn = _ref.pinColumn;
// Need to merge the ordering and the columns since the columns have the renderer function
var orderingMap = React$1.useMemo(function () {
return ordering.map(function (col) {
return _objectSpread$1_(_objectSpread$1_({}, col), columns.find(function (column) {
return column.id === col.columnId;
}));
});
}, [columns, ordering]);
var findAllAncestorRows = function findAllAncestorRows(childId, myRows) {
var result = [];
var applyFunc = function applyFunc(row, ancestors) {
var _result, _row$children;
var lastChildId = ((_result = result[result.length - 1]) === null || _result === void 0 ? void 0 : _result.id) || childId;
var currentRowIsParent = (_row$children = row.children) === null || _row$children === void 0 ? void 0 : _row$children.filter(function (child) {
return child.id === lastChildId;
}).length;
if (currentRowIsParent) {
ancestors.push(row);
}
};
tableTraverser(myRows, applyFunc, result);
return result;
};
var findAllChildRowIds = function findAllChildRowIds(_ref2) {
var _ref2$children = _ref2.children,
children = _ref2$children === void 0 ? [] : _ref2$children;
var result = [];
tableTraverser(children, function (row, aggr) {
return aggr.push(row.id);
}, result);
return result;
};
var updateChildIdSelection = function updateChildIdSelection(triggeringRowId, myRows, selection) {
var row = findRow(triggeringRowId, myRows);
var childRowIds = findAllChildRowIds(row);
var triggeringRowSelected = selection.includes(triggeringRowId);
return triggeringRowSelected ? toConsumableArray(new Set(selection.concat(childRowIds))) : selection.filter(function (id) {
return !childRowIds.includes(id);
});
};
var updateAncestorSelection = function updateAncestorSelection(allAncestorRows, selection) {
var newSelection = toConsumableArray(selection);
allAncestorRows.forEach(function (ancestorRow) {
if (ancestorRow.children.every(function (child) {
return newSelection.includes(child.id);
})) {
newSelection.push(ancestorRow.id);
} else if (newSelection.includes(ancestorRow.id)) {
newSelection.splice(newSelection.indexOf(ancestorRow.id), 1);
}
});
return newSelection;
};
var onRowSelected = function onRowSelected(rowId, selected) {
if (hasRowSelection === 'single') {
actions.onRowSelected(rowId, selected, selected ? [rowId] : []);
} else {
var allAncestorRows = findAllAncestorRows(rowId, rows) || [];
var withNewSelection = selected ? [].concat(toConsumableArray(selectedIds), [rowId]) : selectedIds.filter(function (id) {
return id !== rowId;
});
var withUpdatedAncestors = updateAncestorSelection(allAncestorRows, withNewSelection);
var withUpdatedChildren = updateChildIdSelection(rowId, rows, withUpdatedAncestors);
actions.onRowSelected(rowId, selected, withUpdatedChildren.sort());
}
};
var getIndeterminateRowSelectionIds = function getIndeterminateRowSelectionIds(myRows, mySelectedIds) {
var result = [];
if (hasRowNesting && mySelectedIds.length) {
var applyFunc = function applyFunc(row, indeterminateList) {
var allChildren = findAllChildRowIds(row);
var allAreSelected = allChildren.every(function (childId) {
return mySelectedIds.includes(childId);
});
var someAreSelected = !allAreSelected && allChildren.some(function (childId) {
return mySelectedIds.includes(childId);
});
if (someAreSelected) {
indeterminateList.push(row.id);
}
};
tableTraverser(myRows, applyFunc, result);
}
return result;
};
var _useTableDnd = useTableDnd(rows, selectedIds, zIndex, actions.onDrag, actions.onDrop),
isDragging = _useTableDnd.isDragging,
dragPreview = _useTableDnd.dragPreview,
dragRowIds = _useTableDnd.dragRowIds,
canDropRowIds = _useTableDnd.canDropRowIds,
handleStartPossibleDrag = _useTableDnd.handleStartPossibleDrag,
handleEnterRow = _useTableDnd.handleEnterRow,
handleLeaveRow = _useTableDnd.handleLeaveRow;
var tableBodyClassNames = classnames$1(pinColumnClassNames({
pinColumn: pinColumn,
hasRowSelection: hasRowSelection,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting
}));
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableBody, {
"data-testid": testID || testId,
className: tableBodyClassNames || undefined
}, rows.map(function (row) {
return /*#__PURE__*/React__default['default'].createElement(TableBodyRowRenderer, {
key: row.id,
actionFailedText: actionFailedText,
actions: _objectSpread$1_(_objectSpread$1_({}, actions), {}, {
onRowSelected: onRowSelected
}),
clickToCollapseAria: clickToCollapseAria,
clickToExpandAria: clickToExpandAria,
columns: columns,
dismissText: dismissText,
expandedIds: expandedIds,
expandedRows: expandedRows,
hasRowActions: hasRowActions,
hasRowExpansion: hasRowExpansion,
hasRowNesting: hasRowNesting,
hasRowSelection: hasRowSelection,
useRadioButtonSingleSelect: useRadioButtonSingleSelect,
indeterminateSelectionIds: getIndeterminateRowSelectionIds(rows, selectedIds),
inProgressText: inProgressText,
langDir: langDir,
learnMoreText: learnMoreText,
loadingMoreIds: loadingMoreIds,
loadMoreText: loadMoreText,
locale: locale,
ordering: orderingMap,
overflowMenuAria: overflowMenuAria,
preserveCellWhiteSpace: preserveCellWhiteSpace,
row: row,
rowActionsState: rowActionsState,
rowEditMode: rowEditMode,
selectedIds: selectedIds,
selectRowAria: selectRowAria,
shouldExpandOnRowClick: shouldExpandOnRowClick,
shouldLazyRender: shouldLazyRender,
showExpanderColumn: showExpanderColumn,
singleRowEditButtons: singleRowEditButtons,
size: size,
someRowHasSingleRowEditMode: rowActionsState.some(function (rowAction) {
return rowAction.isEditMode;
}),
tableId: tableId,
testId: testID || testId,
totalColumns: totalColumns,
truncateCellText: truncateCellText,
wrapCellText: wrapCellText,
hasDragAndDrop: hasDragAndDrop,
hideDragHandles: hideDragHandles,
onStartDrag: handleStartPossibleDrag,
onDragEnterRow: isDragging ? handleEnterRow : null,
onDragLeaveRow: isDragging ? handleLeaveRow : null,
dragRowIds: dragRowIds,
canDropRowIds: canDropRowIds
});
})), dragPreview);
};
TableBody.propTypes = propTypes$25;
TableBody.defaultProps = defaultProps$2d;
TableBody.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableBody",
"props": {
"expandedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"selectedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"loadingMoreIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "Array with rowIds that are with loading active"
},
"selectRowAria": {
"defaultValue": {
"value": "'Select row'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"overflowMenuAria": {
"defaultValue": {
"value": "'More actions'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"clickToExpandAria": {
"defaultValue": {
"value": "'Click to expand.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"clickToCollapseAria": {
"defaultValue": {
"value": "'Click to collapse.'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "internationalized label"
},
"locale": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"rows": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableRowsPropTypes"
},
"required": false,
"description": ""
},
"expandedRows": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "ExpandedRowsPropTypes"
},
"required": false,
"description": ""
},
"rowActionsState": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "RowActionsStatePropTypes"
},
"required": false,
"description": "the current state of the row actions"
},
"columns": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes"
},
"required": false,
"description": ""
},
"totalColumns": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "since some columns might not be currently visible"
},
"hasRowSelection": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}]
},
"required": false,
"description": ""
},
"useRadioButtonSingleSelect": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowExpansion": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasRowNesting": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}]
},
"required": false,
"description": ""
},
"hasRowActions": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"shouldExpandOnRowClick": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"shouldLazyRender": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"rowEditMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"singleRowEditButtons": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": ""
},
"langDir": {
"defaultValue": {
"value": "'ltr'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'ltr'",
"computed": false
}, {
"value": "'rtl'",
"computed": false
}]
},
"required": false,
"description": "direction of document"
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "shows an additional column that can expand/shrink as the table is resized"
},
"testId": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"preserveCellWhiteSpace": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use white-space: pre; css when true"
},
"loadMoreText": {
"defaultValue": {
"value": "'Load more...'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for load more"
},
"learnMoreText": {
"defaultValue": {
"value": "'Learn more'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for learn more"
},
"inProgressText": {
"defaultValue": {
"value": "'In progress'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for in progress"
},
"dismissText": {
"defaultValue": {
"value": "'Dismiss'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for dismiss"
},
"actionFailedText": {
"defaultValue": {
"value": "'Action failed'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "I18N label for action failed"
},
"size": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "enum",
"value": [{
"value": "'xs'",
"computed": false
}, {
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}, {
"value": "'xl'",
"computed": false
}]
},
"required": false,
"description": "the size passed to the table to set row height"
},
"hasDragAndDrop": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If room is reserved for drag handles at the start of rows."
},
"hideDragHandles": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "If all drag handles should be hidden. This happens when an undraggable row is in the selection."
},
"zIndex": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "Optional base z-index for the drag image. See details on Table component."
},
"pinColumn": {
"defaultValue": {
"value": "PIN_COLUMN.NONE",
"computed": true
},
"type": {
"name": "custom",
"raw": "PinColumnPropTypes"
},
"required": false,
"description": "column to pin in the table"
},
"tableId": {
"type": {
"name": "string"
},
"required": true,
"description": "The unique id of the table"
},
"wrapCellText": {
"type": {
"name": "custom",
"raw": "WrapCellTextPropTypes.isRequired"
},
"required": false,
"description": ""
},
"truncateCellText": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"actions": {
"type": {
"name": "shape",
"value": {
"onRowSelected": {
"name": "func",
"required": false
},
"onRowClicked": {
"name": "func",
"required": false
},
"onApplyRowActions": {
"name": "func",
"required": false
},
"onRowExpanded": {
"name": "func",
"required": false
},
"onRowLoadMore": {
"name": "func",
"required": false
},
"onDrag": {
"name": "func",
"required": false
},
"onDrop": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": "What column ordering is currently applied to the table"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
}
}
};
var iotPrefix$1Y = settings$1.iotPrefix;
/**
* This pagination component hides the items per page selection dropdown if the isItemsPerPageHidden bit is true.
* It also hides the Items per page and x of x items text if the total width of the pagination bar is less than 500 px.
* In addition, it narrows padding between 608px and 500px due to overflow issue.
*/
var SizedPagination = function SizedPagination(_ref) {
var _classnames;
var isItemPerPageHidden = _ref.isItemPerPageHidden,
className = _ref.className,
preventInteraction = _ref.preventInteraction,
disabled = _ref.disabled,
testId = _ref.testId,
size = _ref.size,
rest = objectWithoutProperties$1(_ref, ["isItemPerPageHidden", "className", "preventInteraction", "disabled", "testId", "size"]);
var _useSizeObserver = useSizeObserver({
initialWidth: 500
}),
_useSizeObserver2 = slicedToArray$2(_useSizeObserver, 2),
width = _useSizeObserver2[0].width,
paginationRef = _useSizeObserver2[1];
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Pagination, _extends_1$1({}, rest, {
forwardedRef: paginationRef,
size: size,
"data-testid": testId,
disabled: preventInteraction || disabled,
className: classnames$1(className, "".concat(iotPrefix$1Y, "--pagination"), (_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$1Y, "--pagination--hide-page"), isItemPerPageHidden), defineProperty$d(_classnames, "".concat(iotPrefix$1Y, "--pagination--hide-select"), preventInteraction), defineProperty$d(_classnames, "".concat(iotPrefix$1Y, "--pagination--narrow"), width > 500 && width < 608), defineProperty$d(_classnames, "".concat(iotPrefix$1Y, "--pagination--compact"), width < 500), _classnames)),
style: {
'--pagination-text-display': width < 500 ? 'none' : 'flex'
}
})));
};
SizedPagination.propTypes = {
isItemPerPageHidden: PropTypes__default['default'].bool,
// It is currently not possible to completely disable the carbon pagination
// therefor we use this prop to combine disable and hiding of controls.
preventInteraction: PropTypes__default['default'].bool,
disabled: PropTypes__default['default'].bool,
size: PropTypes__default['default'].oneOf(['sm', 'md', 'lg']),
testId: PropTypes__default['default'].string
};
SizedPagination.defaultProps = {
isItemPerPageHidden: false,
preventInteraction: false,
disabled: false,
testId: 'sized-pagination',
size: 'lg'
};
SizedPagination.__docgenInfo = {
"description": "This pagination component hides the items per page selection dropdown if the isItemsPerPageHidden bit is true.\nIt also hides the Items per page and x of x items text if the total width of the pagination bar is less than 500 px.\nIn addition, it narrows padding between 608px and 500px due to overflow issue.",
"methods": [],
"displayName": "SizedPagination",
"props": {
"isItemPerPageHidden": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"preventInteraction": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'sized-pagination'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"size": {
"defaultValue": {
"value": "'lg'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}]
},
"required": false,
"description": ""
}
}
};
var iotPrefix$1X = settings$1.iotPrefix;
var propTypes$24 = {
options: PropTypes__default['default'].shape({
hasRowExpansion: PropTypes__default['default'].bool,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
// TODO: don't duplicate this one
hasRowActions: PropTypes__default['default'].bool,
hasRowNesting: PropTypes__default['default'].bool
}),
tableState: PropTypes__default['default'].shape({
aggregations: PropTypes__default['default'].shape({
label: PropTypes__default['default'].string,
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** id of the column that should have its values aggregated */
id: PropTypes__default['default'].string.isRequired,
/** the value to be displayed */
value: PropTypes__default['default'].string,
/** allow aligning the results the same as the column */
align: PropTypes__default['default'].oneOf(['start', 'center', 'end']),
/** allows the aggregation to align with sortable columns extra padding */
isSortable: PropTypes__default['default'].bool
}))
}),
/** TODO: Move this prop out and reuse in TableHead */
/** What column ordering is currently applied to the table */
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
isHidden: PropTypes__default['default'].bool
})).isRequired
}).isRequired,
testId: PropTypes__default['default'].string,
showExpanderColumn: PropTypes__default['default'].bool
};
var defaultProps$2c = {
options: {},
testId: 'table-foot',
showExpanderColumn: false
};
var TableFoot = function TableFoot(_ref) {
var testId = _ref.testId,
_ref$options = _ref.options,
hasRowExpansion = _ref$options.hasRowExpansion,
hasRowSelection = _ref$options.hasRowSelection,
hasRowActions = _ref$options.hasRowActions,
hasRowNesting = _ref$options.hasRowNesting,
_ref$tableState = _ref.tableState,
aggregations = _ref$tableState.aggregations,
ordering = _ref$tableState.ordering,
showExpanderColumn = _ref.showExpanderColumn;
var visibleColumns = ordering.filter(function (col) {
return !col.isHidden;
});
var hasMultiSelect = hasRowSelection === 'multi';
var hasExpandOrNest = hasRowExpansion || hasRowNesting;
var labelColSpan = hasMultiSelect && hasExpandOrNest ? 3 : hasExpandOrNest || hasMultiSelect ? 2 : 1;
return /*#__PURE__*/React__default['default'].createElement("tfoot", {
className: "".concat(iotPrefix$1X, "-table-foot"),
"data-testid": testId
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
key: "aggregate-row"
}, visibleColumns.map(function (orderedCol, index) {
var _classnames;
var aggregated = aggregations.columns.find(function (col) {
return orderedCol.columnId === col.id;
});
var isLabelCell = !aggregated && index === 0;
var cellTestId = "".concat(testId, "-aggregation-").concat(orderedCol.columnId);
var cellKey = "".concat(orderedCol.columnId).concat(index);
return isLabelCell ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: "".concat(iotPrefix$1X, "-table-foot--label"),
"data-testid": cellTestId,
key: cellKey,
colSpan: labelColSpan
}, aggregations.label) : aggregated ? /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, {
key: "aggregated-cell-fragment-".concat(index)
}, index === 0 && (hasMultiSelect || hasExpandOrNest) ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
colSpan: hasMultiSelect && hasExpandOrNest ? 2 : 1
}) : null, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
className: classnames$1((_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$1X, "-table-foot--value"), true), defineProperty$d(_classnames, 'data-table-end', aggregated.align === 'end'), defineProperty$d(_classnames, 'data-table-start', !aggregated.align || aggregated.align === 'start'), defineProperty$d(_classnames, 'data-table-center', aggregated.align === 'center'), defineProperty$d(_classnames, "".concat(iotPrefix$1X, "-table-foot--value__sortable"), aggregated.isSortable), _classnames)),
align: aggregated.align ? aggregated.align : undefined,
"data-testid": cellTestId,
key: cellKey
}, aggregated.value)) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
"data-testid": cellTestId,
key: cellKey
}, "\xA0");
}), hasRowActions ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, null) : null, showExpanderColumn ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
"data-testid": "".concat(testId, "-expander-column")
}) : null));
};
TableFoot.propTypes = propTypes$24;
TableFoot.defaultProps = defaultProps$2c;
TableFoot.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableFoot",
"props": {
"options": {
"defaultValue": {
"value": "{}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"hasRowExpansion": {
"name": "bool",
"required": false
},
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
},
"hasRowNesting": {
"name": "bool",
"required": false
}
}
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'table-foot'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"showExpanderColumn": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"tableState": {
"type": {
"name": "shape",
"value": {
"aggregations": {
"name": "shape",
"value": {
"label": {
"name": "string",
"required": false
},
"columns": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"description": "id of the column that should have its values aggregated",
"required": true
},
"value": {
"name": "string",
"description": "the value to be displayed",
"required": false
},
"align": {
"name": "enum",
"value": [{
"value": "'start'",
"computed": false
}, {
"value": "'center'",
"computed": false
}, {
"value": "'end'",
"computed": false
}],
"description": "allow aligning the results the same as the column",
"required": false
},
"isSortable": {
"name": "bool",
"description": "allows the aggregation to align with sortable columns extra padding",
"required": false
}
}
},
"required": false
}
},
"required": false
},
"ordering": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
},
"description": "What column ordering is currently applied to the table",
"required": true
}
}
},
"required": true,
"description": ""
}
}
};
var immutabilityHelper = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
var hasOwnProperty = Object.prototype.hasOwnProperty;
var splice = Array.prototype.splice;
var toString = Object.prototype.toString;
function type(obj) {
return toString.call(obj).slice(8, -1);
}
var assign = Object.assign || /* istanbul ignore next */ (function (target, source) {
getAllKeys(source).forEach(function (key) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
});
return target;
});
var getAllKeys = typeof Object.getOwnPropertySymbols === 'function'
? function (obj) { return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj)); }
/* istanbul ignore next */
: function (obj) { return Object.keys(obj); };
function copy(object) {
return Array.isArray(object)
? assign(object.constructor(object.length), object)
: (type(object) === 'Map')
? new Map(object)
: (type(object) === 'Set')
? new Set(object)
: (object && typeof object === 'object')
? assign(Object.create(Object.getPrototypeOf(object)), object)
/* istanbul ignore next */
: object;
}
var Context = /** @class */ (function () {
function Context() {
this.commands = assign({}, defaultCommands);
this.update = this.update.bind(this);
// Deprecated: update.extend, update.isEquals and update.newContext
this.update.extend = this.extend = this.extend.bind(this);
this.update.isEquals = function (x, y) { return x === y; };
this.update.newContext = function () { return new Context().update; };
}
Object.defineProperty(Context.prototype, "isEquals", {
get: function () {
return this.update.isEquals;
},
set: function (value) {
this.update.isEquals = value;
},
enumerable: true,
configurable: true
});
Context.prototype.extend = function (directive, fn) {
this.commands[directive] = fn;
};
Context.prototype.update = function (object, $spec) {
var _this = this;
var spec = (typeof $spec === 'function') ? { $apply: $spec } : $spec;
if (!(Array.isArray(object) && Array.isArray(spec))) {
browser(!Array.isArray(spec), 'update(): You provided an invalid spec to update(). The spec may ' +
'not contain an array except as the value of $set, $push, $unshift, ' +
'$splice or any custom command allowing an array value.');
}
browser(typeof spec === 'object' && spec !== null, 'update(): You provided an invalid spec to update(). The spec and ' +
'every included key path must be plain objects containing one of the ' +
'following commands: %s.', Object.keys(this.commands).join(', '));
var nextObject = object;
getAllKeys(spec).forEach(function (key) {
if (hasOwnProperty.call(_this.commands, key)) {
var objectWasNextObject = object === nextObject;
nextObject = _this.commands[key](spec[key], nextObject, spec, object);
if (objectWasNextObject && _this.isEquals(nextObject, object)) {
nextObject = object;
}
}
else {
var nextValueForKey = type(object) === 'Map'
? _this.update(object.get(key), spec[key])
: _this.update(object[key], spec[key]);
var nextObjectValue = type(nextObject) === 'Map'
? nextObject.get(key)
: nextObject[key];
if (!_this.isEquals(nextValueForKey, nextObjectValue)
|| typeof nextValueForKey === 'undefined'
&& !hasOwnProperty.call(object, key)) {
if (nextObject === object) {
nextObject = copy(object);
}
if (type(nextObject) === 'Map') {
nextObject.set(key, nextValueForKey);
}
else {
nextObject[key] = nextValueForKey;
}
}
}
});
return nextObject;
};
return Context;
}());
exports.Context = Context;
var defaultCommands = {
$push: function (value, nextObject, spec) {
invariantPushAndUnshift(nextObject, spec, '$push');
return value.length ? nextObject.concat(value) : nextObject;
},
$unshift: function (value, nextObject, spec) {
invariantPushAndUnshift(nextObject, spec, '$unshift');
return value.length ? value.concat(nextObject) : nextObject;
},
$splice: function (value, nextObject, spec, originalObject) {
invariantSplices(nextObject, spec);
value.forEach(function (args) {
invariantSplice(args);
if (nextObject === originalObject && args.length) {
nextObject = copy(originalObject);
}
splice.apply(nextObject, args);
});
return nextObject;
},
$set: function (value, _nextObject, spec) {
invariantSet(spec);
return value;
},
$toggle: function (targets, nextObject) {
invariantSpecArray(targets, '$toggle');
var nextObjectCopy = targets.length ? copy(nextObject) : nextObject;
targets.forEach(function (target) {
nextObjectCopy[target] = !nextObject[target];
});
return nextObjectCopy;
},
$unset: function (value, nextObject, _spec, originalObject) {
invariantSpecArray(value, '$unset');
value.forEach(function (key) {
if (Object.hasOwnProperty.call(nextObject, key)) {
if (nextObject === originalObject) {
nextObject = copy(originalObject);
}
delete nextObject[key];
}
});
return nextObject;
},
$add: function (values, nextObject, _spec, originalObject) {
invariantMapOrSet(nextObject, '$add');
invariantSpecArray(values, '$add');
if (type(nextObject) === 'Map') {
values.forEach(function (_a) {
var key = _a[0], value = _a[1];
if (nextObject === originalObject && nextObject.get(key) !== value) {
nextObject = copy(originalObject);
}
nextObject.set(key, value);
});
}
else {
values.forEach(function (value) {
if (nextObject === originalObject && !nextObject.has(value)) {
nextObject = copy(originalObject);
}
nextObject.add(value);
});
}
return nextObject;
},
$remove: function (value, nextObject, _spec, originalObject) {
invariantMapOrSet(nextObject, '$remove');
invariantSpecArray(value, '$remove');
value.forEach(function (key) {
if (nextObject === originalObject && nextObject.has(key)) {
nextObject = copy(originalObject);
}
nextObject.delete(key);
});
return nextObject;
},
$merge: function (value, nextObject, _spec, originalObject) {
invariantMerge(nextObject, value);
getAllKeys(value).forEach(function (key) {
if (value[key] !== nextObject[key]) {
if (nextObject === originalObject) {
nextObject = copy(originalObject);
}
nextObject[key] = value[key];
}
});
return nextObject;
},
$apply: function (value, original) {
invariantApply(value);
return value(original);
},
};
var defaultContext = new Context();
exports.isEquals = defaultContext.update.isEquals;
exports.extend = defaultContext.extend;
exports.default = defaultContext.update;
// @ts-ignore
exports.default.default = module.exports = assign(exports.default, exports);
// invariants
function invariantPushAndUnshift(value, spec, command) {
browser(Array.isArray(value), 'update(): expected target of %s to be an array; got %s.', command, value);
invariantSpecArray(spec[command], command);
}
function invariantSpecArray(spec, command) {
browser(Array.isArray(spec), 'update(): expected spec of %s to be an array; got %s. ' +
'Did you forget to wrap your parameter in an array?', command, spec);
}
function invariantSplices(value, spec) {
browser(Array.isArray(value), 'Expected $splice target to be an array; got %s', value);
invariantSplice(spec.$splice);
}
function invariantSplice(value) {
browser(Array.isArray(value), 'update(): expected spec of $splice to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?', value);
}
function invariantApply(fn) {
browser(typeof fn === 'function', 'update(): expected spec of $apply to be a function; got %s.', fn);
}
function invariantSet(spec) {
browser(Object.keys(spec).length === 1, 'Cannot have more than one key in an object with $set');
}
function invariantMerge(target, specValue) {
browser(specValue && typeof specValue === 'object', 'update(): $merge expects a spec of type \'object\'; got %s', specValue);
browser(target && typeof target === 'object', 'update(): $merge expects a target of type \'object\'; got %s', target);
}
function invariantMapOrSet(target, command) {
var typeOfTarget = type(target);
browser(typeOfTarget === 'Map' || typeOfTarget === 'Set', 'update(): %s expects a target of type Set or Map; got %s', command, typeOfTarget);
}
});
var update = /*@__PURE__*/getDefaultExportFromCjs(immutabilityHelper);
var iotPrefix$1W = settings$1.iotPrefix;
var propTypes$23 = {
columnId: PropTypes__default['default'].string.isRequired,
defaultColumnId: PropTypes__default['default'].string.isRequired,
defaultDirectionId: PropTypes__default['default'].string.isRequired,
i18n: PropTypes__default['default'].shape({
multiSortSelectColumnSortByTitle: PropTypes__default['default'].stirng,
multiSortSelectColumnThenByTitle: PropTypes__default['default'].string,
multiSortDragHandle: PropTypes__default['default'].string,
multiSortSelectColumnLabel: PropTypes__default['default'].string,
multiSortDirectionLabel: PropTypes__default['default'].string,
multiSortDirectionTitle: PropTypes__default['default'].string,
multiSortAddColumn: PropTypes__default['default'].string,
multiSortRemoveColumn: PropTypes__default['default'].string
}).isRequired,
index: PropTypes__default['default'].number.isRequired,
multiSortColumns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string,
name: PropTypes__default['default'].string,
disabled: PropTypes__default['default'].bool
})).isRequired,
numSelectedColumns: PropTypes__default['default'].number.isRequired,
onAddMultiSortColumn: PropTypes__default['default'].func.isRequired,
onMoveRow: PropTypes__default['default'].func.isRequired,
onRemoveMultiSortColumn: PropTypes__default['default'].func.isRequired,
onSelectMultiSortColumn: PropTypes__default['default'].func.isRequired,
onSelectMultiSortColumnDirection: PropTypes__default['default'].func.isRequired,
sortDirections: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string,
label: PropTypes__default['default'].string
})).isRequired,
testId: PropTypes__default['default'].string.isRequired
};
var TableMultiSortRow = function TableMultiSortRow(_ref) {
var columnId = _ref.columnId,
defaultColumnId = _ref.defaultColumnId,
defaultDirectionId = _ref.defaultDirectionId,
i18n = _ref.i18n,
index = _ref.index,
multiSortColumns = _ref.multiSortColumns,
numSelectedColumns = _ref.numSelectedColumns,
onAddMultiSortColumn = _ref.onAddMultiSortColumn,
onMoveRow = _ref.onMoveRow,
onRemoveMultiSortColumn = _ref.onRemoveMultiSortColumn,
onSelectMultiSortColumn = _ref.onSelectMultiSortColumn,
onSelectMultiSortColumnDirection = _ref.onSelectMultiSortColumnDirection,
sortDirections = _ref.sortDirections,
testId = _ref.testId;
var dragRef = React$1.useRef(null);
var previewRef = React$1.useRef(null);
var _useDrop = useDrop({
accept: 'TableMultiSortRow',
collect: function collect(monitor) {
return {
handlerId: monitor.getHandlerId()
};
},
hover: function hover(item, monitor) {
var _previewRef$current;
if (!previewRef.current) {
return;
}
var dragIndex = item.index;
var hoverIndex = index; // Don't replace items with themselves
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
} // Determine rectangle on screen
// Determine rectangle on screen
var hoverBoundingRect = (_previewRef$current = previewRef.current) === null || _previewRef$current === void 0 ? void 0 : _previewRef$current.getBoundingClientRect(); // Get vertical middle
// Get vertical middle
var hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position
// Determine mouse position
var clientOffset = monitor.getClientOffset(); // Get pixels to the top
// Get pixels to the top
var hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
} // Dragging upwards
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
} // Time to actually perform the action
// Time to actually perform the action
onMoveRow(dragIndex, hoverIndex); // Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
item.index = hoverIndex; // eslint-disable-line no-param-reassign
}
}),
_useDrop2 = slicedToArray$2(_useDrop, 2),
handlerId = _useDrop2[0].handlerId,
drop = _useDrop2[1];
var _useDrag = useDrag({
type: 'TableMultiSortRow',
item: function item() {
return {
columnId: columnId,
index: index
};
},
collect: function collect(monitor) {
return {
isDragging: monitor.isDragging()
};
}
}),
_useDrag2 = slicedToArray$2(_useDrag, 3),
isDragging = _useDrag2[0].isDragging,
drag = _useDrag2[1],
preview = _useDrag2[2];
drag(dragRef);
drop(preview(previewRef));
return /*#__PURE__*/React__default['default'].createElement("div", {
ref: previewRef,
className: classnames$1("".concat(iotPrefix$1W, "--table-multi-sort-row"), defineProperty$d({}, "".concat(iotPrefix$1W, "--table-multi-sort-row--dragging"), isDragging)),
"data-handler-id": handlerId,
style: {
opacity: isDragging ? 0 : 1
}
}, /*#__PURE__*/React__default['default'].createElement("div", {
ref: dragRef,
className: "".concat(iotPrefix$1W, "--table-multi-sort-row__handle"),
title: i18n.multiSortDragHandle,
"data-testid": "drag-handle-".concat(columnId)
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Draggable16, null)), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Select, {
"data-testid": "".concat(testId, "-column-select"),
id: "".concat(columnId, "-select-sort-column"),
helperText: i18n.multiSortSelectColumnLabel,
onChange: onSelectMultiSortColumn,
labelText: index === 0 ? i18n.multiSortSelectColumnSortByTitle : i18n.multiSortSelectColumnThenByTitle,
defaultValue: defaultColumnId
}, multiSortColumns.map(function (col) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SelectItem, {
key: "".concat(col.id, "-").concat(col.name),
text: col.name,
value: col.id,
disabled: col.disabled
});
})), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Select, {
"data-testid": "".concat(testId, "-direction-select"),
id: "".concat(columnId, "-select-sort-direction"),
helperText: i18n.multiSortDirectionLabel,
labelText: i18n.multiSortDirectionTitle,
defaultValue: defaultDirectionId,
onChange: onSelectMultiSortColumnDirection
}, sortDirections.map(function (dir) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SelectItem, {
key: "".concat(dir.id, "-").concat(dir.label),
text: dir.label,
value: dir.id
});
})), /*#__PURE__*/React__default['default'].createElement(Button$1, {
hasIconOnly: true,
renderIcon: iconsReact.Add16,
kind: "ghost",
tooltipPosition: "top",
iconDescription: i18n.multiSortAddColumn,
onClick: onAddMultiSortColumn,
testId: "".concat(columnId, "-add-sort-button"),
disabled: numSelectedColumns >= multiSortColumns.length
}), /*#__PURE__*/React__default['default'].createElement(Button$1, {
hasIconOnly: true,
renderIcon: iconsReact.Subtract16,
kind: "ghost",
tooltipPosition: "top",
iconDescription: i18n.multiSortRemoveColumn,
onClick: onRemoveMultiSortColumn,
testId: "".concat(columnId, "-remove-sort-button"),
disabled: numSelectedColumns === 1
}));
};
TableMultiSortRow.propTypes = propTypes$23;
TableMultiSortRow.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableMultiSortRow",
"props": {
"columnId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"defaultColumnId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"defaultDirectionId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"i18n": {
"type": {
"name": "shape",
"value": {
"multiSortSelectColumnSortByTitle": {
"name": "custom",
"raw": "PropTypes.stirng",
"required": false
},
"multiSortSelectColumnThenByTitle": {
"name": "string",
"required": false
},
"multiSortDragHandle": {
"name": "string",
"required": false
},
"multiSortSelectColumnLabel": {
"name": "string",
"required": false
},
"multiSortDirectionLabel": {
"name": "string",
"required": false
},
"multiSortDirectionTitle": {
"name": "string",
"required": false
},
"multiSortAddColumn": {
"name": "string",
"required": false
},
"multiSortRemoveColumn": {
"name": "string",
"required": false
}
}
},
"required": true,
"description": ""
},
"index": {
"type": {
"name": "number"
},
"required": true,
"description": ""
},
"multiSortColumns": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": false
},
"name": {
"name": "string",
"required": false
},
"disabled": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"numSelectedColumns": {
"type": {
"name": "number"
},
"required": true,
"description": ""
},
"onAddMultiSortColumn": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onMoveRow": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onRemoveMultiSortColumn": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onSelectMultiSortColumn": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onSelectMultiSortColumnDirection": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"sortDirections": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": false
},
"label": {
"name": "string",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"testId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
}
}
};
function ownKeys$1Z(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$1Z(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1Z(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1Z(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1V = settings$1.iotPrefix;
var propTypes$22 = {
columns: TableColumnsPropTypes.isRequired,
ordering: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string.isRequired,
/* Visibility of column in table, defaults to false */
isHidden: PropTypes__default['default'].bool
})).isRequired,
actions: PropTypes__default['default'].shape({
onAddMultiSortColumn: PropTypes__default['default'].func,
onRemoveMultiSortColumn: PropTypes__default['default'].func,
onSaveMultiSortColumns: PropTypes__default['default'].func,
onCancelMultiSortColumns: PropTypes__default['default'].func,
onClearMultiSortColumns: PropTypes__default['default'].func
}).isRequired,
sort: PropTypes__default['default'].oneOfType([TableSortPropType, PropTypes__default['default'].arrayOf(TableSortPropType)]).isRequired,
showMultiSortModal: PropTypes__default['default'].bool,
i18n: PropTypes__default['default'].shape({
multiSortModalTitle: PropTypes__default['default'].string,
multiSortModalPrimaryLabel: PropTypes__default['default'].string,
multiSortModalSecondaryLabel: PropTypes__default['default'].string,
multiSortModalClearLabel: PropTypes__default['default'].string,
multiSortSelectColumnLabel: PropTypes__default['default'].string,
multiSortSelectColumnSortByTitle: PropTypes__default['default'].string,
multiSortSelectColumnThenByTitle: PropTypes__default['default'].string,
multiSortDirectionLabel: PropTypes__default['default'].string,
multiSortDirectionTitle: PropTypes__default['default'].string,
multiSortAddColumn: PropTypes__default['default'].string,
multiSortRemoveColumn: PropTypes__default['default'].string,
multiSortAscending: PropTypes__default['default'].string,
multiSortDescending: PropTypes__default['default'].string,
multiSortCloseModal: PropTypes__default['default'].string,
multiSortOpenMenu: PropTypes__default['default'].string,
multiSortCloseMenu: PropTypes__default['default'].string,
multiSortDragHandle: PropTypes__default['default'].string
}),
testId: PropTypes__default['default'].string
};
var defaultProps$2b = {
showMultiSortModal: false,
i18n: {
multiSortModalTitle: 'Select columns to sort',
multiSortModalPrimaryLabel: 'Sort',
multiSortModalSecondaryLabel: 'Cancel',
multiSortModalClearLabel: 'Clear sorting',
multiSortSelectColumnLabel: 'Select a column',
multiSortSelectColumnSortByTitle: 'Sort by',
multiSortSelectColumnThenByTitle: 'Then by',
multiSortDirectionLabel: 'Select a direction',
multiSortDirectionTitle: 'Sort order',
multiSortAddColumn: 'Add column',
multiSortRemoveColumn: 'Remove column',
multiSortAscending: 'Ascending',
multiSortDescending: 'Descending',
multiSortCloseModal: 'Close',
multiSortDragHandle: 'Drag handle'
},
testId: 'multi-sort-modal'
};
/**
* Simple helper function to turn the sort object into an array and filter empty values from it
* @param {Array|Object} sort A sort object or an array of sort objects
* @returns Array
*/
var cleanSortArray = function cleanSortArray(sort) {
var sortArray = Array.isArray(sort) ? sort : sort !== undefined ? [sort] : [];
return sortArray.filter(function (_ref) {
var columnId = _ref.columnId;
return columnId;
});
};
var TableMultiSortModal = function TableMultiSortModal(_ref2) {
var columns = _ref2.columns,
ordering = _ref2.ordering,
sort = _ref2.sort,
actions = _ref2.actions,
showMultiSortModal = _ref2.showMultiSortModal,
i18n = _ref2.i18n,
testId = _ref2.testId;
var onAddMultiSortColumn = actions.onAddMultiSortColumn,
onRemoveMultiSortColumn = actions.onRemoveMultiSortColumn,
onSaveMultiSortColumns = actions.onSaveMultiSortColumns,
onCancelMultiSortColumns = actions.onCancelMultiSortColumns,
onClearMultiSortColumns = actions.onClearMultiSortColumns;
var sortHelper = React$1.useCallback(function () {
var sortArray = cleanSortArray(sort);
if (!sortArray.length) {
return [{
columnId: '',
direction: 'ASC'
}];
}
return sortArray;
}, [sort]);
var _useState = React$1.useState(sortHelper),
_useState2 = slicedToArray$2(_useState, 2),
selectedMultiSortColumns = _useState2[0],
setSelectedMultiSortColumns = _useState2[1];
React$1.useEffect(function () {
setSelectedMultiSortColumns(sortHelper);
}, [sort, sortHelper]);
var sortDirections = React$1.useMemo(function () {
return [{
id: 'ASC',
label: i18n.multiSortAscending
}, {
id: 'DESC',
label: i18n.multiSortDescending
}];
}, [i18n.multiSortAscending, i18n.multiSortDescending]);
var handleSelectMultiSortColumn = function handleSelectMultiSortColumn(index) {
return function (event) {
var columnId = event.target.value;
setSelectedMultiSortColumns(function (prev) {
var currentItem = prev[index];
return Object.assign([], prev, defineProperty$d({}, index, _objectSpread$1Z(_objectSpread$1Z({}, currentItem), {}, {
columnId: columnId
})));
});
};
};
var handleSelectMultiSortColumnDirection = function handleSelectMultiSortColumnDirection(index) {
return function (event) {
var direction = event.target.value;
setSelectedMultiSortColumns(function (prev) {
var currentItem = prev[index];
return Object.assign([], prev, defineProperty$d({}, index, _objectSpread$1Z(_objectSpread$1Z({}, currentItem), {}, {
direction: direction
})));
});
};
};
var multiSortColumns = React$1.useMemo(function () {
return columns.filter(function (_ref3) {
var id = _ref3.id,
isSortable = _ref3.isSortable;
var orderCol = ordering.find(function (_ref4) {
var columnId = _ref4.columnId;
return columnId === id;
});
return isSortable && !orderCol.isHidden;
}).map(function (col) {
var columnAlreadySorted = selectedMultiSortColumns.find(function (_ref5) {
var columnId = _ref5.columnId;
return columnId === col.id;
}) !== undefined;
return {
id: col.id,
name: col.name,
disabled: columnAlreadySorted
};
});
}, [columns, ordering, selectedMultiSortColumns]);
var getInitialSelectedColumn = function getInitialSelectedColumn(columnId) {
var selectedColumn = columns.find(function (col) {
return col.id === columnId;
});
return selectedColumn || multiSortColumns.filter(function (col) {
return !col.disabled;
})[0];
};
var getInitialSelectedDirection = function getInitialSelectedDirection(direction) {
var selectedDirection = sortDirections.find(function (dir) {
return dir.id === direction;
});
return selectedDirection || sortDirections[0];
};
var handleAddMultiSortColumn = function handleAddMultiSortColumn(index) {
return function () {
setSelectedMultiSortColumns(function (prev) {
var _multiSortColumns$fil2;
var clone = toConsumableArray(prev);
var nextColumnIndex = 0; // If the default column is in the first position, set it before adding the next column
if (clone.length === 1 && Object.keys(clone[0]).length === 0) {
var _multiSortColumns$fil;
clone.splice(index, 1, {
columnId: (_multiSortColumns$fil = multiSortColumns.filter(function (col) {
return !col.disabled;
})[nextColumnIndex]) === null || _multiSortColumns$fil === void 0 ? void 0 : _multiSortColumns$fil.id,
direction: 'ASC'
});
nextColumnIndex = 1;
}
clone.splice(index + 1, 0, {
columnId: (_multiSortColumns$fil2 = multiSortColumns.filter(function (col) {
return !col.disabled;
})[nextColumnIndex]) === null || _multiSortColumns$fil2 === void 0 ? void 0 : _multiSortColumns$fil2.id,
direction: 'ASC'
});
return clone;
});
onAddMultiSortColumn(index);
};
};
var handleRemoveMultiSortColumn = function handleRemoveMultiSortColumn(index) {
return function () {
setSelectedMultiSortColumns(function (prev) {
return prev.filter(function (c, i) {
return i !== index;
});
});
onRemoveMultiSortColumn(index);
};
};
var handleSaveMultiSortColumns = function handleSaveMultiSortColumns() {
// if empty strings were passed for columnId or direction
// the dropdown will show the first available column and direction,
// but if they save without performing a change, the initial state
// is empty, so we perform a check to ensure the defaults are saved
var defaulted = selectedMultiSortColumns.map(function (_ref6) {
var columnId = _ref6.columnId,
direction = _ref6.direction;
var column = getInitialSelectedColumn(columnId);
var dir = getInitialSelectedDirection(direction);
return {
columnId: columnId || column.id,
direction: direction || dir.id
};
});
if (!isEqual$1(selectedMultiSortColumns, defaulted)) {
setSelectedMultiSortColumns(defaulted);
}
onSaveMultiSortColumns(defaulted);
};
var handleCancelMultiSortColumns = function handleCancelMultiSortColumns() {
setSelectedMultiSortColumns(cleanSortArray(sort));
onCancelMultiSortColumns();
};
var handleClearMultiSortColumns = function handleClearMultiSortColumns() {
setSelectedMultiSortColumns([]);
onClearMultiSortColumns();
};
var onMoveRow = React$1.useCallback(function (dragIndex, hoverIndex) {
setSelectedMultiSortColumns(function (prev) {
var row = prev[dragIndex];
return update(prev, {
$splice: [[dragIndex, 1], [hoverIndex, 0, row]]
});
});
}, []);
return /*#__PURE__*/React__default['default'].createElement(ComposedModal, {
testId: testId,
className: "".concat(iotPrefix$1V, "--table-multi-sort-modal"),
header: {
title: i18n.multiSortModalTitle
},
iconDescription: i18n.multiSortCloseModal,
onClose: handleCancelMultiSortColumns,
footer: /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1V, "--table-multi-sort-modal__footer")
}, /*#__PURE__*/React__default['default'].createElement(Button$1, {
kind: "ghost",
onClick: handleClearMultiSortColumns,
testId: "".concat(testId, "-modal-clear-button")
}, i18n.multiSortModalClearLabel), /*#__PURE__*/React__default['default'].createElement("div", null), /*#__PURE__*/React__default['default'].createElement(Button$1, {
kind: "secondary",
onClick: handleCancelMultiSortColumns,
testId: "".concat(testId, "-modal-secondary-button")
}, i18n.multiSortModalSecondaryLabel), /*#__PURE__*/React__default['default'].createElement(Button$1, {
kind: "primary",
onClick: handleSaveMultiSortColumns,
testId: "".concat(testId, "-modal-primary-button"),
"data-modal-primary-focus": true
}, i18n.multiSortModalPrimaryLabel)),
open: showMultiSortModal
}, /*#__PURE__*/React__default['default'].createElement(DragAndDrop, null, selectedMultiSortColumns.map(function (_ref7, index) {
var columnId = _ref7.columnId,
direction = _ref7.direction;
var defaultColumn = getInitialSelectedColumn(columnId);
var defaultDirection = getInitialSelectedDirection(direction);
return /*#__PURE__*/React__default['default'].createElement(TableMultiSortRow, {
key: "".concat(columnId, "-").concat(direction),
columnId: columnId || (defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id),
defaultColumnId: defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id,
defaultDirectionId: defaultDirection === null || defaultDirection === void 0 ? void 0 : defaultDirection.id,
i18n: i18n,
index: index,
multiSortColumns: multiSortColumns,
numSelectedColumns: selectedMultiSortColumns === null || selectedMultiSortColumns === void 0 ? void 0 : selectedMultiSortColumns.length,
onAddMultiSortColumn: handleAddMultiSortColumn(index),
onMoveRow: onMoveRow,
onRemoveMultiSortColumn: handleRemoveMultiSortColumn(index),
onSelectMultiSortColumn: handleSelectMultiSortColumn(index),
onSelectMultiSortColumnDirection: handleSelectMultiSortColumnDirection(index),
sortDirections: sortDirections,
testId: testId
});
})));
};
TableMultiSortModal.propTypes = propTypes$22;
TableMultiSortModal.defaultProps = defaultProps$2b;
TableMultiSortModal.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableMultiSortModal",
"props": {
"showMultiSortModal": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n multiSortModalTitle: 'Select columns to sort',\n multiSortModalPrimaryLabel: 'Sort',\n multiSortModalSecondaryLabel: 'Cancel',\n multiSortModalClearLabel: 'Clear sorting',\n multiSortSelectColumnLabel: 'Select a column',\n multiSortSelectColumnSortByTitle: 'Sort by',\n multiSortSelectColumnThenByTitle: 'Then by',\n multiSortDirectionLabel: 'Select a direction',\n multiSortDirectionTitle: 'Sort order',\n multiSortAddColumn: 'Add column',\n multiSortRemoveColumn: 'Remove column',\n multiSortAscending: 'Ascending',\n multiSortDescending: 'Descending',\n multiSortCloseModal: 'Close',\n multiSortDragHandle: 'Drag handle',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"multiSortModalTitle": {
"name": "string",
"required": false
},
"multiSortModalPrimaryLabel": {
"name": "string",
"required": false
},
"multiSortModalSecondaryLabel": {
"name": "string",
"required": false
},
"multiSortModalClearLabel": {
"name": "string",
"required": false
},
"multiSortSelectColumnLabel": {
"name": "string",
"required": false
},
"multiSortSelectColumnSortByTitle": {
"name": "string",
"required": false
},
"multiSortSelectColumnThenByTitle": {
"name": "string",
"required": false
},
"multiSortDirectionLabel": {
"name": "string",
"required": false
},
"multiSortDirectionTitle": {
"name": "string",
"required": false
},
"multiSortAddColumn": {
"name": "string",
"required": false
},
"multiSortRemoveColumn": {
"name": "string",
"required": false
},
"multiSortAscending": {
"name": "string",
"required": false
},
"multiSortDescending": {
"name": "string",
"required": false
},
"multiSortCloseModal": {
"name": "string",
"required": false
},
"multiSortOpenMenu": {
"name": "string",
"required": false
},
"multiSortCloseMenu": {
"name": "string",
"required": false
},
"multiSortDragHandle": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'multi-sort-modal'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"columns": {
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes.isRequired"
},
"required": false,
"description": ""
},
"ordering": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": true
},
"isHidden": {
"name": "bool",
"required": false
}
}
}
},
"required": true,
"description": ""
},
"actions": {
"type": {
"name": "shape",
"value": {
"onAddMultiSortColumn": {
"name": "func",
"required": false
},
"onRemoveMultiSortColumn": {
"name": "func",
"required": false
},
"onSaveMultiSortColumns": {
"name": "func",
"required": false
},
"onCancelMultiSortColumns": {
"name": "func",
"required": false
},
"onClearMultiSortColumns": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": ""
},
"sort": {
"type": {
"name": "union",
"value": [{
"name": "custom",
"raw": "TableSortPropType"
}, {
"name": "arrayOf",
"value": {
"name": "custom",
"raw": "TableSortPropType"
}
}]
},
"required": true,
"description": ""
}
}
};
/**
* The expander column will grow when the fixed layout table grows in order to keep
* defined column widths. For resizable tables that don't have any initial
* column widths we have to keep the expander column out of the first
* render cycle, where column widths are measured, so that it won't be
* assigned a width (and occupy space).
* @param {*} hasResize true f the table has resizable columns
* @param {*} useAutoTableLayoutForResize true for table-layout should be 'auto' instead of 'fixed'
* @param {array} ordering the table ordering prop that specifies the order and visibility of columns
* @param {array} columns The table column props*
* @returns
*/
var useShowExpanderColumn = function useShowExpanderColumn(_ref) {
var hasResize = _ref.hasResize,
useAutoTableLayoutForResize = _ref.useAutoTableLayoutForResize,
ordering = _ref.ordering,
columns = _ref.columns;
var _useState = React$1.useState(false),
_useState2 = slicedToArray$2(_useState, 2),
showDelayedExpander = _useState2[0],
setShowDelayedExpander = _useState2[1]; // extra deps will be automatically added by `eslint --fix` and it breaks the tests
// eslint-disable-next-line react-hooks/exhaustive-deps
React$1.useEffect(function () {
if (hasResize && !useAutoTableLayoutForResize) {
setShowDelayedExpander(true);
}
});
var showExpanderImmediately = hasResize && !useAutoTableLayoutForResize && visibleColumnsHaveWidth(ordering, columns);
return showExpanderImmediately || showDelayedExpander;
};
var iotPrefix$1U = settings$1.iotPrefix;
var propTypes$21 = {
/** The unique id of the table */
id: PropTypes__default['default'].string,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
testId: PropTypes__default['default'].string,
/** set of internationalized labels */
i18n: PropTypes__default['default'].objectOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func, PropTypes__default['default'].element])).isRequired,
totalColumns: PropTypes__default['default'].number.isRequired,
/** Empty error state to render */
errorState: PropTypes__default['default'].element,
error: PropTypes__default['default'].string,
onErrorStateAction: PropTypes__default['default'].func
};
var defaultProps$2a = {
id: 'ErrorTable',
testId: 'ErrorTable',
error: null,
errorState: null,
onErrorStateAction: null
};
var ErrorTable = function ErrorTable(_ref) {
var id = _ref.id,
testID = _ref.testID,
testId = _ref.testId,
i18n = _ref.i18n,
totalColumns = _ref.totalColumns,
error = _ref.error,
errorState = _ref.errorState,
onErrorStateAction = _ref.onErrorStateAction;
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableBody, {
id: id,
"data-testid": testID || testId
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableRow, {
className: "".concat(iotPrefix$1U, "--empty-table--table-row")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableCell, {
colSpan: totalColumns
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "empty-table-cell--default"
}, /*#__PURE__*/React__default['default'].isValidElement(errorState) ? errorState : /*#__PURE__*/React__default['default'].createElement(EmptyState, {
icon: "error",
title: i18n.tableErrorStateTitle,
body: error || '',
action: onErrorStateAction ? {
label: i18n.buttonLabelOnTableError,
onClick: onErrorStateAction,
kind: 'secondary'
} : null
})))));
};
ErrorTable.propTypes = propTypes$21;
ErrorTable.defaultProps = defaultProps$2a;
ErrorTable.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ErrorTable",
"props": {
"id": {
"defaultValue": {
"value": "'ErrorTable'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The unique id of the table"
},
"testId": {
"defaultValue": {
"value": "'ErrorTable'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"error": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"errorState": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": "Empty error state to render"
},
"onErrorStateAction": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
},
"i18n": {
"type": {
"name": "objectOf",
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}, {
"name": "element"
}]
}
},
"required": true,
"description": "set of internationalized labels"
},
"totalColumns": {
"type": {
"name": "number"
},
"required": true,
"description": ""
}
}
};
function ownKeys$1Y(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$1Y(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1Y(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1Y(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1T = settings$1.iotPrefix;
var propTypes$20 = {
/** DOM ID for component */
id: PropTypes__default['default'].string,
/** Displays smaller title in header */
secondaryTitle: PropTypes__default['default'].string,
tooltip: PropTypes__default['default'].node,
/** render zebra stripes or not */
useZebraStyles: PropTypes__default['default'].bool,
/** lighter styling where regular table too visually heavy. Deprecated. */
lightweight: deprecate$2(PropTypes__default['default'].bool, "The 'lightweight' prop has been deprecated and will be removed in the next major version."),
/** Specify the properties of each column in the table */
columns: TableColumnsPropTypes.isRequired,
/** Specify the properties of each column group in the table. Defaults to empty array. */
columnGroups: TableColumnGroupPropType,
/** Row value data for the body of the table */
data: TableRowsPropTypes.isRequired,
/** Expanded data for the table details */
expandedData: ExpandedRowsPropTypes,
/**
* Optional base z-index for the table. Used with drag and drop to ensure the drag image is "over"
* other elements on the page. This is generally only needed if the table is in a modal dialog
* with z-index of its own. In that case, set this z-index to be higher than the modal to be sure
* any drags are seen above the modal.
*/
zIndex: PropTypes__default['default'].number,
/** Experimental: Turns on the carbon sticky-header feature. */
stickyHeader: deprecate('stickyHeader'),
/** Optional properties to customize how the table should be rendered */
options: PropTypes__default['default'].shape({
/** If true allows the table to aggregate values of columns in a special row */
hasAggregations: PropTypes__default['default'].bool,
/** If true, search is applied as typed. If false, only after 'Enter' is pressed */
hasFastSearch: PropTypes__default['default'].bool,
hasPagination: PropTypes__default['default'].bool,
hasRowSelection: PropTypes__default['default'].oneOf(['multi', 'single', false]),
/** @TODO: Remove in major release and just show action bar when no actions are defined */
/* option to hide batch action toolbar */
hasBatchActionToolbar: PropTypes__default['default'].bool,
/** True if the rows should be expandable */
hasRowExpansion: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** True if any previously expanded rows should be collapsed when a new row is expanded */
expandRowsExclusively: PropTypes__default['default'].bool
})]),
hasRowNesting: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].shape({
/** If the hierarchy only has 1 nested level of children */
hasSingleNestedHierarchy: PropTypes__default['default'].bool
})]),
hasMultiSort: PropTypes__default['default'].bool,
hasRowActions: PropTypes__default['default'].bool,
hasFilter: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].oneOf(['onKeyPress', 'onEnterAndBlur'])]),
/* Turns on the Advanced Rule Builder Filtering. Is a boolean value */
// eslint-disable-next-line consistent-return
hasAdvancedFilter: function hasAdvancedFilter(props, propName, componentName) {
{
if (props !== null && props !== void 0 && props.hasFilter && props !== null && props !== void 0 && props.hasAdvancedFilter) {
return new Error("Only one of props 'options.hasFilter' or 'options.hasAdvancedFilter' can be specified in '".concat(componentName, "'."));
}
if (![true, false, undefined].includes(props === null || props === void 0 ? void 0 : props.hasAdvancedFilter)) {
return new Error("'options.hasAdvancedFilter' should be a boolean or undefined.");
}
}
},
/** if true, the data prop will be assumed to only represent the currently visible page */
hasOnlyPageData: PropTypes__default['default'].bool,
/** has simple search capability */
hasSearch: PropTypes__default['default'].bool,
hasColumnSelection: PropTypes__default['default'].bool,
hasColumnSelectionConfig: PropTypes__default['default'].bool,
shouldLazyRender: PropTypes__default['default'].bool,
hasRowCountInHeader: PropTypes__default['default'].bool,
/** If true enables the row edit toolbar button and functionality */
hasRowEdit: PropTypes__default['default'].bool,
hasResize: PropTypes__default['default'].bool,
hasSingleRowEdit: PropTypes__default['default'].bool,
hasUserViewManagement: PropTypes__default['default'].bool,
/** Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized. */
preserveColumnWidths: PropTypes__default['default'].bool,
/* If true, fire the onRowExpanded callback with the rowId when a row is clicked */
shouldExpandOnRowClick: PropTypes__default['default'].bool,
/** If true removes the "table-layout: fixed" for resizable tables */
useAutoTableLayoutForResize: PropTypes__default['default'].bool,
/**
* auto - Wrap for tables with dynamic columns widths and truncate for tables with fixed or resizable columns
* always - Wrap if needed for all table column configurations
* never - Tables with dynamic columns widths grow larger and tables with fixed or resizable columns truncate.
* alwaysTruncate - Always truncate if needed for all table column configurations
* expand - Expand to fit text width (by horizontal scrollbar) for table with fixed columns
*/
wrapCellText: WrapCellTextPropTypes,
/** use white-space: pre; css when true */
preserveCellWhiteSpace: PropTypes__default['default'].bool,
/** display icon button in filter row */
hasFilterRowIcon: PropTypes__default['default'].bool,
/** column to pin in the table */
pinColumn: PinColumnPropTypes,
/**
* If rows can be dragged and dropped on top of each other. When this is true there will always
* be space reserved for a drag handle at the start of the row. Each rows data must indicate if
* that row can be dragged by setting `isDraggable: true` on their row data. The table also needs
* `actions.table.onDrag` and `actions.table.onDrop` callback props.
*/
hasDragAndDrop: PropTypes__default['default'].bool,
/** Freezes table header and footer */
pinHeaderAndFooter: PropTypes__default['default'].bool
}),
/** Size prop from Carbon to shrink row height (and header height in some instances) */
size: function checkProps(props, propName, componentName) {
if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {
warning_1(false, "The value `".concat(props[propName], "` has been deprecated for the ") + "`".concat(propName, "` prop on the ").concat(componentName, " component. It will be removed in the next major ") + "release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.") ;
}
},
/** Initial state of the table, should be updated via a local state wrapper component implementation or via a central store/redux see StatefulTable component for an example */
view: PropTypes__default['default'].shape({
aggregations: PropTypes__default['default'].shape({
label: PropTypes__default['default'].string,
columns: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** id of the column that should have its values aggregated */
id: PropTypes__default['default'].string.isRequired,
/** the primitive value or function that will receive an array of values and returns an aggregated value */
value: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].string]),
/** allow aligning the results the same as the column */
align: PropTypes__default['default'].oneOf(['start', 'center', 'end']),
/** allows the aggregation to align with sortable columns extra padding */
isSortable: PropTypes__default['default'].bool
})),
/** hide the aggregation row without removing the aggregations object */
isHidden: PropTypes__default['default'].bool
}),
pagination: PropTypes__default['default'].shape({
pageSize: PropTypes__default['default'].number,
pageSizes: PropTypes__default['default'].arrayOf(PropTypes__default['default'].number),
page: PropTypes__default['default'].number,
totalItems: PropTypes__default['default'].number,
/** Number of pages rendered in pagination */
maxPages: function maxPages(props, propName, componentName) {
{
if (typeof props[propName] !== 'number') {
return new Error("Invalid type of `".concat(propName, "` supplied to `").concat(componentName, "`. `").concat(propName, "` must be a positive integer."));
}
if (props[propName] < 0 || !Number.isInteger(props[propName])) {
var roundedStr = "".concat(props[propName], " will be rounded to ").concat(Math.ceil(props[propName]));
return new Error("Invalid prop `".concat(propName, "` supplied to `").concat(componentName, "`. `").concat(propName, "` must be a positive integer. ").concat(roundedStr, "."));
}
}
return '';
},
isItemPerPageHidden: PropTypes__default['default'].bool,
/**
* Specify the size of the Pagination buttons. Currently supports either `sm`, 'md' (default) or 'lg` as an option.
*/
size: PropTypes__default['default'].oneOf(['sm', 'md', 'lg'])
}),
filters: TableFiltersPropType,
/** a stripped down version of the RuleBuilderFilterPropType */
advancedFilters: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** Unique id for particular filter */
filterId: PropTypes__default['default'].string.isRequired,
/** Text for main title of page */
filterTitleText: PropTypes__default['default'].string.isRequired,
filterRules: RuleGroupPropType.isRequired
})),
selectedAdvancedFilterIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
toolbar: PropTypes__default['default'].shape({
/** Specify which header row to display, will display default header row if null */
activeBar: ActiveTableToolbarPropType,
/** optional content to render inside the toolbar */
customToolbarContent: PropTypes__default['default'].node,
/** Specify which batch actions to render in the batch action bar. If empty, no batch action toolbar will display */
batchActions: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string.isRequired,
labelText: PropTypes__default['default'].string.isRequired,
icon: PropTypes__default['default'].element,
iconDescription: PropTypes__default['default'].string
})),
/** Simple search state */
search: TableSearchPropTypes,
/** is the toolbar currently disabled */
isDisabled: PropTypes__default['default'].bool,
/** buttons to be shown with when activeBar is 'rowEdit' */
rowEditBarButtons: PropTypes__default['default'].node,
/** extra actions that can appear in an overflow menu in the toolbar (same menu as toggle aggregations) */
toolbarActions: TableToolbarActionsPropType,
/** force hide Clear all filters button in toolbar */
hideClearAllFiltersButton: PropTypes__default['default'].bool
}),
table: PropTypes__default['default'].shape({
isSelectAllSelected: PropTypes__default['default'].bool,
isSelectAllIndeterminate: PropTypes__default['default'].bool,
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
sort: PropTypes__default['default'].oneOfType([TableSortPropType, PropTypes__default['default'].arrayOf(TableSortPropType)]),
/** Specify the order, visibility and group belonging of the table columns */
ordering: TableOrderingPropType,
/** what is the current state of the row actions */
rowActions: RowActionsStatePropTypes,
singleRowEditButtons: PropTypes__default['default'].element,
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
emptyState: EmptyStatePropTypes,
/** use custom error state or use error message directly */
errorState: PropTypes__default['default'].element,
loadingState: PropTypes__default['default'].shape({
isLoading: PropTypes__default['default'].bool,
rowCount: PropTypes__default['default'].number,
columnCount: PropTypes__default['default'].number
}),
/* show the modal for selecting multi-sort columns */
showMultiSortModal: PropTypes__default['default'].bool,
multiSortModal: PropTypes__default['default'].shape({
/**
* The anticipatedColumn is used to add the most recently click columnId to the UI of the
* MultiSort modal. This gives the user a better experience by preemptively adding the column
* they clicked multi-sort on to the multisort modal without changing state. They still have to
* click "Sort" to save it, or can click 'Cancel' or the 'X' to clear it.
*/
anticipatedColumn: PropTypes__default['default'].shape({
columnId: PropTypes__default['default'].string,
direction: PropTypes__default['default'].oneOf(['ASC', 'DESC'])
})
}),
/** Array with rowIds that are with loading active */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** icon element for filter row icon */
filterRowIcon: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].object])
})
}),
/** Callbacks for actions of the table, can be used to update state in wrapper component to update `view` props */
actions: PropTypes__default['default'].shape({
pagination: PropTypes__default['default'].shape({
/** Specify a callback for when the current page or page size is changed.
* This callback is passed an object parameter containing the current page and the current page size */
onChangePage: PropTypes__default['default'].func
}),
toolbar: PropTypes__default['default'].shape({
onApplyFilter: PropTypes__default['default'].func,
onToggleFilter: PropTypes__default['default'].func,
onShowRowEdit: PropTypes__default['default'].func,
onToggleColumnSelection: PropTypes__default['default'].func,
/** Specify a callback for when the user clicks toolbar button to clear all filters.
* Receives a parameter of the current filter values for each column */
onClearAllFilters: PropTypes__default['default'].func,
/** Callback for when the automatcally generated Cancel action in the batch actions bar is clicked */
onCancelBatchAction: PropTypes__default['default'].func,
/** Callback for all the batch actions except the cancel. Is called with the id of the clicked action.
* For the StatefulTable the current selections are received as second parameter */
onApplyBatchAction: PropTypes__default['default'].func,
/** Apply a search criteria to the table */
onApplySearch: PropTypes__default['default'].func,
/** Download the table contents */
onDownloadCSV: PropTypes__default['default'].func,
/** When advanced filters are applied */
onApplyAdvancedFilter: PropTypes__default['default'].func,
/** Toggles the advanced filter flyout open */
onToggleAdvancedFilter: PropTypes__default['default'].func,
/** Remove the selected advancedFilter from the table */
onRemoveAdvancedFilter: PropTypes__default['default'].func,
/** Fired the 'create new advanced filter' button is clicked. */
onCreateAdvancedFilter: PropTypes__default['default'].func,
/** Fired when then 'Cancel' button is clicked in the advanced filter flyout menu */
onCancelAdvancedFilter: PropTypes__default['default'].func,
/** Fired when an advanced filter is selected or removed. */
onChangeAdvancedFilter: PropTypes__default['default'].func,
/** fired when 'Toggle aggregations' is clicked in the overflow menu */
onToggleAggregations: PropTypes__default['default'].func,
/** fired when clicking a 'toolbarAction' in the table toolbar */
onApplyToolbarAction: PropTypes__default['default'].func,
/** fired when focus/blur on search bar in the table toolbar */
onSearchExpand: PropTypes__default['default'].func
}),
/** table wide actions */
table: PropTypes__default['default'].shape({
onRowSelected: PropTypes__default['default'].func,
onRowClicked: PropTypes__default['default'].func,
onRowExpanded: PropTypes__default['default'].func,
onSelectAll: PropTypes__default['default'].func,
onChangeSort: PropTypes__default['default'].func,
/** callback if a row action is clicked called with the id of the action then the id of the row if you
* return a promise from apply row action the stateful table will assume you're asynchronous and give a spinner */
onApplyRowAction: PropTypes__default['default'].func,
onClearRowError: PropTypes__default['default'].func,
onEmptyStateAction: PropTypes__default['default'].func,
onChangeOrdering: PropTypes__default['default'].func,
onColumnSelectionConfig: PropTypes__default['default'].func,
onColumnResize: PropTypes__default['default'].func,
onOverflowItemClicked: PropTypes__default['default'].func,
/* (multiSortedColumns) => {} */
onSaveMultiSortColumns: PropTypes__default['default'].func,
/* () => {} */
onCancelMultiSortColumns: PropTypes__default['default'].func,
/* () => {} */
onClearMultiSortColumns: PropTypes__default['default'].func,
/* (index) => {} */
onAddMultiSortColumn: PropTypes__default['default'].func,
/* (index) => {} */
onRemoveMultiSortColumn: PropTypes__default['default'].func,
onTableErrorStateAction: PropTypes__default['default'].func,
/** call back function for when load more row is clicked (rowId) => {} */
onRowLoadMore: PropTypes__default['default'].func,
/** call back function for when icon button in filter row is clicked (evt) => {} */
onFilterRowIconClick: PropTypes__default['default'].func,
/**
* Required callback to support drag and drop. This gets the rows values being dragged. It
* must return an object of the row IDs that can be dropped on, and a node use as the preview
* of what's being dragged (typically the name of the row, possibly with an icon).
*
* @type {(rows: object[]) => {dropIds: string[], preview: React.Node}}
*/
onDrag: PropTypes__default['default'].func,
/**
* Required callback to support drag and drop. This is called after a successful drop and is
* passed the ID of the row that was dragged and the ID of the row that was dropped on. It's
* up to the caller to decide what to do with that--the table does not update itself.
*
* @type {(dragRowIds: string[], dropRowId) => void}
*/
onDrop: PropTypes__default['default'].func
}).isRequired,
/** callback for actions relevant for view management */
onUserViewModified: PropTypes__default['default'].func
}),
/** what locale should we use to format table values if left empty no locale formatting happens */
locale: PropTypes__default['default'].string,
i18n: I18NPropTypes,
/** Specify the error message that need to be displayed by default.
* Incase we use view.table.errorState property then the error state will be displayed instead of error message */
error: PropTypes__default['default'].string,
testId: PropTypes__default['default'].string
};
var defaultProps$29 = function defaultProps(baseProps) {
return {
columnGroups: [],
id: null,
useZebraStyles: false,
lightweight: undefined,
title: null,
tooltip: null,
secondaryTitle: null,
zIndex: 0,
options: {
hasAggregations: false,
hasPagination: false,
hasRowSelection: false,
hasRowExpansion: false,
hasBatchActionToolbar: true,
hasRowActions: false,
hasRowNesting: false,
hasRowEdit: false,
hasFilter: false,
hasAdvancedFilter: false,
hasOnlyPageData: false,
hasFastSearch: true,
hasSearch: false,
hasColumnSelection: false,
hasColumnSelectionConfig: false,
hasResize: false,
hasSingleRowEdit: false,
hasUserViewManagement: false,
preserveColumnWidths: false,
useAutoTableLayoutForResize: false,
shouldLazyRender: false,
shouldExpandOnRowClick: false,
wrapCellText: 'always',
preserveCellWhiteSpace: false,
hasFilterRowIcon: false,
pinColumn: PIN_COLUMN.NONE,
hasDragAndDrop: false,
pinHeaderAndFooter: false
},
size: undefined,
view: {
aggregations: {
columns: []
},
pagination: {
pageSize: 10,
pageSizes: [10, 20, 30],
page: 1,
totalItems: baseProps.data && baseProps.data.length,
maxPages: 100,
isItemPerPageHidden: false,
size: 'lg'
},
filters: [],
advancedFilters: [],
selectedAdvancedFilterIds: [],
toolbar: {
advancedFilterFlyoutOpen: false,
batchActions: [],
search: {},
hideClearAllFiltersButton: false
},
table: {
expandedIds: [],
isSelectAllSelected: undefined,
selectedIds: [],
rowActions: [],
sort: {},
ordering: baseProps.columns && baseProps.columns.map(function (i) {
return {
columnId: i.id
};
}),
loadingState: {
rowCount: 5,
columnCount: 5
},
singleRowEditButtons: null,
loadingMoreIds: [],
showMultiSortModal: false,
multiSortModal: undefined,
filterRowIcon: iconsReact.FilterEdit16
}
},
actions: {
pagination: {
onChangePage: defaultFunction('actions.pagination.onChangePage')
},
toolbar: {
onToggleFilter: defaultFunction('actions.toolbar.onToggleFilter'),
onShowRowEdit: defaultFunction('actions.toolbar.onShowRowEdit'),
onToggleColumnSelection: defaultFunction('actions.toolbar.onToggleColumnSelection'),
onApplyBatchAction: defaultFunction('actions.toolbar.onApplyBatchAction'),
onCancelBatchAction: defaultFunction('actions.toolbar.onCancelBatchAction'),
onApplyToolbarAction: defaultFunction('actions.toolbar.onApplyToolbarAction'),
onRemoveAdvancedFilter: defaultFunction('actions.toolbar.onRemoveAdvancedFilter'),
onCancelAdvancedFilter: defaultFunction('actions.toolbar.onCancelFilter'),
onCreateAdvancedFilter: defaultFunction('actions.toolbar.onCreateAdvancedFilter'),
onApplyAdvancedFilter: defaultFunction('actions.toolbar.onApplyAdvancedFilter'),
onChangeAdvancedFilter: defaultFunction('actions.toolbar.onChangeAdvancedFilter'),
onToggleAdvancedFilter: defaultFunction('actions.toolbar.onToggleAdvancedFilter') // TODO: removed to mimic the current state of consumers in the wild
// since they won't be adding this prop to any of their components
// can be readded in V3.
// onToggleAggregations: defaultFunction('actions.toolbar.onToggleAggregations'),
},
table: {
onChangeSort: defaultFunction('actions.table.onChangeSort'),
onRowExpanded: defaultFunction('actions.table.onRowExpanded'),
onRowClicked: defaultFunction('actions.table.onRowClicked'),
onApplyRowAction: defaultFunction('actions.table.onApplyRowAction'),
onEmptyStateAction: null,
onErrorStateAction: null,
onChangeOrdering: defaultFunction('actions.table.onChangeOrdering'),
onColumnSelectionConfig: defaultFunction('actions.table.onColumnSelectionConfig'),
onColumnResize: defaultFunction('actions.table.onColumnResize'),
onOverflowItemClicked: defaultFunction('actions.table.onOverflowItemClicked'),
onSaveMultiSortColumns: defaultFunction('actions.table.onSaveMultiSortColumns'),
onCancelMultiSortColumns: defaultFunction('actions.table.onCancelMultiSortColumns'),
onAddMultiSortColumn: defaultFunction('actions.table.onAddMultiSortColumn'),
onRemoveMultiSortColumn: defaultFunction('actions.table.onRemoveMultiSortColumn'),
onFilterRowIconClick: defaultFunction('actions.table.onFilterRowIconClick')
},
onUserViewModified: null
},
locale: null,
i18n: {
/** pagination */
pageBackwardAria: 'Previous page',
pageForwardAria: 'Next page',
pageNumberAria: 'Page Number',
itemsPerPage: 'Items per page:',
itemsRangeWithTotal: function itemsRangeWithTotal(min, max, total) {
return "".concat(min, "\u2013").concat(max, " of ").concat(total, " items");
},
pageRange: function pageRange(current, total) {
return "".concat(current, " of ").concat(total, " pages");
},
/** table body */
overflowMenuAria: 'More actions',
clickToExpandAria: 'Click to expand content',
clickToCollapseAria: 'Click to collapse content',
selectAllAria: 'Select all items',
selectRowAria: 'Select row',
/** toolbar */
clearAllFilters: 'Clear all filters',
columnSelectionButtonAria: 'Column Selection',
columnSelectionConfig: 'Manage Columns',
filterButtonAria: 'Filters',
editButtonAria: 'Edit rows',
searchLabel: 'Search',
searchPlaceholder: 'Search',
clearFilterAria: 'Clear filter',
filterAria: 'Filter',
openMenuAria: 'Open menu',
closeMenuAria: 'Close menu',
clearSelectionAria: 'Clear selection',
batchCancel: 'Clear selections',
itemsSelected: function itemsSelected(selectedCount) {
return "".concat(selectedCount, " items selected");
},
itemSelected: function itemSelected(selectedCount) {
return "".concat(selectedCount, " item selected");
},
rowCountInHeader: function rowCountInHeader(totalRowCount) {
return "Results: ".concat(totalRowCount);
},
toggleAggregations: 'Toggle aggregations',
toolbarLabelAria: undefined,
/** empty state */
emptyMessage: 'There is no data',
emptyMessageBody: '',
emptyMessageWithFilters: 'No results match the current filters',
emptyMessageWithFiltersBody: 'Try another search or use column filter criteria',
emptyButtonLabel: 'Create some data',
downloadIconDescription: 'Download table content',
filterNone: 'Unsort rows by this header',
filterAscending: 'Sort rows by this header in ascending order',
filterDescending: 'Sort rows by this header in descending order',
multiSortModalTitle: 'Select columns to sort',
multiSortModalPrimaryLabel: 'Sort',
multiSortModalSecondaryLabel: 'Cancel',
multiSortModalClearLabel: 'Clear sorting',
multiSortSelectColumnLabel: 'Select a column',
multiSortSelectColumnSortByTitle: 'Sort by',
multiSortSelectColumnThenByTitle: 'Then by',
multiSortDirectionLabel: 'Select a direction',
multiSortDirectionTitle: 'Sort order',
multiSortAddColumn: 'Add column',
multiSortRemoveColumn: 'Remove column',
multiSortAscending: 'Ascending',
multiSortDescending: 'Descending',
multiSortOverflowItem: 'Multi-sort',
multiSortDragHandle: 'Drag handle',
// table error state
tableErrorStateTitle: 'Unable to load the page',
buttonLabelOnTableError: 'Refresh the page',
/* table load more */
loadMoreText: 'Load more...',
learnMoreText: 'Learn more',
inProgressText: 'In progress',
dismissText: 'Dismiss',
actionFailedText: 'Action failed',
toolbarTooltipLabel: 'Toolbar tooltip',
filterRowIconDescription: 'Edit filters',
batchActionsOverflowMenuText: '',
filterTagsOverflowMenuText: '+{n}',
toolbarSearchIconDescription: 'Search'
},
error: null,
// TODO: set default in v3. Leaving null for backwards compat. to match 'id' which was
// previously used as testId.
testId: null
};
};
var Table = function Table(props) {
var _view$toolbar, _view$toolbar$search, _view$toolbar$search$, _view$toolbar2, _view$toolbar2$search, _view$toolbar$search$2, _view$toolbar3, _view$toolbar3$search, _classnames3;
var _merge2 = merge$1({}, defaultProps$29(props), props),
id = _merge2.id,
columns = _merge2.columns,
columnGroups = _merge2.columnGroups,
data = _merge2.data,
expandedData = _merge2.expandedData,
locale = _merge2.locale,
view = _merge2.view,
onUserViewModified = _merge2.actions.onUserViewModified,
actions = _merge2.actions,
options = _merge2.options,
lightweight = _merge2.lightweight,
className = _merge2.className,
style = _merge2.style,
i18n = _merge2.i18n,
secondaryTitle = _merge2.secondaryTitle,
tooltip = _merge2.tooltip,
error = _merge2.error,
testId = _merge2.testId,
size = _merge2.size,
zIndex = _merge2.zIndex,
others = objectWithoutProperties$1(_merge2, ["id", "columns", "columnGroups", "data", "expandedData", "locale", "view", "actions", "actions", "options", "lightweight", "className", "style", "i18n", "secondaryTitle", "tooltip", "error", "testId", "size", "zIndex"]); // There is no way to access the current search value in the Table
// so we need to track that for the save view functionality.
var searchValue = React$1.useRef(view === null || view === void 0 ? void 0 : (_view$toolbar = view.toolbar) === null || _view$toolbar === void 0 ? void 0 : (_view$toolbar$search = _view$toolbar.search) === null || _view$toolbar$search === void 0 ? void 0 : _view$toolbar$search.defaultValue);
var initialRendering = React$1.useRef(true); // The save/load view functionality needs access to the latest view configuration
// and also needs to know when the configuration has changed for the StatefulTable.
// This effect satisfies both those needs.
useDeepCompareEffect(function () {
if (options.hasUserViewManagement && onUserViewModified) {
if (!initialRendering.current) {
onUserViewModified({
view: view,
columns: columns,
state: {
currentSearchValue: searchValue.current === undefined ? '' : searchValue.current
}
});
} else {
initialRendering.current = false;
}
}
}, [// Props of type React.Element or React.Node must not be included in
// useDeepCompareEffect dependency arrays, their object signature is
// massive and will throw out of memory errors if compared.
// https://github.com/kentcdodds/use-deep-compare-effect/issues/7
// https://twitter.com/dan_abramov/status/1104415855612432384
view.pagination, view.filters, view.toolbar.activeBar, // Remove the icon as it's a React.Element which can not be compared
view.toolbar.batchActions.map(function (action) {
action.icon;
var nonElements = objectWithoutProperties$1(action, ["icon"]);
return nonElements;
}), view.toolbar.initialDefaultSearch, view.toolbar.search, view.toolbar.isDisabled, view.table.isSelectAllSelected, view.table.isSelectAllIndeterminate, view.table.selectedIds, view.table.loadingMoreIds, view.table.sort, view.table.ordering, // Remove the error as it's a React.Element/Node which can not be compared
view.table.rowActions.map(function (action) {
action.error;
var nonElements = objectWithoutProperties$1(action, ["error"]);
return nonElements;
}), view.table.expandedIds, view.table.loadingState, view.table.filteredData, columns, searchValue === null || searchValue === void 0 ? void 0 : searchValue.current]);
var _view$pagination = view.pagination,
maxPages = _view$pagination.maxPages,
paginationProps = objectWithoutProperties$1(_view$pagination, ["maxPages"]);
var langDir = useLangDirection_2();
var hasMultiSelect = options.hasRowSelection === 'multi';
var _useState = React$1.useState(function () {
return uniqueId('table-');
}),
_useState2 = slicedToArray$2(_useState, 1),
tableId = _useState2[0];
var _useState3 = React$1.useState(0),
_useState4 = slicedToArray$2(_useState3, 2),
forceUpdateCellTextWidth = _useState4[1];
var useCellTextTruncate = React$1.useMemo(function () {
return options ? options.wrapCellText === 'alwaysTruncate' || options.wrapCellText !== 'always' && options.wrapCellText !== 'expand' && (options.hasResize && !options.useAutoTableLayoutForResize || columns.some(function (col) {
return col.hasOwnProperty('width');
})) : undefined;
}, [options, columns]);
var handleClearFilters = function handleClearFilters() {
if (actions.toolbar && actions.toolbar.onClearAllFilters) {
actions.toolbar.onClearAllFilters();
}
if (actions.toolbar && actions.toolbar.onApplySearch) {
actions.toolbar.onApplySearch('');
}
if (searchValue.current) {
searchValue.current = '';
}
};
var handleOnColumnResize = function handleOnColumnResize(resizedCols) {
if (actions.table && actions.table.onColumnResize) {
actions.table.onColumnResize(resizedCols);
}
forceUpdateCellTextWidth(function (n) {
return !n;
});
};
var minItemInView = options.hasPagination && !options.hasOnlyPageData && view.pagination ? (view.pagination.page - 1) * view.pagination.pageSize : 0;
var maxItemInView = options.hasPagination && !options.hasOnlyPageData && view.pagination ? view.pagination.page * view.pagination.pageSize : data.length;
var visibleData = data.slice(minItemInView, maxItemInView);
var visibleColumns = columns.filter(function (c) {
return !(view.table.ordering.find(function (o) {
return o.columnId === c.id;
}) || {
isHidden: false
}).isHidden;
});
var aggregationsProp = view.aggregations;
var getColumnNumbers = function getColumnNumbers(tableData, columnId) {
return tableData.map(function (row) {
return row.values[columnId];
}).filter(function (value) {
return Number.isFinite(value);
});
};
/**
* All of this was written incorrectly the first time, and needs to be removed in v3. However,
* to maintain backwards compatibility for a minor release the state management is left in
* the Table here, and a useEffect is added. If the onToggleAggregations callback is not supplied
* by the consumer we manage the aggregations state here in the table, but if it is provided,
* we push the management of the aggregations.isHidden prop to the consumer to manage. Once
* we move to v3. The useState, useCallback, and useEffects can all be removed and just call
* the onToggleAggregations from the actions.toolbar prop.
*/
var _useState5 = React$1.useState(!options.hasAggregations),
_useState6 = slicedToArray$2(_useState5, 2),
hideAggregations = _useState6[0],
setHideAggregations = _useState6[1];
var statefulOnToggleAggregations = React$1.useCallback(function () {
return setHideAggregations(function (prev) {
return !prev;
});
}, [setHideAggregations]);
React$1.useEffect(function () {
if (!actions.toolbar.onToggleAggregations) {
setHideAggregations(!options.hasAggregations);
}
}, [actions.toolbar.onToggleAggregations, options.hasAggregations]);
var onToggleAggregations = actions.toolbar.onToggleAggregations ? actions.toolbar.onToggleAggregations : statefulOnToggleAggregations;
var aggregationsAreHidden = (aggregationsProp === null || aggregationsProp === void 0 ? void 0 : aggregationsProp.isHidden) !== undefined ? aggregationsProp.isHidden : hideAggregations;
var aggregations = React$1.useMemo(function () {
return options.hasAggregations && aggregationsProp.columns ? {
label: aggregationsProp.label,
columns: aggregationsProp.columns.map(function (col) {
var aggregatedValue;
var isFunction = typeof col.value === 'function';
var calculateValue = isFunction || col.value === undefined;
if (calculateValue) {
var numbers = getColumnNumbers(data, col.id);
aggregatedValue = isFunction ? col.value(numbers) : numbers.reduce(function (total, num) {
return total + num;
}, 0);
}
return calculateValue ? _objectSpread$1Y(_objectSpread$1Y({}, col), {}, {
value: aggregatedValue.toString()
}) : col;
}),
isHidden: aggregationsAreHidden
} : undefined;
}, [options.hasAggregations, aggregationsProp.columns, aggregationsProp.label, aggregationsAreHidden, data]);
var showExpanderColumn = useShowExpanderColumn({
hasResize: options.hasResize,
useAutoTableLayoutForResize: options.useAutoTableLayoutForResize,
ordering: view.table.ordering,
columns: columns
}); // Checks if any selected rows are not draggable. If not, disables drag and drop, which hides all
// the drag handles. This is so we don't try to drag a selection that include an undraggable row.
var hideDragHandles = React$1.useMemo(function () {
if (!options.hasDragAndDrop) return true;
if (view.table.selectedIds.length === 0) return false;
var selectedSet = new Set(view.table.selectedIds);
var areAnySelectedUndraggable = data.some(function (row) {
return selectedSet.has(row.id) && !row.isDraggable;
});
return areAnySelectedUndraggable;
}, [options.hasDragAndDrop, view.table.selectedIds, data]);
var totalColumns = visibleColumns.length + (hasMultiSelect ? 1 : 0) + (options.hasRowExpansion || options.hasRowNesting ? 1 : 0) + (options.hasRowActions ? 1 : 0) + (showExpanderColumn ? 1 : 0) + (options.hasDragAndDrop ? 1 : 0);
var isFiltered = view.filters.length > 0 || view.selectedAdvancedFilterIds.length || ((_view$toolbar$search$ = view === null || view === void 0 ? void 0 : (_view$toolbar2 = view.toolbar) === null || _view$toolbar2 === void 0 ? void 0 : (_view$toolbar2$search = _view$toolbar2.search) === null || _view$toolbar2$search === void 0 ? void 0 : _view$toolbar2$search.value) !== null && _view$toolbar$search$ !== void 0 ? _view$toolbar$search$ : '') !== '' || ((_view$toolbar$search$2 = view === null || view === void 0 ? void 0 : (_view$toolbar3 = view.toolbar) === null || _view$toolbar3 === void 0 ? void 0 : (_view$toolbar3$search = _view$toolbar3.search) === null || _view$toolbar3$search === void 0 ? void 0 : _view$toolbar3$search.defaultValue) !== null && _view$toolbar$search$2 !== void 0 ? _view$toolbar$search$2 : '') !== '';
var rowEditMode = view.toolbar.activeBar === 'rowEdit';
var singleRowEditMode = !!view.table.rowActions.find(function (action) {
return action.isEditMode;
});
var allRowsAreSelected = view.table.selectedIds.length === visibleData.length;
var someRowsAreSelected = view.table.selectedIds.length > 0 && !allRowsAreSelected;
var noSelectAllProp = view.table.isSelectAllSelected === undefined;
var isSelectAllSelected = noSelectAllProp ? allRowsAreSelected : view.table.isSelectAllSelected;
var noIndeterminateProp = view.table.isSelectAllIndeterminate === undefined;
var isSelectAllIndeterminate = noIndeterminateProp && noSelectAllProp ? someRowsAreSelected : view.table.isSelectAllIndeterminate;
var minHeaderSizeIsLarge = visibleColumns.some(function (col) {
return col.isSortable;
});
if (columnGroups.length && options.hasColumnSelection) {
warning_1(false, 'Column grouping (columnGroups) cannot be combined with the option hasColumnSelection:true') ;
}
var multiSortColumns = React$1.useMemo(function () {
var _view$table$multiSort;
var arrayifiedSort = Array.isArray(view.table.sort) ? view.table.sort : view.table.sort !== undefined ? [view.table.sort] : [];
var anticipatedColumn = (_view$table$multiSort = view.table.multiSortModal) === null || _view$table$multiSort === void 0 ? void 0 : _view$table$multiSort.anticipatedColumn;
if (anticipatedColumn) {
var columnNotSortedYet = arrayifiedSort.every(function (sort) {
return sort.columnId !== anticipatedColumn.columnId;
});
if (columnNotSortedYet) {
return [].concat(toConsumableArray(arrayifiedSort), [anticipatedColumn]);
}
}
return arrayifiedSort;
}, [view.table.multiSortModal, view.table.sort]);
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.TableContainer, {
style: style,
"data-testid": "".concat(id || testId, "-table-container"),
className: classnames$1(className, "".concat(iotPrefix$1T, "--table-container"), defineProperty$d({}, "".concat(iotPrefix$1T, "--table-container--pin-header-and-footer"), options.pinHeaderAndFooter))
},
/* If there is no items being rendered in the toolbar, don't render the toolbar */
options.hasAggregations || options.hasFilter || options.hasAdvancedFilter || options.hasSearch || hasMultiSelect && view.table.selectedIds.length > 0 || options.hasRowCountInHeader || options.hasColumnSelection || options.hasRowEdit || actions.toolbar.onDownloadCSV || secondaryTitle || view.toolbar.customToolbarContent || tooltip ? /*#__PURE__*/React__default['default'].createElement(TableToolbar, {
tableId: id || tableId,
secondaryTitle: secondaryTitle,
tooltip: tooltip,
i18n: {
clearAllFilters: i18n.clearAllFilters,
columnSelectionButtonAria: i18n.columnSelectionButtonAria,
filterButtonAria: i18n.filterButtonAria,
editButtonAria: i18n.editButtonAria,
searchLabel: i18n.searchLabel,
searchPlaceholder: i18n.searchPlaceholder,
batchCancel: i18n.batchCancel,
itemsSelected: i18n.itemsSelected,
itemSelected: i18n.itemSelected,
filterNone: i18n.filterNone,
filterAscending: i18n.filterAscending,
filterDescending: i18n.filterDescending,
downloadIconDescription: i18n.downloadIconDescription,
rowCountInHeader: i18n.rowCountInHeader,
toggleAggregations: i18n.toggleAggregations,
toolbarLabelAria: i18n.toolbarLabelAria,
toolbarTooltipLabel: i18n.toolbarTooltipLabel,
batchActionsOverflowMenuText: i18n.batchActionsOverflowMenuText,
toolbarSearchIconDescription: i18n.toolbarSearchIconDescription
},
actions: _objectSpread$1Y(_objectSpread$1Y({}, pick(actions.toolbar, 'onCancelBatchAction', 'onApplyBatchAction', 'onClearAllFilters', 'onToggleColumnSelection', 'onToggleFilter', 'onShowRowEdit', 'onDownloadCSV', 'onApplyFilter', 'onApplyAdvancedFilter', 'onCancelAdvancedFilter', 'onCreateAdvancedFilter', 'onChangeAdvancedFilter', 'onRemoveAdvancedFilter', 'onToggleAdvancedFilter', 'onApplyToolbarAction', 'onSearchExpand')), {}, {
onToggleAggregations: onToggleAggregations,
onApplySearch: function onApplySearch(value) {
var _actions$toolbar;
searchValue.current = value;
if ((_actions$toolbar = actions.toolbar) !== null && _actions$toolbar !== void 0 && _actions$toolbar.onApplySearch) {
actions.toolbar.onApplySearch(value);
}
}
}),
options: _objectSpread$1Y(_objectSpread$1Y({}, pick(options, 'hasAggregations', 'hasColumnSelection', 'hasFastSearch', 'hasSearch', 'hasRowSelection', 'hasRowCountInHeader', 'hasRowEdit', 'hasUserViewManagement', 'hasBatchActionToolbar')), {}, {
hasFilter: Boolean(options === null || options === void 0 ? void 0 : options.hasFilter),
hasAdvancedFilter: Boolean(options === null || options === void 0 ? void 0 : options.hasAdvancedFilter)
}),
tableState: _objectSpread$1Y(_objectSpread$1Y(_objectSpread$1Y({
totalSelected: view.table.selectedIds.length,
totalFilters: (view.filters ? view.filters.length : 0) + (view.selectedAdvancedFilterIds.length ? view.selectedAdvancedFilterIds.length : 0),
totalItemsCount: view.pagination.totalItems,
isDisabled: singleRowEditMode || view.toolbar.isDisabled,
ordering: view.table.ordering,
columns: columns
}, pick(view, 'filters', 'advancedFilters', 'selectedAdvancedFilterIds')), pick(view.toolbar, 'batchActions', 'search', 'activeBar', 'customToolbarContent', 'rowEditBarButtons', 'advancedFilterFlyoutOpen', 'toolbarActions')), {}, {
hideClearAllFiltersButton: view.toolbar.hideClearAllFiltersButton
}),
data: data // TODO: remove id in V3.
,
testId: "".concat(id || testId, "-table-toolbar")
}) : null, view.selectedAdvancedFilterIds.length ? /*#__PURE__*/React__default['default'].createElement("section", {
className: "".concat(iotPrefix$1T, "--table__advanced-filters-container")
}, /*#__PURE__*/React__default['default'].createElement(FilterTags // TODO: remove id in V3.
, {
testId: "".concat(id || testId, "-filter-tags"),
i18n: {
filterTagsOverflowMenuText: i18n.filterTagsOverflowMenuText
}
}, view.advancedFilters.filter(function (advFilter) {
return view.selectedAdvancedFilterIds.includes(advFilter.filterId);
}).map(function (advancedFilter) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tag, {
key: advancedFilter.filterId,
filter: true,
title: i18n.clearFilterAria,
onClose: function onClose(e) {
var _actions$toolbar2;
if (typeof (actions === null || actions === void 0 ? void 0 : (_actions$toolbar2 = actions.toolbar) === null || _actions$toolbar2 === void 0 ? void 0 : _actions$toolbar2.onRemoveAdvancedFilter) === 'function') {
actions.toolbar.onRemoveAdvancedFilter(e, advancedFilter.filterId);
}
} // TODO: remove id in V3.
,
"data-testid": "".concat(id || testId, "-filter-tag-").concat(advancedFilter.filterId),
type: "blue"
}, advancedFilter.filterTitleText);
}))) : null, /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1('addons-iot-table-container', defineProperty$d({}, "".concat(iotPrefix$1T, "-table-container--dropdown-height-fix"), options.hasFilter))
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Table, _extends_1$1({
id: id // TODO: remove id in v3
,
"data-testid": id || testId,
className: classnames$1((_classnames3 = {}, defineProperty$d(_classnames3, "".concat(iotPrefix$1T, "--data-table--column-groups"), columnGroups.length), defineProperty$d(_classnames3, "".concat(iotPrefix$1T, "--data-table--column-groups--min-size-large"), columnGroups.length && minHeaderSizeIsLarge), defineProperty$d(_classnames3, "".concat(iotPrefix$1T, "--data-table--resize"), options.hasResize), defineProperty$d(_classnames3, "".concat(iotPrefix$1T, "--data-table--fixed"), options.hasResize && !options.useAutoTableLayoutForResize), defineProperty$d(_classnames3, "".concat(iotPrefix$1T, "--data-table--row-actions"), options.hasRowActions), _classnames3)),
size: size
}, others), columns.length ? /*#__PURE__*/React__default['default'].createElement(TableHead, _extends_1$1({
size: size
}, others, {
i18n: i18n,
lightweight: lightweight,
options: _objectSpread$1Y(_objectSpread$1Y({}, pick(options, 'hasAggregations', 'hasColumnSelectionConfig', 'hasResize', 'hasRowActions', 'hasRowNesting', 'hasSingleRowEdit', 'hasRowSelection', 'useRadioButtonSingleSelect', 'useAutoTableLayoutForResize', 'hasMultiSort', 'preserveColumnWidths', 'hasFilterRowIcon', 'pinColumn', 'hasDragAndDrop', 'pinHeaderAndFooter')), {}, {
hasRowExpansion: !!options.hasRowExpansion,
wrapCellText: options.wrapCellText,
truncateCellText: useCellTextTruncate
}),
columns: columns,
columnGroups: columnGroups,
filters: view.filters,
actions: _objectSpread$1Y(_objectSpread$1Y(_objectSpread$1Y({}, pick(actions.toolbar, 'onApplyFilter')), pick(actions.table, 'onSelectAll', 'onChangeSort', 'onChangeOrdering', 'onColumnSelectionConfig', 'onOverflowItemClicked', 'onFilterRowIconClick')), {}, {
onColumnResize: handleOnColumnResize
}),
selectAllText: i18n.selectAllAria,
clearFilterText: i18n.clearFilterAria,
filterText: i18n.filterAria,
clearSelectionText: i18n.clearSelectionAria,
openMenuText: i18n.openMenuAria,
closeMenuText: i18n.closeMenuAria,
tableId: id || tableId,
tableState: _objectSpread$1Y(_objectSpread$1Y({
isDisabled: rowEditMode || singleRowEditMode,
activeBar: view.toolbar.activeBar,
filters: view.filters
}, view.table), {}, {
selection: {
isSelectAllSelected: isSelectAllSelected,
isSelectAllIndeterminate: isSelectAllIndeterminate
}
}),
hasFastFilter: (options === null || options === void 0 ? void 0 : options.hasFilter) === 'onKeyPress' // TODO: remove id in v3
,
testId: "".concat(id || testId, "-table-head"),
showExpanderColumn: showExpanderColumn,
filterRowIcon: view.table.filterRowIcon,
filterRowIconDescription: i18n.filterRowIconDescription
})) : null, // Table contents
view.table.loadingState.isLoading ? /*#__PURE__*/React__default['default'].createElement(TableSkeletonWithHeaders, _extends_1$1({
columns: visibleColumns
}, pick(options, 'hasRowSelection', 'hasRowActions'), {
hasRowExpansion: !!options.hasRowExpansion,
hasRowNesting: !!options.hasRowNesting,
hasDragAndDrop: !!options.hasDragAndDrop,
rowCount: view.table.loadingState.rowCount,
columnCount: view.table.loadingState.columnCount // TODO: remove 'id' in v3.
,
testId: "".concat(id || testId, "-table-skeleton"),
showExpanderColumn: showExpanderColumn
})) : error ? /*#__PURE__*/React__default['default'].createElement(ErrorTable, {
id: id,
testId: "".concat(id || testId, "-table-error-body"),
i18n: i18n,
totalColumns: totalColumns,
error: error,
errorState: view.table.errorState,
onErrorStateAction: actions.table.onErrorStateAction
}) : visibleData && visibleData.length ? /*#__PURE__*/React__default['default'].createElement(TableBody, _extends_1$1({
langDir: langDir,
tableId: id || tableId,
rows: visibleData,
locale: locale,
rowActionsState: view.table.rowActions,
singleRowEditButtons: view.table.singleRowEditButtons,
expandedRows: expandedData,
columns: visibleColumns,
expandedIds: view.table.expandedIds,
selectedIds: view.table.selectedIds,
loadingMoreIds: view.table.loadingMoreIds,
zIndex: zIndex
}, pick(i18n, 'overflowMenuAria', 'clickToExpandAria', 'clickToCollapseAria', 'inProgressText', 'actionFailedText', 'learnMoreText', 'dismissText', 'selectRowAria', 'loadMoreText'), {
totalColumns: totalColumns
}, pick(options, 'hasRowSelection', 'hasRowActions', 'hasRowNesting', 'shouldExpandOnRowClick', 'shouldLazyRender', 'preserveCellWhiteSpace', 'useRadioButtonSingleSelect', 'hasDragAndDrop'), {
hideDragHandles: hideDragHandles,
hasRowExpansion: !!options.hasRowExpansion,
wrapCellText: options.wrapCellText,
truncateCellText: useCellTextTruncate,
ordering: view.table.ordering,
rowEditMode: rowEditMode,
actions: pick(actions.table, 'onRowSelected', 'onApplyRowAction', 'onClearRowError', 'onRowExpanded', 'onRowClicked', 'onRowLoadMore', 'onDrag', 'onDrop') // TODO: remove 'id' in v3.
,
testId: "".concat(id || testId, "-table-body"),
showExpanderColumn: showExpanderColumn,
size: size,
pinColumn: options.pinColumn
})) : /*#__PURE__*/React__default['default'].createElement(EmptyTable, {
id: id,
totalColumns: totalColumns,
isFiltered: isFiltered,
emptyState: // only show emptyState if no filters or search is applied
view.table.emptyState && !isFiltered ? view.table.emptyState : {
message: i18n.emptyMessage,
messageBody: i18n.emptyMessageBody,
messageWithFilters: i18n.emptyMessageWithFilters,
messageWithFiltersBody: i18n.emptyMessageWithFiltersBody,
buttonLabel: i18n.emptyButtonLabel,
buttonLabelWithFilters: i18n.emptyButtonLabelWithFilters
},
onEmptyStateAction: isFiltered && i18n.emptyButtonLabelWithFilters ? handleClearFilters // show clear filters
: !isFiltered && actions.table.onEmptyStateAction ? actions.table.onEmptyStateAction : undefined // if not filtered then show normal empty state
// TODO: remove 'id' in v3.
,
testId: "".concat(id || testId, "-table-empty")
}), options.hasAggregations && !aggregationsAreHidden ? /*#__PURE__*/React__default['default'].createElement(TableFoot, {
options: _objectSpread$1Y(_objectSpread$1Y({}, pick(options, 'hasRowSelection', 'hasRowActions', 'hasRowNesting')), {}, {
hasRowExpansion: !!options.hasRowExpansion
}),
tableState: {
aggregations: aggregations,
ordering: view.table.ordering
},
testId: "".concat(id || testId, "-table-foot"),
showExpanderColumn: showExpanderColumn
}) : null)), options.hasPagination && !view.table.loadingState.isLoading && visibleData !== null && visibleData !== void 0 && visibleData.length ? // don't show pagination row while loading
paginationProps.totalItems > Math.ceil(maxPages * paginationProps.pageSize) ? /*#__PURE__*/React__default['default'].createElement(SimplePagination, {
prevPageText: i18n.pageBackwardAria,
nextPageText: i18n.pageForwardAria,
totalItems: paginationProps.totalItems,
page: paginationProps.page,
maxPage: Math.ceil(paginationProps.totalItems / paginationProps.pageSize),
onPage: function onPage(page) {
return actions.pagination.onChangePage({
page: page,
pageSize: paginationProps.pageSize
});
},
testId: "".concat(id || testId, "-table-pagination"),
size: size
}) : /*#__PURE__*/React__default['default'].createElement(SizedPagination, {
pageSize: paginationProps.pageSize,
pageSizes: paginationProps.pageSizes,
page: paginationProps.page,
isItemPerPageHidden: paginationProps.isItemPerPageHidden,
totalItems: paginationProps.totalItems < Math.ceil(maxPages * paginationProps.pageSize) ? paginationProps.totalItems : Math.ceil(maxPages * paginationProps.pageSize),
onChange: actions.pagination.onChangePage,
backwardText: i18n.pageBackwardAria,
forwardText: i18n.pageForwardAria,
pageNumberText: i18n.pageNumberAria,
itemsPerPageText: i18n.itemsPerPage,
itemRangeText: i18n.itemsRangeWithTotal,
pageRangeText: i18n.pageRange,
preventInteraction: rowEditMode || singleRowEditMode,
testId: "".concat(id || testId, "-table-pagination"),
size: paginationProps.size
}) : null, options.hasMultiSort && /*#__PURE__*/React__default['default'].createElement(TableMultiSortModal, {
testId: "".concat(id, "-multi-sort-modal"),
columns: columns,
ordering: view.table.ordering,
sort: multiSortColumns,
actions: _objectSpread$1Y({}, pick(actions.table, 'onSaveMultiSortColumns', 'onCancelMultiSortColumns', 'onAddMultiSortColumn', 'onRemoveMultiSortColumn', 'onClearMultiSortColumns')),
showMultiSortModal: view.table.showMultiSortModal,
i18n: i18n
}));
};
Table.propTypes = propTypes$20;
Table.defaultProps = defaultProps$29({});
Table.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "Table",
"props": {
"id": {
"type": {
"name": "string"
},
"required": false,
"description": "DOM ID for component"
},
"secondaryTitle": {
"type": {
"name": "string"
},
"required": false,
"description": "Displays smaller title in header"
},
"tooltip": {
"type": {
"name": "node"
},
"required": false,
"description": ""
},
"useZebraStyles": {
"type": {
"name": "bool"
},
"required": false,
"description": "render zebra stripes or not"
},
"lightweight": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.bool,\n `The 'lightweight' prop has been deprecated and will be removed in the next major version.`\n)"
},
"required": false,
"description": "lighter styling where regular table too visually heavy. Deprecated."
},
"columns": {
"type": {
"name": "custom",
"raw": "TableColumnsPropTypes.isRequired"
},
"required": false,
"description": "Specify the properties of each column in the table"
},
"columnGroups": {
"type": {
"name": "custom",
"raw": "TableColumnGroupPropType"
},
"required": false,
"description": "Specify the properties of each column group in the table. Defaults to empty array."
},
"data": {
"type": {
"name": "custom",
"raw": "TableRowsPropTypes.isRequired"
},
"required": false,
"description": "Row value data for the body of the table"
},
"expandedData": {
"type": {
"name": "custom",
"raw": "ExpandedRowsPropTypes"
},
"required": false,
"description": "Expanded data for the table details"
},
"zIndex": {
"type": {
"name": "number"
},
"required": false,
"description": "Optional base z-index for the table. Used with drag and drop to ensure the drag image is \"over\"\nother elements on the page. This is generally only needed if the table is in a modal dialog\nwith z-index of its own. In that case, set this z-index to be higher than the modal to be sure\nany drags are seen above the modal."
},
"stickyHeader": {
"type": {
"name": "custom",
"raw": "experimental('stickyHeader')"
},
"required": false,
"description": "Experimental: Turns on the carbon sticky-header feature."
},
"options": {
"type": {
"name": "shape",
"value": {
"hasAggregations": {
"name": "bool",
"description": "If true allows the table to aggregate values of columns in a special row",
"required": false
},
"hasFastSearch": {
"name": "bool",
"description": "If true, search is applied as typed. If false, only after 'Enter' is pressed",
"required": false
},
"hasPagination": {
"name": "bool",
"required": false
},
"hasRowSelection": {
"name": "enum",
"value": [{
"value": "'multi'",
"computed": false
}, {
"value": "'single'",
"computed": false
}, {
"value": "false",
"computed": false
}],
"required": false
},
"hasBatchActionToolbar": {
"name": "bool",
"description": "@TODO: Remove in major release and just show action bar when no actions are defined",
"required": false
},
"hasRowExpansion": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"expandRowsExclusively": {
"name": "bool",
"description": "True if any previously expanded rows should be collapsed when a new row is expanded",
"required": false
}
}
}],
"description": "True if the rows should be expandable",
"required": false
},
"hasRowNesting": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "shape",
"value": {
"hasSingleNestedHierarchy": {
"name": "bool",
"description": "If the hierarchy only has 1 nested level of children",
"required": false
}
}
}],
"required": false
},
"hasMultiSort": {
"name": "bool",
"required": false
},
"hasRowActions": {
"name": "bool",
"required": false
},
"hasFilter": {
"name": "union",
"value": [{
"name": "bool"
}, {
"name": "enum",
"value": [{
"value": "'onKeyPress'",
"computed": false
}, {
"value": "'onEnterAndBlur'",
"computed": false
}]
}],
"required": false
},
"hasAdvancedFilter": {
"name": "custom",
"raw": "(props, propName, componentName) => {\n if (__DEV__) {\n if (props?.hasFilter && props?.hasAdvancedFilter) {\n return new Error(\n `Only one of props 'options.hasFilter' or 'options.hasAdvancedFilter' can be specified in '${componentName}'.`\n );\n }\n\n if (![true, false, undefined].includes(props?.hasAdvancedFilter)) {\n return new Error(`'options.hasAdvancedFilter' should be a boolean or undefined.`);\n }\n }\n}",
"required": false
},
"hasOnlyPageData": {
"name": "bool",
"description": "if true, the data prop will be assumed to only represent the currently visible page",
"required": false
},
"hasSearch": {
"name": "bool",
"description": "has simple search capability",
"required": false
},
"hasColumnSelection": {
"name": "bool",
"required": false
},
"hasColumnSelectionConfig": {
"name": "bool",
"required": false
},
"shouldLazyRender": {
"name": "bool",
"required": false
},
"hasRowCountInHeader": {
"name": "bool",
"required": false
},
"hasRowEdit": {
"name": "bool",
"description": "If true enables the row edit toolbar button and functionality",
"required": false
},
"hasResize": {
"name": "bool",
"required": false
},
"hasSingleRowEdit": {
"name": "bool",
"required": false
},
"hasUserViewManagement": {
"name": "bool",
"required": false
},
"preserveColumnWidths": {
"name": "bool",
"description": "Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized.",
"required": false
},
"shouldExpandOnRowClick": {
"name": "bool",
"required": false
},
"useAutoTableLayoutForResize": {
"name": "bool",
"description": "If true removes the \"table-layout: fixed\" for resizable tables",
"required": false
},
"wrapCellText": {
"name": "custom",
"raw": "WrapCellTextPropTypes",
"description": "auto - Wrap for tables with dynamic columns widths and truncate for tables with fixed or resizable columns\nalways - Wrap if needed for all table column configurations\nnever - Tables with dynamic columns widths grow larger and tables with fixed or resizable columns truncate.\nalwaysTruncate - Always truncate if needed for all table column configurations\nexpand - Expand to fit text width (by horizontal scrollbar) for table with fixed columns",
"required": false
},
"preserveCellWhiteSpace": {
"name": "bool",
"description": "use white-space: pre; css when true",
"required": false
},
"hasFilterRowIcon": {
"name": "bool",
"description": "display icon button in filter row",
"required": false
},
"pinColumn": {
"name": "custom",
"raw": "PinColumnPropTypes",
"description": "column to pin in the table",
"required": false
},
"hasDragAndDrop": {
"name": "bool",
"description": "If rows can be dragged and dropped on top of each other. When this is true there will always\nbe space reserved for a drag handle at the start of the row. Each rows data must indicate if\nthat row can be dragged by setting `isDraggable: true` on their row data. The table also needs\n`actions.table.onDrag` and `actions.table.onDrop` callback props.",
"required": false
},
"pinHeaderAndFooter": {
"name": "bool",
"description": "Freezes table header and footer",
"required": false
}
}
},
"required": false,
"description": "Optional properties to customize how the table should be rendered"
},
"size": {
"type": {
"name": "custom",
"raw": "function checkProps(props, propName, componentName) {\n if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {\n warning(\n false,\n `The value \\`${props[propName]}\\` has been deprecated for the ` +\n `\\`${propName}\\` prop on the ${componentName} component. It will be removed in the next major ` +\n `release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.`\n );\n }\n}"
},
"required": false,
"description": "Size prop from Carbon to shrink row height (and header height in some instances)"
},
"view": {
"type": {
"name": "shape",
"value": {
"aggregations": {
"name": "shape",
"value": {
"label": {
"name": "string",
"required": false
},
"columns": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"description": "id of the column that should have its values aggregated",
"required": true
},
"value": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "string"
}],
"description": "the primitive value or function that will receive an array of values and returns an aggregated value",
"required": false
},
"align": {
"name": "enum",
"value": [{
"value": "'start'",
"computed": false
}, {
"value": "'center'",
"computed": false
}, {
"value": "'end'",
"computed": false
}],
"description": "allow aligning the results the same as the column",
"required": false
},
"isSortable": {
"name": "bool",
"description": "allows the aggregation to align with sortable columns extra padding",
"required": false
}
}
},
"required": false
},
"isHidden": {
"name": "bool",
"description": "hide the aggregation row without removing the aggregations object",
"required": false
}
},
"required": false
},
"pagination": {
"name": "shape",
"value": {
"pageSize": {
"name": "number",
"required": false
},
"pageSizes": {
"name": "arrayOf",
"value": {
"name": "number"
},
"required": false
},
"page": {
"name": "number",
"required": false
},
"totalItems": {
"name": "number",
"required": false
},
"maxPages": {
"name": "custom",
"raw": "(props, propName, componentName) => {\n if (__DEV__) {\n if (typeof props[propName] !== 'number') {\n return new Error(\n `Invalid type of \\`${propName}\\` supplied to \\`${componentName}\\`. \\`${propName}\\` must be a positive integer.`\n );\n }\n if (props[propName] < 0 || !Number.isInteger(props[propName])) {\n const roundedStr = `${props[propName]} will be rounded to ${Math.ceil(\n props[propName]\n )}`;\n return new Error(\n `Invalid prop \\`${propName}\\` supplied to \\`${componentName}\\`. \\`${propName}\\` must be a positive integer. ${roundedStr}.`\n );\n }\n }\n\n return '';\n}",
"description": "Number of pages rendered in pagination",
"required": false
},
"isItemPerPageHidden": {
"name": "bool",
"required": false
},
"size": {
"name": "enum",
"value": [{
"value": "'sm'",
"computed": false
}, {
"value": "'md'",
"computed": false
}, {
"value": "'lg'",
"computed": false
}],
"description": "Specify the size of the Pagination buttons. Currently supports either `sm`, 'md' (default) or 'lg` as an option.",
"required": false
}
},
"required": false
},
"filters": {
"name": "custom",
"raw": "TableFiltersPropType",
"required": false
},
"advancedFilters": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"filterId": {
"name": "string",
"description": "Unique id for particular filter",
"required": true
},
"filterTitleText": {
"name": "string",
"description": "Text for main title of page",
"required": true
},
"filterRules": {
"name": "custom",
"raw": "RuleGroupPropType.isRequired",
"required": true
}
}
},
"description": "a stripped down version of the RuleBuilderFilterPropType",
"required": false
},
"selectedAdvancedFilterIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"required": false
},
"toolbar": {
"name": "shape",
"value": {
"activeBar": {
"name": "custom",
"raw": "ActiveTableToolbarPropType",
"description": "Specify which header row to display, will display default header row if null",
"required": false
},
"customToolbarContent": {
"name": "node",
"description": "optional content to render inside the toolbar",
"required": false
},
"batchActions": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": true
},
"labelText": {
"name": "string",
"required": true
},
"icon": {
"name": "element",
"required": false
},
"iconDescription": {
"name": "string",
"required": false
}
}
},
"description": "Specify which batch actions to render in the batch action bar. If empty, no batch action toolbar will display",
"required": false
},
"search": {
"name": "custom",
"raw": "TableSearchPropTypes",
"description": "Simple search state",
"required": false
},
"isDisabled": {
"name": "bool",
"description": "is the toolbar currently disabled",
"required": false
},
"rowEditBarButtons": {
"name": "node",
"description": "buttons to be shown with when activeBar is 'rowEdit'",
"required": false
},
"toolbarActions": {
"name": "custom",
"raw": "TableToolbarActionsPropType",
"description": "extra actions that can appear in an overflow menu in the toolbar (same menu as toggle aggregations)",
"required": false
},
"hideClearAllFiltersButton": {
"name": "bool",
"description": "force hide Clear all filters button in toolbar",
"required": false
}
},
"required": false
},
"table": {
"name": "shape",
"value": {
"isSelectAllSelected": {
"name": "bool",
"required": false
},
"isSelectAllIndeterminate": {
"name": "bool",
"required": false
},
"selectedIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"required": false
},
"sort": {
"name": "union",
"value": [{
"name": "custom",
"raw": "TableSortPropType"
}, {
"name": "arrayOf",
"value": {
"name": "custom",
"raw": "TableSortPropType"
}
}],
"required": false
},
"ordering": {
"name": "custom",
"raw": "TableOrderingPropType",
"description": "Specify the order, visibility and group belonging of the table columns",
"required": false
},
"rowActions": {
"name": "custom",
"raw": "RowActionsStatePropTypes",
"description": "what is the current state of the row actions",
"required": false
},
"singleRowEditButtons": {
"name": "element",
"required": false
},
"expandedIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"required": false
},
"emptyState": {
"name": "custom",
"raw": "EmptyStatePropTypes",
"required": false
},
"errorState": {
"name": "element",
"description": "use custom error state or use error message directly",
"required": false
},
"loadingState": {
"name": "shape",
"value": {
"isLoading": {
"name": "bool",
"required": false
},
"rowCount": {
"name": "number",
"required": false
},
"columnCount": {
"name": "number",
"required": false
}
},
"required": false
},
"showMultiSortModal": {
"name": "bool",
"required": false
},
"multiSortModal": {
"name": "shape",
"value": {
"anticipatedColumn": {
"name": "shape",
"value": {
"columnId": {
"name": "string",
"required": false
},
"direction": {
"name": "enum",
"value": [{
"value": "'ASC'",
"computed": false
}, {
"value": "'DESC'",
"computed": false
}],
"required": false
}
},
"description": "The anticipatedColumn is used to add the most recently click columnId to the UI of the\nMultiSort modal. This gives the user a better experience by preemptively adding the column\nthey clicked multi-sort on to the multisort modal without changing state. They still have to\nclick \"Sort\" to save it, or can click 'Cancel' or the 'X' to clear it.",
"required": false
}
},
"required": false
},
"loadingMoreIds": {
"name": "arrayOf",
"value": {
"name": "string"
},
"description": "Array with rowIds that are with loading active",
"required": false
},
"filterRowIcon": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "object"
}],
"description": "icon element for filter row icon",
"required": false
}
},
"required": false
}
}
},
"required": false,
"description": "Initial state of the table, should be updated via a local state wrapper component implementation or via a central store/redux see StatefulTable component for an example"
},
"actions": {
"type": {
"name": "shape",
"value": {
"pagination": {
"name": "shape",
"value": {
"onChangePage": {
"name": "func",
"description": "Specify a callback for when the current page or page size is changed.\nThis callback is passed an object parameter containing the current page and the current page size",
"required": false
}
},
"required": false
},
"toolbar": {
"name": "shape",
"value": {
"onApplyFilter": {
"name": "func",
"required": false
},
"onToggleFilter": {
"name": "func",
"required": false
},
"onShowRowEdit": {
"name": "func",
"required": false
},
"onToggleColumnSelection": {
"name": "func",
"required": false
},
"onClearAllFilters": {
"name": "func",
"description": "Specify a callback for when the user clicks toolbar button to clear all filters.\nReceives a parameter of the current filter values for each column",
"required": false
},
"onCancelBatchAction": {
"name": "func",
"description": "Callback for when the automatcally generated Cancel action in the batch actions bar is clicked",
"required": false
},
"onApplyBatchAction": {
"name": "func",
"description": "Callback for all the batch actions except the cancel. Is called with the id of the clicked action.\n For the StatefulTable the current selections are received as second parameter",
"required": false
},
"onApplySearch": {
"name": "func",
"description": "Apply a search criteria to the table",
"required": false
},
"onDownloadCSV": {
"name": "func",
"description": "Download the table contents",
"required": false
},
"onApplyAdvancedFilter": {
"name": "func",
"description": "When advanced filters are applied",
"required": false
},
"onToggleAdvancedFilter": {
"name": "func",
"description": "Toggles the advanced filter flyout open",
"required": false
},
"onRemoveAdvancedFilter": {
"name": "func",
"description": "Remove the selected advancedFilter from the table",
"required": false
},
"onCreateAdvancedFilter": {
"name": "func",
"description": "Fired the 'create new advanced filter' button is clicked.",
"required": false
},
"onCancelAdvancedFilter": {
"name": "func",
"description": "Fired when then 'Cancel' button is clicked in the advanced filter flyout menu",
"required": false
},
"onChangeAdvancedFilter": {
"name": "func",
"description": "Fired when an advanced filter is selected or removed.",
"required": false
},
"onToggleAggregations": {
"name": "func",
"description": "fired when 'Toggle aggregations' is clicked in the overflow menu",
"required": false
},
"onApplyToolbarAction": {
"name": "func",
"description": "fired when clicking a 'toolbarAction' in the table toolbar",
"required": false
},
"onSearchExpand": {
"name": "func",
"description": "fired when focus/blur on search bar in the table toolbar",
"required": false
}
},
"required": false
},
"table": {
"name": "shape",
"value": {
"onRowSelected": {
"name": "func",
"required": false
},
"onRowClicked": {
"name": "func",
"required": false
},
"onRowExpanded": {
"name": "func",
"required": false
},
"onSelectAll": {
"name": "func",
"required": false
},
"onChangeSort": {
"name": "func",
"required": false
},
"onApplyRowAction": {
"name": "func",
"description": "callback if a row action is clicked called with the id of the action then the id of the row if you\nreturn a promise from apply row action the stateful table will assume you're asynchronous and give a spinner",
"required": false
},
"onClearRowError": {
"name": "func",
"required": false
},
"onEmptyStateAction": {
"name": "func",
"required": false
},
"onChangeOrdering": {
"name": "func",
"required": false
},
"onColumnSelectionConfig": {
"name": "func",
"required": false
},
"onColumnResize": {
"name": "func",
"required": false
},
"onOverflowItemClicked": {
"name": "func",
"required": false
},
"onSaveMultiSortColumns": {
"name": "func",
"required": false
},
"onCancelMultiSortColumns": {
"name": "func",
"required": false
},
"onClearMultiSortColumns": {
"name": "func",
"required": false
},
"onAddMultiSortColumn": {
"name": "func",
"required": false
},
"onRemoveMultiSortColumn": {
"name": "func",
"required": false
},
"onTableErrorStateAction": {
"name": "func",
"required": false
},
"onRowLoadMore": {
"name": "func",
"description": "call back function for when load more row is clicked (rowId) => {}",
"required": false
},
"onFilterRowIconClick": {
"name": "func",
"description": "call back function for when icon button in filter row is clicked (evt) => {}",
"required": false
},
"onDrag": {
"name": "func",
"description": "Required callback to support drag and drop. This gets the rows values being dragged. It\nmust return an object of the row IDs that can be dropped on, and a node use as the preview\nof what's being dragged (typically the name of the row, possibly with an icon).\n\n@type {(rows: object[]) => {dropIds: string[], preview: React.Node}}",
"required": false
},
"onDrop": {
"name": "func",
"description": "Required callback to support drag and drop. This is called after a successful drop and is\npassed the ID of the row that was dragged and the ID of the row that was dropped on. It's\nup to the caller to decide what to do with that--the table does not update itself.\n\n@type {(dragRowIds: string[], dropRowId) => void}",
"required": false
}
},
"description": "table wide actions",
"required": true
},
"onUserViewModified": {
"name": "func",
"description": "callback for actions relevant for view management",
"required": false
}
}
},
"required": false,
"description": "Callbacks for actions of the table, can be used to update state in wrapper component to update `view` props"
},
"locale": {
"type": {
"name": "string"
},
"required": false,
"description": "what locale should we use to format table values if left empty no locale formatting happens"
},
"i18n": {
"type": {
"name": "custom",
"raw": "I18NPropTypes"
},
"required": false,
"description": ""
},
"error": {
"type": {
"name": "string"
},
"required": false,
"description": "Specify the error message that need to be displayed by default.\nIncase we use view.table.errorState property then the error state will be displayed instead of error message"
},
"testId": {
"type": {
"name": "string"
},
"required": false,
"description": ""
}
}
};
var prefix$p = settings$1.prefix,
iotPrefix$1S = settings$1.iotPrefix;
var propTypes$1$ = {
/** Disables the form elements when true */
disabled: PropTypes__default['default'].bool,
/** The state values of the controlled form elements e.g. { title: 'My view 1', isDefault: true } */
formValues: PropTypes__default['default'].objectOf(PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number, PropTypes__default['default'].bool])).isRequired,
/** Internationalisation strings */
i18n: PropTypes__default['default'].shape({
titleInputLabelText: PropTypes__default['default'].string,
defaultCheckboxLabelText: PropTypes__default['default'].string,
publicCheckboxLabelText: PropTypes__default['default'].string
}).isRequired,
/** Callback for when any of the form element's value changes */
onChange: PropTypes__default['default'].func.isRequired,
/** Used to overide the internal components and props for advanced customisation */
overrides: PropTypes__default['default'].shape({
form: OverridePropTypes,
titleTextInput: OverridePropTypes,
viewDescriptionContainer: OverridePropTypes,
defaultCheckbox: OverridePropTypes,
publicCheckbox: OverridePropTypes
}),
/** The id of the form elememt that should be initially focused */
primaryInputId: PropTypes__default['default'].string,
/** Id that can be used for testing */
testID: PropTypes__default['default'].string,
/** When true it will show that the title field has invalid input */
titleInputInvalid: PropTypes__default['default'].bool,
/** Used to describe the input validation error for the the title field */
titleInputInvalidText: PropTypes__default['default'].string,
/** A text that describes what this view contains */
viewDescription: PropTypes__default['default'].string
};
var defaultProps$28 = {
disabled: false,
overrides: undefined,
primaryInputId: undefined,
testID: 'TableSaveViewForm',
titleInputInvalid: false,
titleInputInvalidText: undefined,
viewDescription: undefined
};
var preventFormSubmission$2 = function preventFormSubmission(e) {
return e.preventDefault();
};
var TableSaveViewForm = function TableSaveViewForm(_ref) {
var _overrides$form, _overrides$titleTextI, _overrides$viewDescri, _overrides$defaultChe, _overrides$publicChec, _overrides$form2, _overrides$titleTextI2, _overrides$viewDescri2, _overrides$defaultChe2, _overrides$publicChec2;
var formValues = _ref.formValues,
disabled = _ref.disabled,
_ref$i18n = _ref.i18n,
titleInputLabelText = _ref$i18n.titleInputLabelText,
defaultCheckboxLabelText = _ref$i18n.defaultCheckboxLabelText,
publicCheckboxLabelText = _ref$i18n.publicCheckboxLabelText,
_onChange = _ref.onChange,
overrides = _ref.overrides,
primaryInputId = _ref.primaryInputId,
testID = _ref.testID,
titleInputInvalid = _ref.titleInputInvalid,
titleInputInvalidText = _ref.titleInputInvalidText,
viewDescription = _ref.viewDescription;
var MyForm = (overrides === null || overrides === void 0 ? void 0 : (_overrides$form = overrides.form) === null || _overrides$form === void 0 ? void 0 : _overrides$form.component) || 'form';
var MyTitleTextInput = (overrides === null || overrides === void 0 ? void 0 : (_overrides$titleTextI = overrides.titleTextInput) === null || _overrides$titleTextI === void 0 ? void 0 : _overrides$titleTextI.component) || carbonComponentsReact.TextInput;
var MyViewDescriptionContainer = (overrides === null || overrides === void 0 ? void 0 : (_overrides$viewDescri = overrides.viewDescriptionContainer) === null || _overrides$viewDescri === void 0 ? void 0 : _overrides$viewDescri.component) || 'p';
var MyDefaultCheckbox = (overrides === null || overrides === void 0 ? void 0 : (_overrides$defaultChe = overrides.defaultCheckbox) === null || _overrides$defaultChe === void 0 ? void 0 : _overrides$defaultChe.component) || carbonComponentsReact.Checkbox;
var MyPublicCheckbox = (overrides === null || overrides === void 0 ? void 0 : (_overrides$publicChec = overrides.publicCheckbox) === null || _overrides$publicChec === void 0 ? void 0 : _overrides$publicChec.component) || carbonComponentsReact.Checkbox; // A developer might override initial form values and not explicitly
// assign all checkboxes a boolean value, but controlled Checkboxes
// cannot have an undefined value.
var enforceControlledCheckbox = function enforceControlledCheckbox(val) {
return val !== undefined ? val : false;
};
return /*#__PURE__*/React__default['default'].createElement(MyForm, _extends_1$1({
"data-testid": testID,
onSubmit: preventFormSubmission$2
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$form2 = overrides.form) === null || _overrides$form2 === void 0 ? void 0 : _overrides$form2.props), /*#__PURE__*/React__default['default'].createElement(MyTitleTextInput, _extends_1$1({
name: "title",
"data-testid": "".concat(testID, "-title-input"),
value: formValues.title || '',
disabled: disabled,
id: primaryInputId,
invalid: titleInputInvalid,
invalidText: titleInputInvalidText,
labelText: titleInputLabelText,
onChange: function onChange(evt) {
_onChange({
title: evt.target.value
});
},
type: "text"
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$titleTextI2 = overrides.titleTextInput) === null || _overrides$titleTextI2 === void 0 ? void 0 : _overrides$titleTextI2.props)), /*#__PURE__*/React__default['default'].createElement(MyViewDescriptionContainer, _extends_1$1({
className: "".concat(iotPrefix$1S, "--save-view-modal__view-description") // eslint-disable-next-line react/no-children-prop
,
children: viewDescription
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$viewDescri2 = overrides.viewDescriptionContainer) === null || _overrides$viewDescri2 === void 0 ? void 0 : _overrides$viewDescri2.props)), /*#__PURE__*/React__default['default'].createElement("fieldset", {
className: "".concat(prefix$p, "--fieldset")
}, /*#__PURE__*/React__default['default'].createElement(MyDefaultCheckbox, _extends_1$1({
name: "isDefault",
"data-testid": "".concat(testID, "-default-checkbox"),
checked: enforceControlledCheckbox(formValues.isDefault),
disabled: disabled,
id: "save-view-modal-default-checkbox-label",
labelText: defaultCheckboxLabelText,
onChange: function onChange(checked) {
return _onChange({
isDefault: checked
});
},
wrapperClassName: "".concat(iotPrefix$1S, "--save-view-modal__default-view-checkbox")
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$defaultChe2 = overrides.defaultCheckbox) === null || _overrides$defaultChe2 === void 0 ? void 0 : _overrides$defaultChe2.props)), /*#__PURE__*/React__default['default'].createElement(MyPublicCheckbox, _extends_1$1({
name: "isPublic",
"data-testid": "".concat(testID, "-public-checkbox"),
checked: enforceControlledCheckbox(formValues.isPublic),
disabled: disabled,
id: "save-view-modal-public-checkbox-label",
labelText: publicCheckboxLabelText,
wrapperClassName: "".concat(iotPrefix$1S, "--save-view-modal__public-checkbox"),
onChange: function onChange(checked) {
return _onChange({
isPublic: checked
});
}
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$publicChec2 = overrides.publicCheckbox) === null || _overrides$publicChec2 === void 0 ? void 0 : _overrides$publicChec2.props))));
};
TableSaveViewForm.propTypes = propTypes$1$;
TableSaveViewForm.defaultProps = defaultProps$28;
TableSaveViewForm.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableSaveViewForm",
"props": {
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Disables the form elements when true"
},
"overrides": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": {
"form": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"titleTextInput": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"viewDescriptionContainer": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"defaultCheckbox": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"publicCheckbox": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
}
}
},
"required": false,
"description": "Used to overide the internal components and props for advanced customisation"
},
"primaryInputId": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "The id of the form elememt that should be initially focused"
},
"testID": {
"defaultValue": {
"value": "'TableSaveViewForm'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Id that can be used for testing"
},
"titleInputInvalid": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "When true it will show that the title field has invalid input"
},
"titleInputInvalidText": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "Used to describe the input validation error for the the title field"
},
"viewDescription": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "A text that describes what this view contains"
},
"formValues": {
"type": {
"name": "objectOf",
"value": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "number"
}, {
"name": "bool"
}]
}
},
"required": true,
"description": "The state values of the controlled form elements e.g. { title: 'My view 1', isDefault: true }"
},
"i18n": {
"type": {
"name": "shape",
"value": {
"titleInputLabelText": {
"name": "string",
"required": false
},
"defaultCheckboxLabelText": {
"name": "string",
"required": false
},
"publicCheckboxLabelText": {
"name": "string",
"required": false
}
}
},
"required": true,
"description": "Internationalisation strings"
},
"onChange": {
"type": {
"name": "func"
},
"required": true,
"description": "Callback for when any of the form element's value changes"
}
}
};
function ownKeys$1X(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$1X(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1X(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1X(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1R = settings$1.iotPrefix;
var propTypes$1_ = {
/**
* Callbacks for the actions of the modal
* onSave : Called with { title: string, defaultView: boolean, publicView: boolean} on save button click
* onClose : Called on cancel button click and on the top right close icon click
* onClearError : Called when the error msg is cleared
* onChange : Called when view title input value is changed
*/
actions: PropTypes__default['default'].shape({
onSave: PropTypes__default['default'].func,
onClose: PropTypes__default['default'].func,
onClearError: PropTypes__default['default'].func,
onChange: PropTypes__default['default'].func
}).isRequired,
/** Shows this string as a general modal error when present */
error: PropTypes__default['default'].string,
/** Internationalisation strings object */
i18n: PropTypes__default['default'].shape({
modalTitle: PropTypes__default['default'].string,
modalBodyText: PropTypes__default['default'].string,
titleInputLabelText: PropTypes__default['default'].string,
defaultCheckboxLabelText: PropTypes__default['default'].string,
publicCheckboxLabelText: PropTypes__default['default'].string,
closeIconDescription: PropTypes__default['default'].string,
saveButtonLabelText: PropTypes__default['default'].string,
cancelButtonLabelText: PropTypes__default['default'].string
}),
/**
* The initial values of the form elements e.g: { title: 'My view 1', isDefault: true }.
* Can be extended to contain any key-value pair needed for a custom form.
*/
initialFormValues: PropTypes__default['default'].oneOfType([PropTypes__default['default'].shape({
title: PropTypes__default['default'].string,
isDefault: PropTypes__default['default'].bool,
isPublic: PropTypes__default['default'].bool
}), PropTypes__default['default'].object]),
/** Determines if the modal is open or closed (i.e. visible or not to the user) */
open: PropTypes__default['default'].bool.isRequired,
/** Used to overide the internal components and props for advanced customisation */
overrides: PropTypes__default['default'].shape({
composedModal: OverridePropTypes,
tableSaveViewForm: OverridePropTypes
}),
/** Disables the form and shows spinner on save button when true */
sendingData: PropTypes__default['default'].bool,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
/** Id that can be used for testing */
testId: PropTypes__default['default'].string,
/** When true it will show that the title field has invalid input */
titleInputInvalid: PropTypes__default['default'].bool,
/** Used to describe the input validation error for the the title field */
titleInputInvalidText: PropTypes__default['default'].string,
/** A string that describes what this view contains */
viewDescription: PropTypes__default['default'].string
};
var defaultProps$27 = {
error: undefined,
i18n: {
modalTitle: 'Save new view',
modalBodyText: "You can save the current view's settings including applied filters and search.",
titleInputLabelText: 'View title',
defaultCheckboxLabelText: 'Save as my default view',
publicCheckboxLabelText: 'Public view',
closeIconDescription: 'Close',
saveButtonLabelText: 'Save',
cancelButtonLabelText: 'Cancel'
},
initialFormValues: {
title: '',
isDefault: false,
isPublic: false
},
overrides: undefined,
sendingData: false,
testId: 'TableSaveViewModal',
titleInputInvalid: false,
titleInputInvalidText: undefined,
viewDescription: undefined
};
var TableSaveViewModal = function TableSaveViewModal(_ref) {
var _overrides$composedMo, _overrides$tableSaveV, _overrides$composedMo2, _overrides$tableSaveV2;
var _ref$actions = _ref.actions,
onSaveCallback = _ref$actions.onSave,
onClose = _ref$actions.onClose,
onClearError = _ref$actions.onClearError,
onChangeCallback = _ref$actions.onChange,
error = _ref.error,
i18n = _ref.i18n,
initialFormValues = _ref.initialFormValues,
open = _ref.open,
overrides = _ref.overrides,
sendingData = _ref.sendingData,
testID = _ref.testID,
testId = _ref.testId,
titleInputInvalid = _ref.titleInputInvalid,
titleInputInvalidText = _ref.titleInputInvalidText,
viewDescription = _ref.viewDescription;
var _useState = React$1.useState(initialFormValues),
_useState2 = slicedToArray$2(_useState, 2),
formValues = _useState2[0],
setFormValues = _useState2[1];
var _merge2 = merge$1({}, defaultProps$27.i18n, i18n),
modalTitle = _merge2.modalTitle,
modalBodyText = _merge2.modalBodyText,
titleInputLabelText = _merge2.titleInputLabelText,
defaultCheckboxLabelText = _merge2.defaultCheckboxLabelText,
publicCheckboxLabelText = _merge2.publicCheckboxLabelText,
closeIconDescription = _merge2.closeIconDescription,
saveButtonLabelText = _merge2.saveButtonLabelText,
cancelButtonLabelText = _merge2.cancelButtonLabelText;
var onSave = function onSave() {
return onSaveCallback(_objectSpread$1X(_objectSpread$1X({}, formValues), {}, {
description: viewDescription
}));
};
var onChange = function onChange(modifiedFormValue) {
setFormValues(function (currentValues) {
return _objectSpread$1X(_objectSpread$1X({}, currentValues), modifiedFormValue);
});
onChangeCallback(modifiedFormValue);
};
var primaryInputId = 'save-view-modal-view-title';
var i18nFooter = {
primaryButtonLabel: saveButtonLabelText,
secondaryButtonLabel: cancelButtonLabelText
};
var MyComposedModal = (overrides === null || overrides === void 0 ? void 0 : (_overrides$composedMo = overrides.composedModal) === null || _overrides$composedMo === void 0 ? void 0 : _overrides$composedMo.component) || ComposedModal;
var MyTableSaveViewForm = (overrides === null || overrides === void 0 ? void 0 : (_overrides$tableSaveV = overrides.tableSaveViewForm) === null || _overrides$tableSaveV === void 0 ? void 0 : _overrides$tableSaveV.component) || TableSaveViewForm;
return /*#__PURE__*/React__default['default'].createElement(MyComposedModal, _extends_1$1({
footer: _objectSpread$1X(_objectSpread$1X({}, i18nFooter), {}, {
isPrimaryButtonDisabled: formValues.title === ''
}),
iconDescription: closeIconDescription // TODO: remove deprecated 'testID' in v3
,
testID: testID || testId,
error: error,
header: {
title: modalTitle
},
onClearError: onClearError,
onClose: onClose,
onSubmit: onSave,
open: open,
sendingData: sendingData,
selectorPrimaryFocus: "#".concat(primaryInputId)
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$composedMo2 = overrides.composedModal) === null || _overrides$composedMo2 === void 0 ? void 0 : _overrides$composedMo2.props), /*#__PURE__*/React__default['default'].createElement("p", {
className: "".concat(iotPrefix$1R, "--save-view-modal__body-text")
}, modalBodyText), /*#__PURE__*/React__default['default'].createElement(MyTableSaveViewForm, _extends_1$1({
viewDescription: viewDescription,
titleInputInvalid: titleInputInvalid,
titleInputInvalidText: titleInputInvalidText,
onChange: onChange,
formValues: formValues,
disabled: sendingData,
primaryInputId: primaryInputId,
i18n: {
titleInputLabelText: titleInputLabelText,
defaultCheckboxLabelText: defaultCheckboxLabelText,
publicCheckboxLabelText: publicCheckboxLabelText
} // TODO: remove deprecated 'testID' in v3
,
testID: "".concat(testID || testId, "-form")
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$tableSaveV2 = overrides.tableSaveViewForm) === null || _overrides$tableSaveV2 === void 0 ? void 0 : _overrides$tableSaveV2.props)));
};
TableSaveViewModal.propTypes = propTypes$1_;
TableSaveViewModal.defaultProps = defaultProps$27;
TableSaveViewModal.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableSaveViewModal",
"props": {
"error": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "Shows this string as a general modal error when present"
},
"i18n": {
"defaultValue": {
"value": "{\n modalTitle: 'Save new view',\n modalBodyText: `You can save the current view's settings including applied filters and search.`,\n titleInputLabelText: 'View title',\n defaultCheckboxLabelText: 'Save as my default view',\n publicCheckboxLabelText: 'Public view',\n closeIconDescription: 'Close',\n saveButtonLabelText: 'Save',\n cancelButtonLabelText: 'Cancel',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"modalTitle": {
"name": "string",
"required": false
},
"modalBodyText": {
"name": "string",
"required": false
},
"titleInputLabelText": {
"name": "string",
"required": false
},
"defaultCheckboxLabelText": {
"name": "string",
"required": false
},
"publicCheckboxLabelText": {
"name": "string",
"required": false
},
"closeIconDescription": {
"name": "string",
"required": false
},
"saveButtonLabelText": {
"name": "string",
"required": false
},
"cancelButtonLabelText": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "Internationalisation strings object"
},
"initialFormValues": {
"defaultValue": {
"value": "{\n title: '',\n isDefault: false,\n isPublic: false,\n}",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "shape",
"value": {
"title": {
"name": "string",
"required": false
},
"isDefault": {
"name": "bool",
"required": false
},
"isPublic": {
"name": "bool",
"required": false
}
}
}, {
"name": "object"
}]
},
"required": false,
"description": "The initial values of the form elements e.g: { title: 'My view 1', isDefault: true }.\nCan be extended to contain any key-value pair needed for a custom form."
},
"overrides": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": {
"composedModal": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"tableSaveViewForm": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
}
}
},
"required": false,
"description": "Used to overide the internal components and props for advanced customisation"
},
"sendingData": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Disables the form and shows spinner on save button when true"
},
"testId": {
"defaultValue": {
"value": "'TableSaveViewModal'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Id that can be used for testing"
},
"titleInputInvalid": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "When true it will show that the title field has invalid input"
},
"titleInputInvalidText": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "Used to describe the input validation error for the the title field"
},
"viewDescription": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "A string that describes what this view contains"
},
"actions": {
"type": {
"name": "shape",
"value": {
"onSave": {
"name": "func",
"required": false
},
"onClose": {
"name": "func",
"required": false
},
"onClearError": {
"name": "func",
"required": false
},
"onChange": {
"name": "func",
"required": false
}
}
},
"required": true,
"description": "Callbacks for the actions of the modal\nonSave : Called with { title: string, defaultView: boolean, publicView: boolean} on save button click\nonClose : Called on cancel button click and on the top right close icon click\nonClearError : Called when the error msg is cleared\nonChange : Called when view title input value is changed"
},
"open": {
"type": {
"name": "bool"
},
"required": true,
"description": "Determines if the modal is open or closed (i.e. visible or not to the user)"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
}
}
};
var useMerged = function useMerged() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// since the spread args is an array, we don't need to wrap it in another array. Doing so breaks
// the useMemo because a new array would be created with each render
// eslint-disable-next-line react-hooks/exhaustive-deps
return React$1.useMemo(function () {
return merge$1.apply(void 0, [{}].concat(args));
}, args);
};
var iotPrefix$1Q = settings$1.iotPrefix;
var propTypes$1Z = {
title: PropTypes__default['default'].string,
buttons: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
search: PropTypes__default['default'].shape({
onChange: PropTypes__default['default'].func,
value: PropTypes__default['default'].string,
id: PropTypes__default['default'].string,
hasFastSearch: PropTypes__default['default'].bool
}),
i18n: PropTypes__default['default'].shape({
searchPlaceHolderText: PropTypes__default['default'].string,
clearSearchIconDescription: PropTypes__default['default'].string
}),
testId: PropTypes__default['default'].string
};
var defaultProps$26 = {
buttons: [],
search: {
onChange: function onChange() {},
value: '',
hasFastSearch: true
},
i18n: {
searchPlaceHolderText: 'Enter a value'
},
title: null,
testId: 'list-header'
};
var ListHeader = function ListHeader(_ref) {
var title = _ref.title,
buttons = _ref.buttons,
search = _ref.search,
i18n = _ref.i18n,
testId = _ref.testId;
var previousSearchValueRef = React$1.useRef(search === null || search === void 0 ? void 0 : search.value);
var hasFastSearch = (search === null || search === void 0 ? void 0 : search.hasFastSearch) !== false;
var handleSearch = function handleSearch(e) {
var currentValue = e.target.value;
var previousValue = previousSearchValueRef.current;
if (previousValue !== currentValue) {
search.onChange(e);
previousSearchValueRef.current = currentValue;
}
};
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId,
className: "".concat(iotPrefix$1Q, "--list-header-container")
}, title || buttons && buttons.length > 0 ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1Q, "--list-header")
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1Q, "--list-header--title")
}, title), /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1Q, "--list-header--btn-container")
}, buttons)) : null, search ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1Q, "--list-header--search")
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Search, {
closeButtonLabelText: i18n.clearSearchIconDescription,
id: search.id || "".concat(iotPrefix$1Q, "--list-header--search"),
placeholder: i18n.searchPlaceHolderText,
onChange: hasFastSearch !== false ? handleSearch : undefined,
onBlur: hasFastSearch ? undefined : handleSearch,
onKeyDown: handleSpecificKeyDown(['Enter'], handleSearch),
onClear: function onClear() {
return handleSearch({
target: {
value: ''
}
});
},
size: "lg",
value: search.value,
labelText: i18n.searchPlaceHolderText,
"data-testid": "".concat(testId, "-search-input")
})) : null);
};
ListHeader.propTypes = propTypes$1Z;
ListHeader.defaultProps = defaultProps$26;
ListHeader.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ListHeader",
"props": {
"buttons": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "node"
}
},
"required": false,
"description": ""
},
"search": {
"defaultValue": {
"value": "{\n onChange: () => {},\n value: '',\n hasFastSearch: true,\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"onChange": {
"name": "func",
"required": false
},
"value": {
"name": "string",
"required": false
},
"id": {
"name": "string",
"required": false
},
"hasFastSearch": {
"name": "bool",
"required": false
}
}
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n searchPlaceHolderText: 'Enter a value',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"searchPlaceHolderText": {
"name": "string",
"required": false
},
"clearSearchIconDescription": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": ""
},
"title": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'list-header'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
}
}
};
var ITEM_COLUMN_GAP = 16;
var ITEM_LEVEL_OFFSET = 32;
var ITEM_HEIGHT = 40;
var ITEM_HEIGHT_LARGE = 64;
var iotPrefix$1P = settings$1.iotPrefix;
var TargetSize = {
Third: 'third',
Half: 'half',
Full: 'full'
};
var ListTargetPropTypes = {
connectDropTarget: PropTypes__default['default'].func.isRequired,
isOver: PropTypes__default['default'].bool,
targetPosition: PropTypes__default['default'].string.isRequired,
targetSize: PropTypes__default['default'].oneOf([TargetSize.Third, TargetSize.Half, TargetSize.Full]),
// eslint-disable-next-line react/no-unused-prop-types
targetOverride: PropTypes__default['default'].string // eslint flags this as unused though it is used in react-dnd's drop effect
};
var ListTargetDefaultProps = {
isOver: false,
targetSize: TargetSize.Third,
targetOverride: null
};
var ListTarget = function ListTarget(_ref) {
var connectDropTarget = _ref.connectDropTarget,
targetPosition = _ref.targetPosition,
targetSize = _ref.targetSize,
isOver = _ref.isOver;
var height = 33; // defaults to TargetSize.Third
if (targetSize === TargetSize.Full) {
height = 100;
} else if (targetSize === TargetSize.Half) {
height = 50;
}
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": "list-target",
className: classnames$1("".concat(iotPrefix$1P, "--list-item-editable--drop-target-").concat(targetPosition), defineProperty$d({}, "".concat(iotPrefix$1P, "--list-item-editable--drop-target-").concat(targetPosition, "__over"), isOver)),
style: {
height: "".concat(height, "%")
},
ref: function ref(instance) {
/* istanbul ignore else */
if (connectDropTarget) {
connectDropTarget(instance);
}
}
});
};
var rowTarget = {
drop: function drop(hoverProps, monitor) {
var _hoverProps$targetOve;
var hoverId = hoverProps.id;
var dragId = monitor.getItem().id;
var target = (_hoverProps$targetOve = hoverProps.targetOverride) !== null && _hoverProps$targetOve !== void 0 ? _hoverProps$targetOve : hoverProps.targetPosition; // Check if drop is allowed
if (hoverProps.itemWillMove(dragId, hoverId, target)) {
hoverProps.onItemMoved(dragId, hoverId, target);
}
}
};
var dt = DropTarget('ListItem', rowTarget, function (connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver({
shallow: true
})
};
});
ListTarget.propTypes = ListTargetPropTypes;
ListTarget.defaultProps = ListTargetDefaultProps;
ListTarget.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ListTarget",
"props": {
"isOver": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"targetSize": {
"defaultValue": {
"value": "'third'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'third'",
"computed": false
}, {
"value": "'half'",
"computed": false
}, {
"value": "'full'",
"computed": false
}]
},
"required": false,
"description": ""
},
"targetOverride": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"connectDropTarget": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"targetPosition": {
"type": {
"name": "string"
},
"required": true,
"description": ""
}
}
};
var ListTarget$1 = dt(ListTarget);
var iotPrefix$1O = settings$1.iotPrefix;
var ListItemWrapper = function ListItemWrapper(_ref) {
var _classnames4;
var id = _ref.id,
editingStyle = _ref.editingStyle,
expanded = _ref.expanded,
isSelectable = _ref.isSelectable,
itemWillMove = _ref.itemWillMove,
onItemMoved = _ref.onItemMoved,
onSelect = _ref.onSelect,
selected = _ref.selected,
isDragging = _ref.isDragging,
renderDropTargets = _ref.renderDropTargets,
getAllowedDropIds = _ref.getAllowedDropIds,
isLargeRow = _ref.isLargeRow,
children = _ref.children,
connectDragSource = _ref.connectDragSource,
disabled = _ref.disabled,
preventRowFocus = _ref.preventRowFocus;
var body = isSelectable && !disabled ? /*#__PURE__*/React__default['default'].createElement("div", {
role: "button",
tabIndex: preventRowFocus ? -1 : 0,
className: classnames$1("".concat(iotPrefix$1O, "--list-item"), "".concat(iotPrefix$1O, "--list-item__selectable"), defineProperty$d({}, "".concat(iotPrefix$1O, "--list-item__selected"), editingStyle ? false : selected), defineProperty$d({}, "".concat(iotPrefix$1O, "--list-item__large"), isLargeRow), defineProperty$d({}, "".concat(iotPrefix$1O, "--list-item-editable"), editingStyle)),
"data-testid": selected ? 'list-item__selected' : null,
onKeyPress: function onKeyPress(_ref2) {
var key = _ref2.key;
return key === 'Enter' && onSelect(id);
},
onClick: function onClick() {
onSelect(id);
}
}, children) : /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1O, "--list-item"), (_classnames4 = {}, defineProperty$d(_classnames4, "".concat(iotPrefix$1O, "--list-item__large"), isLargeRow), defineProperty$d(_classnames4, "".concat(iotPrefix$1O, "--list-item-editable"), editingStyle), _classnames4))
}, children);
if (editingStyle) {
var canNest = editingStyle === EditingStyle.SingleNesting || editingStyle === EditingStyle.MultipleNesting;
var allowedDropIds = renderDropTargets && getAllowedDropIds && getAllowedDropIds();
var preventDrop = Array.isArray(allowedDropIds) && !allowedDropIds.includes(id);
return /*#__PURE__*/React__default['default'].createElement("div", {
role: "listitem",
className: classnames$1("".concat(iotPrefix$1O, "--list-item-editable--drag-container"), defineProperty$d({}, "".concat(iotPrefix$1O, "--list-item-editable--dragging"), isDragging)),
ref: function ref(instance) {
if (connectDragSource) {
connectDragSource(instance);
}
}
}, renderDropTargets && !preventDrop && /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1O, "--list-item-editable--drop-targets"), defineProperty$d({}, "".concat(iotPrefix$1O, "--list-item__large"), isLargeRow))
}, // Renders Nested location only if nesting is allowed
canNest ? /*#__PURE__*/React__default['default'].createElement(ListTarget$1, {
id: id,
targetPosition: DropLocation.Nested,
targetSize: TargetSize.Full,
itemWillMove: itemWillMove,
onItemMoved: onItemMoved
}) : null, /*#__PURE__*/React__default['default'].createElement(ListTarget$1, {
id: id,
targetPosition: DropLocation.Above,
itemWillMove: itemWillMove,
targetSize: canNest ? TargetSize.Third : TargetSize.Half,
onItemMoved: onItemMoved
}), /*#__PURE__*/React__default['default'].createElement(ListTarget$1, {
id: id,
targetPosition: DropLocation.Below,
itemWillMove: itemWillMove,
targetOverride: expanded ? DropLocation.Nested : null // If item is expanded then the bottom target will nest
,
targetSize: canNest ? TargetSize.Third : TargetSize.Half,
onItemMoved: onItemMoved
})), body);
}
return body;
};
var ListItemWrapperProps = {
id: PropTypes__default['default'].string.isRequired,
editingStyle: PropTypes__default['default'].oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
connectDragSource: PropTypes__default['default'].func.isRequired,
disabled: PropTypes__default['default'].bool,
expanded: PropTypes__default['default'].bool.isRequired,
isLargeRow: PropTypes__default['default'].bool.isRequired,
isSelectable: PropTypes__default['default'].bool.isRequired,
isDragging: PropTypes__default['default'].bool.isRequired,
onSelect: PropTypes__default['default'].func.isRequired,
renderDropTargets: PropTypes__default['default'].bool.isRequired,
selected: PropTypes__default['default'].bool.isRequired,
children: PropTypes__default['default'].node.isRequired,
onItemMoved: PropTypes__default['default'].func.isRequired,
itemWillMove: PropTypes__default['default'].func.isRequired,
getAllowedDropIds: PropTypes__default['default'].func,
preventRowFocus: PropTypes__default['default'].bool.isRequired
};
ListItemWrapper.propTypes = ListItemWrapperProps;
ListItemWrapper.defaultProps = {
getAllowedDropIds: null,
editingStyle: null,
disabled: false
};
ListItemWrapper.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ListItemWrapper",
"props": {
"getAllowedDropIds": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"editingStyle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "EditingStyle.Single",
"computed": true
}, {
"value": "EditingStyle.Multiple",
"computed": true
}, {
"value": "EditingStyle.SingleNesting",
"computed": true
}, {
"value": "EditingStyle.MultipleNesting",
"computed": true
}]
},
"required": false,
"description": ""
},
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"connectDragSource": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"expanded": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"isLargeRow": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"isSelectable": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"isDragging": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"onSelect": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"renderDropTargets": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"selected": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"children": {
"type": {
"name": "node"
},
"required": true,
"description": ""
},
"onItemMoved": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"itemWillMove": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"preventRowFocus": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
}
}
};
function ownKeys$1W(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$1W(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1W(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1W(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1N = settings$1.iotPrefix;
var ItemType = 'ListItem';
var ListItemPropTypes$1 = {
id: PropTypes__default['default'].string.isRequired,
editingStyle: PropTypes__default['default'].oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
isLargeRow: PropTypes__default['default'].bool,
isLocked: PropTypes__default['default'].bool,
isExpandable: PropTypes__default['default'].bool,
onExpand: PropTypes__default['default'].func,
isSelectable: PropTypes__default['default'].bool,
disabled: PropTypes__default['default'].bool,
onSelect: PropTypes__default['default'].func,
renderDropTargets: PropTypes__default['default'].bool,
getAllowedDropIds: PropTypes__default['default'].func,
/** the id of the item currently being dragged if any */
draggingId: PropTypes__default['default'].string,
selected: PropTypes__default['default'].bool,
expanded: PropTypes__default['default'].bool,
value: PropTypes__default['default'].string.isRequired,
/** text displayed on hover */
title: PropTypes__default['default'].string,
/** string value or callback render function */
secondaryValue: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func, PropTypes__default['default'].shape({
value: PropTypes__default['default'].func,
label: PropTypes__default['default'].string
})]),
/** either a callback render function or a node */
rowActions: PropTypes__default['default'].oneOfType([PropTypes__default['default'].arrayOf(PropTypes__default['default'].node), PropTypes__default['default'].func]),
icon: PropTypes__default['default'].node,
iconPosition: PropTypes__default['default'].string,
isCategory: PropTypes__default['default'].bool,
/** i18n strings */
i18n: PropTypes__default['default'].shape({
expand: PropTypes__default['default'].string,
close: PropTypes__default['default'].string
}),
/** Default selected item ref needed for scrolling */
selectedItemRef: PropTypes__default['default'].oneOfType([// Either a function
PropTypes__default['default'].func, // Or the instance of a DOM native element (see the note about SSR)
PropTypes__default['default'].shape({
current: typeof Element === 'undefined' ? PropTypes__default['default'].any : PropTypes__default['default'].instanceOf(Element)
})]),
/** The nodes should be Carbon Tags components */
tags: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
/* these props come from react-dnd */
connectDragSource: PropTypes__default['default'].func.isRequired,
connectDragPreview: PropTypes__default['default'].func.isRequired,
index: PropTypes__default['default'].number.isRequired,
dragPreviewText: PropTypes__default['default'].string,
nestingLevel: PropTypes__default['default'].number,
isDragging: PropTypes__default['default'].bool.isRequired,
onItemMoved: PropTypes__default['default'].func.isRequired,
itemWillMove: PropTypes__default['default'].func.isRequired,
/** true if the list item should not be focusable even though isSelectable is true */
preventRowFocus: PropTypes__default['default'].bool
};
var ListItemDefaultProps = {
editingStyle: null,
isLargeRow: false,
isLocked: false,
isExpandable: false,
dragPreviewText: null,
onExpand: function onExpand() {},
isSelectable: false,
disabled: false,
onSelect: function onSelect() {},
renderDropTargets: false,
getAllowedDropIds: null,
draggingId: null,
selected: false,
expanded: false,
secondaryValue: null,
rowActions: null,
icon: null,
iconPosition: 'left',
nestingLevel: 0,
isCategory: false,
i18n: {
expand: 'Expand',
close: 'Close',
dragHandle: 'Drag handle'
},
selectedItemRef: null,
tags: null,
preventRowFocus: false,
title: null
};
var ListItem = function ListItem(_ref) {
var _classnames8;
var id = _ref.id,
editingStyle = _ref.editingStyle,
isLargeRow = _ref.isLargeRow,
isExpandable = _ref.isExpandable,
onExpand = _ref.onExpand,
expanded = _ref.expanded,
isSelectable = _ref.isSelectable,
onSelect = _ref.onSelect,
selected = _ref.selected,
disabled = _ref.disabled,
value = _ref.value,
title = _ref.title,
secondaryValue = _ref.secondaryValue,
rowActions = _ref.rowActions,
renderDropTargets = _ref.renderDropTargets,
getAllowedDropIds = _ref.getAllowedDropIds,
draggingId = _ref.draggingId,
icon = _ref.icon,
iconPosition = _ref.iconPosition,
onItemMoved = _ref.onItemMoved,
nestingLevel = _ref.nestingLevel,
isCategory = _ref.isCategory,
isLocked = _ref.isLocked,
i18n = _ref.i18n,
isDragging = _ref.isDragging,
selectedItemRef = _ref.selectedItemRef,
tags = _ref.tags,
connectDragSource = _ref.connectDragSource,
connectDragPreview = _ref.connectDragPreview,
itemWillMove = _ref.itemWillMove,
dragPreviewText = _ref.dragPreviewText,
preventRowFocus = _ref.preventRowFocus;
var mergedI18n = React$1.useMemo(function () {
return _objectSpread$1W(_objectSpread$1W({}, ListItemDefaultProps.i18n), i18n);
}, [i18n]);
var handleExpansionClick = function handleExpansionClick(event) {
event.stopPropagation();
/* istanbul ignore else */
if (isExpandable) {
onExpand(id);
}
};
if (Array.isArray(rowActions)) {
warning_1(false, 'You have passed an array of nodes to ListItem as rowActions. This can cause performance problems and has been deprecated. You should pass a render function instead.') ;
}
var renderNestingOffset = function renderNestingOffset() {
return nestingLevel > 0 ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1N, "--list-item--nesting-offset"),
style: {
width: "".concat(nestingLevel * ITEM_LEVEL_OFFSET - ITEM_COLUMN_GAP, "px")
}
}) : null;
};
var renderExpander = function renderExpander() {
return isExpandable ? /*#__PURE__*/React__default['default'].createElement("div", {
role: "button",
tabIndex: 0,
className: classnames$1("".concat(iotPrefix$1N, "--list-item--expand-icon"), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--expand-icon__disabled"), disabled)),
onClick: !disabled ? handleExpansionClick : undefined,
"data-testid": "expand-icon",
"aria-label": expanded ? mergedI18n.close : mergedI18n.expand,
title: expanded ? mergedI18n.close : mergedI18n.expand,
onKeyPress: function onKeyPress(event) {
return event.key === 'Enter' && handleExpansionClick(event);
}
}, expanded ? /*#__PURE__*/React__default['default'].createElement(iconsReact.ChevronUp16, {
"aria-label": "".concat(mergedI18n.close, "-icon")
}) : /*#__PURE__*/React__default['default'].createElement(iconsReact.ChevronDown16, {
"aria-label": "".concat(mergedI18n.expand, "-icon")
})) : null;
};
var renderIcon = function renderIcon() {
return icon ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1N, "--list-item--content--icon ").concat(iotPrefix$1N, "--list-item--content--icon__").concat(iconPosition)
}, icon) : null;
};
var hasRowActions = rowActions && (typeof rowActions === 'function' || (rowActions === null || rowActions === void 0 ? void 0 : rowActions.length));
var renderRowActions = function renderRowActions() {
return hasRowActions ?
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1N, "--list-item--content--row-actions") // add event handlers to prevent rowAction items from bubbling and causing
// list re-renders
,
onKeyPress: handleSpecificKeyDown(['Enter', ' '], function (e) {
e.stopPropagation();
}),
onClick: function onClick(e) {
e.stopPropagation();
}
}, typeof rowActions === 'function' ? rowActions() : rowActions) : null;
};
var renderTags = function renderTags() {
return tags && tags.length > 0 ? /*#__PURE__*/React__default['default'].createElement("div", null, tags) : null;
};
var renderDragPreview = function renderDragPreview() {
if (editingStyle && connectDragPreview) {
return connectDragPreview( /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1N, "--list-item-editable--drag-preview")
}, dragPreviewText || value));
}
return null;
};
var renderSecondaryValue = function renderSecondaryValue() {
var _classnames2;
return secondaryValue ? /*#__PURE__*/React__default['default'].createElement("div", {
title: typeof secondaryValue === 'function' && typeof secondaryValue() === 'string' ? secondaryValue() : typeof secondaryValue === 'function' ? '' : _typeof_1$1(secondaryValue) === 'object' && secondaryValue !== null ? secondaryValue.label : secondaryValue,
className: classnames$1("".concat(iotPrefix$1N, "--list-item--content--values--value"), (_classnames2 = {}, defineProperty$d(_classnames2, "".concat(iotPrefix$1N, "--list-item--content--values--value__large"), isLargeRow), defineProperty$d(_classnames2, "".concat(iotPrefix$1N, "--list-item--content--values__disabled"), disabled), _classnames2))
}, typeof secondaryValue === 'function' ? secondaryValue() : _typeof_1$1(secondaryValue) === 'object' && secondaryValue !== null ? secondaryValue.value() : secondaryValue) : null;
};
var dragIcon = function dragIcon() {
return isLocked ? /*#__PURE__*/React__default['default'].createElement(iconsReact.Locked16, {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--lock"))
}) : editingStyle ? /*#__PURE__*/React__default['default'].createElement("div", {
title: mergedI18n.dragHandle
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Draggable16, {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--handle"), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--handle__disabled"), disabled)),
"data-testid": "list-item-editable"
})) : null;
};
return /*#__PURE__*/React__default['default'].createElement(ListItemWrapper, {
isPreview: false,
id: id,
isSelectable: isSelectable,
selected: selected,
isDragging: isDragging,
editingStyle: editingStyle,
expanded: expanded,
isLargeRow: isLargeRow,
onSelect: onSelect,
connectDragSource: connectDragSource,
onItemMoved: onItemMoved,
itemWillMove: itemWillMove,
disabled: disabled,
renderDropTargets: renderDropTargets,
getAllowedDropIds: getAllowedDropIds ? function () {
return getAllowedDropIds(draggingId);
} : null,
preventRowFocus: preventRowFocus
}, renderDragPreview(), dragIcon(), renderNestingOffset(), renderExpander(), /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--content"), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--content__selected"), !editingStyle && selected), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--content__large"), isLargeRow)),
ref: selectedItemRef
}, renderIcon(), /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--content--values"), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--content--values__large"), isLargeRow))
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--content--values--main"), defineProperty$d({}, "".concat(iotPrefix$1N, "--list-item--content--values--main__large"), isLargeRow))
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1N, "--list-item--content--values--value"), (_classnames8 = {}, defineProperty$d(_classnames8, "".concat(iotPrefix$1N, "--list-item--category"), isCategory), defineProperty$d(_classnames8, "".concat(iotPrefix$1N, "--list-item--content--values__disabled"), disabled), _classnames8)),
title: title || value
}, value), renderSecondaryValue()), renderTags(), renderRowActions())));
};
var dragSourceSpecification = {
beginDrag: function beginDrag(props) {
return {
id: props.id
};
}
}; // These props originate from React DND and are passed down to
// the ListItem via the DragSource wrapper.
var dndPropsCollecting = function dndPropsCollecting(connect, monitor) {
var _monitor$getItem;
return {
connectDragSource: connect.dragSource(),
connectDragPreview: connect.dragPreview(),
isDragging: monitor.isDragging(),
renderDropTargets: monitor.getItemType() !== null,
// render drop targets if anything is dragging
draggingId: (_monitor$getItem = monitor.getItem()) === null || _monitor$getItem === void 0 ? void 0 : _monitor$getItem.id
};
};
var ds = DragSource(ItemType, dragSourceSpecification, dndPropsCollecting);
ListItem.propTypes = ListItemPropTypes$1;
ListItem.defaultProps = ListItemDefaultProps;
ListItem.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ListItem",
"props": {
"editingStyle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "EditingStyle.Single",
"computed": true
}, {
"value": "EditingStyle.Multiple",
"computed": true
}, {
"value": "EditingStyle.SingleNesting",
"computed": true
}, {
"value": "EditingStyle.MultipleNesting",
"computed": true
}]
},
"required": false,
"description": ""
},
"isLargeRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"isLocked": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"isExpandable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"dragPreviewText": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"onExpand": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"isSelectable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"disabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"onSelect": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"renderDropTargets": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"getAllowedDropIds": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"draggingId": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "the id of the item currently being dragged if any"
},
"selected": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"expanded": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"secondaryValue": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "string"
}, {
"name": "func"
}, {
"name": "shape",
"value": {
"value": {
"name": "func",
"required": false
},
"label": {
"name": "string",
"required": false
}
}
}]
},
"required": false,
"description": "string value or callback render function"
},
"rowActions": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "arrayOf",
"value": {
"name": "node"
}
}, {
"name": "func"
}]
},
"required": false,
"description": "either a callback render function or a node"
},
"icon": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": ""
},
"iconPosition": {
"defaultValue": {
"value": "'left'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"nestingLevel": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"isCategory": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n expand: 'Expand',\n close: 'Close',\n dragHandle: 'Drag handle',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"expand": {
"name": "string",
"required": false
},
"close": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "i18n strings"
},
"selectedItemRef": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "shape",
"value": {
"current": {
"name": "custom",
"raw": "typeof Element === 'undefined' ? PropTypes.any : PropTypes.instanceOf(Element)",
"required": false
}
}
}]
},
"required": false,
"description": "Default selected item ref needed for scrolling"
},
"tags": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "node"
}
},
"required": false,
"description": "The nodes should be Carbon Tags components"
},
"preventRowFocus": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "true if the list item should not be focusable even though isSelectable is true"
},
"title": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "text displayed on hover"
},
"id": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"value": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"connectDragSource": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"connectDragPreview": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"index": {
"type": {
"name": "number"
},
"required": true,
"description": ""
},
"isDragging": {
"type": {
"name": "bool"
},
"required": true,
"description": ""
},
"onItemMoved": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"itemWillMove": {
"type": {
"name": "func"
},
"required": true,
"description": ""
}
}
};
var ListItem$1 = ds(ListItem);
var ListItemPropTypes = {
children: PropTypes__default['default'].arrayOf(PropTypes__default['default'].object),
content: PropTypes__default['default'].shape({
icon: PropTypes__default['default'].node,
rowActions: PropTypes__default['default'].oneOfType([PropTypes__default['default'].arrayOf(PropTypes__default['default'].node), PropTypes__default['default'].func]),
secondaryValue: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func, PropTypes__default['default'].shape({
value: PropTypes__default['default'].func,
label: PropTypes__default['default'].string
})]),
/** The nodes should be Carbon Tags components */
tags: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
value: PropTypes__default['default'].string,
title: PropTypes__default['default'].string
}),
/** boolean to define load more row is needed */
hasLoadMore: PropTypes__default['default'].bool,
id: PropTypes__default['default'].string,
isCategory: PropTypes__default['default'].bool,
isSelectable: PropTypes__default['default'].bool
};
function ownKeys$1V(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$1V(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1V(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1V(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1M = settings$1.iotPrefix;
var propTypes$1Y = {
/** content shown if list is empty */
emptyState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
/** content shown if list is empty on search */
emptySearchState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
/** i18n strings */
i18n: PropTypes__default['default'].shape({
searchPlaceHolderText: PropTypes__default['default'].string,
expand: PropTypes__default['default'].string,
close: PropTypes__default['default'].string,
loadMore: PropTypes__default['default'].string
}),
/** data source of list items */
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape(ListItemPropTypes)),
/** if true shows empty search state, instead of empty state, when there are no search results */
isFiltering: PropTypes__default['default'].bool,
/** use full height in list */
isFullHeight: PropTypes__default['default'].bool,
/** use large/fat row in list */
isLargeRow: PropTypes__default['default'].bool,
/** optional skeleton to be rendered while loading data */
isLoading: PropTypes__default['default'].bool,
/** the ids of locked items that cannot be reordered */
lockedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** true if the list should have multiple selectable rows using checkboxes */
isCheckboxMultiSelect: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string,
/** Multiple currently selected items */
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** ids of row expanded */
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** callback function of select */
handleSelect: PropTypes__default['default'].func,
/** callback used to limit which items that should get drop targets rendered.
* receives the id of the item that is being dragged and returns a list of ids. */
getAllowedDropIds: PropTypes__default['default'].func,
/** call back function of expansion */
toggleExpansion: PropTypes__default['default'].func,
/** callback function for reorder */
onItemMoved: PropTypes__default['default'].func,
/** callback function when reorder will occur - can cancel the move by returning false */
itemWillMove: PropTypes__default['default'].func,
/** callback function for when load more row is clicked (rowId) => {} */
handleLoadMore: PropTypes__default['default'].func,
/** ids of selectable rows with indeterminate selection state */
indeterminateIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** RowIds for rows currently loading more child rows */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** list editing style */
editingStyle: PropTypes__default['default'].oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
/** icon can be left or right side of list row primary value */
iconPosition: PropTypes__default['default'].oneOf(['left', 'right']),
selectedItemRef: HtmlElementRefProp,
/** called after the row has expanded or collapsed and is passed the array of expanded ids */
onExpandedChange: PropTypes__default['default'].func,
/** enables horizontal scrollbar to appear if content is wider then container */
enableHorizontalScrollbar: PropTypes__default['default'].bool
};
var ConditionalWrapper = function ConditionalWrapper(_ref) {
var condition = _ref.condition,
wrapper = _ref.wrapper,
children = _ref.children;
return condition ? wrapper(children) : children;
};
var defaultProps$25 = {
editingStyle: null,
emptyState: 'No list items to show',
emptySearchState: 'No results found',
expandedIds: [],
getAllowedDropIds: null,
handleLoadMore: function handleLoadMore() {},
handleSelect: function handleSelect() {},
i18n: {
searchPlaceHolderText: 'Enter a value',
expand: 'Expand',
close: 'Close',
loadMore: 'View more...'
},
iconPosition: 'left',
isFiltering: false,
isFullHeight: false,
isLargeRow: false,
isLoading: false,
isCheckboxMultiSelect: false,
items: [],
itemWillMove: function itemWillMove() {
return true;
},
indeterminateIds: [],
loadingMoreIds: [],
lockedIds: [],
onItemMoved: function onItemMoved() {},
selectedIds: [],
selectedItemRef: /*#__PURE__*/React__default['default'].createRef(),
testId: 'list',
toggleExpansion: function toggleExpansion() {},
onExpandedChange: null,
enableHorizontalScrollbar: false
};
var getAdjustedNestingLevel$1 = function getAdjustedNestingLevel(items, currentLevel) {
return items.some(function (item) {
return (item === null || item === void 0 ? void 0 : item.children) && item.children.length > 0;
}) ? currentLevel + 1 : currentLevel;
};
var ListContent = function ListContent(_ref2) {
var _classnames2;
var isLoading = _ref2.isLoading,
isCheckboxMultiSelect = _ref2.isCheckboxMultiSelect,
isFiltering = _ref2.isFiltering,
isFullHeight = _ref2.isFullHeight,
items = _ref2.items,
testId = _ref2.testId,
emptyState = _ref2.emptyState,
emptySearchState = _ref2.emptySearchState,
selectedIds = _ref2.selectedIds,
expandedIds = _ref2.expandedIds,
indeterminateIds = _ref2.indeterminateIds,
loadingMoreIds = _ref2.loadingMoreIds,
handleSelect = _ref2.handleSelect,
editingStyle = _ref2.editingStyle,
getAllowedDropIds = _ref2.getAllowedDropIds,
iconPosition = _ref2.iconPosition,
toggleExpansion = _ref2.toggleExpansion,
onItemMoved = _ref2.onItemMoved,
itemWillMove = _ref2.itemWillMove,
isLargeRow = _ref2.isLargeRow,
lockedIds = _ref2.lockedIds,
handleLoadMore = _ref2.handleLoadMore,
i18n = _ref2.i18n,
selectedItemRef = _ref2.selectedItemRef,
onExpandedChange = _ref2.onExpandedChange,
enableHorizontalScrollbar = _ref2.enableHorizontalScrollbar;
var mergedI18n = React$1.useMemo(function () {
return _objectSpread$1V(_objectSpread$1V({}, defaultProps$25.i18n), i18n);
}, [i18n]);
var renderLoadMore = function renderLoadMore(item, isLoadingMore, level) {
var indentation = "".concat(level * ITEM_LEVEL_OFFSET - ITEM_COLUMN_GAP, "px");
return isLoadingMore ? /*#__PURE__*/React__default['default'].createElement("div", {
key: "".concat(item.id, "-list-item-load-more"),
className: "".concat(iotPrefix$1M, "--list-item")
}, /*#__PURE__*/React__default['default'].createElement("div", {
style: {
width: indentation
}
}), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, {
className: "".concat(iotPrefix$1M, "--list--load-more-skeleton"),
width: "30%",
"data-testid": "".concat(testId, "-loading-more")
})) : /*#__PURE__*/React__default['default'].createElement(Button$1, {
key: "".concat(item.id, "-list-item-load-more"),
className: "".concat(iotPrefix$1M, "--list-item ").concat(iotPrefix$1M, "--load-more-row"),
onClick: function onClick() {
return handleLoadMore(item.id);
},
"data-testid": "".concat(testId, "-").concat(item.id, "-load-more"),
kind: "ghost"
}, /*#__PURE__*/React__default['default'].createElement("div", {
style: {
width: indentation
}
}), /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1M, "--load-more-row--content")
}, mergedI18n.loadMore));
};
var renderItemAndChildren = function renderItemAndChildren(item, index, parentId, level) {
var hasChildren = (item === null || item === void 0 ? void 0 : item.children) && item.children.length > 0;
var isSelected = selectedIds.some(function (id) {
return item.id === id;
});
var isExpanded = expandedIds.filter(function (rowId) {
return rowId === item.id;
}).length > 0;
var isLoadingMore = loadingMoreIds.includes(item.id);
var isLocked = lockedIds.includes(item.id);
var isIndeterminate = indeterminateIds.includes(item.id);
var _item$content = item.content,
value = _item$content.value,
title = _item$content.title,
secondaryValue = _item$content.secondaryValue,
icon = _item$content.icon,
rowActions = _item$content.rowActions,
tags = _item$content.tags,
isSelectable = item.isSelectable,
isCategory = item.isCategory,
disabled = item.disabled;
return [/*#__PURE__*/React__default['default'].createElement("div", {
key: "".concat(item.id, "-list-item-parent-").concat(level, "-").concat(value) // data-floating-menu-container is a work around for this carbon issue: https://github.com/carbon-design-system/carbon/issues/4755
,
"data-floating-menu-container": true,
className: "".concat(iotPrefix$1M, "--list-item-parent")
}, /*#__PURE__*/React__default['default'].createElement(ListItem$1, {
id: item.id,
index: index,
key: "".concat(item.id, "-list-item-").concat(level, "-").concat(value),
nestingLevel: item !== null && item !== void 0 && item.children && item.children.length > 0 ? level - 1 : level,
title: title,
value: value,
icon: editingStyleIsMultiple(editingStyle) || isSelectable && isCheckboxMultiSelect ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Checkbox, {
id: "".concat(item.id, "-checkbox"),
name: item.value,
"data-testid": "".concat(item.id, "-checkbox"),
labelText: "",
onChange: function onChange() {
return handleSelect(item.id, parentId);
},
onClick: function onClick(event) {
// This is needed as a workaround for a carbon checkbox bug
// https://github.com/carbon-design-system/carbon/issues/10122#issuecomment-984692702
event.stopPropagation();
},
checked: isSelected,
disabled: disabled || isLocked,
indeterminate: isIndeterminate
}) : icon,
disabled: disabled,
iconPosition: iconPosition,
editingStyle: isLocked ? null : editingStyle,
secondaryValue: secondaryValue,
rowActions: rowActions,
onSelect: function onSelect() {
return handleSelect(item.id, parentId);
},
onExpand: toggleExpansion,
onItemMoved: onItemMoved,
itemWillMove: itemWillMove,
getAllowedDropIds: getAllowedDropIds,
selected: isSelected,
expanded: isExpanded,
isExpandable: hasChildren,
isLargeRow: isLargeRow,
isLocked: isLocked,
isCategory: isCategory,
isSelectable: editingStyle === null && isSelectable,
i18n: mergedI18n,
selectedItemRef: isSelected ? selectedItemRef : null,
tags: tags,
preventRowFocus: isCheckboxMultiSelect
}))].concat(toConsumableArray(hasChildren && isExpanded ? item.children.map(function (child, nestedIndex) {
return renderItemAndChildren(child, nestedIndex, item.id, level + 1);
}).concat(item.hasLoadMore ? [renderLoadMore(item, isLoadingMore, level + 1)] : []) : []), toConsumableArray(!hasChildren && item.hasLoadMore ? [renderLoadMore(item, isLoadingMore, level)] : []));
};
var previousExpandedIds = usePrevious(expandedIds, expandedIds);
var selectionChanged = !isEqual$1(expandedIds, previousExpandedIds); // get the lastId of the diff between previous and current, this handles closes
var previousLastId = selectionChanged && previousExpandedIds.filter(function (id) {
return !expandedIds.includes(id);
}).slice(-1)[0]; // get the lastId of the diff between current and previous, this handles opens
var lastId = selectionChanged && expandedIds.filter(function (id) {
return !previousExpandedIds.includes(id);
}).slice(-1)[0];
var notifyOnLastExpansionChange = function notifyOnLastExpansionChange(itemId) {
var isLastItem = lastId === itemId || previousLastId === itemId;
if (isLastItem && expandedIds.includes(itemId) !== previousExpandedIds.includes(itemId)) {
// the setTimeout within the request animation frame helps to ensure the event is fired
// immediately after a repaint. See:
// https://firefox-source-docs.mozilla.org/performance/bestpractices.html#how-do-i-avoid-triggering-uninterruptible-reflow
window.requestAnimationFrame(function () {
setTimeout(function () {
onExpandedChange(expandedIds);
});
}, 0);
}
};
var listItems = items.map(function (item, index) {
notifyOnLastExpansionChange(item.id);
return renderItemAndChildren(item, index, null, getAdjustedNestingLevel$1(items, 0));
});
var renderEmptyContent = function renderEmptyContent() {
var emptyContent = isFiltering ? emptySearchState : emptyState;
return typeof emptyContent === 'string' ? /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1M, "--list--empty-state"), defineProperty$d({}, "".concat(iotPrefix$1M, "--list--empty-state__full-height"), isFullHeight))
}, /*#__PURE__*/React__default['default'].createElement(EmptyState, {
icon: isFiltering ? 'no-result' : 'empty',
title: emptyContent,
body: ""
})) : emptyContent;
};
return /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1((_classnames2 = {}, defineProperty$d(_classnames2, "".concat(iotPrefix$1M, "--list--content__full-height"), isFullHeight), defineProperty$d(_classnames2, "".concat(iotPrefix$1M, "--list--content--w-horizontal-scrollbar"), enableHorizontalScrollbar), _classnames2), "".concat(iotPrefix$1M, "--list--content"))
}, /*#__PURE__*/React__default['default'].createElement(ConditionalWrapper, {
condition: isFullHeight && enableHorizontalScrollbar,
wrapper: function wrapper(children) {
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1M, "--list--content__full-height__support")
}, children);
}
}, /*#__PURE__*/React__default['default'].createElement(ConditionalWrapper, {
condition: enableHorizontalScrollbar,
wrapper: function wrapper(children) {
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1M, "--list--content__scrollbar__support")
}, children);
}
}, !isLoading ? /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, listItems.length ? listItems : renderEmptyContent()) : /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, {
className: "".concat(iotPrefix$1M, "--list--skeleton"),
width: "90%",
"data-testid": "".concat(testId, "-loading")
}))));
};
ListContent.propTypes = propTypes$1Y;
ListContent.defaultProps = defaultProps$25;
ListContent.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ListContent",
"props": {
"editingStyle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "EditingStyle.Single",
"computed": true
}, {
"value": "EditingStyle.Multiple",
"computed": true
}, {
"value": "EditingStyle.SingleNesting",
"computed": true
}, {
"value": "EditingStyle.MultipleNesting",
"computed": true
}]
},
"required": false,
"description": "list editing style"
},
"emptyState": {
"defaultValue": {
"value": "'No list items to show'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty"
},
"emptySearchState": {
"defaultValue": {
"value": "'No results found'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty on search"
},
"expandedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of row expanded"
},
"getAllowedDropIds": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback used to limit which items that should get drop targets rendered.\nreceives the id of the item that is being dragged and returns a list of ids."
},
"handleLoadMore": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function for when load more row is clicked (rowId) => {}"
},
"handleSelect": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function of select"
},
"i18n": {
"defaultValue": {
"value": "{\n searchPlaceHolderText: 'Enter a value',\n expand: 'Expand',\n close: 'Close',\n loadMore: 'View more...',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"searchPlaceHolderText": {
"name": "string",
"required": false
},
"expand": {
"name": "string",
"required": false
},
"close": {
"name": "string",
"required": false
},
"loadMore": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "i18n strings"
},
"iconPosition": {
"defaultValue": {
"value": "'left'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'left'",
"computed": false
}, {
"value": "'right'",
"computed": false
}]
},
"required": false,
"description": "icon can be left or right side of list row primary value"
},
"isFiltering": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "if true shows empty search state, instead of empty state, when there are no search results"
},
"isFullHeight": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use full height in list"
},
"isLargeRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use large/fat row in list"
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "optional skeleton to be rendered while loading data"
},
"isCheckboxMultiSelect": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "true if the list should have multiple selectable rows using checkboxes"
},
"items": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": "import { ListItemPropTypes } from '../ListPropTypes';",
"computed": true
}
},
"required": false,
"description": "data source of list items"
},
"itemWillMove": {
"defaultValue": {
"value": "() => {\n return true;\n}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function when reorder will occur - can cancel the move by returning false"
},
"indeterminateIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of selectable rows with indeterminate selection state"
},
"loadingMoreIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "RowIds for rows currently loading more child rows"
},
"lockedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "the ids of locked items that cannot be reordered"
},
"onItemMoved": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function for reorder"
},
"selectedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "Multiple currently selected items"
},
"selectedItemRef": {
"defaultValue": {
"value": "React.createRef()",
"computed": true
},
"type": {
"name": "custom",
"raw": "HtmlElementRefProp"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'list'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"toggleExpansion": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function of expansion"
},
"onExpandedChange": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "called after the row has expanded or collapsed and is passed the array of expanded ids"
},
"enableHorizontalScrollbar": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "enables horizontal scrollbar to appear if content is wider then container"
}
}
};
function _extends$1() {
_extends$1 = Object.assign || 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$1.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized$1(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var safeIsNaN = Number.isNaN ||
function ponyfill(value) {
return typeof value === 'number' && value !== value;
};
function isEqual(first, second) {
if (first === second) {
return true;
}
if (safeIsNaN(first) && safeIsNaN(second)) {
return true;
}
return false;
}
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (!isEqual(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual) {
if (isEqual === void 0) { isEqual = areInputsEqual; }
var lastThis;
var lastArgs = [];
var lastResult;
var calledOnce = false;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
return lastResult;
}
lastResult = resultFn.apply(this, newArgs);
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
return lastResult;
}
return memoized;
}
// Animation frame based implementation of setTimeout.
// Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js
var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
var now$1 = hasNativePerformanceNow ? function () {
return performance.now();
} : function () {
return Date.now();
};
function cancelTimeout(timeoutID) {
cancelAnimationFrame(timeoutID.id);
}
function requestTimeout(callback, delay) {
var start = now$1();
function tick() {
if (now$1() - start >= delay) {
callback.call(null);
} else {
timeoutID.id = requestAnimationFrame(tick);
}
}
var timeoutID = {
id: requestAnimationFrame(tick)
};
return timeoutID;
}
var cachedRTLResult = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left).
// Safari's elastic bounce makes detecting this even more complicated wrt potential false positives.
// The safest way to check this is to intentionally set a negative offset,
// and then verify that the subsequent "scroll" event matches the negative offset.
// If it does not match, then we can assume a non-standard RTL scroll implementation.
function getRTLOffsetType(recalculate) {
if (recalculate === void 0) {
recalculate = false;
}
if (cachedRTLResult === null || recalculate) {
var outerDiv = document.createElement('div');
var outerStyle = outerDiv.style;
outerStyle.width = '50px';
outerStyle.height = '50px';
outerStyle.overflow = 'scroll';
outerStyle.direction = 'rtl';
var innerDiv = document.createElement('div');
var innerStyle = innerDiv.style;
innerStyle.width = '100px';
innerStyle.height = '100px';
outerDiv.appendChild(innerDiv);
document.body.appendChild(outerDiv);
if (outerDiv.scrollLeft > 0) {
cachedRTLResult = 'positive-descending';
} else {
outerDiv.scrollLeft = 1;
if (outerDiv.scrollLeft === 0) {
cachedRTLResult = 'negative';
} else {
cachedRTLResult = 'positive-ascending';
}
}
document.body.removeChild(outerDiv);
return cachedRTLResult;
}
return cachedRTLResult;
}
var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150;
var defaultItemKey$1 = function defaultItemKey(index, data) {
return index;
}; // In DEV mode, this Set helps us only log a warning once per component instance.
// This avoids spamming the console every time a render happens.
var devWarningsDirection = null;
var devWarningsTagName$1 = null;
{
if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') {
devWarningsDirection =
/*#__PURE__*/
new WeakSet();
devWarningsTagName$1 =
/*#__PURE__*/
new WeakSet();
}
}
function createListComponent(_ref) {
var _class, _temp;
var getItemOffset = _ref.getItemOffset,
getEstimatedTotalSize = _ref.getEstimatedTotalSize,
getItemSize = _ref.getItemSize,
getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment,
getStartIndexForOffset = _ref.getStartIndexForOffset,
getStopIndexForStartIndex = _ref.getStopIndexForStartIndex,
initInstanceProps = _ref.initInstanceProps,
shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange,
validateProps = _ref.validateProps;
return _temp = _class =
/*#__PURE__*/
function (_PureComponent) {
_inheritsLoose(List, _PureComponent);
// Always use explicit constructor for React components.
// It produces less code after transpilation. (#26)
// eslint-disable-next-line no-useless-constructor
function List(props) {
var _this;
_this = _PureComponent.call(this, props) || this;
_this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized$1(_assertThisInitialized$1(_this)));
_this._outerRef = void 0;
_this._resetIsScrollingTimeoutId = null;
_this.state = {
instance: _assertThisInitialized$1(_assertThisInitialized$1(_this)),
isScrolling: false,
scrollDirection: 'forward',
scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0,
scrollUpdateWasRequested: false
};
_this._callOnItemsRendered = void 0;
_this._callOnItemsRendered = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) {
return _this.props.onItemsRendered({
overscanStartIndex: overscanStartIndex,
overscanStopIndex: overscanStopIndex,
visibleStartIndex: visibleStartIndex,
visibleStopIndex: visibleStopIndex
});
});
_this._callOnScroll = void 0;
_this._callOnScroll = memoizeOne(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) {
return _this.props.onScroll({
scrollDirection: scrollDirection,
scrollOffset: scrollOffset,
scrollUpdateWasRequested: scrollUpdateWasRequested
});
});
_this._getItemStyle = void 0;
_this._getItemStyle = function (index) {
var _this$props = _this.props,
direction = _this$props.direction,
itemSize = _this$props.itemSize,
layout = _this$props.layout;
var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize, shouldResetStyleCacheOnItemSizeChange && layout, shouldResetStyleCacheOnItemSizeChange && direction);
var style;
if (itemStyleCache.hasOwnProperty(index)) {
style = itemStyleCache[index];
} else {
var _offset = getItemOffset(_this.props, index, _this._instanceProps);
var size = getItemSize(_this.props, index, _this._instanceProps); // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var isRtl = direction === 'rtl';
var offsetHorizontal = isHorizontal ? _offset : 0;
itemStyleCache[index] = style = {
position: 'absolute',
left: isRtl ? undefined : offsetHorizontal,
right: isRtl ? offsetHorizontal : undefined,
top: !isHorizontal ? _offset : 0,
height: !isHorizontal ? size : '100%',
width: isHorizontal ? size : '100%'
};
}
return style;
};
_this._getItemStyleCache = void 0;
_this._getItemStyleCache = memoizeOne(function (_, __, ___) {
return {};
});
_this._onScrollHorizontal = function (event) {
var _event$currentTarget = event.currentTarget,
clientWidth = _event$currentTarget.clientWidth,
scrollLeft = _event$currentTarget.scrollLeft,
scrollWidth = _event$currentTarget.scrollWidth;
_this.setState(function (prevState) {
if (prevState.scrollOffset === scrollLeft) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
}
var direction = _this.props.direction;
var scrollOffset = scrollLeft;
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
// So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
switch (getRTLOffsetType()) {
case 'negative':
scrollOffset = -scrollLeft;
break;
case 'positive-descending':
scrollOffset = scrollWidth - clientWidth - scrollLeft;
break;
}
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
scrollOffset = Math.max(0, Math.min(scrollOffset, scrollWidth - clientWidth));
return {
isScrolling: true,
scrollDirection: prevState.scrollOffset < scrollLeft ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: false
};
}, _this._resetIsScrollingDebounced);
};
_this._onScrollVertical = function (event) {
var _event$currentTarget2 = event.currentTarget,
clientHeight = _event$currentTarget2.clientHeight,
scrollHeight = _event$currentTarget2.scrollHeight,
scrollTop = _event$currentTarget2.scrollTop;
_this.setState(function (prevState) {
if (prevState.scrollOffset === scrollTop) {
// Scroll position may have been updated by cDM/cDU,
// In which case we don't need to trigger another render,
// And we don't want to update state.isScrolling.
return null;
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
var scrollOffset = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
return {
isScrolling: true,
scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: false
};
}, _this._resetIsScrollingDebounced);
};
_this._outerRefSetter = function (ref) {
var outerRef = _this.props.outerRef;
_this._outerRef = ref;
if (typeof outerRef === 'function') {
outerRef(ref);
} else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) {
outerRef.current = ref;
}
};
_this._resetIsScrollingDebounced = function () {
if (_this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(_this._resetIsScrollingTimeoutId);
}
_this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1);
};
_this._resetIsScrolling = function () {
_this._resetIsScrollingTimeoutId = null;
_this.setState({
isScrolling: false
}, function () {
// Clear style cache after state update has been committed.
// This way we don't break pure sCU for items that don't use isScrolling param.
_this._getItemStyleCache(-1, null);
});
};
return _this;
}
List.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
validateSharedProps$1(nextProps, prevState);
validateProps(nextProps);
return null;
};
var _proto = List.prototype;
_proto.scrollTo = function scrollTo(scrollOffset) {
scrollOffset = Math.max(0, scrollOffset);
this.setState(function (prevState) {
if (prevState.scrollOffset === scrollOffset) {
return null;
}
return {
scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
scrollOffset: scrollOffset,
scrollUpdateWasRequested: true
};
}, this._resetIsScrollingDebounced);
};
_proto.scrollToItem = function scrollToItem(index, align) {
if (align === void 0) {
align = 'auto';
}
var itemCount = this.props.itemCount;
var scrollOffset = this.state.scrollOffset;
index = Math.max(0, Math.min(index, itemCount - 1));
this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps));
};
_proto.componentDidMount = function componentDidMount() {
var _this$props2 = this.props,
direction = _this$props2.direction,
initialScrollOffset = _this$props2.initialScrollOffset,
layout = _this$props2.layout;
if (typeof initialScrollOffset === 'number' && this._outerRef != null) {
var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
outerRef.scrollLeft = initialScrollOffset;
} else {
outerRef.scrollTop = initialScrollOffset;
}
}
this._callPropsCallbacks();
};
_proto.componentDidUpdate = function componentDidUpdate() {
var _this$props3 = this.props,
direction = _this$props3.direction,
layout = _this$props3.layout;
var _this$state = this.state,
scrollOffset = _this$state.scrollOffset,
scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested;
if (scrollUpdateWasRequested && this._outerRef != null) {
var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"
if (direction === 'horizontal' || layout === 'horizontal') {
if (direction === 'rtl') {
// TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
// So we need to determine which browser behavior we're dealing with, and mimic it.
switch (getRTLOffsetType()) {
case 'negative':
outerRef.scrollLeft = -scrollOffset;
break;
case 'positive-ascending':
outerRef.scrollLeft = scrollOffset;
break;
default:
var clientWidth = outerRef.clientWidth,
scrollWidth = outerRef.scrollWidth;
outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;
break;
}
} else {
outerRef.scrollLeft = scrollOffset;
}
} else {
outerRef.scrollTop = scrollOffset;
}
}
this._callPropsCallbacks();
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this._resetIsScrollingTimeoutId !== null) {
cancelTimeout(this._resetIsScrollingTimeoutId);
}
};
_proto.render = function render() {
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
direction = _this$props4.direction,
height = _this$props4.height,
innerRef = _this$props4.innerRef,
innerElementType = _this$props4.innerElementType,
innerTagName = _this$props4.innerTagName,
itemCount = _this$props4.itemCount,
itemData = _this$props4.itemData,
_this$props4$itemKey = _this$props4.itemKey,
itemKey = _this$props4$itemKey === void 0 ? defaultItemKey$1 : _this$props4$itemKey,
layout = _this$props4.layout,
outerElementType = _this$props4.outerElementType,
outerTagName = _this$props4.outerTagName,
style = _this$props4.style,
useIsScrolling = _this$props4.useIsScrolling,
width = _this$props4.width;
var isScrolling = this.state.isScrolling; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var onScroll = isHorizontal ? this._onScrollHorizontal : this._onScrollVertical;
var _this$_getRangeToRend = this._getRangeToRender(),
startIndex = _this$_getRangeToRend[0],
stopIndex = _this$_getRangeToRend[1];
var items = [];
if (itemCount > 0) {
for (var _index = startIndex; _index <= stopIndex; _index++) {
items.push(React$1.createElement(children, {
data: itemData,
key: itemKey(_index, itemData),
index: _index,
isScrolling: useIsScrolling ? isScrolling : undefined,
style: this._getItemStyle(_index)
}));
}
} // Read this value AFTER items have been created,
// So their actual sizes (if variable) are taken into consideration.
var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps);
return React$1.createElement(outerElementType || outerTagName || 'div', {
className: className,
onScroll: onScroll,
ref: this._outerRefSetter,
style: _extends$1({
position: 'relative',
height: height,
width: width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction: direction
}, style)
}, React$1.createElement(innerElementType || innerTagName || 'div', {
children: items,
ref: innerRef,
style: {
height: isHorizontal ? '100%' : estimatedTotalSize,
pointerEvents: isScrolling ? 'none' : undefined,
width: isHorizontal ? estimatedTotalSize : '100%'
}
}));
};
_proto._callPropsCallbacks = function _callPropsCallbacks() {
if (typeof this.props.onItemsRendered === 'function') {
var itemCount = this.props.itemCount;
if (itemCount > 0) {
var _this$_getRangeToRend2 = this._getRangeToRender(),
_overscanStartIndex = _this$_getRangeToRend2[0],
_overscanStopIndex = _this$_getRangeToRend2[1],
_visibleStartIndex = _this$_getRangeToRend2[2],
_visibleStopIndex = _this$_getRangeToRend2[3];
this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex);
}
}
if (typeof this.props.onScroll === 'function') {
var _this$state2 = this.state,
_scrollDirection = _this$state2.scrollDirection,
_scrollOffset = _this$state2.scrollOffset,
_scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;
this._callOnScroll(_scrollDirection, _scrollOffset, _scrollUpdateWasRequested);
}
}; // Lazily create and cache item styles while scrolling,
// So that pure component sCU will prevent re-renders.
// We maintain this cache, and pass a style prop rather than index,
// So that List can clear cached styles and force item re-render if necessary.
_proto._getRangeToRender = function _getRangeToRender() {
var _this$props5 = this.props,
itemCount = _this$props5.itemCount,
overscanCount = _this$props5.overscanCount;
var _this$state3 = this.state,
isScrolling = _this$state3.isScrolling,
scrollDirection = _this$state3.scrollDirection,
scrollOffset = _this$state3.scrollOffset;
if (itemCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps);
var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
// If there isn't at least one extra item, tab loops back around.
var overscanBackward = !isScrolling || scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1;
var overscanForward = !isScrolling || scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
return List;
}(React$1.PureComponent), _class.defaultProps = {
direction: 'ltr',
itemData: undefined,
layout: 'vertical',
overscanCount: 2,
useIsScrolling: false
}, _temp;
} // NOTE: I considered further wrapping individual items with a pure ListItem component.
// This would avoid ever calling the render function for the same index more than once,
// But it would also add the overhead of a lot of components/fibers.
// I assume people already do this (render function returning a class component),
// So my doing it would just unnecessarily double the wrappers.
var validateSharedProps$1 = function validateSharedProps(_ref2, _ref3) {
var children = _ref2.children,
direction = _ref2.direction,
height = _ref2.height,
layout = _ref2.layout,
innerTagName = _ref2.innerTagName,
outerTagName = _ref2.outerTagName,
width = _ref2.width;
var instance = _ref3.instance;
{
if (innerTagName != null || outerTagName != null) {
if (devWarningsTagName$1 && !devWarningsTagName$1.has(instance)) {
devWarningsTagName$1.add(instance);
console.warn('The innerTagName and outerTagName props have been deprecated. ' + 'Please use the innerElementType and outerElementType props instead.');
}
} // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
switch (direction) {
case 'horizontal':
case 'vertical':
if (devWarningsDirection && !devWarningsDirection.has(instance)) {
devWarningsDirection.add(instance);
console.warn('The direction prop should be either "ltr" (default) or "rtl". ' + 'Please use the layout prop to specify "vertical" (default) or "horizontal" orientation.');
}
break;
case 'ltr':
case 'rtl':
// Valid values
break;
default:
throw Error('An invalid "direction" prop has been specified. ' + 'Value should be either "ltr" or "rtl". ' + ("\"" + direction + "\" was specified."));
}
switch (layout) {
case 'horizontal':
case 'vertical':
// Valid values
break;
default:
throw Error('An invalid "layout" prop has been specified. ' + 'Value should be either "horizontal" or "vertical". ' + ("\"" + layout + "\" was specified."));
}
if (children == null) {
throw Error('An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + ("\"" + (children === null ? 'null' : typeof children) + "\" was specified."));
}
if (isHorizontal && typeof width !== 'number') {
throw Error('An invalid "width" prop has been specified. ' + 'Horizontal lists must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified."));
} else if (!isHorizontal && typeof height !== 'number') {
throw Error('An invalid "height" prop has been specified. ' + 'Vertical lists must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified."));
}
}
};
var DEFAULT_ESTIMATED_ITEM_SIZE$1 = 50;
var getItemMetadata$1 = function getItemMetadata(props, index, instanceProps) {
var _ref = props,
itemSize = _ref.itemSize;
var itemMetadataMap = instanceProps.itemMetadataMap,
lastMeasuredIndex = instanceProps.lastMeasuredIndex;
if (index > lastMeasuredIndex) {
var offset = 0;
if (lastMeasuredIndex >= 0) {
var itemMetadata = itemMetadataMap[lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (var i = lastMeasuredIndex + 1; i <= index; i++) {
var size = itemSize(i);
itemMetadataMap[i] = {
offset: offset,
size: size
};
offset += size;
}
instanceProps.lastMeasuredIndex = index;
}
return itemMetadataMap[index];
};
var findNearestItem$1 = function findNearestItem(props, instanceProps, offset) {
var itemMetadataMap = instanceProps.itemMetadataMap,
lastMeasuredIndex = instanceProps.lastMeasuredIndex;
var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return findNearestItemBinarySearch$1(props, instanceProps, lastMeasuredIndex, 0, offset);
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return findNearestItemExponentialSearch$1(props, instanceProps, Math.max(0, lastMeasuredIndex), offset);
}
};
var findNearestItemBinarySearch$1 = function findNearestItemBinarySearch(props, instanceProps, high, low, offset) {
while (low <= high) {
var middle = low + Math.floor((high - low) / 2);
var currentOffset = getItemMetadata$1(props, middle, instanceProps).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
};
var findNearestItemExponentialSearch$1 = function findNearestItemExponentialSearch(props, instanceProps, index, offset) {
var itemCount = props.itemCount;
var interval = 1;
while (index < itemCount && getItemMetadata$1(props, index, instanceProps).offset < offset) {
index += interval;
interval *= 2;
}
return findNearestItemBinarySearch$1(props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset);
};
var getEstimatedTotalSize = function getEstimatedTotalSize(_ref2, _ref3) {
var itemCount = _ref2.itemCount;
var itemMetadataMap = _ref3.itemMetadataMap,
estimatedItemSize = _ref3.estimatedItemSize,
lastMeasuredIndex = _ref3.lastMeasuredIndex;
var totalSizeOfMeasuredItems = 0; // Edge case check for when the number of items decreases while a scroll is in progress.
// https://github.com/bvaughn/react-window/pull/138
if (lastMeasuredIndex >= itemCount) {
lastMeasuredIndex = itemCount - 1;
}
if (lastMeasuredIndex >= 0) {
var itemMetadata = itemMetadataMap[lastMeasuredIndex];
totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;
}
var numUnmeasuredItems = itemCount - lastMeasuredIndex - 1;
var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedItemSize;
return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;
};
var VariableSizeList =
/*#__PURE__*/
createListComponent({
getItemOffset: function getItemOffset(props, index, instanceProps) {
return getItemMetadata$1(props, index, instanceProps).offset;
},
getItemSize: function getItemSize(props, index, instanceProps) {
return instanceProps.itemMetadataMap[index].size;
},
getEstimatedTotalSize: getEstimatedTotalSize,
getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(props, index, align, scrollOffset, instanceProps) {
var direction = props.direction,
height = props.height,
layout = props.layout,
width = props.width; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var size = isHorizontal ? width : height;
var itemMetadata = getItemMetadata$1(props, index, instanceProps); // Get estimated total size after ItemMetadata is computed,
// To ensure it reflects actual measurements instead of just estimates.
var estimatedTotalSize = getEstimatedTotalSize(props, instanceProps);
var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset));
var minOffset = Math.max(0, itemMetadata.offset - size + itemMetadata.size);
if (align === 'smart') {
if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
return Math.round(minOffset + (maxOffset - minOffset) / 2);
case 'auto':
default:
if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
return scrollOffset;
} else if (scrollOffset < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getStartIndexForOffset: function getStartIndexForOffset(props, offset, instanceProps) {
return findNearestItem$1(props, instanceProps, offset);
},
getStopIndexForStartIndex: function getStopIndexForStartIndex(props, startIndex, scrollOffset, instanceProps) {
var direction = props.direction,
height = props.height,
itemCount = props.itemCount,
layout = props.layout,
width = props.width; // TODO Deprecate direction "horizontal"
var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
var size = isHorizontal ? width : height;
var itemMetadata = getItemMetadata$1(props, startIndex, instanceProps);
var maxOffset = scrollOffset + size;
var offset = itemMetadata.offset + itemMetadata.size;
var stopIndex = startIndex;
while (stopIndex < itemCount - 1 && offset < maxOffset) {
stopIndex++;
offset += getItemMetadata$1(props, stopIndex, instanceProps).size;
}
return stopIndex;
},
initInstanceProps: function initInstanceProps(props, instance) {
var _ref4 = props,
estimatedItemSize = _ref4.estimatedItemSize;
var instanceProps = {
itemMetadataMap: {},
estimatedItemSize: estimatedItemSize || DEFAULT_ESTIMATED_ITEM_SIZE$1,
lastMeasuredIndex: -1
};
instance.resetAfterIndex = function (index, shouldForceUpdate) {
if (shouldForceUpdate === void 0) {
shouldForceUpdate = true;
}
instanceProps.lastMeasuredIndex = Math.min(instanceProps.lastMeasuredIndex, index - 1); // We could potentially optimize further by only evicting styles after this index,
// But since styles are only cached while scrolling is in progress-
// It seems an unnecessary optimization.
// It's unlikely that resetAfterIndex() will be called while a user is scrolling.
instance._getItemStyleCache(-1);
if (shouldForceUpdate) {
instance.forceUpdate();
}
};
return instanceProps;
},
shouldResetStyleCacheOnItemSizeChange: false,
validateProps: function validateProps(_ref5) {
var itemSize = _ref5.itemSize;
{
if (typeof itemSize !== 'function') {
throw Error('An invalid "itemSize" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (itemSize === null ? 'null' : typeof itemSize) + "\" was specified."));
}
}
}
});
function ownKeys$1U(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$1U(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1U(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1U(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1L = settings$1.iotPrefix;
var propTypes$1X = {
/** content shown if list is empty */
emptyState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
/** content shown if list is empty on search */
emptySearchState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
/** i18n strings */
i18n: PropTypes__default['default'].shape({
searchPlaceHolderText: PropTypes__default['default'].string,
expand: PropTypes__default['default'].string,
close: PropTypes__default['default'].string,
loadMore: PropTypes__default['default'].string
}),
/** data source of list items */
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape(ListItemPropTypes)),
/** if true shows empty search state, instead of empty state, when there are no search results */
isFiltering: PropTypes__default['default'].bool,
/** use full height in list */
// eslint-disable-next-line consistent-return
isFullHeight: function isFullHeight(props, propName, componentName) {
{
/* istanbul ignore else */
if (props[propName] === true) {
return new Error("".concat(componentName, ": Using '").concat(propName, "' with 'isVirtualList' could have negative performance consequences. Using the them together is discouraged."));
}
}
},
/** use large/fat row in list */
isLargeRow: PropTypes__default['default'].bool,
/** optional skeleton to be rendered while loading data */
isLoading: PropTypes__default['default'].bool,
/** true if the list should have multiple selectable rows using checkboxes */
isCheckboxMultiSelect: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string,
/** Multiple currently selected items */
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** ids of row expanded */
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** callback used to limit which items that should get drop targets rendered.
* receives the id of the item that is being dragged and returns a list of ids. */
getAllowedDropIds: PropTypes__default['default'].func,
/** call back function of select */
handleSelect: PropTypes__default['default'].func,
/** call back function of expansion */
toggleExpansion: PropTypes__default['default'].func,
/** callback function for reorder */
onItemMoved: PropTypes__default['default'].func,
/** callback function when reorder will occur - can cancel the move by returning false */
itemWillMove: PropTypes__default['default'].func,
/** call back function for when load more row is clicked (rowId) => {} */
handleLoadMore: PropTypes__default['default'].func,
/** ids of selectable rows with indeterminate selection state */
indeterminateIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** RowIds for rows currently loading more child rows */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** the ids of locked items that cannot be reordered */
lockedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** list editing style */
editingStyle: PropTypes__default['default'].oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
/** icon can be left or right side of list row primary value */
iconPosition: PropTypes__default['default'].oneOf(['left', 'right']),
virtualListRef: HtmlElementRefProp
};
var defaultProps$24 = {
editingStyle: null,
emptyState: 'No list items to show',
emptySearchState: 'No results found',
expandedIds: [],
getAllowedDropIds: null,
handleLoadMore: function handleLoadMore() {},
handleSelect: function handleSelect() {},
i18n: {
searchPlaceHolderText: 'Enter a value',
expand: 'Expand',
close: 'Close',
loadMore: 'View more...'
},
iconPosition: 'left',
isFiltering: false,
isFullHeight: false,
isLargeRow: false,
isLoading: false,
isCheckboxMultiSelect: false,
items: [],
itemWillMove: function itemWillMove() {
return true;
},
indeterminateIds: [],
loadingMoreIds: [],
lockedIds: [],
onItemMoved: function onItemMoved() {},
selectedIds: [],
testId: 'list',
toggleExpansion: function toggleExpansion() {},
virtualListRef: undefined
};
var getAdjustedNestingLevel = function getAdjustedNestingLevel(items, currentLevel) {
return items.some(function (item) {
return (item === null || item === void 0 ? void 0 : item.children) && item.children.length > 0;
}) ? currentLevel + 1 : currentLevel;
};
var VirtualListContent = function VirtualListContent(_ref) {
var editingStyle = _ref.editingStyle,
emptyState = _ref.emptyState,
emptySearchState = _ref.emptySearchState,
expandedIds = _ref.expandedIds,
handleLoadMore = _ref.handleLoadMore,
handleSelect = _ref.handleSelect,
i18n = _ref.i18n,
iconPosition = _ref.iconPosition,
indeterminateIds = _ref.indeterminateIds,
isFiltering = _ref.isFiltering,
isFullHeight = _ref.isFullHeight,
isLargeRow = _ref.isLargeRow,
isLoading = _ref.isLoading,
isCheckboxMultiSelect = _ref.isCheckboxMultiSelect,
items = _ref.items,
itemWillMove = _ref.itemWillMove,
getAllowedDropIds = _ref.getAllowedDropIds,
loadingMoreIds = _ref.loadingMoreIds,
lockedIds = _ref.lockedIds,
onItemMoved = _ref.onItemMoved,
selectedIds = _ref.selectedIds,
testId = _ref.testId,
toggleExpansion = _ref.toggleExpansion,
virtualListRefProp = _ref.virtualListRef;
var mergedI18n = React$1.useMemo(function () {
return _objectSpread$1U(_objectSpread$1U({}, defaultProps$24.i18n), i18n);
}, [i18n]);
var rowSize = isLargeRow ? ITEM_HEIGHT_LARGE : ITEM_HEIGHT;
var _useState = React$1.useState(0),
_useState2 = slicedToArray$2(_useState, 2),
listHeight = _useState2[0],
setListHeight = _useState2[1];
var listOuterRef = useResize(React$1.useRef(null));
var didScrollRef = React$1.useRef(false);
var internalVirtualListRef = React$1.useRef(null);
var virtualListRef = virtualListRefProp || internalVirtualListRef;
var renderLoadMore = function renderLoadMore(item, isLoadingMore, level, style) {
var indentation = "".concat(level * ITEM_LEVEL_OFFSET - ITEM_COLUMN_GAP, "px");
return isLoadingMore ? /*#__PURE__*/React__default['default'].createElement("div", {
style: style,
key: "".concat(item.id, "-list-item-load-more"),
className: "".concat(iotPrefix$1L, "--list-item")
}, /*#__PURE__*/React__default['default'].createElement("div", {
style: {
width: indentation
}
}), /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, {
className: "".concat(iotPrefix$1L, "--list--load-more-skeleton"),
width: "30%",
"data-testid": "".concat(testId, "-loading-more")
})) : /*#__PURE__*/React__default['default'].createElement(Button$1, {
key: "".concat(item.id, "-list-item-load-more"),
className: "".concat(iotPrefix$1L, "--list-item ").concat(iotPrefix$1L, "--load-more-row"),
onClick: function onClick() {
return handleLoadMore(item.id);
},
"data-testid": "".concat(testId, "-").concat(item.id, "-load-more"),
kind: "ghost",
style: style
}, /*#__PURE__*/React__default['default'].createElement("div", {
style: {
width: indentation
}
}), /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1L, "--load-more-row--content")
}, mergedI18n.loadMore));
};
var flatten = React$1.useCallback(function (initialItems) {
var parentId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var currentLevel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
return initialItems.reduce(function (carry, item) {
var tmp = carry;
var isExpanded = expandedIds.filter(function (rowId) {
return rowId === item.id;
}).length > 0;
var parentIsExpanded = expandedIds.some(function (rowId) {
return parentId === rowId;
});
if (parentId === null || isExpanded || parentIsExpanded) {
tmp = carry.concat(_objectSpread$1U(_objectSpread$1U({}, item), {}, {
parentId: parentId,
level: currentLevel
}));
}
if (isExpanded && item.children) {
tmp = tmp.concat(flatten(item.children, item.id, currentLevel + 1));
if (item.hasLoadMore && isExpanded) {
tmp = tmp.concat([_objectSpread$1U(_objectSpread$1U({}, item), {}, {
parentId: item.id,
level: currentLevel,
isLoadMoreRow: true
})]);
}
}
if (!item.children && item.hasLoadMore) {
tmp = tmp.concat([_objectSpread$1U(_objectSpread$1U({}, item), {}, {
level: currentLevel,
isLoadMoreRow: true
})]);
}
return tmp;
}, []);
}, [expandedIds]);
var flattenHelper = React$1.useCallback(function () {
var flattenedItems = flatten(items);
var parents = flattenedItems.filter(function (item) {
return item.level === 0 || expandedIds.includes(item.id) || expandedIds.includes(item.parentId);
}).length;
return {
flattenedItems: flattenedItems,
parents: parents
};
}, [expandedIds, flatten, items]);
var _useState3 = React$1.useState(function () {
var _flattenHelper = flattenHelper(),
flattenedItems = _flattenHelper.flattenedItems,
parents = _flattenHelper.parents;
return {
items: flattenedItems,
parents: parents,
height: parents * rowSize
};
}),
_useState4 = slicedToArray$2(_useState3, 2),
flattened = _useState4[0],
setFlattened = _useState4[1];
React$1.useEffect(function () {
if (virtualListRef.current) {
virtualListRef.current.resetAfterIndex(0);
}
}, [expandedIds, flattened, virtualListRef, rowSize]);
React$1.useEffect(function () {
var _flattenHelper2 = flattenHelper(),
flattenedItems = _flattenHelper2.flattenedItems,
parents = _flattenHelper2.parents;
setFlattened({
items: flattenedItems,
parents: parents,
height: parents * rowSize
});
}, [flattenHelper, rowSize]);
var renderItemAndChildren = function renderItemAndChildren(item, index, parentId, level, style) {
var hasChildren = (item === null || item === void 0 ? void 0 : item.children) && item.children.length > 0;
var isSelected = selectedIds.some(function (id) {
return item.id === id;
});
var isExpanded = expandedIds.filter(function (rowId) {
return rowId === item.id;
}).length > 0;
var isLoadingMore = loadingMoreIds.includes(item.id);
var isLocked = lockedIds.includes(item.id);
var isIndeterminate = indeterminateIds.includes(item.id);
var parentIsExpanded = expandedIds.filter(function (rowId) {
return rowId === item.parentId;
}).length > 0;
var _item$content = item.content,
value = _item$content.value,
secondaryValue = _item$content.secondaryValue,
icon = _item$content.icon,
rowActions = _item$content.rowActions,
tags = _item$content.tags,
isSelectable = item.isSelectable,
isCategory = item.isCategory,
disabled = item.disabled;
if (item.isLoadMoreRow) {
if (parentIsExpanded || item.level === 0) {
var loadMoreLevel = parentIsExpanded ? level + 1 : level;
return renderLoadMore(item, isLoadingMore, loadMoreLevel, style);
}
return null;
}
return [/*#__PURE__*/React__default['default'].createElement("div", {
key: "".concat(item.id, "-list-item-parent-").concat(level, "-").concat(value),
className: "".concat(iotPrefix$1L, "--list-item-parent"),
style: style
}, /*#__PURE__*/React__default['default'].createElement(ListItem$1, {
id: item.id,
index: index,
key: "".concat(item.id, "-list-item-").concat(level, "-").concat(value),
nestingLevel: item !== null && item !== void 0 && item.children && item.children.length > 0 ? level - 1 : level,
value: value,
icon: editingStyleIsMultiple(editingStyle) || isSelectable && isCheckboxMultiSelect ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Checkbox, {
id: "".concat(item.id, "-checkbox"),
name: item.value,
"data-testid": "".concat(item.id, "-checkbox"),
labelText: "",
onChange: function onChange() {
return handleSelect(item.id, parentId);
},
onClick: function onClick(event) {
// This is needed as a workaround for a carbon checkbox bug
// https://github.com/carbon-design-system/carbon/issues/10122#issuecomment-984692702
event.stopPropagation();
},
checked: isSelected,
disabled: disabled || isLocked,
indeterminate: isIndeterminate
}) : icon,
disabled: disabled,
iconPosition: iconPosition,
editingStyle: isLocked ? null : editingStyle,
secondaryValue: secondaryValue,
rowActions: rowActions,
onSelect: function onSelect() {
return handleSelect(item.id, parentId);
},
onExpand: toggleExpansion,
onItemMoved: onItemMoved,
itemWillMove: itemWillMove,
getAllowedDropIds: getAllowedDropIds,
selected: isSelected,
expanded: isExpanded,
isExpandable: hasChildren,
isLargeRow: isLargeRow,
isLocked: isLocked,
isCategory: isCategory,
isSelectable: editingStyle === null && isSelectable,
i18n: mergedI18n,
tags: tags,
preventRowFocus: isCheckboxMultiSelect
}))];
};
var getItemSize = function getItemSize(index) {
var _flattened$items;
var item = flattened === null || flattened === void 0 ? void 0 : (_flattened$items = flattened.items) === null || _flattened$items === void 0 ? void 0 : _flattened$items[index];
if (!item) {
return 0;
}
var isExpanded = expandedIds.filter(function (rowId) {
return rowId === item.parentId;
}).length > 0;
if (item.isLoadMoreRow && (isExpanded || item.level === 0)) {
return ITEM_HEIGHT;
}
if (!item.parentId || isExpanded) {
return rowSize;
}
return 0;
}; // eslint-disable-next-line react/prop-types
var ListRow = function ListRow(_ref2) {
var _flattened$items2;
var index = _ref2.index,
style = _ref2.style;
var item = flattened === null || flattened === void 0 ? void 0 : (_flattened$items2 = flattened.items) === null || _flattened$items2 === void 0 ? void 0 : _flattened$items2[index];
if (!item || !(item !== null && item !== void 0 && item.content)) {
return null;
}
var isExpanded = expandedIds.filter(function (rowId) {
return rowId === item.id || rowId === item.parentId;
}).length > 0;
if (item.parentId && !isExpanded) {
return null;
}
return renderItemAndChildren(item, index, item.parentId, getAdjustedNestingLevel(items, item.level), style);
};
var renderEmptyContent = function renderEmptyContent() {
var emptyContent = isFiltering ? emptySearchState : emptyState;
return typeof emptyContent === 'string' ? /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1("".concat(iotPrefix$1L, "--list--empty-state"), defineProperty$d({}, "".concat(iotPrefix$1L, "--list--empty-state__full-height"), isFullHeight))
}, /*#__PURE__*/React__default['default'].createElement(EmptyState, {
icon: isFiltering ? 'no-result' : 'empty',
title: emptyContent,
body: ""
})) : emptyContent;
};
var handleItemsRendered = React$1.useCallback(function () {
var parentList = listOuterRef.current.closest(".".concat(iotPrefix$1L, "--list"));
if (parentList) {
var rect = parentList.getBoundingClientRect();
var height = rect.height;
setListHeight(height);
}
if (didScrollRef.current === false && (selectedIds === null || selectedIds === void 0 ? void 0 : selectedIds.length) > 0 && virtualListRef.current) {
var selectedIndex = flattened.items.findIndex(function (item) {
return item.id === selectedIds[0];
});
if (selectedIndex >= 0) {
virtualListRef.current.scrollToItem(selectedIndex, 'start');
didScrollRef.current = true;
}
}
}, [flattened.items, listOuterRef, selectedIds, virtualListRef]);
if (!isLoading && flattened.items.length) {
return /*#__PURE__*/React__default['default'].createElement(VariableSizeList, {
ref: virtualListRef,
itemCount: flattened.items.length,
height: isFullHeight ? flattened.height : Math.min(listHeight, flattened.height),
itemSize: getItemSize,
className: classnames$1("".concat(iotPrefix$1L, "--list--content"), "".concat(iotPrefix$1L, "--list--content--virtual"), defineProperty$d({}, "".concat(iotPrefix$1L, "--list--content__full-height"), isFullHeight)),
outerRef: listOuterRef,
style: {
overflow: isFullHeight ? 'unset' : 'auto'
},
onItemsRendered: handleItemsRendered
}, ListRow);
}
return /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1(defineProperty$d({}, "".concat(iotPrefix$1L, "--list--content__full-height"), isFullHeight), "".concat(iotPrefix$1L, "--list--content"))
}, isLoading ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, {
className: "".concat(iotPrefix$1L, "--list--skeleton"),
width: "90%",
"data-testid": "".concat(testId, "-loading")
}) : renderEmptyContent());
};
VirtualListContent.propTypes = propTypes$1X;
VirtualListContent.defaultProps = defaultProps$24;
VirtualListContent.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "VirtualListContent",
"props": {
"editingStyle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "EditingStyle.Single",
"computed": true
}, {
"value": "EditingStyle.Multiple",
"computed": true
}, {
"value": "EditingStyle.SingleNesting",
"computed": true
}, {
"value": "EditingStyle.MultipleNesting",
"computed": true
}]
},
"required": false,
"description": "list editing style"
},
"emptyState": {
"defaultValue": {
"value": "'No list items to show'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty"
},
"emptySearchState": {
"defaultValue": {
"value": "'No results found'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty on search"
},
"expandedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of row expanded"
},
"getAllowedDropIds": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback used to limit which items that should get drop targets rendered.\nreceives the id of the item that is being dragged and returns a list of ids."
},
"handleLoadMore": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function for when load more row is clicked (rowId) => {}"
},
"handleSelect": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function of select"
},
"i18n": {
"defaultValue": {
"value": "{\n searchPlaceHolderText: 'Enter a value',\n expand: 'Expand',\n close: 'Close',\n loadMore: 'View more...',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"searchPlaceHolderText": {
"name": "string",
"required": false
},
"expand": {
"name": "string",
"required": false
},
"close": {
"name": "string",
"required": false
},
"loadMore": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "i18n strings"
},
"iconPosition": {
"defaultValue": {
"value": "'left'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'left'",
"computed": false
}, {
"value": "'right'",
"computed": false
}]
},
"required": false,
"description": "icon can be left or right side of list row primary value"
},
"isFiltering": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "if true shows empty search state, instead of empty state, when there are no search results"
},
"isFullHeight": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "custom",
"raw": "(props, propName, componentName) => {\n if (__DEV__) {\n /* istanbul ignore else */\n if (props[propName] === true) {\n return new Error(\n `${componentName}: Using '${propName}' with 'isVirtualList' could have negative performance consequences. Using the them together is discouraged.`\n );\n }\n }\n}"
},
"required": false,
"description": "use full height in list"
},
"isLargeRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use large/fat row in list"
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "optional skeleton to be rendered while loading data"
},
"isCheckboxMultiSelect": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "true if the list should have multiple selectable rows using checkboxes"
},
"items": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": "import { ListItemPropTypes } from '../ListPropTypes';",
"computed": true
}
},
"required": false,
"description": "data source of list items"
},
"itemWillMove": {
"defaultValue": {
"value": "() => {\n return true;\n}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function when reorder will occur - can cancel the move by returning false"
},
"indeterminateIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of selectable rows with indeterminate selection state"
},
"loadingMoreIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "RowIds for rows currently loading more child rows"
},
"lockedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "the ids of locked items that cannot be reordered"
},
"onItemMoved": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function for reorder"
},
"selectedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "Multiple currently selected items"
},
"testId": {
"defaultValue": {
"value": "'list'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"toggleExpansion": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function of expansion"
},
"virtualListRef": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "HtmlElementRefProp"
},
"required": false,
"description": ""
}
}
};
function ownKeys$1T(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$1T(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1T(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1T(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1K = settings$1.iotPrefix;
var propTypes$1W = {
/** Specify an optional className to be applied to the container */
className: PropTypes__default['default'].string,
/** list title */
title: PropTypes__default['default'].string,
/** search bar call back function and search value */
search: PropTypes__default['default'].shape({
onChange: PropTypes__default['default'].func,
value: PropTypes__default['default'].string,
id: PropTypes__default['default'].string,
/** should search be trigger onChange (true) or only on Enter/Blur (false) */
hasFastSearch: PropTypes__default['default'].bool
}),
/** action buttons on right side of list title */
buttons: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
/** Node to override the default header or content */
overrides: PropTypes__default['default'].shape({
header: OverridePropTypes,
content: OverridePropTypes
}),
/** ids of selectable rows with indeterminate selection state */
indeterminateIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** data source of list items */
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape(ListItemPropTypes)),
/** list editing style for Drag and Drop */
editingStyle: PropTypes__default['default'].oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
/** if true shows empty search state, instead of empty state, when there are no search results */
isFiltering: PropTypes__default['default'].bool,
/** use full height in list */
isFullHeight: PropTypes__default['default'].bool,
/** use large/fat row in list */
isLargeRow: PropTypes__default['default'].bool,
/** optional skeleton to be rendered while loading data */
isLoading: PropTypes__default['default'].bool,
/** true if the list should have multiple selectable rows using checkboxes */
isCheckboxMultiSelect: PropTypes__default['default'].bool,
/** optional prop to use a virtualized version of the list instead of rendering all items */
isVirtualList: PropTypes__default['default'].bool,
/** icon can be left or right side of list row primary value */
iconPosition: PropTypes__default['default'].oneOf(['left', 'right']),
/** i18n strings */
i18n: PropTypes__default['default'].shape({
searchPlaceHolderText: PropTypes__default['default'].string,
clearSearchIconDescription: PropTypes__default['default'].string,
expand: PropTypes__default['default'].string,
close: PropTypes__default['default'].string,
loadMore: PropTypes__default['default'].string
}),
/** the ids of locked items that cannot be reordered */
lockedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** Multiple currently selected items */
selectedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** pagination at the bottom of list */
pagination: PropTypes__default['default'].shape(SimplePaginationPropTypes),
/** ids of row expanded */
expandedIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** callback used to limit which items that should get drop targets rendered.
* Receives the id of the item that is being dragged and should return a list of allowed ids.
* Returning an empty list will result in 0 drop targets but returning null will
* enable all items as drop targets */
getAllowedDropIds: PropTypes__default['default'].func,
/** call back function of select */
handleSelect: PropTypes__default['default'].func,
/** call back function of expansion */
toggleExpansion: PropTypes__default['default'].func,
/** callback function for reorder */
onItemMoved: PropTypes__default['default'].func,
/** callback function when reorder will occur - can cancel the move by returning false */
itemWillMove: PropTypes__default['default'].func,
/** content shown if list is empty */
emptyState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
/** content shown if list is empty on search */
emptySearchState: PropTypes__default['default'].oneOfType([PropTypes__default['default'].node, PropTypes__default['default'].string]),
testId: PropTypes__default['default'].string,
/** call back function for when load more row is clicked (rowId) => {} */
handleLoadMore: PropTypes__default['default'].func,
/** RowIds for rows currently loading more child rows */
loadingMoreIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string),
/** called after the row has expanded or collapsed and is passed the array of expanded ids */
onExpandedChange: PropTypes__default['default'].func,
/** enables horizontal scrollbar to appear if content is wider then container */
enableHorizontalScrollbar: PropTypes__default['default'].bool
};
var defaultProps$23 = {
className: null,
title: null,
search: null,
buttons: [],
editingStyle: null,
getAllowedDropIds: null,
overrides: null,
indeterminateIds: [],
isFiltering: false,
isFullHeight: false,
isLargeRow: false,
isLoading: false,
isCheckboxMultiSelect: false,
isVirtualList: false,
i18n: {
searchPlaceHolderText: 'Enter a value',
expand: 'Expand',
close: 'Close',
loadMore: 'View more'
},
iconPosition: 'left',
lockedIds: [],
pagination: null,
selectedIds: [],
expandedIds: [],
loadingMoreIds: [],
items: [],
handleSelect: function handleSelect() {},
toggleExpansion: function toggleExpansion() {},
onItemMoved: function onItemMoved() {},
itemWillMove: function itemWillMove() {
return true;
},
emptyState: 'No list items to show',
emptySearchState: 'No results found',
testId: 'list',
handleLoadMore: function handleLoadMore() {},
onExpandedChange: null,
enableHorizontalScrollbar: false
};
var List = /*#__PURE__*/React$1.forwardRef(function (props, ref) {
var _overrides$header, _overrides$content, _classnames, _overrides$header2, _overrides$header2$pr, _overrides$header3, _overrides$content2;
// Destructuring this way is needed to retain the propTypes and defaultProps
var className = props.className,
title = props.title,
search = props.search,
buttons = props.buttons,
items = props.items,
isFullHeight = props.isFullHeight,
i18n = props.i18n,
lockedIds = props.lockedIds,
pagination = props.pagination,
selectedIds = props.selectedIds,
expandedIds = props.expandedIds,
getAllowedDropIds = props.getAllowedDropIds,
handleSelect = props.handleSelect,
overrides = props.overrides,
toggleExpansion = props.toggleExpansion,
iconPosition = props.iconPosition,
editingStyle = props.editingStyle,
indeterminateIds = props.indeterminateIds,
isLargeRow = props.isLargeRow,
isLoading = props.isLoading,
isFiltering = props.isFiltering,
isCheckboxMultiSelect = props.isCheckboxMultiSelect,
isVirtualList = props.isVirtualList,
onItemMoved = props.onItemMoved,
itemWillMove = props.itemWillMove,
emptyState = props.emptyState,
emptySearchState = props.emptySearchState,
testId = props.testId,
handleLoadMore = props.handleLoadMore,
loadingMoreIds = props.loadingMoreIds,
onExpandedChange = props.onExpandedChange,
enableHorizontalScrollbar = props.enableHorizontalScrollbar;
var mergedI18n = React$1.useMemo(function () {
return _objectSpread$1T(_objectSpread$1T({}, defaultProps$23.i18n), i18n);
}, [i18n]);
var ListHeader$1 = (overrides === null || overrides === void 0 ? void 0 : (_overrides$header = overrides.header) === null || _overrides$header === void 0 ? void 0 : _overrides$header.component) || ListHeader;
var ListContent$1 = overrides !== null && overrides !== void 0 && (_overrides$content = overrides.content) !== null && _overrides$content !== void 0 && _overrides$content.component || isVirtualList ? VirtualListContent : ListContent; // getAllowedDropIds will be called by all list items when a drag is initiated and the
// parameter (id of the dragged item) will be the same until a new drag starts.
var memoizedGetAllowedDropIds = getAllowedDropIds ? memoize$1(getAllowedDropIds) : null;
return /*#__PURE__*/React__default['default'].createElement(DragAndDrop, null, /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId,
className: classnames$1("".concat(iotPrefix$1K, "--list"), className, (_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$1K, "--list__full-height"), isFullHeight), defineProperty$d(_classnames, "".concat(iotPrefix$1K, "--list--virtual"), isVirtualList), _classnames))
}, /*#__PURE__*/React__default['default'].createElement(ListHeader$1, _extends_1$1({
className: classnames$1("".concat(iotPrefix$1K, "--list--header"), overrides === null || overrides === void 0 ? void 0 : (_overrides$header2 = overrides.header) === null || _overrides$header2 === void 0 ? void 0 : (_overrides$header2$pr = _overrides$header2.props) === null || _overrides$header2$pr === void 0 ? void 0 : _overrides$header2$pr.className),
title: title,
buttons: buttons,
search: search,
i18n: mergedI18n,
testId: "".concat(testId, "-header")
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$header3 = overrides.header) === null || _overrides$header3 === void 0 ? void 0 : _overrides$header3.props)), /*#__PURE__*/React__default['default'].createElement(ListContent$1, _extends_1$1({
emptyState: emptyState,
emptySearchState: emptySearchState,
items: items,
isFullHeight: isFullHeight,
testId: testId,
indeterminateIds: indeterminateIds,
isFiltering: isFiltering,
isLoading: isLoading,
isCheckboxMultiSelect: isCheckboxMultiSelect,
selectedIds: selectedIds,
expandedIds: expandedIds,
getAllowedDropIds: memoizedGetAllowedDropIds,
handleSelect: handleSelect,
toggleExpansion: toggleExpansion,
iconPosition: iconPosition,
editingStyle: editingStyle,
isLargeRow: isLargeRow,
onItemMoved: onItemMoved,
itemWillMove: itemWillMove,
handleLoadMore: handleLoadMore,
loadingMoreIds: loadingMoreIds,
selectedItemRef: ref,
i18n: mergedI18n,
lockedIds: lockedIds,
onExpandedChange: onExpandedChange,
enableHorizontalScrollbar: enableHorizontalScrollbar
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$content2 = overrides.content) === null || _overrides$content2 === void 0 ? void 0 : _overrides$content2.props)), pagination && !isLoading ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1K, "--list--page")
}, /*#__PURE__*/React__default['default'].createElement(SimplePagination, _extends_1$1({}, pagination, {
size: "md"
}))) : null));
});
List.displayName = 'List';
List.propTypes = propTypes$1W;
List.defaultProps = defaultProps$23;
List.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "List",
"props": {
"className": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Specify an optional className to be applied to the container"
},
"title": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "list title"
},
"search": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "shape",
"value": {
"onChange": {
"name": "func",
"required": false
},
"value": {
"name": "string",
"required": false
},
"id": {
"name": "string",
"required": false
},
"hasFastSearch": {
"name": "bool",
"description": "should search be trigger onChange (true) or only on Enter/Blur (false)",
"required": false
}
}
},
"required": false,
"description": "search bar call back function and search value"
},
"buttons": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "node"
}
},
"required": false,
"description": "action buttons on right side of list title"
},
"editingStyle": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "EditingStyle.Single",
"computed": true
}, {
"value": "EditingStyle.Multiple",
"computed": true
}, {
"value": "EditingStyle.SingleNesting",
"computed": true
}, {
"value": "EditingStyle.MultipleNesting",
"computed": true
}]
},
"required": false,
"description": "list editing style for Drag and Drop"
},
"getAllowedDropIds": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback used to limit which items that should get drop targets rendered.\nReceives the id of the item that is being dragged and should return a list of allowed ids.\nReturning an empty list will result in 0 drop targets but returning null will\nenable all items as drop targets"
},
"overrides": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "shape",
"value": {
"header": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"content": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
}
}
},
"required": false,
"description": "Node to override the default header or content"
},
"indeterminateIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of selectable rows with indeterminate selection state"
},
"isFiltering": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "if true shows empty search state, instead of empty state, when there are no search results"
},
"isFullHeight": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use full height in list"
},
"isLargeRow": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "use large/fat row in list"
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "optional skeleton to be rendered while loading data"
},
"isCheckboxMultiSelect": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "true if the list should have multiple selectable rows using checkboxes"
},
"isVirtualList": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "optional prop to use a virtualized version of the list instead of rendering all items"
},
"i18n": {
"defaultValue": {
"value": "{\n searchPlaceHolderText: 'Enter a value',\n expand: 'Expand',\n close: 'Close',\n loadMore: 'View more',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"searchPlaceHolderText": {
"name": "string",
"required": false
},
"clearSearchIconDescription": {
"name": "string",
"required": false
},
"expand": {
"name": "string",
"required": false
},
"close": {
"name": "string",
"required": false
},
"loadMore": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "i18n strings"
},
"iconPosition": {
"defaultValue": {
"value": "'left'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "'left'",
"computed": false
}, {
"value": "'right'",
"computed": false
}]
},
"required": false,
"description": "icon can be left or right side of list row primary value"
},
"lockedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "the ids of locked items that cannot be reordered"
},
"pagination": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "shape",
"value": "import SimplePagination, { SimplePaginationPropTypes } from '../SimplePagination/SimplePagination';",
"computed": true
},
"required": false,
"description": "pagination at the bottom of list"
},
"selectedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "Multiple currently selected items"
},
"expandedIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "ids of row expanded"
},
"loadingMoreIds": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "string"
}
},
"required": false,
"description": "RowIds for rows currently loading more child rows"
},
"items": {
"defaultValue": {
"value": "[]",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": "import { ListItemPropTypes } from './ListPropTypes';",
"computed": true
}
},
"required": false,
"description": "data source of list items"
},
"handleSelect": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function of select"
},
"toggleExpansion": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function of expansion"
},
"onItemMoved": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function for reorder"
},
"itemWillMove": {
"defaultValue": {
"value": "() => {\n return true;\n}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "callback function when reorder will occur - can cancel the move by returning false"
},
"emptyState": {
"defaultValue": {
"value": "'No list items to show'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty"
},
"emptySearchState": {
"defaultValue": {
"value": "'No results found'",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "node"
}, {
"name": "string"
}]
},
"required": false,
"description": "content shown if list is empty on search"
},
"testId": {
"defaultValue": {
"value": "'list'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"handleLoadMore": {
"defaultValue": {
"value": "() => {}",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "call back function for when load more row is clicked (rowId) => {}"
},
"onExpandedChange": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "called after the row has expanded or collapsed and is passed the array of expanded ids"
},
"enableHorizontalScrollbar": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "enables horizontal scrollbar to appear if content is wider then container"
}
}
};
var ViewsPropType = PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
/** The ID of the view */
id: PropTypes__default['default'].string,
/** True if this view is public, False if private */
isPublic: PropTypes__default['default'].bool,
/** True if this the user can edit this view */
isEditable: PropTypes__default['default'].bool,
/** True if this the user can delete this view */
isDeleteable: PropTypes__default['default'].bool,
/** The name of the view */
title: PropTypes__default['default'].string,
/** A string that describes what this view contains */
description: PropTypes__default['default'].string
}));
function ownKeys$1S(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$1S(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1S(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1S(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1J = settings$1.iotPrefix;
var renderButton = function renderButton(id, _onClick, icon, key, iconText) {
return /*#__PURE__*/React__default['default'].createElement(Button$1, {
key: key,
testId: key,
hasIconOnly: true,
iconDescription: iconText,
kind: "ghost",
onClick: function onClick() {
_onClick(id);
},
renderIcon: icon,
size: "small",
tooltipAlignment: "center",
tooltipPosition: "left"
});
};
var getRowActions = function getRowActions(_ref, _ref2) {
var id = _ref.id,
isEditable = _ref.isEditable,
isDeleteable = _ref.isDeleteable;
var onEdit = _ref2.onEdit,
onDelete = _ref2.onDelete,
_ref2$i18n = _ref2.i18n,
editIconText = _ref2$i18n.editIconText,
deleteIconText = _ref2$i18n.deleteIconText,
testID = _ref2.testID;
var rowActions = [];
if (isEditable) {
var editItemKey = "".concat(testID, "-row-action-").concat(id, "-edit");
var editButton = renderButton(id, onEdit, iconsReact.Edit16, editItemKey, editIconText);
rowActions.push(editButton);
}
if (isDeleteable) {
var deleteItemKey = "".concat(testID, "-row-action-").concat(id, "-delete");
var deleteButton = renderButton(id, onDelete, iconsReact.TrashCan16, deleteItemKey, deleteIconText);
rowActions.push(deleteButton);
}
return rowActions;
};
var getRowDescription = function getRowDescription(_ref3) {
var description = _ref3.description;
return description;
};
var getRowTags = function getRowTags(_ref4, _ref5) {
var id = _ref4.id;
var defaultViewId = _ref5.defaultViewId,
defaultLabelText = _ref5.i18n.defaultLabelText;
return id === defaultViewId ? [/*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tag, {
type: "blue",
key: "defaultTag"
}, defaultLabelText)] : undefined;
};
var getRowTitle = function getRowTitle(_ref6, publicLabelText, privateLabelText) {
var title = _ref6.title,
isPublic = _ref6.isPublic;
return "".concat(title, " (").concat(isPublic ? publicLabelText : privateLabelText, ")");
};
var propTypes$1V = {
/** The ID of the view that should be marked as default */
defaultViewId: PropTypes__default['default'].string,
/** Internationalisation strings */
i18n: PropTypes__default['default'].shape({
listTitle: PropTypes__default['default'].string,
privateLabelText: PropTypes__default['default'].string,
publicLabelText: PropTypes__default['default'].string
}).isRequired,
/** optional skeleton to be rendered while loading data */
isLoading: PropTypes__default['default'].bool,
/** Used to overide the internal components and props for advanced customisation */
overrides: PropTypes__default['default'].shape({
list: OverridePropTypes
}),
/** SimplePagination at the bottom of list */
pagination: PropTypes__default['default'].shape(SimplePaginationPropTypes),
/** Render prop that takes a view and the props obj and returns the rendered actions in an array */
rowActionsRenderer: PropTypes__default['default'].func,
/** Render prop that takes a view and props obj and returns the rendered tags in an array */
rowTagsRenderer: PropTypes__default['default'].func,
/** Function prop that takes a view, public label and private label and returns the title as a string */
rowTitleInterpolation: PropTypes__default['default'].func,
/** Function prop that takes a view and returns the description as a string */
rowDescriptionInterpolation: PropTypes__default['default'].func,
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
/** Id that can be used for testing */
testId: PropTypes__default['default'].string,
/** The views to currently be displayed */
views: ViewsPropType.isRequired
};
var defaultProps$22 = {
defaultViewId: undefined,
isLoading: false,
overrides: undefined,
pagination: undefined,
rowActionsRenderer: undefined,
rowDescriptionInterpolation: undefined,
rowTagsRenderer: undefined,
rowTitleInterpolation: undefined,
testId: 'TableManageViewsList'
};
var TableManageViewsList = function TableManageViewsList(_ref7) {
var _overrides$list, _overrides$list2;
var defaultViewId = _ref7.defaultViewId,
_ref7$i18n = _ref7.i18n,
listTitle = _ref7$i18n.listTitle,
privateLabelText = _ref7$i18n.privateLabelText,
publicLabelText = _ref7$i18n.publicLabelText,
i18n = objectWithoutProperties$1(_ref7$i18n, ["listTitle", "privateLabelText", "publicLabelText"]),
isLoading = _ref7.isLoading,
overrides = _ref7.overrides,
pagination = _ref7.pagination,
_ref7$rowActionsRende = _ref7.rowActionsRenderer,
rowActionsRenderer = _ref7$rowActionsRende === void 0 ? getRowActions : _ref7$rowActionsRende,
_ref7$rowDescriptionI = _ref7.rowDescriptionInterpolation,
rowDescriptionInterpolation = _ref7$rowDescriptionI === void 0 ? getRowDescription : _ref7$rowDescriptionI,
_ref7$rowTagsRenderer = _ref7.rowTagsRenderer,
rowTagsRenderer = _ref7$rowTagsRenderer === void 0 ? getRowTags : _ref7$rowTagsRenderer,
_ref7$rowTitleInterpo = _ref7.rowTitleInterpolation,
rowTitleInterpolation = _ref7$rowTitleInterpo === void 0 ? getRowTitle : _ref7$rowTitleInterpo,
testID = _ref7.testID,
testId = _ref7.testId,
views = _ref7.views,
props = objectWithoutProperties$1(_ref7, ["defaultViewId", "i18n", "isLoading", "overrides", "pagination", "rowActionsRenderer", "rowDescriptionInterpolation", "rowTagsRenderer", "rowTitleInterpolation", "testID", "testId", "views"]);
var MyList = (overrides === null || overrides === void 0 ? void 0 : (_overrides$list = overrides.list) === null || _overrides$list === void 0 ? void 0 : _overrides$list.component) || List;
var listItems = views.map(function (view) {
var id = view.id;
return {
content: {
rowActions: function rowActions() {
return rowActionsRenderer(view, _objectSpread$1S(_objectSpread$1S({}, props), {}, {
i18n: i18n,
testID: testID
}));
},
secondaryValue: rowDescriptionInterpolation(view),
tags: rowTagsRenderer(view, _objectSpread$1S(_objectSpread$1S({}, props), {}, {
defaultViewId: defaultViewId,
i18n: i18n
})),
value: rowTitleInterpolation(view, publicLabelText, privateLabelText)
},
id: id
};
});
return /*#__PURE__*/React__default['default'].createElement(MyList, _extends_1$1({
testID: testID || testId,
className: "".concat(iotPrefix$1J, "--manage-views-list"),
isFullHeight: true,
isLargeRow: true,
isLoading: isLoading,
items: listItems,
title: listTitle,
pagination: pagination
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$list2 = overrides.list) === null || _overrides$list2 === void 0 ? void 0 : _overrides$list2.props));
};
TableManageViewsList.propTypes = propTypes$1V;
TableManageViewsList.defaultProps = defaultProps$22;
TableManageViewsList.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableManageViewsList",
"props": {
"rowActionsRenderer": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Render prop that takes a view and the props obj and returns the rendered actions in an array"
},
"rowDescriptionInterpolation": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Function prop that takes a view and returns the description as a string"
},
"rowTagsRenderer": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Render prop that takes a view and props obj and returns the rendered tags in an array"
},
"rowTitleInterpolation": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Function prop that takes a view, public label and private label and returns the title as a string"
},
"defaultViewId": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "The ID of the view that should be marked as default"
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "optional skeleton to be rendered while loading data"
},
"overrides": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": {
"list": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
}
}
},
"required": false,
"description": "Used to overide the internal components and props for advanced customisation"
},
"pagination": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": "import { SimplePaginationPropTypes } from '../../SimplePagination/SimplePagination';",
"computed": true
},
"required": false,
"description": "SimplePagination at the bottom of list"
},
"testId": {
"defaultValue": {
"value": "'TableManageViewsList'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Id that can be used for testing"
},
"i18n": {
"type": {
"name": "shape",
"value": {
"listTitle": {
"name": "string",
"required": false
},
"privateLabelText": {
"name": "string",
"required": false
},
"publicLabelText": {
"name": "string",
"required": false
}
}
},
"required": true,
"description": "Internationalisation strings"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
},
"views": {
"type": {
"name": "custom",
"raw": "ViewsPropType.isRequired"
},
"required": false,
"description": "The views to currently be displayed"
}
}
};
var iotPrefix$1I = settings$1.iotPrefix;
var propTypes$1U = {
/**
* Callbacks for the actions of the modal
* onEdit : Called when the user clicks edit on a view row. The ID of the view is passed as argument.
* onDelete : Called when the user clicks delete on a view row. The ID of the view is passed as argument.
* onClearError : Called when the dialog error msg is cleared
* onSearchChange : Called when the search input value is changed, the search term is passed as argument.
* onDisplayPublicChange : Called when view title input value is changed, a bool value is passed as argument.
*/
actions: PropTypes__default['default'].shape({
onClose: PropTypes__default['default'].func,
onEdit: PropTypes__default['default'].func,
onDelete: PropTypes__default['default'].func,
onClearError: PropTypes__default['default'].func,
onSearchChange: PropTypes__default['default'].func.isRequired,
onDisplayPublicChange: PropTypes__default['default'].func.isRequired
}).isRequired,
/** The ID of the view that should be marked as default if any */
defaultViewId: PropTypes__default['default'].string,
/** True means that the 'display public' checkbox is checked by default */
displayPublicDefaultChecked: PropTypes__default['default'].bool,
/** Shows this string as a general modal error when present */
error: PropTypes__default['default'].string,
/** Internationalization strings object */
i18n: PropTypes__default['default'].shape({
closeIconDescription: PropTypes__default['default'].string,
defaultLabelText: PropTypes__default['default'].string,
deleteIconText: PropTypes__default['default'].string,
deleteWarningTextTemplate: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].string]),
deleteWarningCancel: PropTypes__default['default'].string,
deleteWarningConfirm: PropTypes__default['default'].string,
editIconText: PropTypes__default['default'].string,
listTitle: PropTypes__default['default'].string,
modalTitle: PropTypes__default['default'].string,
privateLabelText: PropTypes__default['default'].string,
publicLabelText: PropTypes__default['default'].string,
publicCheckboxLabelText: PropTypes__default['default'].string,
searchPlaceholderText: PropTypes__default['default'].string,
searchClearButtonLabelText: PropTypes__default['default'].string,
searchIconLabelText: PropTypes__default['default'].string
}),
/** Shows loading skeleton and disables pagination when true */
isLoading: PropTypes__default['default'].bool,
/** The default value of the search field value */
searchValueDefault: PropTypes__default['default'].string,
/** Determines if the modal is open or closed (i.e. visible or not to the user) */
open: PropTypes__default['default'].bool.isRequired,
/** Used to override the internal components and props for advanced customization */
overrides: PropTypes__default['default'].shape({
mainModal: OverridePropTypes,
publicCheckbox: OverridePropTypes,
search: OverridePropTypes,
tableManageViewsList: OverridePropTypes,
warningModal: OverridePropTypes
}),
/** pagination at the bottom of list, see SimplePaginationPropTypes */
pagination: PropTypes__default['default'].shape(SimplePaginationPropTypes),
// TODO: remove deprecated 'testID' in v3
// eslint-disable-next-line react/require-default-props
testID: deprecate$2(PropTypes__default['default'].string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
/** Id that can be used for testing */
testId: PropTypes__default['default'].string,
/** The views to be displayed in the list, see ViewsPropType */
views: ViewsPropType.isRequired
};
var defaultProps$21 = {
defaultViewId: undefined,
displayPublicDefaultChecked: true,
error: undefined,
i18n: {
closeIconDescription: 'Close',
defaultLabelText: 'default',
deleteIconText: 'delete',
deleteWarningTextTemplate: function deleteWarningTextTemplate(label) {
return "You are about to delete view ".concat(label, ".");
},
deleteWarningCancel: 'Cancel',
deleteWarningConfirm: 'Delete',
editIconText: 'edit',
listTitle: 'Available Views',
modalTitle: 'Manage views',
privateLabelText: 'Private',
publicLabelText: 'Public',
publicCheckboxLabelText: 'Display public views',
searchPlaceholderText: 'Search views',
searchClearButtonLabelText: 'Clear search input',
searchIconLabelText: 'Search'
},
isLoading: false,
overrides: undefined,
searchValueDefault: '',
testId: 'TableManageViewsModal',
pagination: undefined
};
var defaultFunc = function defaultFunc() {};
var TableManageViewsModal = function TableManageViewsModal(_ref) {
var _overrides$mainModal, _overrides$search, _overrides$publicChec, _overrides$tableManag, _overrides$warningMod, _overrides$mainModal2, _overrides$search2, _overrides$publicChec2, _overrides$tableManag2, _overrides$warningMod2;
var _ref$actions = _ref.actions,
_ref$actions$onEdit = _ref$actions.onEdit,
onEdit = _ref$actions$onEdit === void 0 ? defaultFunc : _ref$actions$onEdit,
_ref$actions$onDelete = _ref$actions.onDelete,
onDelete = _ref$actions$onDelete === void 0 ? defaultFunc : _ref$actions$onDelete,
_ref$actions$onClearE = _ref$actions.onClearError,
onClearError = _ref$actions$onClearE === void 0 ? defaultFunc : _ref$actions$onClearE,
onClose = _ref$actions.onClose,
onSearchChange = _ref$actions.onSearchChange,
onDisplayPublicChange = _ref$actions.onDisplayPublicChange,
defaultViewId = _ref.defaultViewId,
displayPublicDefaultChecked = _ref.displayPublicDefaultChecked,
error = _ref.error,
i18n = _ref.i18n,
isLoading = _ref.isLoading,
open = _ref.open,
overrides = _ref.overrides,
pagination = _ref.pagination,
searchValueDefault = _ref.searchValueDefault,
testID = _ref.testID,
testId = _ref.testId,
views = _ref.views;
var _useMerged = useMerged(defaultProps$21.i18n, i18n),
closeIconDescription = _useMerged.closeIconDescription,
deleteWarningTextTemplate = _useMerged.deleteWarningTextTemplate,
deleteWarningCancel = _useMerged.deleteWarningCancel,
deleteWarningConfirm = _useMerged.deleteWarningConfirm,
modalTitle = _useMerged.modalTitle,
publicCheckboxLabelText = _useMerged.publicCheckboxLabelText,
searchPlaceholderText = _useMerged.searchPlaceholderText,
searchClearButtonLabelText = _useMerged.searchClearButtonLabelText,
searchIconLabelText = _useMerged.searchIconLabelText,
mergedI18n = objectWithoutProperties$1(_useMerged, ["closeIconDescription", "deleteWarningTextTemplate", "deleteWarningCancel", "deleteWarningConfirm", "modalTitle", "publicCheckboxLabelText", "searchPlaceholderText", "searchClearButtonLabelText", "searchIconLabelText"]);
var primaryInputId = 'manage-views-modal-search';
var MyMainModal = (overrides === null || overrides === void 0 ? void 0 : (_overrides$mainModal = overrides.mainModal) === null || _overrides$mainModal === void 0 ? void 0 : _overrides$mainModal.component) || ComposedModal;
var MySearch = (overrides === null || overrides === void 0 ? void 0 : (_overrides$search = overrides.search) === null || _overrides$search === void 0 ? void 0 : _overrides$search.component) || carbonComponentsReact.Search;
var MyPublicCheckbox = (overrides === null || overrides === void 0 ? void 0 : (_overrides$publicChec = overrides.publicCheckbox) === null || _overrides$publicChec === void 0 ? void 0 : _overrides$publicChec.component) || carbonComponentsReact.Checkbox;
var MyTableManageViewsList = (overrides === null || overrides === void 0 ? void 0 : (_overrides$tableManag = overrides.tableManageViewsList) === null || _overrides$tableManag === void 0 ? void 0 : _overrides$tableManag.component) || TableManageViewsList;
var MyWarningModal = (overrides === null || overrides === void 0 ? void 0 : (_overrides$warningMod = overrides.warningModal) === null || _overrides$warningMod === void 0 ? void 0 : _overrides$warningMod.component) || carbonComponentsReact.Modal;
var _useState = React$1.useState(false),
_useState2 = slicedToArray$2(_useState, 2),
showDeleteWarning = _useState2[0],
setShowDeleteWarning = _useState2[1];
var _useState3 = React$1.useState(null),
_useState4 = slicedToArray$2(_useState3, 2),
viewIdToDelete = _useState4[0],
setViewIdToDelete = _useState4[1];
var getDeleteWarningText = function getDeleteWarningText() {
var viewTitle = views.find(function (view) {
return view.id === viewIdToDelete;
}).title;
return typeof deleteWarningTextTemplate === 'function' ? deleteWarningTextTemplate(viewTitle) : deleteWarningTextTemplate.replace('{0}', viewTitle);
};
var onShowWarning = function onShowWarning(id) {
setViewIdToDelete(id);
setShowDeleteWarning(true);
};
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(MyMainModal, _extends_1$1({
className: "".concat(iotPrefix$1I, "--manage-views-modal") // TODO: remove deprecated 'testID' in v3.
,
testID: testID || testId,
error: error,
header: {
title: modalTitle
},
iconDescription: closeIconDescription,
onClearError: onClearError,
onClose: onClose,
open: open,
passiveModal: true,
selectorPrimaryFocus: "#".concat(primaryInputId)
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$mainModal2 = overrides.mainModal) === null || _overrides$mainModal2 === void 0 ? void 0 : _overrides$mainModal2.props), /*#__PURE__*/React__default['default'].createElement("div", {
className: "".concat(iotPrefix$1I, "--manage-views-modal__filter-container")
}, /*#__PURE__*/React__default['default'].createElement(MySearch, _extends_1$1({
className: "".concat(iotPrefix$1I, "--manage-views-modal__search"),
defaultValue: searchValueDefault,
closeButtonLabelText: searchClearButtonLabelText,
id: primaryInputId,
name: "searchValue",
labelText: searchIconLabelText,
onChange: function onChange(evt) {
var _evt$target;
return onSearchChange(evt === null || evt === void 0 ? void 0 : (_evt$target = evt.target) === null || _evt$target === void 0 ? void 0 : _evt$target.value);
},
placeholder: searchPlaceholderText,
size: "lg",
type: "text"
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$search2 = overrides.search) === null || _overrides$search2 === void 0 ? void 0 : _overrides$search2.props)), /*#__PURE__*/React__default['default'].createElement(MyPublicCheckbox, _extends_1$1({
name: "isPublic" // TODO: remove deprecated 'testID' in v3.
,
"data-testid": "".concat(testID || testId, "-public-checkbox"),
defaultChecked: displayPublicDefaultChecked,
id: "manage-views-modal-public-checkbox-label",
labelText: publicCheckboxLabelText,
wrapperClassName: "".concat(iotPrefix$1I, "--manage-views-modal__public-checkbox"),
onChange: function onChange(isPublic) {
return onDisplayPublicChange(isPublic);
}
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$publicChec2 = overrides.publicCheckbox) === null || _overrides$publicChec2 === void 0 ? void 0 : _overrides$publicChec2.props))), /*#__PURE__*/React__default['default'].createElement(MyTableManageViewsList, _extends_1$1({
defaultViewId: defaultViewId,
i18n: mergedI18n,
isLoading: isLoading,
onEdit: onEdit,
onDelete: onShowWarning,
pagination: pagination // TODO: remove deprecated 'testID' in v3.
,
testID: "".concat(testID || testId, "-views-list"),
views: views
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$tableManag2 = overrides.tableManageViewsList) === null || _overrides$tableManag2 === void 0 ? void 0 : _overrides$tableManag2.props))), showDeleteWarning && /*#__PURE__*/React__default['default'].createElement(MyWarningModal, _extends_1$1({
className: "".concat(iotPrefix$1I, "--manage-views-modal-warning"),
closeButtonLabel: closeIconDescription,
modalHeading: getDeleteWarningText(),
onRequestClose: function onRequestClose() {
setShowDeleteWarning(false);
},
onRequestSubmit: function onRequestSubmit() {
onDelete(viewIdToDelete);
setShowDeleteWarning(false);
},
open: showDeleteWarning,
primaryButtonText: deleteWarningConfirm,
secondaryButtonText: deleteWarningCancel,
size: "sm"
}, overrides === null || overrides === void 0 ? void 0 : (_overrides$warningMod2 = overrides.warningModal) === null || _overrides$warningMod2 === void 0 ? void 0 : _overrides$warningMod2.props)));
};
TableManageViewsModal.propTypes = propTypes$1U;
TableManageViewsModal.defaultProps = defaultProps$21;
TableManageViewsModal.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "TableManageViewsModal",
"props": {
"defaultViewId": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "The ID of the view that should be marked as default if any"
},
"displayPublicDefaultChecked": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "True means that the 'display public' checkbox is checked by default"
},
"error": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "string"
},
"required": false,
"description": "Shows this string as a general modal error when present"
},
"i18n": {
"defaultValue": {
"value": "{\n closeIconDescription: 'Close',\n defaultLabelText: 'default',\n deleteIconText: 'delete',\n deleteWarningTextTemplate: (label) => `You are about to delete view ${label}.`,\n deleteWarningCancel: 'Cancel',\n deleteWarningConfirm: 'Delete',\n editIconText: 'edit',\n listTitle: 'Available Views',\n modalTitle: 'Manage views',\n privateLabelText: 'Private',\n publicLabelText: 'Public',\n publicCheckboxLabelText: 'Display public views',\n searchPlaceholderText: 'Search views',\n searchClearButtonLabelText: 'Clear search input',\n searchIconLabelText: 'Search',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"closeIconDescription": {
"name": "string",
"required": false
},
"defaultLabelText": {
"name": "string",
"required": false
},
"deleteIconText": {
"name": "string",
"required": false
},
"deleteWarningTextTemplate": {
"name": "union",
"value": [{
"name": "func"
}, {
"name": "string"
}],
"required": false
},
"deleteWarningCancel": {
"name": "string",
"required": false
},
"deleteWarningConfirm": {
"name": "string",
"required": false
},
"editIconText": {
"name": "string",
"required": false
},
"listTitle": {
"name": "string",
"required": false
},
"modalTitle": {
"name": "string",
"required": false
},
"privateLabelText": {
"name": "string",
"required": false
},
"publicLabelText": {
"name": "string",
"required": false
},
"publicCheckboxLabelText": {
"name": "string",
"required": false
},
"searchPlaceholderText": {
"name": "string",
"required": false
},
"searchClearButtonLabelText": {
"name": "string",
"required": false
},
"searchIconLabelText": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": "Internationalization strings object"
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Shows loading skeleton and disables pagination when true"
},
"overrides": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": {
"mainModal": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"publicCheckbox": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"search": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"tableManageViewsList": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
},
"warningModal": {
"name": "custom",
"raw": "OverridePropTypes",
"required": false
}
}
},
"required": false,
"description": "Used to override the internal components and props for advanced customization"
},
"searchValueDefault": {
"defaultValue": {
"value": "''",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "The default value of the search field value"
},
"testId": {
"defaultValue": {
"value": "'TableManageViewsModal'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Id that can be used for testing"
},
"pagination": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "shape",
"value": "import { SimplePaginationPropTypes } from '../../SimplePagination/SimplePagination';",
"computed": true
},
"required": false,
"description": "pagination at the bottom of list, see SimplePaginationPropTypes"
},
"actions": {
"type": {
"name": "shape",
"value": {
"onClose": {
"name": "func",
"required": false
},
"onEdit": {
"name": "func",
"required": false
},
"onDelete": {
"name": "func",
"required": false
},
"onClearError": {
"name": "func",
"required": false
},
"onSearchChange": {
"name": "func",
"required": true
},
"onDisplayPublicChange": {
"name": "func",
"required": true
}
}
},
"required": true,
"description": "Callbacks for the actions of the modal\nonEdit : Called when the user clicks edit on a view row. The ID of the view is passed as argument.\nonDelete : Called when the user clicks delete on a view row. The ID of the view is passed as argument.\nonClearError : Called when the dialog error msg is cleared\nonSearchChange : Called when the search input value is changed, the search term is passed as argument.\nonDisplayPublicChange : Called when view title input value is changed, a bool value is passed as argument."
},
"open": {
"type": {
"name": "bool"
},
"required": true,
"description": "Determines if the modal is open or closed (i.e. visible or not to the user)"
},
"testID": {
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
},
"required": false,
"description": ""
},
"views": {
"type": {
"name": "custom",
"raw": "ViewsPropType.isRequired"
},
"required": false,
"description": "The views to be displayed in the list, see ViewsPropType"
}
}
};
var iotPrefix$1H = settings$1.iotPrefix;
var IDPropTypes = PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].number]);
var ProgressStep = function ProgressStep(_ref) {
var _classnames4;
var id = _ref.id,
label = _ref.label,
secondaryLabel = _ref.secondaryLabel,
description = _ref.description,
onClick = _ref.onClick,
disabled = _ref.disabled,
showLabel = _ref.showLabel,
stepWidth = _ref.stepWidth,
vertical = _ref.vertical,
invalid = _ref.invalid,
stepNumber = _ref.stepNumber,
lastItem = _ref.lastItem,
isClickable = _ref.isClickable,
current = _ref.current,
complete = _ref.complete,
incomplete = _ref.incomplete,
mainStep = _ref.mainStep,
subStep = _ref.subStep,
spaceEqually = _ref.spaceEqually;
var accessible = isClickable && !disabled && !current;
var handleClick = function handleClick() {
if (onClick) {
onClick(id);
}
};
var handleKeyDown = function handleKeyDown(e) {
if (matches(e, [Enter, Space])) {
handleClick();
}
};
var getStepWidth = function getStepWidth() {
if (stepWidth != null && stepWidth > 0 && !spaceEqually) {
return vertical ? {
height: "".concat(stepWidth, "rem"),
minHeight: "".concat(stepWidth, "rem")
} : {
width: "".concat(stepWidth, "rem"),
minWidth: "".concat(stepWidth, "rem")
};
}
if (spaceEqually) {
return {
flexGrow: 1
};
}
return undefined;
};
var StepIcon = function StepIcon() {
var completed = complete && !disabled && !invalid;
var value;
if (mainStep) {
if (completed) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.CheckmarkOutline24, null);
} else if (invalid) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.Warning24, null);
} else {
var number = /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("text", {
x: "50%",
y: "55%",
dominantBaseline: "middle",
textAnchor: "middle"
}, stepNumber));
if (current) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.CircleFilled24, null, number);
} else {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.RadioButton24, null, number);
}
}
} else if (completed) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.CheckmarkOutline16, null);
} else if (invalid) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.Warning16, null);
} else if (current) {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.CircleFilled16, null);
} else {
value = /*#__PURE__*/React__default['default'].createElement(iconsReact.RadioButton16, null);
}
return /*#__PURE__*/React__default['default'].createElement("span", {
className: "".concat(iotPrefix$1H, "--progress-step-icon"),
title: description
}, value);
};
var StepLine = function StepLine() {
var _classnames;
var classes = classnames$1((_classnames = {}, defineProperty$d(_classnames, "".concat(iotPrefix$1H, "--progress-step-line"), !complete && !subStep), defineProperty$d(_classnames, "".concat(iotPrefix$1H, "--progress-step-line--sub"), !complete && subStep), defineProperty$d(_classnames, "".concat(iotPrefix$1H, "--progress-step-line--complete"), complete && !subStep), defineProperty$d(_classnames, "".concat(iotPrefix$1H, "--progress-step-line--sub-complete"), complete && subStep), _classnames));
return !lastItem ? /*#__PURE__*/React__default['default'].createElement("div", {
className: classes
}) : null;
};
var StepLabel = function StepLabel() {
return /*#__PURE__*/React__default['default'].createElement("p", {
className: "".concat(iotPrefix$1H, "--progress-text-label"),
value: description,
title: label
}, label);
};
var StepSecondaryLabel = function StepSecondaryLabel() {
return secondaryLabel !== null && secondaryLabel !== undefined ? /*#__PURE__*/React__default['default'].createElement("p", {
className: "".concat(iotPrefix$1H, "--progress-text-label--optional"),
title: secondaryLabel
}, secondaryLabel) : null;
};
var StepButton = function StepButton() {
var _classnames2, _classnames3;
var buttonClasses = classnames$1((_classnames2 = {}, defineProperty$d(_classnames2, "".concat(iotPrefix$1H, "--progress-step-button"), true), defineProperty$d(_classnames2, "".concat(iotPrefix$1H, "--progress-step-button--main-step"), mainStep), defineProperty$d(_classnames2, "".concat(iotPrefix$1H, "--progress-step-button--sub-step"), subStep), defineProperty$d(_classnames2, "".concat(iotPrefix$1H, "--progress-step-button--clickable"), accessible), _classnames2));
var textClasses = classnames$1((_classnames3 = {}, defineProperty$d(_classnames3, "".concat(iotPrefix$1H, "--progress-text"), true), defineProperty$d(_classnames3, "".concat(iotPrefix$1H, "--progress-text--hidden"), !showLabel && !current), _classnames3)); // for testing purposes
var dataTestIdLabel = label.replace(/\s/g, '-').toLowerCase();
var type = mainStep ? 'main' : 'sub';
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("button", {
className: buttonClasses,
type: "button",
"aria-disabled": disabled,
disabled: disabled,
onClick: accessible ? handleClick : null,
onKeyDown: accessible ? handleKeyDown : null,
"data-testid": "".concat(iotPrefix$1H, "--progress-step-button-").concat(type, "-").concat(dataTestIdLabel),
tabIndex: current || disabled ? -1 : 0
}, /*#__PURE__*/React__default['default'].createElement(StepLine, null), /*#__PURE__*/React__default['default'].createElement(StepIcon, null), /*#__PURE__*/React__default['default'].createElement("div", {
className: textClasses
}, /*#__PURE__*/React__default['default'].createElement(StepLabel, null), /*#__PURE__*/React__default['default'].createElement(StepSecondaryLabel, null))));
};
var classes = classnames$1((_classnames4 = {}, defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step"), true), defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step--current"), current && !disabled), defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step--complete"), complete && !disabled && !invalid), defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step--incomplete"), incomplete && !current && !disabled && !invalid), defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step--disabled"), disabled), defineProperty$d(_classnames4, "".concat(iotPrefix$1H, "--progress-step--invalid"), invalid), _classnames4));
return /*#__PURE__*/React__default['default'].createElement("li", {
className: classes,
style: getStepWidth()
}, /*#__PURE__*/React__default['default'].createElement(StepButton, null));
};
ProgressStep.propTypes = {
id: IDPropTypes.isRequired,
label: PropTypes__default['default'].string,
secondaryLabel: PropTypes__default['default'].string,
description: PropTypes__default['default'].string,
disabled: PropTypes__default['default'].bool,
showLabel: PropTypes__default['default'].bool,
stepWidth: PropTypes__default['default'].number,
vertical: PropTypes__default['default'].bool,
invalid: PropTypes__default['default'].bool,
stepNumber: PropTypes__default['default'].number,
lastItem: PropTypes__default['default'].bool,
isClickable: PropTypes__default['default'].bool,
current: PropTypes__default['default'].bool,
complete: PropTypes__default['default'].bool,
incomplete: PropTypes__default['default'].bool,
mainStep: PropTypes__default['default'].bool,
subStep: PropTypes__default['default'].bool,
onClick: PropTypes__default['default'].func,
spaceEqually: PropTypes__default['default'].bool
};
ProgressStep.defaultProps = {
label: null,
secondaryLabel: null,
description: null,
disabled: false,
showLabel: false,
stepWidth: null,
vertical: false,
invalid: false,
stepNumber: 0,
lastItem: false,
isClickable: false,
current: false,
complete: false,
incomplete: false,
mainStep: false,
subStep: false,
onClick: null,
spaceEqually: false
};
var ProgressIndicator = function ProgressIndicator(_ref2) {
var _classnames5;
var className = _ref2.className,
items = _ref2.items,
currentItemId = _ref2.currentItemId,
showLabels = _ref2.showLabels,
isVerticalMode = _ref2.isVerticalMode,
stepWidth = _ref2.stepWidth,
isClickable = _ref2.isClickable,
onClickItem = _ref2.onClickItem,
testId = _ref2.testId,
spaceEqually = _ref2.spaceEqually;
var _useState = React$1.useState(currentItemId || items[0].id),
_useState2 = slicedToArray$2(_useState, 2),
currentStep = _useState2[0],
setCurrentStep = _useState2[1];
var flattenItems = function flattenItems(itemsList) {
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var newList = [];
var step = 1;
var newVal;
itemsList.forEach(function (item) {
newVal = Object.assign({}, item);
if (item.children) {
delete newVal.children;
newVal.stepNumber = step;
newVal.level = level;
newList.push(newVal);
step += 1;
newList = newList.concat(flattenItems(item.children, level + 1));
} else {
newVal.stepNumber = step;
newVal.level = level;
newList.push(newVal);
step += 1;
}
});
return newList;
};
var newItems = items && flattenItems(items);
var lastItemId = function lastItemId() {
return newItems[newItems.length - 1].id;
};
var getCurrentIndex = function getCurrentIndex() {
var idx = 0;
if (currentStep) {
var index = newItems.findIndex(function (item) {
return item.id === currentStep;
});
idx = index > -1 ? index : 0;
}
return idx;
};
var handleChange = function handleChange(step) {
if (step !== currentStep) {
if (onClickItem) {
onClickItem(step);
} else {
setCurrentStep(step);
}
}
};
React$1.useEffect(function () {
return setCurrentStep(currentItemId);
}, [currentItemId]);
var classes = classnames$1((_classnames5 = {}, defineProperty$d(_classnames5, "".concat(iotPrefix$1H, "--progress-indicator"), true), defineProperty$d(_classnames5, "".concat(iotPrefix$1H, "--progress-indicator--vertical"), isVerticalMode), defineProperty$d(_classnames5, className, className), _classnames5));
return newItems.length > 1 ? /*#__PURE__*/React__default['default'].createElement("ul", {
className: classes,
"data-testid": testId
}, newItems.map(function (_ref3, index) {
var id = _ref3.id,
label = _ref3.label,
secondaryLabel = _ref3.secondaryLabel,
description = _ref3.description,
disabled = _ref3.disabled,
invalid = _ref3.invalid,
stepNumber = _ref3.stepNumber,
level = _ref3.level;
return /*#__PURE__*/React__default['default'].createElement(ProgressStep, {
id: id,
key: id,
label: label,
secondaryLabel: secondaryLabel,
description: description || label,
current: currentStep === id,
complete: getCurrentIndex() > index,
incomplete: getCurrentIndex() < index,
mainStep: level === 0,
subStep: level > 0,
onClick: handleChange,
stepNumber: stepNumber,
vertical: isVerticalMode,
showLabel: showLabels,
stepWidth: stepWidth,
lastItem: lastItemId() === id,
disabled: disabled,
invalid: invalid,
isClickable: isClickable,
spaceEqually: spaceEqually
});
})) : null;
};
ProgressIndicator.propTypes = {
className: PropTypes__default['default'].string,
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: IDPropTypes,
label: PropTypes__default['default'].string.isRequired,
secondaryLabel: PropTypes__default['default'].string,
description: PropTypes__default['default'].string,
disabled: PropTypes__default['default'].bool,
invalid: PropTypes__default['default'].bool
})),
currentItemId: IDPropTypes,
showLabels: PropTypes__default['default'].bool,
stepWidth: PropTypes__default['default'].number,
isVerticalMode: PropTypes__default['default'].bool,
isClickable: PropTypes__default['default'].bool,
onClickItem: PropTypes__default['default'].func,
testId: PropTypes__default['default'].string,
/** Specify whether the progress steps should be split equally in size in the div */
spaceEqually: PropTypes__default['default'].bool
};
ProgressIndicator.defaultProps = {
className: null,
items: null,
showLabels: true,
stepWidth: null,
currentItemId: null,
isVerticalMode: false,
isClickable: false,
onClickItem: null,
testId: "".concat(iotPrefix$1H, "--progress-indicator-testid"),
spaceEqually: false
};
ProgressIndicator.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "ProgressIndicator",
"props": {
"className": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"items": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "custom",
"raw": "IDPropTypes",
"required": false
},
"label": {
"name": "string",
"required": true
},
"secondaryLabel": {
"name": "string",
"required": false
},
"description": {
"name": "string",
"required": false
},
"disabled": {
"name": "bool",
"required": false
},
"invalid": {
"name": "bool",
"required": false
}
}
}
},
"required": false,
"description": ""
},
"showLabels": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"stepWidth": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"currentItemId": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "IDPropTypes"
},
"required": false,
"description": ""
},
"isVerticalMode": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"isClickable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"onClickItem": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "`${iotPrefix}--progress-indicator-testid`",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"spaceEqually": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Specify whether the progress steps should be split equally in size in the div"
}
}
};
var iotPrefix$1G = settings$1.iotPrefix;
var propTypes$1T = {
onNext: PropTypes__default['default'].func.isRequired,
onBack: PropTypes__default['default'].func.isRequired,
onSubmit: PropTypes__default['default'].func.isRequired,
onCancel: PropTypes__default['default'].func.isRequired,
backLabel: PropTypes__default['default'].node.isRequired,
nextLabel: PropTypes__default['default'].node.isRequired,
cancelLabel: PropTypes__default['default'].node.isRequired,
submitLabel: PropTypes__default['default'].node.isRequired,
hasPrev: PropTypes__default['default'].bool,
hasNext: PropTypes__default['default'].bool,
footerLeftContent: PropTypes__default['default'].node,
nextDisabled: PropTypes__default['default'].bool,
sendingData: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string
};
var defaultProps$20 = {
footerLeftContent: null,
nextDisabled: false,
hasPrev: true,
hasNext: true,
sendingData: false,
testId: 'wizard-footer'
};
var WizardFooter = function WizardFooter(_ref) {
var onNext = _ref.onNext,
onBack = _ref.onBack,
onSubmit = _ref.onSubmit,
className = _ref.className,
onCancel = _ref.onCancel,
cancelLabel = _ref.cancelLabel,
backLabel = _ref.backLabel,
nextLabel = _ref.nextLabel,
submitLabel = _ref.submitLabel,
hasPrev = _ref.hasPrev,
hasNext = _ref.hasNext,
footerLeftContent = _ref.footerLeftContent,
nextDisabled = _ref.nextDisabled,
sendingData = _ref.sendingData,
testId = _ref.testId;
return /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, null, footerLeftContent && /*#__PURE__*/React__default['default'].createElement("div", {
className: "WizardInline-custom-footer-content"
}, footerLeftContent), /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId,
className: classnames$1(className, "".concat(iotPrefix$1G, "--wizard-footer__buttons"))
}, !hasPrev ? /*#__PURE__*/React__default['default'].createElement(Button$1, {
onClick: onCancel,
kind: "secondary" // TODO: pass testId in v3 to override defaults
// testId={`${testId}-cancel-button`}
}, cancelLabel) : null, hasPrev ? /*#__PURE__*/React__default['default'].createElement(Button$1, {
onClick: onBack,
kind: "secondary" // TODO: pass testId in v3 to override defaults
// testId={`${testId}-previous-button`}
}, backLabel) : null, hasNext ? /*#__PURE__*/React__default['default'].createElement(Button$1, {
onClick: onNext,
disabled: nextDisabled // TODO: pass testId in v3 to override defaults
// testId={`${testId}-next-button`}
}, nextLabel) : /*#__PURE__*/React__default['default'].createElement(Button$1, {
onClick: onSubmit,
disabled: nextDisabled,
loading: sendingData // TODO: pass testId in v3 to override defaults
// testId={`${testId}-submit-button`}
}, submitLabel)));
};
WizardFooter.propTypes = propTypes$1T;
WizardFooter.defaultProps = defaultProps$20;
WizardFooter.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "WizardFooter",
"props": {
"footerLeftContent": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": ""
},
"nextDisabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasPrev": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"hasNext": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"sendingData": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'wizard-footer'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"onNext": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onBack": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onSubmit": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"onCancel": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"backLabel": {
"type": {
"name": "node"
},
"required": true,
"description": ""
},
"nextLabel": {
"type": {
"name": "node"
},
"required": true,
"description": ""
},
"cancelLabel": {
"type": {
"name": "node"
},
"required": true,
"description": ""
},
"submitLabel": {
"type": {
"name": "node"
},
"required": true,
"description": ""
}
}
};
function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$7() { 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 iotPrefix$1F = settings$1.iotPrefix;
/**
* Extends ComposedModal to add wizard, refer to that component for common props
*/
var WizardModal = /*#__PURE__*/function (_Component) {
inherits(WizardModal, _Component);
var _super = _createSuper$7(WizardModal);
function WizardModal() {
var _this;
classCallCheck(this, WizardModal);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty$d(assertThisInitialized(_this), "state", {
step: _this.props.currentStepIndex
});
defineProperty$d(assertThisInitialized(_this), "handleNext", function () {
if (_this.validateCurrentStep()) {
_this.setState(function (state) {
return {
step: state.step + 1
};
});
}
});
defineProperty$d(assertThisInitialized(_this), "handlePrevious", function () {
var onBack = _this.props.onBack;
_this.setState(function (state) {
return {
step: state.step - 1
};
}, function () {
if (onBack) {
onBack(_this.state.step);
}
});
});
defineProperty$d(assertThisInitialized(_this), "handleClick", function (key) {
// If you're trying to go higher then validate
var step = _this.state.step;
var onBack = _this.props.onBack;
if (key < step || _this.validateCurrentStep()) {
_this.setState({
step: key
}, function () {
if (onBack && key < step) {
onBack(key);
}
});
}
});
defineProperty$d(assertThisInitialized(_this), "validateCurrentStep", function () {
var steps = _this.props.steps;
var step = _this.state.step;
var onValidate = steps[step].onValidate;
if (onValidate) {
var isValid = onValidate();
return isNil(isValid) || isValid;
}
return true;
});
defineProperty$d(assertThisInitialized(_this), "handleSubmit", function () {
var onSubmit = _this.props.onSubmit; // eslint-disable-line react/prop-types
if (_this.validateCurrentStep()) {
onSubmit();
}
});
defineProperty$d(assertThisInitialized(_this), "renderFooter", function () {
var _this$props = _this.props,
onClose = _this$props.onClose,
sendingData = _this$props.sendingData,
_this$props$footer = _this$props.footer,
leftContent = _this$props$footer.leftContent,
submitButtonLabel = _this$props$footer.submitButtonLabel,
cancelButtonLabel = _this$props$footer.cancelButtonLabel,
nextButtonLabel = _this$props$footer.nextButtonLabel,
previousButtonLabel = _this$props$footer.previousButtonLabel,
steps = _this$props.steps,
testId = _this$props.testId;
var step = _this.state.step;
var defaultFooterProps = WizardModal.defaultProps.footer;
var hasNext = step !== steps.length - 1;
var hasPrev = step !== 0;
return /*#__PURE__*/React__default['default'].createElement(WizardFooter, {
hasPrev: hasPrev,
hasNext: hasNext,
onCancel: onClose,
onBack: _this.handlePrevious,
onNext: _this.handleNext,
onSubmit: _this.handleSubmit,
footerLeftContent: leftContent,
cancelLabel: cancelButtonLabel || defaultFooterProps.cancelButtonLabel,
nextLabel: nextButtonLabel || defaultFooterProps.nextButtonLabel,
backLabel: previousButtonLabel || defaultFooterProps.previousButtonLabel,
submitLabel: submitButtonLabel || defaultFooterProps.submitButtonLabel,
sendingData: typeof sendingData === 'boolean' && sendingData || typeof sendingData === 'string',
className: "".concat(iotPrefix$1F, "--wizard-modal__footer"),
testId: "".concat(testId, "-footer")
});
});
return _this;
}
createClass(WizardModal, [{
key: "render",
value: function render() {
var _this$props2 = this.props,
steps = _this$props2.steps,
className = _this$props2.className;
_this$props2.currentStepIndex;
var isClickable = _this$props2.isClickable;
_this$props2.onBack;
var testId = _this$props2.testId,
other = objectWithoutProperties$1(_this$props2, ["steps", "className", "currentStepIndex", "isClickable", "onBack", "testId"]); // Transform object to be what Progress Indicator expects
var items = steps.map(function (step, index) {
return {
id: index,
label: step.label
};
});
var stepIndex = this.state.step;
return /*#__PURE__*/React__default['default'].createElement(ComposedModal, _extends_1$1({}, other, {
className: classnames$1("".concat(iotPrefix$1F, "--wizard-modal"), className),
footer: this.renderFooter() // TODO: pass testId in v3 to override defaults.
// testId={testId}
}), /*#__PURE__*/React__default['default'].createElement(ProgressIndicator, {
items: items,
currentItemId: !isNil(stepIndex) ? items[stepIndex] && items[stepIndex].id : null,
onClickItem: this.handleClick,
isClickable: isClickable // TODO: pass testId in v3 to override defaults.
// testId={`${testId}-progress-indicator`}
}), /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": "".concat(testId, "-content"),
className: "".concat(iotPrefix$1F, "--wizard-modal__content")
}, steps[stepIndex].content));
}
}]);
return WizardModal;
}(React$1.Component);
defineProperty$d(WizardModal, "propTypes", {
/**
* Header to pass through to Modal
*/
header: PropTypes__default['default'].shape({
label: PropTypes__default['default'].string,
title: PropTypes__default['default'].string.isRequired,
helpText: PropTypes__default['default'].string
}).isRequired,
/**
* steps for the wizard to take you through
* label: the label of each step up in the progress bar,
* content: the wizard page content for each step
* onValidate: is the callback called to validate that we can leave this step
*/
steps: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
label: PropTypes__default['default'].node.isRequired,
content: PropTypes__default['default'].node.isRequired,
onValidate: PropTypes__default['default'].func
})).isRequired,
/** optionally pass in the current Step */
currentStepIndex: PropTypes__default['default'].number,
/** Make the progress indicator clickable */
isClickable: PropTypes__default['default'].bool,
/** callback when dialog is submitted */
onSubmit: PropTypes__default['default'].func.isRequired,
/** Callback when going to previous step */
onBack: PropTypes__default['default'].func,
/**
* leftContent: Anything that will placed to the left of the buttons inside the footer
* labels: Internationalized string labels for the buttons in the footer
*/
footer: PropTypes__default['default'].shape({
leftContent: PropTypes__default['default'].node,
nextButtonLabel: PropTypes__default['default'].node,
previousButtonLabel: PropTypes__default['default'].node,
submitButtonLabel: PropTypes__default['default'].node,
cancelButtonLabel: PropTypes__default['default'].node
}),
testId: PropTypes__default['default'].string
});
defineProperty$d(WizardModal, "defaultProps", {
currentStepIndex: 0,
isClickable: false,
onBack: null,
footer: {
leftContent: null,
nextButtonLabel: 'Next',
previousButtonLabel: 'Previous',
submitButtonLabel: 'Submit',
cancelButtonLabel: 'Cancel'
},
testId: 'wizard-modal'
});
WizardModal.__docgenInfo = {
"description": "Extends ComposedModal to add wizard, refer to that component for common props",
"methods": [{
"name": "handleNext",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "handlePrevious",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "handleClick",
"docblock": null,
"modifiers": [],
"params": [{
"name": "key",
"type": null
}],
"returns": null
}, {
"name": "validateCurrentStep",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "handleSubmit",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}, {
"name": "renderFooter",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}],
"displayName": "WizardModal",
"props": {
"currentStepIndex": {
"defaultValue": {
"value": "0",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "optionally pass in the current Step"
},
"isClickable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Make the progress indicator clickable"
},
"onBack": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback when going to previous step"
},
"footer": {
"defaultValue": {
"value": "{\n leftContent: null,\n nextButtonLabel: 'Next',\n previousButtonLabel: 'Previous',\n submitButtonLabel: 'Submit',\n cancelButtonLabel: 'Cancel',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"leftContent": {
"name": "node",
"required": false
},
"nextButtonLabel": {
"name": "node",
"required": false
},
"previousButtonLabel": {
"name": "node",
"required": false
},
"submitButtonLabel": {
"name": "node",
"required": false
},
"cancelButtonLabel": {
"name": "node",
"required": false
}
}
},
"required": false,
"description": "leftContent: Anything that will placed to the left of the buttons inside the footer\nlabels: Internationalized string labels for the buttons in the footer"
},
"testId": {
"defaultValue": {
"value": "'wizard-modal'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"header": {
"type": {
"name": "shape",
"value": {
"label": {
"name": "string",
"required": false
},
"title": {
"name": "string",
"required": true
},
"helpText": {
"name": "string",
"required": false
}
}
},
"required": true,
"description": "Header to pass through to Modal"
},
"steps": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"label": {
"name": "node",
"required": true
},
"content": {
"name": "node",
"required": true
},
"onValidate": {
"name": "func",
"required": false
}
}
}
},
"required": true,
"description": "steps for the wizard to take you through\n label: the label of each step up in the progress bar,\n content: the wizard page content for each step\n onValidate: is the callback called to validate that we can leave this step"
},
"onSubmit": {
"type": {
"name": "func"
},
"required": true,
"description": "callback when dialog is submitted"
}
}
};
// ----------------
// TO BE DEPRECATED
// ----------------
// These definitions support legacy styled-component styles and are to be deprecated in favor of Sass.
// Please see the new Sass entry point: ./src/styles.scss
var COLORS = {
superLightGray: '#f9fafb',
darkGray: '#152935',
darkGrayHover: '#2d3f48',
gray: '#5a6872',
lightGrey: '#dfe3e6',
blue: '#3d70b2',
lightBlue: 'rgba(85, 150, 230, 0.1)',
errorRed: '#e62325',
okayGreen: '#5aa700',
white: '#fff',
gray100: '#171717',
gray80: '#3d3d3d',
gray80hover: '#4c4c4c',
gray70: '#565656',
gray20: '#dcdcdc',
gray20hover: '#cacaca',
gray10: '#f3f3f3',
gray10hover: '#e5e5e5',
blue60: '#0062ff',
navToggle: '#282828',
purple: '#8A3FFC',
teal: '#009C98',
magenta: '#EE538B',
cyan: '#0072C3'
};
var PADDING = {
verticalPadding: '1rem',
horizontalWrapPadding: '1rem'
};
var SIZES = {
navigationBarHeight: '3rem'
};
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle$1(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject$1(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
function ownKeys$1R(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$1R(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1R(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1R(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var iotPrefix$1E = settings$1.iotPrefix;
var HEADER_MODES = {
STATIC: 'STATIC',
STICKY: 'STICKY',
DYNAMIC: 'DYNAMIC',
CONDENSED: 'CONDENSED'
};
var BREADCRUMB_CONDENSED_HEIGHT = 40;
var PageTitleBarPropTypes = {
/** Title of the page */
title: PropTypes__default['default'].node.isRequired,
/** Details about what the page shows */
description: PropTypes__default['default'].oneOfType([PropTypes__default['default'].element, PropTypes__default['default'].string]),
/** How the header should react to scrolling */
headerMode: PropTypes__default['default'].oneOf(Object.values(HEADER_MODES)),
/** offset for the 'top' attribute on the sticky header. Number will be converted to px */
stickyHeaderOffset: PropTypes__default['default'].number,
/** Optional node to render in the right side of the PageTitleBar
* NOTE: Deprecated in favor of extraContent
*/
rightContent: deprecate$2(PropTypes__default['default'].node, '\nThe prop `rightContent` for PageTitleBar has been deprecated in favor of `extraContent`'),
/** Optional node to render to the side of the PageTitleBar */
extraContent: PropTypes__default['default'].node,
/** Optional node to render actions/text above the main actions area */
upperActions: PropTypes__default['default'].node,
/** Breadcrumbs to show */
breadcrumb: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
/** Should page description be collapsed into tooltip. Should be `true` when using in conjunction with tabs. */
collapsed: PropTypes__default['default'].bool,
/** Is the title editable, will display edit icon with callback */
editable: PropTypes__default['default'].bool,
/** Is the page actively loading */
isLoading: PropTypes__default['default'].bool,
onEdit: PropTypes__default['default'].func,
i18n: PropTypes__default['default'].shape({
editIconDescription: PropTypes__default['default'].string,
tooltipIconDescription: PropTypes__default['default'].string
}),
className: PropTypes__default['default'].string,
style: PropTypes__default['default'].objectOf(PropTypes__default['default'].string),
/* Force the content element to be outside the page title component element
Normally this is automatically detected, i.e. if the header is dynamic and if tabs are present
the content must render outside in order for sticky positioning to work correctly on the tabs
*/
forceContentOutside: PropTypes__default['default'].bool,
/** Tabs should be a Tabs component */
tabs: deprecate$2(PropTypes__default['default'].oneOfType([PropTypes__default['default'].shape({
type: PropTypes__default['default'].oneOf([carbonComponentsReact.Tabs])
})]), '\nThe prop `tabs` for PageTitleBar has been deprecated in favor of `content`'),
/** Content rendered beneath title bar */
content: PropTypes__default['default'].node,
/** Callback to allow custom rendering of the title, it is called back with the title property */
renderTitleFunction: PropTypes__default['default'].func,
testId: PropTypes__default['default'].string,
/**
* In dynamic or condensed modes, when true keep both the breadcrumbs and tabs on the screen
* If false, only keep tabs after scrolling passed breadcrumbs
*/
stackBreadcrumbsWithTabs: PropTypes__default['default'].bool
};
var defaultProps$1$ = {
description: null,
className: null,
rightContent: undefined,
extraContent: undefined,
upperActions: undefined,
breadcrumb: null,
collapsed: undefined,
editable: false,
forceContentOutside: false,
onEdit: null,
i18n: {
editIconDescription: 'Edit page title',
tooltipIconDescription: 'More information'
},
style: null,
isLoading: false,
tabs: undefined,
content: undefined,
renderTitleFunction: undefined,
headerMode: HEADER_MODES.STATIC,
stackBreadcrumbsWithTabs: false,
stickyHeaderOffset: 48,
// default to 3rem to stick to the bottom of the suite header
testId: 'page-title-bar'
};
var PageTitleBar = function PageTitleBar(_ref) {
var _titleBarContent$prop, _titleBarContent$prop2, _classnames;
var title = _ref.title,
renderTitleFunction = _ref.renderTitleFunction,
description = _ref.description,
className = _ref.className,
rightContent = _ref.rightContent,
extraContent = _ref.extraContent,
upperActions = _ref.upperActions,
breadcrumb = _ref.breadcrumb,
collapsed = _ref.collapsed,
forceContentOutside = _ref.forceContentOutside,
headerMode = _ref.headerMode,
stickyHeaderOffsetProp = _ref.stickyHeaderOffset,
editable = _ref.editable,
isLoading = _ref.isLoading,
_ref$i18n = _ref.i18n,
editIconDescription = _ref$i18n.editIconDescription,
tooltipIconDescription = _ref$i18n.tooltipIconDescription,
onEdit = _ref.onEdit,
tabs = _ref.tabs,
stackBreadcrumbsWithTabsProp = _ref.stackBreadcrumbsWithTabs,
style = _ref.style,
content = _ref.content,
testId = _ref.testId;
var titleBarContent = content || tabs;
var _useState = React$1.useState(headerMode === HEADER_MODES.CONDENSED),
_useState2 = slicedToArray$2(_useState, 2),
condensed = _useState2[0],
setCondensed = _useState2[1];
var _useState3 = React$1.useState(0),
_useState4 = slicedToArray$2(_useState3, 2),
transitionProgress = _useState4[0],
setTransitionProgress = _useState4[1];
var _useState5 = React$1.useState(false),
_useState6 = slicedToArray$2(_useState5, 2),
contentActive = _useState6[0],
setContentActive = _useState6[1];
var _useState7 = React$1.useState(stackBreadcrumbsWithTabsProp),
_useState8 = slicedToArray$2(_useState7, 2),
stackBreadcrumbsWithTabs = _useState8[0],
setStackBreadcrumbsWithTabs = _useState8[1];
var breadcrumbRef = React$1.useRef(null);
var contentRef = React$1.useRef(null);
var titleRef = React$1.useRef(null);
var previousScrollY = React$1.useRef(null);
var stickyHeaderOffset = "".concat(stickyHeaderOffsetProp, "px"); // convert to px for styling
/** We need the tabs to render outside the header so the tab stickiness will push away
the header stickiness naturally with the scroll.
We also want sticky mode to render outside so we can sticky the entire header element
*/
var hasTabs = (titleBarContent === null || titleBarContent === void 0 ? void 0 : titleBarContent.type) === carbonComponentsReact.Tabs || [].concat((_titleBarContent$prop = titleBarContent === null || titleBarContent === void 0 ? void 0 : (_titleBarContent$prop2 = titleBarContent.props) === null || _titleBarContent$prop2 === void 0 ? void 0 : _titleBarContent$prop2.children) !== null && _titleBarContent$prop !== void 0 ? _titleBarContent$prop : []).filter(function (child) {
return (child === null || child === void 0 ? void 0 : child.type) === carbonComponentsReact.Tabs;
}).length;
var renderContentOutside = hasTabs && headerMode === HEADER_MODES.DYNAMIC || headerMode === HEADER_MODES.STICKY || forceContentOutside;
var checkForActiveContent = React$1.useCallback(function () {
// Detect when content area rises above sticky header offset, to set background
// on tabs, which replaces existing sticky header. We add 40 to it, to account for
// the height of the breadcrumbs (2.5rem) when stacking them together.
var activeThreshold = stackBreadcrumbsWithTabs && hasTabs ? stickyHeaderOffsetProp + BREADCRUMB_CONDENSED_HEIGHT : stickyHeaderOffsetProp;
setContentActive(contentRef.current && contentRef.current.getBoundingClientRect().top <= activeThreshold);
}, [hasTabs, stackBreadcrumbsWithTabs, stickyHeaderOffsetProp]);
var checkToShowBreadcrumbs = React$1.useCallback(function () {
var previousY = previousScrollY.current;
var currentY = window.scrollY;
if (!stackBreadcrumbsWithTabsProp && currentY < previousY - BREADCRUMB_CONDENSED_HEIGHT / 2) {
setStackBreadcrumbsWithTabs(true);
} else if (!stackBreadcrumbsWithTabsProp && currentY > previousY + BREADCRUMB_CONDENSED_HEIGHT / 2) {
setStackBreadcrumbsWithTabs(false);
}
previousScrollY.current = window.scrollY;
}, [stackBreadcrumbsWithTabsProp]);
React$1.useEffect(function () {
var handleScroll = throttle$1(function () {
var isCondensed;
var percentComplete; // Detect when sticky overlap begins to start fading out/fading in
// content based on scroll position
/* istanbul ignore else */
if (breadcrumbRef.current && titleRef.current) {
var breadcrumbDims = breadcrumbRef.current.getBoundingClientRect();
var titleDims = titleRef.current.getBoundingClientRect();
if (titleDims.top < breadcrumbDims.bottom) {
isCondensed = true;
var distanceLeftToGo = breadcrumbDims.top - titleDims.top;
var total = breadcrumbDims.height;
percentComplete = (total - Math.abs(distanceLeftToGo)) / total;
if (percentComplete < 0.06) {
percentComplete = 0;
}
if (titleDims.top <= breadcrumbDims.top) {
percentComplete = 1;
}
} else if (window.scrollY < breadcrumbDims.bottom) {
isCondensed = false;
percentComplete = 0;
} else {
isCondensed = condensed;
percentComplete = transitionProgress;
}
setCondensed(isCondensed);
setTransitionProgress(percentComplete);
}
checkForActiveContent();
checkToShowBreadcrumbs();
}, 50);
if (headerMode === HEADER_MODES.DYNAMIC) {
window.addEventListener('scroll', handleScroll);
handleScroll();
}
return function () {
return window.removeEventListener('scroll', handleScroll);
};
}, [checkForActiveContent, condensed, checkToShowBreadcrumbs, headerMode, stackBreadcrumbsWithTabs, stickyHeaderOffsetProp, transitionProgress]);
React$1.useEffect(function () {
var handleScroll = throttle$1(function () {
checkForActiveContent();
}, 50);
if (stackBreadcrumbsWithTabs && headerMode === HEADER_MODES.CONDENSED) {
window.addEventListener('scroll', handleScroll);
}
return function () {
return window.removeEventListener('scroll', handleScroll);
};
}, [checkForActiveContent, headerMode, stackBreadcrumbsWithTabs]);
React$1.useEffect(function () {
setStackBreadcrumbsWithTabs(stackBreadcrumbsWithTabsProp);
}, [stackBreadcrumbsWithTabsProp]);
React$1.useEffect(function () {
setContentActive(false);
}, [headerMode]);
var titleActions = React$1.useMemo(function () {
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, description && (collapsed || condensed) ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tooltip, {
tabIndex: 0,
triggerText: "",
triggerId: "tooltip",
tooltipId: "tooltip",
renderIcon: iconsReact.Information16,
iconDescription: tooltipIconDescription,
"data-testid": "".concat(testId, "-tooltip")
}, typeof description === 'string' ? /*#__PURE__*/React__default['default'].createElement("p", null, description) : description) : null, editable ? /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: "page-title-bar-title--edit",
kind: "ghost",
size: "field",
hasIconOnly: true,
renderIcon: iconsReact.Edit16,
title: editIconDescription,
iconDescription: editIconDescription,
tooltipAlignment: "center",
tooltipPosition: "bottom",
onClick: onEdit // TODO: pass testId in v3 to override defaults
// testId={`${testId}-edit-button`}
}) : null);
}, [description, collapsed, condensed, tooltipIconDescription, testId, editable, editIconDescription, onEdit]);
var headerOffsetCssVar = stackBreadcrumbsWithTabs && (headerMode === HEADER_MODES.DYNAMIC || headerMode === HEADER_MODES.CONDENSED) ? "".concat(stickyHeaderOffsetProp + BREADCRUMB_CONDENSED_HEIGHT, "px") : stickyHeaderOffset;
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId,
className: classnames$1(className, 'page-title-bar', (_classnames = {
'page-title-bar--sticky': headerMode === HEADER_MODES.STICKY,
'page-title-bar--condensed-static': headerMode === HEADER_MODES.CONDENSED,
'page-title-bar--dynamic--before': headerMode === HEADER_MODES.DYNAMIC && !condensed,
'page-title-bar--dynamic--during': headerMode === HEADER_MODES.DYNAMIC && condensed && transitionProgress < 1 && transitionProgress > 0,
'page-title-bar--dynamic--after': headerMode === HEADER_MODES.DYNAMIC && condensed && transitionProgress === 1,
'page-title-bar--dynamic': headerMode === HEADER_MODES.DYNAMIC,
'page-title-bar--with-actions': upperActions && headerMode === HEADER_MODES.DYNAMIC
}, defineProperty$d(_classnames, "".concat(iotPrefix$1E, "--page-title-bar--stack-tabs"), stackBreadcrumbsWithTabs), defineProperty$d(_classnames, "".concat(iotPrefix$1E, "--page-title-bar--stack-tabs-override-show"), headerMode === HEADER_MODES.DYNAMIC && stackBreadcrumbsWithTabs && !stackBreadcrumbsWithTabsProp), defineProperty$d(_classnames, "".concat(iotPrefix$1E, "--page-title-bar--stack-tabs-override-hide"), headerMode === HEADER_MODES.DYNAMIC && !stackBreadcrumbsWithTabs && !stackBreadcrumbsWithTabsProp), _classnames)),
style: _objectSpread$1R({
'--header-offset': headerOffsetCssVar,
'--negative-header-offset': "-".concat(headerOffsetCssVar),
'--scroll-transition-progress': headerMode !== HEADER_MODES.DYNAMIC ? 1 : transitionProgress
}, style)
}, isLoading ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.SkeletonText, {
className: "page-title-bar-loading",
heading: true,
width: "30%"
}) : /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-header"
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-breadcrumb-bg"
}), breadcrumb || upperActions || headerMode === HEADER_MODES.DYNAMIC || headerMode === HEADER_MODES.CONDENSED ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-breadcrumb breadcrumb--container",
ref: breadcrumbRef
}, /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Breadcrumb, null, breadcrumb ? breadcrumb.map(function (crumb, index) {
return /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.BreadcrumbItem, {
key: "breadcrumb-".concat(index)
}, crumb);
}) : null, headerMode === HEADER_MODES.DYNAMIC || headerMode === HEADER_MODES.CONDENSED ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.BreadcrumbItem, {
key: "breadcrumb-current",
className: "page-title-bar-breadcrumb-current",
isCurrentPage: true,
title: title
}, /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, title, description ? /*#__PURE__*/React__default['default'].createElement(carbonComponentsReact.Tooltip, {
tabIndex: 0,
triggerText: "",
triggerId: "tooltip",
tooltipId: "tooltip",
renderIcon: iconsReact.Information16,
iconDescription: tooltipIconDescription,
"data-testid": "".concat(testId, "-tooltip")
}, typeof description === 'string' ? /*#__PURE__*/React__default['default'].createElement("p", null, description) : description) : null)) : null)) : null, upperActions ? /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-actions-upper"
}, upperActions) : null, /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-title",
ref: titleRef
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-title--text"
}, !renderTitleFunction ? /*#__PURE__*/React__default['default'].createElement("h2", {
title: title
}, title) : renderTitleFunction(title), titleActions)), description && !collapsed && !condensed ? /*#__PURE__*/React__default['default'].createElement("p", {
className: "page-title-bar-description"
}, description) : null, /*#__PURE__*/React__default['default'].createElement("div", {
className: "page-title-bar-header-right"
}, extraContent || rightContent), titleBarContent && !renderContentOutside ? /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1('page-title-bar-content', {
'page-title-bar-content--active': contentActive
}),
ref: contentRef
}, titleBarContent) : null), titleBarContent && renderContentOutside ? /*#__PURE__*/React__default['default'].createElement("div", {
className: classnames$1('page-title-bar-content', {
'page-title-bar-content--active': contentActive
}),
ref: contentRef
}, titleBarContent) : null));
};
PageTitleBar.propTypes = PageTitleBarPropTypes;
PageTitleBar.defaultProps = defaultProps$1$;
PageTitleBar.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "PageTitleBar",
"props": {
"description": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "union",
"value": [{
"name": "element"
}, {
"name": "string"
}]
},
"required": false,
"description": "Details about what the page shows"
},
"className": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"rightContent": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.node,\n '\\nThe prop `rightContent` for PageTitleBar has been deprecated in favor of `extraContent`'\n)"
},
"required": false,
"description": "Optional node to render in the right side of the PageTitleBar\n NOTE: Deprecated in favor of extraContent"
},
"extraContent": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "node"
},
"required": false,
"description": "Optional node to render to the side of the PageTitleBar"
},
"upperActions": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "node"
},
"required": false,
"description": "Optional node to render actions/text above the main actions area"
},
"breadcrumb": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "node"
}
},
"required": false,
"description": "Breadcrumbs to show"
},
"collapsed": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "bool"
},
"required": false,
"description": "Should page description be collapsed into tooltip. Should be `true` when using in conjunction with tabs."
},
"editable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Is the title editable, will display edit icon with callback"
},
"forceContentOutside": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"onEdit": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"i18n": {
"defaultValue": {
"value": "{\n editIconDescription: 'Edit page title',\n tooltipIconDescription: 'More information',\n}",
"computed": false
},
"type": {
"name": "shape",
"value": {
"editIconDescription": {
"name": "string",
"required": false
},
"tooltipIconDescription": {
"name": "string",
"required": false
}
}
},
"required": false,
"description": ""
},
"style": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "objectOf",
"value": {
"name": "string"
}
},
"required": false,
"description": ""
},
"isLoading": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Is the page actively loading"
},
"tabs": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.oneOfType([\n PropTypes.shape({\n type: PropTypes.oneOf([Tabs]),\n }),\n ]),\n '\\nThe prop `tabs` for PageTitleBar has been deprecated in favor of `content`'\n)"
},
"required": false,
"description": "Tabs should be a Tabs component"
},
"content": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "node"
},
"required": false,
"description": "Content rendered beneath title bar"
},
"renderTitleFunction": {
"defaultValue": {
"value": "undefined",
"computed": true
},
"type": {
"name": "func"
},
"required": false,
"description": "Callback to allow custom rendering of the title, it is called back with the title property"
},
"headerMode": {
"defaultValue": {
"value": "'STATIC'",
"computed": false
},
"type": {
"name": "enum",
"value": [{
"value": "\"CONDENSED\"",
"computed": false
}, {
"value": "\"DYNAMIC\"",
"computed": false
}, {
"value": "\"STATIC\"",
"computed": false
}, {
"value": "\"STICKY\"",
"computed": false
}]
},
"required": false,
"description": "How the header should react to scrolling"
},
"stackBreadcrumbsWithTabs": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "In dynamic or condensed modes, when true keep both the breadcrumbs and tabs on the screen\nIf false, only keep tabs after scrolling passed breadcrumbs"
},
"stickyHeaderOffset": {
"defaultValue": {
"value": "48",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "offset for the 'top' attribute on the sticky header. Number will be converted to px"
},
"testId": {
"defaultValue": {
"value": "'page-title-bar'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"title": {
"type": {
"name": "node"
},
"required": true,
"description": "Title of the page"
}
}
};
function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$6() { 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 prefix$o = settings$1.prefix,
iotPrefix$1D = settings$1.iotPrefix;
var WizardHeader = /*#__PURE__*/function (_Component) {
inherits(WizardHeader, _Component);
var _super = _createSuper$6(WizardHeader);
function WizardHeader() {
var _this;
classCallCheck(this, WizardHeader);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty$d(assertThisInitialized(_this), "state", {});
defineProperty$d(assertThisInitialized(_this), "render", function () {
var _this$props = _this.props,
currentItemId = _this$props.currentItemId,
setItem = _this$props.setItem,
items = _this$props.items,
showLabels = _this$props.showLabels,
stepWidth = _this$props.stepWidth,
title = _this$props.title,
blurb = _this$props.blurb,
description = _this$props.description,
onClose = _this$props.onClose,
closeButtonTitle = _this$props.closeButtonTitle,
isClickable = _this$props.isClickable,
testId = _this$props.testId;
var closeButton = /*#__PURE__*/React__default['default'].createElement(Button$1, {
className: "".concat(prefix$o, "--modal-close"),
title: closeButtonTitle,
type: "button" // TODO: pass testId in v3 to override defaults
// testId={`${testId}-close-button`}
}, /*#__PURE__*/React__default['default'].createElement(iconsReact.Close20, {
onClick: onClose
}));
return /*#__PURE__*/React__default['default'].createElement(React$1.Fragment, null, /*#__PURE__*/React__default['default'].createElement(PageTitleBar, {
className: "".concat(iotPrefix$1D, "--wizard-inline__header"),
title: title,
description: blurb || description,
extraContent: onClose ? closeButton : null,
testId: "".concat(testId, "-page-title-bar")
}), /*#__PURE__*/React__default['default'].createElement(ProgressIndicator, {
className: "".concat(iotPrefix$1D, "--wizard-inline__progress-indicator"),
currentItemId: currentItemId,
items: items.map(function (item) {
return {
id: item.id,
label: item.name
};
}),
showLabels: showLabels,
onClickItem: setItem,
stepWidth: stepWidth,
isClickable: isClickable // TODO: pass testId in v3 to override defaults
// testId={`${testId}-progress-indicator`}
}));
});
return _this;
}
return WizardHeader;
}(React$1.Component);
defineProperty$d(WizardHeader, "propTypes", {
/** Title in the header */
title: PropTypes__default['default'].string,
description: PropTypes__default['default'].string,
blurb: PropTypes__default['default'].string,
onClose: PropTypes__default['default'].func,
closeButtonTitle: PropTypes__default['default'].string,
currentItemId: PropTypes__default['default'].string.isRequired,
setItem: PropTypes__default['default'].func.isRequired,
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string.isRequired,
name: PropTypes__default['default'].string.isRequired,
component: PropTypes__default['default'].element.isRequired
})).isRequired,
showLabels: PropTypes__default['default'].bool,
stepWidth: PropTypes__default['default'].number,
isClickable: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string
});
defineProperty$d(WizardHeader, "defaultProps", {
title: null,
blurb: null,
description: null,
showLabels: true,
stepWidth: 136,
onClose: null,
closeButtonTitle: 'Close',
isClickable: false,
testId: 'wizard-header'
});
WizardHeader.__docgenInfo = {
"description": "",
"methods": [{
"name": "render",
"docblock": null,
"modifiers": [],
"params": [],
"returns": null
}],
"displayName": "WizardHeader",
"props": {
"title": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Title in the header"
},
"blurb": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"description": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"showLabels": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"stepWidth": {
"defaultValue": {
"value": "136",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"onClose": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": ""
},
"closeButtonTitle": {
"defaultValue": {
"value": "'Close'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"isClickable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'wizard-header'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"currentItemId": {
"type": {
"name": "string"
},
"required": true,
"description": ""
},
"setItem": {
"type": {
"name": "func"
},
"required": true,
"description": ""
},
"items": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": true
},
"name": {
"name": "string",
"required": true
},
"component": {
"name": "element",
"required": true
}
}
}
},
"required": true,
"description": ""
}
}
};
var iotPrefix$1C = settings$1.iotPrefix;
var propTypes$1S = {
sidebar: PropTypes__default['default'].element,
width: PropTypes__default['default'].number,
testId: PropTypes__default['default'].string
};
var defaultProps$1_ = {
sidebar: null,
width: 200,
testId: 'wizard-sidebar'
};
var WizardSidebar = function WizardSidebar(_ref) {
var sidebar = _ref.sidebar,
width = _ref.width,
testId = _ref.testId;
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId,
className: "".concat(iotPrefix$1C, "--wizard-inline__sidebar"),
style: {
'--min-width': "".concat(width, "px")
}
}, sidebar);
};
WizardSidebar.propTypes = propTypes$1S;
WizardSidebar.defaultProps = defaultProps$1_;
WizardSidebar.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "WizardSidebar",
"props": {
"sidebar": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": ""
},
"width": {
"defaultValue": {
"value": "200",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": ""
},
"testId": {
"defaultValue": {
"value": "'wizard-sidebar'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
}
}
};
var WizardContent = function WizardContent(_ref) {
var component = _ref.component,
testId = _ref.testId;
return /*#__PURE__*/React__default['default'].createElement("div", {
"data-testid": testId
}, component);
};
WizardContent.propTypes = {
component: PropTypes__default['default'].element.isRequired,
testId: PropTypes__default['default'].string
};
WizardContent.defaultProps = {
testId: 'wizard-content'
};
WizardContent.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "WizardContent",
"props": {
"testId": {
"defaultValue": {
"value": "'wizard-content'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"component": {
"type": {
"name": "element"
},
"required": true,
"description": ""
}
}
};
var prefix$n = settings$1.prefix;
var StyledWizardWrapper = styled__default['default'].div.withConfig({
displayName: "WizardInline__StyledWizardWrapper",
componentId: "sc-8orpb0-0"
})([".", "--modal-content[data-id='WizardInlineContent']{max-height:80vh;overflow:auto;width:auto;}.", "--modal-container[data-id='WizardInlineContainer']{min-width:630px;max-width:90%;margin:", " auto;width:90%;padding-bottom:4.5rem;}"], prefix$n, prefix$n, PADDING.verticalPadding);
var StyledWizardContainer = styled__default['default'].div.withConfig({
displayName: "WizardInline__StyledWizardContainer",
componentId: "sc-8orpb0-1"
})(["display:flex;padding:0 ", " 0 0;"], PADDING.horizontalWrapPadding);
var StyledMessageBox = styled__default['default'](carbonComponentsReact.InlineNotification).withConfig({
displayName: "WizardInline__StyledMessageBox",
componentId: "sc-8orpb0-2"
})(["&&&{width:calc(100% - ", " * 2);margin:", " auto;max-width:unset;}"], PADDING.horizontalWrapPadding, PADDING.verticalPadding);
var StyledFooter = styled__default['default'].div.withConfig({
displayName: "WizardInline__StyledFooter",
componentId: "sc-8orpb0-3"
})(["display:flex;position:absolute;bottom:0px;width:100%;align-items:center;line-height:40px;.", "--modal-footer[data-id='WizardInlineFooter']{width:100%;& > *{width:100%;}}"], prefix$n);
var propTypes$1R = {
/** Title in the header */
title: PropTypes__default['default'].string,
description: PropTypes__default['default'].string,
blurb: deprecate$2(PropTypes__default['default'].string, '\nThe prop `blurb` for WizardInline has been deprecated in favor of `description`'),
/** Breadcrumbs to show */
breadcrumb: PropTypes__default['default'].arrayOf(PropTypes__default['default'].node),
/** Id of current step */
currentItemId: PropTypes__default['default'].string,
/** Array of items representing pages of wizard. Must contain id, name, component. Optional: backLabel, nextLabel, nextDisabled */
items: PropTypes__default['default'].arrayOf(PropTypes__default['default'].shape({
id: PropTypes__default['default'].string.isRequired,
name: PropTypes__default['default'].string.isRequired,
component: PropTypes__default['default'].node.isRequired,
/** if you return false the onNext or setItem functions will not be called to change the current step */
onValidate: PropTypes__default['default'].func
})).isRequired,
/** action when click next button called with no param */
onNext: PropTypes__default['default'].func,
/** action when click back button called with no param */
onBack: PropTypes__default['default'].func,
/** action if the inline wizard is closed or canceled */
onClose: PropTypes__default['default'].func,
/** action triggered if the inline wizard has submitted final step */
onSubmit: PropTypes__default['default'].func,
/** string to pass to close button icon title prop */
closeButtonTitle: PropTypes__default['default'].string,
/** label to show on the cancel button */
cancelLabel: PropTypes__default['default'].node,
/** label to show on the back button */
backLabel: PropTypes__default['default'].node,
/** label to show on the next button */
nextLabel: PropTypes__default['default'].node,
/** label to show on the submit button */
submitLabel: PropTypes__default['default'].node,
/** optional component to show in sidebar */
sidebar: PropTypes__default['default'].element,
/** component to show in footer on the left of the buttons */
footerLeftContent: PropTypes__default['default'].element,
/** function to go to item when click ProgressIndicator items. */
setItem: PropTypes__default['default'].func,
/** show labels in Progress Indicator */
showLabels: PropTypes__default['default'].bool,
/** next button disabled */
nextDisabled: PropTypes__default['default'].bool,
/** width of each step in px. Circle is 24px. Passed to Header */
stepWidth: PropTypes__default['default'].number,
/** is the wizard actively sending data should disable the button */
sendingData: PropTypes__default['default'].bool,
/** should we show the close button at the top of the screen */
showCloseButton: PropTypes__default['default'].bool,
/** Form Error Details */
error: PropTypes__default['default'].string,
/** Clear the currently shown error, triggered if the user closes the ErrorNotification */
onClearError: PropTypes__default['default'].func,
/** Set the progress indicator button to clickable */
isClickable: PropTypes__default['default'].bool,
testId: PropTypes__default['default'].string
};
var defaultProps$1Z = {
title: null,
breadcrumb: null,
sidebar: null,
footerLeftContent: null,
showCloseButton: true,
showLabels: true,
nextDisabled: false,
currentItemId: null,
blurb: null,
description: null,
stepWidth: 8,
onNext: null,
onBack: null,
setItem: null,
onClose: null,
closeButtonTitle: 'Close',
onSubmit: null,
backLabel: 'Back',
nextLabel: 'Next',
cancelLabel: 'Cancel',
submitLabel: 'Add',
sendingData: false,
error: null,
onClearError: null,
isClickable: false,
testId: 'wizard-inline'
};
var WizardInline = function WizardInline(_ref) {
var title = _ref.title,
breadcrumb = _ref.breadcrumb,
description = _ref.description,
blurb = _ref.blurb,
currentItemId = _ref.currentItemId,
items = _ref.items,
_onNext = _ref.onNext,
onBack = _ref.onBack,
sidebar = _ref.sidebar,
footerLeftContent = _ref.footerLeftContent,
_setItem = _ref.setItem,
showLabels = _ref.showLabels,
backLabel = _ref.backLabel,
nextLabel = _ref.nextLabel,
cancelLabel = _ref.cancelLabel,
submitLabel = _ref.submitLabel,
onSubmit = _ref.onSubmit,
onClose = _ref.onClose,
showCloseButton = _ref.showCloseButton,
nextDisabled = _ref.nextDisabled,
sendingData = _ref.sendingData,
stepWidth = _ref.stepWidth,
className = _ref.className,
error = _ref.error,
onClearError = _ref.onClearError,
closeButtonTitle = _ref.closeButtonTitle,
isClickable = _ref.isClickable,
testId = _ref.testId;
{
warning_1(false, 'WizardInline component has been deprecated and will be removed in the next release of `carbon-addons-iot-react`. \n Refactor to use PageWizard component instead.') ;
}
var currentItemObj = items.find(function (_ref2) {
var id = _ref2.id;
return currentItemId === id;
}) || items[0];
var currentItemIndex = items.findIndex(function (_ref3) {
var id = _ref3.id;
return currentItemId === id;
});
var hasNext = currentItemIndex !== items.length - 1;
var hasPrev = currentItemIndex !== 0;
var handleClearError = function handleClearError() {
if (onClearError) {
onClearError();
}
};
var isValid = function isValid(callback) {
if (currentItemObj && currentItemObj.onValidate) {
if (currentItemObj.onValidate(currentItemId)) {
callback();
} else return;
}
callback();
};
return /*#__PURE__*/React__default['default'].createElement(StyledWizardWrapper, {
"data-testid": testId,
className: className
}, /*#__PURE__*/React__default['default'].createElement("div", {
"data-id": "WizardInlineContainer",
className: "".concat(prefix$n, "--modal-container")
}, /*#__PURE__*/React__default['default'].createElement(WizardHeader, {
title: title,
description: description,
blurb: blurb,
currentItemId: currentItemId,
breadcrumb: breadcrumb // only go if current step passes validation
,
setItem: function setItem(id) {
return isValid(function () {
return _setItem(id);
});
},
items: items,
showLabels: showLabels,
onClose: showCloseButton ? onClose : null,
stepWidth: stepWidth,
closeButtonTitle: closeButtonTitle,
isClickable: isClickable,
testId: "".concat(testId, "-header")
}), error ? /*#__PURE__*/React__default['default'].createElement(StyledMessageBox, {
title: error,
subtitle: "",
kind: "error",
onCloseButtonClick: handleClearError,
"data-testid": "".concat(testId, "-error-notification")
}) : null, /*#__PURE__*/React__default['default'].createElement(StyledWizardContainer, null, sidebar ? /*#__PURE__*/React__default['default'].createElement(WizardSidebar, {
sidebar: sidebar,
testId: "".concat(testId, "-sidebar")
}) : null, /*#__PURE__*/React__default['default'].createElement("div", {
"data-id": "WizardInlineContent",
className: "".concat(prefix$n, "--modal-content")
}, /*#__PURE__*/React__default['default'].createElement(WizardContent, {
component: currentItemObj.component,
testId: "".concat(testId, "-content")
}))), /*#__PURE__*/React__default['default'].createElement(StyledFooter, {
className: className
}, /*#__PURE__*/React__default['default'].createElement("div", {
"data-id": "WizardInlineFooter",
className: "".concat(prefix$n, "--modal-footer")
}, /*#__PURE__*/React__default['default'].createElement(WizardFooter, {
backLabel: backLabel,
nextLabel: nextLabel,
hasNext: hasNext,
hasPrev: hasPrev,
cancelLabel: cancelLabel,
submitLabel: submitLabel // Validate before next
,
onNext: function onNext(event) {
return isValid(function () {
return _onNext(event);
});
},
onBack: onBack,
onSubmit: onSubmit,
onCancel: onClose,
footerLeftContent: footerLeftContent,
nextDisabled: nextDisabled || false,
sendingData: sendingData,
testId: "".concat(testId, "-footer")
})))));
};
WizardInline.propTypes = propTypes$1R;
WizardInline.defaultProps = defaultProps$1Z;
WizardInline.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "WizardInline",
"props": {
"title": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Title in the header"
},
"breadcrumb": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "arrayOf",
"value": {
"name": "node"
}
},
"required": false,
"description": "Breadcrumbs to show"
},
"sidebar": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": "optional component to show in sidebar"
},
"footerLeftContent": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "element"
},
"required": false,
"description": "component to show in footer on the left of the buttons"
},
"showCloseButton": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "should we show the close button at the top of the screen"
},
"showLabels": {
"defaultValue": {
"value": "true",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "show labels in Progress Indicator"
},
"nextDisabled": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "next button disabled"
},
"currentItemId": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Id of current step"
},
"blurb": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "custom",
"raw": "deprecate(\n PropTypes.string,\n '\\nThe prop `blurb` for WizardInline has been deprecated in favor of `description`'\n)"
},
"required": false,
"description": ""
},
"description": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"stepWidth": {
"defaultValue": {
"value": "8",
"computed": false
},
"type": {
"name": "number"
},
"required": false,
"description": "width of each step in px. Circle is 24px. Passed to Header"
},
"onNext": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "action when click next button called with no param"
},
"onBack": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "action when click back button called with no param"
},
"setItem": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "function to go to item when click ProgressIndicator items."
},
"onClose": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "action if the inline wizard is closed or canceled"
},
"closeButtonTitle": {
"defaultValue": {
"value": "'Close'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "string to pass to close button icon title prop"
},
"onSubmit": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "action triggered if the inline wizard has submitted final step"
},
"backLabel": {
"defaultValue": {
"value": "'Back'",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "label to show on the back button"
},
"nextLabel": {
"defaultValue": {
"value": "'Next'",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "label to show on the next button"
},
"cancelLabel": {
"defaultValue": {
"value": "'Cancel'",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "label to show on the cancel button"
},
"submitLabel": {
"defaultValue": {
"value": "'Add'",
"computed": false
},
"type": {
"name": "node"
},
"required": false,
"description": "label to show on the submit button"
},
"sendingData": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "is the wizard actively sending data should disable the button"
},
"error": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": "Form Error Details"
},
"onClearError": {
"defaultValue": {
"value": "null",
"computed": false
},
"type": {
"name": "func"
},
"required": false,
"description": "Clear the currently shown error, triggered if the user closes the ErrorNotification"
},
"isClickable": {
"defaultValue": {
"value": "false",
"computed": false
},
"type": {
"name": "bool"
},
"required": false,
"description": "Set the progress indicator button to clickable"
},
"testId": {
"defaultValue": {
"value": "'wizard-inline'",
"computed": false
},
"type": {
"name": "string"
},
"required": false,
"description": ""
},
"items": {
"type": {
"name": "arrayOf",
"value": {
"name": "shape",
"value": {
"id": {
"name": "string",
"required": true
},
"name": {
"name": "string",
"required": true
},
"component": {
"name": "node",
"required": true
},
"onValidate": {
"name": "func",
"description": "if you return false the onNext or setItem functions will not be called to change the current step",
"required": false
}
}
}
},
"required": true,
"description": "Array of items representing pages of wizard. Must contain id, name, component. Optional: backLabel, nextLabel, nextDisabled"
}
}
};
var StatefulWizardInline = function StatefulWizardInline(_ref) {
var currentItemIdProp = _ref.currentItemId,
items = _ref.items,
onNext = _ref.onNext,
onBack = _ref.onBack,
_setItem = _ref.setItem,
other = objectWithoutProperties$1(_ref, ["currentItemId", "items", "onNext", "onBack", "setItem"]);
var _useState = React$1.useState(currentItemIdProp || items && items[0].id),
_useState2 = slicedToArray$2(_useState, 2),
currentItemId = _useState2[0],
setCurrentItemId = _useState2[1];
var currentItemIndex = items.findIndex(function (item) {
return item.id === currentItemId;
});
var nextItem = currentItemIndex < items.length - 1 ? items[currentItemIndex + 1] : undefined;
var prevItem = currentItemIndex > 0 ? items[currentItemIndex - 1] : undefined;
var handleNext = function handleNext(id) {
// Find the last one
setCurrentItemId(id);
if (onNext) {
onNext(id);
}
};
var handleBack = function handleBack(id) {
// Find the first one
setCurrentItemId(id);
if (onBack) {
onBack(id);
}
};
return /*#__PURE__*/React__default['default'].createElement(WizardInline, _extends_1$1({}, other, {
items: items,
onBack: function onBack() {
return handleBack(prevItem.id);
},
onNext: function onNext() {
return handleNext(nextItem.id);
},
currentItemId: currentItemId,
setItem: function setItem(id) {
setCurrentItemId(id);
if (_setItem) {
_setItem(id);
}
}
}));
};
StatefulWizardInline.propTypes = propTypes$1R;
StatefulWizardInline.defaultProps = defaultProps$1Z;
StatefulWizardInline.__docgenInfo = {
"description": "",
"methods": [],
"displayName": "StatefulWizardInline",
"composes": ["./WizardInline"]
};
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var asyncToGenerator = _asyncToGenerator;
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get$4(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime_1 = createCommonjsModule(function (module) {
var runtime = (function (exports) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined$1; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined$1;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined$1, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined$1;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined$1;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module.exports
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
});
var regenerator = runtime_1;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$1 = 1,
COMPARE_UNORDERED_FLAG$1 = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject$1(value);
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys$1(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get$4(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity$6;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate);
collection = keys$1(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber$1(value);
if (value === INFINITY$1 || value === -INFINITY$1) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger$1(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex$1(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger$1(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate), index);
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find$3 = createFind(findIndex$1);
/**
* Pushes row id to the provided array (including row children)
*
* @param {object} row A table row with id
* @param {array} arrToFill An array that will be filled with all rows id
*/
var fillArrWithRowIds = function fillArrWithRowIds(row, arrToFill) {
if (row.isSelectable !== false) {
arrToFill.push(row.id);
}
if (!isEmpty(row.children)) {
row.children.forEach(function (el) {
return fillArrWithRowIds(el, arrToFill);
});
}
};
var TABLE_REGISTER = 'TABLE_REGISTER';
var TABLE_LOAD_VIEW = 'TABLE_LOAD_VIEW';
var TABLE_PAGE_CHANGE = 'TABLE_PAGE_CHANGE';
var TABLE_FILTER_APPLY = 'TABLE_FILTER_APPLY';
var TABLE_FILTER_CLEAR = 'TABLE_FILTER_CLEAR';
var TABLE_TOOLBAR_TOGGLE = 'TABLE_TOOLBAR_TOGGLE';
var TABLE_ACTION_CANCEL = 'TABLE_ACTION_CANCEL';
var TABLE_ACTION_APPLY = 'TABLE_ACTION_APPLY';
var TABLE_ROW_ACTION_START = 'TABLE_ROW_ACTION_START';
var TABLE_ROW_ACTION_EDIT = 'TABLE_ROW_ACTION_EDIT';
var TABLE_ROW_ACTION_COMPLETE = 'TABLE_ROW_ACTION_COMPLETE';
var TABLE_ROW_ACTION_ERROR = 'TABLE_ROW_ACTION_ERROR';
var TABLE_COLUMN_SORT = 'TABLE_COLUMN_SORT';
var TABLE_COLUMN_ORDER = 'TABLE_COLUMN_ORDER';
var TABLE_COLUMN_RESIZE = 'TABLE_COLUMN_RESIZE';
var TABLE_ROW_SELECT = 'TABLE_ROW_SELECT';
var TABLE_ROW_SELECT_ALL = 'TABLE_ROW_SELECT_ALL';
var TABLE_ROW_CLICK = 'TABLE_ROW_CLICK';
var TABLE_ROW_EXPAND = 'TABLE_ROW_EXPAND';
var TABLE_SEARCH_APPLY = 'TABLE_SEARCH_APPLY';
var TABLE_EMPTY_STATE_ACTION = 'TABLE_EMPTY_STATE_ACTION';
var TABLE_LOADING_SET = 'TABLE_LOADING_SET';
var TABLE_ADVANCED_FILTER_CANCEL = 'TABLE_ADVACNED_FILTER_CANCEL';
var TABLE_ADVANCED_FILTER_CREATE = 'TABLE_ADVANCED_FILTER_CREATE';
var TABLE_ADVANCED_FILTER_REMOVE = 'TABLE_ADVANCED_FILTER_REMOVE';
var TABLE_ADVANCED_FILTER_CHANGE = 'TABLE_ADVANCED_FILTER_CHANGE';
var TABLE_ADVANCED_FILTER_TOGGLE = 'TABLE_ADVANCED_FILTER_TOGGLE';
var TABLE_ADVANCED_FILTER_APPLY = 'TABLE_ADVANCED_FILTER_APPLY';
var TABLE_TOGGLE_AGGREGATIONS = 'TABLE_TOGGLE_AGGREGATIONS';
var TABLE_MULTI_SORT_TOGGLE_MODAL = 'TABLE_MULTI_SORT_TOGGLE_MODAL';
var TABLE_MULTI_SORT_SAVE = 'TABLE_MULTI_SORT_SAVE';
var TABLE_MULTI_SORT_CANCEL = 'TABLE_MULTI_SORT_CANCEL';
var TABLE_MULTI_SORT_CLEAR = 'TABLE_MULTI_SORT_CLEAR';
var TABLE_MULTI_SORT_ADD_COLUMN = 'TABLE_MULTI_SORT_ADD_COLUMN';
var TABLE_MULTI_SORT_REMOVE_COLUMN = 'TABLE_MULTI_SORT_REMOVE_COLUMN';
var TABLE_ROW_LOAD_MORE = 'TABLE_ROW_LOAD_MORE';
var tableRegister = function tableRegister(_ref) {
var data = _ref.data,
isLoading = _ref.isLoading,
view = _ref.view,
totalItems = _ref.totalItems,
hasUserViewManagement = _ref.hasUserViewManagement,
hasRowSelection = _ref.hasRowSelection,
_ref$instanceId = _ref.instanceId,
instanceId = _ref$instanceId === void 0 ? null : _ref$instanceId;
return {
type: TABLE_REGISTER,
payload: {
data: data,
view: view,
isLoading: isLoading,
totalItems: totalItems,
hasUserViewManagement: hasUserViewManagement,
hasRowSelection: hasRowSelection
},
instanceId: instanceId
};
};
var tablePageChange = function tablePageChange(page) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_PAGE_CHANGE,
payload: page,
instanceId: instanceId
};
};
var tableToolbarToggle = function tableToolbarToggle(toolbar) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_TOOLBAR_TOGGLE,
payload: toolbar,
instanceId: instanceId
};
};
/** Apply filters */
var tableFilterApply = function tableFilterApply(filter) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_FILTER_APPLY,
payload: filter,
instanceId: instanceId
};
};
var tableFilterClear = function tableFilterClear() {
var instanceId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return {
type: TABLE_FILTER_CLEAR,
instanceId: instanceId
};
};
var tableSearchApply = function tableSearchApply(search) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_SEARCH_APPLY,
payload: search,
instanceId: instanceId
};
};
/** Table Batch Actions */
var tableActionCancel = function tableActionCancel() {
var instanceId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return {
type: TABLE_ACTION_CANCEL,
instanceId: instanceId
};
};
var tableActionApply = function tableActionApply(id) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ACTION_APPLY,
payload: id,
instanceId: instanceId
};
};
/** Table column actions */
var tableColumnSort = function tableColumnSort(column, columns) {
var instanceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return {
type: TABLE_COLUMN_SORT,
payload: column,
columns: columns,
instanceId: instanceId
};
};
var tableColumnOrder = function tableColumnOrder(ordering) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_COLUMN_ORDER,
payload: ordering,
instanceId: instanceId
};
};
var tableColumnResize = function tableColumnResize(columns) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_COLUMN_RESIZE,
payload: columns,
instanceId: instanceId
};
};
/** Table empty state action */
var tableEmptyStateAction = function tableEmptyStateAction() {
var instanceId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return {
type: TABLE_EMPTY_STATE_ACTION,
instanceId: instanceId
};
};
/** Table row actions */
var tableRowActionStart = function tableRowActionStart(rowId) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ROW_ACTION_START,
payload: rowId,
instanceId: instanceId
};
};
var tableRowActionEdit = function tableRowActionEdit(rowId) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ROW_ACTION_EDIT,
payload: rowId,
instanceId: instanceId
};
};
var tableRowActionComplete = function tableRowActionComplete(rowId) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ROW_ACTION_COMPLETE,
payload: rowId,
instanceId: instanceId
};
};
var tableRowActionError = function tableRowActionError(rowId, error) {
var instanceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return {
type: TABLE_ROW_ACTION_ERROR,
payload: rowId,
error: error,
instanceId: instanceId
};
};
/** Select a row of the table */
var tableRowSelect = function tableRowSelect(selectedIds, hasRowSelection) {
var instanceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return {
type: TABLE_ROW_SELECT,
payload: {
selectedIds: selectedIds,
hasRowSelection: hasRowSelection
},
instanceId: instanceId
};
};
/** Select all the currently filtered rows of the table */
var tableRowSelectAll = function tableRowSelectAll(isSelected) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ROW_SELECT_ALL,
payload: {
isSelected: isSelected
},
instanceId: instanceId
};
};
var tableRowClick = function tableRowClick(rowId) {
var instanceId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return {
type: TABLE_ROW_CLICK,
payload: {
rowId: rowId
},
instanceId: instanceId
};
};
var tableRowExpand = function tableRowExpand(rowId, isExpanded) {
var instanceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var options = arguments.length > 3 ? arguments[3] : undefined;
return {
type: TABLE_ROW_EXPAND,
payload: {
rowId: rowId,
isExpanded: isExpanded,
options: options
},
instanceId: instanceId
};
};
/**
* rowCount: The number of rows currently being loaded
*/
var tableLoadingSet = function tableLoadingSet(isLoading, rowCount) {
var instanceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return {
type: TABLE_LOADING_SET,
payload: {
isLoading: isLoading,
rowCount: rowCount
},
instanceId: instanceId
};
};
/**
* Advanced filters
*/
var tableAdvancedFiltersToggle = function tableAdvancedFiltersToggle() {
return {
type: TABLE_ADVANCED_FILTER_TOGGLE
};
};
var tableAdvancedFiltersCancel = function tableAdvancedFiltersCancel() {
return {
type: TABLE_ADVANCED_FILTER_CANCEL
};
};
var tableAdvancedFiltersCreate = function tableAdvancedFiltersCreate() {
return {
type: TABLE_ADVANCED_FILTER_CREATE
};
};
var tableAdvancedFiltersRemove = function tableAdvancedFiltersRemove(filterId) {
return {
type: TABLE_ADVANCED_FILTER_REMOVE,
payload: {
filterId: filterId
}
};
};
var tableAdvancedFiltersChange = function tableAdvancedFiltersChange() {
return {
type: TABLE_ADVANCED_FILTER_CHANGE
};
};
var tableAdvancedFiltersApply = function tableAdvancedFiltersApply(filterState) {
return {
type: TABLE_ADVANCED_FILTER_APPLY,
payload: filterState
};
};
var tableToggleAggregations = function tableToggleAggregations() {
return {
type: TABLE_TOGGLE_AGGREGATIONS
};
};
var tableMultiSortToggleModal = function tableMultiSortToggleModal(meta) {
return {
type: TABLE_MULTI_SORT_TOGGLE_MODAL,
payload: meta
};
};
var tableSaveMultiSortColumns = function tableSaveMultiSortColumns(sortColumns) {
return {
type: TABLE_MULTI_SORT_SAVE,
payload: sortColumns
};
};
var tableCancelMultiSortColumns = function tableCancelMultiSortColumns() {
return {
type: TABLE_MULTI_SORT_CANCEL
};
};
var tableClearMultiSortColumns = function tableClearMultiSortColumns() {
return {
type: TABLE_MULTI_SORT_CLEAR
};
};
var tableAddMultiSortColumn = function tableAddMultiSortColumn(index) {
return {
type: TABLE_MULTI_SORT_ADD_COLUMN,
payload: index
};
};
var tableRemoveMultiSortColumn = function tableRemoveMultiSortColumn(index) {
return {
type: TABLE_MULTI_SORT_REMOVE_COLUMN,
payload: index
};
};
var tableRowLoadMore = function tableRowLoadMore(rowId) {
return {
type: TABLE_ROW_LOAD_MORE,
payload: rowId
};
};
var tableActionCreators = /*#__PURE__*/Object.freeze({
__proto__: null,
TABLE_REGISTER: TABLE_REGISTER,
TABLE_LOAD_VIEW: TABLE_LOAD_VIEW,
TABLE_PAGE_CHANGE: TABLE_PAGE_CHANGE,
TABLE_FILTER_APPLY: TABLE_FILTER_APPLY,
TABLE_FILTER_CLEAR: TABLE_FILTER_CLEAR,
TABLE_TOOLBAR_TOGGLE: TABLE_TOOLBAR_TOGGLE,
TABLE_ACTION_CANCEL: TABLE_ACTION_CANCEL,
TABLE_ACTION_APPLY: TABLE_ACTION_APPLY,
TABLE_ROW_ACTION_START: TABLE_ROW_ACTION_START,
TABLE_ROW_ACTION_EDIT: TABLE_ROW_ACTION_EDIT,
TABLE_ROW_ACTION_COMPLETE: TABLE_ROW_ACTION_COMPLETE,
TABLE_ROW_ACTION_ERROR: TABLE_ROW_ACTION_ERROR,
TABLE_COLUMN_SORT: TABLE_COLUMN_SORT,
TABLE_COLUMN_ORDER: TABLE_COLUMN_ORDER,
TABLE_COLUMN_RESIZE: TABLE_COLUMN_RESIZE,
TABLE_ROW_SELECT: TABLE_ROW_SELECT,
TABLE_ROW_SELECT_ALL: TABLE_ROW_SELECT_ALL,
TABLE_ROW_CLICK: TABLE_ROW_CLICK,
TABLE_ROW_EXPAND: TABLE_ROW_EXPAND,
TABLE_SEARCH_APPLY: TABLE_SEARCH_APPLY,
TABLE_EMPTY_STATE_ACTION: TABLE_EMPTY_STATE_ACTION,
TABLE_LOADING_SET: TABLE_LOADING_SET,
TABLE_ADVANCED_FILTER_CANCEL: TABLE_ADVANCED_FILTER_CANCEL,
TABLE_ADVANCED_FILTER_CREATE: TABLE_ADVANCED_FILTER_CREATE,
TABLE_ADVANCED_FILTER_REMOVE: TABLE_ADVANCED_FILTER_REMOVE,
TABLE_ADVANCED_FILTER_CHANGE: TABLE_ADVANCED_FILTER_CHANGE,
TABLE_ADVANCED_FILTER_TOGGLE: TABLE_ADVANCED_FILTER_TOGGLE,
TABLE_ADVANCED_FILTER_APPLY: TABLE_ADVANCED_FILTER_APPLY,
TABLE_TOGGLE_AGGREGATIONS: TABLE_TOGGLE_AGGREGATIONS,
TABLE_MULTI_SORT_TOGGLE_MODAL: TABLE_MULTI_SORT_TOGGLE_MODAL,
TABLE_MULTI_SORT_SAVE: TABLE_MULTI_SORT_SAVE,
TABLE_MULTI_SORT_CANCEL: TABLE_MULTI_SORT_CANCEL,
TABLE_MULTI_SORT_CLEAR: TABLE_MULTI_SORT_CLEAR,
TABLE_MULTI_SORT_ADD_COLUMN: TABLE_MULTI_SORT_ADD_COLUMN,
TABLE_MULTI_SORT_REMOVE_COLUMN: TABLE_MULTI_SORT_REMOVE_COLUMN,
TABLE_ROW_LOAD_MORE: TABLE_ROW_LOAD_MORE,
tableRegister: tableRegister,
tablePageChange: tablePageChange,
tableToolbarToggle: tableToolbarToggle,
tableFilterApply: tableFilterApply,
tableFilterClear: tableFilterClear,
tableSearchApply: tableSearchApply,
tableActionCancel: tableActionCancel,
tableActionApply: tableActionApply,
tableColumnSort: tableColumnSort,
tableColumnOrder: tableColumnOrder,
tableColumnResize: tableColumnResize,
tableEmptyStateAction: tableEmptyStateAction,
tableRowActionStart: tableRowActionStart,
tableRowActionEdit: tableRowActionEdit,
tableRowActionComplete: tableRowActionComplete,
tableRowActionError: tableRowActionError,
tableRowSelect: tableRowSelect,
tableRowSelectAll: tableRowSelectAll,
tableRowClick: tableRowClick,
tableRowExpand: tableRowExpand,
tableLoadingSet: tableLoadingSet,
tableAdvancedFiltersToggle: tableAdvancedFiltersToggle,
tableAdvancedFiltersCancel: tableAdvancedFiltersCancel,
tableAdvancedFiltersCreate: tableAdvancedFiltersCreate,
tableAdvancedFiltersRemove: tableAdvancedFiltersRemove,
tableAdvancedFiltersChange: tableAdvancedFiltersChange,
tableAdvancedFiltersApply: tableAdvancedFiltersApply,
tableToggleAggregations: tableToggleAggregations,
tableMultiSortToggleModal: tableMultiSortToggleModal,
tableSaveMultiSortColumns: tableSaveMultiSortColumns,
tableCancelMultiSortColumns: tableCancelMultiSortColumns,
tableClearMultiSortColumns: tableClearMultiSortColumns,
tableAddMultiSortColumn: tableAddMultiSortColumn,
tableRemoveMultiSortColumn: tableRemoveMultiSortColumn,
tableRowLoadMore: tableRowLoadMore
});
function ownKeys$1Q(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$1Q(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1Q(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1Q(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var baseTableReducer = function baseTableReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 ? arguments[1] : undefined;
// To support instance matching (i.e. multiple table states in one store), just ensure
// that a instanceId is provided on state passed to baseTableReducer. If no instanceId
// is provided, all matching actions will be processed by this table reducer.
if (typeof action.instanceId === 'string' && action.instanceId !== state.instanceId) {
return state;
}
switch (action.type) {
// Page Actions
case TABLE_PAGE_CHANGE:
{
var _state$view$paginatio = state.view.pagination,
currentPageSize = _state$view$paginatio.pageSize,
totalItems = _state$view$paginatio.totalItems,
currentPage = _state$view$paginatio.page;
var _action$payload = action.payload,
page = _action$payload.page,
pageSize = _action$payload.pageSize;
var isPageSizeChange = pageSize && currentPageSize !== pageSize;
var maxPage = Math.ceil(totalItems / pageSize);
var isPageChange = page !== currentPage && page <= maxPage;
var newPagination = isPageSizeChange ? _objectSpread$1Q(_objectSpread$1Q(_objectSpread$1Q({}, state.view.pagination), action.payload), {}, {
page: 1
}) : isPageChange ? _objectSpread$1Q(_objectSpread$1Q({}, state.view.pagination), action.payload) : state.view.pagination;
var result = update(state, {
view: {
pagination: {
$set: newPagination
}
}
});
return result;
}
// Filter Actions
case TABLE_FILTER_APPLY:
{
var newFilters = Object.entries(action.payload).map(function (_ref) {
var _ref2 = slicedToArray$2(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return value !== '' ? {
columnId: key,
value: value
} : null;
}).filter(function (i) {
return i;
});
return update(state, {
view: {
filters: {
$set: newFilters
},
pagination: {
page: {
$set: 1
}
}
}
});
}
case TABLE_FILTER_CLEAR:
return update(state, {
view: {
filters: {
$set: []
},
pagination: {
page: {
$set: 1
}
}
}
});
case TABLE_SEARCH_APPLY:
{
var isExpanded = get$4(state, 'view.toolbar.search.isExpanded');
return update(state, {
view: {
toolbar: {
search: {
$set: {
defaultValue: action.payload,
isExpanded: isExpanded
}
}
},
pagination: {
page: {
$set: 1
}
}
}
});
}
// Toolbar Actions
case TABLE_TOOLBAR_TOGGLE:
{
var filterToggled = state.view.toolbar.activeBar === action.payload ? null : action.payload;
return update(state, {
view: {
toolbar: {
activeBar: {
$set: filterToggled
}
}
}
});
}
// Batch Actions
case TABLE_ACTION_CANCEL:
return update(state, {
view: {
table: {
selectedIds: {
$set: []
},
isSelectAllSelected: {
$set: false
},
isSelectAllIndeterminate: {
$set: false
}
}
}
});
case TABLE_ACTION_APPLY:
{
return update(state, {
view: {
table: {
selectedIds: {
$set: []
},
isSelectAllSelected: {
$set: false
},
isSelectAllIndeterminate: {
$set: false
}
}
}
});
}
// Row Actions
case TABLE_ROW_ACTION_START:
return update(state, {
view: {
table: {
// add the in progress row
rowActions: {
$push: [{
rowId: action.payload,
isRunning: true
}]
}
}
}
});
case TABLE_ROW_ACTION_EDIT:
return update(state, {
view: {
table: {
// mark the row as being in edit mode
rowActions: {
$push: [{
rowId: action.payload,
isEditMode: true
}]
}
}
}
});
case TABLE_ROW_ACTION_COMPLETE:
{
var index = state.view.table.rowActions.findIndex(function (rowAction) {
return rowAction.rowId === action.payload;
});
return update(state, {
view: {
table: {
// remove the finished row
rowActions: {
$splice: [[index, 1]]
}
}
}
});
}
case TABLE_ROW_ACTION_ERROR:
{
var _index = state.view.table.rowActions.findIndex(function (rowAction) {
return rowAction.rowId === action.payload;
});
return update(state, {
view: {
table: {
// replace the row with the error
rowActions: {
$splice: [[_index, 1, {
rowId: action.payload,
error: action.error
}]]
}
}
}
});
}
// Column operations
case TABLE_COLUMN_SORT:
{
// TODO should check that columnId actually is valid
var columnId = action.payload;
var sorts = ['NONE', 'ASC', 'DESC'];
var currentSort = state.view.table.sort;
var isInMultiSort = Array.isArray(currentSort) && currentSort.some(function (column) {
return column.columnId === columnId;
});
var currentSortDir = isInMultiSort ? currentSort.find(function (sort) {
return sort.columnId === columnId;
}).direction : currentSort && currentSort.columnId === columnId ? currentSort.direction : 'NONE';
var nextSortDir = isInMultiSort ? currentSortDir === 'ASC' ? 'DESC' : 'ASC' : sorts[(sorts.findIndex(function (i) {
return i === currentSortDir;
}) + 1) % sorts.length];
var sort;
if (isInMultiSort) {
sort = currentSort.reduce(function (carry, column) {
if (column.columnId === columnId) {
return [].concat(toConsumableArray(carry), [_objectSpread$1Q(_objectSpread$1Q({}, column), {}, {
direction: nextSortDir
})]);
}
return [].concat(toConsumableArray(carry), [column]);
}, []);
} else {
sort = nextSortDir === 'NONE' ? undefined : {
columnId: action.payload,
direction: nextSortDir
};
}
return update(state, {
view: {
table: {
sort: {
$set: sort
}
}
}
});
}
case TABLE_COLUMN_ORDER:
return update(state, {
view: {
table: {
ordering: {
$set: action.payload
}
}
}
});
case TABLE_COLUMN_RESIZE:
return update(state, {
columns: {
$set: action.payload
}
});
// Row operations
case TABLE_ROW_SELECT:
{
var _action$payload2 = action.payload,
selectedIds = _action$payload2.selectedIds,
hasRowSelection = _action$payload2.hasRowSelection;
var isMultiSelect = hasRowSelection === 'multi';
var isClearing = isMultiSelect && selectedIds.length === 0;
var allRowsId = [];
var iterables = state.view.table.filteredData || state.data;
iterables.forEach(function (row) {
return fillArrWithRowIds(row, allRowsId);
});
var isSelectingAll = isMultiSelect && selectedIds.length === allRowsId.length;
return update(state, {
view: {
table: {
selectedIds: {
$set: selectedIds
},
isSelectAllIndeterminate: {
$set: !(isClearing || isSelectingAll)
},
isSelectAllSelected: {
$set: isSelectingAll
}
}
}
});
}
case TABLE_ROW_SELECT_ALL:
{
var isSelected = action.payload.isSelected;
var _selectedIds = [];
if (isSelected) {
var _iterables = state.view.table.filteredData || state.data;
_iterables.forEach(function (row) {
return fillArrWithRowIds(row, _selectedIds);
});
}
return update(state, {
view: {
table: {
isSelectAllSelected: {
$set: isSelected
},
selectedIds: {
$set: _selectedIds
},
isSelectAllIndeterminate: {
$set: false
}
}
}
});
}
case TABLE_ROW_EXPAND:
{
var _action$payload3 = action.payload,
rowId = _action$payload3.rowId,
_isExpanded = _action$payload3.isExpanded,
options = _action$payload3.options;
return update(state, {
view: {
table: {
expandedIds: {
$set: _isExpanded ? options !== null && options !== void 0 && options.expandRowsExclusively ? [rowId] : state.view.table.expandedIds.concat([rowId]) : state.view.table.expandedIds.filter(function (i) {
return i !== rowId;
})
}
}
}
});
}
case TABLE_LOADING_SET:
{
var _action$payload4 = action.payload,
isLoading = _action$payload4.isLoading,
rowCount = _action$payload4.rowCount;
return update(state, {
view: {
table: {
loadingState: {
isLoading: {
$set: isLoading
},
rowCount: {
$set: rowCount
}
}
}
}
});
}
default:
return state;
}
};
function ownKeys$1P(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$1P(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1P(Object(source), true).forEach(function (key) { defineProperty$d(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1P(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var searchWithEmptyString = function searchWithEmptyString(keys, searchTerm, baseSearch) {
if (searchTerm === FILTER_EMPTY_STRING) {
return keys.some(function (key) {
return isEmptyString(key);
});
}
return baseSearch(keys, searchTerm);
};
var arraySearchWithEmptyString = function arraySearchWithEmptyString(arr, item) {
if (arr.includes(FILTER_EMPTY_STRING) && isEmptyString(item)) {
return true;
}
return arr.includes(item);
};
/**
* Default function to compare value 1 and 2
* @param {*} value1, filter value
* @param {*} value2, actual
* returns true if value1 contains value2 for strings, and true if value1 === value2 for numbers
*/
var defaultComparison = function defaultComparison(value1, value2) {
return !isNil(value1) && typeof value1 === 'number' // only if the column value filter is not null/undefined
? value1 === Number(value2) // for a number type, attempt to convert filter to number and direct compare
: !isNil(value1) && // type string do a lowercase includes comparison
searchWithEmptyString([value1 === null || value1 === void 0 ? void 0 : value1.toString()], value2 === null || value2 === void 0 ? void 0 : value2.toString(), caseInsensitiveSearch);
};
var runSimpleFilters = function runSimpleFilters(data, filters, columns) {
return data.filter(function (_ref) {
var values = _ref.values;
return (// return false if a value doesn't match a valid filter
filters.reduce(function (acc, _ref2) {
var columnId = _ref2.columnId,
value = _ref2.value;
if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean' || Array.isArray(value) || value instanceof Date) {
if (!isNil(columns)) {
var _ref3 = find$3(columns, {
id: columnId
}) || {},
filter = _ref3.filter;
var filterFunction = filter === null || filter === void 0 ? void 0 : filter.filterFunction;
if (Array.isArray(value) && !isEmpty(value)) {
return acc && (filterFunction ? filterFunction(values[columnId], value) : arraySearchWithEmptyString(value, values[columnId]));
}
return acc && (filterFunction ? filterFunction(values[columnId], value) : defaultComparison(values[columnId], value));
}
if (Array.isArray(value) && !isEmpty(value)) {
return acc && arraySearchWithEmptyString(value, values[columnId]);
}
return acc && defaultComparison(values[columnId], value);
}
return false;
}, true)
);
});
};
var operands = {
NEQ: function NEQ(a, b) {
return a !== b;
},
LT: function LT(a, b) {
return a < b;
},
LTOET: function LTOET(a, b) {
return a <= b;
},
EQ: function EQ(a, b) {
return a === b;
},
GTOET: function GTOET(a, b) {
return a >= b;
},
GT: function GT(a, b) {
return a > b;
},
CONTAINS: function CONTAINS(a, b) {
return a.includes(b);
}
};
/**
* Recursively check each rule and determine if it's a normal rule or a ruleGroup.
* If it's a group dig deeper into the tree passing the values and logic down as we go.
* If it's a normal rule just run `every` on all the rules for 'ALL' logic and `some`
* for 'ANY' logic.
*
* @param {string} logic 'ALL' or 'ANY'
* @param {Array