import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useVirtualizer } from "@tanstack/react-virtual"; import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store"; import { ContextMenu, ImageTile } from "./Gallery"; const GAP = 6; const HEADER_HEIGHT = 52; interface TimelineGroup { key: string; label: string; images: ImageRecord[]; } function buildLabel(key: string): string { if (key === "unknown") return "Unknown Date"; const [yearStr, monthStr] = key.split("-"); const year = Number(yearStr); const month = Number(monthStr); if (!isFinite(year) || !isFinite(month) || month < 1 || month > 12) return "Unknown Date"; const date = new Date(year, month - 1); if (isNaN(date.getTime())) return "Unknown Date"; return date.toLocaleDateString(undefined, { month: "long", year: "numeric" }); } function groupImages(images: ImageRecord[]): TimelineGroup[] { const map = new Map(); for (const img of images) { const ds = img.taken_at ?? img.modified_at; const key = ds ? ds.substring(0, 7) : "unknown"; let bucket = map.get(key); if (bucket === undefined) { bucket = []; map.set(key, bucket); } bucket.push(img); } return Array.from(map.entries()) .sort(([a], [b]) => { if (a === "unknown") return 1; if (b === "unknown") return -1; return a < b ? -1 : a > b ? 1 : 0; }) .map(([key, imgs]) => ({ key, label: buildLabel(key), images: imgs })); } export function Timeline() { const images = useGalleryStore((s) => s.images); const loadMoreImages = useGalleryStore((s) => s.loadMoreImages); const openImage = useGalleryStore((s) => s.openImage); const totalImages = useGalleryStore((s) => s.totalImages); const loadingImages = useGalleryStore((s) => s.loadingImages); const imageLoadError = useGalleryStore((s) => s.imageLoadError); const zoomPreset = useGalleryStore((s) => s.zoomPreset); const parentRef = useRef(null); const [containerWidth, setContainerWidth] = useState(0); const [contextMenu, setContextMenu] = useState<{ x: number; y: number; image: ImageRecord; } | null>(null); // Measure container width before first paint to avoid a single-column flash. useLayoutEffect(() => { const el = parentRef.current; if (!el) return; setContainerWidth(el.clientWidth); const ro = new ResizeObserver((entries) => { setContainerWidth(entries[0].contentRect.width); }); ro.observe(el); return () => ro.disconnect(); }, []); const tileSize = tileSizeForZoom(zoomPreset); const cols = useMemo( () => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))), [containerWidth, tileSize], ); const groups = useMemo(() => groupImages(images), [images]); // estimateSize must be exact so virtualizer positions groups correctly. // Each group height = header + rowCount * (tileSize + GAP) where the last row's // GAP acts as spacing between this group and the next header. const estimateSize = useCallback( (index: number): number => { const group = groups[index]; if (!group) return HEADER_HEIGHT; const rowCount = Math.ceil(group.images.length / cols); return HEADER_HEIGHT + rowCount * (tileSize + GAP); }, [groups, cols, tileSize], ); const virtualizer = useVirtualizer({ count: groups.length, getScrollElement: () => parentRef.current, estimateSize, overscan: 2, }); // Re-measure all items when cols changes so virtualizer positions stay accurate // after a window resize (react-virtual v3 doesn't invalidate cached sizes on its own). useEffect(() => { virtualizer.measure(); }, [cols, virtualizer]); const handleScroll = useCallback(() => { const el = parentRef.current; if (!el) return; if (el.scrollTop < 24) return; const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600; if (nearBottom && !loadingImages && images.length < totalImages) { void loadMoreImages(); } }, [images.length, loadMoreImages, loadingImages, totalImages]); useEffect(() => { const el = parentRef.current; if (!el) return; el.addEventListener("scroll", handleScroll, { passive: true }); return () => el.removeEventListener("scroll", handleScroll); }, [handleScroll]); useEffect(() => { const close = (e: PointerEvent) => { if ((e.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return; setContextMenu(null); }; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setContextMenu(null); }; window.addEventListener("pointerdown", close); window.addEventListener("keydown", onKey); return () => { window.removeEventListener("pointerdown", close); window.removeEventListener("keydown", onKey); }; }, []); return (
{images.length === 0 && loadingImages ? (

Loading timeline

Fetching results

) : images.length === 0 ? (

{imageLoadError ? "Could not load timeline" : "No media found"}

{imageLoadError ?? "Add a folder to see your timeline"}

) : (
{virtualizer.getVirtualItems().map((virtualItem) => { const group = groups[virtualItem.index]; if (!group) return null; return (
{/* Group header */}
{group.label} {group.images.length}
{/* Image grid — paddingBottom:GAP gives the gap below the last row, matching the row-to-row gap and making estimateSize exact. */}
{group.images.map((image) => ( openImage(image)} onContextMenu={(event) => { event.preventDefault(); setContextMenu({ x: event.clientX, y: event.clientY, image }); }} /> ))}
); })}
)} {images.length > 0 && loadingImages ? (
) : null} {contextMenu ? ( setContextMenu(null)} /> ) : null}
); }