Skip to content

armgit / ente

Public Imported from GitHub
0

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

refactor(photos):limit-slideshow-to-basic-playback

Aswin Asokc73b854a37d5
diff --git a/web/apps/photos/src/components/CollectionDialog/styles.ts b/web/apps/photos/src/components/CollectionDialog/styles.ts
index 2e4607f6d7..837c88d24a 100644
--- a/web/apps/photos/src/components/CollectionDialog/styles.ts
+++ b/web/apps/photos/src/components/CollectionDialog/styles.ts
@@ -83,44 +83,3 @@ 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
index 1dc28ba88a..e72e9e4542 100644
--- a/web/apps/photos/src/components/Collections/AlbumSlideshow.tsx
+++ b/web/apps/photos/src/components/Collections/AlbumSlideshow.tsx
@@ -1,28 +1,17 @@
-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 { CenteredFill } from "ente-base/components/containers";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
import type { EnteFile } from "ente-media/file";
@@ -32,20 +21,11 @@ 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";
+import { scheduleSlideshowAdvance, slideshowIndex } from "./album-slideshow";
interface AlbumSlideshowProps {
files: EnteFile[];
@@ -54,29 +34,14 @@ interface AlbumSlideshowProps {
}
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 [slide, setSlide] = useState({ index: 0, ready: 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) => {
+ (offset: number) => {
setSlide((previous) => {
const index = slideshowIndex(
previous.index,
@@ -85,15 +50,10 @@ export function AlbumSlideshow({ files, title, onClose }: AlbumSlideshowProps) {
);
return index === previous.index
? previous
- : {
- index,
- ready: false,
- automatic,
- previous: files[previous.index],
- };
+ : { index, ready: false };
});
},
- [files],
+ [files.length],
);
const markReady = useCallback(
@@ -111,100 +71,30 @@ export function AlbumSlideshow({ files, title, onClose }: AlbumSlideshowProps) {
() =>
scheduleSlideshowAdvance(
{
- enabled,
+ enabled: playing && visible,
ready: slide.ready,
- durationSeconds: settings.durationSeconds,
count: files.length,
},
- () => navigate(1, true),
+ () => navigate(1),
),
- [
- enabled,
- slide.ready,
- settings.durationSeconds,
- files.length,
- current.id,
- navigate,
- ],
+ [playing, visible, slide.ready, 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")
+ event.key === " "
)
return;
switch (event.key) {
@@ -222,15 +112,13 @@ export function AlbumSlideshow({ files, title, onClose }: AlbumSlideshowProps) {
}
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);
+ if (x < 0.25) navigate(-1);
+ else if (x > 0.75) navigate(1);
};
return (
@@ -246,220 +134,77 @@ export function AlbumSlideshow({ files, title, onClose }: AlbumSlideshowProps) {
},
}}
>
+ <Slide key={current.id} file={current} onReady={markReady} />
<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);
+ onClick={handlePhotoClick}
+ sx={{ position: "absolute", inset: 0 }}
+ />
+ <Stack
+ direction="row"
+ sx={{
+ position: "relative",
+ alignItems: "center",
+ p: 2,
+ gap: 2,
+ background: "linear-gradient(#000b, transparent)",
}}
>
- {[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}
+ <IconButton
+ aria-label={t("close")}
+ onClick={onClose}
+ color="inherit"
+ >
+ <CloseIcon />
+ </IconButton>
+ <Typography id="album-slideshow-title" noWrap>
+ {title}
+ </Typography>
+ </Stack>
+ {files.length > 1 && (
+ <Stack
+ direction="row"
sx={{
position: "absolute",
- inset: 0,
- zIndex: 3,
+ top: "50%",
+ width: "100%",
+ transform: "translateY(-50%)",
+ alignItems: "center",
+ justifyContent: "space-between",
+ px: 2,
pointerEvents: "none",
- opacity: showControls ? 1 : 0,
- transition: reducedMotion ? "none" : "opacity 200ms",
- "& button": {
- pointerEvents: showControls ? "auto" : "none",
- color: "inherit",
- },
+ "& button": { pointerEvents: "auto", 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("previous")}
+ onClick={() => navigate(-1)}
>
- <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,
- }}
+ <NavigateBeforeIcon />
+ </IconButton>
+ <IconButton
+ aria-label={t(playing ? "pause" : "play")}
+ onClick={() => setPlaying((value) => !value)}
+ sx={{ bgcolor: "#0007", width: 56, height: 56 }}
>
- <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>
+ {playing ? <PauseIcon /> : <PlayArrowIcon />}
+ </IconButton>
+ <IconButton
+ aria-label={t("next")}
+ onClick={() => navigate(1)}
+ >
+ <NavigateNextIcon />
+ </IconButton>
</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>();
@@ -467,10 +212,7 @@ function Slide({
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
@@ -500,20 +242,7 @@ function Slide({
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
@@ -526,88 +255,55 @@ function Slide({
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>
+ {thumbnail && (
+ <Box
+ component="img"
+ src={thumbnail}
+ alt={loaded ? "" : fileFileName(file)}
+ sx={imageStyle}
+ onLoad={() => {
+ setThumbnailLoaded(true);
+ onReady(file.id);
+ }}
+ />
+ )}
+ {original && (
+ <Box
+ component="img"
+ src={original}
+ alt={loaded ? fileFileName(file) : ""}
+ sx={{ ...imageStyle, opacity: loaded ? 1 : 0 }}
+ onLoad={() => {
+ setLoaded(true);
+ onReady(file.id);
+ }}
+ onError={() => {
+ setOriginal(undefined);
+ setFailed(true);
+ }}
+ />
+ )}
+ {!loaded && !thumbnailLoaded && (
+ <CenteredFill sx={{ position: "absolute", inset: 0 }}>
+ {failed ? (
+ <Typography>
+ {t("unpreviewable_file_message")}
+ </Typography>
+ ) : (
+ <CircularProgress color="inherit" />
+ )}
+ </CenteredFill>
+ )}
</>
);
}
-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",
- }),
-});
+const imageStyle = {
+ position: "absolute",
+ inset: 0,
+ width: "100%",
+ height: "100%",
+ objectFit: "contain",
+} as const;
diff --git a/web/apps/photos/src/components/Collections/AllAlbums.tsx b/web/apps/photos/src/components/Collections/AllAlbums.tsx
index 888d5613bc..50af33191c 100644
--- a/web/apps/photos/src/components/Collections/AllAlbums.tsx
+++ b/web/apps/photos/src/components/Collections/AllAlbums.tsx
@@ -9,7 +9,6 @@ import {
collectionDialogBodyMutedSx as bodyMutedSx,
collectionDialogFullScreenQuery,
collectionDialogDividerSx as dividerSx,
- collectionDialogToggleGroupSx as filterPillsSx,
collectionDialogHeaderActionsSx as headerActionsSx,
collectionDialogHeaderRowSx as headerRowSx,
collectionDialogHeaderSx as headerSx,
@@ -550,6 +549,46 @@ 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/album-slideshow.ts b/web/apps/photos/src/components/Collections/album-slideshow.ts
index 62a00b54ff..41b316dff4 100644
--- a/web/apps/photos/src/components/Collections/album-slideshow.ts
+++ b/web/apps/photos/src/components/Collections/album-slideshow.ts
@@ -2,40 +2,6 @@ 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(
@@ -47,74 +13,18 @@ export const slideshowFiles = (files: EnteFile[]) =>
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.
+// ponytail: fixed five-second playback; skip photos that cannot load in ten seconds.
export function scheduleSlideshowAdvance(
{
enabled,
ready,
- durationSeconds,
count,
- }: {
- enabled: boolean;
- ready: boolean;
- durationSeconds: number;
- count: number;
- },
+ }: { enabled: boolean; ready: boolean; count: number },
advance: () => void,
) {
const timer =
enabled && count > 1
- ? setTimeout(advance, ready ? durationSeconds * 1000 : 10_000)
+ ? setTimeout(advance, ready ? 5000 : 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 5a9d48ce48..d3cf81a37d 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -15,10 +15,7 @@ import {
type AlbumDetails,
} from "@/components/Collections/EditAlbumDetailsDialog";
import { GalleryBarAndListHeader } from "@/components/Collections/GalleryBarAndListHeader";
-import {
- requestSlideshowFullscreen,
- slideshowFiles,
-} from "@/components/Collections/album-slideshow";
+import { slideshowFiles } from "@/components/Collections/album-slideshow";
import { Export } from "@/components/Export";
import { FamilyManagement } from "@/components/FamilyManagement";
import type { FileListHeaderOrFooter } from "@/components/FileList";
@@ -473,14 +470,12 @@ const Page: React.FC = () => {
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();
});
@@ -490,7 +485,6 @@ const Page: React.FC = () => {
activeCollection,
activeCollectionFiles,
activeCollectionSummary?.name,
- closeSlideshow,
showNotification,
]);
diff --git a/web/apps/photos/tests/album-slideshow.test.ts b/web/apps/photos/tests/album-slideshow.test.ts
index 29c2c06a32..ed8900442c 100644
--- a/web/apps/photos/tests/album-slideshow.test.ts
+++ b/web/apps/photos/tests/album-slideshow.test.ts
@@ -2,12 +2,7 @@ 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";
@@ -17,8 +12,6 @@ const photo = (id: number, fileType: FileType = FileType.image) =>
afterEach(() => {
vi.useRealTimers();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
});
test("uses only unique images and Live Photo stills, preserving album order", () => {
@@ -41,69 +34,19 @@ test("navigation loops in both directions and handles empty and single-photo alb
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);
- },
- );
+ const ready = { enabled: true, ready: true, count: 2 };
+ test("advances once after five seconds", () => {
+ vi.useFakeTimers();
+ const advance = vi.fn();
+ scheduleSlideshowAdvance(ready, advance);
+ vi.advanceTimersByTime(4999);
+ expect(advance).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(advance).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(60_000);
+ expect(advance).toHaveBeenCalledTimes(1);
+ });
test("skips undisplayable media after ten seconds, or replaces that timeout once ready", () => {
vi.useFakeTimers();
@@ -124,14 +67,14 @@ describe("playback timeout", () => {
);
vi.advanceTimersByTime(2000);
cancelLoading();
- scheduleSlideshowAdvance({ ...ready, durationSeconds: 60 }, advance);
- vi.advanceTimersByTime(59_999);
+ scheduleSlideshowAdvance(ready, advance);
+ vi.advanceTimersByTime(4999);
expect(advance).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(advance).toHaveBeenCalledTimes(1);
});
- test("cancels on suspension, navigation, settings changes, and close", () => {
+ test("cancels on pause, hidden document, navigation, and close", () => {
vi.useFakeTimers();
const advance = vi.fn();
const cancel = scheduleSlideshowAdvance(ready, advance);
@@ -140,11 +83,8 @@ describe("playback timeout", () => {
scheduleSlideshowAdvance({ ...ready, enabled: false }, advance);
vi.advanceTimersByTime(600_000);
expect(advance).not.toHaveBeenCalled();
- const cancelResumed = scheduleSlideshowAdvance(
- { ...ready, durationSeconds: 10 },
- advance,
- );
- vi.advanceTimersByTime(9999);
+ const cancelResumed = scheduleSlideshowAdvance(ready, advance);
+ vi.advanceTimersByTime(4999);
expect(advance).not.toHaveBeenCalled();
cancelResumed();
expect(vi.getTimerCount()).toBe(0);
@@ -156,97 +96,3 @@ describe("playback timeout", () => {
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 f6a9d17752..b99211fde4 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -479,10 +479,6 @@
"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",