Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[web][photos] Add date scrubber to All view (#14355)

Aswin Asokb2ed3dc93e49
diff --git a/web/apps/photos/src/components/FileList.tsx b/web/apps/photos/src/components/FileList.tsx
index 427a95b298..17331463c3 100644
--- a/web/apps/photos/src/components/FileList.tsx
+++ b/web/apps/photos/src/components/FileList.tsx
@@ -1,4 +1,9 @@
import Avatar from "@/components/Avatar";
+import { DateScrubber } from "@/components/date-scrubber/DateScrubber";
+import {
+ createTimeline,
+ indexAtOffset,
+} from "@/components/date-scrubber/timeline";
import {
FileContextMenu,
type ContextMenuPosition,
@@ -23,7 +28,15 @@ import AlbumOutlinedIcon from "@mui/icons-material/AlbumOutlined";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import PlayArrowRoundedIcon from "@mui/icons-material/PlayArrowRounded";
import PlayCircleOutlineOutlinedIcon from "@mui/icons-material/PlayCircleOutlineOutlined";
-import { Box, Checkbox, Fab, Typography, styled } from "@mui/material";
+import {
+ Box,
+ Checkbox,
+ Fab,
+ Typography,
+ styled,
+ useMediaQuery,
+ useTheme,
+} from "@mui/material";
import type { LocalUser } from "ente-accounts/services/user";
import { assertionFailed } from "ente-base/assert";
import { Overlay } from "ente-base/components/containers";
@@ -31,7 +44,10 @@ import { formattedDateRelative } from "ente-base/i18n-date";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
import type { EnteFile } from "ente-media/file";
-import { fileDurationString } from "ente-media/file-metadata";
+import {
+ fileCreationPhotoDate,
+ fileDurationString,
+} from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import {
LoadingThumbnail,
@@ -49,8 +65,10 @@ import {
} from "ente-new/photos/services/collection-summary";
import { batch } from "ente-utils/array";
import React, {
+ createContext,
memo,
useCallback,
+ useContext,
useDeferredValue,
useEffect,
useMemo,
@@ -112,6 +130,7 @@ export interface FileListProps {
user?: LocalUser;
disableGrouping?: boolean;
enableSelect?: boolean;
+ enableDateScrubber?: boolean;
setSelected: (
selected: SelectedState | ((selected: SelectedState) => SelectedState),
) => void;
@@ -135,6 +154,26 @@ export interface FileListProps {
suppressSelectionUI?: boolean;
}
+const emptyTimeline = createTimeline([]);
+
+// Keep the inner element type stable so height changes preserve mounted rows.
+const ListInnerHeightContext = createContext<number | undefined>(undefined);
+
+const FileListInner = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ style, ...props }, ref) => {
+ const height = useContext(ListInnerHeightContext);
+ return (
+ <div
+ {...props}
+ ref={ref}
+ style={height === undefined ? style : { ...style, height }}
+ />
+ );
+});
+FileListInner.displayName = "FileListInner";
+
export const FileList: React.FC<FileListProps> = ({
height,
width,
@@ -149,6 +188,7 @@ export const FileList: React.FC<FileListProps> = ({
annotatedFiles,
disableGrouping,
enableSelect,
+ enableDateScrubber = false,
selected,
setSelected,
activeCollectionID,
@@ -167,6 +207,26 @@ export const FileList: React.FC<FileListProps> = ({
}) => {
const [_items, setItems] = useState<FileListItem[]>([]);
const items = useDeferredValue(_items);
+ const theme = useTheme();
+ const desktop = useMediaQuery(theme.breakpoints.up("md"));
+ const scrubberEnabled = enableDateScrubber && desktop;
+ const [scrollOffset, setScrollOffset] = useState(0);
+ const timeline = useMemo(() => {
+ if (!scrubberEnabled) return emptyTimeline;
+ return createTimeline(
+ items.map((item) => {
+ if (item.type !== "file") return item;
+ const dates = item.groups.map(({ annotatedFiles }) =>
+ fileCreationPhotoDate(annotatedFiles[0]!.file),
+ );
+ return { height: item.height, dates };
+ }),
+ );
+ }, [items, scrubberEnabled]);
+ const showScrubber =
+ timeline.months.length > 0 &&
+ timeline.totalHeight > height &&
+ height > 64;
const [rangeStartIndex, setRangeStartIndex] = useState<number | undefined>(
undefined,
@@ -354,6 +414,26 @@ export const FileList: React.FC<FileListProps> = ({
listRef.current?.resetAfterIndex(0);
}, [items]);
+ const seekTimeline = useCallback((offset: number, row: number) => {
+ listRef.current?.scrollToItem(row, "start");
+ listRef.current?.scrollTo(offset);
+ }, []);
+
+ const scrollTimelineBy = useCallback((delta: number) => {
+ if (outerRef.current) outerRef.current.scrollTop += delta;
+ }, []);
+
+ useEffect(() => {
+ if (showScrubber) {
+ const offset = Math.min(
+ outerRef.current?.scrollTop ?? 0,
+ timeline.totalHeight - height,
+ );
+ seekTimeline(offset, indexAtOffset(timeline.offsets, offset));
+ setScrollOffset(offset);
+ }
+ }, [timeline, height, showScrubber, seekTimeline]);
+
useEffect(() => {
const notSelectedFiles = annotatedFiles.filter(
(af) => !selected[af.file.id],
@@ -779,6 +859,7 @@ export const FileList: React.FC<FileListProps> = ({
onScroll?.(scrollOffset);
setShowBackToTop(scrollOffset > 500);
+ if (showScrubber) setScrollOffset(scrollOffset);
if (onVisibleDateChange && items.length > 0) {
let cumulativeHeight = 0;
@@ -800,7 +881,7 @@ export const FileList: React.FC<FileListProps> = ({
}
}
},
- [onScroll, onVisibleDateChange, items],
+ [onScroll, onVisibleDateChange, items, showScrubber],
);
const handleScrollToTop = useCallback(() => {
@@ -826,26 +907,55 @@ export const FileList: React.FC<FileListProps> = ({
}
return (
- <Box sx={{ position: "relative", width, height }}>
- <VariableSizeList
- key={key}
- ref={listRef}
- outerRef={outerRef}
- {...{ width, height, itemData, itemSize, itemKey }}
- itemCount={items.length}
- overscanCount={3}
- useIsScrolling
- onScroll={handleScroll}
- style={
- listBorderRadius
- ? { borderRadius: listBorderRadius }
- : undefined
- }
+ <Box
+ sx={{
+ position: "relative",
+ width,
+ height,
+ ...(showScrubber && {
+ "& > .photo-list": {
+ scrollbarWidth: "none",
+ "&::-webkit-scrollbar": { display: "none" },
+ },
+ "&:has([data-date-scrubber-active]) .back-to-top, &:has([data-date-scrubber]:hover) .back-to-top, &:has([data-date-scrubber] :focus-visible) .back-to-top":
+ { visibility: "hidden" },
+ }),
+ }}
+ >
+ <ListInnerHeightContext.Provider
+ value={showScrubber ? timeline.totalHeight : undefined}
>
- {FileListRow}
- </VariableSizeList>
+ <VariableSizeList
+ key={key}
+ ref={listRef}
+ outerRef={outerRef}
+ {...{ height, itemData, itemSize, itemKey }}
+ innerElementType={FileListInner}
+ width={width}
+ className="photo-list"
+ itemCount={items.length}
+ overscanCount={3}
+ useIsScrolling
+ onScroll={handleScroll}
+ style={
+ listBorderRadius
+ ? { borderRadius: listBorderRadius }
+ : undefined
+ }
+ >
+ {FileListRow}
+ </VariableSizeList>
+ </ListInnerHeightContext.Provider>
+ {showScrubber && (
+ <DateScrubber
+ {...{ timeline, height, scrollOffset }}
+ onSeek={seekTimeline}
+ onScrollBy={scrollTimelineBy}
+ />
+ )}
{showBackToTop && (
<BackToTopButton
+ className="back-to-top"
size="small"
aria-label="scroll to top"
onClick={handleScrollToTop}
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index 298db30ddb..b2a87c48e0 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -50,6 +50,7 @@ export type FileListWithViewerProps = {
| "onAddPhotos"
| "disableGrouping"
| "enableSelect"
+ | "enableDateScrubber"
| "selected"
| "setSelected"
| "activeCollectionID"
@@ -95,6 +96,7 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
enableImageEditing = true,
disableGrouping,
enableSelect,
+ enableDateScrubber,
selected,
setSelected,
activeCollectionID,
@@ -225,6 +227,7 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
user,
disableGrouping,
enableSelect,
+ enableDateScrubber,
selected,
setSelected,
activeCollectionID,
diff --git a/web/apps/photos/src/components/date-scrubber/DateScrubber.tsx b/web/apps/photos/src/components/date-scrubber/DateScrubber.tsx
new file mode 100644
index 0000000000..0f5a92dd1b
--- /dev/null
+++ b/web/apps/photos/src/components/date-scrubber/DateScrubber.tsx
@@ -0,0 +1,331 @@
+import { Box } from "@mui/material";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ adjacentMonthOffset,
+ indexAtOffset,
+ timelineMarkers,
+ wheelScrollDelta,
+ type Timeline,
+} from "./timeline";
+
+interface DateScrubberProps {
+ timeline: Timeline;
+ height: number;
+ scrollOffset: number;
+ onSeek: (offset: number, row: number) => void;
+ onScrollBy: (delta: number) => void;
+}
+
+const inset = 24;
+
+export const DateScrubber = ({
+ timeline,
+ height,
+ scrollOffset,
+ onSeek,
+ onScrollBy,
+}: DateScrubberProps) => {
+ const { t, i18n } = useTranslation();
+ const railRef = useRef<HTMLDivElement>(null);
+ const pointer = useRef<
+ { id: number; grabOffset: number; lastY: number } | undefined
+ >(undefined);
+ const [dragging, setDragging] = useState(false);
+ const [hoverOffset, setHoverOffset] = useState<number>();
+ const [focused, setFocused] = useState(false);
+ const maxOffset = Math.max(0, timeline.totalHeight - height);
+ const trackHeight = Math.max(1, height - 2 * inset);
+ const clamp = (offset: number) => Math.max(0, Math.min(maxOffset, offset));
+ const fraction = (offset: number) => clamp(offset) / Math.max(1, maxOffset);
+ const position = (offset: number) => inset + fraction(offset) * trackHeight;
+ const { months } = timeline;
+ const monthOffsets = useMemo(
+ () => months.map(({ offset }) => offset),
+ [months],
+ );
+ const markers = useMemo(
+ () => timelineMarkers(months, maxOffset, trackHeight),
+ [months, maxOffset, trackHeight],
+ );
+ const formatter = useMemo(
+ () =>
+ new Intl.DateTimeFormat(i18n.resolvedLanguage, {
+ calendar: "gregory",
+ month: "long",
+ year: "numeric",
+ }),
+ [i18n.resolvedLanguage],
+ );
+ const bottomOffset = Math.floor(maxOffset);
+ const monthAt = (offset: number) =>
+ offset > 0 && offset >= bottomOffset
+ ? months[months.length - 1]!
+ : months[indexAtOffset(monthOffsets, offset + 1)]!;
+ const seek = (offset: number) => {
+ const target = clamp(offset);
+ onSeek(target, indexAtOffset(timeline.offsets, target));
+ };
+ const offsetAtPointer = (clientY: number) =>
+ clamp(
+ ((clientY - railRef.current!.getBoundingClientRect().top - inset) /
+ trackHeight) *
+ maxOffset,
+ );
+
+ useEffect(() => {
+ const rail = railRef.current!;
+ const onWheel = (event: WheelEvent) => {
+ const delta = wheelScrollDelta(event, height);
+ if (!delta) return;
+ event.preventDefault();
+ event.stopPropagation();
+ onScrollBy(delta);
+ };
+ rail.addEventListener("wheel", onWheel, { passive: false });
+ return () => rail.removeEventListener("wheel", onWheel);
+ }, [height, onScrollBy]);
+
+ useEffect(() => {
+ setHoverOffset(undefined);
+ }, [timeline, height]);
+
+ useEffect(() => {
+ const rail = railRef.current!;
+ return () => {
+ const id = pointer.current?.id;
+ pointer.current = undefined;
+ if (id !== undefined && rail.hasPointerCapture(id))
+ rail.releasePointerCapture(id);
+ };
+ }, []);
+
+ const stopDragging = () => {
+ pointer.current = undefined;
+ setDragging(false);
+ setHoverOffset(undefined);
+ };
+
+ const previewOffset = dragging
+ ? scrollOffset
+ : (hoverOffset ?? scrollOffset);
+ const label = formatter.format(monthAt(previewOffset).date);
+ return (
+ <Box
+ ref={railRef}
+ data-date-scrubber
+ data-date-scrubber-active={dragging ? "" : undefined}
+ onPointerDown={(event) => {
+ if (
+ event.button !== 0 ||
+ pointer.current ||
+ !(event.target as HTMLElement).closest(".date-handle")
+ )
+ return;
+ event.preventDefault();
+ const grabOffset =
+ event.clientY -
+ event.currentTarget.getBoundingClientRect().top -
+ position(scrollOffset);
+ pointer.current = {
+ id: event.pointerId,
+ grabOffset,
+ lastY: event.clientY,
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ setDragging(true);
+ }}
+ onPointerMove={(event) => {
+ const drag = pointer.current;
+ if (!drag) {
+ setHoverOffset(offsetAtPointer(event.clientY));
+ } else if (
+ drag.id === event.pointerId &&
+ drag.lastY !== event.clientY
+ ) {
+ drag.lastY = event.clientY;
+ seek(offsetAtPointer(event.clientY - drag.grabOffset));
+ }
+ }}
+ onPointerLeave={() => setHoverOffset(undefined)}
+ onPointerCancel={stopDragging}
+ onLostPointerCapture={stopDragging}
+ sx={{
+ position: "absolute",
+ right: 0,
+ top: 0,
+ width: 24,
+ height,
+ touchAction: "none",
+ userSelect: "none",
+ zIndex: 1,
+ "& .date-tick, & .date-handle, & .date-label": {
+ position: "absolute",
+ transform: "translateY(-50%)",
+ },
+ "& .date-tick, & .date-handle": {
+ transition: "opacity 250ms ease-in-out",
+ },
+ "& .date-tick": { opacity: 0 },
+ "& .date-year-target": { pointerEvents: "none" },
+ "& .date-handle": { opacity: 0.3 },
+ "& .date-year-target, & .date-handle": { p: 0, border: 0 },
+ "& .date-label": {
+ px: 1,
+ py: 0.5,
+ border: "0.5px solid",
+ borderColor: "stroke.faint",
+ borderRadius: "6px",
+ bgcolor: "background.elevatedPaper",
+ boxShadow: "0 2px 3px rgba(0, 0, 0, 0.1)",
+ },
+ "&:hover, &:has(:focus-visible), &[data-date-scrubber-active]":
+ {
+ "& .date-tick, & .date-handle": { opacity: 1 },
+ "& .date-year-target": { pointerEvents: "auto" },
+ },
+ "@media (prefers-reduced-motion: reduce)": {
+ "& .date-tick, & .date-handle": { transition: "none" },
+ },
+ }}
+ >
+ {markers.map((marker) =>
+ !marker.yearStart ? (
+ <Box
+ key={`${marker.date.getFullYear()}-${marker.date.getMonth()}`}
+ className="date-tick"
+ aria-hidden
+ sx={{
+ top: inset + marker.position,
+ right: 11,
+ width: 3,
+ height: "3px",
+ bgcolor: "text.muted",
+ borderRadius: "50%",
+ pointerEvents: "none",
+ }}
+ />
+ ) : (
+ <Box
+ component="button"
+ type="button"
+ className="date-tick date-year-target"
+ key={`${marker.date.getFullYear()}-${marker.date.getMonth()}`}
+ aria-label={t("jump_to_date", {
+ date: formatter.format(marker.date),
+ })}
+ onPointerDown={(event) => event.stopPropagation()}
+ onPointerMove={(event) => {
+ event.stopPropagation();
+ setHoverOffset(marker.offset);
+ }}
+ onFocus={() => setHoverOffset(marker.offset)}
+ onBlur={() => setHoverOffset(undefined)}
+ onClick={() => seek(marker.offset)}
+ sx={{
+ top: inset + marker.position,
+ right: 0,
+ width: 24,
+ height: 24,
+ bgcolor: "transparent",
+ cursor: "pointer",
+ "&::before": {
+ content: '""',
+ position: "absolute",
+ top: "50%",
+ right: 8,
+ width: 8,
+ height: "2px",
+ bgcolor: "text.muted",
+ },
+ }}
+ >
+ <Box
+ component="span"
+ className="date-year-label date-label"
+ sx={{
+ right: 32,
+ pointerEvents: "none",
+ top: "50%",
+ color: "text.muted",
+ typography: "mini",
+ fontVariantNumeric: "tabular-nums",
+ }}
+ >
+ {marker.date.getFullYear()}
+ </Box>
+ </Box>
+ ),
+ )}
+ <Box
+ component="button"
+ type="button"
+ role="slider"
+ className="date-handle"
+ aria-label={t("browse_photos_by_date")}
+ aria-orientation="vertical"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(fraction(scrollOffset) * 100)}
+ aria-valuetext={formatter.format(monthAt(scrollOffset).date)}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ onKeyDown={(event) => {
+ const edges: Partial<Record<string, number>> = {
+ Home: 0,
+ End: maxOffset,
+ };
+ let target = edges[event.key];
+ if (event.key.startsWith("Arrow")) {
+ const older = ["ArrowDown", "ArrowRight"].includes(
+ event.key,
+ );
+ target =
+ adjacentMonthOffset(
+ monthOffsets,
+ clamp(scrollOffset),
+ older ? "older" : "newer",
+ bottomOffset,
+ ) ?? (older ? maxOffset : 0);
+ }
+ if (target === undefined) return;
+ event.preventDefault();
+ setHoverOffset(undefined);
+ seek(target);
+ }}
+ sx={{
+ top: position(scrollOffset),
+ right: 8,
+ width: 8,
+ height: 36,
+ borderRadius: "4px",
+ bgcolor: "text.muted",
+ cursor: "ns-resize",
+ touchAction: "none",
+ "&::before": {
+ content: '""',
+ position: "absolute",
+ inset: "-4px -7px",
+ },
+ }}
+ />
+ {(hoverOffset !== undefined || dragging || focused) && (
+ <Box
+ role="tooltip"
+ className="date-label"
+ sx={{
+ right: 88,
+ top: position(previewOffset),
+ color: "text.primary",
+ typography: "small",
+ whiteSpace: "nowrap",
+ pointerEvents: "none",
+ zIndex: 2,
+ }}
+ >
+ {label}
+ </Box>
+ )}
+ </Box>
+ );
+};
diff --git a/web/apps/photos/src/components/date-scrubber/timeline.ts b/web/apps/photos/src/components/date-scrubber/timeline.ts
new file mode 100644
index 0000000000..811aef3744
--- /dev/null
+++ b/web/apps/photos/src/components/date-scrubber/timeline.ts
@@ -0,0 +1,124 @@
+export interface TimelineRow {
+ height: number;
+ dates?: Date[];
+}
+
+export interface TimelineMonth {
+ date: Date;
+ offset: number;
+ yearStart: boolean;
+}
+
+export const createTimeline = (rows: TimelineRow[]) => {
+ const offsets: number[] = [];
+ const months: TimelineMonth[] = [];
+ const seenMonths = new Set<string>();
+ const seenYears = new Set<number>();
+ let totalHeight = 0;
+ rows.forEach(({ height, dates }) => {
+ offsets.push(totalHeight);
+ for (const date of dates ?? []) {
+ if (!Number.isFinite(date.getTime())) continue;
+ const year = date.getFullYear();
+ const key = `${year}-${date.getMonth()}`;
+ if (seenMonths.has(key)) continue;
+ seenMonths.add(key);
+ months.push({
+ date,
+ offset: totalHeight,
+ yearStart: !seenYears.has(year),
+ });
+ seenYears.add(year);
+ }
+ totalHeight += height;
+ });
+ return { offsets, months, totalHeight };
+};
+
+export type Timeline = ReturnType<typeof createTimeline>;
+
+export const wheelScrollDelta = (
+ event: Pick<WheelEvent, "deltaY" | "deltaX" | "deltaMode" | "ctrlKey">,
+ pageHeight: number,
+) => {
+ if (event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY))
+ return 0;
+ const unit =
+ event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? pageHeight : 1;
+ return event.deltaY * unit;
+};
+
+const firstOffsetOutside = (
+ offsets: number[],
+ inPrefix: (offset: number) => boolean,
+) => {
+ let low = 0;
+ let high = offsets.length;
+ while (low < high) {
+ const middle = (low + high) >>> 1;
+ if (inPrefix(offsets[middle]!)) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+};
+
+export const indexAtOffset = (offsets: number[], offset: number) => {
+ const end = firstOffsetOutside(offsets, (value) => value <= offset);
+ if (end === 0) return 0;
+ return firstOffsetOutside(offsets, (value) => value < offsets[end - 1]!);
+};
+
+export const adjacentMonthOffset = (
+ offsets: number[],
+ offset: number,
+ direction: "older" | "newer",
+ bottomOffset = Infinity,
+) => {
+ if (direction === "newer" && offset > 0 && offset >= bottomOffset) {
+ const firstAtBottom = firstOffsetOutside(
+ offsets,
+ (value) => value < bottomOffset,
+ );
+ return offsets[firstAtBottom - 1] ?? 0;
+ }
+ const roundedOffset = offset + 1;
+ if (direction === "older") {
+ const boundary = Math.max(roundedOffset, offsets[0] ?? 0);
+ return offsets[
+ firstOffsetOutside(offsets, (value) => value <= boundary)
+ ];
+ }
+ const current = indexAtOffset(offsets, roundedOffset);
+ const previous = indexAtOffset(offsets, (offsets[current] ?? 0) - 1);
+ return previous === current ? 0 : offsets[previous];
+};
+
+export const timelineMarkers = (
+ months: TimelineMonth[],
+ maxOffset: number,
+ trackHeight: number,
+) => {
+ if (maxOffset <= 0 || trackHeight <= 0) return [];
+ const positions: { position: number; yearStart: boolean }[] = [];
+ return [
+ ...months.filter((month) => month.yearStart),
+ ...months.filter((month) => !month.yearStart),
+ ].flatMap((month) => {
+ const position =
+ (Math.min(month.offset, maxOffset) / maxOffset) * trackHeight;
+ if (
+ positions.some((other) => {
+ const gap =
+ month.yearStart && other.yearStart
+ ? 48
+ : month.yearStart || other.yearStart
+ ? 24
+ : 12;
+ return Math.abs(other.position - position) < gap;
+ })
+ )
+ return [];
+ positions.push({ position, yearStart: month.yearStart });
+ return [{ ...month, position }];
+ });
+};
diff --git a/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx b/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx
index 2c95f6b377..90b035b2a2 100644
--- a/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx
+++ b/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx
@@ -34,6 +34,7 @@ type GalleryMediaProps = Pick<
> & {
source: GalleryMediaSource;
header?: FileListHeaderOrFooter;
+ enableDateScrubber?: boolean;
onAddPhotos?: () => void;
children?: (hasSelection: boolean) => ReactNode;
};
@@ -58,6 +59,7 @@ const GalleryMediaContent = ({
navigation,
source,
header,
+ enableDateScrubber,
onAddPhotos,
children,
}: GalleryMediaProps) => {
@@ -225,6 +227,7 @@ const GalleryMediaContent = ({
}
user={library.user}
header={header}
+ enableDateScrubber={enableDateScrubber}
onAddPhotos={onAddPhotos}
footer={footer}
enableDownload
diff --git a/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx
index 76b3a21c4d..71e744788c 100644
--- a/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx
+++ b/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx
@@ -348,6 +348,12 @@ export const AlbumsSection = ({
<GalleryMedia
{...{ library, operations, navigation }}
header={fileListHeader}
+ enableDateScrubber={
+ !library.isFirstLoad &&
+ barMode === "albums" &&
+ activeCollectionID === PseudoCollectionID.all &&
+ !isInSearchMode
+ }
onAddPhotos={canAddPhotos ? handleAddPhotos : undefined}
source={{
mode: barMode,
diff --git a/web/apps/photos/tests/albums-section-summary.test.tsx b/web/apps/photos/tests/albums-section-summary.test.tsx
index f3f62d498e..4ff09fbaee 100644
--- a/web/apps/photos/tests/albums-section-summary.test.tsx
+++ b/web/apps/photos/tests/albums-section-summary.test.tsx
@@ -6,6 +6,7 @@ import { PseudoCollectionID } from "ente-new/photos/services/collection-summary"
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, expect, test, vi } from "vitest";
+import { GalleryMedia } from "../src/components/gallery/media/GalleryMedia";
import {
galleryReducer,
initialGalleryState,
@@ -51,11 +52,10 @@ vi.mock("../src/components/gallery/sections/albums/AlbumsNavigation", () => ({
AlbumsNavigation: () => null,
}));
vi.mock("../src/components/gallery/media/GalleryMedia", () => ({
- GalleryMedia: ({
- children,
- }: {
- children?: (hasSelection: boolean) => ReactNode;
- }) => children?.(false),
+ GalleryMedia: vi.fn(
+ ({ children }: { children?: (hasSelection: boolean) => ReactNode }) =>
+ children?.(false),
+ ),
}));
vi.mock("../src/components/gallery/navigation/GallerySectionLayout", () => ({
GallerySectionLayout: ({ children }: { children: ReactNode }) => children,
@@ -111,11 +111,16 @@ const openAlbum = (
return state;
};
-const headerSummary = (state: GalleryState, collectionID = 10) => {
+const headerSummary = (
+ state: GalleryState,
+ collectionID = 10,
+ overlay?: GallerySectionProps["navigation"]["overlay"],
+ isFirstLoad = false,
+) => {
const props: GallerySectionProps = {
library: {
...state,
- isFirstLoad: false,
+ isFirstLoad,
searchIndexRevision: 0,
remotePullRevision: 0,
},
@@ -144,6 +149,7 @@ const headerSummary = (state: GalleryState, collectionID = 10) => {
setSectionActivity: vi.fn(),
},
navigation: {
+ overlay,
destination: {
section: "albums",
collectionID,
@@ -185,6 +191,36 @@ const headerSummary = (state: GalleryState, collectionID = 10) => {
return vi.mocked(AlbumContentHeader).mock.lastCall![0].collectionSummary;
};
+test("enables the date scrubber only for the normal All grid", () => {
+ const state = openAlbum(ItemVisibility.visible, files);
+ headerSummary(state, PseudoCollectionID.all, undefined, true);
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: false,
+ });
+ headerSummary(state, PseudoCollectionID.all);
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: true,
+ });
+ for (const id of [10, PseudoCollectionID.trash]) {
+ headerSummary(state, id);
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: false,
+ });
+ }
+ headerSummary(state, PseudoCollectionID.all, { section: "search" });
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: false,
+ });
+ headerSummary(openAlbum(ItemVisibility.hidden, files));
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: false,
+ });
+ headerSummary(openAlbum(ItemVisibility.archived, files));
+ expect(vi.mocked(GalleryMedia).mock.lastCall![0]).toMatchObject({
+ enableDateScrubber: false,
+ });
+});
+
test.each([
["normal", ItemVisibility.visible],
["hidden", ItemVisibility.hidden],
diff --git a/web/apps/photos/tests/date-scrubber.test.tsx b/web/apps/photos/tests/date-scrubber.test.tsx
new file mode 100644
index 0000000000..17f4597e10
--- /dev/null
+++ b/web/apps/photos/tests/date-scrubber.test.tsx
@@ -0,0 +1,245 @@
+import { createTheme, ThemeProvider } from "@mui/material";
+import type { EnteFile } from "ente-media/file";
+import { fileCreationPhotoDate } from "ente-media/file-metadata";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, test, vi } from "vitest";
+import { DateScrubber } from "../src/components/date-scrubber/DateScrubber";
+import {
+ adjacentMonthOffset,
+ createTimeline,
+ indexAtOffset,
+ timelineMarkers,
+ wheelScrollDelta,
+} from "../src/components/date-scrubber/timeline";
+
+let resolvedLanguage = "en-US";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: { date: string }) =>
+ values ? `Jump to ${values.date}` : key,
+ i18n: { resolvedLanguage },
+ }),
+}));
+
+const november = new Date(2026, 10, 2);
+const october = new Date(2026, 9, 4);
+const december = new Date(2025, 11, 25);
+const timelineOf = (...rows: [height: number, ...dates: Date[]][]) =>
+ createTimeline(rows.map(([height, ...dates]) => ({ height, dates })));
+
+describe("date scrubber timeline", () => {
+ test("forwards wheel and trackpad deltas while preserving horizontal gestures and zoom", () => {
+ const wheel = { deltaY: 120, deltaX: 0, deltaMode: 0, ctrlKey: false };
+ for (const [overrides, expected] of [
+ [{}, 120],
+ [{ deltaY: -2.5 }, -2.5],
+ [{ deltaY: 3, deltaMode: 1 }, 48],
+ [{ deltaY: 1, deltaMode: 2 }, 600],
+ [{ ctrlKey: true }, 0],
+ [{ deltaX: 200 }, 0],
+ [{ deltaY: 0 }, 0],
+ ] as const)
+ expect(wheelScrollDelta({ ...wheel, ...overrides }, 600)).toBe(
+ expected,
+ );
+ });
+ test("keyboard navigation skips the content header and shared-month rows", () => {
+ const offsets = [120, 120, 500, 900];
+ for (const [offset, direction, expected] of [
+ [0, "older", 500],
+ [0, "newer", 0],
+ [120, "older", 500],
+ [500, "newer", 120],
+ [600, "older", 900],
+ [1000, "older", undefined],
+ [1000, "newer", 500],
+ ] as const)
+ expect(adjacentMonthOffset(offsets, offset, direction)).toBe(
+ expected,
+ );
+ for (const [direction, expected] of [
+ ["older", 900.8],
+ ["newer", 120.4],
+ ] as const)
+ expect(
+ adjacentMonthOffset([120.4, 500.6, 900.8], 500, direction),
+ ).toBe(expected);
+ });
+ test("includes headers, date rows, and footers in exact scroll offsets", () => {
+ const timeline = timelineOf(
+ [80],
+ [40],
+ [180, november, november],
+ [180, november],
+ [40],
+ [180, december],
+ [100],
+ );
+ expect(timeline.totalHeight).toBe(800);
+ expect(timeline.offsets).toEqual([0, 80, 120, 300, 480, 520, 700]);
+ expect(
+ timeline.months.map(({ offset, yearStart }) => ({
+ offset,
+ row: indexAtOffset(timeline.offsets, offset),
+ yearStart,
+ })),
+ ).toEqual([
+ { offset: 120, row: 2, yearStart: true },
+ { offset: 520, row: 5, yearStart: true },
+ ]);
+ });
+ test("indexes sparse months sharing a row without inventing empty months", () => {
+ const { months } = timelineOf(
+ [180, november, october],
+ [180, december],
+ );
+ expect(months.map(({ date }) => date.getMonth())).toEqual([10, 9, 11]);
+ expect(months.map(({ offset }) => offset)).toEqual([0, 0, 180]);
+ expect(months.map(({ yearStart }) => yearStart)).toEqual([
+ true,
+ false,
+ true,
+ ]);
+ expect(
+ [0, 100, 180].map((offset) => indexAtOffset([0, 0, 180], offset)),
+ ).toEqual([0, 0, 2]);
+ });
+ test("finds row boundaries, including before photos and within the footer", () => {
+ const offsets = [0, 80, 120, 300, 480, 520, 700];
+ expect(
+ [-10, 0, 119, 120, 699, 1000].map((offset) =>
+ indexAtOffset(offsets, offset),
+ ),
+ ).toEqual([0, 0, 1, 2, 5, 6]);
+ expect(timelineOf()).toEqual({
+ offsets: [],
+ months: [],
+ totalHeight: 0,
+ });
+ });
+ test("looks up a distant row in a large library with logarithmic work", () => {
+ let reads = 0;
+ const offsets = new Proxy(
+ Array.from({ length: 100_000 }, (_, index) => index * 180),
+ {
+ get(target, property, receiver) {
+ reads++;
+ return Reflect.get(target, property, receiver) as unknown;
+ },
+ },
+ );
+ expect(indexAtOffset(offsets, 99_999 * 180)).toBe(99_999);
+ expect(reads).toBeLessThan(60);
+ });
+ test("uses edited photo-local dates instead of original upload metadata", () => {
+ const file = {
+ metadata: { creationTime: 1 },
+ pubMagicMetadata: { data: { dateTime: "2026-11-02T12:30:00" } },
+ } as EnteFile;
+ const { months } = timelineOf(
+ [180, fileCreationPhotoDate(file)],
+ [180, new Date(NaN)],
+ );
+ expect(months).toHaveLength(1);
+ expect(months[0]!.date.getFullYear()).toBe(2026);
+ expect(months[0]!.date.getMonth()).toBe(10);
+ });
+ test("gives year labels 48px of space and clamps the last marker", () => {
+ const { months } = timelineOf(
+ [10, november],
+ [10, october],
+ [100, december],
+ );
+ const markers = timelineMarkers(months, 100, 200);
+ expect(markers.map(({ yearStart }) => yearStart)).toEqual([true]);
+ expect(markers.map(({ position }) => position)).toEqual([0]);
+ expect(timelineMarkers(months, 0, 200)).toEqual([]);
+ expect(timelineMarkers(months, 5, 200).at(-1)?.position).toBe(200);
+ });
+ test("keeps month dots 12px apart and clear of the year chips", () => {
+ const { months } = timelineOf(
+ [24, november],
+ [12, october],
+ [8, new Date(2026, 8, 1)],
+ [60, new Date(2026, 7, 1)],
+ [100, december],
+ );
+ expect(
+ timelineMarkers(months, 200, 200).map(({ position }) => position),
+ ).toEqual([0, 104, 24, 36]);
+ });
+ test("rebuilds offsets after a resize or deletion", () => {
+ expect(
+ timelineOf([180, november], [180, october]).months[1]!.offset,
+ ).toBe(180);
+ expect(
+ timelineOf([90, november], [90, october]).months[1]!.offset,
+ ).toBe(90);
+ expect(timelineOf([90, october]).months).toHaveLength(1);
+ });
+});
+
+test.each(["en-US", "en-US-u-ca-buddhist"])(
+ "renders Gregorian month labels and hidden year chips in %s",
+ (language) => {
+ resolvedLanguage = language;
+ const markup = renderToStaticMarkup(
+ <ThemeProvider theme={createTheme()}>
+ <DateScrubber
+ timeline={timelineOf(
+ [500, november],
+ [500, october],
+ [500, december],
+ )}
+ height={300}
+ scrollOffset={0}
+ onSeek={vi.fn()}
+ onScrollBy={vi.fn()}
+ />
+ </ThemeProvider>,
+ );
+ resolvedLanguage = "en-US";
+ expect(markup).toContain('role="slider"');
+ expect(markup).toContain('aria-orientation="vertical"');
+ expect(markup).toContain('aria-valuetext="November 2026"');
+ expect(markup).toContain('aria-label="Jump to December 2025"');
+ expect(markup).not.toContain('role="tooltip"');
+ expect(markup).not.toMatch(/>November 2026</);
+ expect(markup).toMatch(/>2026</);
+ expect(markup).toMatch(/>2025</);
+ expect(markup).toContain("date-year-label");
+ expect(markup).toContain("opacity:0");
+ expect(markup).toContain("pointer-events:none");
+ expect(markup).toContain("border-radius:6px");
+ expect(markup).toContain("height:3px");
+ },
+);
+
+test.each([
+ [400, "November 2026"],
+ [450, "December 2025"],
+])(
+ "labels the oldest month at the scroll limit (offset %i)",
+ (offset, label) => {
+ const markup = renderToStaticMarkup(
+ <ThemeProvider theme={createTheme()}>
+ <DateScrubber
+ timeline={timelineOf([700, november], [50, december])}
+ height={300}
+ scrollOffset={offset}
+ onSeek={vi.fn()}
+ onScrollBy={vi.fn()}
+ />
+ </ThemeProvider>,
+ );
+ expect(markup).toContain(`aria-valuetext="${label}"`);
+ },
+);
+
+test("moves to the preceding reachable month from the scroll limit", () => {
+ expect(adjacentMonthOffset([0, 300, 700], 450, "newer", 450)).toBe(300);
+ expect(adjacentMonthOffset([0, 300, 450, 700], 450, "newer", 450)).toBe(
+ 300,
+ );
+});
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index 8fedd6deed..256283cb95 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -511,6 +511,8 @@
"clear_search": "Clear search",
"album": "Album",
"date": "Date",
+ "browse_photos_by_date": "Browse photos by date",
+ "jump_to_date": "Jump to {{date}}",
"description": "Description",
"file_type": "File type",
"camera_make": "Camera Make",