funda-ui
Version:
React components using pure Bootstrap 5+ which does not contain any external style and script libraries.
1,258 lines (1,158 loc) • 140 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["RPB"] = factory(require("react"));
else
root["RPB"] = factory(root["React"]);
})(this, (__WEBPACK_EXTERNAL_MODULE__787__) => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 188:
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof2(obj) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof2(obj); }
(function webpackUniversalModuleDefinition(root, factory) {
if (( false ? 0 : _typeof2(exports)) === 'object' && ( false ? 0 : _typeof2(module)) === 'object') module.exports = factory();else if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else {}
})(this, function () {
return (/******/function () {
// webpackBootstrap
/******/
"use strict";
/******/ // The require scope
/******/
var __nested_webpack_require_993__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/
(function () {
/******/ // define getter functions for harmony exports
/******/__nested_webpack_require_993__.d = function (exports, definition) {
/******/for (var key in definition) {
/******/if (__nested_webpack_require_993__.o(definition, key) && !__nested_webpack_require_993__.o(exports, key)) {
/******/Object.defineProperty(exports, key, {
enumerable: true,
get: definition[key]
});
/******/
}
/******/
}
/******/
};
/******/
})();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/
(function () {
/******/__nested_webpack_require_993__.o = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
/******/
})();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/
(function () {
/******/ // define __esModule on exports
/******/__nested_webpack_require_993__.r = function (exports) {
/******/if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/Object.defineProperty(exports, Symbol.toStringTag, {
value: 'Module'
});
/******/
}
/******/
Object.defineProperty(exports, '__esModule', {
value: true
});
/******/
};
/******/
})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
__nested_webpack_require_993__.r(__webpack_exports__);
/* harmony export */
__nested_webpack_require_993__.d(__webpack_exports__, {
/* harmony export */"clsWrite": function clsWrite() {
return (/* binding */_clsWrite
);
},
/* harmony export */"combinedCls": function combinedCls() {
return (/* binding */_combinedCls
);
}
/* harmony export */
});
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s,
_e,
_x,
_r,
_arr = [],
_n = !0,
_d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
/**
* Output of class name
* @param {*} s - Any
* @param {String} defaultCls - Default string
* @param {?*} targetCls - Any
* @returns {*}
*/
function _clsWrite(s, defaultCls) {
var targetCls = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return s || s === '' ? typeof targetCls === 'undefined' ? s : targetCls : defaultCls;
}
/**
* Combined classnames
* @param {*} args
* @returns {String|undefined}
*/
/* Usage:
console.log(combinedCls('a-1', 'a-2', 'a-3', {
'p-1': null,
'p-2': undefined,
'p-3': true,
'p-4': false,
'p-5': 'kkk',
'p-6': 0,
'p-7': 1,
'p-8': '',
undefined
})); // a-1 a-2 a-3 p-3 p-5 p-7
*/
function _combinedCls() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args) {
var classes = [];
for (var i = 0; i < args.length; i++) {
var className = args[i];
if (!className) {
continue;
}
var type = _typeof(className);
if (type === 'string' || type === 'number') {
classes.push(className);
} else if (type === 'object') {
var _classes = Array.isArray(className) ? className : Object.entries(className).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return value ? key : null;
});
classes = _classes.length ? classes.concat(_classes.filter(function (c) {
return !!c;
})) : classes;
}
}
return classes.join(' ').trim();
}
return undefined;
}
/******/
return __webpack_exports__;
/******/
}()
);
});
/***/ }),
/***/ 85:
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
(function webpackUniversalModuleDefinition(root, factory) {
if (( false ? 0 : _typeof(exports)) === 'object' && ( false ? 0 : _typeof(module)) === 'object') module.exports = factory(__webpack_require__(787));else if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(787)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else {}
})(this, function (__WEBPACK_EXTERNAL_MODULE__787__) {
return (/******/function () {
// webpackBootstrap
/******/
"use strict";
/******/
var __webpack_modules__ = {
/***/787: /***/function _(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE__787__;
/***/
}
/******/
};
/************************************************************************/
/******/ // The module cache
/******/
var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/
function __nested_webpack_require_1465__(moduleId) {
/******/ // Check if module is in cache
/******/var cachedModule = __webpack_module_cache__[moduleId];
/******/
if (cachedModule !== undefined) {
/******/return cachedModule.exports;
/******/
}
/******/ // Create a new module (and put it into the cache)
/******/
var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/exports: {}
/******/
};
/******/
/******/ // Execute the module function
/******/
__webpack_modules__[moduleId](module, module.exports, __nested_webpack_require_1465__);
/******/
/******/ // Return the exports of the module
/******/
return module.exports;
/******/
}
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/
(function () {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/__nested_webpack_require_1465__.n = function (module) {
/******/var getter = module && module.__esModule ? /******/function () {
return module['default'];
} : /******/function () {
return module;
};
/******/
__nested_webpack_require_1465__.d(getter, {
a: getter
});
/******/
return getter;
/******/
};
/******/
})();
/******/
/******/ /* webpack/runtime/define property getters */
/******/
(function () {
/******/ // define getter functions for harmony exports
/******/__nested_webpack_require_1465__.d = function (exports, definition) {
/******/for (var key in definition) {
/******/if (__nested_webpack_require_1465__.o(definition, key) && !__nested_webpack_require_1465__.o(exports, key)) {
/******/Object.defineProperty(exports, key, {
enumerable: true,
get: definition[key]
});
/******/
}
/******/
}
/******/
};
/******/
})();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/
(function () {
/******/__nested_webpack_require_1465__.o = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
/******/
})();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/
(function () {
/******/ // define __esModule on exports
/******/__nested_webpack_require_1465__.r = function (exports) {
/******/if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/Object.defineProperty(exports, Symbol.toStringTag, {
value: 'Module'
});
/******/
}
/******/
Object.defineProperty(exports, '__esModule', {
value: true
});
/******/
};
/******/
})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(function () {
__nested_webpack_require_1465__.r(__webpack_exports__);
/* harmony export */
__nested_webpack_require_1465__.d(__webpack_exports__, {
/* harmony export */"default": function _default() {
return __WEBPACK_DEFAULT_EXPORT__;
}
/* harmony export */
});
/* harmony import */
var react__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_1465__(787);
/* harmony import */
var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nested_webpack_require_1465__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/**
* Create an available ID
*
*/
var useComId = function useComId() {
return "ID-".concat((0, react__WEBPACK_IMPORTED_MODULE_0__.useId)().replace(/\:/g, "-"));
};
/* harmony default export */
var __WEBPACK_DEFAULT_EXPORT__ = useComId;
})();
/******/
return __webpack_exports__;
/******/
}()
);
});
/***/ }),
/***/ 787:
/***/ ((module) => {
"use strict";
module.exports = __WEBPACK_EXTERNAL_MODULE__787__;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ (() => {
/******/ __webpack_require__.nmd = (module) => {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"DragHandleSprite": () => (/* reexport */ utils_DragHandleSprite),
"SortSprite": () => (/* reexport */ utils_SortSprite),
"Table": () => (/* reexport */ src_Table),
"TableBody": () => (/* reexport */ src_TableBody),
"TableCaption": () => (/* reexport */ src_TableCaption),
"TableCell": () => (/* reexport */ src_TableCell),
"TableColgroup": () => (/* reexport */ src_TableColgroup),
"TableFilter": () => (/* reexport */ utils_TableFilter),
"TableFoot": () => (/* reexport */ src_TableFoot),
"TableHead": () => (/* reexport */ src_TableHead),
"TableRow": () => (/* reexport */ src_TableRow),
"ToggleSelection": () => (/* reexport */ utils_ToggleSelection)
});
// EXTERNAL MODULE: external {"root":"React","commonjs2":"react","commonjs":"react","amd":"react"}
var external_root_React_commonjs2_react_commonjs_react_amd_react_ = __webpack_require__(787);
var external_root_React_commonjs2_react_commonjs_react_amd_react_default = /*#__PURE__*/__webpack_require__.n(external_root_React_commonjs2_react_commonjs_react_amd_react_);
// EXTERNAL MODULE: ../Utils/dist/cjs/useComId.js
var useComId = __webpack_require__(85);
var useComId_default = /*#__PURE__*/__webpack_require__.n(useComId);
// EXTERNAL MODULE: ../Utils/dist/cjs/cls.js
var cls = __webpack_require__(188);
;// CONCATENATED MODULE: ./src/TableContext.tsx
var TableContext = /*#__PURE__*/(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext)(undefined);
var TableProvider = function TableProvider(props) {
var children = props.children,
value = props.value;
return /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().createElement(TableContext.Provider, {
value: value
}, children);
};
;// CONCATENATED MODULE: ./src/utils/func.ts
function convertMapToArr(setData) {
var res = [];
var s = setData;
for (var it = s.values(), val = null; val = it.next().value;) {
res.push(val);
}
return res;
}
function htmlToPlain(input) {
return input.replace(/(<([^>]+)>)/ig, '');
}
function sortDataByIndex(orderArr, data) {
return Array.isArray(data) ? orderArr.map(function (index) {
return data[index];
}) : data;
}
function getTbody(root) {
if (root === null) return null;
var tbodyRef = root.querySelector('table tbody');
return tbodyRef;
}
function getThead(root) {
if (root === null) return null;
var tbodyRef = root.querySelector('table thead');
return tbodyRef;
}
function allRows(root) {
var tbodyRef = getTbody(root);
if (tbodyRef === null) return [];
return [].slice.call(tbodyRef.children);
}
function allHeadRows(root) {
var tbodyRef = getThead(root);
if (tbodyRef === null) return [];
return [].slice.call(tbodyRef.children);
}
function initOrderProps(rootElem) {
if (rootElem === null) return;
// !!! Execute it only once
if (typeof rootElem.dataset.customPropsInit !== 'undefined') return;
rootElem.dataset.customPropsInit = 1;
var _allRows = allRows(rootElem);
// key
_allRows.forEach(function (node, i) {
node.dataset.order = "".concat(i);
});
}
function initRowColProps(rootElem) {
if (rootElem === null) return;
// !!! Important, performance optimization for large data renderings
// With this protection, it is only performed once
if (typeof rootElem.dataset.rowColPropsInit !== 'undefined') return;
rootElem.dataset.rowColPropsInit = 1;
//
var _allRows = allRows(rootElem);
var _allHeadRows = allHeadRows(rootElem);
// key
_allRows.forEach(function (node, i) {
node.dataset.tableRow = "".concat(i);
// columns
var perCol = [].slice.call(node.children);
perCol.forEach(function (col, j) {
col.dataset.tableRow = "".concat(i);
col.dataset.tableCol = "".concat(j);
col.classList.add(cellMark(i, j));
});
});
_allHeadRows.forEach(function (node, i) {
node.dataset.tableRow = "-1";
// columns
var perCol = [].slice.call(node.children);
perCol.forEach(function (col, j) {
col.dataset.tableRow = "-1";
col.dataset.tableCol = "".concat(j);
col.classList.add(cellMark(-1, j));
});
});
}
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
function maxDimension(elements) {
var res = {
'height': 0,
'width': 0
};
var elementHeights = Array.prototype.map.call(elements, function (el) {
return el.clientHeight;
});
var elementWidths = Array.prototype.map.call(elements, function (el) {
return el.clientWidth;
});
var maxHeight = Math.max.apply(null, elementHeights);
var maxWidth = Math.max.apply(null, elementWidths);
res = {
'height': maxHeight,
'width': maxWidth
};
return res;
}
;
function tableElemScrolledInit(root, w) {
var tbodyRef = getTbody(root);
if (tbodyRef === null) return;
if (w <= 768 && tbodyRef.querySelector('tr') !== null) {
var _loop = function _loop() {
var tbodyRows = root.querySelectorAll("tbody tr [data-table-col=\"".concat(i, "\"]"));
var maxHeight = maxDimension(tbodyRows).height;
if (maxHeight > 0) {
[].slice.call(tbodyRows).forEach(function (row) {
row.style.height = maxHeight + 'px';
});
//
var theadRows = root.querySelectorAll("thead tr [data-table-col=\"".concat(i, "\"]"));
[].slice.call(theadRows).forEach(function (row) {
row.style.height = maxHeight + 'px';
});
}
};
//get maxHeight of per row
for (var i = 0; i < tbodyRef.querySelector('tr').children.length; i++) {
_loop();
}
} else {
[].slice.call(root.querySelectorAll('tbody td, tbody th, thead th')).forEach(function (node, i) {
node.style.removeProperty('height');
});
}
}
function cellMark(row, col) {
var isNegative = function isNegative(num) {
return num < 0;
};
return "cell-".concat(isNegative(row) ? 0 : row, "-").concat(isNegative(col) ? 0 : col);
}
function removeCellFocusClassName(root) {
if (root) {
// !!! Important, performance optimization for large data renderings
// Only query elements with cell-focus classes
var focusedCells = root.querySelectorAll('td.cell-focus, th.cell-focus');
focusedCells.forEach(function (el) {
el.classList.remove('cell-focus');
});
}
}
function getTableRowsColCount(root) {
var rows = allRows(root);
return rows.map(function (row, i) {
return {
row: i,
colCount: row.children.length
};
});
}
;// CONCATENATED MODULE: ./src/utils/hooks/useTableResponsive.tsx
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(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(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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; }
/**
* Handles the event of responsive table
*
* @usage:
const App = () => {
const responsiveTable = true;
const rootRef = useRef<any>(null);
useTableResponsive({
enabled: responsiveTable && rootRef.current,
spyElement: rootRef.current
}, [rootRef]);
return (
<div
ref={rootRef}
>Test</div>
);
};
*/
function useTableResponsive(_ref, deps) {
var enabled = _ref.enabled,
spyElement = _ref.spyElement;
var debounce = function debounce(fn) {
var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300;
var timer;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this, arguments);
}, limit);
};
};
var windowResizeUpdate = debounce(handleWindowUpdate, 50);
var windowWidth = typeof window !== 'undefined' ? window.innerWidth : 0;
function handleWindowUpdate() {
// Check window width has actually changed and it's not just iOS triggering a resize event on scroll
if (window.innerWidth != windowWidth) {
// Update the window width for next time
windowWidth = window.innerWidth;
// Do stuff here
tableElemScrolledInit(spyElement, windowWidth);
}
}
(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () {
if (enabled && spyElement) {
// 1. Remove the tag to allow initRowColProps to re-execute (!!!REQUIRED)
delete spyElement.dataset.customPropsInit;
delete spyElement.dataset.rowColPropsInit;
// 2. Initialize custom props of table elements
initOrderProps(spyElement);
initRowColProps(spyElement);
// 3. With scroll bars
var _windowWidth = window.innerWidth;
tableElemScrolledInit(spyElement, _windowWidth);
// 4. Add function to the element that should be used as the scrollable area.
window.removeEventListener('resize', windowResizeUpdate);
window.addEventListener('resize', windowResizeUpdate);
// Remove the global list of events, especially as scroll and interval.
return function () {
window.removeEventListener('resize', windowResizeUpdate);
};
}
}, [enabled, spyElement].concat(_toConsumableArray(deps)));
}
/* harmony default export */ const hooks_useTableResponsive = (useTableResponsive);
;// CONCATENATED MODULE: ./src/utils/hooks/useTableDraggable.tsx
function useTableDraggable_toConsumableArray(arr) { return useTableDraggable_arrayWithoutHoles(arr) || useTableDraggable_iterableToArray(arr) || useTableDraggable_unsupportedIterableToArray(arr) || useTableDraggable_nonIterableSpread(); }
function useTableDraggable_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 useTableDraggable_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function useTableDraggable_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return useTableDraggable_arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || useTableDraggable_unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function useTableDraggable_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return useTableDraggable_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 useTableDraggable_arrayLikeToArray(o, minLen); }
function useTableDraggable_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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
* Handles the event of drag-and-drop sorting
*
* @usage:
const App = () => {
const rowDraggable = true;
const data = [{a: 1}, {b: 2}]
const rootRef = useRef<any>(null);
const {
handleDragStart,
handleDragEnd,
handledragOver,
handleTbodyEnter
} = useTableDraggable({
enabled: rowDraggable && spyElement,
data: data,
spyElement: spyElement
onRowDrag: (dragStart: any, dragEnd: any) => void(0)
}, [data, rootRef]);
return (
<div
ref={rootRef}
>Test</div>
);
};
*/
/**
* Performance Optimizations for Large Data Sets:
*
* This hook has been optimized to handle large datasets (1000+ rows) efficiently.
* Key optimizations include:
*
* 1. RequestAnimationFrame for DOM Updates
* - DOM operations are batched within requestAnimationFrame callbacks
* - Browser executes updates before next frame render, reducing visual lag
* - Pending RAF callbacks are cancelled to prevent accumulation
*
* 2. Caching Strategy
* - tbodyRef: Cached to avoid repeated DOM queries
* - colCount: Cached to eliminate repeated queries in placeholderGenerator
* - allRowsCache: Cached with time-based invalidation (100ms)
*
* 3. Redundant Operation Prevention
* - Tracks last hovered row order (lastOverOrder)
* - Skips placeholder operations when hovering over the same row
* - Reduces unnecessary DOM manipulations during drag
*
* 4. Batch DOM Operations
* - removePlaceholder: Uses cached tbodyRef and batch removal
* - handleDragEnd: Uses DocumentFragment for batch DOM updates
* - Map-based lookups instead of repeated querySelector calls
*/
function useTableDraggable(_ref, deps) {
var enabled = _ref.enabled,
data = _ref.data,
spyElement = _ref.spyElement,
onRowDrag = _ref.onRowDrag;
// drag & drop
var _useState = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)([]),
_useState2 = _slicedToArray(_useState, 2),
sortData = _useState2[0],
setSortData = _useState2[1];
var _useState3 = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(false),
_useState4 = _slicedToArray(_useState3, 2),
isDragging = _useState4[0],
setIsDragging = _useState4[1];
// Performance optimization: cache for drag operations
var dragCacheRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)({
draggedObj: null,
overObj: null,
allRowsCache: null,
lastUpdateTime: 0,
tbodyRef: null,
colCount: 0,
lastOverOrder: null,
rafId: null
});
// ================================================================
// drag & drop
// ================================================================
var draggedObj = null;
var overObj = null;
// Helper function to filter out cloned elements and get only real rows
var getRealRows = function getRealRows(rows) {
return rows.filter(function (row) {
return !row.classList.contains('row-obj-clonelast') && !row.classList.contains('row-obj-lastplaceholder');
});
};
var placeholderGenerator = function placeholderGenerator(trHeight) {
// Use cached tbodyRef and colCount for better performance
var tbodyRef = dragCacheRef.current.tbodyRef;
if (!tbodyRef) {
tbodyRef = getTbody(spyElement);
dragCacheRef.current.tbodyRef = tbodyRef;
}
if (tbodyRef === null) return null;
// Cache colCount to avoid repeated queries
var colCount = dragCacheRef.current.colCount;
if (colCount === 0) {
var firstRow = tbodyRef.querySelector('tr');
if (firstRow === null) return null;
colCount = firstRow.children.length;
dragCacheRef.current.colCount = colCount;
}
// Insert a row at the "index" of the table
var newRow = document.createElement('tr');
newRow.className = 'row-placeholder';
newRow.dataset.placeholder = 'true';
newRow.style.height = trHeight + 'px';
newRow.style.minHeight = trHeight + 'px'; // Ensure minimum height
// Insert a cell in the row at index
var newCell = newRow.insertCell(0);
newCell.colSpan = colCount;
newCell.style.minHeight = trHeight + 'px'; // Ensure cell has minimum height
// Use non-breaking space to ensure proper height rendering
// Multiple spaces or a placeholder element helps maintain consistent height
newCell.innerHTML = ' '; // Use instead of regular space for better height consistency
return newRow;
};
var lastPlaceholderGenerator = function lastPlaceholderGenerator(trHeight) {
// Use cached tbodyRef and colCount for better performance
var tbodyRef = dragCacheRef.current.tbodyRef;
if (!tbodyRef) {
tbodyRef = getTbody(spyElement);
dragCacheRef.current.tbodyRef = tbodyRef;
}
if (tbodyRef === null) return null;
var curEl = tbodyRef.querySelector('.row-obj-lastplaceholder');
if (curEl !== null) return;
// Cache colCount to avoid repeated queries
var colCount = dragCacheRef.current.colCount;
if (colCount === 0) {
var firstRow = tbodyRef.querySelector('tr');
if (firstRow === null) return null;
colCount = firstRow.children.length;
dragCacheRef.current.colCount = colCount;
}
// Create a dedicated last placeholder row that is kept in DOM but hidden by default
var newRow = document.createElement('tr');
newRow.className = 'row-obj row-obj-lastplaceholder';
// NOTE: Do NOT set data-placeholder here, otherwise it will be removed by removePlaceholder
newRow.style.height = trHeight + 'px';
newRow.style.minHeight = trHeight + 'px';
newRow.style.display = 'none';
var newCell = newRow.insertCell(0);
newCell.colSpan = colCount;
newCell.style.minHeight = trHeight + 'px';
newCell.innerHTML = ' ';
// Insert after the last real row (excluding cloned rows)
var rows = getRealRows(allRows(spyElement));
var lastRealRow = rows.length > 0 ? rows[rows.length - 1] : null;
if (lastRealRow && lastRealRow.parentNode === tbodyRef) {
insertAfter(newRow, lastRealRow);
} else {
tbodyRef.appendChild(newRow);
}
return newRow;
};
// An invisible HELPER element used to trigger the touch of the last element
var lastRowGenerator = function lastRowGenerator(trHeight) {
var tbodyRef = getTbody(spyElement);
if (tbodyRef === null || tbodyRef.querySelector('tr') === null) return;
var curEl = tbodyRef.querySelector('.row-obj-clonelast');
if (curEl !== null) return;
// Insert a row at the "index" of the table
var newRow = document.createElement('tr');
newRow.className = 'row-obj row-obj-clonelast';
newRow.dataset.order = allRows(spyElement).length.toString();
newRow.style.height = trHeight + 'px';
// Insert a cell in the row at index
var newCell = newRow.insertCell(0);
newCell.colSpan = tbodyRef.querySelector('tr').children.length;
// Append a text node to the cell
var newText = document.createTextNode(' ');
newCell.appendChild(newText);
//
lastPlaceholderGenerator(trHeight);
return newRow;
};
var removePlaceholder = function removePlaceholder() {
// Use cached tbodyRef
var tbodyRef = dragCacheRef.current.tbodyRef;
if (!tbodyRef) {
tbodyRef = getTbody(spyElement);
dragCacheRef.current.tbodyRef = tbodyRef;
}
if (tbodyRef === null) return;
// Optimize: use querySelectorAll and remove in batch
var placeholders = tbodyRef.querySelectorAll("[data-placeholder]");
if (placeholders.length > 0) {
// Use DocumentFragment for batch removal (though in this case direct removal is fine)
placeholders.forEach(function (node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
});
}
};
// Initialize drag & drop data
// !!! Execute it only once
var initDragDropData = function initDragDropData() {
if (spyElement === null) return;
if (typeof spyElement.dataset.dragdropDataInit !== 'undefined') return;
spyElement.dataset.dragdropDataInit = 1;
var _allRows = allRows(spyElement);
// sort list data
var listIndexes = _allRows.map(function (node, i) {
return i;
});
setSortData(listIndexes);
//last placeholder
if (_allRows.length > 0) {
var lastEl = lastRowGenerator(_allRows.at(-1).clientHeight);
if (typeof _allRows.at(-1) !== 'undefined') {
insertAfter(lastEl, _allRows.at(-1));
}
}
};
var handleTbodyEnter = function handleTbodyEnter(e) {
var _table = e.currentTarget.closest('table');
if (_table === null) return;
_table.querySelector('tbody').classList.add('drag-trigger-mousedown');
};
var handleTbodyLeave = function handleTbodyLeave(e) {
var tbodyRef = getTbody(spyElement);
if (tbodyRef === null) return;
tbodyRef === null || tbodyRef === void 0 ? void 0 : tbodyRef.classList.remove('drag-trigger-mousedown');
};
// events fired on the drop targets
// Optimized with requestAnimationFrame, throttling and caching
var handledragOver = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function (e) {
// Always prevent default in sync code
e.preventDefault();
// Use cached draggedObj and tbodyRef
var currentDraggedObj = dragCacheRef.current.draggedObj || draggedObj;
if (currentDraggedObj === null) return;
var tbodyRef = dragCacheRef.current.tbodyRef;
if (!tbodyRef) {
tbodyRef = getTbody(spyElement);
if (tbodyRef === null) return;
dragCacheRef.current.tbodyRef = tbodyRef;
}
// Early return for placeholder targets
if (e.target.classList.contains('row-placeholder')) return;
var itemsWrapper = e.target.parentNode;
if (!itemsWrapper || !itemsWrapper.classList || !itemsWrapper.classList.contains('row-obj')) {
return;
}
// Skip cloned elements - they should not be valid drop targets
if (itemsWrapper.classList.contains('row-obj-lastplaceholder')) {
return;
}
// Check if we're still over the same row (avoid unnecessary operations)
var currentOrder = Number(itemsWrapper.dataset.order);
if (dragCacheRef.current.lastOverOrder === currentOrder) {
return; // Same target, skip
}
// console.log(' --> overObj: ', itemsWrapper);
// Use requestAnimationFrame for smoother DOM updates
// Cancel previous frame if pending
if (dragCacheRef.current.rafId !== null) {
cancelAnimationFrame(dragCacheRef.current.rafId);
}
// Store references for use in RAF callback
var targetWrapper = itemsWrapper;
var targetOrder = currentOrder;
dragCacheRef.current.rafId = requestAnimationFrame(function () {
overObj = targetWrapper;
dragCacheRef.current.overObj = targetWrapper;
dragCacheRef.current.lastOverOrder = targetOrder;
currentDraggedObj.style.display = 'none';
removePlaceholder();
// Cache allRows result to avoid multiple queries
var cachedRows = dragCacheRef.current.allRowsCache;
var now = Date.now();
if (!cachedRows || now - dragCacheRef.current.lastUpdateTime > 100) {
cachedRows = allRows(spyElement);
dragCacheRef.current.allRowsCache = cachedRows;
dragCacheRef.current.lastUpdateTime = now;
}
// Filter out cloned elements to get real rows count
var realRows = getRealRows(cachedRows);
var totalRows = realRows.length;
var overOrder = Number(overObj.dataset.order);
// When hovering over the last real row, use its height for placeholder
// Otherwise use the overObj's height
var isOverLastRow = overOrder === totalRows - 1 && realRows.length > 0 && realRows[totalRows - 1];
var placeholderHeight = isOverLastRow ? realRows[totalRows - 1].clientHeight : overObj.clientHeight;
var placeholder = placeholderGenerator(placeholderHeight);
if (placeholder) {
var draggedOrder = Number(currentDraggedObj.dataset.order);
//console.log(' --> drag index list: ', draggedOrder, overOrder, totalRows - 1);
tbodyRef.insertBefore(placeholder, overObj);
}
dragCacheRef.current.rafId = null;
});
}, [sortData, spyElement]);
var handleDragStart = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function (e) {
var tbodyRef = getTbody(spyElement);
if (tbodyRef === null) return;
setIsDragging(true);
draggedObj = e.currentTarget;
// Cache draggedObj and tbodyRef for performance
dragCacheRef.current.draggedObj = draggedObj;
dragCacheRef.current.tbodyRef = tbodyRef;
dragCacheRef.current.lastOverOrder = null; // Reset
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', draggedObj);
draggedObj.classList.add('dragging');
// Cache allRows and use cached result
var cachedRows = allRows(spyElement);
dragCacheRef.current.allRowsCache = cachedRows;
dragCacheRef.current.lastUpdateTime = Date.now();
// Cache colCount if not already cached
if (dragCacheRef.current.colCount === 0) {
var firstRow = tbodyRef.querySelector('tr');
if (firstRow) {
dragCacheRef.current.colCount = firstRow.children.length;
}
}
var lastRow = cachedRows[cachedRows.length - 1];
if (lastRow && !lastRow.classList.contains('row-obj-lastplaceholder')) {
lastRow.style.setProperty('display', 'table-row', "important");
}
// callback
var dragStart = function dragStart(callback) {
callback.call(null, draggedObj, sortData, sortDataByIndex(sortData, data));
};
onRowDrag === null || onRowDrag === void 0 ? void 0 : onRowDrag(dragStart, null);
}, [handledragOver, sortData, data, spyElement, onRowDrag]);
var handleDragEnd = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function (e) {
var tbodyRef = getTbody(spyElement);
if (tbodyRef === null) return;
setIsDragging(false);
// Use cached draggedObj if available
var currentDraggedObj = dragCacheRef.current.draggedObj || draggedObj;
var currentOverObj = dragCacheRef.current.overObj || overObj;
if (currentDraggedObj) {
currentDraggedObj.style.display = 'table-row';
currentDraggedObj.classList.remove('dragging');
}
removePlaceholder();
tbodyRef === null || tbodyRef === void 0 ? void 0 : tbodyRef.classList.remove('drag-trigger-mousedown');
// Cancel any pending animation frame
if (dragCacheRef.current.rafId !== null) {
cancelAnimationFrame(dragCacheRef.current.rafId);
dragCacheRef.current.rafId = null;
}
if (currentOverObj === null) {
// Reset cache
dragCacheRef.current.draggedObj = null;
dragCacheRef.current.overObj = null;
dragCacheRef.current.allRowsCache = null;
dragCacheRef.current.lastOverOrder = null;
return;
}
// update state
var curData = [];
curData = JSON.parse(JSON.stringify(sortData));
var from = Number(currentDraggedObj.dataset.order);
var to = Number(currentOverObj.dataset.order);
// Get real rows to determine the actual last row index
var allRowsForLastIndex = allRows(spyElement);
var realRows = getRealRows(allRowsForLastIndex);
var actualLastRowIndex = realRows.length - 1;
// Standard drag-and-drop logic:
// When dragging from a lower index to a higher index, we need to decrement 'to'
// because removing the element at 'from' causes all subsequent elements to shift left by 1
// However, when dragging to the last position, we want to swap with the last element
// After removing 'from', if we want to swap with the last element, we should insert
// at the position that will result in the dragged element being at the last position
if (from < to) {
// Special case: dragging to the last position
// We want to swap with the last element, so after removing 'from',
// we should insert at the new last position (which is curData.length - 1)
// Since 'to' is the original last index, and we're removing 'from' (which is < 'to'),
// the new last position after removal is still 'to' (no shift because 'from' is before 'to')
// Wait, that's not right. If we remove 'from', elements from 'from+1' to 'to' shift left by 1
// So 'to' becomes 'to-1'. But we want to insert at the last position, which is 'to-1'
// So we should decrement 'to' as normal. But then the element will be at 'to-1', not 'to'
//
// Actually, the issue is: when dragging to the last element, we want to SWAP with it
// So the dragged element should end up at the last position, and the last element should
// end up at the dragged element's original position
//
// Let's think step by step with an example: [A, B, C, D, E], from=1 (B), to=4 (E)
// We want result: [A, C, D, E, B] (B and E swapped)
// Step 1: Remove B -> [A, C, D, E] (indices 0-3)
// Step 2: Insert B at position 4 -> [A, C, D, E, B] ✓
// So 'to' should be 4 (not decremented) to get the correct result
if (to === actualLastRowIndex) {
// Don't decrement 'to' when dragging to the last position
// This ensures the element is inserted at the last position after removal
} else {
// Normal case: dragging forward but not to the last position
to--;
}
}
// If from >= to, no adjustment needed (dragging backward)
// Optimize: simplify the sorting logic (the nested loop was inefficient)
curData.splice(to, 0, curData.splice(from, 1)[0]);
var newData = useTableDraggable_toConsumableArray(curData); // Direct copy instead of nested loop
setSortData(newData);
// Performance optimization: batch DOM updates using a map
var table = spyElement.querySelector('table');
if (!table) return;
var tbody = table.querySelector('tbody');
if (!tbody) return;
// Get all rows once and create a map for faster lookups
// Support both data-key attribute (user-provided) and data-order fallback
var allRowsElements = Array.from(allRows(spyElement));
// Create a map: original index (from sortData) -> row element
var rowMap = new Map();
allRowsElements.forEach(function (row) {
// First try to use data-key attribute (if user provided it)
var dataKey = row.getAttribute('data-key');
if (dataKey) {
var match = dataKey.match(/row-(\d+)/);
if (match) {
var index = Number(match[1]);