diff --git a/bun.lockb b/bun.lockb index 158441f..7310b1b 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/docs/VIRTUALIZED_ASSET_GRID.md b/docs/VIRTUALIZED_ASSET_GRID.md new file mode 100644 index 0000000..2235259 --- /dev/null +++ b/docs/VIRTUALIZED_ASSET_GRID.md @@ -0,0 +1,155 @@ +# Virtualized Asset Grid Components + +This document explains how to use the new React Window-based virtualized asset grid components for better performance with large datasets. + +## Overview + +The virtualized asset grid components provide significant performance improvements when displaying large numbers of assets by only rendering the items that are currently visible in the viewport. This is especially useful for photo galleries with thousands of images. + +## Components + +### 1. VirtualizedAssetGrid + +A basic virtualized grid with fixed dimensions. + +```tsx +import VirtualizedAssetGrid from '@/components/shared/VirtualizedAssetGrid'; + + +``` + +**Props:** +- `assets`: Array of IAsset objects +- `selectable`: Whether assets can be selected (default: false) +- `onSelectionChange`: Callback when selection changes +- `columnCount`: Number of columns (default: 5) +- `itemSize`: Size of each item in pixels (default: 200) +- `height`: Height of the grid container (default: 600) + +### 2. ResponsiveVirtualizedAssetGrid + +A responsive virtualized grid that automatically adjusts to container size. + +```tsx +import ResponsiveVirtualizedAssetGrid from '@/components/shared/ResponsiveVirtualizedAssetGrid'; + + +``` + +**Props:** +- `assets`: Array of IAsset objects +- `selectable`: Whether assets can be selected (default: false) +- `onSelectionChange`: Callback when selection changes +- `targetItemSize`: Target size for each item (default: 200) +- `gap`: Gap between items in pixels (default: 8) +- `minColumns`: Minimum number of columns (default: 2) +- `maxColumns`: Maximum number of columns (default: 8) +- `className`: Additional CSS classes + +## Features + +### Selection +Both components support asset selection with the following features: +- Click to select/deselect individual assets +- Shift+click for range selection +- ESC key to clear all selections +- Visual indicators for selected items + +### Lightbox Integration +Both components integrate with the existing lightbox for full-screen viewing: +- Click on an asset to open in lightbox +- Video support with duration display +- Download functionality + +### Performance Optimizations +- Only renders visible items +- Lazy loading of images +- Efficient memory usage +- Smooth scrolling performance + +## Migration from AssetGrid + +To migrate from the existing `AssetGrid` component: + +### Before: +```tsx +import AssetGrid from '@/components/shared/AssetGrid'; + + +``` + +### After: +```tsx +import ResponsiveVirtualizedAssetGrid from '@/components/shared/ResponsiveVirtualizedAssetGrid'; + +
+ +
+``` + +**Important:** The virtualized components require a container with a defined height. Make sure to wrap them in a div with appropriate height styling. + +## Custom Hook: useGridDimensions + +The `useGridDimensions` hook can be used to calculate optimal grid dimensions: + +```tsx +import { useGridDimensions } from '@/hooks'; + +const gridDimensions = useGridDimensions({ + containerWidth: 800, + containerHeight: 600, + itemSize: 200, + gap: 8, + minColumns: 2, + maxColumns: 8 +}); +``` + +## Example Usage + +See `src/components/shared/AssetGridExample.tsx` for a complete example showing different configurations of the virtualized grid components. + +## Performance Considerations + +- Use `ResponsiveVirtualizedAssetGrid` for most use cases as it automatically adapts to container size +- Set appropriate `targetItemSize` based on your design requirements +- Consider using smaller `gap` values for dense layouts +- The components work best with containers that have a defined height + +## Browser Support + +The components use modern browser APIs: +- ResizeObserver (for responsive behavior) +- IntersectionObserver (for lazy loading) +- CSS Grid and Flexbox + +For older browsers, consider using polyfills or the basic `VirtualizedAssetGrid` with fixed dimensions. diff --git a/package.json b/package.json index cc00a8b..913f8b2 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "@remotion/cli": "4.0.232", "@remotion/eslint-plugin": "^4.0.232", "@tanstack/react-query": "^5.69.0", - "@tanstack/react-table": "^8.20.1", + "@tanstack/react-table": "^8.21.3", "@types/cookie": "^0.6.0", "@types/qs": "^6.9.15", "@types/react-autosuggest": "^10.1.11", diff --git a/src/components/shared/AssetGridExample.tsx b/src/components/shared/AssetGridExample.tsx new file mode 100644 index 0000000..e1913c7 --- /dev/null +++ b/src/components/shared/AssetGridExample.tsx @@ -0,0 +1,87 @@ +import React, { useRef } from 'react'; +import { IAsset } from '@/types/asset'; +import VirtualizedAssetGrid from './VirtualizedAssetGrid'; +import ResponsiveVirtualizedAssetGrid from './ResponsiveVirtualizedAssetGrid'; +import { Button } from '@/components/ui/button'; + +interface AssetGridExampleProps { + assets: IAsset[]; + onSelectionChange?: (ids: string[]) => void; +} + +export default function AssetGridExample({ assets, onSelectionChange }: AssetGridExampleProps) { + const gridRef = useRef(null); + + const handleSelectAll = () => { + gridRef.current?.selectAll(); + }; + + const handleUnselectAll = () => { + gridRef.current?.unselectAll(); + }; + + return ( +
+
+ + +
+ + {/* Example 1: Basic Virtualized Grid with fixed dimensions */} +
+

Fixed Size Virtualized Grid

+
+ +
+
+ + {/* Example 2: Responsive Virtualized Grid */} +
+

Responsive Virtualized Grid

+
+ +
+
+ + {/* Example 3: Responsive Grid with different target sizes */} +
+

Small Items Virtualized Grid

+
+ +
+
+
+ ); +} diff --git a/src/components/shared/FloatingBar.tsx b/src/components/shared/FloatingBar.tsx index 81aea89..072eb13 100644 --- a/src/components/shared/FloatingBar.tsx +++ b/src/components/shared/FloatingBar.tsx @@ -8,7 +8,7 @@ interface FloatingBarProps { export default function FloatingBar({ children, className }: FloatingBarProps) { return ( -
+
{children}
) diff --git a/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx new file mode 100644 index 0000000..95d0294 --- /dev/null +++ b/src/components/shared/ResponsiveVirtualizedAssetGrid.tsx @@ -0,0 +1,254 @@ +import "yet-another-react-lightbox/styles.css"; + +import { IAsset } from '@/types/asset'; +import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState, useCallback, useRef } from 'react' +import Lightbox from 'yet-another-react-lightbox'; +import Download from "yet-another-react-lightbox/plugins/download"; +import Video from "yet-another-react-lightbox/plugins/video"; +import { usePhotoSelectionContext } from '@/contexts/PhotoSelectionContext'; +import { FixedSizeGrid as Grid } from 'react-window'; +import LazyImage from '../ui/lazy-image'; +import { humanizeDuration } from '@/helpers/string.helper'; +import { PlayIcon } from '@radix-ui/react-icons'; +import { useGridDimensions } from '@/hooks'; + +interface ResponsiveVirtualizedAssetGridProps { + assets: IAsset[]; + isInternal?: boolean; + selectable?: boolean; + onSelectionChange?: (ids: string[]) => void; + targetItemSize?: number; + gap?: number; + minColumns?: number; + maxColumns?: number; + className?: string; +} + +interface ResponsiveVirtualizedAssetGridRef { + getSelectedIds: () => string[]; + selectAll: () => void; + unselectAll: () => void; +} + +const ResponsiveVirtualizedAssetGrid = forwardRef(({ + assets, + isInternal = true, + selectable = false, + onSelectionChange, + targetItemSize = 200, + gap = 8, + minColumns = 2, + maxColumns = 8, + className = "" +}, ref) => { + const [index, setIndex] = useState(-1); + const [lastSelectedIndex, setLastSelectedIndex] = useState(-1); + const containerRef = useRef(null); + const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }); + + // Use context for selection state + const { selectedIds, updateContext } = usePhotoSelectionContext(); + + // Calculate grid dimensions + const gridDimensions = useGridDimensions({ + containerWidth: containerSize.width, + containerHeight: containerSize.height, + itemSize: targetItemSize, + gap, + minColumns, + maxColumns + }); + + // Update row count when assets change + useEffect(() => { + gridDimensions.updateRowCount(assets.length); + }, [assets.length, gridDimensions]); + + // Resize observer to handle container size changes + useEffect(() => { + if (!containerRef.current) return; + + const resizeObserver = new ResizeObserver((entries) => { + for (const entry of entries) { + const { width, height } = entry.contentRect; + setContainerSize({ width, height }); + } + }); + + resizeObserver.observe(containerRef.current); + + return () => { + resizeObserver.disconnect(); + }; + }, []); + + useImperativeHandle(ref, () => ({ + getSelectedIds: () => selectedIds, + selectAll: () => { + const allIds = assets.map((asset) => asset.id); + updateContext({ selectedIds: allIds }); + onSelectionChange?.(allIds); + }, + unselectAll: () => { + updateContext({ selectedIds: [] }); + onSelectionChange?.([]); + }, + }), [assets, selectedIds, updateContext]); + + const slides = useMemo(() => { + return assets.map((asset) => ({ + ...asset, + orientation: 1, + src: asset.previewUrl as string, + type: (asset.type === "VIDEO" ? "video" : "image") as any, + sources: + asset.type === "VIDEO" + ? [ + { + src: asset.downloadUrl as string, + type: "video/mp4", + }, + ] + : undefined, + height: asset.exifImageHeight as number, + width: asset.exifImageWidth as number, + downloadUrl: asset.downloadUrl as string, + })); + }, [assets]); + + const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent) => { + if (selectedIds.length > 0) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds]); + + const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { + event.stopPropagation(); + const isPresent = selectedIds.includes(asset.id); + if (isPresent) { + const newSelectedIds = selectedIds.filter((id) => id !== asset.id); + updateContext({ selectedIds: newSelectedIds }); + onSelectionChange?.(newSelectedIds); + } else { + const clickedIndex = assets.findIndex((a) => a.id === asset.id); + if (event.shiftKey) { + const startIndex = Math.min(clickedIndex, lastSelectedIndex); + const endIndex = Math.max(clickedIndex, lastSelectedIndex); + const rangeSelectedIds = assets.slice(startIndex, endIndex + 1).map((a) => a.id); + const allSelectedIds = [...selectedIds, ...rangeSelectedIds]; + const uniqueSelectedIds = [...new Set(allSelectedIds)]; + updateContext({ selectedIds: uniqueSelectedIds }); + onSelectionChange?.(uniqueSelectedIds); + } else { + const newSelectedIds = [...selectedIds, asset.id]; + updateContext({ selectedIds: newSelectedIds }); + onSelectionChange?.(newSelectedIds); + } + setLastSelectedIndex(clickedIndex); + } + }, [selectedIds, assets, lastSelectedIndex, updateContext, onSelectionChange]); + + const handleEsc = useCallback((event: KeyboardEvent) => { + if (event.key === "Escape") { + updateContext({ selectedIds: [] }); + onSelectionChange?.([]); + } + }, [updateContext, onSelectionChange]); + + useEffect(() => { + window.addEventListener("keydown", handleEsc); + return () => window.removeEventListener("keydown", handleEsc); + }, [handleEsc]); + + // Cell renderer for React Window + const Cell = useCallback(({ columnIndex, rowIndex, style }: { columnIndex: number; rowIndex: number; style: React.CSSProperties }) => { + const assetIndex = rowIndex * gridDimensions.columnCount + columnIndex; + const asset = assets[assetIndex]; + + if (!asset) { + return
; + } + + const isSelected = selectedIds.includes(asset.id); + + return ( +
handleClick(assetIndex, asset, e)} + > +
+ + {asset.type === "VIDEO" && ( +
+ + {asset.duration && ( + + {humanizeDuration(asset.duration)} + + )} +
+ )} + {selectable && ( +
+ )} +
+
+ ); + }, [assets, selectedIds, gridDimensions.columnCount, handleClick, selectable, gap]); + + // Don't render grid until we have container dimensions + if (containerSize.width === 0 || gridDimensions.rowCount === 0) { + return ( +
+
+
Loading...
+
+
+ ); + } + + return ( +
+ = 0} + index={index} + close={() => setIndex(-1)} + /> + + {Cell} + +
+ ); +}); + +ResponsiveVirtualizedAssetGrid.displayName = "ResponsiveVirtualizedAssetGrid"; +export default ResponsiveVirtualizedAssetGrid; diff --git a/src/components/shared/VirtualizedAssetGrid.tsx b/src/components/shared/VirtualizedAssetGrid.tsx new file mode 100644 index 0000000..c038131 --- /dev/null +++ b/src/components/shared/VirtualizedAssetGrid.tsx @@ -0,0 +1,205 @@ +import "yet-another-react-lightbox/styles.css"; + +import { IAsset } from '@/types/asset'; +import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState, useCallback } from 'react' +import Lightbox from 'yet-another-react-lightbox'; +import Download from "yet-another-react-lightbox/plugins/download"; +import Video from "yet-another-react-lightbox/plugins/video"; +import { usePhotoSelectionContext } from '@/contexts/PhotoSelectionContext'; +import { FixedSizeGrid as Grid } from 'react-window'; +import LazyImage from '../ui/lazy-image'; +import { humanizeDuration } from '@/helpers/string.helper'; +import { PlayIcon } from '@radix-ui/react-icons'; + +interface VirtualizedAssetGridProps { + assets: IAsset[]; + isInternal?: boolean; + selectable?: boolean; + onSelectionChange?: (ids: string[]) => void; + columnCount?: number; + itemSize?: number; + height?: number; +} + +interface VirtualizedAssetGridRef { + getSelectedIds: () => string[]; + selectAll: () => void; + unselectAll: () => void; +} + +const VirtualizedAssetGrid = forwardRef(({ + assets, + isInternal = true, + selectable = false, + onSelectionChange, + columnCount = 5, + itemSize = 200, + height = 600 +}, ref) => { + const [index, setIndex] = useState(-1); + const [lastSelectedIndex, setLastSelectedIndex] = useState(-1); + + // Use context for selection state + const { selectedIds, updateContext } = usePhotoSelectionContext(); + + useImperativeHandle(ref, () => ({ + getSelectedIds: () => selectedIds, + selectAll: () => { + const allIds = assets.map((asset) => asset.id); + updateContext({ selectedIds: allIds }); + onSelectionChange?.(allIds); + }, + unselectAll: () => { + updateContext({ selectedIds: [] }); + onSelectionChange?.([]); + }, + }), [assets, selectedIds, updateContext]); + + const slides = useMemo(() => { + return assets.map((asset) => ({ + ...asset, + orientation: 1, + src: asset.previewUrl as string, + type: (asset.type === "VIDEO" ? "video" : "image") as any, + sources: + asset.type === "VIDEO" + ? [ + { + src: asset.downloadUrl as string, + type: "video/mp4", + }, + ] + : undefined, + height: asset.exifImageHeight as number, + width: asset.exifImageWidth as number, + downloadUrl: asset.downloadUrl as string, + })); + }, [assets]); + + const handleClick = useCallback((index: number, asset: IAsset, event: React.MouseEvent) => { + if (selectedIds.length > 0) { + handleSelect(index, asset, event); + } else { + setIndex(index); + } + }, [selectedIds]); + + const handleSelect = useCallback((_idx: number, asset: IAsset, event: React.MouseEvent) => { + event.stopPropagation(); + const isPresent = selectedIds.includes(asset.id); + if (isPresent) { + const newSelectedIds = selectedIds.filter((id) => id !== asset.id); + updateContext({ selectedIds: newSelectedIds }); + onSelectionChange?.(newSelectedIds); + } else { + const clickedIndex = assets.findIndex((a) => a.id === asset.id); + if (event.shiftKey) { + const startIndex = Math.min(clickedIndex, lastSelectedIndex); + const endIndex = Math.max(clickedIndex, lastSelectedIndex); + const rangeSelectedIds = assets.slice(startIndex, endIndex + 1).map((a) => a.id); + const allSelectedIds = [...selectedIds, ...rangeSelectedIds]; + const uniqueSelectedIds = [...new Set(allSelectedIds)]; + updateContext({ selectedIds: uniqueSelectedIds }); + onSelectionChange?.(uniqueSelectedIds); + } else { + const newSelectedIds = [...selectedIds, asset.id]; + updateContext({ selectedIds: newSelectedIds }); + onSelectionChange?.(newSelectedIds); + } + setLastSelectedIndex(clickedIndex); + } + }, [selectedIds, assets, lastSelectedIndex, updateContext, onSelectionChange]); + + const handleEsc = useCallback((event: KeyboardEvent) => { + if (event.key === "Escape") { + updateContext({ selectedIds: [] }); + onSelectionChange?.([]); + } + }, [updateContext, onSelectionChange]); + + useEffect(() => { + window.addEventListener("keydown", handleEsc); + return () => window.removeEventListener("keydown", handleEsc); + }, [handleEsc]); + + // Calculate grid dimensions + const rowCount = Math.ceil(assets.length / columnCount); + const width = columnCount * itemSize; + + // Cell renderer for React Window + const Cell = useCallback(({ columnIndex, rowIndex, style }: { columnIndex: number; rowIndex: number; style: React.CSSProperties }) => { + const assetIndex = rowIndex * columnCount + columnIndex; + const asset = assets[assetIndex]; + + if (!asset) { + return
; + } + + const isSelected = selectedIds.includes(asset.id); + + return ( +
handleClick(assetIndex, asset, e)} + > +
+ + {asset.type === "VIDEO" && ( +
+ + {asset.duration && ( + + {humanizeDuration(asset.duration)} + + )} +
+ )} + {selectable && ( +
+ )} +
+
+ ); + }, [assets, selectedIds, columnCount, handleClick, selectable]); + + return ( +
+ = 0} + index={index} + close={() => setIndex(-1)} + /> + + {Cell} + +
+ ); +}); + +VirtualizedAssetGrid.displayName = "VirtualizedAssetGrid"; +export default VirtualizedAssetGrid; diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index 8fd8bb6..cfc3b73 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -13,20 +13,15 @@ import { useReactTable, VisibilityState, } from "@tanstack/react-table" -import { ArrowUpDown, ChevronDown, MoreHorizontal } from "lucide-react" +import { ChevronDown } 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, @@ -94,7 +89,6 @@ export function DataTable({ enableSorting: true, enableFilters: true, enableColumnFilters: true, - enablePagination: true, }) // Sync external selection with table selection @@ -175,22 +169,10 @@ export function DataTable({ { - // Prevent row click from interfering with link clicks - if (e.target instanceof HTMLAnchorElement) { - e.stopPropagation() - } - }} > {row.getVisibleCells().map((cell) => ( { - // Allow link clicks to propagate - if (e.target instanceof HTMLAnchorElement) { - e.stopPropagation() - } - }} > {flexRender( cell.column.columnDef.cell, diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 7714555..2a4749c 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1 +1,2 @@ -export { useAlbumSelection } from './useAlbumSelection' \ No newline at end of file +export { useAlbumSelection } from './useAlbumSelection' +export { useGridDimensions } from './useGridDimensions' \ No newline at end of file diff --git a/src/hooks/useGridDimensions.ts b/src/hooks/useGridDimensions.ts new file mode 100644 index 0000000..c22aba9 --- /dev/null +++ b/src/hooks/useGridDimensions.ts @@ -0,0 +1,82 @@ +import { useState, useEffect, useCallback } from 'react'; + +interface UseGridDimensionsProps { + containerWidth: number; + containerHeight: number; + itemSize: number; + gap?: number; + minColumns?: number; + maxColumns?: number; +} + +interface GridDimensions { + columnCount: number; + rowCount: number; + itemSize: number; + gap: number; + width: number; + height: number; +} + +export const useGridDimensions = ({ + containerWidth, + containerHeight, + itemSize, + gap = 8, + minColumns = 2, + maxColumns = 10 +}: UseGridDimensionsProps): GridDimensions => { + const [dimensions, setDimensions] = useState({ + columnCount: minColumns, + rowCount: 0, + itemSize, + gap, + width: containerWidth, + height: containerHeight + }); + + const calculateDimensions = useCallback(() => { + if (containerWidth <= 0) return; + + // Calculate optimal column count based on container width + const availableWidth = containerWidth - gap; // Account for gap + const optimalColumnCount = Math.floor(availableWidth / (itemSize + gap)); + + // Clamp column count between min and max + const columnCount = Math.max(minColumns, Math.min(maxColumns, optimalColumnCount)); + + // Calculate actual item size to fit the container + const actualItemSize = (availableWidth - (columnCount - 1) * gap) / columnCount; + + // Calculate total width needed + const totalWidth = columnCount * actualItemSize + (columnCount - 1) * gap; + + // Calculate height (this will be updated when we know the total number of items) + const totalHeight = containerHeight; + + setDimensions({ + columnCount, + rowCount: 0, // Will be calculated when we have the data + itemSize: actualItemSize, + gap, + width: totalWidth, + height: totalHeight + }); + }, [containerWidth, containerHeight, itemSize, gap, minColumns, maxColumns]); + + useEffect(() => { + calculateDimensions(); + }, [calculateDimensions]); + + const updateRowCount = useCallback((totalItems: number) => { + setDimensions(prev => ({ + ...prev, + rowCount: Math.ceil(totalItems / prev.columnCount) + })); + }, []); + + return { + ...dimensions, + updateRowCount + }; +}; diff --git a/src/pages/albums/[albumId].tsx b/src/pages/albums/[albumId].tsx index 2cf9e87..c67c7bf 100644 --- a/src/pages/albums/[albumId].tsx +++ b/src/pages/albums/[albumId].tsx @@ -145,7 +145,7 @@ export default function AlbumListPage() { } return ( - +
+
@@ -233,7 +233,7 @@ export default function AlbumListPage() { /> {renderContent()} {currentSelectedCount > 0 && ( - +

{currentSelectedCount} Selected diff --git a/src/pages/albums/potential-albums.tsx b/src/pages/albums/potential-albums.tsx index 98fe253..e9cccf6 100644 --- a/src/pages/albums/potential-albums.tsx +++ b/src/pages/albums/potential-albums.tsx @@ -112,7 +112,7 @@ export default function PotentialAlbums() { } return ( - +

+
+
+
{geminiEnabled ? ( <>