fix: table view for albums

Signed-off-by: Varun Raj <varun@skcript.com>
This commit is contained in:
Varun Raj committed 2025-07-29 10:30:11 +05:30
1 parent cf59b4fa3f
commit 9589be8821
3 files changed
+566 -13

No files matched your search

+236
View File
@@ -0,0 +1,236 @@
import { ColumnDef } from "@tanstack/react-table"
import { IAlbum } from "@/types/album"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { ArrowUpDown, MoreHorizontal, Calendar, Camera, Users, HardDrive } from "lucide-react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { formatDate } from "@/helpers/date.helper"
import { humanizeBytes, humanizeNumber, pluralize } from "@/helpers/string.helper"
import { differenceInDays } from "date-fns"
import Link from "next/link"
import { ASSET_THUMBNAIL_PATH } from "@/config/routes"
import LazyImage from "@/components/ui/lazy-image"
export const albumColumns: ColumnDef<IAlbum>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "albumThumbnailAssetId",
header: "Thumbnail",
cell: ({ row }) => {
const album = row.original
return (
<div className="w-16 h-16 rounded-md overflow-hidden">
<LazyImage
src={ASSET_THUMBNAIL_PATH(album.albumThumbnailAssetId)}
alt={album.albumName}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
</div>
)
},
enableSorting: false,
},
{
accessorKey: "albumName",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
Album Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const album = row.original
return (
<Link
href={`/albums/${album.id}`}
className="font-medium hover:underline"
onClick={(e) => {
// Ensure the link click is not blocked by table events
e.stopPropagation()
}}
>
{album.albumName}
</Link>
)
},
},
{
accessorKey: "assetCount",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
<Camera className="mr-2 h-4 w-4" />
Assets
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const count = row.getValue("assetCount") as number
return <div className="font-medium">{humanizeNumber(count)}</div>
},
},
{
accessorKey: "faceCount",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
<Users className="mr-2 h-4 w-4" />
People
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const count = row.getValue("faceCount") as number
return <div>{humanizeNumber(count)} {pluralize(count, 'person', 'people')}</div>
},
},
{
accessorKey: "size",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
<HardDrive className="mr-2 h-4 w-4" />
Size
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const size = row.getValue("size") as string
return <div>{humanizeBytes(parseInt(size))}</div>
},
},
{
accessorKey: "firstPhotoDate",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
<Calendar className="mr-2 h-4 w-4" />
Date Range
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const album = row.original
const numberOfDays = differenceInDays(album.lastPhotoDate, album.firstPhotoDate)
return (
<div className="space-y-1">
<div className="text-sm">
{album.firstPhotoDate ? formatDate(album.firstPhotoDate.toString(), 'MMM d, yyyy') : ''} - {album.lastPhotoDate ? formatDate(album.lastPhotoDate.toString(), 'MMM d, yyyy') : ''}
</div>
<div className="text-xs text-muted-foreground">
{numberOfDays === 0 ? '1 day' : `${numberOfDays.toLocaleString()} days`}
</div>
</div>
)
},
},
{
accessorKey: "createdAt",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
Created
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
cell: ({ row }) => {
const date = row.getValue("createdAt") as string
return <div>{formatDate(date, 'MMM d, yyyy')}</div>
},
},
{
id: "actions",
enableHiding: false,
cell: ({ row }) => {
const album = row.original
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem asChild>
<Link href={`/albums/${album.id}`}>
View Album
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
Share Album
</DropdownMenuItem>
<DropdownMenuItem>
Edit Album
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-red-600">
Delete Album
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
]
+242
View File
@@ -0,0 +1,242 @@
"use client"
import * as React from "react"
import {
ColumnDef,
ColumnFiltersState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
SortingState,
useReactTable,
VisibilityState,
} from "@tanstack/react-table"
import { ArrowUpDown, ChevronDown, MoreHorizontal } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import {
TableRoot,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
onRowSelectionChange?: (selectedIds: string[]) => void
selectedIds?: string[]
getRowId?: (row: TData) => string
searchValue?: string
onSearchChange?: (value: string) => void
}
export function DataTable<TData, TValue>({
columns,
data,
onRowSelectionChange,
selectedIds = [],
getRowId,
searchValue,
onSearchChange,
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([])
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
// Initialize row selection from selectedIds
const initialRowSelection = React.useMemo(() => {
const selection: Record<string, boolean> = {}
selectedIds.forEach(id => {
selection[id] = true
})
return selection
}, [selectedIds])
const [rowSelection, setRowSelection] = React.useState<Record<string, boolean>>(initialRowSelection)
const table = useReactTable({
data,
columns,
getRowId: getRowId || ((row: any) => row.id),
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
},
// Add these options to prevent potential issues
enableRowSelection: true,
enableMultiRowSelection: true,
enableSorting: true,
enableFilters: true,
enableColumnFilters: true,
enablePagination: true,
})
// Sync external selection with table selection
React.useEffect(() => {
const newRowSelection: Record<string, boolean> = {}
selectedIds.forEach((id) => {
newRowSelection[id] = true
})
setRowSelection(newRowSelection)
}, [selectedIds])
// Sync external search with table filter
React.useEffect(() => {
if (searchValue !== undefined) {
table.getColumn("albumName")?.setFilterValue(searchValue)
}
}, [searchValue, table])
// Notify parent of selection changes
React.useEffect(() => {
const selectedRowIds = Object.keys(rowSelection).filter(id => rowSelection[id])
onRowSelectionChange?.(selectedRowIds)
}, [rowSelection, onRowSelectionChange])
return (
<div className="w-full">
<div className="flex items-center py-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="ml-auto">
Columns <ChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{table
.getAllColumns()
.filter((column) => column.getCanHide())
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onCheckedChange={(value) =>
column.toggleVisibility(!!value)
}
>
{column.id}
</DropdownMenuCheckboxItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="overflow-hidden rounded-md border">
<TableRoot>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
onClick={(e) => {
// Prevent row click from interfering with link clicks
if (e.target instanceof HTMLAnchorElement) {
e.stopPropagation()
}
}}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
onClick={(e) => {
// Allow link clicks to propagate
if (e.target instanceof HTMLAnchorElement) {
e.stopPropagation()
}
}}
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</TableRoot>
</div>
<div className="flex items-center justify-end space-x-2 py-4">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>
</div>
</div>
)
}
+88 -13
View File
@@ -9,13 +9,15 @@ import AlbumThumbnail from '@/components/albums/list/AlbumThumbnail'
import { Button } from '@/components/ui/button'
import { Select, SelectItem, SelectContent, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useRouter } from 'next/router'
import { Share, SortAsc, SortDesc, Trash } from 'lucide-react'
import { Share, SortAsc, SortDesc, Trash, Grid3X3, Table as TableIcon } from 'lucide-react'
import { Input } from '@/components/ui/input'
import AlbumShareDialog, { IAlbumShareDialogRef } from '@/components/albums/share/AlbumShareDialog'
import { AlertDialog } from '@/components/ui/alert-dialog'
import toast from 'react-hot-toast'
import { useAlbumSelection } from '@/hooks'
import FloatingBar from '@/components/shared/FloatingBar'
import { DataTable } from '@/components/ui/data-table'
import { albumColumns } from '@/components/albums/AlbumTableColumns'
const SORT_BY_OPTIONS = [
{ value: 'lastPhotoDate', label: 'Last Photo Date' },
@@ -31,6 +33,7 @@ const SORT_BY_OPTIONS = [
export default function AlbumListPage() {
const router = useRouter()
const [search, setSearch] = useState('')
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid')
const { query, pathname } = router
const { sortBy, sortOrder } = query as { sortBy: string, sortOrder: string }
const [albums, setAlbums] = useState<IAlbum[]>([])
@@ -38,6 +41,9 @@ export default function AlbumListPage() {
const [errorMessage, setErrorMessage] = useState('')
const albumShareDialogRef = useRef<IAlbumShareDialogRef>(null);
const [deleting, setDeleting] = useState(false)
// Separate selection state for table view
const [tableSelectedIds, setTableSelectedIds] = useState<string[]>([])
const selectedSortBy = useMemo(() => SORT_BY_OPTIONS.find((option) => option.value === sortBy), [sortBy])
@@ -56,6 +62,11 @@ export default function AlbumListPage() {
const selectedAlbums = useMemo(() => albums.filter((album) => selectedIds.includes(album.id)), [albums, selectedIds])
// Use appropriate selection state based on view mode
const currentSelectedIds = viewMode === 'table' ? tableSelectedIds : selectedIds
const currentSelectedCount = currentSelectedIds.length
const currentSelectedAlbums = useMemo(() => albums.filter((album) => currentSelectedIds.includes(album.id)), [albums, currentSelectedIds])
const fetchAlbums = async () => {
setLoading(true)
listAlbums({
@@ -77,10 +88,14 @@ export default function AlbumListPage() {
const handleDeleteAlbums = async () => {
setDeleting(true)
return deleteAlbums(selectedIds).then(() => {
clearSelection()
setAlbums(albums.filter((album) => !selectedIds.includes(album.id)))
toast.success(`Deleted ${selectedCount} albums`)
return deleteAlbums(currentSelectedIds).then(() => {
if (viewMode === 'table') {
setTableSelectedIds([])
} else {
clearSelection()
}
setAlbums(albums.filter((album) => !currentSelectedIds.includes(album.id)))
toast.success(`Deleted ${currentSelectedCount} albums`)
}).catch((error) => {
toast.error(error.message)
}).finally(() => {
@@ -88,6 +103,29 @@ export default function AlbumListPage() {
})
}
const handleTableSelectionChange = (selectedRowIds: string[]) => {
setTableSelectedIds(selectedRowIds)
}
const handleSelectAll = () => {
if (viewMode === 'table') {
setTableSelectedIds(searchedAlbums.map(album => album.id))
} else {
selectAll()
}
}
const handleClearSelection = () => {
if (viewMode === 'table') {
setTableSelectedIds([])
} else {
clearSelection()
}
}
const isAllSelectedCurrent = searchedAlbums.length > 0 && currentSelectedCount === searchedAlbums.length
const isPartiallySelectedCurrent = currentSelectedCount > 0 && currentSelectedCount < searchedAlbums.length
const renderContent = () => {
if (loading) {
return <Loader />
@@ -95,6 +133,23 @@ export default function AlbumListPage() {
else if (errorMessage) {
return <div>{errorMessage}</div>
}
if (viewMode === 'table') {
return (
<div className="p-4">
<DataTable
columns={albumColumns}
data={searchedAlbums}
selectedIds={currentSelectedIds}
onRowSelectionChange={handleTableSelectionChange}
getRowId={(row) => row.id}
searchValue={search}
onSearchChange={setSearch}
/>
</div>
)
}
return (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 p-4">
{searchedAlbums.map((album) => (
@@ -108,15 +163,16 @@ export default function AlbumListPage() {
</div>
)
}
return (
<PageLayout className="!p-0 !mb-0 relative">
<Header
leftComponent={
<div className="flex items-center gap-2">
<span>Manage Albums</span>
{selectedCount > 0 && (
{currentSelectedCount > 0 && (
<span className="text-sm text-gray-500 dark:text-gray-400">
({selectedCount} selected)
({currentSelectedCount} selected)
</span>
)}
</div>
@@ -125,6 +181,25 @@ export default function AlbumListPage() {
<div className="flex items-center gap-2">
<Input type="text" placeholder="Search" className="w-48" onChange={(e) => setSearch(e.target.value)} />
<div className="flex items-center border rounded-md">
<Button
variant={viewMode === 'grid' ? 'default' : 'ghost'}
size="sm"
onClick={() => setViewMode('grid')}
className="rounded-r-none"
>
<Grid3X3 className="h-4 w-4" />
</Button>
<Button
variant={viewMode === 'table' ? 'default' : 'ghost'}
size="sm"
onClick={() => setViewMode('table')}
className="rounded-l-none"
>
<TableIcon className="h-4 w-4" />
</Button>
</div>
<Select
defaultValue={selectedSortBy?.value}
onValueChange={(value) => router.push({
@@ -157,18 +232,18 @@ export default function AlbumListPage() {
}
/>
{renderContent()}
{selectedCount > 0 && (
{currentSelectedCount > 0 && (
<FloatingBar className="!fixed">
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-sm text-muted-foreground">
{selectedCount} Selected
{currentSelectedCount} Selected
</p>
<div className="flex items-center gap-2">
{isAllSelected ? (
{isAllSelectedCurrent ? (
<Button
variant="outline"
size="sm"
onClick={clearSelection}
onClick={handleClearSelection}
className="text-xs"
>
Clear Selection
@@ -177,7 +252,7 @@ export default function AlbumListPage() {
<Button
variant="outline"
size="sm"
onClick={selectAll}
onClick={handleSelectAll}
className="text-xs"
>
Select All
@@ -188,7 +263,7 @@ export default function AlbumListPage() {
size="sm"
className="flex items-center gap-2"
onClick={() => {
albumShareDialogRef.current?.open(selectedAlbums)
albumShareDialogRef.current?.open(currentSelectedAlbums)
}}>
<Share size={16} /> Share
</Button>