Files
no-copy-frontend/src/app/components/tanstakTable.tsx
T

664 lines
18 KiB
TypeScript
Raw Normal View History

2025-12-12 14:22:00 +07:00
'use client';
import { useState, useMemo } from 'react';
import {
useReactTable,
getCoreRowModel,
getSortedRowModel,
getPaginationRowModel,
getFilteredRowModel,
ColumnDef,
SortingState,
ColumnFiltersState,
} from '@tanstack/react-table';
2025-12-26 14:03:57 +07:00
import { IconImageFile, IconVideoFile, IconAudioFile, IconEye, IconDoubleArrowRight, IconArrowRight, IconDoubleArrowLeft, IconArrowLeft, IconArrowUp, IconArrowDown, IconFilter, IconFileOpen, IconShieldExclamation, IconDelete } from '@/app/ui/icons/icons';
2025-12-12 20:28:59 +07:00
import { useTranslations } from 'next-intl';
import DropDownList from '@/app/components/dropDownList';
2025-12-26 14:03:57 +07:00
import { useQuery } from '@tanstack/react-query';
import { getUserFilesData, removeUserFile } from '@/app/actions/fileEntity';
2025-12-12 14:22:00 +07:00
// Типы данных
2025-12-12 20:28:59 +07:00
type FileType = 'image' | 'video' | 'audio';
type FileItem = {
2025-12-26 14:03:57 +07:00
id: string;
2025-12-12 20:28:59 +07:00
fileName: string;
fileType: FileType;
2025-12-26 14:03:57 +07:00
violations?: number | undefined;
checks?: number | undefined;
lastCheck?: number; // timestamp в миллисекундах
2025-12-12 14:22:00 +07:00
};
2025-12-12 20:28:59 +07:00
// Иконки для типов файлов
const FileTypeIcon = ({ type }: { type: FileType }) => {
switch (type) {
case 'image':
return <span className="text-[#f08c00]">
<IconImageFile />
</span>;
case 'video':
return <span className="text-[#2f9e44]">
<IconVideoFile />
</span>;
case 'audio':
return <span className="text-[#1971c2]">
<IconAudioFile />
</span>;
default:
return <span>📄</span>;
2025-12-12 14:22:00 +07:00
}
2025-12-12 20:28:59 +07:00
};
2025-12-12 14:22:00 +07:00
2025-12-12 20:28:59 +07:00
// Форматирование даты из timestamp
const formatDate = (timestamp: number) => {
const date = new Date(timestamp);
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
2025-12-26 14:03:57 +07:00
2025-12-12 20:28:59 +07:00
return `${day}.${month}.${year}`;
};
2025-12-26 14:03:57 +07:00
const formatDateTime = (timestamp: number) => {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
};
2025-12-12 20:28:59 +07:00
export default function TanstakFilesTable() {
2025-12-26 14:03:57 +07:00
const {
data: userFilesData,
isLoading,
isError,
error
} = useQuery({
queryKey: ['userFilesData'],
queryFn: () => {
return getUserFilesData();
}
});
const [tableData] = useState<FileItem[]>(
userFilesData.files.map((item: any) => {
//когда с бека будет приходить время в милисекундах можно будет удалить
const [datePart, timePart] = item.updatedAt.split(' ');
const [day, month, year] = datePart.split('-').map(Number);
const [hours, minutes, seconds] = timePart.split(':').map(Number);
const newDate = new Date(year, month - 1, day, hours, minutes, seconds).getTime();
return {
id: item.id,
fileName: item.originalFileName,
fileType: item.mimeType.toLocaleLowerCase(),
violations: item.violations,
checks: item.checks,
lastCheck: newDate
}
})
)
if (typeof window !== 'undefined') {
}
2025-12-12 14:22:00 +07:00
// Состояния
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
2025-12-12 20:28:59 +07:00
const [dateFilter, setDateFilter] = useState<string>('all');
const [typeFilter, setTypeFilter] = useState<string>('all');
const t = useTranslations("Global");
2025-12-12 14:22:00 +07:00
// Определение колонок
2025-12-12 20:28:59 +07:00
const columns = useMemo<ColumnDef<FileItem>[]>(
2025-12-12 14:22:00 +07:00
() => [
{
2025-12-12 20:28:59 +07:00
accessorKey: 'fileName',
header: ({ column }) => (
<div className="flex items-center justify-start">
<span>
{t('file')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="ml-2 p-1 hover:bg-gray-200 rounded"
>
{
column.getIsSorted() === 'asc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowUp />
2025-12-12 20:28:59 +07:00
</span>
: column.getIsSorted() === 'desc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowDown />
2025-12-12 20:28:59 +07:00
</span>
: <span>
2025-12-17 16:41:07 +07:00
<IconFilter />
2025-12-12 20:28:59 +07:00
</span>
}
</button>
</div>
2025-12-12 14:22:00 +07:00
),
cell: ({ row }) => (
2025-12-19 13:05:50 +07:00
<div className="flex items-center space-x-2 w-[250px]">
2025-12-12 20:28:59 +07:00
<FileTypeIcon type={row.original.fileType} />
<div>
2025-12-19 13:05:50 +07:00
<div className="font-medium w-full max-w-[300px] truncate" title={row.original.fileName}>{row.original.fileName}</div>
2025-12-12 20:28:59 +07:00
</div>
</div>
2025-12-12 14:22:00 +07:00
),
enableColumnFilter: false,
},
2025-12-26 14:03:57 +07:00
{
accessorKey: 'status',
header: ({ column }) => (
<div className="flex items-center justify-center">
<span>
status
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="ml-2 p-1 hover:bg-gray-200 rounded"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => {
return (
<div className={`text-center font-semibold`}>
status
</div>
)
},
},
2025-12-12 14:22:00 +07:00
{
2025-12-12 20:28:59 +07:00
accessorKey: 'violations',
header: ({ column }) => (
<div className="flex items-center justify-center">
<span>
{t('violations')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="ml-2 p-1 hover:bg-gray-200 rounded"
>
{
column.getIsSorted() === 'asc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowUp />
2025-12-12 20:28:59 +07:00
</span>
: column.getIsSorted() === 'desc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowDown />
2025-12-12 20:28:59 +07:00
</span>
: <span>
2025-12-17 16:41:07 +07:00
<IconFilter />
2025-12-12 20:28:59 +07:00
</span>
}
</button>
</div>
),
2025-12-26 14:03:57 +07:00
cell: ({ row }) => {
let classCollor = () => {
let result = ''
if (row.original.violations !== undefined) {
result = row.original.violations > 0 ? 'text-red-600' : 'text-green-600'
}
return result;
}
return (
<div className={`text-center font-semibold ${classCollor()}`}>
{row.original.violations !== undefined ? row.original.violations : '-'}
</div>
)
},
2025-12-12 14:22:00 +07:00
},
{
2025-12-12 20:28:59 +07:00
accessorKey: 'checks',
header: ({ column }) => (
<div className="flex items-center justify-center">
<span>
{t('checks')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="ml-2 p-1 hover:bg-gray-200 rounded"
>
{
column.getIsSorted() === 'asc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowUp />
2025-12-12 20:28:59 +07:00
</span>
: column.getIsSorted() === 'desc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowDown />
2025-12-12 20:28:59 +07:00
</span>
: <span>
2025-12-17 16:41:07 +07:00
<IconFilter />
2025-12-12 20:28:59 +07:00
</span>
}
</button>
</div>
),
cell: ({ row }) => (
<div className="text-center">
2025-12-26 14:03:57 +07:00
{row.original.checks !== undefined ? row.original.checks : '-'}
2025-12-12 20:28:59 +07:00
</div>
),
2025-12-12 14:22:00 +07:00
},
{
2025-12-12 20:28:59 +07:00
accessorKey: 'lastCheck',
header: ({ column }) => (
<div className="flex items-center justify-center">
<span>
{t('last-check')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="ml-2 p-1 hover:bg-gray-200 rounded"
>
{
column.getIsSorted() === 'asc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowUp />
2025-12-12 20:28:59 +07:00
</span>
: column.getIsSorted() === 'desc' ?
<span>
2025-12-17 16:41:07 +07:00
<IconArrowDown />
2025-12-12 20:28:59 +07:00
</span>
: <span>
2025-12-17 16:41:07 +07:00
<IconFilter />
2025-12-12 20:28:59 +07:00
</span>
}
</button>
</div>
),
2025-12-26 14:03:57 +07:00
cell: ({ row }) => {
return (
<div className="text-center">
{row.original.lastCheck ? (
<>
{formatDate(row.original.lastCheck)}
<br />
{formatDateTime(row.original.lastCheck)}
</>
) : (
<div>-</div>
)}
</div>
)
},
2025-12-12 20:28:59 +07:00
enableColumnFilter: false,
2025-12-12 14:22:00 +07:00
},
{
2025-12-12 20:28:59 +07:00
id: 'actions',
header: () => {
return (
<div className="flex items-center justify-center">
{t('actions')}
</div>
)
},
cell: ({ row }) => (
<div className="flex space-x-2 justify-center">
<button
onClick={() => handleView(row.original)}
className="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm"
>
<IconEye />
</button>
<button
onClick={() => handleDownload(row.original)}
className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm"
>
2025-12-19 13:05:50 +07:00
<IconFileOpen />
2025-12-12 20:28:59 +07:00
</button>
<button
onClick={() => handleProtect(row.original)}
className="px-3 py-1 bg-violet-500 text-white rounded hover:bg-violet-600 text-sm"
>
2025-12-19 13:05:50 +07:00
<IconShieldExclamation />
2025-12-12 20:28:59 +07:00
</button>
2025-12-26 14:03:57 +07:00
<button
onClick={() => handleRemove(row.original)}
className="px-3 py-1 bg-red-700 text-white rounded hover:bg-red-800 text-sm"
>
<IconDelete />
</button>
2025-12-12 20:28:59 +07:00
</div>
),
enableSorting: false,
enableColumnFilter: false,
2025-12-12 14:22:00 +07:00
},
],
[]
);
2025-12-12 20:28:59 +07:00
// Обработчики действий
const handleView = (file: FileItem) => {
console.log(`Просмотр файла: ${file.fileName}`);
};
const handleDownload = (file: FileItem) => {
console.log(`Скачать: ${file.fileName}`);
};
const handleProtect = (file: FileItem) => {
console.log(`Щиток: ${file.fileName}`);
};
2025-12-26 14:03:57 +07:00
const handleRemove = async (file: FileItem) => {
const response = await removeUserFile(file.id);
console.log(`Removed: ${response}`);
};
2025-12-12 20:28:59 +07:00
// Фильтрация по типу файла и дате
const filteredData = useMemo(() => {
2025-12-26 14:03:57 +07:00
let result = tableData;
2025-12-12 20:28:59 +07:00
// Фильтр по типу файла
if (typeFilter !== 'all') {
result = result.filter(item => item.fileType === typeFilter);
}
// Фильтр по дате
if (dateFilter !== 'all') {
const now = Date.now();
const oneDay = 24 * 60 * 60 * 1000;
const sevenDays = 7 * oneDay;
const thirtyDays = 30 * oneDay;
switch (dateFilter) {
case 'today':
const todayStart = new Date().setHours(0, 0, 0, 0);
2025-12-26 14:03:57 +07:00
result = result.filter(item => {
if (item.lastCheck) {
return item.lastCheck >= todayStart
} else {
return 0
}
});
2025-12-12 20:28:59 +07:00
break;
case 'week':
const weekAgo = now - sevenDays;
2025-12-26 14:03:57 +07:00
result = result.filter(item => {
if (item.lastCheck) {
return item.lastCheck >= weekAgo;
}
});
2025-12-12 20:28:59 +07:00
break;
case 'month':
const monthAgo = now - thirtyDays;
2025-12-26 14:03:57 +07:00
result = result.filter(item => {
if (item.lastCheck) {
return item.lastCheck >= monthAgo;
}
});
2025-12-12 20:28:59 +07:00
break;
case 'older':
const monthAgo2 = now - thirtyDays;
2025-12-26 14:03:57 +07:00
result = result.filter(item => {
if (item.lastCheck) {
return item.lastCheck < monthAgo2;
}
});
2025-12-12 20:28:59 +07:00
break;
}
}
return result;
2025-12-26 14:03:57 +07:00
}, [tableData, typeFilter, dateFilter]);
2025-12-12 20:28:59 +07:00
2025-12-12 14:22:00 +07:00
// Создание таблицы
const table = useReactTable({
2025-12-12 20:28:59 +07:00
data: filteredData,
2025-12-12 14:22:00 +07:00
columns,
state: {
sorting,
columnFilters,
},
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFilteredRowModel: getFilteredRowModel(),
2025-12-12 20:28:59 +07:00
initialState: {
pagination: {
pageSize: 10,
},
},
2025-12-12 14:22:00 +07:00
});
return (
2025-12-19 13:05:50 +07:00
<div className="p-6 mx-auto tanstak-table">
2025-12-12 20:28:59 +07:00
{/* Фильтры */}
2025-12-19 13:05:50 +07:00
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 pb-4 pt-0 px-0">
2025-12-12 20:28:59 +07:00
<div className="flex flex-col md:flex-row gap-4 w-full md:w-auto">
2025-12-18 13:36:56 +07:00
<div className="flex flex-col w-50">
2025-12-12 20:28:59 +07:00
<div className="text-sm font-medium mb-1">{t('date-filter')}:</div>
<DropDownList
2025-12-19 13:05:50 +07:00
value={dateFilter}
translatedValue={(() => {
2025-12-15 11:24:07 +07:00
switch (dateFilter) {
case 'all':
return t('all-dates')
case 'week':
return t('for-a-week')
case 'month':
return t('for-a-month')
case 'older':
return t('older-than-a-month')
default:
return t('today')
}
})()}
2025-12-12 20:28:59 +07:00
callBack={setDateFilter}
>
<li value="all">
{t('all-dates')}
</li>
<li value="today">
{t('today')}
</li>
<li value="week">
{t('for-a-week')}
</li>
<li value="month">
{t('for-a-month')}
</li>
<li value="older">
{t('older-than-a-month')}
</li>
</DropDownList>
</div>
2025-12-12 14:22:00 +07:00
2025-12-18 13:36:56 +07:00
<div className="flex flex-col w-50">
2025-12-12 20:28:59 +07:00
<div className="text-sm font-medium mb-1">{t('type-filter')}:</div>
<DropDownList
2025-12-19 13:05:50 +07:00
value={typeFilter}
translatedValue={
(() => {
switch (typeFilter) {
case 'image':
return t('images')
case 'video':
return t('videos')
case 'audio':
return t('audios')
default:
return t('all-types')
}
})()
}
2025-12-12 20:28:59 +07:00
callBack={setTypeFilter}
>
<li value="all">
{t('all-types')}
</li>
<li value="image">
{t('images')}
</li>
<li value="video">
{t('videos')}
</li>
<li value="audio">
{t('audios')}
</li>
</DropDownList>
</div>
</div>
2025-12-12 14:22:00 +07:00
2025-12-12 20:28:59 +07:00
<div className="flex flex-col w-full md:w-auto">
<div className="text-sm font-medium mb-1">{t('items-per-page')}:</div>
<DropDownList
value={table.getState().pagination.pageSize}
//@ts-ignore сделал так потому что для table.setPageSize нужна цифра
callBack={table.setPageSize}
>
{[5, 10, 20, 50, 100].map(pageSize => (
<li key={pageSize} value={pageSize}>
{t('show')} {pageSize}
</li>
))}
</DropDownList>
</div>
2025-12-12 14:22:00 +07:00
</div>
{/* Таблица */}
2025-12-16 20:26:17 +07:00
<div className='w-full tanstak-file-table'>
<div className="overflow-x-auto rounded-lg shadow">
<table className=" divide-y divide-gray-200 table-fixed md:table-auto w-full">
<thead className="bg-gray-50">
{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th
key={header.id}
className="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap"
>
{header.isPlaceholder
? null
: typeof header.column.columnDef.header === 'function'
? header.column.columnDef.header(header.getContext())
: header.column.columnDef.header as string}
</th>
2025-12-12 20:28:59 +07:00
))}
</tr>
2025-12-16 20:26:17 +07:00
))}
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map(row => (
<tr key={row.id} className="hover:bg-gray-50 transition-colors">
{row.getVisibleCells().map(cell => (
<td key={cell.id} className="px-6 py-4 whitespace-nowrap">
{typeof cell.column.columnDef.cell === 'function'
? cell.column.columnDef.cell(cell.getContext())
: cell.getValue() as string}
</td>
))}
</tr>
))
) : (
<tr>
<td colSpan={columns.length} className="px-6 py-8 text-center text-gray-500">
{t('no-data-for-selected-filters')}
</td>
</tr>
)}
</tbody>
</table>
</div>
2025-12-12 14:22:00 +07:00
</div>
{/* Пагинация */}
2025-12-18 13:36:56 +07:00
<div className="flex flex-col md:flex-row items-end justify-between mt-6 gap-4">
2025-12-12 20:28:59 +07:00
<div className="flex items-center gap-2">
<span className="text-sm text-gray-700">
{t('page')}{' '}
<strong>
2025-12-19 13:05:50 +07:00
{table.getState().pagination.pageIndex + 1} {t('out-of')} {table.getPageCount() ? table.getPageCount() : 1}
2025-12-12 20:28:59 +07:00
</strong>
</span>
<span className="text-sm text-gray-500">
| {t('shown')} {table.getRowModel().rows.length} {t('out-of')} {filteredData.length} {t('files')}
</span>
</div>
2025-12-12 14:22:00 +07:00
<div className="flex items-center gap-2">
<button
2025-12-12 20:28:59 +07:00
className="px-2 py-1 border rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
onClick={() => table.firstPage()}
2025-12-12 14:22:00 +07:00
disabled={!table.getCanPreviousPage()}
>
2025-12-17 16:41:07 +07:00
<IconDoubleArrowLeft />
2025-12-12 14:22:00 +07:00
</button>
<button
2025-12-12 20:28:59 +07:00
className="px-2 py-1 border rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
2025-12-12 14:22:00 +07:00
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
2025-12-17 16:41:07 +07:00
<IconArrowLeft />
2025-12-12 14:22:00 +07:00
</button>
2025-12-12 20:28:59 +07:00
<div className="flex items-center gap-1">
{Array.from({ length: Math.min(5, table.getPageCount()) }, (_, i) => {
const pageIndex = Math.max(
0,
Math.min(
table.getPageCount() - 5,
table.getState().pagination.pageIndex - 2
)
) + i;
if (pageIndex < table.getPageCount()) {
return (
<button
key={pageIndex}
className={`border border-black px-3 py-1 rounded-md ${table.getState().pagination.pageIndex === pageIndex
? 'bg-blue-500 text-white'
: 'hover:bg-gray-100'
}`}
onClick={() => table.setPageIndex(pageIndex)}
>
{pageIndex + 1}
</button>
);
}
return null;
})}
</div>
2025-12-12 14:22:00 +07:00
<button
2025-12-12 20:28:59 +07:00
className="px-2 py-1 border rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
2025-12-12 14:22:00 +07:00
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
2025-12-17 16:41:07 +07:00
<IconArrowRight />
2025-12-12 14:22:00 +07:00
</button>
<button
2025-12-12 20:28:59 +07:00
className="px-2 py-1 border rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
onClick={() => table.lastPage()}
2025-12-12 14:22:00 +07:00
disabled={!table.getCanNextPage()}
>
2025-12-17 16:41:07 +07:00
<IconDoubleArrowRight />
2025-12-12 14:22:00 +07:00
</button>
</div>
</div>
</div>
);
}