Skip to content

armgit / ente

Public Imported from GitHub
0

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

Refine Space friend interactions

Anand Baburajan0802f1687e15
diff --git a/web/apps/space/package.json b/web/apps/space/package.json
index a4cbdb6105..23c518b709 100644
--- a/web/apps/space/package.json
+++ b/web/apps/space/package.json
@@ -3,7 +3,8 @@
"version": "0.0.0",
"private": true,
"scripts": {
- "build:post": "rm -f out/404.html"
+ "build:post": "rm -f out/404.html",
+ "test": "vitest --run"
},
"dependencies": {
"@fontsource-variable/inter": "5.2.8",
@@ -20,6 +21,7 @@
"thumbhash": "0.1.1"
},
"devDependencies": {
- "ente-build-config": "*"
+ "ente-build-config": "*",
+ "vitest": "4.1.8"
}
}
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index abc2c9a8a9..7fe56f26cc 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -1,5 +1,6 @@
import { SpacePageMeta } from "components/PageMeta";
import { SpaceRouteFallback } from "components/RouteFallback";
+import type { FriendProfile } from "data/friends";
import log from "ente-base/log";
import React, { useEffect, useState } from "react";
import { HomeScreen, homeBackground } from "screens/HomeScreen";
@@ -8,19 +9,22 @@ import {
prependCachedSpaceFeedPost,
} from "services/feed-cache";
import { consumeSentSpaceInviteFriend } from "services/invite";
+import { loadUnseenSpacePostIDs, markSpacePostSeen } from "services/post-seen";
import { loadExistingSpaceId } from "services/profile";
import {
createCurrentPhotoPost,
+ loadCurrentFriendAvatarURL,
loadCurrentSpaceFriends,
loadCurrentSpaceLatestPost,
loadCurrentSpacePostAssetURL,
- loadCurrentSpacePostAvatarURL,
loadCurrentUnreadStatus,
replyToCurrentPost,
+ sendCurrentMessage,
setCurrentPostLiked,
type SpacePost,
} from "services/space";
import { useSpaceAppState } from "state/app-state";
+import { spaceWaveMessageText } from "utils/message-limits";
import { prepareSpacePostImageFromEdit } from "utils/post-image";
import { useSpaceRouter } from "utils/route-transitions";
import { spaceRoutes } from "utils/routes";
@@ -39,6 +43,7 @@ const Page: React.FC = () => {
const [friendRequestSentToastName, setFriendRequestSentToastName] =
useState<string>();
const [latestPosts, setLatestPosts] = useState<SpacePost[]>([]);
+ const [unseenPostIDs, setUnseenPostIDs] = useState<Set<number>>(new Set());
const [hasUnreadMessages, setHasUnreadMessages] = useState<boolean>();
const [isLatestPostsLoading, setIsLatestPostsLoading] = useState(true);
const [isFriendsLoading, setIsFriendsLoading] = useState(true);
@@ -67,6 +72,7 @@ const Page: React.FC = () => {
let cancelled = false;
setSpaceId(undefined);
setLatestPosts([]);
+ setUnseenPostIDs(new Set());
setHasUnreadMessages(undefined);
setIsLatestPostsLoading(true);
setIsFriendsLoading(true);
@@ -115,9 +121,14 @@ const Page: React.FC = () => {
).then((latestPosts) => {
if (cancelled) return;
- setLatestPosts(
- latestPosts.filter(
- (post): post is SpacePost => post !== null,
+ const nextLatestPosts = latestPosts.filter(
+ (post): post is SpacePost => post !== null,
+ );
+ setLatestPosts(nextLatestPosts);
+ setUnseenPostIDs(
+ loadUnseenSpacePostIDs(
+ nextFriends,
+ nextLatestPosts,
),
);
});
@@ -158,6 +169,29 @@ const Page: React.FC = () => {
[spaceId],
);
+ const waveAtFriend = async (friend: FriendProfile) => {
+ if (!profile?.spaceId) throw new Error("Missing space.");
+
+ await sendCurrentMessage(
+ profile.spaceId,
+ friend.spaceId ?? friend.id,
+ spaceWaveMessageText,
+ {
+ avatarKeyVersion: profile.avatarKeyVersion,
+ avatarObjectID: profile.avatarObjectID,
+ avatarUpdatedAt: profile.avatarUpdatedAt,
+ avatarUrl: profile.avatarUrl,
+ friendsCount: 0,
+ fullName: profile.fullName,
+ id: profile.spaceId,
+ spaceId: profile.spaceId,
+ spaceSlug: profile.spaceSlug,
+ username: profile.username,
+ },
+ friend,
+ );
+ };
+
if (
profileLoadStatus == "error" ||
(profileLoadStatus == "ready" && !profile)
@@ -182,6 +216,7 @@ const Page: React.FC = () => {
isLatestPostsLoading={isLatestPostsLoading}
isFriendsLoading={isFriendsLoading}
profile={profile}
+ unseenPostIDs={unseenPostIDs}
viewerSpaceId={spaceId ?? profile?.spaceId}
showInstallPrompt={
profileLoadStatus == "ready" &&
@@ -191,6 +226,7 @@ const Page: React.FC = () => {
}
onFriendRequestSentToastClose={closeFriendRequestSentToast}
onInitialPostPhotoConsumed={() => setPendingPostPhotoFile(null)}
+ onLoadFriendAvatar={loadCurrentFriendAvatarURL}
onCreatePost={
profile
? async (image, caption) => {
@@ -229,8 +265,17 @@ const Page: React.FC = () => {
);
}
}}
- onLoadPostAvatar={loadCurrentSpacePostAvatarURL}
onLoadPostImage={loadCurrentSpacePostAssetURL}
+ onPostSeen={(friendSpaceID, postID) => {
+ markSpacePostSeen(friendSpaceID, postID);
+ setUnseenPostIDs((currentPostIDs) => {
+ if (!currentPostIDs.has(postID)) return currentPostIDs;
+
+ const nextPostIDs = new Set(currentPostIDs);
+ nextPostIDs.delete(postID);
+ return nextPostIDs;
+ });
+ }}
onOpenMessages={() => void router.push(spaceRoutes.messages)}
onOpenProfile={
profile
@@ -256,6 +301,7 @@ const Page: React.FC = () => {
: undefined
}
onSetPostLiked={setLatestPostLiked}
+ onWaveFriend={profile?.spaceId ? waveAtFriend : undefined}
/>
</>
);
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index 7935716858..8750c75d26 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -25,7 +25,6 @@ import {
isSpaceContentError,
type SpacePost,
type SpacePostAssetURLLoader,
- type SpacePostAvatarURLLoader,
} from "services/space";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom } from "utils/display";
@@ -40,12 +39,10 @@ import {
spacePostImageInputAccept,
spacePostPreviewImageForFile,
} from "utils/post-image";
-import { thumbHashDataURLFromBase64 } from "utils/thumbhash";
export const homeBackground = "#0C1014";
const green = "#08C225";
-const inactivePostCircleBorderColor = "rgba(180, 195, 186, 0.1)";
const mediaSkeletonElementBackground = "#E6E6E6";
const textBase = "#000";
const textSecondary = "#6B6B6B";
@@ -60,6 +57,9 @@ const headerIconSize = 22;
const headerSideWidth = 36;
const homeHorizontalPadding = "16px";
const postCircleMediaLoadRootMargin = "640px 0px";
+const waveAnimationDurationMs = 900;
+const waveHoldDurationMs = 500;
+const waveHoldMovementTolerancePx = 12;
const avatarFadeSx = {
"@keyframes spaceAvatarFade": { from: { opacity: 0 }, to: { opacity: 1 } },
animation: "spaceAvatarFade 320ms cubic-bezier(0.22, 1, 0.36, 1) both",
@@ -74,23 +74,26 @@ interface HomeScreenProps {
isLatestPostsLoading?: boolean;
isFriendsLoading?: boolean;
showInstallPrompt?: boolean;
+ unseenPostIDs: ReadonlySet<number>;
onCreatePost?: (
image: DraftSpacePostImage,
caption: string,
) => Promise<void>;
- onLoadPostAvatar?: SpacePostAvatarURLLoader;
+ onLoadFriendAvatar?: (friend: FriendProfile) => Promise<string | null>;
onLoadPostImage?: SpacePostAssetURLLoader;
onFriendRequestSentToastClose?: () => void;
onInitialPostPhotoConsumed?: () => void;
onOpenFriend?: (friendID: string, username?: string) => void;
onOpenMessages?: () => void;
onOpenProfile?: () => void;
+ onPostSeen?: (friendSpaceID: string, postID: number) => void;
onReplyToPost?: (
postSpaceId: string,
postId: number,
text: string,
) => Promise<void>;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
+ onWaveFriend?: (friend: FriendProfile) => Promise<void>;
profile: SetupProfile | null;
viewerSpaceId?: string;
}
@@ -138,13 +141,13 @@ const postImageCacheKey = (item: SpacePost) =>
item.imageAsset?.objectKey ?? item.imageUrl ?? "",
].join(":");
-const postAvatarCacheKey = (item: SpacePost) =>
+const friendAvatarCacheKey = (friend: FriendProfile) =>
[
- item.spaceId,
- item.avatarKeyVersion ?? "",
- item.avatarObjectID ?? "",
- item.avatarUpdatedAt ?? "",
- item.avatarSize ?? "",
+ friend.spaceId ?? friend.id,
+ friend.avatarKeyVersion ?? "",
+ friend.avatarObjectID ?? "",
+ friend.avatarUpdatedAt ?? "",
+ friend.avatarSize ?? "",
].join(":");
const useDecodedImage = (
@@ -221,6 +224,7 @@ interface FriendPostCircleProps {
onLoadImage?: () => Promise<string | undefined>;
onOpenFriend?: (friendID: string, username?: string) => void;
onOpenPhoto: (photo: SpaceViewerPhoto) => void;
+ onWave?: () => Promise<void>;
placement: HomeCirclePlacement;
post?: SpacePost;
}
@@ -236,24 +240,31 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
onLoadImage,
onOpenFriend,
onOpenPhoto,
+ onWave,
placement,
post,
}) => {
const rootRef = React.useRef<HTMLLIElement | null>(null);
+ const holdOriginRef = React.useRef<
+ { pointerID: number; x: number; y: number } | undefined
+ >(undefined);
+ const holdTimeoutRef = React.useRef<number | undefined>(undefined);
+ const suppressClickRef = React.useRef(false);
+ const waveAnimationTimeoutRef = React.useRef<number | undefined>(undefined);
+ const ringGradientID = `space-new-post-${React.useId().replaceAll(":", "")}`;
const [shouldLoadMedia, setShouldLoadMedia] = useState(Boolean(imageUrl));
+ const [isHoldingWave, setIsHoldingWave] = useState(false);
+ const [isWaveSending, setIsWaveSending] = useState(false);
+ const [waveAnimationID, setWaveAnimationID] = useState(0);
const decodedPhoto = useDecodedImage(imageUrl, true);
const decodedAvatar = useDecodedImage(
avatarUrl ?? friend.avatarUrl ?? null,
true,
);
- const thumbHashDataURL = React.useMemo(
- () => thumbHashDataURLFromBase64(post?.thumbHash),
- [post?.thumbHash],
- );
const displayName = friend.fullName.trim() || friend.username.trim();
const firstName = firstNameFrom(displayName);
- const initial = firstName.charAt(0).toLocaleUpperCase();
const postUnavailable = isUnavailable || decodedPhoto.failed;
+ const hasNewPost = Boolean(post && !postUnavailable);
const displayImageUrl =
(decodedPhoto.failed
? undefined
@@ -298,20 +309,117 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
return () => observer.disconnect();
}, [isLoading, post, postUnavailable, shouldLoadMedia]);
+ React.useEffect(() => {
+ if (isAvatarPending) void onLoadAvatar?.();
+ }, [isAvatarPending, onLoadAvatar]);
+
React.useEffect(() => {
if (!shouldLoadMedia || postUnavailable) return;
if (!imageUrl) void onLoadImage?.();
- if (isAvatarPending) void onLoadAvatar?.();
- }, [
- imageUrl,
- isAvatarPending,
- onLoadAvatar,
- onLoadImage,
- postUnavailable,
- shouldLoadMedia,
- ]);
+ }, [imageUrl, onLoadImage, postUnavailable, shouldLoadMedia]);
+
+ React.useEffect(
+ () => () => {
+ if (holdTimeoutRef.current !== undefined) {
+ window.clearTimeout(holdTimeoutRef.current);
+ }
+ if (waveAnimationTimeoutRef.current !== undefined) {
+ window.clearTimeout(waveAnimationTimeoutRef.current);
+ }
+ },
+ [],
+ );
+
+ const cancelWaveHold = () => {
+ if (holdTimeoutRef.current !== undefined) {
+ window.clearTimeout(holdTimeoutRef.current);
+ holdTimeoutRef.current = undefined;
+ }
+ holdOriginRef.current = undefined;
+ setIsHoldingWave(false);
+ };
+
+ const suppressPendingClick = () => {
+ suppressClickRef.current = true;
+ window.setTimeout(() => {
+ suppressClickRef.current = false;
+ }, 0);
+ };
+
+ const handlePointerDown: React.PointerEventHandler<HTMLButtonElement> = (
+ event,
+ ) => {
+ if (
+ hasNewPost ||
+ isWaveSending ||
+ !onWave ||
+ !event.isPrimary ||
+ event.button != 0
+ ) {
+ return;
+ }
+
+ cancelWaveHold();
+ holdOriginRef.current = {
+ pointerID: event.pointerId,
+ x: event.clientX,
+ y: event.clientY,
+ };
+ setIsHoldingWave(true);
+ holdTimeoutRef.current = window.setTimeout(() => {
+ holdTimeoutRef.current = undefined;
+ suppressClickRef.current = true;
+ setIsHoldingWave(false);
+ setWaveAnimationID((currentID) => currentID + 1);
+ if (waveAnimationTimeoutRef.current !== undefined) {
+ window.clearTimeout(waveAnimationTimeoutRef.current);
+ }
+ waveAnimationTimeoutRef.current = window.setTimeout(() => {
+ waveAnimationTimeoutRef.current = undefined;
+ setWaveAnimationID(0);
+ }, waveAnimationDurationMs);
+ setIsWaveSending(true);
+ void onWave()
+ .catch((error: unknown) =>
+ log.error("Failed to send wave", error),
+ )
+ .finally(() => setIsWaveSending(false));
+ }, waveHoldDurationMs);
+ };
+
+ const handlePointerMove: React.PointerEventHandler<HTMLButtonElement> = (
+ event,
+ ) => {
+ const origin = holdOriginRef.current;
+ if (origin?.pointerID != event.pointerId) return;
+
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const moved =
+ Math.hypot(event.clientX - origin.x, event.clientY - origin.y) >
+ waveHoldMovementTolerancePx;
+ const outside =
+ event.clientX < bounds.left ||
+ event.clientX > bounds.right ||
+ event.clientY < bounds.top ||
+ event.clientY > bounds.bottom;
+ if (!moved && !outside) return;
+
+ cancelWaveHold();
+ suppressClickRef.current = true;
+ };
+
+ const handlePointerEnd: React.PointerEventHandler<
+ HTMLButtonElement
+ > = () => {
+ cancelWaveHold();
+ if (suppressClickRef.current) suppressPendingClick();
+ };
const openCircle = () => {
+ if (suppressClickRef.current) {
+ suppressClickRef.current = false;
+ return;
+ }
if (!post || postUnavailable) {
onOpenFriend?.(friend.id, friend.username);
return;
@@ -357,7 +465,7 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
<Box
sx={{
aspectRatio: "1",
- border: `${circleBorderWidth}px solid ${inactivePostCircleBorderColor}`,
+ border: `${circleBorderWidth}px solid transparent`,
borderRadius: "50%",
boxSizing: "border-box",
height: "100%",
@@ -367,18 +475,64 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
zIndex: 1,
}}
>
+ <Box
+ component="svg"
+ viewBox="0 0 100 100"
+ aria-hidden
+ sx={{
+ display: "block",
+ inset: `-${circleBorderWidth}px`,
+ overflow: "visible",
+ pointerEvents: "none",
+ position: "absolute",
+ transform: "rotate(-90deg)",
+ }}
+ >
+ <defs>
+ <linearGradient
+ id={ringGradientID}
+ x1="0"
+ y1="0"
+ x2="100"
+ y2="100"
+ gradientUnits="userSpaceOnUse"
+ >
+ <stop offset="0%" stopColor={green} />
+ <stop offset="32%" stopColor="#70EC80" />
+ <stop offset="62%" stopColor={green} />
+ <stop offset="100%" stopColor="#049C1B" />
+ </linearGradient>
+ </defs>
+ <Box
+ component="circle"
+ cx="50"
+ cy="50"
+ r="49"
+ fill="none"
+ stroke={`url(#${ringGradientID})`}
+ strokeWidth={(circleBorderWidth / placement.size) * 100}
+ sx={{ opacity: hasNewPost ? 1 : 0 }}
+ />
+ </Box>
<Box
component="button"
type="button"
aria-label={
isLoading
- ? `Loading ${firstName}'s latest post`
+ ? `Loading ${firstName}`
: post && !postUnavailable
- ? `Open ${firstName}'s latest post`
- : `Open ${firstName}'s profile`
+ ? `View ${firstName}'s new post`
+ : `View ${firstName}'s profile`
}
disabled={isCircleDisabled}
onClick={openCircle}
+ onContextMenu={(event) => {
+ if (!hasNewPost) event.preventDefault();
+ }}
+ onPointerCancel={handlePointerEnd}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerEnd}
sx={{
alignItems: "center",
appearance: "none",
@@ -386,6 +540,9 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
bgcolor: "#E5E7EA",
border: 0,
borderRadius: "50%",
+ boxShadow: isHoldingWave
+ ? "0 1px 3px rgba(0, 0, 0, 0.22), 0 4px 10px rgba(0, 0, 0, 0.14)"
+ : "0 3px 8px rgba(0, 0, 0, 0.2), 0 12px 24px rgba(0, 0, 0, 0.14)",
color: textBase,
cursor: isCircleDisabled ? "default" : "pointer",
display: "flex",
@@ -395,10 +552,19 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
overflow: "hidden",
p: 0,
position: "relative",
+ transform: isHoldingWave ? "scale(0.98)" : "scale(1)",
+ transition:
+ "box-shadow 160ms ease-out, transform 160ms ease-out",
+ userSelect: "none",
+ WebkitTouchCallout: "none",
width: "100%",
+ "@media (prefers-reduced-motion: reduce)": {
+ transform: "none",
+ transition: "box-shadow 160ms ease-out",
+ },
}}
>
- {isLoading ? (
+ {isLoading || isAvatarPending ? (
<Skeleton
variant="circular"
sx={{
@@ -408,70 +574,75 @@ const FriendPostCircle: React.FC<FriendPostCircleProps> = ({
width: "100%",
}}
/>
- ) : post && !postUnavailable ? (
- <>
- {!thumbHashDataURL && !isPhotoReady && (
- <Skeleton
- variant="circular"
- sx={{
- bgcolor: mediaSkeletonElementBackground,
- height: "100%",
- transform: "none",
- width: "100%",
- }}
- />
- )}
- {thumbHashDataURL && (
- <Box
- component="img"
- alt=""
- aria-hidden
- src={thumbHashDataURL}
- sx={{
- filter: "blur(14px)",
- height: "100%",
- inset: 0,
- objectFit: "cover",
- position: "absolute",
- transform: "scale(1.08)",
- width: "100%",
- }}
- />
- )}
- {isPhotoReady && (
- <Box
- component="img"
- alt={`${displayName} post`}
- src={displayImageUrl}
- sx={{
- height: "100%",
- inset: 0,
- objectFit: "cover",
- position: "absolute",
- width: "100%",
- }}
- />
- )}
- </>
) : (
- <Box
- sx={{
- alignItems: "center",
- background:
- "linear-gradient(145deg, #ECF7ED, #D9EDDC)",
- color: green,
- display: "flex",
- fontSize: 40,
- fontWeight: 700,
- height: "100%",
- justifyContent: "center",
- width: "100%",
- }}
- >
- {initial}
- </Box>
+ <SpaceAvatarImage
+ alt={`${displayName} profile photo`}
+ src={displayAvatarUrl}
+ />
)}
</Box>
+ {waveAnimationID > 0 && (
+ <Box
+ key={waveAnimationID}
+ component="span"
+ aria-hidden
+ sx={{
+ "@keyframes spaceWaveSent": {
+ "0%": {
+ opacity: 0,
+ transform:
+ "translateY(8px) scale(0.7) rotate(0deg)",
+ },
+ "15%": {
+ opacity: 1,
+ transform:
+ "translateY(0) scale(1) rotate(-18deg)",
+ },
+ "35%": {
+ opacity: 1,
+ transform:
+ "translateY(-1px) scale(1) rotate(16deg)",
+ },
+ "55%": {
+ opacity: 1,
+ transform:
+ "translateY(-3px) scale(1) rotate(-14deg)",
+ },
+ "75%": {
+ opacity: 1,
+ transform:
+ "translateY(-6px) scale(1) rotate(12deg)",
+ },
+ "100%": {
+ opacity: 0,
+ transform:
+ "translateY(-12px) scale(0.95) rotate(0deg)",
+ },
+ },
+ "@keyframes spaceWaveSentReduced": {
+ "0%, 80%": { opacity: 1 },
+ "100%": { opacity: 0 },
+ },
+ animation: `spaceWaveSent ${waveAnimationDurationMs}ms ease-out both`,
+ fontSize: Math.max(
+ 28,
+ Math.min(48, placement.size * 0.23),
+ ),
+ lineHeight: 1,
+ bottom: "8%",
+ pointerEvents: "none",
+ position: "absolute",
+ right: "8%",
+ transformOrigin: "70% 75%",
+ zIndex: 2,
+ "@media (prefers-reduced-motion: reduce)": {
+ animation: `spaceWaveSentReduced ${waveAnimationDurationMs}ms ease-out both`,
+ },
+ }}
+ >
+ πŸ‘‹
+ </Box>
+ )}
</Box>
</Box>
);
@@ -582,16 +753,19 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
isLatestPostsLoading = false,
isFriendsLoading = false,
showInstallPrompt = false,
+ unseenPostIDs,
onCreatePost,
- onLoadPostAvatar,
+ onLoadFriendAvatar,
onLoadPostImage,
onFriendRequestSentToastClose,
onInitialPostPhotoConsumed,
onOpenFriend,
onOpenMessages,
onOpenProfile,
+ onPostSeen,
onReplyToPost,
onSetPostLiked,
+ onWaveFriend,
profile,
viewerSpaceId,
}) => {
@@ -603,9 +777,8 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
useState(false);
const [isDraftPostExiting, setIsDraftPostExiting] = useState(false);
const [isPostPhotoOpening, setIsPostPhotoOpening] = useState(false);
- const [loadedPostAvatarURLsByKey, setLoadedPostAvatarURLsByKey] = useState<
- Record<string, string | null>
- >({});
+ const [loadedFriendAvatarURLsByKey, setLoadedFriendAvatarURLsByKey] =
+ useState<Record<string, string | null>>({});
const [loadedPostImageURLsByKey, setLoadedPostImageURLsByKey] = useState<
Record<string, string>
>({});
@@ -688,6 +861,9 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
) => {
const isOwnPost =
Boolean(viewerSpaceId) && photo.friendID == viewerSpaceId;
+ if (!isOwnPost && photo.spaceId && photo.postId) {
+ onPostSeen?.(photo.spaceId, photo.postId);
+ }
setSelectedViewer({
focusReplyOnOpen: isOwnPost ? false : focusReplyOnOpen,
photo,
@@ -714,13 +890,13 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
item.imageUrl ?? loadedPostImageURLsByKey[postImageCacheKey(item)],
[loadedPostImageURLsByKey],
);
- const loadedPostAvatarURLFor = React.useCallback(
- (item: SpacePost) => {
- if (item.avatarUrl) return item.avatarUrl;
- if (!item.avatarObjectID) return null;
- return loadedPostAvatarURLsByKey[postAvatarCacheKey(item)];
+ const loadedFriendAvatarURLFor = React.useCallback(
+ (friend: FriendProfile) => {
+ if (friend.avatarUrl) return friend.avatarUrl;
+ if (!friend.avatarObjectID) return null;
+ return loadedFriendAvatarURLsByKey[friendAvatarCacheKey(friend)];
},
- [loadedPostAvatarURLsByKey],
+ [loadedFriendAvatarURLsByKey],
);
const loadPostImage = React.useCallback(
(item: SpacePost) => {
@@ -764,23 +940,23 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
},
[loadedPostImageURLFor, onLoadPostImage, unavailablePostsByKey],
);
- const loadPostAvatar = React.useCallback(
- (item: SpacePost) => {
- const loadedAvatarUrl = loadedPostAvatarURLFor(item);
+ const loadFriendAvatar = React.useCallback(
+ (friend: FriendProfile) => {
+ const loadedAvatarUrl = loadedFriendAvatarURLFor(friend);
if (loadedAvatarUrl !== undefined) {
return Promise.resolve(loadedAvatarUrl);
}
- if (!item.avatarObjectID || !onLoadPostAvatar) {
+ if (!friend.avatarObjectID || !onLoadFriendAvatar) {
return Promise.resolve(null);
}
- const cacheKey = postAvatarCacheKey(item);
+ const cacheKey = friendAvatarCacheKey(friend);
const inFlight = avatarLoadsInFlightRef.current.get(cacheKey);
if (inFlight) return inFlight;
- const load = onLoadPostAvatar(item)
+ const load = onLoadFriendAvatar(friend)
.then((avatarUrl) => {
- setLoadedPostAvatarURLsByKey((currentURLs) =>
+ setLoadedFriendAvatarURLsByKey((currentURLs) =>
currentURLs[cacheKey] == avatarUrl
? currentURLs
: { ...currentURLs, [cacheKey]: avatarUrl },
@@ -788,8 +964,8 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
return avatarUrl;
})
.catch((error: unknown) => {
- log.warn("Failed to load latest post avatar", error);
- setLoadedPostAvatarURLsByKey((currentURLs) =>
+ log.warn("Failed to load friend avatar", error);
+ setLoadedFriendAvatarURLsByKey((currentURLs) =>
currentURLs[cacheKey] === null
? currentURLs
: { ...currentURLs, [cacheKey]: null },
@@ -802,15 +978,23 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
avatarLoadsInFlightRef.current.set(cacheKey, load);
return load;
},
- [loadedPostAvatarURLFor, onLoadPostAvatar],
+ [loadedFriendAvatarURLFor, onLoadFriendAvatar],
);
const friendPostCircleFor = (friend: FriendProfile, index: number) => {
const placement = postCirclePlacements[index]!;
- const item = latestPostByFriendID.get(friend.spaceId ?? friend.id);
+ const latestPost = latestPostByFriendID.get(
+ friend.spaceId ?? friend.id,
+ );
+ const item =
+ latestPost && unseenPostIDs.has(latestPost.postId)
+ ? latestPost
+ : undefined;
const imageUrl = item ? loadedPostImageURLFor(item) : undefined;
- const avatarUrl = item ? loadedPostAvatarURLFor(item) : null;
+ const avatarUrl = loadedFriendAvatarURLFor(friend);
const isAvatarPending = Boolean(
- item && !item.isUnavailable && avatarUrl === undefined,
+ friend.avatarObjectID &&
+ friend.avatarKeyVersion &&
+ avatarUrl === undefined,
);
const isUnavailable = Boolean(
item &&
@@ -827,9 +1011,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
isLoading={isFriendsLoading || isLatestPostsLoading}
isUnavailable={isUnavailable}
onLoadAvatar={
- item && isAvatarPending
- ? () => loadPostAvatar(item)
- : undefined
+ isAvatarPending ? () => loadFriendAvatar(friend) : undefined
}
onLoadImage={
item && !imageUrl && !isUnavailable
@@ -838,6 +1020,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
}
onOpenFriend={onOpenFriend}
onOpenPhoto={openPostPhoto}
+ onWave={onWaveFriend ? () => onWaveFriend(friend) : undefined}
placement={placement}
post={item}
/>
@@ -1262,7 +1445,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
) : orderedFriends.length > 0 ? (
<Box
component="ul"
- aria-label="Friends' latest posts"
+ aria-label="Friends"
sx={{
height: "100%",
m: 0,
@@ -1294,7 +1477,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
textAlign: "center",
}}
>
- Your friends’ latest posts will show up here.
+ Your friends will show up here.
</Box>
)}
</Box>
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index af032b4466..b561c7e721 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -30,7 +30,10 @@ import type {
} from "services/space";
import { spaceTouchTargetSize } from "styles/touch-targets";
import { firstNameFrom } from "utils/display";
-import { clampSpaceMessageText } from "utils/message-limits";
+import {
+ clampSpaceMessageText,
+ spaceWaveMessageText,
+} from "utils/message-limits";
import { spacePostImageInputAccept } from "utils/post-image";
export const messagesBackground = "#FFFFFF";
@@ -65,10 +68,8 @@ const messageLongPressMs = 520;
const messageLongPressMoveTolerancePx = 10;
const messageActionsTouchOpenMouseSuppressMs = 900;
const dayMs = 24 * 60 * 60 * 1000;
-const waveMessageText = "πŸ‘‹";
-
const isWaveMessageText = (text: string | undefined) =>
- text?.trim() == waveMessageText;
+ text?.trim() == spaceWaveMessageText;
const shouldShowPostSomething = (
conversation: SpaceMessageConversation,
@@ -1820,7 +1821,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
stickToThreadBottomRef.current = true;
smoothNextMessageScrollRef.current = true;
setSendPhase("sending");
- void onSendMessage(spaceId, waveMessageText)
+ void onSendMessage(spaceId, spaceWaveMessageText)
.then(() => setSendPhase("idle"))
.catch((error: unknown) => {
smoothNextMessageScrollRef.current = false;
@@ -2315,7 +2316,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
lineHeight: 1,
}}
>
- {waveMessageText}
+ {spaceWaveMessageText}
</Box>
</Box>
) : (
diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsx
index f8d74f93ad..c252d50acf 100644
--- a/web/apps/space/src/screens/ProfileScreen.tsx
+++ b/web/apps/space/src/screens/ProfileScreen.tsx
@@ -591,8 +591,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const friendActionsMenuID = React.useId();
const isFriendActionsOpen = Boolean(friendActionsAnchor);
const isUnfriendActionRunning = unfriendActionPhase != null;
- const canManageFriend =
- isFriendProfile && Boolean(onMessageFriend || onUnfriend);
+ const canManageFriend = isFriendProfile && Boolean(onUnfriend);
const displayName = profile.fullName.trim() || profile.username.trim();
const coverUrl = profile.coverUrl ?? null;
const isCoverURLPending = Boolean(profile.coverObjectID && !coverUrl);
@@ -640,11 +639,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
const closeFriendActions = () => setFriendActionsAnchor(null);
- const messageFriend = () => {
- closeFriendActions();
- onMessageFriend?.();
- };
-
const requestUnfriend = () => {
closeFriendActions();
setUnfriendErrorMessage(null);
@@ -1281,7 +1275,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
whiteSpace: "nowrap",
}}
>
- {profile.username}
+ {firstName}
</Box>
{isOwnerProfile ? (
<Box
@@ -1315,6 +1309,40 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
strokeWidth={2.4}
/>
</Box>
+ ) : isFriendProfile && onMessageFriend ? (
+ <Box
+ component="button"
+ type="button"
+ aria-label={`Open chat with ${displayName}`}
+ onClick={onMessageFriend}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: "inherit",
+ cursor: "pointer",
+ display: "flex",
+ height: spaceTouchTargetSize,
+ justifyContent: "flex-end",
+ justifySelf: "end",
+ p: 0,
+ width: spaceTouchTargetSize,
+ "& svg path:first-of-type": {
+ display: "none",
+ },
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <HugeiconsIcon
+ icon={BubbleChatIcon}
+ size={21}
+ strokeWidth={2.5}
+ />
+ </Box>
) : (
<Box
aria-hidden
@@ -1438,8 +1466,10 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
width: 112,
}}
/>
- ) : (
+ ) : isPublicProfile ? (
displayName
+ ) : (
+ profile.username
)}
</Box>
{isOwnerProfile ? (
@@ -1562,54 +1592,6 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({
},
}}
>
- {onMessageFriend && (
- <MenuItem
- dense
- disableRipple
- onClick={messageFriend}
- sx={{
- alignItems: "center",
- borderRadius: "10px",
- color: textBase,
- display: "flex",
- gap: "8px",
- minHeight: 36,
- px: "9px",
- py: "4px",
- whiteSpace: "nowrap",
- "&.Mui-focusVisible": {
- bgcolor:
- "rgba(0, 0, 0, 0.04)",
- },
- "&:active": {
- bgcolor:
- "rgba(0, 0, 0, 0.04)",
- },
- "&:hover": {
- bgcolor:
- "rgba(0, 0, 0, 0.04)",
- },
- }}
- >
- <HugeiconsIcon
- icon={BubbleChatIcon}
- size={18}
- strokeWidth={1.8}
- style={{ flexShrink: 0 }}
- />
- <Box
- sx={{
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 650,
- lineHeight: "18px",
- }}
- >
- Message
- </Box>
- </MenuItem>
- )}
{onUnfriend && (
<MenuItem
dense
diff --git a/web/apps/space/src/services/post-seen.test.ts b/web/apps/space/src/services/post-seen.test.ts
new file mode 100644
index 0000000000..5535a185ce
--- /dev/null
+++ b/web/apps/space/src/services/post-seen.test.ts
@@ -0,0 +1,82 @@
+import type { FriendProfile } from "data/friends";
+import type { SpacePost } from "services/space";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { loadUnseenSpacePostIDs, markSpacePostSeen } from "./post-seen";
+
+const values = new Map<string, string>();
+const storage: Storage = {
+ clear: () => values.clear(),
+ getItem: (key) => values.get(key) ?? null,
+ key: (index) => [...values.keys()][index] ?? null,
+ get length() {
+ return values.size;
+ },
+ removeItem: (key) => values.delete(key),
+ setItem: (key, value) => values.set(key, value),
+};
+
+const friend = (spaceId: string): FriendProfile => ({
+ friendsCount: 0,
+ fullName: spaceId,
+ id: spaceId,
+ spaceId,
+ username: spaceId,
+});
+
+const post = (spaceId: string, postId: number): SpacePost => ({
+ friendID: spaceId,
+ name: spaceId,
+ postId,
+ spaceId,
+ timestampMs: 0,
+ viewerLiked: false,
+});
+
+describe("Space post seen state", () => {
+ beforeEach(() => {
+ values.clear();
+ vi.stubGlobal("localStorage", storage);
+ });
+
+ test("uses the current latest post as the first baseline", () => {
+ const alice = friend("alice");
+
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 10)])).toEqual(
+ new Set(),
+ );
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 11)])).toEqual(
+ new Set([11]),
+ );
+ });
+
+ test("detects the first post from a friend who had no posts", () => {
+ const alice = friend("alice");
+
+ expect(loadUnseenSpacePostIDs([alice], [])).toEqual(new Set());
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 1)])).toEqual(
+ new Set([1]),
+ );
+ });
+
+ test("stops returning a post after it is marked seen", () => {
+ const alice = friend("alice");
+ loadUnseenSpacePostIDs([alice], [post("alice", 10)]);
+
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 11)])).toEqual(
+ new Set([11]),
+ );
+ markSpacePostSeen("alice", 11);
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 11)])).toEqual(
+ new Set(),
+ );
+ });
+
+ test("does not treat an older replacement post as unseen", () => {
+ const alice = friend("alice");
+ loadUnseenSpacePostIDs([alice], [post("alice", 10)]);
+
+ expect(loadUnseenSpacePostIDs([alice], [post("alice", 9)])).toEqual(
+ new Set(),
+ );
+ });
+});
diff --git a/web/apps/space/src/services/post-seen.ts b/web/apps/space/src/services/post-seen.ts
new file mode 100644
index 0000000000..7319bd3db9
--- /dev/null
+++ b/web/apps/space/src/services/post-seen.ts
@@ -0,0 +1,58 @@
+import type { FriendProfile } from "data/friends";
+import type { SpacePost } from "services/space";
+
+const storageKeyFor = (friendSpaceID: string) =>
+ `space.posts.lastSeen.${friendSpaceID}`;
+
+const storedPostID = (value: string | null) => {
+ if (value === null) return undefined;
+
+ const postID = Number(value);
+ return Number.isSafeInteger(postID) && postID >= 0 ? postID : undefined;
+};
+
+export const loadUnseenSpacePostIDs = (
+ friends: FriendProfile[],
+ latestPosts: SpacePost[],
+) => {
+ const latestPostBySpaceID = new Map(
+ latestPosts.map((post) => [post.spaceId, post]),
+ );
+ const unseenPostIDs = new Set<number>();
+
+ try {
+ for (const friend of friends) {
+ const friendSpaceID = friend.spaceId ?? friend.id;
+ const latestPost = latestPostBySpaceID.get(friendSpaceID);
+ const storageKey = storageKeyFor(friendSpaceID);
+ const lastSeenPostID = storedPostID(
+ localStorage.getItem(storageKey),
+ );
+
+ if (lastSeenPostID === undefined) {
+ localStorage.setItem(
+ storageKey,
+ String(latestPost?.postId ?? 0),
+ );
+ } else if (latestPost && latestPost.postId > lastSeenPostID) {
+ unseenPostIDs.add(latestPost.postId);
+ }
+ }
+ } catch {
+ unseenPostIDs.clear();
+ }
+
+ return unseenPostIDs;
+};
+
+export const markSpacePostSeen = (friendSpaceID: string, postID: number) => {
+ try {
+ const storageKey = storageKeyFor(friendSpaceID);
+ const lastSeenPostID = storedPostID(localStorage.getItem(storageKey));
+ if (lastSeenPostID === undefined || postID > lastSeenPostID) {
+ localStorage.setItem(storageKey, String(postID));
+ }
+ } catch {
+ return;
+ }
+};
diff --git a/web/apps/space/src/utils/home-circle-layout.ts b/web/apps/space/src/utils/home-circle-layout.ts
index afc9d980c7..2d9c528b37 100644
--- a/web/apps/space/src/utils/home-circle-layout.ts
+++ b/web/apps/space/src/utils/home-circle-layout.ts
@@ -67,7 +67,12 @@ export const homeCirclePlacements = (
slotsByRow[row - 1]!.length != slotsByRow[row]!.length;
rowOffsets.push(rowOffsets[row - 1]! + (rowsAreStaggered ? 1 : 1.1));
}
- const layoutWidth = columns + (columns - 1) * circleGapRatio;
+ const layoutWidth =
+ count == 1
+ ? 1 / 0.5
+ : count == 2
+ ? 1 / 0.48
+ : columns + (columns - 1) * circleGapRatio;
const layoutHeight = 1 + rowOffsets[rowOffsets.length - 1]!;
const size = Math.min(
canvasWidth / layoutWidth,
diff --git a/web/apps/space/src/utils/message-limits.ts b/web/apps/space/src/utils/message-limits.ts
index 91e8da789a..37ce477e3c 100644
--- a/web/apps/space/src/utils/message-limits.ts
+++ b/web/apps/space/src/utils/message-limits.ts
@@ -1,4 +1,5 @@
export const spaceMessageTextMaxLength = 1000;
+export const spaceWaveMessageText = "πŸ‘‹";
export const clampSpaceMessageText = (text: string) =>
Array.from(text).slice(0, spaceMessageTextMaxLength).join("");
diff --git a/web/package-lock.json b/web/package-lock.json
index 43d7d578fd..833b7d5523 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -358,7 +358,8 @@
"thumbhash": "0.1.1"
},
"devDependencies": {
- "ente-build-config": "*"
+ "ente-build-config": "*",
+ "vitest": "4.1.8"
}
},
"apps/space/node_modules/@hugeicons/react": {
diff --git a/web/package.json b/web/package.json
index 3bee38bffc..910183cdb3 100644
--- a/web/package.json
+++ b/web/package.json
@@ -52,7 +52,7 @@
"dev:twoof3": "npm exec --workspace twoof3 -- next dev --webpack -p 3012",
"lint": "concurrently --names 'prettier,eslint,tsc,wasm-imports' \"prettier --check --log-level warn .\" \"npm exec --workspaces -- eslint --max-warnings 0\" \"npm exec --workspaces -- tsc\" \"npm run check:wasm-imports\"",
"lint:fix": "concurrently --names 'prettier,eslint,tsc' \"prettier --write --log-level warn .\" \"npm exec --workspaces -- eslint --fix --max-warnings 0\" \"npm exec --workspaces -- tsc\"",
- "test": "npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace locker && npm run test --workspace photos"
+ "test": "npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace locker && npm run test --workspace space && npm run test --workspace photos"
},
"overrides": {
"@types/react": "19.2.17",