Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(photos):add-album-slideshows

Aswin Asokd0f504c8f755
diff --git a/web/apps/photos/src/components/CollectionDialog/styles.ts b/web/apps/photos/src/components/CollectionDialog/styles.ts
index 837c88d24a..2e4607f6d7 100644
--- a/web/apps/photos/src/components/CollectionDialog/styles.ts
+++ b/web/apps/photos/src/components/CollectionDialog/styles.ts
@@ -83,3 +83,44 @@ export const collectionDialogNoResultsSx = {
alignItems: "center",
minHeight: 154,
};
+
+export const collectionDialogToggleGroupSx = (theme: Theme) => ({
+ display: "flex",
+ gap: "8px",
+ "& .MuiToggleButtonGroup-grouped": {
+ flex: "1 1 0",
+ minWidth: 0,
+ marginLeft: "0 !important",
+ padding: "10px 12px",
+ border: 0,
+ borderRadius: "16px !important",
+ color: "text.muted",
+ backgroundColor: "background.paper",
+ fontSize: "14px",
+ lineHeight: "20px",
+ fontWeight: 500,
+ letterSpacing: "-0.011em",
+ textTransform: "none",
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ transition: theme.transitions.create("background-color", {
+ duration: 120,
+ }),
+ "&:hover": { backgroundColor: "fill.faintHover", color: "text.base" },
+ "&:focus-visible": {
+ outline: `1px solid ${theme.vars.palette.stroke.base}`,
+ outlineOffset: 2,
+ },
+ ...theme.applyStyles("dark", {
+ "&:not(.Mui-selected)": {
+ backgroundColor: "rgba(255 255 255 / 0.12)",
+ },
+ }),
+ "&.Mui-selected": {
+ backgroundColor: "accent.main",
+ color: "accent.contrastText",
+ },
+ "&.Mui-selected:hover": { backgroundColor: "accent.dark" },
+ },
+});
diff --git a/web/apps/photos/src/components/Collections/AlbumSlideshow.tsx b/web/apps/photos/src/components/Collections/AlbumSlideshow.tsx
new file mode 100644
index 0000000000..1dc28ba88a
--- /dev/null
+++ b/web/apps/photos/src/components/Collections/AlbumSlideshow.tsx
@@ -0,0 +1,613 @@
+import {
+ collectionDialogIconButtonSx,
+ collectionDialogSurfaceStroke,
+ collectionDialogSurfaceStrokeDark,
+ collectionDialogTitleSx,
+ collectionDialogToggleGroupSx,
+} from "@/components/CollectionDialog/styles";
+import CloseIcon from "@mui/icons-material/Close";
+import NavigateBeforeIcon from "@mui/icons-material/NavigateBefore";
+import NavigateNextIcon from "@mui/icons-material/NavigateNext";
+import PauseIcon from "@mui/icons-material/Pause";
+import PlayArrowIcon from "@mui/icons-material/PlayArrow";
+import SettingsIcon from "@mui/icons-material/Settings";
+import {
+ Box,
+ CircularProgress,
+ Dialog,
+ IconButton,
+ Stack,
+ ToggleButton,
+ ToggleButtonGroup,
+ Typography,
+ useMediaQuery,
+ type Theme,
+} from "@mui/material";
+import log from "ente-base/log";
+import { downloadManager } from "ente-gallery/services/download";
+import type { EnteFile } from "ente-media/file";
+import { fileFileName } from "ente-media/file-metadata";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type KeyboardEvent,
+ type MouseEvent,
+} from "react";
+import {
+ holdSlideshowWakeLock,
+ readSlideshowSettings,
+ saveSlideshowSettings,
+ scheduleSlideshowAdvance,
+ slideshowDurations,
+ slideshowIndex,
+ type SlideshowSettings,
+} from "./album-slideshow";
+
+interface AlbumSlideshowProps {
+ files: EnteFile[];
+ title: string;
+ onClose: () => void;
+}
+
+export function AlbumSlideshow({ files, title, onClose }: AlbumSlideshowProps) {
+ const [settings, setSettings] = useState(readSlideshowSettings);
+ const [slide, setSlide] = useState<{
+ index: number;
+ ready: boolean;
+ automatic: boolean;
+ previous?: EnteFile;
+ }>({ index: 0, ready: false, automatic: false });
+ const [playing, setPlaying] = useState(true);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const [visible, setVisible] = useState(() => !document.hidden);
+ const [controlsVisible, setControlsVisible] = useState(true);
+ const [keyboardFocus, setKeyboardFocus] = useState(false);
+ const controlsTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
+ const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
+ const { setIsFileViewerOpen } = usePhotosAppContext();
+ const current = files[slide.index]!;
+ const enabled = playing && visible && !settingsOpen;
+ const showControls =
+ controlsVisible || !playing || settingsOpen || keyboardFocus;
+ const fadeDuration = reducedMotion ? 0 : slide.automatic ? 600 : 200;
+
+ const navigate = useCallback(
+ (offset: number, automatic = false) => {
+ setSlide((previous) => {
+ const index = slideshowIndex(
+ previous.index,
+ offset,
+ files.length,
+ );
+ return index === previous.index
+ ? previous
+ : {
+ index,
+ ready: false,
+ automatic,
+ previous: files[previous.index],
+ };
+ });
+ },
+ [files],
+ );
+
+ const markReady = useCallback(
+ (id: number) => {
+ setSlide((previous) =>
+ files[previous.index]?.id === id && !previous.ready
+ ? { ...previous, ready: true }
+ : previous,
+ );
+ },
+ [files],
+ );
+
+ useEffect(
+ () =>
+ scheduleSlideshowAdvance(
+ {
+ enabled,
+ ready: slide.ready,
+ durationSeconds: settings.durationSeconds,
+ count: files.length,
+ },
+ () => navigate(1, true),
+ ),
+ [
+ enabled,
+ slide.ready,
+ settings.durationSeconds,
+ files.length,
+ current.id,
+ navigate,
+ ],
+ );
+
+ useEffect(() => {
+ if (!slide.previous) return;
+ const timer = setTimeout(
+ () =>
+ setSlide((previous) => ({ ...previous, previous: undefined })),
+ reducedMotion ? 0 : 750,
+ );
+ return () => clearTimeout(timer);
+ }, [current.id, slide.previous, reducedMotion]);
+
+ useEffect(() => {
+ const changed = () => setVisible(!document.hidden);
+ document.addEventListener("visibilitychange", changed);
+ return () => document.removeEventListener("visibilitychange", changed);
+ }, []);
+
+ useEffect(() => {
+ return enabled ? holdSlideshowWakeLock() : undefined;
+ }, [enabled]);
+
+ useEffect(() => {
+ setIsFileViewerOpen?.(true);
+ return () => setIsFileViewerOpen?.(false);
+ }, [setIsFileViewerOpen]);
+
+ useEffect(() => {
+ for (
+ let offset = 1;
+ offset <= Math.min(10, files.length - 1);
+ offset++
+ ) {
+ const file = files[(slide.index + offset) % files.length]!;
+ void downloadManager
+ .renderableThumbnailURL(file)
+ .catch(() => undefined);
+ if (offset <= 3)
+ void downloadManager
+ .renderableSourceURLs(file)
+ .then((source) =>
+ source.type === "livePhoto"
+ ? source.imageURL()
+ : undefined,
+ )
+ .catch(() => undefined);
+ }
+ }, [files, slide.index]);
+
+ const revealControls = useCallback(() => {
+ setControlsVisible(true);
+ clearTimeout(controlsTimer.current);
+ if (enabled && !keyboardFocus)
+ controlsTimer.current = setTimeout(
+ () => setControlsVisible(false),
+ 3000,
+ );
+ }, [enabled, keyboardFocus]);
+
+ useEffect(() => {
+ revealControls();
+ return () => clearTimeout(controlsTimer.current);
+ }, [revealControls]);
+
+ const updateSettings = (next: SlideshowSettings) => {
+ setSettings(next);
+ saveSlideshowSettings(next);
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (settingsOpen) return;
+ if (event.key === "Tab") {
+ setKeyboardFocus(true);
+ revealControls();
+ return;
+ }
+ if (
+ (event.target as HTMLElement).closest("button") &&
+ (event.key === " " || event.key === "Enter")
+ )
+ return;
+ switch (event.key) {
+ case "ArrowLeft":
+ navigate(-1);
+ break;
+ case "ArrowRight":
+ navigate(1);
+ break;
+ case " ":
+ if (files.length > 1) setPlaying((value) => !value);
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ revealControls();
+ };
+
+ const handlePhotoClick = (event: MouseEvent<HTMLElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const x = (event.clientX - bounds.left) / bounds.width;
+ if (files.length > 1 && x < 0.25) navigate(-1);
+ else if (files.length > 1 && x > 0.75) navigate(1);
+ else setControlsVisible((value) => !value);
+ };
+
+ return (
+ <Dialog
+ open
+ fullScreen
+ onClose={onClose}
+ aria-labelledby="album-slideshow-title"
+ onKeyDown={handleKeyDown}
+ slotProps={{
+ paper: {
+ sx: { bgcolor: "#000", color: "#fff", overflow: "hidden" },
+ },
+ }}
+ >
+ <Box
+ sx={{ position: "relative", height: "100%", outline: 0 }}
+ tabIndex={-1}
+ onMouseMove={revealControls}
+ onPointerDown={() => setKeyboardFocus(false)}
+ onFocus={(event) => {
+ if (event.target.matches("button:focus-visible"))
+ setKeyboardFocus(true);
+ }}
+ onBlur={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget))
+ setKeyboardFocus(false);
+ }}
+ >
+ {[slide.previous, current]
+ .filter((file): file is EnteFile => !!file)
+ .map((file) => (
+ <Slide
+ key={file.id}
+ file={file}
+ active={file.id === current.id}
+ fadeDuration={fadeDuration}
+ reducedMotion={reducedMotion}
+ onReady={markReady}
+ />
+ ))}
+ <Box
+ onClick={handlePhotoClick}
+ sx={{ position: "absolute", inset: 0 }}
+ />
+ <Box
+ inert={!showControls}
+ sx={{
+ position: "absolute",
+ inset: 0,
+ zIndex: 3,
+ pointerEvents: "none",
+ opacity: showControls ? 1 : 0,
+ transition: reducedMotion ? "none" : "opacity 200ms",
+ "& button": {
+ pointerEvents: showControls ? "auto" : "none",
+ color: "inherit",
+ },
+ }}
+ >
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ p: 2,
+ gap: 2,
+ background: "linear-gradient(#000b, transparent)",
+ position: "absolute",
+ inset: "0 0 auto",
+ }}
+ >
+ <IconButton aria-label={t("close")} onClick={onClose}>
+ <CloseIcon />
+ </IconButton>
+ <Typography
+ id="album-slideshow-title"
+ sx={{ flex: 1 }}
+ noWrap
+ >
+ {title}
+ </Typography>
+ <IconButton
+ aria-label={t("slideshow_settings")}
+ onClick={() => setSettingsOpen(true)}
+ >
+ <SettingsIcon />
+ </IconButton>
+ </Stack>
+ {files.length > 1 && (
+ <Stack
+ direction="row"
+ sx={{
+ position: "absolute",
+ top: "50%",
+ width: "100%",
+ transform: "translateY(-50%)",
+ alignItems: "center",
+ justifyContent: "space-between",
+ px: 2,
+ }}
+ >
+ <IconButton
+ aria-label={t("previous")}
+ onClick={() => navigate(-1)}
+ >
+ <NavigateBeforeIcon />
+ </IconButton>
+ <IconButton
+ aria-label={t(playing ? "pause" : "play")}
+ onClick={() => setPlaying((value) => !value)}
+ sx={{ bgcolor: "#0007", width: 56, height: 56 }}
+ >
+ {playing ? <PauseIcon /> : <PlayArrowIcon />}
+ </IconButton>
+ <IconButton
+ aria-label={t("next")}
+ onClick={() => navigate(1)}
+ >
+ <NavigateNextIcon />
+ </IconButton>
+ </Stack>
+ )}
+ </Box>
+ </Box>
+ <Dialog
+ open={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ aria-labelledby="slideshow-settings-title"
+ maxWidth={false}
+ slotProps={{ paper: { sx: settingsPaperSx } }}
+ >
+ <Stack sx={{ p: "20px", gap: "32px" }}>
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 2,
+ }}
+ >
+ <Typography
+ component="h2"
+ id="slideshow-settings-title"
+ sx={[
+ collectionDialogTitleSx,
+ {
+ fontFamily: "'Outfit Variable', sans-serif",
+ whiteSpace: "normal",
+ },
+ ]}
+ >
+ {t("slideshow_settings")}
+ </Typography>
+ <IconButton
+ aria-label={t("close")}
+ onClick={() => setSettingsOpen(false)}
+ sx={[
+ collectionDialogIconButtonSx,
+ { flexShrink: 0 },
+ ]}
+ >
+ <CloseIcon sx={{ fontSize: 18 }} />
+ </IconButton>
+ </Stack>
+ <Stack sx={{ gap: 3 }}>
+ <Stack sx={{ gap: 1 }}>
+ <Typography sx={settingsLabelSx}>
+ {t("slideshow_time_per_photo")}
+ </Typography>
+ <ToggleButtonGroup
+ exclusive
+ value={settings.durationSeconds}
+ aria-label={t("slideshow_time_per_photo")}
+ sx={[
+ collectionDialogToggleGroupSx,
+ {
+ flexWrap: "wrap",
+ "& .MuiToggleButtonGroup-grouped": {
+ flex: "1 0 auto",
+ minWidth: 52,
+ },
+ },
+ ]}
+ onChange={(
+ _,
+ durationSeconds: number | null,
+ ) => {
+ if (durationSeconds !== null)
+ updateSettings({
+ ...settings,
+ durationSeconds,
+ });
+ }}
+ >
+ {slideshowDurations.map((seconds) => (
+ <ToggleButton key={seconds} value={seconds}>
+ {t(
+ seconds < 60
+ ? "slideshow_seconds"
+ : "slideshow_minutes",
+ {
+ count:
+ seconds < 60
+ ? seconds
+ : seconds / 60,
+ },
+ )}
+ </ToggleButton>
+ ))}
+ </ToggleButtonGroup>
+ </Stack>
+ </Stack>
+ </Stack>
+ </Dialog>
+ </Dialog>
+ );
+}
+
+function Slide({
+ file,
+ active,
+ fadeDuration,
+ reducedMotion,
+ onReady,
+}: {
+ file: EnteFile;
+ active: boolean;
+ fadeDuration: number;
+ reducedMotion: boolean;
+ onReady: (id: number) => void;
+}) {
+ const [thumbnail, setThumbnail] = useState<string>();
+ const [original, setOriginal] = useState<string>();
+ const [loaded, setLoaded] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [thumbnailLoaded, setThumbnailLoaded] = useState(false);
+ useEffect(() => {
+ // A quick previous/next can reactivate an already-loaded fading slide.
+ if (active && (loaded || thumbnailLoaded)) onReady(file.id);
+ }, [active, loaded, thumbnailLoaded, onReady, file.id]);
+ useEffect(() => {
+ let cancelled = false;
+ void downloadManager
+ .renderableThumbnailURL(file)
+ .then((url) => {
+ if (!cancelled) setThumbnail(url);
+ })
+ .catch(() => undefined);
+ void downloadManager
+ .renderableSourceURLs(file)
+ .then(async (source) => {
+ const url =
+ source.type === "image"
+ ? source.imageURL
+ : source.type === "livePhoto"
+ ? await source.imageURL()
+ : undefined;
+ if (!cancelled) setOriginal(url);
+ })
+ .catch((error: unknown) => {
+ if (!cancelled) {
+ log.error("Failed to load slideshow photo", error);
+ setFailed(true);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [file]);
+ const fade = (duration: number) => ({
+ animation:
+ active && !reducedMotion
+ ? `slideshow-fade ${duration}ms ease-out`
+ : "none",
+ "@keyframes slideshow-fade": { from: { opacity: 0 } },
+ });
+ const imageStyle = {
+ position: "absolute",
+ inset: 0,
+ width: "100%",
+ height: "100%",
+ objectFit: "contain",
+ } as const;
+ return (
+ <>
+ <Box
+ aria-hidden
+ sx={{
+ position: "absolute",
+ inset: -100,
+ backgroundImage: `url("${thumbnail ?? original ?? ""}")`,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ filter: "blur(100px)",
+ opacity: 0.6,
+ ...fade(750),
+ }}
+ />
+ <Box
+ aria-hidden={!active}
+ sx={{
+ // Only backgrounds overlap; old photos show around differing aspect ratios.
+ display: active ? "block" : "none",
+ position: "absolute",
+ inset: 0,
+ zIndex: 1,
+ pointerEvents: "none",
+ ...fade(fadeDuration),
+ }}
+ >
+ {thumbnail && (
+ <Box
+ component="img"
+ src={thumbnail}
+ alt={loaded ? "" : fileFileName(file)}
+ sx={imageStyle}
+ onLoad={() => {
+ setThumbnailLoaded(true);
+ }}
+ />
+ )}
+ {original && (
+ <Box
+ component="img"
+ src={original}
+ alt={loaded ? fileFileName(file) : ""}
+ sx={{ ...imageStyle, opacity: loaded ? 1 : 0 }}
+ onLoad={() => {
+ setLoaded(true);
+ }}
+ onError={() => {
+ setOriginal(undefined);
+ setFailed(true);
+ }}
+ />
+ )}
+ {!loaded && !thumbnailLoaded && (
+ <Stack
+ sx={{
+ height: "100%",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ {failed ? (
+ <Typography>
+ {t("unpreviewable_file_message")}
+ </Typography>
+ ) : (
+ <CircularProgress color="inherit" />
+ )}
+ </Stack>
+ )}
+ </Box>
+ </>
+ );
+}
+
+const settingsLabelSx = {
+ fontSize: 14,
+ lineHeight: "20px",
+ fontWeight: 500,
+ color: "text.muted",
+};
+
+const settingsPaperSx = (theme: Theme) => ({
+ width: "min(500px, calc(100svw - 32px))",
+ maxWidth: "500px",
+ m: 2,
+ borderRadius: "20px",
+ border: `1px solid ${collectionDialogSurfaceStroke}`,
+ backgroundColor: "#f4f4f4",
+ backgroundImage: "none",
+ boxShadow: "none",
+ color: "text.base",
+ ...theme.applyStyles("dark", {
+ borderColor: collectionDialogSurfaceStrokeDark,
+ backgroundColor: "#1b1b1b",
+ }),
+});
diff --git a/web/apps/photos/src/components/Collections/AllAlbums.tsx b/web/apps/photos/src/components/Collections/AllAlbums.tsx
index 50af33191c..888d5613bc 100644
--- a/web/apps/photos/src/components/Collections/AllAlbums.tsx
+++ b/web/apps/photos/src/components/Collections/AllAlbums.tsx
@@ -9,6 +9,7 @@ import {
collectionDialogBodyMutedSx as bodyMutedSx,
collectionDialogFullScreenQuery,
collectionDialogDividerSx as dividerSx,
+ collectionDialogToggleGroupSx as filterPillsSx,
collectionDialogHeaderActionsSx as headerActionsSx,
collectionDialogHeaderRowSx as headerRowSx,
collectionDialogHeaderSx as headerSx,
@@ -549,46 +550,6 @@ const sweepButtonSx: SxProps<Theme> = (theme) => ({
...theme.applyStyles("dark", { borderColor: surfaceStrokeDark }),
});
-const filterPillsSx = (theme: Theme) => ({
- display: "flex",
- gap: "8px",
- "& .MuiToggleButtonGroup-grouped": {
- flex: "1 1 0",
- minWidth: 0,
- marginLeft: "0 !important",
- padding: "10px 12px",
- border: 0,
- borderRadius: "16px !important",
- color: "text.muted",
- backgroundColor: "background.paper",
- fontSize: "14px",
- lineHeight: "20px",
- fontWeight: 500,
- letterSpacing: "-0.011em",
- textTransform: "none",
- whiteSpace: "nowrap",
- overflow: "hidden",
- textOverflow: "ellipsis",
- transition: theme.transitions.create("background-color", {
- duration: 120,
- }),
- "&:hover": { backgroundColor: "fill.faintHover", color: "text.base" },
- "&:focus-visible": {
- outline: `1px solid ${theme.vars.palette.stroke.base}`,
- outlineOffset: 2,
- },
- ...theme.applyStyles("dark", {
- "&:not(.Mui-selected)": {
- backgroundColor: "rgba(255 255 255 / 0.12)",
- },
- }),
- "&.Mui-selected": {
- backgroundColor: "accent.main",
- color: "accent.contrastText",
- },
- "&.Mui-selected:hover": { backgroundColor: "accent.dark" },
- },
-});
const GridColumns = 3;
const GridGap = 8;
const GridPaddingInline = 20;
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index e3ea64dfca..c612b6290a 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -19,6 +19,7 @@ import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
import PublicIcon from "@mui/icons-material/Public";
import PushPinIcon from "@mui/icons-material/PushPin";
import PushPinOutlinedIcon from "@mui/icons-material/PushPinOutlined";
+import SlideshowIcon from "@mui/icons-material/Slideshow";
import SortIcon from "@mui/icons-material/Sort";
import TvIcon from "@mui/icons-material/Tv";
import UnarchiveIcon from "@mui/icons-material/Unarchive";
@@ -82,6 +83,7 @@ export interface CollectionHeaderProps {
onCollectionShare: () => void;
onCollectionManageLink: () => void;
onCollectionCast: () => void;
+ onCollectionSlideshow: () => void;
onEditAlbumDetails: () => void;
hasActiveFileSelection: boolean;
onAddSaveGroup: AddSaveGroup;
@@ -141,6 +143,7 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
onCollectionShare,
onCollectionManageLink,
onCollectionCast,
+ onCollectionSlideshow,
onEditAlbumDetails,
hasActiveFileSelection,
onAddSaveGroup,
@@ -663,6 +666,16 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
break;
}
+ if (activeCollection)
+ menuOptions.push(
+ <OverflowMenuOption
+ key="slideshow"
+ startIcon={<SlideshowIcon />}
+ onClick={onCollectionSlideshow}
+ >
+ {t("slideshow")}
+ </OverflowMenuOption>,
+ );
const validMenuOptions = menuOptions.filter((o) => !!o);
return (
diff --git a/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx b/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
index 2aad239233..2ce1c196e2 100644
--- a/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
+++ b/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
@@ -63,7 +63,11 @@ type GalleryBarAndListHeaderProps = Omit<
canCreateAlbum: boolean;
} & Pick<
CollectionHeaderProps,
- "onRemotePull" | "onAddSaveGroup" | "onEditAlbumDetails" | "onShowMap"
+ | "onRemotePull"
+ | "onAddSaveGroup"
+ | "onEditAlbumDetails"
+ | "onShowMap"
+ | "onCollectionSlideshow"
> &
Pick<
CollectionShareProps,
@@ -96,6 +100,7 @@ export const GalleryBarAndListHeader: React.FC<
onEditAlbumDetails,
onAddSaveGroup,
onShowMap,
+ onCollectionSlideshow,
setFileListHeader,
}) => {
const { show: showAllAlbums, props: allAlbumsVisibilityProps } =
@@ -184,6 +189,7 @@ export const GalleryBarAndListHeader: React.FC<
onRemotePull,
onAddSaveGroup,
onShowMap,
+ onCollectionSlideshow,
}}
collectionSummary={collectionSummary}
onCollectionShare={openCollectionShare}
@@ -227,6 +233,7 @@ export const GalleryBarAndListHeader: React.FC<
onRemotePull,
onAddSaveGroup,
onShowMap,
+ onCollectionSlideshow,
onEditAlbumDetails,
albumDescription,
descriptionHeight,
diff --git a/web/apps/photos/src/components/Collections/album-slideshow.ts b/web/apps/photos/src/components/Collections/album-slideshow.ts
new file mode 100644
index 0000000000..62a00b54ff
--- /dev/null
+++ b/web/apps/photos/src/components/Collections/album-slideshow.ts
@@ -0,0 +1,120 @@
+import { uniqueFilesByID } from "ente-gallery/utils/file";
+import type { EnteFile } from "ente-media/file";
+import { FileType } from "ente-media/file-type";
+
+export const slideshowDurations = [5, 10, 15, 30, 60, 300, 600];
+const settingsKey = "albumSlideshow";
+
+export interface SlideshowSettings {
+ durationSeconds: number;
+}
+
+const defaultSettings: SlideshowSettings = { durationSeconds: 5 };
+
+export function readSlideshowSettings(): SlideshowSettings {
+ try {
+ const value: unknown = JSON.parse(
+ localStorage.getItem(settingsKey) ?? "null",
+ );
+ if (!value || typeof value !== "object") return { ...defaultSettings };
+ const saved = value as Partial<SlideshowSettings>;
+ return {
+ durationSeconds: slideshowDurations.includes(saved.durationSeconds!)
+ ? saved.durationSeconds!
+ : defaultSettings.durationSeconds,
+ };
+ } catch {
+ return { ...defaultSettings };
+ }
+}
+
+export function saveSlideshowSettings(settings: SlideshowSettings) {
+ try {
+ localStorage.setItem(settingsKey, JSON.stringify(settings));
+ } catch {
+ // Playback still works when browser storage is unavailable.
+ }
+}
+
+export const slideshowFiles = (files: EnteFile[]) =>
+ uniqueFilesByID(
+ files.filter(
+ ({ metadata: { fileType } }) =>
+ fileType === FileType.image || fileType === FileType.livePhoto,
+ ),
+ );
+
+export const slideshowIndex = (index: number, offset: number, count: number) =>
+ count ? (index + offset + count) % count : 0;
+
+// ponytail: one cancellable timeout; the component owns readiness and visibility.
+export function scheduleSlideshowAdvance(
+ {
+ enabled,
+ ready,
+ durationSeconds,
+ count,
+ }: {
+ enabled: boolean;
+ ready: boolean;
+ durationSeconds: number;
+ count: number;
+ },
+ advance: () => void,
+) {
+ const timer =
+ enabled && count > 1
+ ? setTimeout(advance, ready ? durationSeconds * 1000 : 10_000)
+ : undefined;
+ return () => clearTimeout(timer);
+}
+
+export function holdSlideshowWakeLock() {
+ let cancelled = false;
+ let lock: WakeLockSentinel | undefined;
+ if ("wakeLock" in navigator)
+ void navigator.wakeLock
+ .request("screen")
+ .then((acquired) => {
+ if (cancelled) void acquired.release().catch(() => undefined);
+ else lock = acquired;
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ void lock?.release().catch(() => undefined);
+ };
+}
+
+// Called directly from the menu click so fullscreen retains user activation.
+export function requestSlideshowFullscreen(onExit: () => void) {
+ const element = document.documentElement;
+ if (
+ document.fullscreenElement ||
+ typeof element.requestFullscreen !== "function"
+ )
+ return () => undefined;
+ let cancelled = false;
+ let entered = false;
+ const changed = () => {
+ if (document.fullscreenElement === element) entered = true;
+ else if (entered) onExit();
+ };
+ const exit = () => {
+ if (document.fullscreenElement === element)
+ void document.exitFullscreen().catch(() => undefined);
+ };
+ document.addEventListener("fullscreenchange", changed);
+ void element
+ .requestFullscreen()
+ .then(() => {
+ if (cancelled) exit();
+ else entered = true;
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ document.removeEventListener("fullscreenchange", changed);
+ if (entered) exit();
+ };
+}
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index b6d1114000..5a9d48ce48 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -8,12 +8,17 @@ import {
CollectionSelector,
type CollectionSelectorAttributes,
} from "@/components/CollectionSelector";
+import { AlbumSlideshow } from "@/components/Collections/AlbumSlideshow";
import { CollectionMapDialog } from "@/components/Collections/CollectionMapDialog";
import {
EditAlbumDetailsDialog,
type AlbumDetails,
} from "@/components/Collections/EditAlbumDetailsDialog";
import { GalleryBarAndListHeader } from "@/components/Collections/GalleryBarAndListHeader";
+import {
+ requestSlideshowFullscreen,
+ slideshowFiles,
+} from "@/components/Collections/album-slideshow";
import { Export } from "@/components/Export";
import { FamilyManagement } from "@/components/FamilyManagement";
import type { FileListHeaderOrFooter } from "@/components/FileList";
@@ -206,6 +211,15 @@ const Page: React.FC = () => {
[],
);
const [isFileViewerOpen, setIsFileViewerOpen] = useState(false);
+ const [slideshow, setSlideshow] = useState<{
+ files: EnteFile[];
+ title: string;
+ collectionID: number;
+ restore: () => void;
+ }>();
+ const closeSlideshow = useCallback(() => setSlideshow(undefined), []);
+
+ useEffect(() => slideshow?.restore, [slideshow]);
const [pendingFileNavigation, setPendingFileNavigation] = useState<{
fileIndex: number;
@@ -446,6 +460,50 @@ const Page: React.FC = () => {
tempDeletedFileIDs,
tempHiddenFileIDs,
]);
+ const startSlideshow = useCallback(() => {
+ if (!activeCollection) return;
+ const files = slideshowFiles(activeCollectionFiles);
+ if (!files.length) {
+ showNotification({
+ color: "primary",
+ title: t("no_photos_found_here"),
+ });
+ return;
+ }
+ const trigger = document.querySelector<HTMLButtonElement>(
+ '[aria-controls="collection-options"]',
+ );
+ const restoreFullscreen = requestSlideshowFullscreen(closeSlideshow);
+ // ponytail: snapshot the album; live playlist updates are outside this feature.
+ setSlideshow({
+ files,
+ title: activeCollectionSummary?.name ?? activeCollection.name,
+ collectionID: activeCollection.id,
+ restore: () => {
+ restoreFullscreen();
+ requestAnimationFrame(() => {
+ if (trigger?.isConnected) trigger.focus();
+ });
+ },
+ });
+ }, [
+ activeCollection,
+ activeCollectionFiles,
+ activeCollectionSummary?.name,
+ closeSlideshow,
+ showNotification,
+ ]);
+
+ useEffect(() => {
+ if (
+ slideshow &&
+ (slideshow.collectionID !== activeCollection?.id ||
+ isInSearchMode ||
+ !user)
+ )
+ closeSlideshow();
+ }, [slideshow, activeCollection?.id, isInSearchMode, user, closeSlideshow]);
+
const mapFileSource = useMemo(
() => ({
collectionFiles: state.collectionFiles,
@@ -704,7 +762,8 @@ const Page: React.FC = () => {
authenticateUserVisibilityProps.open ||
albumNameInputVisibilityProps.open ||
editAlbumDetailsVisibilityProps.open ||
- isFileViewerOpen
+ isFileViewerOpen ||
+ slideshow
) {
return;
}
@@ -1810,7 +1869,7 @@ const Page: React.FC = () => {
message={
watchFolderView ? t("watch_folder_dropzone_hint") : undefined
}
- disabled={shouldDisableDropzone}
+ disabled={shouldDisableDropzone || !!slideshow}
onDrop={setDragAndDropFiles}
>
{blockingLoad && <TranslucentLoadingOverlay />}
@@ -1931,6 +1990,7 @@ const Page: React.FC = () => {
onAddSaveGroup,
onEditAlbumDetails: showEditAlbumDetails,
onShowMap: handleShowCollectionMap,
+ onCollectionSlideshow: startSlideshow,
}}
mode={barMode}
shouldHide={isInSearchMode}
@@ -2075,6 +2135,15 @@ const Page: React.FC = () => {
}
/>
)}
+ {slideshow &&
+ slideshow.collectionID === activeCollection?.id &&
+ !isInSearchMode && (
+ <AlbumSlideshow
+ files={slideshow.files}
+ title={slideshow.title}
+ onClose={closeSlideshow}
+ />
+ )}
{activeCollectionSummary && (
<CollectionMapDialog
{...collectionMapVisibilityProps}
diff --git a/web/apps/photos/tests/album-slideshow.test.ts b/web/apps/photos/tests/album-slideshow.test.ts
new file mode 100644
index 0000000000..29c2c06a32
--- /dev/null
+++ b/web/apps/photos/tests/album-slideshow.test.ts
@@ -0,0 +1,252 @@
+import type { EnteFile } from "ente-media/file";
+import { FileType } from "ente-media/file-type";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import {
+ holdSlideshowWakeLock,
+ readSlideshowSettings,
+ requestSlideshowFullscreen,
+ saveSlideshowSettings,
+ scheduleSlideshowAdvance,
+ slideshowDurations,
+ slideshowFiles,
+ slideshowIndex,
+} from "../src/components/Collections/album-slideshow";
+
+const photo = (id: number, fileType: FileType = FileType.image) =>
+ ({ id, metadata: { fileType } }) as EnteFile;
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+test("uses only unique images and Live Photo stills, preserving album order", () => {
+ const files = [
+ photo(3),
+ photo(2, FileType.video),
+ photo(1, FileType.livePhoto),
+ photo(3),
+ ];
+ expect(slideshowFiles(files)).toEqual([files[0], files[2]]);
+ expect(files).toHaveLength(4);
+ expect(slideshowFiles([])).toEqual([]);
+ expect(slideshowFiles([photo(2, FileType.video)])).toEqual([]);
+});
+
+test("navigation loops in both directions and handles empty and single-photo albums", () => {
+ expect(slideshowIndex(2, 1, 3)).toBe(0);
+ expect(slideshowIndex(0, -1, 3)).toBe(2);
+ expect(slideshowIndex(0, 1, 1)).toBe(0);
+ expect(slideshowIndex(0, -1, 0)).toBe(0);
+});
+
+describe("preferences", () => {
+ const defaults = { durationSeconds: 5 };
+ test.each([
+ null,
+ "broken JSON",
+ "null",
+ "[]",
+ "12",
+ '{"durationSeconds":-1,"shuffle":"true","blurred":0}',
+ ])("uses defaults for invalid or missing storage: %s", (saved) => {
+ vi.stubGlobal("localStorage", { getItem: () => saved });
+ expect(readSlideshowSettings()).toEqual(defaults);
+ });
+
+ test("round-trips every duration and ignores removed preferences", () => {
+ const entries = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => entries.get(key) ?? null,
+ setItem: (key: string, value: string) => entries.set(key, value),
+ });
+ for (const durationSeconds of slideshowDurations) {
+ const settings = { durationSeconds };
+ saveSlideshowSettings(settings);
+ expect(readSlideshowSettings()).toEqual(settings);
+ }
+ entries.set("albumSlideshow", '{"durationSeconds":7,"shuffle":true}');
+ expect(readSlideshowSettings()).toEqual(defaults);
+ entries.set(
+ "albumSlideshow",
+ '{"durationSeconds":30,"shuffle":true,"blurred":false}',
+ );
+ expect(readSlideshowSettings()).toEqual({ durationSeconds: 30 });
+ });
+
+ test("continues when storage access throws", () => {
+ const unavailable = () => {
+ throw new Error("Storage denied");
+ };
+ vi.stubGlobal("localStorage", {
+ getItem: unavailable,
+ setItem: unavailable,
+ });
+ expect(readSlideshowSettings()).toEqual(defaults);
+ expect(() => saveSlideshowSettings(defaults)).not.toThrow();
+ });
+});
+
+describe("playback timeout", () => {
+ const ready = { enabled: true, ready: true, durationSeconds: 5, count: 2 };
+ test.each(slideshowDurations)(
+ "advances once after %i seconds",
+ (durationSeconds) => {
+ vi.useFakeTimers();
+ const advance = vi.fn();
+ scheduleSlideshowAdvance({ ...ready, durationSeconds }, advance);
+ vi.advanceTimersByTime(durationSeconds * 1000 - 1);
+ expect(advance).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(advance).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(600_000);
+ expect(advance).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ test("skips undisplayable media after ten seconds, or replaces that timeout once ready", () => {
+ vi.useFakeTimers();
+ const advance = vi.fn();
+ const cancel = scheduleSlideshowAdvance(
+ { ...ready, ready: false },
+ advance,
+ );
+ vi.advanceTimersByTime(9999);
+ expect(advance).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(advance).toHaveBeenCalledTimes(1);
+ cancel();
+ advance.mockClear();
+ const cancelLoading = scheduleSlideshowAdvance(
+ { ...ready, ready: false },
+ advance,
+ );
+ vi.advanceTimersByTime(2000);
+ cancelLoading();
+ scheduleSlideshowAdvance({ ...ready, durationSeconds: 60 }, advance);
+ vi.advanceTimersByTime(59_999);
+ expect(advance).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(advance).toHaveBeenCalledTimes(1);
+ });
+
+ test("cancels on suspension, navigation, settings changes, and close", () => {
+ vi.useFakeTimers();
+ const advance = vi.fn();
+ const cancel = scheduleSlideshowAdvance(ready, advance);
+ vi.advanceTimersByTime(4000);
+ cancel();
+ scheduleSlideshowAdvance({ ...ready, enabled: false }, advance);
+ vi.advanceTimersByTime(600_000);
+ expect(advance).not.toHaveBeenCalled();
+ const cancelResumed = scheduleSlideshowAdvance(
+ { ...ready, durationSeconds: 10 },
+ advance,
+ );
+ vi.advanceTimersByTime(9999);
+ expect(advance).not.toHaveBeenCalled();
+ cancelResumed();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ test.each([0, 1])("does not schedule for %i photos", (count) => {
+ vi.useFakeTimers();
+ scheduleSlideshowAdvance({ ...ready, count }, vi.fn());
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
+
+describe("browser resources", () => {
+ test("releases a wake lock acquired after playback has stopped", async () => {
+ let resolve!: (lock: WakeLockSentinel) => void;
+ const request = vi.fn(
+ () =>
+ new Promise<WakeLockSentinel>((done) => {
+ resolve = done;
+ }),
+ );
+ vi.stubGlobal("navigator", { wakeLock: { request } });
+ const release = vi.fn().mockResolvedValue(undefined);
+ const cancel = holdSlideshowWakeLock();
+ cancel();
+ resolve({ release } as unknown as WakeLockSentinel);
+ await Promise.resolve();
+ expect(release).toHaveBeenCalledOnce();
+ });
+
+ test("releases and reacquires wake locks, tolerating rejection or missing support", async () => {
+ const release = vi.fn().mockResolvedValue(undefined);
+ const request = vi.fn().mockResolvedValue({ release });
+ vi.stubGlobal("navigator", { wakeLock: { request } });
+ const cancel = holdSlideshowWakeLock();
+ await Promise.resolve();
+ cancel();
+ expect(release).toHaveBeenCalledOnce();
+ const cancelAgain = holdSlideshowWakeLock();
+ await Promise.resolve();
+ expect(request).toHaveBeenCalledTimes(2);
+ cancelAgain();
+ request.mockRejectedValueOnce(new Error("Denied"));
+ holdSlideshowWakeLock()();
+ await Promise.resolve();
+ vi.stubGlobal("navigator", {});
+ expect(() => holdSlideshowWakeLock()()).not.toThrow();
+ });
+
+ function fullscreenDocument() {
+ const doc = Object.assign(new EventTarget(), {
+ fullscreenElement: null as object | null,
+ documentElement: {
+ requestFullscreen: vi.fn().mockResolvedValue(undefined),
+ },
+ exitFullscreen: vi.fn().mockResolvedValue(undefined),
+ });
+ vi.stubGlobal("document", doc);
+ return doc;
+ }
+
+ test("closes on fullscreen exit and removes its listener on cleanup", async () => {
+ const doc = fullscreenDocument();
+ const onExit = vi.fn();
+ const restore = requestSlideshowFullscreen(onExit);
+ expect(doc.documentElement.requestFullscreen).toHaveBeenCalledOnce();
+ await Promise.resolve();
+ doc.fullscreenElement = doc.documentElement;
+ doc.dispatchEvent(new Event("fullscreenchange"));
+ doc.fullscreenElement = null;
+ doc.dispatchEvent(new Event("fullscreenchange"));
+ expect(onExit).toHaveBeenCalledOnce();
+ restore();
+ doc.dispatchEvent(new Event("fullscreenchange"));
+ expect(onExit).toHaveBeenCalledOnce();
+ });
+
+ test("restores only fullscreen owned by this slideshow, including late entry", async () => {
+ const doc = fullscreenDocument();
+ doc.fullscreenElement = {};
+ requestSlideshowFullscreen(vi.fn())();
+ expect(doc.documentElement.requestFullscreen).not.toHaveBeenCalled();
+ expect(doc.exitFullscreen).not.toHaveBeenCalled();
+ doc.fullscreenElement = null;
+ const restore = requestSlideshowFullscreen(vi.fn());
+ restore();
+ doc.fullscreenElement = doc.documentElement;
+ await Promise.resolve();
+ expect(doc.exitFullscreen).toHaveBeenCalledOnce();
+ });
+
+ test("fullscreen rejection leaves playback available and is cleaned up", async () => {
+ const doc = fullscreenDocument();
+ doc.documentElement.requestFullscreen.mockRejectedValueOnce(
+ new Error("Denied"),
+ );
+ const onExit = vi.fn();
+ const restore = requestSlideshowFullscreen(onExit);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(onExit).not.toHaveBeenCalled();
+ restore();
+ expect(doc.exitFullscreen).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index c9f8649a1e..f6a9d17752 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -478,6 +478,11 @@
"description": "Description",
"file_type": "File type",
"settings": "Settings",
+ "slideshow": "Slideshow",
+ "slideshow_settings": "Slideshow settings",
+ "slideshow_time_per_photo": "Time per photo",
+ "slideshow_seconds": "{{count}} s",
+ "slideshow_minutes": "{{count}} min",
"magic": "Magic",
"photos_count_zero": "No memories",
"photos_count_one": "1 memory",