@maherunlocker/custom-react-table
Version:
dynamic table based on react table v7
217 lines • 12.4 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicTable = exports.DynamicTableContext = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
require("regenerator-runtime/runtime");
const react_1 = __importDefault(require("react"));
const axios_1 = __importDefault(require("axios"));
const react_i18next_1 = require("react-i18next");
const AngleSmallRightIcon_1 = require("../components/assets/AngleSmallRightIcon");
const DuplicateIcon_1 = require("../components/assets/DuplicateIcon");
const LoadingDataAnimation_1 = __importDefault(require("../components/LoadingDataAnimation"));
const LoadingErrorAnimation_1 = __importDefault(require("../components/LoadingDataAnimation/LoadingErrorAnimation"));
const Table_1 = require("./Table");
const TrashIcon_1 = require("../components/assets/TrashIcon");
const TableStyle_1 = require("./TableStyle");
require("react-toastify/dist/ReactToastify.css");
const i18n_1 = __importDefault(require("../i18n"));
exports.DynamicTableContext = react_1.default.createContext(null);
function filterGreaterThan(rows, id, filterValue) {
return rows.filter((row) => {
const rowValue = row.values[id[0]];
return rowValue >= filterValue;
});
}
// This is an autoRemove method on the filter function
//that when given the new filter value and returns true, the filter
// will be automatically removed. Normally this is just an undefined
// check, but here, we want to remove the filter if it's not a number
filterGreaterThan.autoRemove = (val) => typeof val !== 'number';
function DynamicTable({ url, name, actionColumn, canGroupBy, canSort, canResize, canExpand, canSelect, customSelect, showGlobalFilter, showFilter, showColumnIcon, canDeleteOrDuplicate, arrayOfCustomColumns, filterActive, setLocalFilterActive, customJsxSideFilterButton, onClick, elevationTable, setSelectedRows, setDataIsUpdated, dataIsUpdated, minHeight, maxHeight, requestHeader, setData, canMovedCheckboxLeftOnExpand, defaultHiddenColumns, defaultPaginationValues, }) {
const [apiResult, setApiResult] = react_1.default.useState();
const [loading, setLoading] = react_1.default.useState(true);
const [error, setError] = react_1.default.useState(null);
const classes = (0, TableStyle_1.useStyles)();
const defaultContext = {
setSelectedRows,
};
function fetchData(url) {
return __awaiter(this, void 0, void 0, function* () {
yield axios_1.default
.get(url, {
headers: requestHeader,
})
.then((response) => {
setApiResult(response.data);
setData !== undefined &&
setData({
data: response.data.data,
others: 'response.data.othersData',
});
})
.catch((err) => {
setError(err);
})
.finally(() => {
setLoading(false);
});
});
}
if (elevationTable === undefined) {
elevationTable = 0;
}
const apiResultColumns = react_1.default.useMemo(() => apiResult !== undefined &&
apiResult.structure !== undefined &&
Array.isArray(apiResult === null || apiResult === void 0 ? void 0 : apiResult.structure)
? apiResult.structure
.filter((key) => key !== 'subRows')
.map((key) => {
if (key.toLowerCase().includes('image') ||
key.toLowerCase().includes('picture') ||
key.toLowerCase().includes('logo') ||
key.toLowerCase().includes('icon') ||
key.toLowerCase().includes('pic') ||
key.toLowerCase().includes('img')) {
return {
id: key,
Header: key,
accessor: key,
disableFilters: true,
disableResizing: true,
canFilter: false,
width: 120,
//minWidth: 120,
Cell: (value) => ((0, jsx_runtime_1.jsx)("img", { src: value.cell.value, style: {
height: '50px',
width: '100px',
objectFit: 'contain',
}, alt: "" })),
};
}
return {
id: key,
Header: key,
accessor: key,
aggregate: 'count',
primary: false,
canFilter: true,
filter: 'multiSelect',
Aggregated: ({ cell: { value } }) => `${value} `,
};
})
: [], [apiResult]);
const deleteRow = (index) => {
const dataCopy = Object.assign({}, apiResult);
dataCopy.data.splice(index, 1);
setApiResult(dataCopy);
};
function duplicateRow(index) {
const duplicatedData = Object.assign({}, apiResult);
const duplicateRow = duplicatedData === null || duplicatedData === void 0 ? void 0 : duplicatedData.data[index];
const firstPart = duplicatedData === null || duplicatedData === void 0 ? void 0 : duplicatedData.data.slice(0, index + 1);
const secondPart = duplicatedData === null || duplicatedData === void 0 ? void 0 : duplicatedData.data.slice(index + 1, duplicatedData.data.length);
duplicatedData.data = [...firstPart, duplicateRow, ...secondPart];
setApiResult(duplicatedData);
}
const columns = react_1.default.useMemo(() => {
let modifiedColumns = apiResultColumns;
if (canExpand) {
modifiedColumns = [
{
// Build our expander column
id: 'expander',
Header: '',
// Header: ({ getToggleAllRowsExpandedProps, isAllRowsExpanded }: any) => (
// <span {...getToggleAllRowsExpandedProps({ title: 'expand all' })}>
// {isAllRowsExpanded ? (
// <AngleSmallRightIcon height={25} width={25} className={classes.iconDirectionAsc} />
// ) : (
// <AngleSmallRightIcon height={25} width={25} />
// )}
// </span>
// ),
minWidth: 30,
// width: 60,
// disableResizing: true,
// disableGroupBy: true,
canFilter: false,
disableFilters: true,
Cell: ({ row }) =>
// Use the row.canExpand and row.getToggleRowExpandedProps prop getter
// to build the toggle for expanding a row
row.canExpand ? ((0, jsx_runtime_1.jsx)("span", Object.assign({}, row.getToggleRowExpandedProps({
style: {
// We can even use the row.depth property
// and paddingLeft to indicate the depth
// of the row
paddingLeft: `${row.depth * 2}rem`,
},
title: '',
}), { children: row.isExpanded ? ((0, jsx_runtime_1.jsx)(AngleSmallRightIcon_1.AngleSmallRightIcon, { height: 25, width: 25, className: classes.iconDirectionAsc })) : ((0, jsx_runtime_1.jsx)(AngleSmallRightIcon_1.AngleSmallRightIcon, { height: 25, width: 25 })) }))) : null,
},
...modifiedColumns,
];
}
if (arrayOfCustomColumns && arrayOfCustomColumns.length > 0) {
arrayOfCustomColumns.map((elm) => modifiedColumns.splice(elm.indexOFColumn, 0, {
id: elm.columnName,
Header: elm.columnName,
accessor: elm.filterName,
aggregate: 'count',
disableFilters: elm.disableFilter === undefined ? false : elm.disableFilter,
disableResizing: false,
filter: 'multiSelect',
Cell: (cell) => ((0, jsx_runtime_1.jsx)(elm.customJsx, { selectedRow: Object.assign(Object.assign({}, cell.row.original), { depth: cell.row.depth, selectedRows: cell.state.customSelectedRows.length > 0
? cell.state.customSelectedRows.map((select) => select.original)
: [] }) })),
}));
}
if (canDeleteOrDuplicate) {
modifiedColumns = [
...modifiedColumns,
{
Header: '_Actions',
id: '_Actions',
accessor: (str) => 'delete',
canFilter: false,
disableFilters: true,
disableGroupBy: true,
disableSortBy: true,
Cell: ({ row }) => ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(TrashIcon_1.TrashIcon, { width: 25, height: 25, onClick: () => deleteRow(row.index) }), (0, jsx_runtime_1.jsx)(DuplicateIcon_1.DuplicateIcon, { width: 25, height: 25, onClick: () => {
duplicateRow(row.index);
} })] })),
},
];
}
return modifiedColumns;
// eslint-disable-next-line
}, [apiResultColumns]);
const data = react_1.default.useMemo(() => ((apiResult === null || apiResult === void 0 ? void 0 : apiResult.data) !== undefined ? apiResult === null || apiResult === void 0 ? void 0 : apiResult.data : []), [apiResult]);
react_1.default.useEffect(() => {
fetchData(url);
setDataIsUpdated !== undefined && setDataIsUpdated(false);
// eslint-disable-next-line
}, [url, dataIsUpdated]);
if (loading)
return (0, jsx_runtime_1.jsx)(LoadingDataAnimation_1.default, {});
if (error ||
apiResult === undefined ||
(apiResult === null || apiResult === void 0 ? void 0 : apiResult.structure) === undefined ||
(apiResult === null || apiResult === void 0 ? void 0 : apiResult.structure.length) === 0)
return (0, jsx_runtime_1.jsx)(LoadingErrorAnimation_1.default, {});
return ((0, jsx_runtime_1.jsx)(react_i18next_1.I18nextProvider, Object.assign({ i18n: i18n_1.default }, { children: (0, jsx_runtime_1.jsx)(exports.DynamicTableContext.Provider, Object.assign({ value: defaultContext }, { children: (0, jsx_runtime_1.jsx)(Table_1.Table, { name: name, columns: columns, setSelectedRows: setSelectedRows, data: data, canGroupBy: canGroupBy, canSort: canSort, canSelect: canSelect, canResize: canResize, actionColumn: actionColumn, showGlobalFilter: showGlobalFilter, showFilter: showFilter, showColumnIcon: showColumnIcon, filterActive: filterActive, setLocalFilterActive: setLocalFilterActive, customJsxSideFilterButton: customJsxSideFilterButton, onClick: onClick, elevationTable: elevationTable, minHeight: minHeight, maxHeight: maxHeight, customSelect: customSelect, defaultHiddenColumns: defaultHiddenColumns, defaultPaginationValues: defaultPaginationValues, canMovedCheckboxLeftOnExpand: canMovedCheckboxLeftOnExpand }) })) })));
}
exports.DynamicTable = DynamicTable;
//# sourceMappingURL=DynamicTable.js.map