Skip to content

armgit / ente

Public Imported from GitHub
0

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

Improve messages loading performance

Anand Baburajan0e68379963fc
diff --git a/web/apps/space/src/components/SpaceMessagesPage.tsx b/web/apps/space/src/components/SpaceMessagesPage.tsx
index 2cc9b3cc19..bbc71b7057 100644
--- a/web/apps/space/src/components/SpaceMessagesPage.tsx
+++ b/web/apps/space/src/components/SpaceMessagesPage.tsx
@@ -10,6 +10,7 @@ import {
deleteCurrentMessage,
isFriendRequestCanceledError,
loadCurrentMessageActivityPostPreview,
+ loadCurrentMessageConversationAvatar,
loadCurrentMessageConversations,
loadCurrentMessageThread,
loadCurrentSpaceProfile,
@@ -133,6 +134,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
undefined,
);
const markedReadSpaceIdRef = React.useRef<string | undefined>(undefined);
+ const conversationsLoadGenerationRef = React.useRef(0);
const previousSelectedSpaceIdRef = React.useRef<string | undefined>(
selectedSpaceId,
);
@@ -242,9 +244,13 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
const actorSpaceId = profile?.spaceId;
if (!actorSpaceId) return false;
+ const generation = ++conversationsLoadGenerationRef.current;
setIsConversationsLoading(true);
try {
const page = await loadCurrentMessageConversations(actorSpaceId);
+ if (conversationsLoadGenerationRef.current != generation) {
+ return false;
+ }
const items = page.items.sort((a, b) => {
const createdAtDiff =
b.latestActivity.createdAtMs - a.latestActivity.createdAtMs;
@@ -271,6 +277,68 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
)
.map((conversation) => conversation.friend),
);
+ for (const conversation of items) {
+ const friend = conversation.friend;
+ if (
+ isFriendRequestConversation(conversation) ||
+ friend.avatarUrl ||
+ !friend.avatarObjectID ||
+ !friend.avatarKeyVersion
+ ) {
+ continue;
+ }
+
+ const itemID = conversationId(conversation);
+ const itemFriendSpaceID = friendSpaceId(friend);
+ void loadCurrentMessageConversationAvatar(actorSpaceId, friend)
+ .then((avatarUrl) => {
+ if (
+ !avatarUrl ||
+ conversationsLoadGenerationRef.current != generation
+ ) {
+ return;
+ }
+
+ setConversations((currentConversations) =>
+ currentConversations.map((currentConversation) => {
+ const currentFriend =
+ currentConversation.friend;
+ return conversationId(currentConversation) ==
+ itemID &&
+ currentFriend.avatarObjectID ==
+ friend.avatarObjectID &&
+ currentFriend.avatarKeyVersion ==
+ friend.avatarKeyVersion
+ ? {
+ ...currentConversation,
+ friend: {
+ ...currentFriend,
+ avatarUrl,
+ },
+ }
+ : currentConversation;
+ }),
+ );
+ setFriends((currentFriends) =>
+ currentFriends.map((currentFriend) =>
+ friendSpaceId(currentFriend) ==
+ itemFriendSpaceID &&
+ currentFriend.avatarObjectID ==
+ friend.avatarObjectID &&
+ currentFriend.avatarKeyVersion ==
+ friend.avatarKeyVersion
+ ? { ...currentFriend, avatarUrl }
+ : currentFriend,
+ ),
+ );
+ })
+ .catch((error: unknown) =>
+ console.warn(
+ "Failed to load message conversation avatar",
+ error,
+ ),
+ );
+ }
if (passiveUnreadConversationIds.length > 0) {
void Promise.all(
passiveUnreadConversationIds.map((spaceId) =>
@@ -288,10 +356,19 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
console.error("Failed to load message conversations", error);
return false;
} finally {
- setIsConversationsLoading(false);
+ if (conversationsLoadGenerationRef.current == generation) {
+ setIsConversationsLoading(false);
+ }
}
}, [profile?.spaceId, setFriends]);
+ React.useEffect(
+ () => () => {
+ conversationsLoadGenerationRef.current += 1;
+ },
+ [],
+ );
+
const openConversation = React.useCallback(
(conversation: SpaceMessageConversation) => {
if (isFriendRequestConversation(conversation)) return;
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index bd242a3121..0e8a550d0a 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -432,19 +432,18 @@ const ConversationListItem: React.FC<{
conversation.latestActivity.type == "friend_request";
const post = conversation.latestActivity.post;
const postThumbnailUrl = (activityPost ?? post)?.imageUrl;
+ const showPostThumbnailSlot = Boolean(post);
+ const isPostThumbnailUnavailable =
+ Boolean(post?.isDeleted) ||
+ Boolean(activityPost && !activityPost.imageUrl);
const unreadCount = conversation.unreadCount;
React.useEffect(() => {
- if (
- !post ||
- post.isDeleted ||
- post.imageUrl ||
- activityPost?.imageUrl
- ) {
+ if (!post || post.isDeleted || post.imageUrl || activityPost) {
return;
}
onLoadActivityPost?.(post);
}, [
- activityPost?.imageUrl,
+ activityPost,
onLoadActivityPost,
post,
post?.imageUrl,
@@ -577,7 +576,7 @@ const ConversationListItem: React.FC<{
display: "grid",
gap: "10px",
gridColumn: isFriendRequest ? undefined : "2 / -1",
- gridTemplateColumns: postThumbnailUrl
+ gridTemplateColumns: showPostThumbnailSlot
? "minmax(0, 1fr) 44px"
: "minmax(0, 1fr)",
minWidth: 0,
@@ -654,21 +653,49 @@ const ConversationListItem: React.FC<{
</Box>
<ConversationPreviewLine conversation={conversation} />
</Box>
- {postThumbnailUrl && (
- <Box
- component="img"
- alt=""
- src={postThumbnailUrl}
- sx={{
- borderRadius: "6px",
- display: "block",
- height: 44,
- objectFit: "cover",
- objectPosition: "center",
- width: 44,
- }}
- />
- )}
+ {showPostThumbnailSlot &&
+ (postThumbnailUrl ? (
+ <Box
+ component="img"
+ alt=""
+ src={postThumbnailUrl}
+ sx={{
+ borderRadius: "6px",
+ display: "block",
+ height: 44,
+ objectFit: "cover",
+ objectPosition: "center",
+ width: 44,
+ }}
+ />
+ ) : (
+ <Box
+ aria-label={
+ isPostThumbnailUnavailable
+ ? "Post image unavailable"
+ : "Loading post image"
+ }
+ role="img"
+ sx={{
+ alignItems: "center",
+ bgcolor: incomingQuoteBubble,
+ borderRadius: "6px",
+ color: incomingQuoteText,
+ display: "flex",
+ height: 44,
+ justifyContent: "center",
+ width: 44,
+ }}
+ >
+ {isPostThumbnailUnavailable && (
+ <HugeiconsIcon
+ icon={ImageDelete02Icon}
+ size={18}
+ strokeWidth={1.5}
+ />
+ )}
+ </Box>
+ ))}
</Box>
{isFriendRequest && (
<Box sx={{ display: "flex", flexShrink: 0, gap: "6px" }}>
@@ -1123,14 +1150,38 @@ const MessageReplyPreview: React.FC<{
};
const PostQuotePreview: React.FC<{
+ activityPost?: SpaceMessageActivityPost;
isOwn: boolean;
message: SpaceMessage;
mb?: string;
+ onLoadActivityPost?: (post: SpaceMessageActivityPost) => void;
onOpenQuotePost: (quote: SpaceMessageQuote) => void;
-}> = ({ isOwn, message, mb, onOpenQuotePost }) => {
+}> = ({
+ activityPost,
+ isOwn,
+ message,
+ mb,
+ onLoadActivityPost,
+ onOpenQuotePost,
+}) => {
const quote = message.quote;
- const isUnavailable = !quote || quote.isUnavailable || !quote.imageUrl;
- const canOpen = Boolean(quote && !isUnavailable);
+ const imageUrl = quote?.imageUrl ?? activityPost?.imageUrl;
+ const isUnavailable =
+ !quote ||
+ quote.isUnavailable == true ||
+ (!imageUrl &&
+ (activityPost != undefined || onLoadActivityPost == undefined));
+ const loadedQuote =
+ quote && imageUrl && !isUnavailable
+ ? { ...quote, imageUrl }
+ : undefined;
+ const isLoading = quote != undefined && !imageUrl && !isUnavailable;
+ const canOpen = Boolean(loadedQuote);
+
+ React.useEffect(() => {
+ if (!quote || imageUrl || isUnavailable) return;
+ onLoadActivityPost?.(quote);
+ }, [imageUrl, isUnavailable, onLoadActivityPost, quote]);
return (
<QuoteFrame isOwn={isOwn} mb={mb}>
@@ -1139,9 +1190,9 @@ const PostQuotePreview: React.FC<{
type={canOpen ? "button" : undefined}
aria-label={canOpen ? "Open quoted post" : undefined}
onClick={(event: React.MouseEvent) => {
- if (!quote || !canOpen) return;
+ if (!loadedQuote) return;
event.stopPropagation();
- onOpenQuotePost(quote);
+ onOpenQuotePost(loadedQuote);
}}
sx={{
appearance: "none",
@@ -1159,10 +1210,28 @@ const PostQuotePreview: React.FC<{
},
}}
>
- {isUnavailable ? (
+ {imageUrl ? (
+ <Box
+ component="img"
+ alt=""
+ src={imageUrl}
+ sx={{
+ borderRadius: "8px",
+ display: "block",
+ height: postQuoteThumbnailSize,
+ objectFit: "cover",
+ objectPosition: "center",
+ width: postQuoteThumbnailSize,
+ }}
+ />
+ ) : (
<Box
role="img"
- aria-label="Deleted post"
+ aria-label={
+ isLoading
+ ? "Loading post image"
+ : "Post unavailable"
+ }
sx={{
alignItems: "center",
bgcolor: incomingQuoteBubble,
@@ -1180,26 +1249,14 @@ const PostQuotePreview: React.FC<{
px: "12px",
}}
>
- <HugeiconsIcon
- icon={ImageDelete02Icon}
- size={28}
- strokeWidth={1.5}
- />
+ {isUnavailable && (
+ <HugeiconsIcon
+ icon={ImageDelete02Icon}
+ size={28}
+ strokeWidth={1.5}
+ />
+ )}
</Box>
- ) : (
- <Box
- component="img"
- alt=""
- src={quote.imageUrl}
- sx={{
- borderRadius: "8px",
- display: "block",
- height: postQuoteThumbnailSize,
- objectFit: "cover",
- objectPosition: "center",
- width: postQuoteThumbnailSize,
- }}
- />
)}
</Box>
</QuoteFrame>
@@ -1210,6 +1267,7 @@ const isMessageLongPressIgnoredTarget = (target: EventTarget | null) =>
target instanceof Element && Boolean(target.closest("button"));
const MessageBubble: React.FC<{
+ activityPost?: SpaceMessageActivityPost;
groupsWithNext: boolean;
groupsWithPrevious: boolean;
isHighlighted: boolean;
@@ -1219,16 +1277,19 @@ const MessageBubble: React.FC<{
anchorEl: HTMLElement,
source: MessageActionsOpenSource,
) => void;
+ onLoadActivityPost?: (post: SpaceMessageActivityPost) => void;
onOpenQuotePost: (quote: SpaceMessageQuote) => void;
ownSpaceID?: string;
parentMessage?: SpaceMessage;
profile: SetupProfile;
}> = ({
+ activityPost,
groupsWithNext,
groupsWithPrevious,
isHighlighted,
message,
onOpenActions,
+ onLoadActivityPost,
onOpenQuotePost,
ownSpaceID,
parentMessage,
@@ -1394,9 +1455,11 @@ const MessageBubble: React.FC<{
)}
{(isPostReply || isSyntheticPostLike) && (
<PostQuotePreview
+ activityPost={activityPost}
isOwn={isOwn}
mb={hasBodyBubble ? "8px" : "0"}
message={message}
+ onLoadActivityPost={onLoadActivityPost}
onOpenQuotePost={onOpenQuotePost}
/>
)}
@@ -1572,15 +1635,28 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
activityPostLoadsInFlightRef.current.add(key);
void onLoadActivityPost(post)
.then((loadedPost) => {
- if (!loadedPost) return;
setActivityPostsByKey((currentPosts) =>
currentPosts[key]
? currentPosts
- : { ...currentPosts, [key]: loadedPost },
+ : {
+ ...currentPosts,
+ [key]: loadedPost ?? {
+ ...post,
+ isDeleted: true,
+ },
+ },
);
})
.catch((error: unknown) => {
console.warn("Failed to load message activity post", error);
+ setActivityPostsByKey((currentPosts) =>
+ currentPosts[key]
+ ? currentPosts
+ : {
+ ...currentPosts,
+ [key]: { ...post, isDeleted: true },
+ },
+ );
})
.finally(() => {
activityPostLoadsInFlightRef.current.delete(key);
@@ -2078,7 +2154,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
py: "12px",
}}
>
- {isThreadLoading || isThreadRecipientLoading ? (
+ {isThreadLoading ? (
<Box
sx={{
alignItems: "center",
@@ -2176,6 +2252,15 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
/>
)}
<MessageBubble
+ activityPost={
+ message.quote
+ ? activityPostsByKey[
+ activityPostKey(
+ message.quote,
+ )
+ ]
+ : undefined
+ }
groupsWithNext={
groupsWithNext
}
@@ -2194,6 +2279,9 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
onOpenActions={
openMessageActions
}
+ onLoadActivityPost={
+ loadActivityPost
+ }
onOpenQuotePost={
onOpenQuotePost
}
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index fa4cd0cd66..d755bb556d 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -8,6 +8,7 @@ import type {
import type { PendingSpaceInvite } from "services/spaceInvite";
import {
cachedSpaceMediaBlobURL,
+ cachedSpaceMediaBlobURLIfPresent,
clearSpaceMediaCache,
rememberCachedSpaceMediaBlobURL,
spacePostMediaCacheKey,
@@ -506,6 +507,23 @@ const accountAvatarURL = async (
}
};
+const cachedAccountAvatarURLIfPresent = async (
+ spaceId: string | undefined,
+ avatar: SpaceAvatar | undefined,
+) => {
+ if (!spaceId || !avatar?.objectID) return null;
+ return (
+ (await cachedSpaceMediaBlobURLIfPresent(
+ spaceProfileMediaCacheKey(
+ spaceId,
+ "avatar",
+ avatar.objectID,
+ avatar.keyVersion,
+ ),
+ )) ?? null
+ );
+};
+
const postAssetFrom = (
post: SpacePostResponse,
object: SpacePostObject,
@@ -896,13 +914,28 @@ export const loadCurrentMessageActivityPostPreview = async (
viewerSpaceId?: string,
): Promise<SpaceMessageActivityPost | undefined> => {
if (post.isDeleted) return post;
- const loadedPost = await loadCurrentSpacePost(
- post.spaceId,
- post.postId,
- viewerSpaceId,
- );
- if (!loadedPost) return post;
- return { ...post, imageUrl: loadedPost.imageUrl };
+ const ctx = await ensureCurrentSpaceContext();
+ try {
+ const response = (await ctx.getPost(
+ post.spaceId,
+ BigInt(post.postId),
+ viewerSpaceId ?? null,
+ )) as SpacePostResponse | null;
+ if (!response) return post;
+ const quote = await messageQuoteFromPostResponse(
+ ctx,
+ response,
+ true,
+ viewerSpaceId,
+ );
+ return {
+ ...post,
+ imageUrl: quote.imageUrl,
+ isDeleted: quote.isUnavailable,
+ };
+ } finally {
+ releaseCurrentSpaceContext(ctx);
+ }
};
const messageActivityFromSpaceActivity = (
@@ -1416,11 +1449,9 @@ export const loadCurrentMessageConversations = async (
(response.friends ?? []).map(async (conversation) => {
const friend = actorProfile(conversation.friend);
const friendSpaceID = friendSpaceId(friend);
- friend.avatarUrl = await accountAvatarURL(
- ctx,
+ friend.avatarUrl = await cachedAccountAvatarURLIfPresent(
friendSpaceID,
conversation.friend.avatar,
- spaceId,
);
const summary = conversationSummaryForFriend(
summaries,
@@ -1475,6 +1506,36 @@ export const loadCurrentMessageConversations = async (
}
};
+export const loadCurrentMessageConversationAvatar = async (
+ viewerSpaceId: string,
+ friend: FriendProfile,
+) => {
+ if (
+ friend.avatarUrl ||
+ !friend.avatarObjectID ||
+ !friend.avatarKeyVersion
+ ) {
+ return friend.avatarUrl ?? null;
+ }
+
+ const ctx = await ensureCurrentSpaceContext();
+ try {
+ return await accountAvatarURL(
+ ctx,
+ friendSpaceId(friend),
+ {
+ keyVersion: friend.avatarKeyVersion,
+ objectID: friend.avatarObjectID,
+ size: friend.avatarSize,
+ updatedAt: friend.avatarUpdatedAt,
+ },
+ viewerSpaceId,
+ );
+ } finally {
+ releaseCurrentSpaceContext(ctx);
+ }
+};
+
export const confirmCurrentFriendRequest = async (
spaceId: string,
requestId: number,
@@ -1540,10 +1601,13 @@ export const loadCurrentMessageThread = async (
const items = (
await Promise.all(
(page.items ?? []).map((message) =>
- messageFromSpaceMessage(ctx, message, true, viewerSpaceId, {
- friend,
- viewer,
- }),
+ messageFromSpaceMessage(
+ ctx,
+ message,
+ false,
+ viewerSpaceId,
+ { friend, viewer },
+ ),
),
)
).reverse();