@maherunlocker/custom-react-table
Version:
dynamic table based on react table v7
210 lines • 11.5 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());
});
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import 'regenerator-runtime/runtime';
import React from 'react';
import axios from 'axios';
import { I18nextProvider } from 'react-i18next';
import { AngleSmallRightIcon } from '../components/assets/AngleSmallRightIcon';
import { DuplicateIcon } from '../components/assets/DuplicateIcon';
import LoadingDataAnimation from '../components/LoadingDataAnimation';
import LoadingErrorAnimation from '../components/LoadingDataAnimation/LoadingErrorAnimation';
import { Table } from './Table';
import { TrashIcon } from '../components/assets/TrashIcon';
import { useStyles } from './TableStyle';
import 'react-toastify/dist/ReactToastify.css';
import i18nConfig from '../i18n';
export const DynamicTableContext = React.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';
export 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.useState();
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
const classes = useStyles();
const defaultContext = {
setSelectedRows,
};
function fetchData(url) {
return __awaiter(this, void 0, void 0, function* () {
yield axios
.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.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) => (_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.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 ? (_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 ? (_jsx(AngleSmallRightIcon, { height: 25, width: 25, className: classes.iconDirectionAsc })) : (_jsx(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) => (_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 }) => (_jsxs(React.Fragment, { children: [_jsx(TrashIcon, { width: 25, height: 25, onClick: () => deleteRow(row.index) }), _jsx(DuplicateIcon, { width: 25, height: 25, onClick: () => {
duplicateRow(row.index);
} })] })),
},
];
}
return modifiedColumns;
// eslint-disable-next-line
}, [apiResultColumns]);
const data = React.useMemo(() => ((apiResult === null || apiResult === void 0 ? void 0 : apiResult.data) !== undefined ? apiResult === null || apiResult === void 0 ? void 0 : apiResult.data : []), [apiResult]);
React.useEffect(() => {
fetchData(url);
setDataIsUpdated !== undefined && setDataIsUpdated(false);
// eslint-disable-next-line
}, [url, dataIsUpdated]);
if (loading)
return _jsx(LoadingDataAnimation, {});
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 _jsx(LoadingErrorAnimation, {});
return (_jsx(I18nextProvider, Object.assign({ i18n: i18nConfig }, { children: _jsx(DynamicTableContext.Provider, Object.assign({ value: defaultContext }, { children: _jsx(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 }) })) })));
}
//# sourceMappingURL=DynamicTable.js.map