Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

[space][web] Autoplay feed videos and refine post controls

Anand Baburajaned91c96a4b05
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsx
index d56c62f0a8..6349f969cd 100644
--- a/web/apps/space/src/components/FileViewer.tsx
+++ b/web/apps/space/src/components/FileViewer.tsx
@@ -1,4 +1,5 @@
import {
+ Add01Icon,
ArrowLeft02Icon,
ArrowRight02Icon,
Cancel01Icon,
@@ -146,6 +147,7 @@ interface SpaceFileViewerProps {
draftPostPreparationError?: string;
isDraftPostPreviewPending?: boolean;
onClose: () => void;
+ onAddDraftPhoto?: () => void;
onEditDraftPhoto?: () => void;
onDeletePost?: () => Promise<void> | void;
onDraftPostExitAnimationStart?: () => void;
@@ -236,6 +238,29 @@ const viewerHeaderButtonSx = {
"&:focus-visible": { outline: `2px solid ${green}`, outlineOffset: 2 },
};
+const draftHeaderButtonSx = {
+ ...viewerHeaderButtonSx,
+ borderRadius: "999px",
+ fontFamily: "inherit",
+ fontSize: 12,
+ fontWeight: 600,
+ left: 0,
+ minWidth: spaceTouchTargetSize,
+ mx: 0,
+ width: "auto",
+ "&:disabled": { opacity: 0.3, cursor: "default" },
+};
+
+const draftHeaderButtonContentSx = {
+ alignItems: "center",
+ bgcolor: "#242424",
+ borderRadius: "999px",
+ display: "flex",
+ gap: "6px",
+ height: 32,
+ px: "10px",
+};
+
const resizeCaptionInput = (
input: HTMLTextAreaElement | null,
minHeight = captionInputMinHeight,
@@ -374,6 +399,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
focusReplyOnOpen = false,
isDraftPostPreviewPending = false,
onClose,
+ onAddDraftPhoto,
onEditDraftPhoto,
onDeletePost,
onDraftPostExitAnimationStart,
@@ -1402,7 +1428,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
gridTemplateColumns: "minmax(0, 1fr) auto",
minHeight: viewerHeaderHeight,
position: "relative",
- px: "16px",
+ pl: "16px",
+ pr: isDraftPost ? "8px" : "16px",
width: "100%",
zIndex: 2,
}}
@@ -1581,6 +1608,29 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
/>
</Box>
)}
+ {isDraftPost && onAddDraftPhoto && (
+ <Box
+ component="button"
+ type="button"
+ aria-label="Add photos or videos"
+ title="Add photos or videos"
+ disabled={isDraftPostActionRunning}
+ onClick={onAddDraftPhoto}
+ sx={draftHeaderButtonSx}
+ >
+ <Box
+ component="span"
+ sx={draftHeaderButtonContentSx}
+ >
+ <HugeiconsIcon
+ icon={Add01Icon}
+ size={20}
+ strokeWidth={1.8}
+ />
+ Add
+ </Box>
+ </Box>
+ )}
{isDraftPost && onEditDraftPhoto && (
<Box
component="button"
@@ -1598,26 +1648,27 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
);
onEditDraftPhoto();
}}
- sx={{
- ...viewerHeaderButtonSx,
- mr: postPhotoCount > 1 ? "8px" : 0,
- "&:disabled": {
- opacity: 0.3,
- cursor: "default",
- },
- }}
+ sx={draftHeaderButtonSx}
>
- <HugeiconsIcon
- icon={Edit03Icon}
- size={16}
- strokeWidth={1.8}
- />
+ <Box
+ component="span"
+ sx={draftHeaderButtonContentSx}
+ >
+ <HugeiconsIcon
+ icon={Edit03Icon}
+ size={16}
+ strokeWidth={1.8}
+ />
+ Edit
+ </Box>
</Box>
)}
- <SpacePostPhotosCounter
- index={postPhotoIndex}
- count={postPhotoCount}
- />
+ {!isDraftPost && (
+ <SpacePostPhotosCounter
+ index={postPhotoIndex}
+ count={postPhotoCount}
+ />
+ )}
<Box
component="button"
type="button"
@@ -1628,13 +1679,35 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({
}
disabled={isDraftPostActionRunning}
onClick={closeViewer}
- sx={viewerHeaderButtonSx}
+ sx={
+ isDraftPost
+ ? draftHeaderButtonSx
+ : viewerHeaderButtonSx
+ }
>
- <HugeiconsIcon
- icon={Cancel01Icon}
- size={20}
- strokeWidth={1.8}
- />
+ {isDraftPost ? (
+ <Box
+ component="span"
+ sx={{
+ ...draftHeaderButtonContentSx,
+ width: 32,
+ p: 0,
+ justifyContent: "center",
+ }}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={20}
+ strokeWidth={1.8}
+ />
+ </Box>
+ ) : (
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={20}
+ strokeWidth={1.8}
+ />
+ )}
</Box>
</Box>
{canManagePost && (
diff --git a/web/apps/space/src/components/InlinePostVideo.tsx b/web/apps/space/src/components/InlinePostVideo.tsx
index 56c14a4af5..2ed3fd83bf 100644
--- a/web/apps/space/src/components/InlinePostVideo.tsx
+++ b/web/apps/space/src/components/InlinePostVideo.tsx
@@ -1,56 +1,59 @@
import { Box } from "@mui/material";
import { createSpaceVideoContent } from "components/PostVideoContent";
+import { registerFeedVideo } from "components/feed-video-playback";
import React, { useEffect, useRef } from "react";
import type { SpacePostAssetURLLoader, SpacePostVideo } from "services/space";
-let playingVideo: ReturnType<typeof createSpaceVideoContent> | undefined;
-
export const SpaceInlinePostVideo: React.FC<{
imageUrl: string;
video: SpacePostVideo;
isActive: boolean;
+ muted: boolean;
onLoadVideo?: SpacePostAssetURLLoader;
-}> = ({ imageUrl, video, isActive, onLoadVideo }) => {
+}> = ({ imageUrl, video, isActive, muted, onLoadVideo }) => {
const root = useRef<HTMLDivElement>(null);
const player = useRef<
ReturnType<typeof createSpaceVideoContent> | undefined
>(undefined);
+ const playback = useRef<ReturnType<typeof registerFeedVideo>>(undefined);
useEffect(() => {
const container = root.current!;
const content = createSpaceVideoContent(
{ imageUrl, video },
onLoadVideo,
- { inline: true },
+ {
+ inline: true,
+ onTogglePlayback: (play) => {
+ if (play) registration.play();
+ else registration.pause();
+ },
+ },
);
+ const registration = registerFeedVideo(container, content);
+ playback.current = registration;
player.current = content;
container.append(content.element);
- const onPlay = () => {
- if (playingVideo != content) playingVideo?.pause();
- playingVideo = content;
- };
- content.video.addEventListener("play", onPlay);
- const observer = new IntersectionObserver(([entry]) => {
- if (!entry!.isIntersecting) content.deactivate();
- });
- observer.observe(container);
return () => {
- observer.disconnect();
- content.video.removeEventListener("play", onPlay);
+ registration.unregister();
content.destroy();
content.element.remove();
- if (playingVideo == content) playingVideo = undefined;
player.current = undefined;
+ playback.current = undefined;
};
}, [imageUrl, onLoadVideo, video]);
useEffect(() => {
const content = player.current!;
- if (!isActive) content.deactivate();
content.video.tabIndex = isActive ? 0 : -1;
content.element.querySelector("button")!.tabIndex = isActive ? 0 : -1;
+ playback.current!.setActive(isActive);
}, [imageUrl, isActive, onLoadVideo, video]);
+ useEffect(() => {
+ player.current!.video.muted = muted;
+ }, [imageUrl, muted, onLoadVideo, video]);
+
return (
<Box ref={root} sx={{ position: "absolute", inset: 0, zIndex: 1 }} />
);
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsx
index 60c5c949f4..325ec3091f 100644
--- a/web/apps/space/src/components/PostComposer.tsx
+++ b/web/apps/space/src/components/PostComposer.tsx
@@ -318,8 +318,7 @@ export const SpacePostComposer: React.FC<{
})),
[drafts],
);
- const showPhotoStrip = files.length > 1;
- const controls = showPhotoStrip && (
+ const controls = drafts.length > 1 && (
<SpacePostPhotoStrip
activeIndex={activeIndex}
disabled={isPublishing}
@@ -353,6 +352,11 @@ export const SpacePostComposer: React.FC<{
onClose={() => {
if (!isPublishing || isExiting) onClose();
}}
+ onAddDraftPhoto={
+ drafts.length == 1
+ ? () => inputRef.current?.click()
+ : undefined
+ }
onEditDraftPhoto={() => {
if (!isPublishing)
setEditorSnapshot({ drafts, activeIndex });
@@ -380,7 +384,6 @@ export const SpacePostComposer: React.FC<{
{editorSnapshot && (
<SpacePostPhotoEditor
initialIndex={activeIndex}
- showPhotoStrip={showPhotoStrip}
onAdd={addPhotos}
onClose={cancelEdits}
onDone={applyEdits}
diff --git a/web/apps/space/src/components/PostPhotoEditor.tsx b/web/apps/space/src/components/PostPhotoEditor.tsx
index 09f56309f9..16990fbbb1 100644
--- a/web/apps/space/src/components/PostPhotoEditor.tsx
+++ b/web/apps/space/src/components/PostPhotoEditor.tsx
@@ -74,7 +74,6 @@ const buttonSx = {
export const SpacePostPhotoEditor: React.FC<{
photos: SpaceEditablePostPhoto[];
initialIndex: number;
- showPhotoStrip: boolean;
onAdd: (files: File[]) => void;
onClose: () => void;
onDone: (
@@ -82,14 +81,7 @@ export const SpacePostPhotoEditor: React.FC<{
activeIndex: number,
photoIDs: number[],
) => void;
-}> = ({
- photos: initialPhotos,
- initialIndex,
- showPhotoStrip,
- onAdd,
- onClose,
- onDone,
-}) => {
+}> = ({ photos: initialPhotos, initialIndex, onAdd, onClose, onDone }) => {
const [photos, setPhotos] = React.useState(initialPhotos);
const [activeID, setActiveID] = React.useState(
initialPhotos[initialIndex]!.id,
@@ -112,6 +104,7 @@ export const SpacePostPhotoEditor: React.FC<{
(photo) => photo.preparationError,
)?.preparationError;
const isPreparing = photos.some((photo) => photo.isLoading);
+ const showPhotoStrip = photos.length > 1;
const aspectIndex = aspects.findIndex(({ value }) => value == edit.aspect);
const size = rotatedImageSize(photo, edit.rotationDegrees);
const crop = edit.cropArea ?? fullImageCrop(size);
@@ -252,58 +245,44 @@ export const SpacePostPhotoEditor: React.FC<{
<Box
component="button"
type="button"
- aria-label="Cancel edits"
- onClick={onClose}
- sx={{
- ...buttonSx,
- justifySelf: "start",
- width: 44,
- ml: "-16px",
- p: 0,
- }}
+ disabled={
+ isSaving || isPreparing || Boolean(preparationError)
+ }
+ aria-busy={isSaving}
+ onClick={() => void save()}
+ sx={{ ...buttonSx, justifySelf: "start", p: 0 }}
>
- <HugeiconsIcon
- icon={Cancel01Icon}
- size={20}
- strokeWidth={1.8}
- />
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor: "#FFFFFF",
+ borderRadius: "999px",
+ color: "#171717",
+ display: "inline-flex",
+ height: 32,
+ px: "16px",
+ }}
+ >
+ {isSaving ? "Saving…" : "Done"}
+ </Box>
</Box>
<Box
id="space-photo-editor-title"
- sx={{
- alignItems: "center",
- display: "flex",
- gap: "8px",
- fontSize: 14,
- fontWeight: 600,
- }}
+ sx={{ fontSize: 14, fontWeight: 600 }}
>
Edit
- {photos.length > 1 && (
- <Box
- component="span"
- sx={{
- color: "#A6A6A6",
- fontSize: 12,
- fontWeight: 500,
- }}
- >
- {activeIndex + 1} / {photos.length}
- </Box>
- )}
</Box>
<Box
component="button"
type="button"
- disabled={
- isSaving || isPreparing || Boolean(preparationError)
- }
- aria-busy={isSaving}
- onClick={() => void save()}
+ aria-label="Cancel edits"
+ onClick={onClose}
sx={{
...buttonSx,
justifySelf: "end",
- borderRadius: "999px",
+ width: 44,
+ mr: "-8px",
p: 0,
}}
>
@@ -311,15 +290,20 @@ export const SpacePostPhotoEditor: React.FC<{
component="span"
sx={{
alignItems: "center",
- bgcolor: "#FFFFFF",
- borderRadius: "999px",
- color: "#171717",
- display: "inline-flex",
+ bgcolor: "#242424",
+ borderRadius: "50%",
+ color: "#E4E4E4",
+ display: "flex",
height: 32,
- px: "16px",
+ justifyContent: "center",
+ width: 32,
}}
>
- {isSaving ? "Saving…" : "Done"}
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={20}
+ strokeWidth={1.8}
+ />
</Box>
</Box>
</Box>
diff --git a/web/apps/space/src/components/PostPhotosDots.tsx b/web/apps/space/src/components/PostPhotosDots.tsx
index 34a8fa8815..e978e4365d 100644
--- a/web/apps/space/src/components/PostPhotosDots.tsx
+++ b/web/apps/space/src/components/PostPhotosDots.tsx
@@ -3,9 +3,11 @@ import { Box } from "@mui/material";
export const SpacePostPhotosDots = ({
index,
count,
+ activeColor = "#08C225",
}: {
index: number;
count: number;
+ activeColor?: string;
}) =>
count > 1 ? (
<Box
@@ -25,14 +27,11 @@ export const SpacePostPhotosDots = ({
key={photoIndex}
component="span"
sx={{
- bgcolor:
- photoIndex == index
- ? "#FFFFFF"
- : "rgba(255, 255, 255, 0.4)",
+ bgcolor: photoIndex == index ? activeColor : "#FFFFFF",
borderRadius: "50%",
boxShadow: "0 1px 2px rgba(0, 0, 0, 0.4)",
- height: 5,
- width: 5,
+ height: photoIndex == index ? 6 : 5,
+ width: photoIndex == index ? 6 : 5,
}}
/>
))}
diff --git a/web/apps/space/src/components/PostVideoContent.ts b/web/apps/space/src/components/PostVideoContent.ts
index b3604ae319..dbc5c8c268 100644
--- a/web/apps/space/src/components/PostVideoContent.ts
+++ b/web/apps/space/src/components/PostVideoContent.ts
@@ -4,7 +4,10 @@ import type { SpacePostAssetURLLoader } from "services/space";
export const createSpaceVideoContent = (
item: Pick<SpaceViewerPhoto, "imageUrl" | "video">,
load?: SpacePostAssetURLLoader,
- { inline = false }: { inline?: boolean } = {},
+ {
+ inline = false,
+ onTogglePlayback,
+ }: { inline?: boolean; onTogglePlayback?: (play: boolean) => void } = {},
) => {
const media = item.video!;
const element = document.createElement("div");
@@ -20,7 +23,8 @@ export const createSpaceVideoContent = (
video.playsInline = true;
video.preload = "none";
video.poster = item.imageUrl;
- video.muted = media.muted ?? false;
+ video.muted = inline || (media.muted ?? false);
+ video.loop = inline;
video.tabIndex = 0;
video.setAttribute("role", "button");
video.setAttribute("aria-label", "Play video");
@@ -146,15 +150,15 @@ export const createSpaceVideoContent = (
video.currentTime = media.start ?? 0;
}
await video.play();
- if (generation != current) video.pause();
- else showPlaying();
+ if (generation == current) showPlaying();
})().catch(() => {
if (!disposed && generation == current) showPlayButton();
});
};
const togglePlayback = () => {
if (button.disabled) return;
- if (video.paused) play();
+ if (onTogglePlayback) onTogglePlayback(video.paused);
+ else if (video.paused) play();
else pause();
};
button.onclick = togglePlayback;
@@ -188,7 +192,8 @@ export const createSpaceVideoContent = (
video.onerror = pause;
video.ontimeupdate = () => {
if (media.end != undefined && video.currentTime >= media.end) {
- reset();
+ if (inline) video.currentTime = media.start ?? 0;
+ else reset();
}
};
element.addEventListener("pointerdown", (event) => {
diff --git a/web/apps/space/src/components/feed-video-playback.ts b/web/apps/space/src/components/feed-video-playback.ts
new file mode 100644
index 0000000000..4081270b25
--- /dev/null
+++ b/web/apps/space/src/components/feed-video-playback.ts
@@ -0,0 +1,161 @@
+import type { createSpaceVideoContent } from "components/PostVideoContent";
+
+interface FeedVideo {
+ element: HTMLElement;
+ player: Pick<
+ ReturnType<typeof createSpaceVideoContent>,
+ "play" | "pause" | "deactivate"
+ >;
+ active: boolean;
+ manuallyPaused: boolean;
+}
+
+const posts = new Map<HTMLElement, boolean>();
+const videos = new Map<Element, FeedVideo>();
+let selected: FeedVideo | undefined;
+let manual: FeedVideo | undefined;
+let observer: IntersectionObserver | undefined;
+let frame: number | undefined;
+let scrollTimer: ReturnType<typeof setTimeout> | undefined;
+
+const select = (next: FeedVideo | undefined) => {
+ if (selected == next) return;
+ selected?.player.deactivate();
+ selected = next;
+ if (next && !next.manuallyPaused) next.player.play();
+};
+
+const isVisible = (element: HTMLElement) => {
+ const rect = element.getBoundingClientRect();
+ return rect.bottom > 0 && rect.top < window.innerHeight;
+};
+
+const update = () => {
+ for (const video of videos.values()) {
+ if (!isVisible(video.element)) {
+ video.manuallyPaused = false;
+ if (manual == video) manual = undefined;
+ }
+ }
+ if (manual && !manual.active) manual = undefined;
+ if (document.hidden) {
+ select(undefined);
+ return;
+ }
+ let focusedPost: HTMLElement | undefined;
+ let firstTop = Infinity;
+ for (const [element, visible] of posts) {
+ if (!visible) continue;
+ const rect = element.getBoundingClientRect();
+ const visibleHeight =
+ Math.min(rect.bottom, window.innerHeight) - Math.max(rect.top, 0);
+ if (
+ visibleHeight > 0 &&
+ visibleHeight >= Math.min(rect.height, window.innerHeight) / 2 &&
+ rect.top < firstTop
+ ) {
+ focusedPost = element;
+ firstTop = rect.top;
+ }
+ }
+ const next =
+ manual ??
+ [...videos.values()].find(
+ (video) => video.active && focusedPost?.contains(video.element),
+ );
+ select(scrollTimer != undefined && next != selected ? undefined : next);
+};
+
+const scheduleUpdate = () => {
+ frame ??= requestAnimationFrame(() => {
+ frame = undefined;
+ update();
+ });
+};
+
+const handleScroll = () => {
+ clearTimeout(scrollTimer);
+ scrollTimer = setTimeout(() => {
+ scrollTimer = undefined;
+ update();
+ }, 150);
+ scheduleUpdate();
+};
+
+export const registerFeedPost = (element: HTMLElement) => {
+ if (!observer) {
+ observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ const element = entry.target as HTMLElement;
+ if (posts.has(element))
+ posts.set(element, entry.isIntersecting);
+ }
+ scheduleUpdate();
+ },
+ { threshold: [0, 0.5, 1] },
+ );
+ window.addEventListener("scroll", handleScroll, { passive: true });
+ window.addEventListener("resize", scheduleUpdate);
+ document.addEventListener("visibilitychange", update);
+ }
+ posts.set(element, false);
+ observer.observe(element);
+ return () => {
+ posts.delete(element);
+ observer!.unobserve(element);
+ if (manual && element.contains(manual.element)) manual = undefined;
+ if (selected && element.contains(selected.element)) select(undefined);
+ if (posts.size) {
+ scheduleUpdate();
+ } else {
+ observer!.disconnect();
+ observer = undefined;
+ if (frame != undefined) cancelAnimationFrame(frame);
+ frame = undefined;
+ clearTimeout(scrollTimer);
+ scrollTimer = undefined;
+ window.removeEventListener("scroll", handleScroll);
+ window.removeEventListener("resize", scheduleUpdate);
+ document.removeEventListener("visibilitychange", update);
+ }
+ };
+};
+
+export const registerFeedVideo = (
+ element: HTMLElement,
+ player: FeedVideo["player"],
+) => {
+ const video: FeedVideo = {
+ element,
+ player,
+ active: false,
+ manuallyPaused: false,
+ };
+ videos.set(element, video);
+ return {
+ setActive: (active: boolean) => {
+ video.active = active;
+ if (!active && selected == video) select(undefined);
+ scheduleUpdate();
+ },
+ play: () => {
+ if (!video.active || document.hidden || !isVisible(element)) return;
+ video.manuallyPaused = false;
+ manual = video;
+ const wasSelected = selected == video;
+ select(video);
+ if (wasSelected) player.play();
+ },
+ pause: () => {
+ video.manuallyPaused = true;
+ player.pause();
+ },
+ unregister: () => {
+ videos.delete(element);
+ if (manual == video) manual = undefined;
+ if (selected == video) select(undefined);
+ if (posts.size) scheduleUpdate();
+ },
+ };
+};
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index f0e879916e..51a64c3020 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -2,6 +2,8 @@ import {
FavouriteIcon,
MultiplicationSignIcon,
UserAdd02Icon,
+ VolumeHighIcon,
+ VolumeOffIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Box, Skeleton } from "@mui/material";
@@ -9,6 +11,7 @@ import { visuallyHidden } from "@mui/utils";
import { SpaceActionToast } from "components/ActionToast";
import { SpaceAvatarImage } from "components/AvatarImage";
import { SpaceCaptionText } from "components/CaptionText";
+import { registerFeedPost } from "components/feed-video-playback";
import { SpaceFeedPostButton } from "components/FeedPostButton";
import {
SpaceFileViewer,
@@ -645,7 +648,11 @@ const FeedPhotoOverlay: React.FC<{
zIndex: 2,
}}
>
- <SpacePostPhotosDots index={photoIndex} count={photoCount} />
+ <SpacePostPhotosDots
+ index={photoIndex}
+ count={photoCount}
+ activeColor={green}
+ />
{caption && (
<Box title={caption} sx={{ minWidth: 0, width: "100%" }}>
<SpaceCaptionText caption={caption} lineClamp={2} />
@@ -660,6 +667,7 @@ const FeedPhoto: React.FC<{
imageUrl?: string;
isActive: boolean;
isUnavailable: boolean;
+ muted: boolean;
name: string;
onLoadImage?: () => Promise<string | undefined>;
onLoadVideo?: SpacePostAssetURLLoader;
@@ -670,6 +678,7 @@ const FeedPhoto: React.FC<{
imageUrl,
isActive,
isUnavailable,
+ muted,
name,
onLoadImage,
onLoadVideo,
@@ -812,6 +821,7 @@ const FeedPhoto: React.FC<{
imageUrl={displayImageUrl!}
video={video}
isActive={isActive}
+ muted={muted}
onLoadVideo={onLoadVideo}
/>
)}
@@ -867,6 +877,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
viewerLiked,
}) => {
const [isLiked, setIsLiked] = useState(viewerLiked);
+ const [muted, setMuted] = useState(true);
const [likePopID, setLikePopID] = useState(0);
const [shouldLoadMedia, setShouldLoadMedia] = useState(
!isUnavailable && Boolean(imageUrl) && !isAvatarPending,
@@ -874,6 +885,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
const feedPhotos = photos ?? [{ imageUrl, thumbHash }];
const activePhoto = feedPhotos[photoIndex]!;
const carouselRef = React.useRef<HTMLDivElement | null>(null);
+ React.useEffect(() => registerFeedPost(carouselRef.current!), []);
const photoAnimationRef = React.useRef<number | null>(null);
const swipeRef = React.useRef<{
pointerID: number;
@@ -1051,6 +1063,8 @@ const FeedItem: React.FC<FeedItemProps> = ({
: photoDimensions.width / photoDimensions.height,
);
const isPhotoReady = Boolean(displayImageUrl) && decodedPhoto.ready;
+ const showSoundControl =
+ !isPostUnavailable && isPhotoReady && Boolean(activePhoto.video);
const canOpenPhoto =
!isPostUnavailable && isPhotoReady && Boolean(onOpenPhoto);
const openPhoto = (focusReplyOnOpen = false, index = photoIndex) => {
@@ -1185,17 +1199,75 @@ const FeedItem: React.FC<FeedItemProps> = ({
},
}}
>
- {photoCount > 1 && (
+ {(photoCount > 1 || showSoundControl) && (
<Box
sx={{
+ alignItems: "center",
display: "flex",
+ minHeight: spaceTouchTargetSize,
position: "absolute",
- right: 16,
- top: 16,
+ right: photoCount > 1 ? 16 : 8,
+ top: 12,
zIndex: 3,
pointerEvents: "none",
}}
>
+ {showSoundControl && (
+ <Box
+ component="button"
+ type="button"
+ aria-label={
+ muted ? "Unmute video" : "Mute video"
+ }
+ tabIndex={isViewerOpen ? -1 : 0}
+ onClick={() => setMuted(!muted)}
+ sx={{
+ alignItems: "center",
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "50%",
+ color: "#FFFFFF",
+ cursor: "pointer",
+ display: "flex",
+ flexShrink: 0,
+ height: spaceTouchTargetSize,
+ justifyContent: "center",
+ p: 0,
+ pointerEvents: "auto",
+ width: spaceTouchTargetSize,
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: -4,
+ },
+ "&:hover > span": {
+ bgcolor: "rgba(32, 32, 32, 0.75)",
+ },
+ }}
+ >
+ <Box
+ component="span"
+ sx={{
+ alignItems: "center",
+ bgcolor: "rgba(32, 32, 32, 0.55)",
+ borderRadius: "50%",
+ display: "flex",
+ height: 28,
+ justifyContent: "center",
+ width: 28,
+ }}
+ >
+ <HugeiconsIcon
+ icon={
+ muted
+ ? VolumeOffIcon
+ : VolumeHighIcon
+ }
+ size={16}
+ />
+ </Box>
+ </Box>
+ )}
<SpacePostPhotosCounter
compact
index={photoIndex}
@@ -1317,6 +1389,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
isUnavailable={
isUnavailable || Boolean(photo.isUnavailable)
}
+ muted={muted}
name={name}
onLoadImage={
onLoadImage
@@ -1367,7 +1440,13 @@ const FeedItem: React.FC<FeedItemProps> = ({
minHeight: 32,
pointerEvents: "none",
position: "absolute",
- right: photoCount > 1 ? 68 : 12,
+ right: showSoundControl
+ ? photoCount > 1
+ ? 112
+ : 64
+ : photoCount > 1
+ ? 68
+ : 12,
top: 12,
zIndex: 2,
}}
diff --git a/web/apps/space/tests/feed-video-playback.test.ts b/web/apps/space/tests/feed-video-playback.test.ts
new file mode 100644
index 0000000000..180500f576
--- /dev/null
+++ b/web/apps/space/tests/feed-video-playback.test.ts
@@ -0,0 +1,408 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import {
+ registerFeedPost,
+ registerFeedVideo,
+} from "../src/components/feed-video-playback";
+
+let viewport: EventTarget & { innerHeight: number; scrollY: number };
+let page: EventTarget & { hidden: boolean };
+let frames: Map<number, FrameRequestCallback>;
+let notifyVisibility: IntersectionObserverCallback;
+let registrations: ReturnType<typeof registerFeedVideo>[];
+let postCleanups: (() => void)[];
+let playing: Set<string>;
+let transitions: string[];
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ viewport = Object.assign(new EventTarget(), {
+ innerHeight: 1000,
+ scrollY: 0,
+ });
+ page = Object.assign(new EventTarget(), { hidden: false });
+ frames = new Map();
+ registrations = [];
+ postCleanups = [];
+ playing = new Set();
+ transitions = [];
+ let frame = 0;
+ vi.stubGlobal("window", viewport);
+ vi.stubGlobal("document", page);
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ frames.set(++frame, callback);
+ return frame;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
+ vi.stubGlobal(
+ "IntersectionObserver",
+ class {
+ constructor(callback: IntersectionObserverCallback) {
+ notifyVisibility = callback;
+ }
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ },
+ );
+});
+
+afterEach(() => {
+ registrations.forEach((registration) => registration.unregister());
+ postCleanups.forEach((cleanup) => cleanup());
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+const flush = () => {
+ const callbacks = [...frames.values()];
+ frames.clear();
+ callbacks.forEach((callback) => callback(0));
+};
+
+const visibility = (element: HTMLElement, ratio: number) => {
+ notifyVisibility(
+ [
+ {
+ target: element,
+ boundingClientRect: element.getBoundingClientRect(),
+ intersectionRect: element.getBoundingClientRect(),
+ intersectionRatio: ratio,
+ isIntersecting: ratio > 0,
+ rootBounds: null,
+ time: 0,
+ },
+ ],
+ {} as IntersectionObserver,
+ );
+};
+
+const addPost = (top: number, height = 250) => {
+ const children = new Set<HTMLElement>();
+ const element = {
+ getBoundingClientRect: () => ({
+ top: top - viewport.scrollY,
+ bottom: top + height - viewport.scrollY,
+ height,
+ }),
+ contains: (element: HTMLElement) => children.has(element),
+ } as unknown as HTMLElement;
+ const cleanup = registerFeedPost(element);
+ postCleanups.push(cleanup);
+ visibility(element, 1);
+ return { element, children, cleanup };
+};
+
+const addVideo = (
+ name: string,
+ top: number,
+ active = true,
+ height = 250,
+ post = addPost(top, height),
+) => {
+ const element = {
+ getBoundingClientRect: () => post.element.getBoundingClientRect(),
+ } as HTMLElement;
+ post.children.add(element);
+ const stop = () => {
+ playing.delete(name);
+ transitions.push(`stop ${name}`);
+ };
+ const player = {
+ play: vi.fn(() => {
+ expect(playing.size).toBe(0);
+ playing.add(name);
+ transitions.push(`play ${name}`);
+ }),
+ pause: vi.fn(stop),
+ deactivate: vi.fn(stop),
+ };
+ const control = registerFeedVideo(element, player);
+ registrations.push(control);
+ control.setActive(active);
+ return { element, player, control, post };
+};
+
+const scrollTo = (y: number, settle = true) => {
+ viewport.scrollY = y;
+ viewport.dispatchEvent(new Event("scroll"));
+ flush();
+ if (settle) vi.advanceTimersByTime(150);
+};
+
+test("autoplay waits for scrolling to settle and skips posts passed along the way", () => {
+ addVideo("upper", 100);
+ addVideo("middle", 500);
+ addVideo("lower", 1000);
+ flush();
+ scrollTo(400, false);
+ expect(playing.size).toBe(0);
+ vi.advanceTimersByTime(100);
+ scrollTo(900, false);
+ vi.advanceTimersByTime(100);
+ expect(playing.size).toBe(0);
+ vi.advanceTimersByTime(50);
+ expect(transitions).toEqual(["play upper", "stop upper", "play lower"]);
+});
+
+test("observer updates during scrolling do not start playback", () => {
+ const video = addVideo("video", 900);
+ flush();
+ scrollTo(700, false);
+ visibility(video.post.element, 1);
+ flush();
+ expect(playing.size).toBe(0);
+ vi.advanceTimersByTime(150);
+ expect([...playing]).toEqual(["video"]);
+});
+
+test("manual play takes effect immediately even before scrolling settles", () => {
+ const upper = addVideo("upper", -200);
+ addVideo("focused", 100);
+ flush();
+ scrollTo(10, false);
+ upper.control.play();
+ expect([...playing]).toEqual(["upper"]);
+ vi.advanceTimersByTime(150);
+ expect(transitions).toEqual(["play focused", "stop focused", "play upper"]);
+});
+
+test("a short landscape video plays before a lower video crossing the midpoint", () => {
+ addVideo("landscape", 100, true, 180);
+ addVideo("lower", 320, true, 500);
+ flush();
+ expect([...playing]).toEqual(["landscape"]);
+ expect(transitions).toEqual(["play landscape"]);
+});
+
+test("selection follows post position rather than registration order", () => {
+ addVideo("lower", 400);
+ addVideo("upper", 100);
+ flush();
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("playback transfers only after less than half of the first post remains visible", () => {
+ addVideo("upper", 100, true, 200);
+ addVideo("lower", 400);
+ flush();
+ scrollTo(200);
+ expect([...playing]).toEqual(["upper"]);
+ scrollTo(201);
+ expect([...playing]).toEqual(["lower"]);
+ expect(transitions).toEqual(["play upper", "stop upper", "play lower"]);
+});
+
+test("scrolling back up restores the earlier eligible post", () => {
+ addVideo("upper", 100);
+ addVideo("lower", 400);
+ flush();
+ scrollTo(300);
+ expect([...playing]).toEqual(["lower"]);
+ scrollTo(0);
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("a video entering the bottom of the viewport does not steal playback", () => {
+ addVideo("upper", 100);
+ flush();
+ addVideo("new", 700);
+ flush();
+ expect(transitions).toEqual(["play upper"]);
+});
+
+test("a mostly visible photo blocks autoplay in the next post", () => {
+ addPost(100);
+ addVideo("lower", 400);
+ flush();
+ expect(playing.size).toBe(0);
+});
+
+test("an unloaded post blocks autoplay in the next post until its video is ready", () => {
+ const post = addPost(100);
+ addVideo("lower", 400);
+ flush();
+ expect(playing.size).toBe(0);
+ addVideo("upper", 100, true, 250, post);
+ flush();
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("swiping the focused post to a photo does not start another post's video", () => {
+ addVideo("upper", -200);
+ const focused = addVideo("focused", 100);
+ addVideo("lower", 400);
+ flush();
+ focused.control.setActive(false);
+ flush();
+ expect(playing.size).toBe(0);
+ expect(transitions).toEqual(["play focused", "stop focused"]);
+ focused.control.setActive(true);
+ flush();
+ expect([...playing]).toEqual(["focused"]);
+});
+
+test("swiping the focused carousel between videos pauses the old slide first", () => {
+ const first = addVideo("first", 100);
+ const second = addVideo("second", 100, false, 250, first.post);
+ flush();
+ first.control.setActive(false);
+ second.control.setActive(true);
+ flush();
+ expect(transitions).toEqual(["play first", "stop first", "play second"]);
+});
+
+test("swiping another carousel to a video does not steal playback", () => {
+ addVideo("upper", 100);
+ const lower = addVideo("lower", 400, false);
+ flush();
+ lower.control.setActive(true);
+ flush();
+ expect(transitions).toEqual(["play upper"]);
+});
+
+test("tapping a partially visible video overrides autoplay synchronously", () => {
+ const upper = addVideo("upper", -200);
+ addVideo("focused", 100);
+ flush();
+ upper.control.play();
+ expect(transitions).toEqual(["play focused", "stop focused", "play upper"]);
+ scrollTo(10);
+ viewport.dispatchEvent(new Event("resize"));
+ visibility(upper.post.element, 0.16);
+ flush();
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("manual playback returns to autoplay when the chosen video leaves the screen", () => {
+ const upper = addVideo("upper", -200);
+ addVideo("focused", 100);
+ flush();
+ upper.control.play();
+ scrollTo(51);
+ expect([...playing]).toEqual(["focused"]);
+ expect(transitions).toEqual([
+ "play focused",
+ "stop focused",
+ "play upper",
+ "stop upper",
+ "play focused",
+ ]);
+});
+
+test("manual playback releases an inactive carousel slide", () => {
+ addVideo("upper", 100);
+ const lower = addVideo("lower", 400);
+ flush();
+ lower.control.play();
+ lower.control.setActive(false);
+ flush();
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("manual pause keeps other videos paused until an explicit resume or leaving the screen", () => {
+ const upper = addVideo("upper", -200);
+ addVideo("focused", 100);
+ flush();
+ upper.control.play();
+ upper.control.pause();
+ scrollTo(10);
+ expect(playing.size).toBe(0);
+ upper.control.play();
+ expect([...playing]).toEqual(["upper"]);
+ upper.control.pause();
+ scrollTo(51);
+ expect([...playing]).toEqual(["focused"]);
+});
+
+test("inactive or offscreen videos cannot be started manually", () => {
+ const inactive = addVideo("inactive", 100, false);
+ const offscreen = addVideo("offscreen", -300);
+ flush();
+ inactive.control.play();
+ offscreen.control.play();
+ expect(playing.size).toBe(0);
+});
+
+test("a tall post is eligible when at least half the viewport is covered", () => {
+ const video = addVideo("tall", -500, true, 2500);
+ visibility(video.post.element, 0.4);
+ flush();
+ expect([...playing]).toEqual(["tall"]);
+});
+
+test("playback stops when no post is sufficiently visible", () => {
+ addVideo("upper", -200);
+ addVideo("lower", 900);
+ flush();
+ expect(playing.size).toBe(0);
+});
+
+test("nonintersecting posts do not autoplay", () => {
+ const video = addVideo("clipped", 100);
+ visibility(video.post.element, 0);
+ flush();
+ expect(playing.size).toBe(0);
+});
+
+test("automatic playback respects pause until the post leaves and returns", () => {
+ const video = addVideo("upper", 100);
+ addVideo("lower", 400);
+ flush();
+ video.control.pause();
+ scrollTo(10);
+ expect(playing.size).toBe(0);
+ scrollTo(400);
+ expect([...playing]).toEqual(["lower"]);
+ scrollTo(0);
+ expect([...playing]).toEqual(["upper"]);
+});
+
+test("resizing the viewport updates post eligibility", () => {
+ addVideo("lower", 450, true, 200);
+ flush();
+ expect([...playing]).toEqual(["lower"]);
+ viewport.innerHeight = 500;
+ viewport.dispatchEvent(new Event("resize"));
+ flush();
+ expect(playing.size).toBe(0);
+});
+
+test("hiding the tab stops playback and preserves manual choice on return", () => {
+ addVideo("upper", 100);
+ const lower = addVideo("lower", 400);
+ flush();
+ lower.control.play();
+ page.hidden = true;
+ page.dispatchEvent(new Event("visibilitychange"));
+ expect(playing.size).toBe(0);
+ page.hidden = false;
+ page.dispatchEvent(new Event("visibilitychange"));
+ expect([...playing]).toEqual(["lower"]);
+});
+
+test("manual pause survives hiding and restoring the tab", () => {
+ const upper = addVideo("upper", -200);
+ addVideo("focused", 100);
+ flush();
+ upper.control.play();
+ upper.control.pause();
+ page.hidden = true;
+ page.dispatchEvent(new Event("visibilitychange"));
+ page.hidden = false;
+ page.dispatchEvent(new Event("visibilitychange"));
+ expect(playing.size).toBe(0);
+});
+
+test("unmounting releases playback and ignores queued observer notifications", () => {
+ const video = addVideo("upper", 100);
+ flush();
+ video.control.unregister();
+ video.post.cleanup();
+ registrations = [];
+ postCleanups = [];
+ visibility(video.post.element, 1);
+ viewport.dispatchEvent(new Event("scroll"));
+ flush();
+ expect(playing.size).toBe(0);
+ expect(video.player.play).toHaveBeenCalledTimes(1);
+});