Files
drive/apps/drive-web/src/directories/directory-page/directory-content-table.tsx

421 lines
9.8 KiB
TypeScript
Raw Normal View History

2025-12-17 22:59:18 +00:00
import { useInfiniteQuery } from "@tanstack/react-query"
import { Link, useNavigate, useSearch } from "@tanstack/react-router"
import {
type ColumnDef,
flexRender,
getCoreRowModel,
getFilteredRowModel,
type Row,
type Table as TableType,
useReactTable,
} from "@tanstack/react-table"
2025-12-17 22:59:18 +00:00
import { type PrimitiveAtom, useAtomValue, useSetAtom, useStore } from "jotai"
import { useContext, useEffect, useMemo, useRef } from "react"
import { DirectoryIcon } from "@/components/icons/directory-icon"
import { TextFileIcon } from "@/components/icons/text-file-icon"
import { Checkbox } from "@/components/ui/checkbox"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { type FileDragInfo, useFileDrop } from "@/files/use-file-drop"
2025-09-21 15:12:05 +00:00
import {
isControlOrCommandKeyActive,
keyboardModifierAtom,
} from "@/lib/keyboard"
import { cn } from "@/lib/utils"
import type { DirectoryInfo, DirectoryItem, FileInfo } from "@/vfs/vfs"
2025-12-17 22:59:18 +00:00
import { directoryContentQueryAtom } from "../../vfs/api"
import { DirectoryPageContext } from "./context"
2025-12-17 22:59:18 +00:00
import { DirectoryContentTableSkeleton } from "./directory-content-table-skeleton"
type DirectoryContentTableItemIdFilter = Set<string>
type DirectoryContentTableProps = {
directoryUrlFn: (directory: DirectoryInfo) => string
fileDragInfoAtom: PrimitiveAtom<FileDragInfo | null>
onContextMenu: (
row: Row<DirectoryItem>,
table: TableType<DirectoryItem>,
) => void
onOpenFile: (file: FileInfo) => void
}
function formatFileSize(bytes: number): string {
if (bytes === 0) return "0 B"
const k = 1024
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"]
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}
function useTableColumns(
onOpenFile: (file: FileInfo) => void,
directoryUrlFn: (directory: DirectoryInfo) => string,
): ColumnDef<DirectoryItem>[] {
return useMemo(
() => [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => {
table.toggleAllPageRowsSelected(!!value)
}}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onClick={(e) => {
e.stopPropagation()
}}
onCheckedChange={row.getToggleSelectedHandler()}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
size: 24,
},
{
header: "Name",
accessorKey: "doc.name",
cell: ({ row }) => {
switch (row.original.kind) {
case "file":
return (
<FileNameCell
file={row.original}
onOpenFile={onOpenFile}
/>
)
case "directory":
return (
<DirectoryNameCell
directory={row.original}
directoryUrlFn={directoryUrlFn}
/>
)
}
},
size: 1000,
},
{
header: "Size",
accessorKey: "size",
cell: ({ row }) => {
switch (row.original.kind) {
case "file":
return (
<div>{formatFileSize(row.original.size)}</div>
)
case "directory":
return <div className="font-mono">-</div>
}
},
},
{
header: "Created At",
accessorKey: "createdAt",
cell: ({ row }) => {
return (
<div>
{new Date(row.original.createdAt).toLocaleString()}
</div>
)
},
},
],
[onOpenFile, directoryUrlFn],
)
}
export function DirectoryContentTable({
directoryUrlFn,
onContextMenu,
fileDragInfoAtom,
onOpenFile,
}: DirectoryContentTableProps) {
2025-12-17 22:59:18 +00:00
const { directory } = useContext(DirectoryPageContext)
const search = useSearch({
from: "/_authenticated/_sidebar-layout/directories/$directoryId",
})
const directoryContentQuery = useAtomValue(
directoryContentQueryAtom({
directoryId: directory.id,
orderBy: search.orderBy,
direction: search.direction,
limit: 100,
}),
)
const { data: directoryContent, isLoading: isLoadingDirectoryContent } =
useInfiniteQuery(directoryContentQuery)
const store = useStore()
const navigate = useNavigate()
2025-09-26 22:28:51 +00:00
const table = useReactTable({
2025-12-17 22:59:18 +00:00
data: useMemo(
() => directoryContent?.pages.flatMap((page) => page.items) || [],
[directoryContent],
),
columns: useTableColumns(onOpenFile, directoryUrlFn),
2025-09-26 22:28:51 +00:00
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
2025-09-26 22:28:51 +00:00
enableRowSelection: true,
enableGlobalFilter: true,
globalFilterFn: (
row,
_columnId,
filterValue: DirectoryContentTableItemIdFilter,
_addMeta,
) => !filterValue.has(row.original.id),
getRowId: (row) => row.id,
2025-09-26 22:28:51 +00:00
})
useEffect(
function escapeToClearSelections() {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") {
table.setRowSelection({})
}
}
window.addEventListener("keydown", handleEscape)
return () => window.removeEventListener("keydown", handleEscape)
},
[table.setRowSelection],
)
2025-12-17 22:59:18 +00:00
if (isLoadingDirectoryContent) {
return <DirectoryContentTableSkeleton />
}
const handleRowContextMenu = (
row: Row<DirectoryItem>,
_event: React.MouseEvent,
) => {
if (!row.getIsSelected()) {
selectRow(row)
}
onContextMenu(row, table)
}
const selectRow = (row: Row<DirectoryItem>) => {
2025-09-21 15:12:05 +00:00
const keyboardModifiers = store.get(keyboardModifierAtom)
const isMultiSelectMode = isControlOrCommandKeyActive(keyboardModifiers)
const isRowSelected = row.getIsSelected()
if (isRowSelected && isMultiSelectMode) {
row.toggleSelected(false)
} else if (isRowSelected && !isMultiSelectMode) {
table.setRowSelection({
[row.id]: true,
})
row.toggleSelected(true)
2025-09-21 15:12:05 +00:00
} else if (!isRowSelected) {
if (isMultiSelectMode) {
row.toggleSelected(true)
} else {
table.setRowSelection({
[row.id]: true,
})
}
}
}
const handleRowDoubleClick = (row: Row<DirectoryItem>) => {
if (row.original.kind === "directory") {
navigate({
to: `/directories/${row.original.id}`,
})
}
}
return (
<div className="overflow-hidden">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow className="px-4" key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead
className="first:pl-4 last:pr-4"
key={header.id}
style={{ width: header.getSize() }}
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<FileItemRow
key={row.id}
table={table}
row={row}
onClick={() => selectRow(row)}
fileDragInfoAtom={fileDragInfoAtom}
onContextMenu={(e) =>
handleRowContextMenu(row, e)
}
onDoubleClick={() => {
handleRowDoubleClick(row)
}}
/>
))
) : (
<NoResultsRow />
)}
</TableBody>
</Table>
</div>
)
}
function NoResultsRow() {
return (
2025-10-05 00:46:29 +00:00
<TableRow className="hover:bg-transparent">
<TableCell colSpan={4} className="text-center">
No results.
</TableCell>
</TableRow>
)
}
2025-09-20 22:25:01 +00:00
function FileItemRow({
table,
2025-09-20 22:25:01 +00:00
row,
onClick,
onContextMenu,
onDoubleClick,
fileDragInfoAtom,
2025-09-20 22:25:01 +00:00
}: {
table: TableType<DirectoryItem>
row: Row<DirectoryItem>
2025-09-20 22:25:01 +00:00
onClick: () => void
onContextMenu: (e: React.MouseEvent) => void
onDoubleClick: () => void
fileDragInfoAtom: PrimitiveAtom<FileDragInfo | null>
2025-09-20 22:25:01 +00:00
}) {
const ref = useRef<HTMLTableRowElement>(null)
const setFileDragInfo = useSetAtom(fileDragInfoAtom)
2025-09-20 22:25:01 +00:00
const { isDraggedOver, dropHandlers } = useFileDrop({
enabled: row.original.kind === "directory",
destDir: row.original.kind === "directory" ? row.original : undefined,
dragInfoAtom: fileDragInfoAtom,
2025-09-20 22:25:01 +00:00
})
2025-09-28 15:45:49 +00:00
const handleDragStart = (_e: React.DragEvent) => {
let draggedItems: DirectoryItem[]
2025-09-26 22:20:30 +00:00
// drag all selections, but only if the currently dragged row is also selected
if (row.getIsSelected()) {
draggedItems = []
let currentRowFound = false
for (const { original: item } of table.getSelectedRowModel().rows) {
draggedItems.push(item)
if (item.id === row.original.id) {
currentRowFound = true
}
}
if (!currentRowFound) {
draggedItems.push(row.original)
}
2025-09-26 22:20:30 +00:00
} else {
draggedItems = [row.original]
2025-09-26 22:20:30 +00:00
}
setFileDragInfo({
source: row.original,
items: draggedItems,
})
2025-09-20 22:25:01 +00:00
}
const handleDragEnd = () => {
setFileDragInfo(null)
2025-09-20 22:25:01 +00:00
}
return (
<TableRow
draggable
ref={ref}
key={row.id}
data-state={row.getIsSelected() && "selected"}
onClick={onClick}
onDoubleClick={onDoubleClick}
2025-09-20 22:25:01 +00:00
onContextMenu={onContextMenu}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
{...dropHandlers}
2025-09-20 22:25:01 +00:00
className={cn({ "bg-muted": isDraggedOver })}
>
{row.getVisibleCells().map((cell) => (
<TableCell
className="first:pl-4 last:pr-4"
key={cell.id}
style={{ width: cell.column.getSize() }}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
)
}
function DirectoryNameCell({
directory,
directoryUrlFn,
}: {
directory: DirectoryInfo
directoryUrlFn: (directory: DirectoryInfo) => string
}) {
return (
<div className="flex w-full items-center gap-2">
<DirectoryIcon className="size-4" />
<Link className="hover:underline" to={directoryUrlFn(directory)}>
{directory.name}
</Link>
</div>
)
}
function FileNameCell({
file,
onOpenFile,
}: {
file: FileInfo
onOpenFile: (file: FileInfo) => void
}) {
return (
<div className="flex w-full items-center gap-2">
<TextFileIcon className="size-4" />
2025-09-20 19:55:20 +00:00
<button
type="button"
className="hover:underline cursor-pointer"
onClick={() => {
onOpenFile(file)
2025-09-20 19:55:20 +00:00
}}
>
{file.name}
</button>
</div>
)
}