Skip to content

armgit / ente

Public Imported from GitHub
0

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

Update Space notification activity handling

Anand Baburajan4ba596057c82
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rs
index 9d71c492ca..4e05cc379a 100644
--- a/rust/bindings/wasm/ente-wasm/src/space.rs
+++ b/rust/bindings/wasm/ente-wasm/src/space.rs
@@ -243,6 +243,7 @@ struct MessageConversationActivityJs {
#[serde(rename = "type")]
activity_type: String,
created_at: String,
+ outgoing: bool,
message: Option<MessageJs>,
post: Option<MessageConversationPostJs>,
}
@@ -482,6 +483,7 @@ async fn message_conversation_activity_to_js(
id: activity.id,
activity_type: activity.activity_type,
created_at: activity.created_at,
+ outgoing: activity.outgoing,
message,
post: activity.post.map(message_conversation_post_to_js),
})
diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rs
index d5cbd568de..c002dcbfca 100644
--- a/rust/space/src/transport.rs
+++ b/rust/space/src/transport.rs
@@ -220,6 +220,8 @@ pub struct MessageConversationActivity {
pub activity_type: String,
pub created_at: String,
#[serde(default)]
+ pub outgoing: bool,
+ #[serde(default)]
pub message: Option<MessageResponse>,
#[serde(default)]
pub post: Option<MessageConversationPost>,
@@ -393,7 +395,7 @@ pub struct SpaceKeyVersionResponse {
#[cfg(test)]
mod tests {
- use super::AssetDownloadResponse;
+ use super::{AssetDownloadResponse, MessageConversationActivity};
#[test]
fn asset_download_response_deserializes_camel_case() {
@@ -403,6 +405,15 @@ mod tests {
assert_eq!(response.url, "http://127.0.0.1:3900/example");
assert_eq!(response.expires_in, 900);
}
+
+ #[test]
+ fn message_conversation_activity_deserializes_outgoing() {
+ let activity: MessageConversationActivity = serde_json::from_str(
+ r#"{"id":"friend_event:1","type":"friend_add","createdAt":"2026-05-25T00:00:00Z","outgoing":true}"#,
+ )
+ .expect("activity should deserialize");
+ assert!(activity.outgoing);
+ }
}
#[derive(Debug, Clone, Serialize)]
diff --git a/server/space/controller/messages.go b/server/space/controller/messages.go
index baa2149973..58ef70864f 100644
--- a/server/space/controller/messages.go
+++ b/server/space/controller/messages.go
@@ -338,6 +338,7 @@ func toMessageConversationActivityResponse(activity repo.SpaceMessageConversatio
ID: activity.ID,
Type: activity.Type,
CreatedAt: formatMicros(activity.CreatedAt),
+ Outgoing: activity.Outgoing,
}
if activity.Message != nil {
resp.Message = toMessageResponse(*activity.Message)
diff --git a/server/space/models/models.go b/server/space/models/models.go
index d0e166bb39..0e0cbf7233 100644
--- a/server/space/models/models.go
+++ b/server/space/models/models.go
@@ -320,6 +320,7 @@ type MessageConversationActivityResponse struct {
ID string `json:"id"`
Type string `json:"type"`
CreatedAt string `json:"createdAt"`
+ Outgoing bool `json:"outgoing,omitempty"`
Message *MessageResponse `json:"message,omitempty"`
Post *MessageConversationPostResponse `json:"post,omitempty"`
}
diff --git a/server/space/repo/messages.go b/server/space/repo/messages.go
index 988ee3b2f0..6f7d2563df 100644
--- a/server/space/repo/messages.go
+++ b/server/space/repo/messages.go
@@ -208,7 +208,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
CASE WHEN m.sender_space_id = $2 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id,
m.message_id,
NULL::bigint AS post_id,
- CASE WHEN m.recipient_space_id = $2 THEN m.created_at ELSE NULL::bigint END AS unread_created_at
+ CASE WHEN m.recipient_space_id = $2 THEN m.created_at ELSE NULL::bigint END AS unread_created_at,
+ FALSE AS is_outgoing
FROM space_messages m
WHERE (m.sender_space_id = $2 OR m.recipient_space_id = $2)
AND (m.sender_id = $1 OR m.recipient_id = $1)
@@ -224,7 +225,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
liker_space.space_id AS friend_space_id,
m.message_id,
NULL::bigint AS post_id,
- ml.created_at AS unread_created_at
+ ml.created_at AS unread_created_at,
+ FALSE AS is_outgoing
FROM space_message_likes ml
JOIN space_messages m ON m.message_id = ml.message_id
JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id
@@ -274,7 +276,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
COALESCE(l.friend_space_id, r.friend_space_id) AS friend_space_id,
r.message_id,
COALESCE(l.post_id, r.post_id) AS post_id,
- GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS unread_created_at
+ GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS unread_created_at,
+ FALSE AS is_outgoing
FROM post_like_events l
FULL OUTER JOIN post_reply_events r
ON r.friend_space_id = l.friend_space_id
@@ -288,13 +291,14 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
END AS activity_type,
'friend_event:' || fe.event_id::text AS activity_id,
fe.created_at AS activity_created_at,
- fe.actor_space_id AS friend_space_id,
+ CASE WHEN fe.actor_space_id = $2 THEN fe.target_space_id ELSE fe.actor_space_id END AS friend_space_id,
NULL::text AS message_id,
NULL::bigint AS post_id,
- fe.created_at AS unread_created_at
+ CASE WHEN fe.target_space_id = $2 THEN fe.created_at ELSE NULL::bigint END AS unread_created_at,
+ fe.actor_space_id = $2 AS is_outgoing
FROM space_friend_events fe
- WHERE fe.target_space_id = $2
- AND fe.actor_space_id <> $2
+ WHERE (fe.target_space_id = $2 OR fe.actor_space_id = $2)
+ AND fe.actor_space_id <> fe.target_space_id
),
candidates AS (
SELECT * FROM message_candidates
@@ -353,6 +357,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
c.activity_type,
c.activity_id,
c.activity_created_at,
+ c.is_outgoing,
(c.unread_created_at IS NOT NULL AND c.unread_created_at > c.read_at) AS unread,
c.sort_created_at,
c.sort_id,
@@ -526,10 +531,11 @@ func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.Context
SELECT
fe.created_at AS activity_created_at,
'friend_event:' || fe.event_id::text AS activity_id,
- fe.actor_space_id AS friend_space_id
+ CASE WHEN fe.actor_space_id = $1 THEN fe.target_space_id ELSE fe.actor_space_id END AS friend_space_id
FROM space_friend_events fe
- WHERE fe.target_space_id = $1
- AND fe.actor_space_id <> $1
+ WHERE (fe.target_space_id = $1 OR fe.actor_space_id = $1)
+ AND fe.actor_space_id <> fe.target_space_id
+
)
SELECT c.activity_created_at
FROM candidates c
@@ -614,11 +620,12 @@ func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerI
SELECT
fe.created_at AS activity_created_at,
'friend_event:' || fe.event_id::text AS activity_id,
- fe.actor_space_id AS friend_space_id,
- fe.created_at AS unread_created_at
+ CASE WHEN fe.actor_space_id = $1 THEN fe.target_space_id ELSE fe.actor_space_id END AS friend_space_id,
+ CASE WHEN fe.target_space_id = $1 THEN fe.created_at ELSE NULL::bigint END AS unread_created_at
FROM space_friend_events fe
- WHERE fe.target_space_id = $1
- AND fe.actor_space_id <> $1
+ WHERE (fe.target_space_id = $1 OR fe.actor_space_id = $1)
+ AND fe.actor_space_id <> fe.target_space_id
+
),
candidates AS (
SELECT * FROM message_candidates
@@ -693,6 +700,7 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })
&rec.LatestActivity.Type,
&rec.LatestActivity.ID,
&rec.LatestActivity.CreatedAt,
+ &rec.LatestActivity.Outgoing,
&rec.Unread,
&rec.SortCreatedAt,
&rec.SortID,
diff --git a/server/space/repo/module.go b/server/space/repo/module.go
index 5df728f72d..60f93394f5 100644
--- a/server/space/repo/module.go
+++ b/server/space/repo/module.go
@@ -156,6 +156,7 @@ type SpaceMessageConversationActivityRecord struct {
ID string
Type string
CreatedAt int64
+ Outgoing bool
Message *SpaceMessageRecord
Post *SpaceMessageConversationPostRecord
}
diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.go
index 167ed73385..f3e3a5cff0 100644
--- a/server/space/repo/module_test.go
+++ b/server/space/repo/module_test.go
@@ -323,6 +323,67 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {
require.Nil(t, conversations[0].LatestActivity.Post)
}
+func TestSpaceFriendEventsCreateConversationForBothSides(t *testing.T) {
+ ctx := context.Background()
+ module := newSpaceTestModule(t)
+
+ aliceID := insertSpaceUser(t, module, "[email protected]", "alice-friend-events-public")
+ bobID := insertSpaceUser(t, module, "[email protected]", "bob-friend-events-public")
+ aliceSpace, err := module.Spaces.CreateSpace(ctx, aliceID, "alice-friend-events", "alice-space-key", "alice-profile")
+ require.NoError(t, err)
+ bobSpace, err := module.Spaces.CreateSpace(ctx, bobID, "bob-friend-events", "bob-space-key", "bob-profile")
+ require.NoError(t, err)
+
+ require.NoError(t, module.Friends.AddFriend(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))
+ setFriendEventCreatedAt(t, module, 1000, "friend_add", bobID, aliceID)
+
+ aliceConversations, _, err := module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, aliceConversations, 1)
+ require.Equal(t, bobSpace.SpaceID, aliceConversations[0].Friend.SpaceID)
+ require.Equal(t, "friend_add", aliceConversations[0].LatestActivity.Type)
+ require.False(t, aliceConversations[0].LatestActivity.Outgoing)
+ require.True(t, aliceConversations[0].Unread)
+
+ bobConversations, _, err := module.Messages.ListConversations(ctx, bobID, bobSpace.SpaceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, bobConversations, 1)
+ require.Equal(t, aliceSpace.SpaceID, bobConversations[0].Friend.SpaceID)
+ require.Equal(t, "friend_add", bobConversations[0].LatestActivity.Type)
+ require.True(t, bobConversations[0].LatestActivity.Outgoing)
+ require.False(t, bobConversations[0].Unread)
+
+ aliceUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
+ require.NoError(t, err)
+ require.True(t, aliceUnread)
+ bobUnread, err := module.Messages.HasUnreadNotifications(ctx, bobID, bobSpace.SpaceID)
+ require.NoError(t, err)
+ require.False(t, bobUnread)
+ bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)
+ require.NoError(t, err)
+ require.Equal(t, int64(1000), bobLatestActivityAt)
+
+ require.NoError(t, module.Friends.DeleteFriendship(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID))
+ setFriendEventCreatedAt(t, module, 2000, "friend_remove", bobID, aliceID)
+
+ aliceConversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, aliceConversations, 1)
+ require.Equal(t, "friend_remove", aliceConversations[0].LatestActivity.Type)
+ require.False(t, aliceConversations[0].LatestActivity.Outgoing)
+ require.True(t, aliceConversations[0].Unread)
+
+ bobConversations, _, err = module.Messages.ListConversations(ctx, bobID, bobSpace.SpaceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, bobConversations, 1)
+ require.Equal(t, "friend_remove", bobConversations[0].LatestActivity.Type)
+ require.True(t, bobConversations[0].LatestActivity.Outgoing)
+ require.False(t, bobConversations[0].Unread)
+ bobLatestActivityAt, err = module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)
+ require.NoError(t, err)
+ require.Equal(t, int64(2000), bobLatestActivityAt)
+}
+
func TestSpaceMessageConversationPreviewPrioritizesUnreadIncomingMessage(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
diff --git a/web/apps/space/src/pages/app/notifications.tsx b/web/apps/space/src/pages/app/notifications.tsx
index ef41ead136..a4b624ed94 100644
--- a/web/apps/space/src/pages/app/notifications.tsx
+++ b/web/apps/space/src/pages/app/notifications.tsx
@@ -18,6 +18,9 @@ import {
import { useSpaceAppState } from "state/spaceAppState";
import { spaceRoutes } from "utils/spaceRoutes";
+const conversationId = (conversation: SpaceMessageConversation) =>
+ conversation.friend.spaceId ?? conversation.friend.id;
+
const Page: React.FC = () => {
const router = useRouter();
const {
@@ -32,9 +35,11 @@ const Page: React.FC = () => {
>([]);
const [isConversationsLoading, setIsConversationsLoading] =
React.useState(true);
- const [isFriendsLoaded, setIsFriendsLoaded] = React.useState(false);
const [isThreadLoading, setIsThreadLoading] = React.useState(false);
const [messages, setMessages] = React.useState<SpaceMessage[]>([]);
+ const [newConversationIds, setNewConversationIds] = React.useState<
+ string[]
+ >([]);
const [selectedFriend, setSelectedFriend] = React.useState<
SpaceMessageConversation["friend"] | undefined
>();
@@ -63,7 +68,25 @@ const Page: React.FC = () => {
setIsConversationsLoading(true);
void loadCurrentMessageConversations()
.then((page) => {
- setConversations(page.items);
+ const unreadConversationIds = page.items
+ .filter((conversation) => conversation.unread)
+ .map(conversationId);
+ setNewConversationIds(unreadConversationIds);
+ setConversations(
+ page.items.map((conversation) =>
+ conversation.unread
+ ? { ...conversation, unread: false }
+ : conversation,
+ ),
+ );
+ if (unreadConversationIds.length == 0) return;
+ void Promise.all(
+ unreadConversationIds.map((friendSpaceId) =>
+ markCurrentNotificationsRead(friendSpaceId),
+ ),
+ ).catch((error: unknown) =>
+ console.warn("Failed to mark notifications read", error),
+ );
})
.catch((error: unknown) =>
console.error("Failed to load message conversations", error),
@@ -127,11 +150,9 @@ const Page: React.FC = () => {
React.useEffect(() => {
if (!profile?.spaceId) return;
- setIsFriendsLoaded(false);
void loadCurrentSpaceFriends(profile.spaceId)
.then((nextFriends) => {
setFriends(nextFriends);
- setIsFriendsLoaded(true);
})
.catch((error: unknown) =>
console.error("Failed to load space friends", error),
@@ -180,12 +201,11 @@ const Page: React.FC = () => {
<SpacePageMeta themeColor={messagesBackground} />
<MessagesScreen
conversations={conversations}
- friends={friends}
isConversationsLoading={isConversationsLoading}
- isFriendsLoaded={isFriendsLoaded}
isThreadLoading={isThreadLoading}
isThreadReadOnly={isThreadReadOnly}
messages={messages}
+ newConversationIds={newConversationIds}
onBack={() => void router.push(spaceRoutes.home)}
onCloseThread={closeConversation}
onOpenSelectedFriendProfile={(friend) =>
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index 139f0cc0af..44bb631f43 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -9,7 +9,6 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Box, Menu, MenuItem, Tooltip } from "@mui/material";
import { keyframes } from "@mui/material/styles";
import { SpaceLoadingSpinner } from "components/SpaceRouteFallback";
-import type { FriendProfile } from "data/friends";
import { formatTimeAgo } from "ente-base/date";
import React from "react";
import type { SetupProfile } from "screens/SetupProfileScreen";
@@ -50,9 +49,7 @@ const sendSpin = keyframes`
interface MessagesScreenProps {
conversations: SpaceMessageConversation[];
- friends: FriendProfile[];
isConversationsLoading?: boolean;
- isFriendsLoaded?: boolean;
isThreadLoading?: boolean;
isThreadReadOnly?: boolean;
messages: SpaceMessage[];
@@ -70,6 +67,7 @@ interface MessagesScreenProps {
) => Promise<void>;
onSendMessage: (spaceId: string, text: string) => Promise<void>;
onSetMessageLiked: (messageId: string, liked: boolean) => Promise<void>;
+ newConversationIds?: string[];
profile: SetupProfile;
selectedFriend?: SpaceMessageConversation["friend"];
}
@@ -198,39 +196,19 @@ const messageLikeTooltipLabel = (
return likerNames.filter(Boolean).join(" and ") || "Liked";
};
-const isCurrentFriend = (
- conversationFriend: SpaceMessageConversation["friend"],
- friends: FriendProfile[],
-) => {
- const conversationSpaceId =
- conversationFriend.spaceId ?? conversationFriend.id;
- const conversationSpaceSlug = conversationFriend.spaceSlug;
- const conversationUsername = conversationFriend.username;
- return friends.some((friend) => {
- const friendSpaceId = friend.spaceId ?? friend.id;
- return (
- friendSpaceId == conversationSpaceId ||
- (conversationSpaceSlug &&
- friend.spaceSlug == conversationSpaceSlug) ||
- friend.username == conversationUsername
- );
- });
-};
-
const conversationPreview = (
conversation: SpaceMessageConversation,
profile: SetupProfile,
- currentlyFriends?: boolean,
) => {
const activity = conversation.latestActivity;
if (activity.type == "friend_add") {
- return currentlyFriends === false
- ? "No longer friends"
+ return activity.outgoing
+ ? "You're now friends"
: "Added you as a friend";
}
if (activity.type == "friend_remove") {
- return currentlyFriends === true
- ? "Friends again"
+ return activity.outgoing
+ ? "You're no longer friends"
: "Removed you as a friend";
}
if (activity.type == "post_like") return "Liked your post";
@@ -276,16 +254,15 @@ const quotedConversationActivityPreview = (
const ConversationPreviewLine: React.FC<{
conversation: SpaceMessageConversation;
- currentlyFriends?: boolean;
profile: SetupProfile;
-}> = ({ conversation, currentlyFriends, profile }) => {
+}> = ({ conversation, profile }) => {
const activity = conversation.latestActivity;
const quotedPreview = quotedConversationActivityPreview(activity);
const previewLineSx = {
color: textSecondary,
fontFamily: '"Inter Variable", Inter, sans-serif',
fontSize: 13,
- fontWeight: conversation.unread ? 700 : 500,
+ fontWeight: 500,
lineHeight: "18px",
minWidth: 0,
overflow: "hidden",
@@ -296,7 +273,7 @@ const ConversationPreviewLine: React.FC<{
if (!quotedPreview) {
return (
<Box sx={previewLineSx}>
- {conversationPreview(conversation, profile, currentlyFriends)}
+ {conversationPreview(conversation, profile)}
</Box>
);
}
@@ -324,6 +301,190 @@ const ConversationPreviewLine: React.FC<{
);
};
+const conversationId = (conversation: SpaceMessageConversation) =>
+ conversation.friend.spaceId ?? conversation.friend.id;
+
+const dayMs = 24 * 60 * 60 * 1000;
+
+const NotificationListItem: React.FC<{
+ conversation: SpaceMessageConversation;
+ onOpenThread: (conversation: SpaceMessageConversation) => void;
+ profile: SetupProfile;
+}> = ({ conversation, onOpenThread, profile }) => {
+ const name =
+ conversation.friend.fullName.trim() || conversation.friend.username;
+ const timestampLabel = formatTimeAgo(
+ microsForTimestamp(conversation.latestActivity.createdAtMs),
+ );
+ const postThumbnailUrl = conversation.latestActivity.post?.imageUrl;
+
+ return (
+ <Box component="li" sx={{ listStyle: "none" }}>
+ <Box
+ component="button"
+ type="button"
+ onClick={() => onOpenThread(conversation)}
+ sx={{
+ alignItems: "center",
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "8px",
+ color: textBase,
+ cursor: "pointer",
+ display: "grid",
+ gap: "10px",
+ gridTemplateColumns: postThumbnailUrl
+ ? "44px minmax(0, 1fr) 44px"
+ : "44px minmax(0, 1fr)",
+ minHeight: 64,
+ p: "8px 0",
+ textAlign: "left",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <Avatar
+ avatarUrl={conversation.friend.avatarUrl}
+ name={name}
+ size={44}
+ />
+ <Box sx={{ minWidth: 0 }}>
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ gap: "4px",
+ minWidth: 0,
+ }}
+ >
+ <Box
+ sx={{
+ flex: "0 1 auto",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 700,
+ lineHeight: "20px",
+ minWidth: 0,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {firstNameFrom(name)}
+ </Box>
+ <Box
+ aria-hidden
+ component="span"
+ sx={{
+ color: textSecondary,
+ flexShrink: 0,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 600,
+ lineHeight: "16px",
+ }}
+ >
+ &middot;
+ </Box>
+ <Box
+ component="time"
+ dateTime={new Date(
+ conversation.latestActivity.createdAtMs,
+ ).toISOString()}
+ sx={{
+ color: textSecondary,
+ flexShrink: 0,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 600,
+ lineHeight: "16px",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {timestampLabel}
+ </Box>
+ </Box>
+ <ConversationPreviewLine
+ conversation={conversation}
+ profile={profile}
+ />
+ </Box>
+ {postThumbnailUrl && (
+ <Box
+ component="img"
+ alt=""
+ src={postThumbnailUrl}
+ sx={{
+ borderRadius: "6px",
+ display: "block",
+ height: 44,
+ objectFit: "cover",
+ objectPosition: "center",
+ width: 44,
+ }}
+ />
+ )}
+ </Box>
+ </Box>
+ );
+};
+
+interface NotificationSectionItem {
+ conversations: SpaceMessageConversation[];
+ title: string;
+}
+
+const NotificationSection: React.FC<{
+ conversations: SpaceMessageConversation[];
+ onOpenThread: (conversation: SpaceMessageConversation) => void;
+ profile: SetupProfile;
+ title: string;
+}> = ({ conversations, onOpenThread, profile, title }) => {
+ if (conversations.length == 0) return null;
+
+ return (
+ <Box component="section" sx={{ mb: "10px" }}>
+ <Box
+ component="h2"
+ sx={{
+ color: textSecondary,
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 700,
+ lineHeight: "18px",
+ m: 0,
+ pb: "4px",
+ pt: "12px",
+ }}
+ >
+ {title}
+ {title == "New" && (
+ <Box component="span" sx={{ color: green, ml: "4px" }}>
+ ({conversations.length})
+ </Box>
+ )}
+ </Box>
+ <Box component="ul" sx={{ listStyle: "none", m: 0, p: 0 }}>
+ {conversations.map((conversation) => (
+ <NotificationListItem
+ key={conversationId(conversation)}
+ conversation={conversation}
+ onOpenThread={onOpenThread}
+ profile={profile}
+ />
+ ))}
+ </Box>
+ </Box>
+ );
+};
+
const sameMessageSender = (
first: SpaceMessage | undefined,
second: SpaceMessage | undefined,
@@ -833,12 +994,11 @@ const MessageBubble: React.FC<{
export const MessagesScreen: React.FC<MessagesScreenProps> = ({
conversations,
- friends,
isConversationsLoading = false,
- isFriendsLoaded = false,
isThreadLoading = false,
isThreadReadOnly = false,
messages,
+ newConversationIds = [],
onBack,
onCloseThread,
onDeleteMessage,
@@ -874,6 +1034,57 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
() => new Map(messages.map((message) => [message.id, message])),
[messages],
);
+ const groupedConversations = React.useMemo(() => {
+ const newIds = new Set(newConversationIds);
+ const now = Date.now();
+ const today = new Date(now);
+ const startOfTodayMs = new Date(
+ today.getFullYear(),
+ today.getMonth(),
+ today.getDate(),
+ ).getTime();
+ const startOfYesterdayMs = new Date(
+ today.getFullYear(),
+ today.getMonth(),
+ today.getDate() - 1,
+ ).getTime();
+ const nextSections: NotificationSectionItem[] = [
+ { title: "New", conversations: [] },
+ { title: "Today", conversations: [] },
+ { title: "Yesterday", conversations: [] },
+ { title: "Last 7 days", conversations: [] },
+ { title: "Last 30 days", conversations: [] },
+ { title: "Older", conversations: [] },
+ ];
+ for (const conversation of conversations) {
+ if (newIds.has(conversationId(conversation))) {
+ nextSections[0]!.conversations.push(conversation);
+ continue;
+ }
+
+ const activityCreatedAtMs = conversation.latestActivity.createdAtMs;
+ if (activityCreatedAtMs >= startOfTodayMs) {
+ nextSections[1]!.conversations.push(conversation);
+ continue;
+ }
+ if (activityCreatedAtMs >= startOfYesterdayMs) {
+ nextSections[2]!.conversations.push(conversation);
+ continue;
+ }
+
+ const ageMs = Math.max(0, now - activityCreatedAtMs);
+ if (ageMs <= 7 * dayMs) {
+ nextSections[3]!.conversations.push(conversation);
+ continue;
+ }
+ if (ageMs <= 30 * dayMs) {
+ nextSections[4]!.conversations.push(conversation);
+ continue;
+ }
+ nextSections[5]!.conversations.push(conversation);
+ }
+ return nextSections;
+ }, [conversations, newConversationIds]);
const isContextMessageLiked = Boolean(
messageContextMenu?.message.viewerLiked,
);
@@ -1723,190 +1934,21 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
</Box>
) : (
<Box
- component="ul"
sx={{
boxSizing: "border-box",
- listStyle: "none",
m: 0,
- p: "12px 16px 28px",
+ p: "6px 16px 28px",
}}
>
- {conversations.map((conversation) => {
- const name =
- conversation.friend.fullName.trim() ||
- conversation.friend.username;
- const currentlyFriends = isCurrentFriend(
- conversation.friend,
- friends,
- );
- const timestampLabel = formatTimeAgo(
- microsForTimestamp(
- conversation.latestActivity
- .createdAtMs,
- ),
- );
- const postThumbnailUrl =
- conversation.latestActivity.post
- ?.imageUrl;
- return (
- <Box
- component="li"
- key={conversation.friend.id}
- sx={{ listStyle: "none" }}
- >
- <Box
- component="button"
- type="button"
- onClick={() =>
- onOpenThread(conversation)
- }
- sx={{
- alignItems: "center",
- appearance: "none",
- bgcolor: "transparent",
- border: 0,
- borderRadius: "8px",
- color: textBase,
- cursor: "pointer",
- display: "grid",
- gap: "10px",
- gridTemplateColumns:
- postThumbnailUrl
- ? "44px minmax(0, 1fr) 44px"
- : "44px minmax(0, 1fr)",
- minHeight: 64,
- p: "8px 0",
- textAlign: "left",
- width: "100%",
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- }}
- >
- <Avatar
- avatarUrl={
- conversation.friend
- .avatarUrl
- }
- name={name}
- size={44}
- />
- <Box sx={{ minWidth: 0 }}>
- <Box
- sx={{
- alignItems:
- "center",
- display: "flex",
- gap: "4px",
- minWidth: 0,
- }}
- >
- <Box
- sx={{
- flex: "0 1 auto",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 700,
- lineHeight:
- "20px",
- minWidth: 0,
- overflow:
- "hidden",
- textOverflow:
- "ellipsis",
- whiteSpace:
- "nowrap",
- }}
- >
- {firstNameFrom(
- name,
- )}
- </Box>
- <Box
- aria-hidden
- component="span"
- sx={{
- color: textSecondary,
- flexShrink: 0,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 12,
- fontWeight: 600,
- lineHeight:
- "16px",
- }}
- >
- &middot;
- </Box>
- <Box
- component="time"
- dateTime={new Date(
- conversation.latestActivity.createdAtMs,
- ).toISOString()}
- sx={{
- color: textSecondary,
- flexShrink: 0,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 12,
- fontWeight: 600,
- lineHeight:
- "16px",
- whiteSpace:
- "nowrap",
- }}
- >
- {timestampLabel}
- </Box>
- {conversation.unread && (
- <Box
- aria-hidden
- sx={{
- bgcolor:
- green,
- borderRadius:
- "50%",
- flexShrink: 0,
- height: 8,
- width: 8,
- }}
- />
- )}
- </Box>
- <ConversationPreviewLine
- conversation={
- conversation
- }
- currentlyFriends={
- isFriendsLoaded
- ? currentlyFriends
- : undefined
- }
- profile={profile}
- />
- </Box>
- {postThumbnailUrl && (
- <Box
- component="img"
- alt=""
- src={postThumbnailUrl}
- sx={{
- borderRadius: "6px",
- display: "block",
- height: 44,
- objectFit: "cover",
- objectPosition:
- "center",
- width: 44,
- }}
- />
- )}
- </Box>
- </Box>
- );
- })}
+ {groupedConversations.map((section) => (
+ <NotificationSection
+ key={section.title}
+ conversations={section.conversations}
+ onOpenThread={onOpenThread}
+ profile={profile}
+ title={section.title}
+ />
+ ))}
</Box>
)}
</>
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 553caa78f1..98ced7ee41 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -96,6 +96,7 @@ interface SpaceMessageConversationActivity {
createdAt: string;
id: string;
message?: SpaceMessageResponse;
+ outgoing?: boolean;
post?: SpaceMessageConversationPostResponse;
type: SpaceMessageConversationActivityType;
}
@@ -242,6 +243,7 @@ export interface SpaceMessageActivity {
createdAtMs: number;
id: string;
message?: SpaceMessage;
+ outgoing: boolean;
post?: SpaceMessageActivityPost;
type: SpaceMessageActivityType;
}
@@ -758,6 +760,7 @@ const messageActivityFromSpaceActivity = async (
createdAtMs: timestampMsFromSpaceDate(activity.createdAt),
id: activity.id,
message,
+ outgoing: Boolean(activity.outgoing),
post,
type: activity.type,
};
diff --git a/web/apps/space/src/state/SpaceAppStateProvider.tsx b/web/apps/space/src/state/SpaceAppStateProvider.tsx
index 86ce23868a..b9197be252 100644
--- a/web/apps/space/src/state/SpaceAppStateProvider.tsx
+++ b/web/apps/space/src/state/SpaceAppStateProvider.tsx
@@ -146,7 +146,7 @@ export const SpaceAppStateProvider: React.FC<React.PropsWithChildren> = ({
const profileErrorMessage = (error: unknown) =>
error instanceof Error
? error.message
- : "Couldn't load your Space profile. Please try again or contact support.";
+ : "Couldn't load this page. Please try again later or contact support.";
const refreshProfile = useCallback(async () => {
const generation = ++profileLoadGenerationRef.current;