Skip to content

armgit / ente

Public Imported from GitHub
0

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

Revert Space notification split

Anand Baburajan3e950ec05a75
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rs
index 8f715f95bc..f9fb1baa3f 100644
--- a/rust/bindings/wasm/ente-wasm/src/space.rs
+++ b/rust/bindings/wasm/ente-wasm/src/space.rs
@@ -2,11 +2,10 @@
use ente_core::http::Error as HttpError;
use ente_space::{
- AccountSpaceCtx, CreatedSpace, CreatedSpaceLink, DecryptedMessage,
- DecryptedPost, DecryptedSpaceProfile, MessageConversationActivity, MessageConversationPost,
- MessageResponse, OpenAccountSpaceCtxInput, OpenSpaceLinkCtxInput, PostResponse,
- ProfileAvatarResponse, ProfileCoverResponse, SpaceActorResponse,
- SpaceError as CoreSpaceError, SpaceLinkCtx, SpaceNotificationResponse,
+ AccountSpaceCtx, CreatedSpace, CreatedSpaceLink, DecryptedMessage, DecryptedPost,
+ DecryptedSpaceProfile, MessageConversationActivity, MessageConversationPost, MessageResponse,
+ OpenAccountSpaceCtxInput, OpenSpaceLinkCtxInput, PostResponse, ProfileAvatarResponse,
+ ProfileCoverResponse, SpaceActorResponse, SpaceError as CoreSpaceError, SpaceLinkCtx,
crypto::{decode_b64, encode_b64},
};
use serde::{Deserialize, Serialize};
@@ -227,9 +226,10 @@ struct MessagePageJs {
#[serde(rename_all = "camelCase")]
struct MessageConversationJs {
friend: ActorJs,
- latest_activity: Option<MessageConversationActivityJs>,
+ latest_activity: MessageConversationActivityJs,
unread: bool,
unread_count: i64,
+ notification_unread: bool,
}
#[derive(Serialize)]
@@ -282,25 +282,6 @@ struct MessageConversationPageJs {
next_cursor: String,
}
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct SpaceNotificationJs {
- id: String,
- #[serde(rename = "type")]
- notification_type: String,
- created_at: String,
- unread: bool,
- actor: ActorJs,
- post: Option<MessageConversationPostJs>,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct SpaceNotificationPageJs {
- items: Vec<SpaceNotificationJs>,
- next_cursor: String,
-}
-
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct FriendJs {
@@ -568,23 +549,6 @@ fn message_conversation_post_to_js(
})
}
-async fn account_notification_to_js(
- ctx: &AccountSpaceCtx,
- notification: SpaceNotificationResponse,
-) -> Result<SpaceNotificationJs, WasmSpaceError> {
- Ok(SpaceNotificationJs {
- id: notification.id,
- notification_type: notification.notification_type,
- created_at: notification.created_at,
- unread: notification.unread,
- actor: account_actor_to_js(ctx, notification.actor).await?,
- post: notification
- .post
- .map(message_conversation_post_to_js)
- .transpose()?,
- })
-}
-
/// Open an authenticated space context for web.
#[wasm_bindgen]
pub async fn space_open_account_ctx(
@@ -862,43 +826,12 @@ impl SpaceAccountCtxHandle {
swb::to_value(&self.inner.unread_status().await?).map_err(Into::into)
}
- /// List post-like and friend notifications.
- pub async fn list_notifications(
- &self,
- cursor: Option<String>,
- limit: Option<i32>,
- ) -> Result<JsValue, WasmSpaceError> {
- let page = self.inner.list_notifications(cursor, limit).await?;
- let mut items = Vec::with_capacity(page.items.len());
- for notification in page.items {
- items.push(account_notification_to_js(&self.inner, notification).await?);
- }
- swb::to_value(&SpaceNotificationPageJs {
- items,
- next_cursor: page.next_cursor,
- })
- .map_err(Into::into)
- }
-
- /// Mark post-like and friend notifications as read.
+ /// Mark notification activity for one friend as read.
pub async fn mark_notifications_read(
- &self,
- read_at: Option<String>,
- ) -> Result<JsValue, WasmSpaceError> {
- swb::to_value(&self.inner.mark_notifications_read(read_at).await?).map_err(Into::into)
- }
-
- /// Mark message-like notifications as read.
- pub async fn mark_message_likes_read(&self) -> Result<JsValue, WasmSpaceError> {
- swb::to_value(&self.inner.mark_message_likes_read().await?).map_err(Into::into)
- }
-
- /// Mark one message conversation as read.
- pub async fn mark_message_thread_read(
&self,
friend_space_id: String,
) -> Result<JsValue, WasmSpaceError> {
- swb::to_value(&self.inner.mark_message_thread_read(friend_space_id).await?)
+ swb::to_value(&self.inner.mark_notifications_read(friend_space_id).await?)
.map_err(Into::into)
}
@@ -1133,17 +1066,16 @@ impl SpaceAccountCtxHandle {
let mut items = Vec::with_capacity(page.items.len());
for conversation in page.items {
let friend = account_actor_to_js(&self.inner, conversation.friend).await?;
- let latest_activity = match conversation.latest_activity {
- Some(activity) => {
- Some(message_conversation_activity_to_js(&self.inner, activity).await?)
- }
- None => None,
- };
items.push(MessageConversationJs {
friend,
- latest_activity,
+ latest_activity: message_conversation_activity_to_js(
+ &self.inner,
+ conversation.latest_activity,
+ )
+ .await?,
unread: conversation.unread,
unread_count: conversation.unread_count,
+ notification_unread: conversation.notification_unread,
});
}
swb::to_value(&MessageConversationPageJs {
diff --git a/rust/space/src/client.rs b/rust/space/src/client.rs
index 5ed2851412..f8608d5b5c 100644
--- a/rust/space/src/client.rs
+++ b/rust/space/src/client.rs
@@ -21,15 +21,14 @@ use crate::transport::{
CreatePostRequest, CreatePostResponse, CreateSpaceRequest, EntityKeyPayload, EntityKeyResponse,
FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse, FriendTargetPayload,
LikeMessageRequest, LikeMessageResponse, LikePostRequest, LikePostResponse,
- ListPostLikersResponse, MarkMessageThreadReadRequest, MarkNotificationsReadRequest,
- MessageConversationPage, MessagePage, MessageResponse, PostObjectPayload, PostPage,
- PostResponse, PresignUploadRequest, PresignUploadResponse, ProfileAvatarPayload,
- ProfileCoverPayload, RefreshFriendSharesRequest, RotateSpaceKeyRequest, ShareUpdatePayload,
- SpaceActorResponse, SpaceFriendResponse, SpaceKeyResponse, SpaceKeyVersionResponse,
- SpaceLinkCreateRequest, SpaceLinkLoginRequest, SpaceLinkLoginResponse, SpaceLinkStatusResponse,
- SpaceLookupResponse, SpaceNotificationPage, SpaceProfileResponse, SpaceUnreadStatusResponse,
- UpdatePostCaptionRequest, UpdateSpaceProfileRequest, UpdateSpaceProfileResponse,
- UpdateSpaceSlugRequest,
+ ListPostLikersResponse, MarkNotificationsReadRequest, MessageConversationPage, MessagePage,
+ MessageResponse, PostObjectPayload, PostPage, PostResponse, PresignUploadRequest,
+ PresignUploadResponse, ProfileAvatarPayload, ProfileCoverPayload, RefreshFriendSharesRequest,
+ RotateSpaceKeyRequest, ShareUpdatePayload, SpaceActorResponse, SpaceFriendResponse,
+ SpaceKeyResponse, SpaceKeyVersionResponse, SpaceLinkCreateRequest, SpaceLinkLoginRequest,
+ SpaceLinkLoginResponse, SpaceLinkStatusResponse, SpaceLookupResponse, SpaceProfileResponse,
+ SpaceUnreadStatusResponse, UpdatePostCaptionRequest, UpdateSpaceProfileRequest,
+ UpdateSpaceProfileResponse, UpdateSpaceSlugRequest,
};
use ente_core::crypto::{keys, sealed};
use ente_core::http::Error as HttpError;
@@ -812,45 +811,7 @@ impl AccountSpaceCtx {
.map_err(Into::into)
}
- pub async fn list_notifications(
- &self,
- cursor: Option<String>,
- limit: Option<i32>,
- ) -> Result<SpaceNotificationPage> {
- let mut query = Vec::new();
- if let Some(value) = cursor.filter(|value| !value.trim().is_empty()) {
- query.push(("cursor", value));
- }
- if let Some(value) = limit {
- query.push(("limit", value.to_string()));
- }
- self.client
- .get_json("/space/notifications", &query)
- .await
- .map_err(Into::into)
- }
-
pub async fn mark_notifications_read(
- &self,
- read_at: Option<String>,
- ) -> Result<SpaceUnreadStatusResponse> {
- self.client
- .post_json(
- "/space/notifications/read",
- &MarkNotificationsReadRequest { read_at },
- )
- .await
- .map_err(Into::into)
- }
-
- pub async fn mark_message_likes_read(&self) -> Result<SpaceUnreadStatusResponse> {
- self.client
- .post_json("/space/messages/likes/read", &())
- .await
- .map_err(Into::into)
- }
-
- pub async fn mark_message_thread_read(
&self,
friend_space_id: impl Into<String>,
) -> Result<SpaceUnreadStatusResponse> {
@@ -863,7 +824,7 @@ impl AccountSpaceCtx {
self.client
.post_json(
"/space/messages/read",
- &MarkMessageThreadReadRequest { friend_space_id },
+ &MarkNotificationsReadRequest { friend_space_id },
)
.await
.map_err(Into::into)
@@ -3406,62 +3367,17 @@ mod tests {
.mock("GET", "/space/unread")
.match_header("x-space-session-token", "space-session-token")
.with_status(200)
- .with_body(
- json!({
- "notificationsUnread": false,
- "messagesUnread": false,
- "messageLikesUnread": false
- })
- .to_string(),
- )
+ .with_body(json!({"notificationsUnread": false}).to_string())
.create_async()
.await;
let notifications_read = server
- .mock("POST", "/space/notifications/read")
- .match_header("x-space-session-token", "space-session-token")
- .match_body(Matcher::JsonString(
- json!({"readAt": "2026-04-16T00:00:00Z"}).to_string(),
- ))
- .with_status(200)
- .with_body(
- json!({
- "notificationsUnread": false,
- "messagesUnread": false,
- "messageLikesUnread": false
- })
- .to_string(),
- )
- .create_async()
- .await;
- let message_likes_read = server
- .mock("POST", "/space/messages/likes/read")
- .match_header("x-space-session-token", "space-session-token")
- .with_status(200)
- .with_body(
- json!({
- "notificationsUnread": false,
- "messagesUnread": false,
- "messageLikesUnread": false
- })
- .to_string(),
- )
- .create_async()
- .await;
- let thread_read = server
.mock("POST", "/space/messages/read")
.match_header("x-space-session-token", "space-session-token")
.match_body(Matcher::JsonString(
json!({"friendSpaceId": "space_friend"}).to_string(),
))
.with_status(200)
- .with_body(
- json!({
- "notificationsUnread": false,
- "messagesUnread": false,
- "messageLikesUnread": false
- })
- .to_string(),
- )
+ .with_body(json!({"notificationsUnread": false}).to_string())
.create_async()
.await;
@@ -3470,31 +3386,15 @@ mod tests {
.await
.expect("unread status should load");
assert!(!unread.notifications_unread);
- assert!(!unread.messages_unread);
- assert!(!unread.message_likes_unread);
assert!(
- !ctx.mark_notifications_read(Some("2026-04-16T00:00:00Z".to_owned()))
+ !ctx.mark_notifications_read("space_friend")
.await
.expect("notifications read")
.notifications_unread
);
- assert!(
- !ctx.mark_message_likes_read()
- .await
- .expect("message likes read")
- .message_likes_unread
- );
- assert!(
- !ctx.mark_message_thread_read("space_friend")
- .await
- .expect("thread read")
- .messages_unread
- );
status.assert_async().await;
notifications_read.assert_async().await;
- message_likes_read.assert_async().await;
- thread_read.assert_async().await;
}
#[tokio::test]
@@ -3700,58 +3600,6 @@ mod tests {
likers.assert_async().await;
}
- #[tokio::test]
- async fn list_notifications_uses_notifications_endpoint() {
- let mut server = Server::new_async().await;
- let ctx = test_account_ctx(&server.url());
- let notifications = server
- .mock("GET", "/space/notifications")
- .match_header("x-space-session-token", "space-session-token")
- .match_query(Matcher::AllOf(vec![
- Matcher::UrlEncoded("cursor".into(), "3000:post_like:1".into()),
- Matcher::UrlEncoded("limit".into(), "10".into()),
- ]))
- .with_status(200)
- .with_body(
- json!({
- "items": [{
- "id": "post_like:42:space_liker",
- "type": "post_like",
- "createdAt": "2026-04-16T00:00:00Z",
- "unread": true,
- "actor": {
- "userId": 8,
- "spaceId": "space_liker",
- "spaceSlug": "liker"
- },
- "post": {
- "postId": 42,
- "spaceId": "space_owner",
- "spaceSlug": "owner",
- "ownerUserId": 7,
- "isDeleted": false
- }
- }],
- "nextCursor": "2000:friend_event:2"
- })
- .to_string(),
- )
- .create_async()
- .await;
-
- let response = ctx
- .list_notifications(Some("3000:post_like:1".to_owned()), Some(10))
- .await
- .expect("notifications should load");
-
- assert_eq!(response.items[0].notification_type, "post_like");
- assert_eq!(response.items[0].actor.space_id, "space_liker");
- assert!(response.items[0].unread);
- assert_eq!(response.items[0].post.as_ref().unwrap().post_id, 42);
- assert_eq!(response.next_cursor, "2000:friend_event:2");
- notifications.assert_async().await;
- }
-
#[tokio::test]
async fn list_space_friends_uses_space_friends_endpoint() {
let mut server = Server::new_async().await;
diff --git a/rust/space/src/lib.rs b/rust/space/src/lib.rs
index 63e52ade0c..fd59e68bca 100644
--- a/rust/space/src/lib.rs
+++ b/rust/space/src/lib.rs
@@ -26,6 +26,5 @@ pub use transport::{
PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, ProfileCoverPayload,
ProfileCoverResponse, SpaceActorResponse, SpaceFriendResponse, SpaceKeyResponse,
SpaceKeyVersionResponse, SpaceLinkLoginResponse, SpaceLinkStatusResponse, SpaceLookupResponse,
- SpaceNotificationPage, SpaceNotificationResponse, SpaceProfileResponse,
- SpaceUnreadStatusResponse,
+ SpaceProfileResponse, SpaceUnreadStatusResponse,
};
diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rs
index 4f253f3fc2..6677f41d41 100644
--- a/rust/space/src/transport.rs
+++ b/rust/space/src/transport.rs
@@ -132,13 +132,6 @@ pub struct LikePostResponse {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarkNotificationsReadRequest {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub read_at: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct MarkMessageThreadReadRequest {
pub friend_space_id: String,
}
@@ -146,8 +139,6 @@ pub struct MarkMessageThreadReadRequest {
#[serde(rename_all = "camelCase")]
pub struct SpaceUnreadStatusResponse {
pub notifications_unread: bool,
- pub messages_unread: bool,
- pub message_likes_unread: bool,
}
#[derive(Debug, Clone, Serialize)]
@@ -210,12 +201,13 @@ pub struct MessagePage {
#[serde(rename_all = "camelCase")]
pub struct MessageConversationResponse {
pub friend: SpaceActorResponse,
- #[serde(default)]
- pub latest_activity: Option<MessageConversationActivity>,
+ pub latest_activity: MessageConversationActivity,
#[serde(default)]
pub unread: bool,
#[serde(default)]
pub unread_count: i64,
+ #[serde(default)]
+ pub notification_unread: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -255,28 +247,6 @@ pub struct MessageConversationPage {
pub next_cursor: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SpaceNotificationResponse {
- pub id: String,
- #[serde(rename = "type")]
- pub notification_type: String,
- pub created_at: String,
- #[serde(default)]
- pub unread: bool,
- pub actor: SpaceActorResponse,
- #[serde(default)]
- pub post: Option<MessageConversationPost>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SpaceNotificationPage {
- pub items: Vec<SpaceNotificationResponse>,
- #[serde(default)]
- pub next_cursor: String,
-}
-
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePostCaptionRequest {
diff --git a/server/migrations/124_space.down.sql b/server/migrations/124_space.down.sql
index 9da54f35e7..6b71729cbe 100644
--- a/server/migrations/124_space.down.sql
+++ b/server/migrations/124_space.down.sql
@@ -30,8 +30,8 @@ DROP TABLE IF EXISTS space_entity_keys;
DROP TRIGGER IF EXISTS update_space_browser_sessions_updated_at ON space_browser_sessions;
DROP TABLE IF EXISTS space_browser_sessions;
-DROP TRIGGER IF EXISTS update_space_read_markers_updated_at ON space_read_markers;
-DROP TABLE IF EXISTS space_read_markers;
+DROP TRIGGER IF EXISTS update_space_notification_read_markers_updated_at ON space_notification_read_markers;
+DROP TABLE IF EXISTS space_notification_read_markers;
DROP TRIGGER IF EXISTS update_spaces_updated_at ON spaces;
DROP TABLE IF EXISTS spaces;
diff --git a/server/migrations/124_space.up.sql b/server/migrations/124_space.up.sql
index df7a05ddc7..0bc75f9d43 100644
--- a/server/migrations/124_space.up.sql
+++ b/server/migrations/124_space.up.sql
@@ -28,28 +28,21 @@ CREATE TRIGGER update_spaces_updated_at
FOR EACH ROW
EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
-CREATE TABLE IF NOT EXISTS space_read_markers (
- user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
+CREATE TABLE IF NOT EXISTS space_notification_read_markers (
+ user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
viewer_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
- scope TEXT NOT NULL,
- friend_space_id TEXT NOT NULL DEFAULT '',
- read_at BIGINT NOT NULL DEFAULT 0,
- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
- updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
- PRIMARY KEY (viewer_space_id, scope, friend_space_id),
- CONSTRAINT chk_space_read_markers_scope CHECK (scope IN ('notifications', 'message_likes', 'message_thread')),
- CONSTRAINT chk_space_read_markers_friend_scope CHECK (
- (scope = 'message_thread' AND friend_space_id <> '')
- OR
- (scope <> 'message_thread' AND friend_space_id = '')
- )
+ friend_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
+ read_at BIGINT NOT NULL DEFAULT 0,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ PRIMARY KEY (viewer_space_id, friend_space_id)
);
-CREATE INDEX IF NOT EXISTS idx_space_read_markers_user
- ON space_read_markers (user_id, scope, read_at DESC);
+CREATE INDEX IF NOT EXISTS idx_space_notification_read_markers_user
+ ON space_notification_read_markers (user_id, read_at DESC);
-CREATE TRIGGER update_space_read_markers_updated_at
- BEFORE UPDATE ON space_read_markers
+CREATE TRIGGER update_space_notification_read_markers_updated_at
+ BEFORE UPDATE ON space_notification_read_markers
FOR EACH ROW
EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
diff --git a/server/space/api/messages.go b/server/space/api/messages.go
index 5602c3df6c..9d85b64600 100644
--- a/server/space/api/messages.go
+++ b/server/space/api/messages.go
@@ -51,16 +51,6 @@ func (h *Handlers) ListMessages(c *gin.Context) {
respondJSON(c, resp, err)
}
-func (h *Handlers) ListNotifications(c *gin.Context) {
- var req models.ListNotificationsRequest
- if err := c.ShouldBindQuery(&req); err != nil {
- respondJSON(c, nil, ente.ErrBadRequest)
- return
- }
- resp, err := h.Module.Messages.ListNotifications(c, req)
- respondJSON(c, resp, err)
-}
-
func (h *Handlers) ListMessageThread(c *gin.Context) {
var req models.ListMessageThreadRequest
if err := c.ShouldBindQuery(&req); err != nil {
diff --git a/server/space/api/read_markers.go b/server/space/api/read_markers.go
index 8da95911d3..44c95ce2bf 100644
--- a/server/space/api/read_markers.go
+++ b/server/space/api/read_markers.go
@@ -1,9 +1,6 @@
package api
import (
- "errors"
- "io"
-
"github.com/ente-io/museum/ente"
"github.com/ente-io/museum/space/models"
"github.com/gin-gonic/gin"
@@ -16,25 +13,10 @@ func (h *Handlers) GetUnreadStatus(c *gin.Context) {
func (h *Handlers) MarkNotificationsRead(c *gin.Context) {
var req models.MarkNotificationsReadRequest
- if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
- respondJSON(c, nil, ente.ErrBadRequest)
- return
- }
- resp, err := h.Module.Read.MarkNotificationsRead(c, req)
- respondJSON(c, resp, err)
-}
-
-func (h *Handlers) MarkMessageLikesRead(c *gin.Context) {
- resp, err := h.Module.Read.MarkMessageLikesRead(c)
- respondJSON(c, resp, err)
-}
-
-func (h *Handlers) MarkMessageThreadRead(c *gin.Context) {
- var req models.MarkMessageThreadReadRequest
if err := c.ShouldBindJSON(&req); err != nil {
respondJSON(c, nil, ente.ErrBadRequest)
return
}
- resp, err := h.Module.Read.MarkMessageThreadRead(c, req)
+ resp, err := h.Module.Read.MarkNotificationsRead(c, req)
respondJSON(c, resp, err)
}
diff --git a/server/space/api/register.go b/server/space/api/register.go
index c7db59b4f0..d909f79f60 100644
--- a/server/space/api/register.go
+++ b/server/space/api/register.go
@@ -19,11 +19,8 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
privateAPI.POST("/space/posts/:postID/like", handlers.TogglePostLike)
privateAPI.POST("/space/posts/:postID/reply", handlers.ReplyToPost)
privateAPI.DELETE("/space/posts/:postID", handlers.DeletePost)
- privateAPI.GET("/space/notifications", handlers.ListNotifications)
- privateAPI.POST("/space/notifications/read", handlers.MarkNotificationsRead)
privateAPI.GET("/space/messages", handlers.ListMessages)
- privateAPI.POST("/space/messages/likes/read", handlers.MarkMessageLikesRead)
- privateAPI.POST("/space/messages/read", handlers.MarkMessageThreadRead)
+ privateAPI.POST("/space/messages/read", handlers.MarkNotificationsRead)
privateAPI.GET("/space/messages/:spaceID", handlers.ListMessageThread)
privateAPI.POST("/space/messages/:spaceID", handlers.CreateMessage)
privateAPI.POST("/space/message/:messageID/like", handlers.ToggleMessageLike)
diff --git a/server/space/controller/messages.go b/server/space/controller/messages.go
index 8b913ad232..de6a042292 100644
--- a/server/space/controller/messages.go
+++ b/server/space/controller/messages.go
@@ -140,40 +140,17 @@ func (c *MessagesController) List(ctx *gin.Context, req models.ListMessagesReque
}
items := make([]models.MessageConversationResponse, 0, len(conversations))
for _, conversation := range conversations {
- item := models.MessageConversationResponse{
- Friend: toActorResponse(conversation.Friend, true),
- Unread: conversation.Unread,
- UnreadCount: conversation.UnreadCount,
- }
- if strings.TrimSpace(conversation.LatestActivity.Type) != "" {
- latestActivity := toMessageConversationActivityResponse(conversation.LatestActivity)
- item.LatestActivity = &latestActivity
- }
- items = append(items, item)
+ items = append(items, models.MessageConversationResponse{
+ Friend: toActorResponse(conversation.Friend, true),
+ LatestActivity: toMessageConversationActivityResponse(conversation.LatestActivity),
+ Unread: conversation.Unread,
+ UnreadCount: conversation.UnreadCount,
+ NotificationUnread: conversation.NotificationUnread,
+ })
}
return &models.MessageConversationPage{Items: items, NextCursor: nextCursor}, nil
}
-func (c *MessagesController) ListNotifications(ctx *gin.Context, req models.ListNotificationsRequest) (*models.SpaceNotificationPage, error) {
- userID, err := c.auth.requireUser(ctx)
- if err != nil {
- return nil, err
- }
- viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)
- if err != nil {
- return nil, err
- }
- notifications, nextCursor, err := c.MessagesRepo.ListNotifications(ctx.Request.Context(), viewerSpace.SpaceID, req.Cursor, req.Limit)
- if err != nil {
- return nil, err
- }
- items := make([]models.SpaceNotificationResponse, 0, len(notifications))
- for _, notification := range notifications {
- items = append(items, toSpaceNotificationResponse(notification))
- }
- return &models.SpaceNotificationPage{Items: items, NextCursor: nextCursor}, nil
-}
-
func (c *MessagesController) ListThread(ctx *gin.Context, targetSpaceID string, req models.ListMessageThreadRequest) (*models.MessagePage, error) {
userID, err := c.auth.requireUser(ctx)
if err != nil {
@@ -373,42 +350,23 @@ func toMessageConversationActivityResponse(activity repo.SpaceMessageConversatio
resp.Message = toMessageResponse(*activity.Message)
}
if activity.Post != nil {
- resp.Post = toMessageConversationPostResponse(*activity.Post)
- }
- return resp
-}
-
-func toSpaceNotificationResponse(notification repo.SpaceNotificationRecord) models.SpaceNotificationResponse {
- resp := models.SpaceNotificationResponse{
- ID: notification.ID,
- Type: notification.Type,
- CreatedAt: formatMicros(notification.CreatedAt),
- Unread: notification.Unread,
- Actor: toActorResponse(notification.Actor, true),
- }
- if notification.Post != nil {
- resp.Post = toMessageConversationPostResponse(*notification.Post)
- }
- return resp
-}
-
-func toMessageConversationPostResponse(post repo.SpaceMessageConversationPostRecord) *models.MessageConversationPostResponse {
- resp := &models.MessageConversationPostResponse{
- PostID: post.PostID,
- SpaceID: post.SpaceID,
- SpaceSlug: post.SpaceSlug,
- OwnerUserID: post.OwnerID,
- IsDeleted: post.IsDeleted,
- }
- if post.ObjectKey.Valid {
- resp.Objects = []models.PostObjectPayload{
- toPostObjectPayload(repo.SpacePostAssetRecord{
- PostID: post.PostID,
- ObjectKey: post.ObjectKey.String,
- Size: post.ObjectSize,
- Position: int(post.ObjectPosition.Int64),
- MetadataCipher: post.ObjectMetadataCipher.String,
- }),
+ resp.Post = &models.MessageConversationPostResponse{
+ PostID: activity.Post.PostID,
+ SpaceID: activity.Post.SpaceID,
+ SpaceSlug: activity.Post.SpaceSlug,
+ OwnerUserID: activity.Post.OwnerID,
+ IsDeleted: activity.Post.IsDeleted,
+ }
+ if activity.Post.ObjectKey.Valid {
+ resp.Post.Objects = []models.PostObjectPayload{
+ toPostObjectPayload(repo.SpacePostAssetRecord{
+ PostID: activity.Post.PostID,
+ ObjectKey: activity.Post.ObjectKey.String,
+ Size: activity.Post.ObjectSize,
+ Position: int(activity.Post.ObjectPosition.Int64),
+ MetadataCipher: activity.Post.ObjectMetadataCipher.String,
+ }),
+ }
}
}
return resp
diff --git a/server/space/controller/read_markers.go b/server/space/controller/read_markers.go
index ec99ce7219..206f27fee8 100644
--- a/server/space/controller/read_markers.go
+++ b/server/space/controller/read_markers.go
@@ -4,7 +4,6 @@ import (
"database/sql"
"errors"
"strings"
- "time"
"github.com/ente-io/museum/ente"
"github.com/ente-io/museum/space/models"
@@ -28,88 +27,16 @@ func (c *ReadMarkersController) GetUnreadStatus(ctx *gin.Context) (*models.Space
if err != nil {
return nil, err
}
- notificationsUnread, err := c.MessagesRepo.HasUnreadNotifications(ctx.Request.Context(), viewerSpace.SpaceID)
- if err != nil {
- return nil, err
- }
- messagesUnread, err := c.MessagesRepo.HasUnreadMessages(ctx.Request.Context(), viewerSpace.SpaceID)
- if err != nil {
- return nil, err
- }
- messageLikesUnread, err := c.MessagesRepo.HasUnreadMessageLikes(ctx.Request.Context(), viewerSpace.SpaceID)
+ notificationsUnread, err := c.MessagesRepo.HasUnreadNotifications(ctx.Request.Context(), userID, viewerSpace.SpaceID)
if err != nil {
return nil, err
}
return &models.SpaceUnreadStatusResponse{
NotificationsUnread: notificationsUnread,
- MessagesUnread: messagesUnread,
- MessageLikesUnread: messageLikesUnread,
}, nil
}
func (c *ReadMarkersController) MarkNotificationsRead(ctx *gin.Context, req models.MarkNotificationsReadRequest) (*models.SpaceUnreadStatusResponse, error) {
- userID, err := c.auth.requireUser(ctx)
- if err != nil {
- return nil, err
- }
- viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)
- if err != nil {
- return nil, err
- }
- readAt, hasReadAt, err := parseNotificationReadAt(req.ReadAt)
- if err != nil {
- return nil, err
- }
- if !hasReadAt {
- readAt, err = c.MessagesRepo.GetLatestNotificationActivityAt(ctx.Request.Context(), viewerSpace.SpaceID)
- if err != nil {
- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
- return c.GetUnreadStatus(ctx)
- }
- return nil, err
- }
- }
- if err := c.ReadMarkersRepo.UpsertNotificationsReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, readAt); err != nil {
- return nil, err
- }
- return c.GetUnreadStatus(ctx)
-}
-
-func parseNotificationReadAt(value string) (int64, bool, error) {
- value = strings.TrimSpace(value)
- if value == "" {
- return 0, false, nil
- }
- readAt, err := time.Parse(time.RFC3339Nano, value)
- if err != nil {
- return 0, true, ente.NewBadRequestWithMessage("invalid readAt")
- }
- return readAt.UnixMicro(), true, nil
-}
-
-func (c *ReadMarkersController) MarkMessageLikesRead(ctx *gin.Context) (*models.SpaceUnreadStatusResponse, error) {
- userID, err := c.auth.requireUser(ctx)
- if err != nil {
- return nil, err
- }
- viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)
- if err != nil {
- return nil, err
- }
- readAt, err := c.MessagesRepo.GetLatestMessageLikeActivityAt(ctx.Request.Context(), viewerSpace.SpaceID)
- if err != nil {
- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
- return c.GetUnreadStatus(ctx)
- }
- return nil, err
- }
- if err := c.ReadMarkersRepo.UpsertMessageLikesReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, readAt); err != nil {
- return nil, err
- }
- return c.GetUnreadStatus(ctx)
-}
-
-func (c *ReadMarkersController) MarkMessageThreadRead(ctx *gin.Context, req models.MarkMessageThreadReadRequest) (*models.SpaceUnreadStatusResponse, error) {
userID, err := c.auth.requireUser(ctx)
if err != nil {
return nil, err
@@ -121,14 +48,14 @@ func (c *ReadMarkersController) MarkMessageThreadRead(ctx *gin.Context, req mode
if err != nil {
return nil, err
}
- readAt, err := c.MessagesRepo.GetLatestMessageThreadActivityAt(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID)
+ readAt, err := c.MessagesRepo.GetLatestConversationActivityAt(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID)
if err != nil {
if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
return nil, ente.ErrPermissionDenied
}
return nil, err
}
- if err := c.ReadMarkersRepo.UpsertMessageThreadReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID, readAt); err != nil {
+ if err := c.ReadMarkersRepo.UpsertNotificationReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID, readAt); err != nil {
return nil, err
}
return c.GetUnreadStatus(ctx)
diff --git a/server/space/models/models.go b/server/space/models/models.go
index d4ac05907d..272188ac9d 100644
--- a/server/space/models/models.go
+++ b/server/space/models/models.go
@@ -58,11 +58,6 @@ type ListMessagesRequest struct {
Limit int `form:"limit"`
}
-type ListNotificationsRequest struct {
- Cursor string `form:"cursor"`
- Limit int `form:"limit"`
-}
-
type ListMessageThreadRequest struct {
Cursor string `form:"cursor"`
Limit int `form:"limit"`
@@ -351,10 +346,11 @@ type MessagePage struct {
}
type MessageConversationResponse struct {
- Friend SpaceActorResponse `json:"friend"`
- LatestActivity *MessageConversationActivityResponse `json:"latestActivity,omitempty"`
- Unread bool `json:"unread"`
- UnreadCount int64 `json:"unreadCount"`
+ Friend SpaceActorResponse `json:"friend"`
+ LatestActivity MessageConversationActivityResponse `json:"latestActivity"`
+ Unread bool `json:"unread"`
+ UnreadCount int64 `json:"unreadCount"`
+ NotificationUnread bool `json:"notificationUnread"`
}
type MessageConversationActivityResponse struct {
@@ -380,20 +376,6 @@ type MessageConversationPage struct {
NextCursor string `json:"nextCursor,omitempty"`
}
-type SpaceNotificationResponse struct {
- ID string `json:"id"`
- Type string `json:"type"`
- CreatedAt string `json:"createdAt"`
- Unread bool `json:"unread"`
- Actor SpaceActorResponse `json:"actor"`
- Post *MessageConversationPostResponse `json:"post,omitempty"`
-}
-
-type SpaceNotificationPage struct {
- Items []SpaceNotificationResponse `json:"items"`
- NextCursor string `json:"nextCursor,omitempty"`
-}
-
type PostObjectPayload struct {
ObjectKey string `json:"objectKey"`
Size int64 `json:"size,omitempty"`
@@ -418,15 +400,9 @@ type PostResponse struct {
type SpaceUnreadStatusResponse struct {
NotificationsUnread bool `json:"notificationsUnread"`
- MessagesUnread bool `json:"messagesUnread"`
- MessageLikesUnread bool `json:"messageLikesUnread"`
}
type MarkNotificationsReadRequest struct {
- ReadAt string `json:"readAt,omitempty"`
-}
-
-type MarkMessageThreadReadRequest struct {
FriendSpaceID string `json:"friendSpaceId"`
}
diff --git a/server/space/repo/messages.go b/server/space/repo/messages.go
index ff3347e650..db749f32ab 100644
--- a/server/space/repo/messages.go
+++ b/server/space/repo/messages.go
@@ -198,39 +198,54 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
cursorID = id
}
rows, err := r.DB.QueryContext(ctx, `
- WITH message_candidates AS (
- SELECT
- 'message' AS activity_type,
- 'message:' || m.message_id AS activity_id,
- m.created_at AS activity_created_at,
- 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,
- m.sender_space_id = $2 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)
- AND m.is_deleted = FALSE
- AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $2)
+ WITH message_candidates AS (
+ SELECT
+ 'message' AS activity_type,
+ 'message:' || m.message_id AS activity_id,
+ m.created_at AS activity_created_at,
+ 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 notification_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)
+ AND m.is_deleted = FALSE
+ AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $2)
UNION ALL
SELECT
- 'message_like' AS activity_type,
- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
- ml.created_at AS activity_created_at,
- liker_space.space_id AS friend_space_id,
- m.message_id,
- NULL::bigint AS post_id,
- 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
- WHERE m.sender_space_id = $2
+ 'message_like' AS activity_type,
+ 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
+ ml.created_at AS activity_created_at,
+ liker_space.space_id AS friend_space_id,
+ m.message_id,
+ NULL::bigint AS post_id,
+ ml.created_at AS notification_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
+ WHERE m.sender_space_id = $2
AND m.recipient_space_id = ml.actor_space_id
AND ml.actor_space_id <> $2
AND m.is_deleted = FALSE
),
+ post_like_events AS (
+ SELECT
+ actor_space.space_id AS friend_space_id,
+ p.post_id,
+ MAX(pl.created_at) AS liked_at
+ FROM space_post_likes pl
+ JOIN space_posts p ON p.post_id = pl.post_id
+ JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
+ WHERE p.space_id = $2
+ AND pl.actor_space_id <> $2
+ AND p.is_deleted = FALSE
+ GROUP BY actor_space.space_id, p.post_id
+ ),
post_reply_events AS (
SELECT DISTINCT ON (m.sender_space_id, m.reply_post_id)
m.sender_space_id AS friend_space_id,
@@ -247,134 +262,143 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
AND p.space_id = $2
ORDER BY m.sender_space_id, m.reply_post_id, m.created_at DESC, m.message_id DESC
),
- post_reply_candidates AS (
- SELECT
- 'post_reply' AS activity_type,
- 'post_reply:' || r.message_id AS activity_id,
- r.replied_at AS activity_created_at,
- r.friend_space_id,
- r.message_id,
- r.post_id,
- FALSE AS is_outgoing
- FROM post_reply_events r
- ),
- candidates AS (
- SELECT * FROM message_candidates
- UNION ALL
- SELECT * FROM post_reply_candidates
- ),
- current_friends AS (
- SELECT
- fs.friend_space_id,
- fs.created_at AS friendship_created_at
- FROM space_friend_shares fs
- WHERE fs.space_id = $2
- ),
- conversation_friends AS (
- SELECT friend_space_id FROM candidates
- UNION
- SELECT friend_space_id FROM current_friends
- ),
- readable_activities AS (
- SELECT
- m.sender_space_id AS friend_space_id,
- m.created_at AS readable_created_at
- FROM space_messages m
- WHERE m.recipient_space_id = $2
- AND m.sender_space_id <> $2
- AND m.kind = 'regular'
- AND m.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- m.sender_space_id AS friend_space_id,
- m.created_at AS readable_created_at
- FROM space_messages m
- JOIN space_posts p ON p.post_id = m.reply_post_id
- WHERE m.recipient_space_id = $2
- AND m.sender_space_id <> $2
- AND m.kind = 'post_reply'
- AND m.is_deleted = FALSE
- AND m.reply_post_id IS NOT NULL
- AND p.space_id = $2
- ),
- readable_unread_counts AS (
- SELECT
- ra.friend_space_id,
- COUNT(*) AS unread_count
- FROM readable_activities ra
- LEFT JOIN space_read_markers nrm
- ON nrm.viewer_space_id = $2
- AND nrm.scope = 'message_thread'
- AND nrm.friend_space_id = ra.friend_space_id
- WHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)
- GROUP BY ra.friend_space_id
- ),
- message_like_unread_counts AS (
- SELECT
- ml.actor_space_id AS friend_space_id,
- COUNT(*) AS unread_count
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- LEFT JOIN space_read_markers nrm
- ON nrm.viewer_space_id = $2
- AND nrm.scope = 'message_likes'
- AND nrm.friend_space_id = ''
- WHERE m.sender_space_id = $2
- AND m.recipient_space_id = ml.actor_space_id
- AND ml.actor_space_id <> $2
- AND m.is_deleted = FALSE
- AND ml.created_at > COALESCE(nrm.read_at, 0)
- GROUP BY ml.actor_space_id
- ),
- latest_activities AS (
- SELECT DISTINCT ON (friend_space_id)
- friend_space_id,
- activity_type,
- activity_id,
- activity_created_at,
- message_id,
- post_id,
- is_outgoing
- FROM candidates
+ post_like_candidates AS (
+ SELECT
+ 'post_like' AS activity_type,
+ 'post_like:' || l.post_id::text || ':' || l.friend_space_id AS activity_id,
+ l.liked_at AS activity_created_at,
+ l.friend_space_id,
+ NULL::text AS message_id,
+ l.post_id,
+ l.liked_at AS notification_created_at,
+ FALSE AS is_outgoing
+ FROM post_like_events l
+ ),
+ post_reply_candidates AS (
+ SELECT
+ 'post_reply' AS activity_type,
+ 'post_reply:' || r.message_id AS activity_id,
+ r.replied_at AS activity_created_at,
+ r.friend_space_id,
+ r.message_id,
+ r.post_id,
+ r.replied_at AS notification_created_at,
+ FALSE AS is_outgoing
+ FROM post_reply_events r
+ ),
+ friend_candidates AS (
+ SELECT
+ CASE fe.event_type
+ WHEN 'friend_remove' THEN 'friend_remove'
+ ELSE 'friend_add'
+ END AS activity_type,
+ 'friend_event:' || fe.event_id::text AS activity_id,
+ fe.created_at AS activity_created_at,
+ 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,
+ CASE WHEN fe.target_space_id = $2 THEN fe.created_at ELSE NULL::bigint END AS notification_created_at,
+ fe.actor_space_id = $2 AS is_outgoing
+ FROM space_friend_events fe
+ 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
+ UNION ALL
+ SELECT * FROM post_like_candidates
+ UNION ALL
+ SELECT * FROM post_reply_candidates
+ UNION ALL
+ SELECT * FROM friend_candidates
+ ),
+ readable_activities AS (
+ SELECT
+ m.sender_space_id AS friend_space_id,
+ m.created_at AS readable_created_at
+ FROM space_messages m
+ WHERE m.recipient_space_id = $2
+ AND m.sender_space_id <> $2
+ AND m.kind = 'regular'
+ AND m.is_deleted = FALSE
+
+ UNION ALL
+
+ SELECT
+ m.sender_space_id AS friend_space_id,
+ m.created_at AS readable_created_at
+ FROM space_messages m
+ JOIN space_posts p ON p.post_id = m.reply_post_id
+ WHERE m.recipient_space_id = $2
+ AND m.sender_space_id <> $2
+ AND m.kind = 'post_reply'
+ AND m.is_deleted = FALSE
+ AND m.reply_post_id IS NOT NULL
+ AND p.space_id = $2
+ ),
+ readable_unread_counts AS (
+ SELECT
+ ra.friend_space_id,
+ COUNT(*) AS unread_count
+ FROM readable_activities ra
+ LEFT JOIN space_notification_read_markers nrm
+ ON nrm.viewer_space_id = $2
+ AND nrm.friend_space_id = ra.friend_space_id
+ WHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)
+ GROUP BY ra.friend_space_id
+ ),
+ latest_activities AS (
+ SELECT DISTINCT ON (friend_space_id)
+ friend_space_id,
+ activity_created_at AS sort_created_at,
+ activity_id AS sort_id
+ FROM candidates
ORDER BY friend_space_id, activity_created_at DESC, activity_id DESC
- ),
- conversations AS (
- SELECT
- cf.friend_space_id,
- COALESCE(la.activity_type, '') AS activity_type,
- COALESCE(la.activity_id, '') AS activity_id,
- COALESCE(la.activity_created_at, 0) AS activity_created_at,
- la.message_id,
- la.post_id,
- COALESCE(la.is_outgoing, FALSE) AS is_outgoing,
- COALESCE(ruc.unread_count, 0) AS unread_count,
- COALESCE(mluc.unread_count, 0) AS message_like_unread_count,
- COALESCE(la.activity_created_at, current_friends.friendship_created_at, 0) AS sort_created_at,
- COALESCE(la.activity_id, 'friend:' || cf.friend_space_id) AS sort_id
- FROM conversation_friends cf
- LEFT JOIN current_friends
- ON current_friends.friend_space_id = cf.friend_space_id
- LEFT JOIN latest_activities la
- ON la.friend_space_id = cf.friend_space_id
- LEFT JOIN readable_unread_counts ruc
- ON ruc.friend_space_id = cf.friend_space_id
- LEFT JOIN message_like_unread_counts mluc
- ON mluc.friend_space_id = cf.friend_space_id
+ ),
+ candidates_with_read_state AS (
+ SELECT
+ c.*,
+ COALESCE(nrm.read_at, 0) AS read_at,
+ COALESCE(ruc.unread_count, 0) AS unread_count,
+ la.sort_created_at,
+ la.sort_id,
+ (
+ c.notification_created_at IS NOT NULL
+ AND c.notification_created_at > COALESCE(nrm.read_at, 0)
+ ) AS notification_unread
+ FROM candidates c
+ JOIN latest_activities la ON la.friend_space_id = c.friend_space_id
+ LEFT JOIN space_notification_read_markers nrm
+ ON nrm.viewer_space_id = $2
+ AND nrm.friend_space_id = c.friend_space_id
+ LEFT JOIN readable_unread_counts ruc
+ ON ruc.friend_space_id = c.friend_space_id
+ ),
+ ranked AS (
+ SELECT
+ c.*,
+ (c.unread_count > 0) AS conversation_unread,
+ c.unread_count AS conversation_unread_count,
+ BOOL_OR(c.notification_unread) OVER (PARTITION BY c.friend_space_id) AS conversation_notification_unread,
+ ROW_NUMBER() OVER (
+ PARTITION BY c.friend_space_id
+ ORDER BY c.activity_created_at DESC, c.activity_id DESC
+ ) AS rn
+ FROM candidates_with_read_state c
)
SELECT
c.activity_type,
c.activity_id,
- c.activity_created_at,
- c.is_outgoing,
- (c.unread_count > 0 OR c.message_like_unread_count > 0) AS unread,
- c.unread_count AS unread_count,
- c.sort_created_at,
+ c.activity_created_at,
+ c.is_outgoing,
+ c.conversation_unread AS unread,
+ c.conversation_unread_count AS unread_count,
+ c.conversation_notification_unread AS notification_unread,
+ c.sort_created_at,
c.sort_id,
- friend_space.owner_id,
- friend_space.space_id,
- friend_space.space_slug,
+ friend_space.owner_id,
+ friend_space.space_id,
+ friend_space.space_slug,
friend_space.public_key,
friend_space.current_version,
friend_space.encrypted_profile,
@@ -433,7 +457,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
asset.size AS post_object_size,
asset.position AS post_object_position,
asset.metadata_cipher AS post_object_metadata_cipher
- FROM conversations c
+ FROM ranked c
JOIN spaces friend_space ON friend_space.space_id = c.friend_space_id
LEFT JOIN space_messages m ON m.message_id = c.message_id
LEFT JOIN spaces sender_space ON sender_space.space_id = m.sender_space_id
@@ -447,10 +471,11 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
ORDER BY position ASC, asset_id ASC
LIMIT 1
) asset ON TRUE
- WHERE ($3::bigint IS NULL OR (c.sort_created_at, c.sort_id) < ($3::bigint, $4::text))
+ WHERE c.rn = 1
+ AND ($3::bigint IS NULL OR (c.sort_created_at, c.sort_id) < ($3::bigint, $4::text))
ORDER BY c.sort_created_at DESC, c.sort_id DESC
LIMIT $5
- `, viewerID, viewerSpaceID, cursorCreatedAt, cursorID, limit+1)
+ `, viewerID, viewerSpaceID, cursorCreatedAt, cursorID, limit+1)
if err != nil {
return nil, "", stacktrace.Propagate(err, "")
}
@@ -474,116 +499,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
return out, nextCursor, nil
}
-func (r *MessagesRepository) ListNotifications(ctx context.Context, viewerSpaceID string, cursor string, limit int) ([]SpaceNotificationRecord, string, error) {
- limit = optionalInt(limit, 50)
- if limit > 100 {
- limit = 100
- }
- var cursorCreatedAt any
- var cursorID any
- if createdAt, id, ok := parseMessageCursor(cursor); ok {
- cursorCreatedAt = createdAt
- cursorID = id
- }
- rows, err := r.DB.QueryContext(ctx, `
- WITH notification_candidates AS (
- SELECT
- 'post_like' AS activity_type,
- 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id,
- pl.created_at AS activity_created_at,
- pl.actor_space_id AS actor_space_id,
- pl.post_id
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- WHERE p.space_id = $1
- AND pl.actor_space_id <> $1
- AND p.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- CASE fe.event_type
- WHEN 'friend_remove' THEN 'friend_remove'
- ELSE 'friend_add'
- 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 actor_space_id,
- NULL::bigint AS post_id
- FROM space_friend_events fe
- WHERE fe.target_space_id = $1
- AND fe.actor_space_id <> fe.target_space_id
- )
- SELECT
- n.activity_type,
- n.activity_id,
- n.activity_created_at,
- n.activity_created_at > COALESCE(nrm.read_at, 0) AS unread,
- n.activity_created_at AS sort_created_at,
- n.activity_id AS sort_id,
- actor_space.owner_id,
- actor_space.space_id,
- actor_space.space_slug,
- actor_space.public_key,
- actor_space.current_version,
- actor_space.encrypted_profile,
- actor_space.avatar_object_key,
- actor_space.avatar_size,
- actor_space.updated_at,
- (SELECT COUNT(*) FROM space_friend_shares fs WHERE fs.space_id = actor_space.space_id) AS actor_friends,
- (SELECT COUNT(*) FROM space_posts ap WHERE ap.space_id = actor_space.space_id AND ap.is_deleted = FALSE) AS actor_posts,
- p.post_id,
- COALESCE(p.space_id, '') AS post_space_id,
- COALESCE(post_space.space_slug, '') AS post_space_slug,
- COALESCE(p.owner_id, 0) AS post_owner_id,
- COALESCE(p.is_deleted, FALSE) AS post_is_deleted,
- asset.object_key AS post_object_key,
- asset.size AS post_object_size,
- asset.position AS post_object_position,
- asset.metadata_cipher AS post_object_metadata_cipher
- FROM notification_candidates n
- JOIN spaces actor_space ON actor_space.space_id = n.actor_space_id
- LEFT JOIN space_read_markers nrm
- ON nrm.viewer_space_id = $1
- AND nrm.scope = 'notifications'
- AND nrm.friend_space_id = ''
- LEFT JOIN space_posts p ON p.post_id = n.post_id
- LEFT JOIN spaces post_space ON post_space.space_id = p.space_id
- LEFT JOIN LATERAL (
- SELECT object_key, size, position, metadata_cipher
- FROM space_post_assets
- WHERE post_id = p.post_id AND p.is_deleted = FALSE
- ORDER BY position ASC, asset_id ASC
- LIMIT 1
- ) asset ON TRUE
- WHERE ($2::bigint IS NULL OR (n.activity_created_at, n.activity_id) < ($2::bigint, $3::text))
- ORDER BY n.activity_created_at DESC, n.activity_id DESC
- LIMIT $4
- `, strings.TrimSpace(viewerSpaceID), cursorCreatedAt, cursorID, limit+1)
- if err != nil {
- return nil, "", stacktrace.Propagate(err, "")
- }
- defer rows.Close()
- out := make([]SpaceNotificationRecord, 0, limit+1)
- for rows.Next() {
- notification, err := scanSpaceNotificationRecord(rows)
- if err != nil {
- return nil, "", err
- }
- out = append(out, *notification)
- }
- if err := rows.Err(); err != nil {
- return nil, "", stacktrace.Propagate(err, "")
- }
- nextCursor := ""
- if len(out) > limit {
- nextCursor = formatSpaceNotificationCursor(out[limit-1])
- out = out[:limit]
- }
- return out, nextCursor, nil
-}
-
-func (r *MessagesRepository) GetLatestMessageThreadActivityAt(ctx context.Context, viewerID int64, viewerSpaceID string, friendSpaceID string) (int64, error) {
+func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.Context, viewerID int64, viewerSpaceID string, friendSpaceID string) (int64, error) {
var activityCreatedAt int64
if err := r.DB.QueryRowContext(ctx, `
WITH candidates AS (
@@ -593,148 +509,116 @@ func (r *MessagesRepository) GetLatestMessageThreadActivityAt(ctx context.Contex
CASE WHEN m.sender_space_id = $1 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id
FROM space_messages m
WHERE (m.sender_space_id = $1 OR m.recipient_space_id = $1)
- AND (m.sender_id = $3 OR m.recipient_id = $3)
AND m.is_deleted = FALSE
- )
- SELECT c.activity_created_at
- FROM candidates c
- WHERE c.friend_space_id = $2
- ORDER BY c.activity_created_at DESC, c.activity_id DESC
- LIMIT 1
- `, strings.TrimSpace(viewerSpaceID), strings.TrimSpace(friendSpaceID), viewerID).Scan(&activityCreatedAt); err != nil {
- return 0, stacktrace.Propagate(err, "")
- }
- return activityCreatedAt, nil
-}
+ AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $1)
+
+ UNION ALL
+
+ SELECT
+ ml.created_at AS activity_created_at,
+ 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
+ liker_space.space_id AS friend_space_id
+ 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
+ WHERE m.sender_space_id = $1
+ AND m.recipient_space_id = ml.actor_space_id
+ AND ml.actor_space_id <> $1
+ AND m.is_deleted = FALSE
+
+ UNION ALL
-func (r *MessagesRepository) GetLatestNotificationActivityAt(ctx context.Context, viewerSpaceID string) (int64, error) {
- var activityCreatedAt int64
- if err := r.DB.QueryRowContext(ctx, `
- WITH notification_candidates AS (
SELECT
pl.created_at AS activity_created_at,
- 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id
+ 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id,
+ actor_space.space_id AS friend_space_id
FROM space_post_likes pl
JOIN space_posts p ON p.post_id = pl.post_id
+ JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
WHERE p.space_id = $1
AND pl.actor_space_id <> $1
AND p.is_deleted = FALSE
UNION ALL
+ SELECT
+ m.created_at AS activity_created_at,
+ 'post_reply:' || m.message_id AS activity_id,
+ m.sender_space_id AS friend_space_id
+ FROM space_messages m
+ JOIN space_posts p ON p.post_id = m.reply_post_id
+ WHERE m.recipient_space_id = $1
+ AND m.sender_space_id <> $1
+ AND m.kind = 'post_reply'
+ AND m.is_deleted = FALSE
+ AND m.reply_post_id IS NOT NULL
+ AND p.space_id = $1
+
+ UNION ALL
+
SELECT
fe.created_at AS activity_created_at,
- 'friend_event:' || fe.event_id::text AS activity_id
+ 'friend_event:' || fe.event_id::text AS activity_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
+ 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 notification_candidates c
+ FROM candidates c
+ WHERE c.friend_space_id = $2
ORDER BY c.activity_created_at DESC, c.activity_id DESC
LIMIT 1
- `, strings.TrimSpace(viewerSpaceID)).Scan(&activityCreatedAt); err != nil {
- return 0, stacktrace.Propagate(err, "")
- }
- return activityCreatedAt, nil
-}
-
-func (r *MessagesRepository) GetLatestMessageLikeActivityAt(ctx context.Context, viewerSpaceID string) (int64, error) {
- var activityCreatedAt int64
- if err := r.DB.QueryRowContext(ctx, `
- SELECT ml.created_at
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- WHERE m.sender_space_id = $1
- AND m.recipient_space_id = ml.actor_space_id
- AND ml.actor_space_id <> $1
- AND m.is_deleted = FALSE
- ORDER BY ml.created_at DESC, ml.message_id DESC, ml.actor_space_id DESC
- LIMIT 1
- `, strings.TrimSpace(viewerSpaceID)).Scan(&activityCreatedAt); err != nil {
+ `, strings.TrimSpace(viewerSpaceID), strings.TrimSpace(friendSpaceID)).Scan(&activityCreatedAt); err != nil {
return 0, stacktrace.Propagate(err, "")
}
return activityCreatedAt, nil
}
-func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerSpaceID string) (bool, error) {
+func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerID int64, viewerSpaceID string) (bool, error) {
var exists bool
if err := r.DB.QueryRowContext(ctx, `
WITH notification_candidates AS (
SELECT
- pl.created_at AS notification_created_at
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- WHERE p.space_id = $1
- AND pl.actor_space_id <> $1
- AND p.is_deleted = FALSE
+ m.sender_space_id AS friend_space_id,
+ m.created_at AS notification_created_at
+ FROM space_messages m
+ WHERE m.recipient_space_id = $1
+ AND m.sender_space_id <> $1
+ AND m.kind = 'regular'
+ AND m.is_deleted = FALSE
UNION ALL
SELECT
- fe.created_at AS notification_created_at
- FROM space_friend_events fe
- WHERE fe.target_space_id = $1
- AND fe.actor_space_id <> fe.target_space_id
- )
- SELECT EXISTS (
- SELECT 1
- FROM notification_candidates c
- LEFT JOIN space_read_markers nrm
- ON nrm.viewer_space_id = $1
- AND nrm.scope = 'notifications'
- AND nrm.friend_space_id = ''
- WHERE c.notification_created_at > COALESCE(nrm.read_at, 0)
- LIMIT 1
- )
- `, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {
- return false, stacktrace.Propagate(err, "")
- }
- return exists, nil
-}
-
-func (r *MessagesRepository) HasUnreadMessageLikes(ctx context.Context, viewerSpaceID string) (bool, error) {
- var exists bool
- if err := r.DB.QueryRowContext(ctx, `
- SELECT EXISTS (
- SELECT 1
+ liker_space.space_id AS friend_space_id,
+ ml.created_at AS notification_created_at
FROM space_message_likes ml
JOIN space_messages m ON m.message_id = ml.message_id
- LEFT JOIN space_read_markers nrm
- ON nrm.viewer_space_id = $1
- AND nrm.scope = 'message_likes'
- AND nrm.friend_space_id = ''
+ JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id
WHERE m.sender_space_id = $1
AND m.recipient_space_id = ml.actor_space_id
AND ml.actor_space_id <> $1
AND m.is_deleted = FALSE
- AND ml.created_at > COALESCE(nrm.read_at, 0)
- LIMIT 1
- )
- `, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {
- return false, stacktrace.Propagate(err, "")
- }
- return exists, nil
-}
-func (r *MessagesRepository) HasUnreadMessages(ctx context.Context, viewerSpaceID string) (bool, error) {
- var exists bool
- if err := r.DB.QueryRowContext(ctx, `
- WITH readable_activities AS (
+ UNION ALL
+
SELECT
- m.sender_space_id AS friend_space_id,
- m.created_at AS readable_created_at
- FROM space_messages m
- WHERE m.recipient_space_id = $1
- AND m.sender_space_id <> $1
- AND m.kind = 'regular'
- AND m.is_deleted = FALSE
+ actor_space.space_id AS friend_space_id,
+ pl.created_at AS notification_created_at
+ FROM space_post_likes pl
+ JOIN space_posts p ON p.post_id = pl.post_id
+ JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
+ WHERE p.space_id = $1
+ AND pl.actor_space_id <> $1
+ AND p.is_deleted = FALSE
UNION ALL
SELECT
m.sender_space_id AS friend_space_id,
- m.created_at AS readable_created_at
+ m.created_at AS notification_created_at
FROM space_messages m
JOIN space_posts p ON p.post_id = m.reply_post_id
WHERE m.recipient_space_id = $1
@@ -743,15 +627,23 @@ func (r *MessagesRepository) HasUnreadMessages(ctx context.Context, viewerSpaceI
AND m.is_deleted = FALSE
AND m.reply_post_id IS NOT NULL
AND p.space_id = $1
+
+ UNION ALL
+
+ SELECT
+ fe.actor_space_id AS friend_space_id,
+ fe.created_at AS notification_created_at
+ FROM space_friend_events fe
+ WHERE fe.target_space_id = $1
+ AND fe.actor_space_id <> fe.target_space_id
)
SELECT EXISTS (
SELECT 1
- FROM readable_activities ra
- LEFT JOIN space_read_markers nrm
+ FROM notification_candidates c
+ LEFT JOIN space_notification_read_markers nrm
ON nrm.viewer_space_id = $1
- AND nrm.scope = 'message_thread'
- AND nrm.friend_space_id = ra.friend_space_id
- WHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)
+ AND nrm.friend_space_id = c.friend_space_id
+ WHERE c.notification_created_at > COALESCE(nrm.read_at, 0)
LIMIT 1
)
`, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {
@@ -803,6 +695,7 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })
&rec.LatestActivity.Outgoing,
&rec.Unread,
&rec.UnreadCount,
+ &rec.NotificationUnread,
&rec.SortCreatedAt,
&rec.SortID,
}
@@ -850,40 +743,6 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })
return &rec, nil
}
-func scanSpaceNotificationRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceNotificationRecord, error) {
- var rec SpaceNotificationRecord
- var postID sql.NullInt64
- var post SpaceMessageConversationPostRecord
- dest := []any{
- &rec.Type,
- &rec.ID,
- &rec.CreatedAt,
- &rec.Unread,
- &rec.SortCreatedAt,
- &rec.SortID,
- }
- dest = append(dest, spaceActorScanDest(&rec.Actor)...)
- dest = append(dest,
- &postID,
- &post.SpaceID,
- &post.SpaceSlug,
- &post.OwnerID,
- &post.IsDeleted,
- &post.ObjectKey,
- &post.ObjectSize,
- &post.ObjectPosition,
- &post.ObjectMetadataCipher,
- )
- if err := scanner.Scan(dest...); err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- if postID.Valid {
- post.PostID = postID.Int64
- rec.Post = &post
- }
- return &rec, nil
-}
-
func parseMessageCursor(cursor string) (int64, string, bool) {
createdAtText, id, ok := strings.Cut(strings.TrimSpace(cursor), ":")
if !ok || strings.TrimSpace(id) == "" {
@@ -904,15 +763,5 @@ func formatMessageConversationCursor(conversation SpaceMessageConversationRecord
if conversation.SortCreatedAt > 0 && strings.TrimSpace(conversation.SortID) != "" {
return strconv.FormatInt(conversation.SortCreatedAt, 10) + ":" + conversation.SortID
}
- if conversation.LatestActivity.CreatedAt <= 0 || strings.TrimSpace(conversation.LatestActivity.ID) == "" {
- return ""
- }
return strconv.FormatInt(conversation.LatestActivity.CreatedAt, 10) + ":" + conversation.LatestActivity.ID
}
-
-func formatSpaceNotificationCursor(notification SpaceNotificationRecord) string {
- if notification.SortCreatedAt > 0 && strings.TrimSpace(notification.SortID) != "" {
- return strconv.FormatInt(notification.SortCreatedAt, 10) + ":" + notification.SortID
- }
- return strconv.FormatInt(notification.CreatedAt, 10) + ":" + notification.ID
-}
diff --git a/server/space/repo/module.go b/server/space/repo/module.go
index 51bcaad1e2..dc094712d9 100644
--- a/server/space/repo/module.go
+++ b/server/space/repo/module.go
@@ -153,23 +153,13 @@ type SpaceMessageRecord struct {
}
type SpaceMessageConversationRecord struct {
- Friend SpaceActorRecord
- LatestActivity SpaceMessageConversationActivityRecord
- Unread bool
- UnreadCount int64
- SortCreatedAt int64
- SortID string
-}
-
-type SpaceNotificationRecord struct {
- ID string
- Type string
- CreatedAt int64
- Unread bool
- Actor SpaceActorRecord
- Post *SpaceMessageConversationPostRecord
- SortCreatedAt int64
- SortID string
+ Friend SpaceActorRecord
+ LatestActivity SpaceMessageConversationActivityRecord
+ Unread bool
+ UnreadCount int64
+ NotificationUnread bool
+ SortCreatedAt int64
+ SortID string
}
type SpaceMessageConversationActivityRecord struct {
diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.go
index 0fe1ade3b5..a0a2087f4c 100644
--- a/server/space/repo/module_test.go
+++ b/server/space/repo/module_test.go
@@ -186,7 +186,7 @@ func TestSpaceMessagesThreadAndConversations(t *testing.T) {
require.Error(t, err)
}
-func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T) {
+func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
@@ -206,17 +206,9 @@ func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T)
require.Empty(t, nextCursor)
require.Len(t, conversations, 1)
require.Equal(t, bobSpace.SpaceID, conversations[0].Friend.SpaceID)
- require.Empty(t, conversations[0].LatestActivity.Type)
- require.False(t, conversations[0].Unread)
- require.Equal(t, int64(0), conversations[0].UnreadCount)
-
- notifications, nextCursor, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Empty(t, nextCursor)
- require.Len(t, notifications, 1)
- require.Equal(t, bobSpace.SpaceID, notifications[0].Actor.SpaceID)
- require.Equal(t, "friend_add", notifications[0].Type)
- require.Nil(t, notifications[0].Post)
+ require.Equal(t, "friend_add", conversations[0].LatestActivity.Type)
+ require.Nil(t, conversations[0].LatestActivity.Message)
+ require.Nil(t, conversations[0].LatestActivity.Post)
bobMessage, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{
Kind: "regular",
@@ -233,7 +225,6 @@ func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T)
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.Len(t, conversations, 1)
require.Equal(t, "message", conversations[0].LatestActivity.Type)
require.Equal(t, bobMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)
@@ -271,13 +262,10 @@ func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T)
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.Equal(t, "message_like", conversations[0].LatestActivity.Type)
- notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Equal(t, "post_like", notifications[0].Type)
- require.NotNil(t, notifications[0].Post)
- require.Equal(t, postID, notifications[0].Post.PostID)
- require.Equal(t, "activity-post-object", notifications[0].Post.ObjectKey.String)
+ require.Equal(t, "post_like", conversations[0].LatestActivity.Type)
+ require.NotNil(t, conversations[0].LatestActivity.Post)
+ require.Equal(t, postID, conversations[0].LatestActivity.Post.PostID)
+ require.Equal(t, "activity-post-object", conversations[0].LatestActivity.Post.ObjectKey.String)
postReply, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{
Kind: "post_reply",
@@ -336,13 +324,10 @@ func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T)
require.Equal(t, replyOnlyPostID, conversations[0].LatestActivity.Post.PostID)
require.True(t, conversations[0].LatestActivity.Post.IsDeleted)
require.False(t, conversations[0].LatestActivity.Post.ObjectKey.Valid)
- latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
+ latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
require.NoError(t, err)
require.Equal(t, int64(5500), latestActivityAt)
- messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
@@ -351,14 +336,12 @@ func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T)
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.Equal(t, "post_reply", conversations[0].LatestActivity.Type)
- notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Equal(t, "friend_remove", notifications[0].Type)
- require.Equal(t, bobSpace.SpaceID, notifications[0].Actor.SpaceID)
+ require.Equal(t, "friend_remove", conversations[0].LatestActivity.Type)
+ require.Nil(t, conversations[0].LatestActivity.Message)
+ require.Nil(t, conversations[0].LatestActivity.Post)
}
-func TestSpaceFriendEventsCreateNotificationsForTarget(t *testing.T) {
+func TestSpaceFriendEventsCreateConversationForBothSides(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
@@ -376,63 +359,51 @@ func TestSpaceFriendEventsCreateNotificationsForTarget(t *testing.T) {
require.NoError(t, err)
require.Len(t, aliceConversations, 1)
require.Equal(t, bobSpace.SpaceID, aliceConversations[0].Friend.SpaceID)
- require.Empty(t, aliceConversations[0].LatestActivity.Type)
+ require.Equal(t, "friend_add", aliceConversations[0].LatestActivity.Type)
+ require.False(t, aliceConversations[0].LatestActivity.Outgoing)
require.False(t, aliceConversations[0].Unread)
- require.Equal(t, int64(0), aliceConversations[0].UnreadCount)
+ require.True(t, aliceConversations[0].NotificationUnread)
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.Empty(t, bobConversations[0].LatestActivity.Type)
+ require.Equal(t, "friend_add", bobConversations[0].LatestActivity.Type)
+ require.True(t, bobConversations[0].LatestActivity.Outgoing)
+ require.False(t, bobConversations[0].Unread)
+ require.False(t, bobConversations[0].NotificationUnread)
- aliceNotifications, _, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Len(t, aliceNotifications, 1)
- require.Equal(t, "friend_add", aliceNotifications[0].Type)
- require.Equal(t, bobSpace.SpaceID, aliceNotifications[0].Actor.SpaceID)
- require.True(t, aliceNotifications[0].Unread)
- bobNotifications, _, err := module.Messages.ListNotifications(ctx, bobSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Empty(t, bobNotifications)
-
- aliceUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ aliceUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, aliceUnread)
- bobUnread, err := module.Messages.HasUnreadNotifications(ctx, bobSpace.SpaceID)
+ bobUnread, err := module.Messages.HasUnreadNotifications(ctx, bobID, bobSpace.SpaceID)
require.NoError(t, err)
require.False(t, bobUnread)
- aliceLatestActivityAt, err := module.Messages.GetLatestNotificationActivityAt(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.Equal(t, int64(1000), aliceLatestActivityAt)
- require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, aliceLatestActivityAt))
- aliceUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)
require.NoError(t, err)
- require.False(t, aliceUnread)
- aliceNotifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Len(t, aliceNotifications, 1)
- require.False(t, aliceNotifications[0].Unread)
+ 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.Empty(t, aliceConversations)
+ require.Len(t, aliceConversations, 1)
+ require.Equal(t, "friend_remove", aliceConversations[0].LatestActivity.Type)
+ require.False(t, aliceConversations[0].LatestActivity.Outgoing)
+ require.False(t, aliceConversations[0].Unread)
+ require.True(t, aliceConversations[0].NotificationUnread)
bobConversations, _, err = module.Messages.ListConversations(ctx, bobID, bobSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.Empty(t, bobConversations)
- aliceNotifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Len(t, aliceNotifications, 2)
- require.Equal(t, "friend_remove", aliceNotifications[0].Type)
- require.True(t, aliceNotifications[0].Unread)
- require.False(t, aliceNotifications[1].Unread)
- aliceLatestActivityAt, err = module.Messages.GetLatestNotificationActivityAt(ctx, aliceSpace.SpaceID)
+ 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)
+ require.False(t, bobConversations[0].NotificationUnread)
+ bobLatestActivityAt, err = module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(2000), aliceLatestActivityAt)
+ require.Equal(t, int64(2000), bobLatestActivityAt)
}
func TestSpaceMessageConversationPreviewUsesLatestActivityWithSeparateUnreadState(t *testing.T) {
@@ -479,42 +450,22 @@ func TestSpaceMessageConversationPreviewUsesLatestActivityWithSeparateUnreadStat
require.NoError(t, err)
require.Len(t, conversations, 1)
require.True(t, conversations[0].Unread)
+ require.True(t, conversations[0].NotificationUnread)
require.Equal(t, "message_like", conversations[0].LatestActivity.Type)
require.Equal(t, aliceOldMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)
require.Equal(t, int64(3000), conversations[0].SortCreatedAt)
- messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- messageLikesUnread, err := module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messageLikesUnread)
- latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
+ latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(2000), latestActivityAt)
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
+ require.Equal(t, int64(3000), latestActivityAt)
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.True(t, conversations[0].Unread)
- require.Equal(t, int64(0), conversations[0].UnreadCount)
+ require.False(t, conversations[0].Unread)
+ require.False(t, conversations[0].NotificationUnread)
require.Equal(t, "message_like", conversations[0].LatestActivity.Type)
require.Equal(t, aliceOldMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
- messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messageLikesUnread)
-
- require.NoError(t, module.Read.UpsertMessageLikesReadMarker(ctx, aliceID, aliceSpace.SpaceID, 3000))
- conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.False(t, conversations[0].Unread)
- require.Equal(t, int64(0), conversations[0].UnreadCount)
- messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messageLikesUnread)
}
func TestSpaceModuleLifecycle(t *testing.T) {
@@ -1432,7 +1383,7 @@ func TestListFeedCursorUsesCreatedAtSortOrder(t *testing.T) {
require.Empty(t, nextCursor)
}
-func TestSpaceReadMarkersDriveSplitUnreadState(t *testing.T) {
+func TestSpaceReadMarkersDriveNotificationState(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
@@ -1462,27 +1413,16 @@ func TestSpaceReadMarkersDriveSplitUnreadState(t *testing.T) {
require.Len(t, conversations, 1)
require.True(t, conversations[0].Unread)
require.Equal(t, int64(1), conversations[0].UnreadCount)
- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, 2000))
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, 2000))
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
require.False(t, conversations[0].Unread)
require.Equal(t, int64(0), conversations[0].UnreadCount)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, notificationsUnread)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
-
- require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 500))
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.False(t, notificationsUnread)
@@ -1503,15 +1443,12 @@ func TestSpaceReadMarkersDriveSplitUnreadState(t *testing.T) {
require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)
require.False(t, conversations[0].Unread)
require.Equal(t, int64(0), conversations[0].UnreadCount)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.False(t, notificationsUnread)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
}
-func TestSpaceReadMarkersUseThreadAndGlobalScopes(t *testing.T) {
+func TestSpaceNotificationReadMarkersArePerFriend(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
@@ -1587,54 +1524,31 @@ func TestSpaceReadMarkersUseThreadAndGlobalScopes(t *testing.T) {
charlieConversation := conversationBySpaceID(charlieSpace.SpaceID)
require.True(t, charlieConversation.Unread)
require.Equal(t, int64(1), charlieConversation.UnreadCount)
- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- messageLikesUnread, err := module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messageLikesUnread)
- bobLatestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
+ bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(1001), bobLatestActivityAt)
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, bobLatestActivityAt))
+ require.Equal(t, int64(1002), bobLatestActivityAt)
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, bobLatestActivityAt))
bobConversation = conversationBySpaceID(bobSpace.SpaceID)
require.True(t, bobConversation.Unread)
require.Equal(t, int64(0), bobConversation.UnreadCount)
charlieConversation = conversationBySpaceID(charlieSpace.SpaceID)
require.True(t, charlieConversation.Unread)
require.Equal(t, int64(1), charlieConversation.UnreadCount)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messageLikesUnread)
-
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, charlieSpace.SpaceID, 2000))
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 200))
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, charlieSpace.SpaceID, 2000))
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.False(t, notificationsUnread)
- require.NoError(t, module.Read.UpsertMessageLikesReadMarker(ctx, aliceID, aliceSpace.SpaceID, 1002))
- bobConversation = conversationBySpaceID(bobSpace.SpaceID)
- require.False(t, bobConversation.Unread)
- require.Equal(t, int64(0), bobConversation.UnreadCount)
- messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messageLikesUnread)
}
-func TestUnreadScopesTrackReadableActivityWithoutChangingLatestPreview(t *testing.T) {
+func TestUnreadNotificationsTrackReadableActivityWithoutChangingLatestPreview(t *testing.T) {
ctx := context.Background()
module := newSpaceTestModule(t)
@@ -1679,28 +1593,24 @@ func TestUnreadScopesTrackReadableActivityWithoutChangingLatestPreview(t *testin
require.Equal(t, int64(2000), conversations[0].SortCreatedAt)
require.True(t, conversations[0].Unread)
require.Equal(t, int64(1), conversations[0].UnreadCount)
- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ require.True(t, conversations[0].NotificationUnread)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
- latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
+ latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
require.NoError(t, err)
require.Equal(t, int64(2000), latestActivityAt)
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)
require.False(t, conversations[0].Unread)
require.Equal(t, int64(0), conversations[0].UnreadCount)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, notificationsUnread)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
+ require.False(t, conversations[0].NotificationUnread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
- require.False(t, messagesUnread)
+ require.False(t, notificationsUnread)
alicePostID, err := module.Posts.CreatePost(ctx, aliceID, aliceSpace.SpaceID, "alice-post-key", nil, aliceSpace.CurrentVersion, nil)
require.NoError(t, err)
@@ -1729,12 +1639,10 @@ func TestUnreadScopesTrackReadableActivityWithoutChangingLatestPreview(t *testin
require.Equal(t, int64(4000), conversations[0].SortCreatedAt)
require.False(t, conversations[0].Unread)
require.Equal(t, int64(0), conversations[0].UnreadCount)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ require.True(t, conversations[0].NotificationUnread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
incomingPostReply, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{
Kind: "post_reply",
@@ -1770,53 +1678,37 @@ func TestUnreadScopesTrackReadableActivityWithoutChangingLatestPreview(t *testin
require.Equal(t, int64(5001), conversations[0].SortCreatedAt)
require.True(t, conversations[0].Unread)
require.Equal(t, int64(2), conversations[0].UnreadCount)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ require.True(t, conversations[0].NotificationUnread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, messagesUnread)
setPostLikeCreatedAt(t, module, 6000, alicePostID, bobSpace.SpaceID)
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
- require.Equal(t, "post_reply", conversations[0].LatestActivity.Type)
- require.Equal(t, secondIncomingPostReply.MessageID, conversations[0].LatestActivity.Message.MessageID)
- require.Equal(t, int64(5001), conversations[0].SortCreatedAt)
+ require.Equal(t, "post_like", conversations[0].LatestActivity.Type)
+ require.Equal(t, alicePostID, conversations[0].LatestActivity.Post.PostID)
+ require.Equal(t, int64(6000), conversations[0].SortCreatedAt)
require.True(t, conversations[0].Unread)
require.Equal(t, int64(2), conversations[0].UnreadCount)
- notifications, _, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.Equal(t, "post_like", notifications[0].Type)
- require.Equal(t, alicePostID, notifications[0].Post.PostID)
- require.Equal(t, int64(6000), notifications[0].CreatedAt)
- require.True(t, notifications[0].Unread)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ require.True(t, conversations[0].NotificationUnread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.True(t, notificationsUnread)
- latestActivityAt, err = module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
+ latestActivityAt, err = module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(5001), latestActivityAt)
- require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
+ require.Equal(t, int64(6000), latestActivityAt)
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))
conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)
require.NoError(t, err)
require.False(t, conversations[0].Unread)
require.Equal(t, int64(0), conversations[0].UnreadCount)
- messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.False(t, messagesUnread)
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
- require.NoError(t, err)
- require.True(t, notificationsUnread)
- require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 6000))
- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)
+ require.False(t, conversations[0].NotificationUnread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
require.False(t, notificationsUnread)
- notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)
- require.NoError(t, err)
- require.False(t, notifications[0].Unread)
}
func TestListPostLikersPaginates(t *testing.T) {
diff --git a/server/space/repo/read_markers.go b/server/space/repo/read_markers.go
index 368cf99f21..dca356051b 100644
--- a/server/space/repo/read_markers.go
+++ b/server/space/repo/read_markers.go
@@ -7,48 +7,20 @@ import (
"github.com/ente-io/stacktrace"
)
-const (
- readScopeNotifications = "notifications"
- readScopeMessageLikes = "message_likes"
- readScopeMessageThread = "message_thread"
-)
-
-func (r *ReadMarkersRepository) UpsertNotificationsReadMarker(ctx context.Context, userID int64, viewerSpaceID string, readAt int64) error {
- return r.upsertReadMarker(ctx, userID, viewerSpaceID, "", readScopeNotifications, readAt)
-}
-
-func (r *ReadMarkersRepository) UpsertMessageLikesReadMarker(ctx context.Context, userID int64, viewerSpaceID string, readAt int64) error {
- return r.upsertReadMarker(ctx, userID, viewerSpaceID, "", readScopeMessageLikes, readAt)
-}
-
-func (r *ReadMarkersRepository) UpsertMessageThreadReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, readAt int64) error {
- return r.upsertReadMarker(ctx, userID, viewerSpaceID, friendSpaceID, readScopeMessageThread, readAt)
-}
-
-func (r *ReadMarkersRepository) upsertReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, scope string, readAt int64) error {
+func (r *ReadMarkersRepository) UpsertNotificationReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, readAt int64) error {
viewerSpaceID = strings.TrimSpace(viewerSpaceID)
friendSpaceID = strings.TrimSpace(friendSpaceID)
- scope = strings.TrimSpace(scope)
- if userID <= 0 || viewerSpaceID == "" || scope == "" || readAt <= 0 {
- return nil
- }
- if scope == readScopeMessageThread && friendSpaceID == "" {
- return nil
- }
- if scope != readScopeMessageThread {
- friendSpaceID = ""
- }
- if scope == readScopeMessageThread && friendSpaceID == viewerSpaceID {
+ if userID <= 0 || viewerSpaceID == "" || friendSpaceID == "" || readAt <= 0 {
return nil
}
_, err := r.DB.ExecContext(ctx, `
- INSERT INTO space_read_markers (user_id, viewer_space_id, scope, friend_space_id, read_at)
- VALUES ($1, $2, $3, $4, $5)
- ON CONFLICT (viewer_space_id, scope, friend_space_id) DO UPDATE
+ INSERT INTO space_notification_read_markers (user_id, viewer_space_id, friend_space_id, read_at)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (viewer_space_id, friend_space_id) DO UPDATE
SET read_at = GREATEST(
- space_read_markers.read_at,
+ space_notification_read_markers.read_at,
EXCLUDED.read_at
)
- `, userID, viewerSpaceID, scope, friendSpaceID, readAt)
+ `, userID, viewerSpaceID, friendSpaceID, readAt)
return stacktrace.Propagate(err, "")
}
diff --git a/web/apps/space/src/components/SpaceMessagesPage.tsx b/web/apps/space/src/components/SpaceMessagesPage.tsx
index b2f69bc4cb..b9b86b5b63 100644
--- a/web/apps/space/src/components/SpaceMessagesPage.tsx
+++ b/web/apps/space/src/components/SpaceMessagesPage.tsx
@@ -10,7 +10,6 @@ import {
loadCurrentMessageThread,
loadCurrentSpaceFriends,
loadCurrentSpaceProfile,
- markCurrentMessageLikesRead,
markCurrentMessagesRead,
replyToCurrentMessage,
sendCurrentMessage,
@@ -19,7 +18,7 @@ import {
type SpaceMessageConversation,
} from "services/space";
import { useSpaceAppState } from "state/spaceAppState";
-import { messageThreadSourceFromQuery, spaceRoutes } from "utils/spaceRoutes";
+import { spaceRoutes } from "utils/spaceRoutes";
import { useSpaceRouter } from "utils/spaceRouteTransitions";
interface SpaceMessagesPageProps {
@@ -116,15 +115,13 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
selectedFriendProfileLoadFailedSpaceId,
setSelectedFriendProfileLoadFailedSpaceId,
] = React.useState<string>();
+ const [newConversationIds, setNewConversationIds] = React.useState<
+ string[]
+ >([]);
const selectedFriendSpaceIdRef = React.useRef<string | undefined>(
undefined,
);
const markedReadSpaceIdRef = React.useRef<string | undefined>(undefined);
- const messageThreadSource = messageThreadSourceFromQuery(router.query.from);
- const closeConversationRoute =
- messageThreadSource == "notifications"
- ? spaceRoutes.notifications
- : spaceRoutes.messages;
const selectedConversation = React.useMemo(
() =>
selectedSpaceId
@@ -180,10 +177,18 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
Boolean(selectedFriend) && !isSelectedFriendCurrent;
const markConversationRead = React.useCallback((spaceId: string) => {
+ setNewConversationIds((currentIds) =>
+ currentIds.filter((id) => id != spaceId),
+ );
setConversations((currentConversations) => {
return currentConversations.map((conversation) =>
conversationId(conversation) == spaceId
- ? { ...conversation, unread: false, unreadCount: 0 }
+ ? {
+ ...conversation,
+ notificationUnread: false,
+ unread: false,
+ unreadCount: 0,
+ }
: conversation,
);
});
@@ -196,7 +201,29 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
setIsConversationsLoading(true);
try {
const page = await loadCurrentMessageConversations();
+ const unreadConversationIds = page.items
+ .filter((conversation) => conversation.notificationUnread)
+ .map(conversationId);
+ const passiveUnreadConversationIds = page.items
+ .filter(
+ (conversation) =>
+ conversation.notificationUnread && !conversation.unread,
+ )
+ .map(conversationId);
+ setNewConversationIds(unreadConversationIds);
setConversations(page.items);
+ if (passiveUnreadConversationIds.length > 0) {
+ void Promise.all(
+ passiveUnreadConversationIds.map((spaceId) =>
+ markCurrentMessagesRead(spaceId),
+ ),
+ ).catch((error: unknown) =>
+ console.warn(
+ "Failed to mark passive message activity read",
+ error,
+ ),
+ );
+ }
return true;
} catch (error: unknown) {
console.error("Failed to load message conversations", error);
@@ -214,8 +241,8 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
);
const closeConversation = React.useCallback(() => {
- if (selectedSpaceId) void router.push(closeConversationRoute);
- }, [closeConversationRoute, router, selectedSpaceId]);
+ if (selectedSpaceId) void router.push(spaceRoutes.messages);
+ }, [router, selectedSpaceId]);
const appendMessageIfThreadIsCurrent = React.useCallback(
(spaceId: string, message: SpaceMessage) => {
@@ -278,16 +305,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
React.useEffect(() => {
if (!profile) return;
- let cancelled = false;
- void refreshConversations().then((loaded) => {
- if (cancelled || !loaded) return;
- void markCurrentMessageLikesRead().catch((error: unknown) =>
- console.warn("Failed to mark message likes read", error),
- );
- });
- return () => {
- cancelled = true;
- };
+ void refreshConversations();
}, [profile, refreshConversations]);
React.useEffect(() => {
@@ -316,12 +334,6 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
React.useEffect(() => {
if (!selectedSpaceId || !selectedConversation) return;
- if (
- !selectedConversation.unread &&
- selectedConversation.unreadCount <= 0
- ) {
- return;
- }
if (markedReadSpaceIdRef.current == selectedSpaceId) return;
markedReadSpaceIdRef.current = selectedSpaceId;
@@ -448,6 +460,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
isThreadLoading={isThreadLoading}
isThreadReadOnly={isThreadReadOnly}
messages={messages}
+ newConversationIds={newConversationIds}
onBack={() => void router.push(spaceRoutes.home)}
onCloseThread={closeConversation}
onOpenSelectedFriendProfile={(friend) =>
@@ -544,11 +557,6 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
}}
profile={profile}
selectedFriend={selectedFriend}
- threadBackLabel={
- messageThreadSource == "notifications"
- ? "Back to notifications"
- : undefined
- }
/>
</>
);
diff --git a/web/apps/space/src/components/SpaceNotificationsPage.tsx b/web/apps/space/src/components/SpaceNotificationsPage.tsx
deleted file mode 100644
index 436aa678a5..0000000000
--- a/web/apps/space/src/components/SpaceNotificationsPage.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { SpacePageMeta } from "components/SpacePageMeta";
-import { SpaceRouteFallback } from "components/SpaceRouteFallback";
-import React from "react";
-import {
- NotificationsScreen,
- notificationsBackground,
-} from "screens/NotificationsScreen";
-import {
- createCurrentProfileLink,
- loadCurrentNotifications,
- loadCurrentSpaceFriends,
- markCurrentNotificationsRead,
- type SpaceNotification,
-} from "services/space";
-import { useSpaceAppState } from "state/spaceAppState";
-import { spaceRoutes } from "utils/spaceRoutes";
-import { useSpaceRouter } from "utils/spaceRouteTransitions";
-
-export const SpaceNotificationsPage: React.FC = () => {
- const router = useSpaceRouter();
- const {
- friends,
- profile,
- profileLoadError,
- profileLoadStatus,
- setFriends,
- } = useSpaceAppState();
- const [notifications, setNotifications] = React.useState<
- SpaceNotification[]
- >([]);
- const [isFriendsLoading, setIsFriendsLoading] = React.useState(true);
- const [isLoading, setIsLoading] = React.useState(true);
-
- React.useEffect(() => {
- if (profileLoadStatus == "ready" && !profile) {
- void router.replace(spaceRoutes.onboarding);
- }
- }, [profile, profileLoadStatus, router]);
-
- React.useEffect(() => {
- if (!profile) return;
-
- let cancelled = false;
- setIsLoading(true);
- void loadCurrentNotifications()
- .then((page) => {
- if (cancelled) return;
- setNotifications(page.items);
- const latestUnread = page.items.find(
- (notification) => notification.unread,
- );
- if (latestUnread) {
- void markCurrentNotificationsRead(
- latestUnread.createdAt,
- ).catch((error: unknown) =>
- console.warn(
- "Failed to mark space notifications read",
- error,
- ),
- );
- }
- })
- .catch((error: unknown) =>
- console.error("Failed to load space notifications", error),
- )
- .finally(() => {
- if (!cancelled) setIsLoading(false);
- });
-
- return () => {
- cancelled = true;
- };
- }, [profile]);
-
- React.useEffect(() => {
- if (!profile?.spaceId) {
- setIsFriendsLoading(false);
- return;
- }
-
- let cancelled = false;
- setIsFriendsLoading(true);
- void loadCurrentSpaceFriends(profile.spaceId)
- .then((nextFriends) => {
- if (!cancelled) setFriends(nextFriends);
- })
- .catch((error: unknown) =>
- console.error("Failed to load space friends", error),
- )
- .finally(() => {
- if (!cancelled) setIsFriendsLoading(false);
- });
-
- return () => {
- cancelled = true;
- };
- }, [profile?.spaceId, setFriends]);
-
- if (profileLoadStatus != "ready" || !profile) {
- return (
- <SpaceRouteFallback
- background={notificationsBackground}
- message={profileLoadError}
- />
- );
- }
-
- return (
- <>
- <SpacePageMeta
- themeColor={notificationsBackground}
- title="Notifications | Ente Space"
- />
- <NotificationsScreen
- friendsCount={friends.length}
- isLoading={isLoading || isFriendsLoading}
- notifications={notifications}
- onBack={() => void router.push(spaceRoutes.home)}
- onOpenFriendMessages={(spaceId) =>
- void router.push(
- spaceRoutes.messageFromNotifications(spaceId),
- )
- }
- onOpenPost={(spaceId, postId) =>
- void router.push(
- spaceRoutes.postFromNotifications(spaceId, postId),
- )
- }
- onShareProfileLink={async () => {
- if (!profile.spaceId) throw new Error("Missing space.");
- return (await createCurrentProfileLink(profile.spaceId))
- .url;
- }}
- />
- </>
- );
-};
diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsx
index 439756a0df..91f279bbdd 100644
--- a/web/apps/space/src/pages/app/index.tsx
+++ b/web/apps/space/src/pages/app/index.tsx
@@ -45,8 +45,6 @@ const Page: React.FC = () => {
const [feedItems, setFeedItems] = useState<SpacePost[]>([]);
const [feedNextCursor, setFeedNextCursor] = useState<string>();
const [hasUnreadMessages, setHasUnreadMessages] = useState<boolean>();
- const [hasUnreadNotifications, setHasUnreadNotifications] =
- useState<boolean>();
const [isFeedLoading, setIsFeedLoading] = useState(true);
const [isFeedLoadingMore, setIsFeedLoadingMore] = useState(false);
const isInitialFeedLoading =
@@ -87,7 +85,6 @@ const Page: React.FC = () => {
setFeedItems([]);
setFeedNextCursor(undefined);
setHasUnreadMessages(false);
- setHasUnreadNotifications(false);
setIsFeedLoading(false);
setIsFeedLoadingMore(false);
setSkipNextHomeFeedSkeleton(false);
@@ -98,7 +95,6 @@ const Page: React.FC = () => {
setFeedItems([]);
setFeedNextCursor(undefined);
setHasUnreadMessages(undefined);
- setHasUnreadNotifications(undefined);
setIsFeedLoading(true);
setIsFeedLoadingMore(false);
void loadCurrentFeedPage()
@@ -121,11 +117,7 @@ const Page: React.FC = () => {
void loadCurrentUnreadStatus()
.then((unreadStatus) => {
if (!cancelled) {
- setHasUnreadMessages(
- unreadStatus.messagesUnread ||
- unreadStatus.messageLikesUnread,
- );
- setHasUnreadNotifications(unreadStatus.notificationsUnread);
+ setHasUnreadMessages(unreadStatus.messagesUnread);
}
})
.catch((error: unknown) =>
@@ -209,7 +201,6 @@ const Page: React.FC = () => {
friendsCount={friends.length}
addedFriendToastName={addedFriendToastName}
hasUnreadMessages={hasUnreadMessages}
- hasUnreadNotifications={hasUnreadNotifications}
hasMoreFeedItems={Boolean(feedNextCursor)}
isFeedLoading={
isSkippingInitialFeedSkeleton ? false : isFeedLoading
@@ -299,9 +290,6 @@ const Page: React.FC = () => {
onLoadPostImage={loadCurrentSpacePostAssetURL}
onLoadPostLikers={loadCurrentPostLikers}
onOpenMessages={() => void router.push(spaceRoutes.messages)}
- onOpenNotifications={() =>
- void router.push(spaceRoutes.notifications)
- }
onOpenProfile={
profile
? () => void router.push(spaceRoutes.profile)
diff --git a/web/apps/space/src/pages/app/notifications.tsx b/web/apps/space/src/pages/app/notifications.tsx
deleted file mode 100644
index 108a9dd0fe..0000000000
--- a/web/apps/space/src/pages/app/notifications.tsx
+++ /dev/null
@@ -1,6 +0,0 @@
-import { SpaceNotificationsPage } from "components/SpaceNotificationsPage";
-import React from "react";
-
-const Page: React.FC = () => <SpaceNotificationsPage />;
-
-export default Page;
diff --git a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
index 4c9708b2ef..2d3b1bbea1 100644
--- a/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
+++ b/web/apps/space/src/pages/app/posts/[spaceId]/[postId].tsx
@@ -10,7 +10,7 @@ import {
type SpacePost,
} from "services/space";
import { useSpaceAppState } from "state/spaceAppState";
-import { postRouteSourceFromQuery, spaceRoutes } from "utils/spaceRoutes";
+import { spaceRoutes } from "utils/spaceRoutes";
import { useSpaceRouter } from "utils/spaceRouteTransitions";
const postBackground = "#000000";
@@ -66,7 +66,6 @@ const Page: React.FC = () => {
const spaceId =
valueFromQuery(router.query.spaceId) ?? pathParams.spaceId ?? "";
const postId = postIdFromQuery(router.query.postId) ?? pathParams.postId;
- const postRouteSource = postRouteSourceFromQuery(router.query.from);
const [post, setPost] = React.useState<SpacePost | null>(null);
const [postLoadError, setPostLoadError] = React.useState<string>();
const [isPostLoading, setIsPostLoading] = React.useState(false);
@@ -123,12 +122,8 @@ const Page: React.FC = () => {
router.back();
return;
}
- if (postRouteSource == "notifications") {
- void router.push(spaceRoutes.notifications);
- return;
- }
void router.push(ownerProfileRoute());
- }, [ownerProfileRoute, postRouteSource, router]);
+ }, [ownerProfileRoute, router]);
if (
!router.isReady ||
diff --git a/web/apps/space/src/screens/FriendsScreen.tsx b/web/apps/space/src/screens/FriendsScreen.tsx
index 5e41fa5bff..b11280f7ba 100644
--- a/web/apps/space/src/screens/FriendsScreen.tsx
+++ b/web/apps/space/src/screens/FriendsScreen.tsx
@@ -643,7 +643,7 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({
onClick={openInviteDialog}
sx={{
alignItems: "center",
- bgcolor: "#F2F2F2",
+ bgcolor: "#E8E8E8",
border: 0,
borderRadius: "18px",
color: textBase,
@@ -669,7 +669,7 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({
outlineOffset: 2,
},
"&:hover": onShareProfileLink
- ? { bgcolor: "#E8E8E8" }
+ ? { bgcolor: "#DEDEDE" }
: undefined,
}}
>
diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsx
index c877f53620..b610cf656e 100644
--- a/web/apps/space/src/screens/HomeScreen.tsx
+++ b/web/apps/space/src/screens/HomeScreen.tsx
@@ -1,7 +1,7 @@
import {
+ BubbleChatIcon,
FavouriteIcon,
MultiplicationSignIcon,
- SentIcon,
UserCheck01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -58,13 +58,12 @@ const textSecondary = "#6B6B6B";
const dangerColor = "#F63A3A";
const headerActionSize = spaceTouchTargetSize;
const headerAvatarSize = 29;
-const headerIconStrokeWidth = 1.8;
const feedAvatarSize = 38;
const headerHeight = 64;
const headerIconSize = 30;
const headerHideStartY = 96;
const headerScrollDelta = 4;
-const headerSideWidth = 76;
+const headerSideWidth = 32;
const feedLikeActionSize = spaceTouchTargetSize;
const feedActionIconSize = 20;
const feedReplyIconSize = 17;
@@ -111,7 +110,6 @@ interface HomeScreenProps {
friendsCount: number;
hasMoreFeedItems?: boolean;
hasUnreadMessages?: boolean;
- hasUnreadNotifications?: boolean;
isFeedLoading?: boolean;
isFeedLoadingMore?: boolean;
localFeedPosts?: LocalSpaceFeedPost[];
@@ -127,7 +125,6 @@ interface HomeScreenProps {
onLoadPostLikers?: SpacePostLikersLoader;
onOpenFriend?: (friendID: string) => void;
onOpenMessages?: () => void;
- onOpenNotifications?: () => void;
onOpenProfile?: () => void;
onReplyToPost?: (postId: number, text: string) => Promise<void>;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
@@ -1450,7 +1447,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
friendsCount,
hasMoreFeedItems = false,
hasUnreadMessages,
- hasUnreadNotifications,
isFeedLoading = false,
isFeedLoadingMore = false,
localFeedPosts = [],
@@ -1463,7 +1459,6 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onLoadPostLikers,
onOpenFriend,
onOpenMessages,
- onOpenNotifications,
onOpenProfile,
onReplyToPost,
onSetPostLiked,
@@ -1516,8 +1511,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
localFeedPosts.length > 0 || remoteFeedItems.length > 0;
const isEmptyFeedLoading = !hasFeedItems && isFeedLoading;
const showFeedCards = hasFeedItems;
- const showMessagesUnreadIndicator = hasUnreadMessages === true;
- const showNotificationsUnreadIndicator = hasUnreadNotifications === true;
+ const showUnreadIndicator = hasUnreadMessages === true;
const emptyFeedMessage =
friendsCount == 0
? "When you add friends, their posts will appear here."
@@ -2014,7 +2008,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
justifyContent: "center",
lineHeight: 0,
ml: "-6px",
- overflow: "visible",
+ overflow: "hidden",
p: 0,
placeSelf: "center start",
width: headerActionSize,
@@ -2033,7 +2027,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
display: "flex",
height: headerAvatarSize,
justifyContent: "center",
- overflow: "visible",
+ overflow: "hidden",
width: headerAvatarSize,
}}
>
@@ -2089,113 +2083,81 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
/>
</Box>
<Box
+ component="button"
+ type="button"
+ aria-label={
+ showUnreadIndicator
+ ? "Open messages with unread activity"
+ : "Open messages"
+ }
+ onClick={onOpenMessages}
sx={{
+ appearance: "none",
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ boxSizing: "border-box",
+ color: textBase,
+ cursor: onOpenMessages ? "pointer" : "default",
display: "flex",
- gap: "2px",
+ fontSize: 0,
+ height: headerActionSize,
+ justifyContent: "center",
justifySelf: "end",
+ lineHeight: 0,
mr: "-6px",
+ p: 0,
+ position: "relative",
+ width: headerActionSize,
+ "& svg": { display: "block" },
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
}}
>
- {[
- {
- ariaLabel: showNotificationsUnreadIndicator
- ? "Open notifications with unread activity"
- : "Open notifications",
- icon: FavouriteIcon,
- key: "notifications",
- onClick: onOpenNotifications,
- showUnread: showNotificationsUnreadIndicator,
- },
- {
- ariaLabel: showMessagesUnreadIndicator
- ? "Open messages with unread activity"
- : "Open messages",
- icon: SentIcon,
- key: "messages",
- onClick: onOpenMessages,
- showUnread: showMessagesUnreadIndicator,
- },
- ].map(
- ({ ariaLabel, icon, key, onClick, showUnread }) => (
- <Box
- key={key}
- component="button"
- type="button"
- aria-label={ariaLabel}
- onClick={onClick}
- sx={{
- appearance: "none",
- alignItems: "center",
- bgcolor: "transparent",
- border: 0,
- boxSizing: "border-box",
- color: textBase,
- cursor: onClick ? "pointer" : "default",
- display: "flex",
- fontSize: 0,
- height: headerActionSize,
- justifyContent: "center",
- lineHeight: 0,
- p: 0,
- position: "relative",
- width: headerActionSize,
- "& svg": { display: "block" },
- "&:focus-visible": {
- borderRadius: "50%",
- outline: `2px solid ${green}`,
- outlineOffset: 2,
+ <HugeiconsIcon
+ icon={BubbleChatIcon}
+ size={headerIconSize}
+ strokeWidth={1.5}
+ />
+ {showUnreadIndicator && (
+ <Box
+ aria-hidden
+ sx={{
+ "@keyframes spaceUnreadBadgePing": {
+ "75%, 100%": {
+ opacity: 0,
+ transform: "scale(2.5)",
},
- }}
- >
- <HugeiconsIcon
- icon={icon}
- size={headerIconSize}
- strokeWidth={headerIconStrokeWidth}
- />
- {showUnread && (
- <Box
- aria-hidden
- sx={{
- "@keyframes spaceUnreadBadgePing":
- {
- "75%, 100%": {
- opacity: 0,
- transform:
- "scale(2.5)",
- },
- },
- "@media (prefers-reduced-motion: reduce)":
- {
- "&::after": {
- display: "none",
- },
- },
- bgcolor: dangerColor,
- border: `2px solid ${homeBackground}`,
- borderRadius: "50%",
- height: 13,
- position: "absolute",
- right: 5,
- top: 6,
- width: 13,
- zIndex: 0,
- "&::after": {
- animation:
- "spaceUnreadBadgePing 1.25s cubic-bezier(0, 0, 0.2, 1) 1",
- bgcolor: dangerColor,
- borderRadius: "50%",
- content: '""',
- inset: 0,
- opacity: 0.75,
- pointerEvents: "none",
- position: "absolute",
- zIndex: -1,
- },
- }}
- />
- )}
- </Box>
- ),
+ },
+ "@media (prefers-reduced-motion: reduce)": {
+ "&::after": { display: "none" },
+ },
+ bgcolor: dangerColor,
+ border: `2px solid ${homeBackground}`,
+ borderRadius: "50%",
+ height: 13,
+ position: "absolute",
+ right: 7,
+ top: 7,
+ width: 13,
+ zIndex: 0,
+ "&::after": {
+ animation:
+ "spaceUnreadBadgePing 1.25s cubic-bezier(0, 0, 0.2, 1) 1",
+ bgcolor: dangerColor,
+ borderRadius: "50%",
+ content: '""',
+ inset: 0,
+ opacity: 0.75,
+ pointerEvents: "none",
+ position: "absolute",
+ zIndex: -1,
+ },
+ }}
+ />
)}
</Box>
</Box>
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index 34f19e653d..aef132056a 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -83,6 +83,7 @@ interface MessagesScreenProps {
onSendMessage: (spaceId: string, text: string) => Promise<void>;
onSetMessageLiked: (messageId: string, liked: boolean) => Promise<void>;
onShareProfileLink?: () => Promise<string>;
+ newConversationIds?: string[];
profile: SetupProfile;
selectedFriend?: SpaceMessageConversation["friend"];
threadBackLabel?: string;
@@ -229,7 +230,15 @@ const conversationPreview = (
profile: SetupProfile,
) => {
const activity = conversation.latestActivity;
- if (!activity) return "Say hello!";
+ if (activity.type == "friend_add") {
+ return "You're now friends";
+ }
+ if (activity.type == "friend_remove") {
+ return activity.outgoing
+ ? "You're no longer friends"
+ : "Removed you as a friend";
+ }
+ if (activity.type == "post_like") return "Liked your post";
if (activity.type == "post_reply") {
return "Replied";
}
@@ -251,7 +260,6 @@ const conversationPreview = (
const quotedConversationActivityPreview = (
activity: SpaceMessageConversation["latestActivity"],
) => {
- if (!activity) return undefined;
const text = activity.message?.text.trim();
if (!text) return undefined;
const previewText = truncateMessageText(text);
@@ -271,12 +279,10 @@ const ConversationPreviewLine: React.FC<{
}> = ({ conversation, profile }) => {
const activity = conversation.latestActivity;
const quotedPreview = quotedConversationActivityPreview(activity);
- const isEmptyConversation = !activity;
const previewLineSx = {
color: textSecondary,
fontFamily: '"Inter Variable", Inter, sans-serif',
fontSize: 13,
- fontStyle: isEmptyConversation ? "italic" : "normal",
fontWeight: 500,
lineHeight: "18px",
minWidth: 0,
@@ -321,7 +327,9 @@ const conversationId = (conversation: SpaceMessageConversation) =>
const conversationTimeSections = (
conversations: SpaceMessageConversation[],
+ newConversationIds: string[],
) => {
+ const newIds = new Set(newConversationIds);
const now = Date.now();
const today = new Date(now);
const startOfTodayMs = new Date(
@@ -345,16 +353,12 @@ const conversationTimeSections = (
];
for (const conversation of conversations) {
- if (conversation.unread) {
+ if (newIds.has(conversationId(conversation))) {
sections[0]!.items.push(conversation);
continue;
}
const activity = conversation.latestActivity;
- if (!activity) {
- sections[6]!.items.push(conversation);
- continue;
- }
if (activity.createdAtMs >= startOfTodayMs) {
sections[1]!.items.push(conversation);
continue;
@@ -388,11 +392,10 @@ const ConversationListItem: React.FC<{
}> = ({ conversation, onOpenThread, profile }) => {
const name =
conversation.friend.fullName.trim() || conversation.friend.username;
- const latestActivity = conversation.latestActivity;
- const timestampLabel = latestActivity
- ? formatTimeAgo(microsForTimestamp(latestActivity.createdAtMs))
- : undefined;
- const postThumbnailUrl = latestActivity?.post?.imageUrl;
+ const timestampLabel = formatTimeAgo(
+ microsForTimestamp(conversation.latestActivity.createdAtMs),
+ );
+ const postThumbnailUrl = conversation.latestActivity.post?.imageUrl;
const unreadCount = conversation.unreadCount;
return (
@@ -492,43 +495,39 @@ const ConversationListItem: React.FC<{
>
{firstNameFrom(name)}
</Box>
- {timestampLabel && (
- <>
- <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(
- 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
+ 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}
@@ -1290,6 +1289,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
isThreadLoading = false,
isThreadReadOnly = false,
messages,
+ newConversationIds = [],
onBack,
onCloseThread,
onDeleteMessage,
@@ -1341,11 +1341,11 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
friendsCount == 0 && Boolean(onShareProfileLink);
const emptyConversationsCopy =
friendsCount == 0
- ? "No messages yet. Once you add friends, you'll see your their messages and replies to your posts here."
+ ? "No messages yet. Once you add friends, you'll see their messages and replies to your posts here."
: "No messages yet. You'll see your friends' messages and replies to your posts here.";
const conversationSections = React.useMemo(
- () => conversationTimeSections(conversations),
- [conversations],
+ () => conversationTimeSections(conversations, newConversationIds),
+ [conversations, newConversationIds],
);
const messageByID = React.useMemo(
() => new Map(messages.map((message) => [message.id, message])),
@@ -1650,730 +1650,760 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
);
return (
- <Box
- component="main"
- sx={{
- bgcolor: messagesBackground,
- color: textBase,
- display: "grid",
- height: isThreadOpen ? "100dvh" : undefined,
- minHeight: isThreadOpen ? 0 : "100svh",
- overflow: isThreadOpen ? "hidden" : undefined,
- overflowX: "hidden",
- placeItems: { xs: "stretch", sm: "start center" },
- }}
- >
+ <>
<Box
+ component="main"
sx={{
- bgcolor: "inherit",
- boxSizing: "border-box",
- display: isThreadOpen ? "grid" : undefined,
- gridTemplateRows: isThreadOpen
- ? isThreadReadOnly
- ? "56px minmax(0, 1fr)"
- : "56px minmax(0, 1fr) auto"
- : undefined,
- height: isThreadOpen ? "100%" : undefined,
+ bgcolor: messagesBackground,
+ color: textBase,
+ display: "grid",
+ height: isThreadOpen ? "100dvh" : undefined,
minHeight: isThreadOpen ? 0 : "100svh",
- mx: "auto",
overflow: isThreadOpen ? "hidden" : undefined,
- position: "relative",
- width: "100%",
- "@media (min-width: 600px)": { maxWidth: 390 },
+ overflowX: "hidden",
+ placeItems: { xs: "stretch", sm: "start center" },
}}
>
<Box
- component="header"
sx={{
- alignItems: "center",
- display: "grid",
- gridTemplateColumns: `${spaceTouchTargetSize}px 1fr ${spaceTouchTargetSize}px`,
- height: 56,
- px: 2,
+ bgcolor: "inherit",
+ boxSizing: "border-box",
+ display: isThreadOpen ? "grid" : undefined,
+ gridTemplateRows: isThreadOpen
+ ? isThreadReadOnly
+ ? "56px minmax(0, 1fr)"
+ : "56px minmax(0, 1fr) auto"
+ : undefined,
+ height: isThreadOpen ? "100%" : undefined,
+ minHeight: isThreadOpen ? 0 : "100svh",
+ mx: "auto",
+ overflow: isThreadOpen ? "hidden" : undefined,
+ position: "relative",
width: "100%",
+ "@media (min-width: 600px)": { maxWidth: 390 },
}}
>
<Box
- component="button"
- type="button"
- aria-label={isThreadOpen ? threadBackLabel : "Back"}
- onClick={isThreadOpen ? onCloseThread : onBack}
+ component="header"
sx={{
alignItems: "center",
- bgcolor: "transparent",
- border: 0,
- color: "inherit",
- cursor:
- isThreadOpen || onBack ? "pointer" : "default",
- display: "flex",
- height: spaceTouchTargetSize,
- justifyContent: "flex-start",
- ml: "-2px",
- p: 0,
- width: spaceTouchTargetSize,
- "&:focus-visible": {
- borderRadius: "50%",
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
+ display: "grid",
+ gridTemplateColumns: `${spaceTouchTargetSize}px 1fr ${spaceTouchTargetSize}px`,
+ height: 56,
+ px: 2,
+ width: "100%",
}}
>
- <HugeiconsIcon
- icon={ArrowLeft02Icon}
- size={24}
- strokeWidth={1.8}
- />
- </Box>
- {isThreadOpen && selectedFriend ? (
<Box
- component="h1"
+ component="button"
+ type="button"
+ aria-label={isThreadOpen ? threadBackLabel : "Back"}
+ onClick={isThreadOpen ? onCloseThread : onBack}
sx={{
- justifySelf: "center",
- m: 0,
- minWidth: 0,
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: "inherit",
+ cursor:
+ isThreadOpen || onBack
+ ? "pointer"
+ : "default",
+ display: "flex",
+ height: spaceTouchTargetSize,
+ justifyContent: "flex-start",
+ ml: "-2px",
+ p: 0,
+ width: spaceTouchTargetSize,
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
}}
>
+ <HugeiconsIcon
+ icon={ArrowLeft02Icon}
+ size={24}
+ strokeWidth={1.8}
+ />
+ </Box>
+ {isThreadOpen && selectedFriend ? (
<Box
- component="button"
- type="button"
- aria-label={
- !canInteract
- ? selectedName || "Conversation"
- : selectedName
- ? `Open ${selectedName}'s profile`
- : "Open friend profile"
- }
- disabled={!canInteract}
- onClick={() =>
- canInteract &&
- onOpenSelectedFriendProfile(selectedFriend)
- }
+ component="h1"
+ sx={{
+ justifySelf: "center",
+ m: 0,
+ minWidth: 0,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ aria-label={
+ !canInteract
+ ? selectedName || "Conversation"
+ : selectedName
+ ? `Open ${selectedName}'s profile`
+ : "Open friend profile"
+ }
+ disabled={!canInteract}
+ onClick={() =>
+ canInteract &&
+ onOpenSelectedFriendProfile(
+ selectedFriend,
+ )
+ }
+ sx={{
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ color: "inherit",
+ cursor: canInteract
+ ? "pointer"
+ : "default",
+ display: "block",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 18,
+ fontWeight: 700,
+ lineHeight: "24px",
+ m: 0,
+ maxWidth: "100%",
+ minWidth: 0,
+ overflow: "hidden",
+ p: 0,
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ "&:focus-visible": {
+ borderRadius: "4px",
+ outline: `2px solid ${green}`,
+ outlineOffset: 3,
+ },
+ }}
+ >
+ {firstNameFrom(selectedName)}
+ </Box>
+ </Box>
+ ) : (
+ <Box
+ component="h1"
sx={{
- appearance: "none",
- bgcolor: "transparent",
- border: 0,
color: "inherit",
- cursor: canInteract ? "pointer" : "default",
- display: "block",
fontFamily:
'"Inter Variable", Inter, sans-serif',
fontSize: 18,
fontWeight: 700,
+ justifySelf: "center",
lineHeight: "24px",
m: 0,
- maxWidth: "100%",
minWidth: 0,
overflow: "hidden",
- p: 0,
textOverflow: "ellipsis",
whiteSpace: "nowrap",
- "&:focus-visible": {
- borderRadius: "4px",
- outline: `2px solid ${green}`,
- outlineOffset: 3,
- },
}}
>
- {firstNameFrom(selectedName)}
+ Messages
</Box>
- </Box>
- ) : (
- <Box
- component="h1"
- sx={{
- color: "inherit",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 18,
- fontWeight: 700,
- justifySelf: "center",
- lineHeight: "24px",
- m: 0,
- minWidth: 0,
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
- }}
- >
- Messages
- </Box>
- )}
- <Box aria-hidden />
- </Box>
+ )}
+ <Box aria-hidden />
+ </Box>
- {isThreadOpen && selectedFriend ? (
- <>
- <Box
- ref={threadScrollRef}
- onScroll={handleThreadScroll}
- sx={{
- boxSizing: "border-box",
- minHeight: 0,
- overscrollBehaviorY: "contain",
- overflowY: "auto",
- px: "14px",
- py: "12px",
- }}
- >
- {isThreadLoading ? (
- <Box
- sx={{
- alignItems: "center",
- display: "flex",
- height: "100%",
- justifyContent: "center",
- }}
- >
- <SpaceLoadingSpinner ariaLabel="Loading messages" />
- </Box>
- ) : messages.length == 0 ? (
- <Box
- sx={{
- alignItems: "center",
- display: "flex",
- height: "100%",
- justifyContent: "center",
- pointerEvents: "none",
- textAlign: "center",
- }}
- >
+ {isThreadOpen && selectedFriend ? (
+ <>
+ <Box
+ ref={threadScrollRef}
+ onScroll={handleThreadScroll}
+ sx={{
+ boxSizing: "border-box",
+ minHeight: 0,
+ overscrollBehaviorY: "contain",
+ overflowY: "auto",
+ px: "14px",
+ py: "12px",
+ }}
+ >
+ {isThreadLoading ? (
<Box
- component="p"
sx={{
- color: textSecondary,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 650,
- lineHeight: "20px",
+ alignItems: "center",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ }}
+ >
+ <SpaceLoadingSpinner ariaLabel="Loading messages" />
+ </Box>
+ ) : messages.length == 0 ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ pointerEvents: "none",
+ textAlign: "center",
+ }}
+ >
+ <Box
+ component="p"
+ sx={{
+ color: textSecondary,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 650,
+ lineHeight: "20px",
+ m: 0,
+ }}
+ >
+ {isThreadReadOnly
+ ? "No messages"
+ : "Say hello!"}
+ </Box>
+ </Box>
+ ) : (
+ <Box
+ component="ol"
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ listStyle: "none",
m: 0,
+ p: 0,
}}
>
- {isThreadReadOnly
- ? "No messages"
- : "Say hello!"}
+ {messages.map((message, index) => {
+ const nextMessage =
+ messages[index + 1];
+ const isSameSequenceAsNext =
+ sameMessageSender(
+ message,
+ nextMessage,
+ ) &&
+ nextMessage!.createdAtMs -
+ message.createdAtMs <=
+ messageGroupTimeThresholdMs;
+ const isLastInSequence =
+ !isSameSequenceAsNext;
+
+ return (
+ <MessageBubble
+ key={message.id}
+ isHighlighted={
+ messageContextMenu
+ ?.message.id ==
+ message.id
+ }
+ isLastInSequence={
+ isLastInSequence
+ }
+ message={message}
+ onOpenActions={
+ openMessageActions
+ }
+ onOpenQuotePost={
+ onOpenQuotePost
+ }
+ ownSpaceID={profile.spaceId}
+ parentMessage={
+ message.replyMessageId
+ ? messageByID.get(
+ message.replyMessageId,
+ )
+ : undefined
+ }
+ profile={profile}
+ showTimestamp={
+ isLastInSequence
+ }
+ />
+ );
+ })}
</Box>
- </Box>
- ) : (
+ )}
+ </Box>
+ <Popper
+ anchorEl={messageContextMenu?.anchorEl ?? null}
+ modifiers={messageActionsPopperModifiers}
+ open={Boolean(messageContextMenu?.open)}
+ placement="bottom-end"
+ sx={{ outline: 0, zIndex: 1300 }}
+ transition
+ >
+ {({ TransitionProps, placement }) => (
+ <ClickAwayListener
+ mouseEvent="onMouseDown"
+ touchEvent="onTouchStart"
+ onClickAway={
+ handleMessageActionsClickAway
+ }
+ >
+ <Grow
+ {...(TransitionProps ?? {})}
+ style={{
+ transformOrigin:
+ placement.startsWith("top")
+ ? "right bottom"
+ : "right top",
+ }}
+ onExited={() => {
+ TransitionProps?.onExited();
+ clearClosedMessageActions();
+ }}
+ timeout={
+ messageActionsTransitionDuration
+ }
+ >
+ <Box
+ sx={{
+ WebkitTapHighlightColor:
+ "transparent",
+ bgcolor: messagesBackground,
+ borderRadius: "16px",
+ boxShadow:
+ "0 14px 40px rgba(0, 0, 0, 0.14)",
+ minWidth: 132,
+ outline: 0,
+ p: "4px",
+ }}
+ >
+ <MenuList
+ autoFocus
+ autoFocusItem
+ onKeyDown={
+ handleMessageActionsKeyDown
+ }
+ sx={{
+ outline: 0,
+ p: 0,
+ "&:focus": {
+ outline: 0,
+ },
+ "&:focus-visible": {
+ outline: 0,
+ },
+ }}
+ variant="menu"
+ >
+ {!isThreadReadOnly && (
+ <>
+ <MessageActionMenuItem
+ icon={
+ <HeartIcon
+ small
+ />
+ }
+ label={
+ isContextMessageLiked
+ ? "Unlike"
+ : "Like"
+ }
+ onClick={() =>
+ handleMessageAction(
+ "like",
+ )
+ }
+ />
+ <MessageActionMenuItem
+ icon={
+ <ReplyIcon />
+ }
+ label="Reply"
+ onClick={() =>
+ handleMessageAction(
+ "reply",
+ )
+ }
+ />
+ </>
+ )}
+ <MessageActionMenuItem
+ icon={<CopyIcon />}
+ label="Copy"
+ onClick={() =>
+ handleMessageAction(
+ "copy",
+ )
+ }
+ />
+ {!isThreadReadOnly &&
+ messageContextMenu?.message &&
+ isCurrentProfileMessage(
+ messageContextMenu.message,
+ profile,
+ ) && (
+ <MessageActionMenuItem
+ icon={
+ <DeleteIcon />
+ }
+ label="Delete"
+ onClick={() =>
+ handleMessageAction(
+ "delete",
+ )
+ }
+ tone="danger"
+ />
+ )}
+ </MenuList>
+ </Box>
+ </Grow>
+ </ClickAwayListener>
+ )}
+ </Popper>
+ {!isThreadReadOnly && (
<Box
- component="ol"
sx={{
- display: "flex",
- flexDirection: "column",
- listStyle: "none",
- m: 0,
- p: 0,
+ bgcolor: messagesBackground,
+ boxSizing: "border-box",
+ display: "grid",
+ gap: "8px",
+ p: "10px 14px calc(10px + env(safe-area-inset-bottom))",
+ width: "100%",
}}
>
- {messages.map((message, index) => {
- const nextMessage = messages[index + 1];
- const isSameSequenceAsNext =
- sameMessageSender(
- message,
- nextMessage,
- ) &&
- nextMessage!.createdAtMs -
- message.createdAtMs <=
- messageGroupTimeThresholdMs;
- const isLastInSequence =
- !isSameSequenceAsNext;
-
- return (
- <MessageBubble
- key={message.id}
- isHighlighted={
- messageContextMenu?.message
- .id == message.id
- }
- isLastInSequence={
- isLastInSequence
- }
- message={message}
- onOpenActions={
- openMessageActions
- }
- onOpenQuotePost={
- onOpenQuotePost
- }
- ownSpaceID={profile.spaceId}
- parentMessage={
- message.replyMessageId
- ? messageByID.get(
- message.replyMessageId,
- )
- : undefined
- }
- profile={profile}
- showTimestamp={isLastInSequence}
- />
- );
- })}
- </Box>
- )}
- </Box>
- <Popper
- anchorEl={messageContextMenu?.anchorEl ?? null}
- modifiers={messageActionsPopperModifiers}
- open={Boolean(messageContextMenu?.open)}
- placement="bottom-end"
- sx={{ outline: 0, zIndex: 1300 }}
- transition
- >
- {({ TransitionProps, placement }) => (
- <ClickAwayListener
- mouseEvent="onMouseDown"
- touchEvent="onTouchStart"
- onClickAway={handleMessageActionsClickAway}
- >
- <Grow
- {...(TransitionProps ?? {})}
- style={{
- transformOrigin:
- placement.startsWith("top")
- ? "right bottom"
- : "right top",
- }}
- onExited={() => {
- TransitionProps?.onExited();
- clearClosedMessageActions();
- }}
- timeout={
- messageActionsTransitionDuration
- }
- >
+ {replyingTo && (
<Box
sx={{
- WebkitTapHighlightColor:
- "transparent",
- bgcolor: messagesBackground,
- borderRadius: "16px",
- boxShadow:
- "0 14px 40px rgba(0, 0, 0, 0.14)",
- minWidth: 132,
- outline: 0,
- p: "4px",
+ bgcolor: lightSurface,
+ borderLeft: `3px solid ${green}`,
+ borderRadius: "12px",
+ boxSizing: "border-box",
+ p: "9px 40px 9px 12px",
+ position: "relative",
+ width: "100%",
}}
>
- <MenuList
- autoFocus
- autoFocusItem
- onKeyDown={
- handleMessageActionsKeyDown
- }
+ <Box sx={{ minWidth: 0 }}>
+ <Box
+ sx={{
+ color: textSecondary,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 650,
+ lineHeight: "16px",
+ }}
+ >
+ {isCurrentProfileMessage(
+ replyingTo,
+ profile,
+ )
+ ? "You"
+ : firstNameFrom(
+ replyingTo.sender.fullName.trim() ||
+ replyingTo
+ .sender
+ .username,
+ )}
+ </Box>
+ <Box
+ sx={{
+ color: textBase,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 600,
+ lineHeight: "18px",
+ overflow: "hidden",
+ textOverflow:
+ "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {truncateMessageText(
+ replyingTo.text,
+ )}
+ </Box>
+ </Box>
+ <Box
+ component="button"
+ type="button"
+ aria-label="Cancel reply"
+ onClick={() => {
+ setReplyingTo(null);
+ }}
sx={{
- outline: 0,
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "50%",
+ color: textSecondary,
+ cursor: "pointer",
+ display: "flex",
+ height: spaceTouchTargetSize,
+ justifyContent: "center",
p: 0,
- "&:focus": { outline: 0 },
+ position: "absolute",
+ right: 0,
+ top: 0,
+ width: spaceTouchTargetSize,
"&:focus-visible": {
- outline: 0,
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ "&:hover": {
+ color: textBase,
+ },
+ "& svg": {
+ position: "absolute",
+ right: 8,
+ top: 8,
},
}}
- variant="menu"
>
- {!isThreadReadOnly && (
- <>
- <MessageActionMenuItem
- icon={
- <HeartIcon
- small
- />
- }
- label={
- isContextMessageLiked
- ? "Unlike"
- : "Like"
- }
- onClick={() =>
- handleMessageAction(
- "like",
- )
- }
- />
- <MessageActionMenuItem
- icon={<ReplyIcon />}
- label="Reply"
- onClick={() =>
- handleMessageAction(
- "reply",
- )
- }
- />
- </>
- )}
- <MessageActionMenuItem
- icon={<CopyIcon />}
- label="Copy"
- onClick={() =>
- handleMessageAction(
- "copy",
- )
- }
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={16}
+ strokeWidth={1.8}
/>
- {!isThreadReadOnly &&
- messageContextMenu?.message &&
- isCurrentProfileMessage(
- messageContextMenu.message,
- profile,
- ) && (
- <MessageActionMenuItem
- icon={
- <DeleteIcon />
- }
- label="Delete"
- onClick={() =>
- handleMessageAction(
- "delete",
- )
- }
- tone="danger"
- />
- )}
- </MenuList>
+ </Box>
</Box>
- </Grow>
- </ClickAwayListener>
- )}
- </Popper>
- {!isThreadReadOnly && (
- <Box
- sx={{
- bgcolor: messagesBackground,
- boxSizing: "border-box",
- display: "grid",
- gap: "8px",
- p: "10px 14px calc(10px + env(safe-area-inset-bottom))",
- width: "100%",
- }}
- >
- {replyingTo && (
+ )}
<Box
sx={{
- bgcolor: lightSurface,
- borderLeft: `3px solid ${green}`,
- borderRadius: "12px",
- boxSizing: "border-box",
- p: "9px 40px 9px 12px",
- position: "relative",
+ alignItems: "flex-end",
+ display: "flex",
+ gap: "8px",
width: "100%",
}}
>
- <Box sx={{ minWidth: 0 }}>
- <Box
- sx={{
+ <Box
+ ref={composerRef}
+ component="textarea"
+ aria-label={`Message ${selectedName}`}
+ onChange={(event) => {
+ const nextText =
+ clampSpaceMessageText(
+ event.target.value,
+ );
+ event.currentTarget.value =
+ nextText;
+ setMessageText(nextText);
+ resizeComposer(
+ event.currentTarget,
+ );
+ }}
+ onBlur={handleComposerBlur}
+ onFocus={handleComposerFocus}
+ placeholder="Message"
+ rows={1}
+ value={messageText}
+ sx={{
+ bgcolor: composerSurface,
+ border: `1px solid ${composerBorder}`,
+ borderRadius: "24px",
+ boxSizing: "border-box",
+ color: textBase,
+ flex: "1 1 auto",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: "20px",
+ maxHeight: composerMaxHeight,
+ minHeight: composerHeight,
+ minWidth: 0,
+ outline: 0,
+ overflow: "hidden",
+ pb: `${composerPadding}px`,
+ pl: `${composerPaddingLeft}px`,
+ pr: `${composerPadding}px`,
+ pt: `${composerPadding}px`,
+ resize: "none",
+ "&::placeholder": {
color: textSecondary,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 12,
- fontWeight: 650,
- lineHeight: "16px",
- }}
- >
- {isCurrentProfileMessage(
- replyingTo,
- profile,
- )
- ? "You"
- : firstNameFrom(
- replyingTo.sender.fullName.trim() ||
- replyingTo.sender
- .username,
- )}
- </Box>
- <Box
- sx={{
- color: textBase,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 600,
- lineHeight: "18px",
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
- }}
- >
- {truncateMessageText(
- replyingTo.text,
- )}
- </Box>
- </Box>
+ },
+ "&:focus": {
+ borderColor: green,
+ },
+ }}
+ />
<Box
component="button"
type="button"
- aria-label="Cancel reply"
- onClick={() => {
- setReplyingTo(null);
- }}
+ aria-label="Send message"
+ className={
+ canSend ? "green-bg" : undefined
+ }
+ disabled={!canSend}
+ onClick={sendMessage}
sx={{
alignItems: "center",
- bgcolor: "transparent",
+ bgcolor: canSend
+ ? green
+ : lightSurfaceHover,
border: 0,
borderRadius: "50%",
- color: textSecondary,
- cursor: "pointer",
+ color: canSend
+ ? "#FFFFFF"
+ : textSecondary,
+ cursor: canSend
+ ? "pointer"
+ : "default",
display: "flex",
- height: spaceTouchTargetSize,
+ flexShrink: 0,
+ height: composerHeight,
justifyContent: "center",
+ opacity: canSend ? 1 : 0.42,
p: 0,
- position: "absolute",
- right: 0,
- top: 0,
- width: spaceTouchTargetSize,
+ transition:
+ "background-color 180ms ease, color 180ms ease, opacity 180ms ease, transform 120ms ease",
+ width: composerHeight,
+ "&:active": {
+ transform: canSend
+ ? "scale(0.96)"
+ : "none",
+ },
"&:focus-visible": {
outline: `2px solid ${green}`,
outlineOffset: 2,
},
- "&:hover": { color: textBase },
- "& svg": {
- position: "absolute",
- right: 8,
- top: 8,
+ "&:hover": {
+ bgcolor: canSend
+ ? "#07AE22"
+ : lightSurfaceHover,
},
}}
>
- <HugeiconsIcon
- icon={Cancel01Icon}
- size={16}
- strokeWidth={1.8}
- />
+ <Box
+ component="span"
+ sx={{
+ display: "flex",
+ transform:
+ "translate(-1px, 1px)",
+ }}
+ >
+ <HugeiconsIcon
+ icon={Navigation03Icon}
+ size={24}
+ strokeWidth={1.8}
+ />
+ </Box>
</Box>
</Box>
- )}
+ </Box>
+ )}
+ </>
+ ) : (
+ <>
+ {isConversationsLoading ? (
<Box
sx={{
- alignItems: "flex-end",
+ alignItems: "center",
+ boxSizing: "border-box",
display: "flex",
- gap: "8px",
- width: "100%",
+ inset: 0,
+ justifyContent: "center",
+ pointerEvents: "none",
+ position: "absolute",
+ }}
+ >
+ <SpaceLoadingSpinner ariaLabel="Loading messages" />
+ </Box>
+ ) : conversations.length == 0 ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ gap: "22px",
+ inset: 0,
+ justifyContent: "center",
+ pointerEvents: "none",
+ position: "absolute",
+ px: 3,
+ textAlign: "center",
}}
>
<Box
- ref={composerRef}
- component="textarea"
- aria-label={`Message ${selectedName}`}
- onChange={(event) => {
- const nextText =
- clampSpaceMessageText(
- event.target.value,
- );
- event.currentTarget.value =
- nextText;
- setMessageText(nextText);
- resizeComposer(event.currentTarget);
- }}
- onBlur={handleComposerBlur}
- onFocus={handleComposerFocus}
- placeholder="Message"
- rows={1}
- value={messageText}
+ component="p"
sx={{
- bgcolor: composerSurface,
- border: `1px solid ${composerBorder}`,
- borderRadius: "24px",
- boxSizing: "border-box",
- color: textBase,
- flex: "1 1 auto",
+ color: textSecondary,
fontFamily:
'"Inter Variable", Inter, sans-serif',
fontSize: 14,
- fontWeight: 600,
+ fontWeight: 500,
lineHeight: "20px",
- maxHeight: composerMaxHeight,
- minHeight: composerHeight,
- minWidth: 0,
- outline: 0,
- overflow: "hidden",
- pb: `${composerPadding}px`,
- pl: `${composerPaddingLeft}px`,
- pr: `${composerPadding}px`,
- pt: `${composerPadding}px`,
- resize: "none",
- "&::placeholder": {
- color: textSecondary,
- },
- "&:focus": { borderColor: green },
- }}
- />
- <Box
- component="button"
- type="button"
- aria-label="Send message"
- className={
- canSend ? "green-bg" : undefined
- }
- disabled={!canSend}
- onClick={sendMessage}
- sx={{
- alignItems: "center",
- bgcolor: canSend
- ? green
- : lightSurfaceHover,
- border: 0,
- borderRadius: "50%",
- color: canSend
- ? "#FFFFFF"
- : textSecondary,
- cursor: canSend
- ? "pointer"
- : "default",
- display: "flex",
- flexShrink: 0,
- height: composerHeight,
- justifyContent: "center",
- opacity: canSend ? 1 : 0.42,
- p: 0,
- transition:
- "background-color 180ms ease, color 180ms ease, opacity 180ms ease, transform 120ms ease",
- width: composerHeight,
- "&:active": {
- transform: canSend
- ? "scale(0.96)"
- : "none",
- },
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- "&:hover": {
- bgcolor: canSend
- ? "#07AE22"
- : lightSurfaceHover,
- },
+ m: 0,
+ maxWidth: 260,
}}
>
+ {emptyConversationsCopy}
+ </Box>
+ {showInviteEmptyState && (
<Box
- component="span"
+ component="button"
+ type="button"
+ onClick={openInviteDialog}
sx={{
- display: "flex",
- transform:
- "translate(-1px, 1px)",
+ alignItems: "center",
+ bgcolor: "#F2F2F2",
+ border: 0,
+ borderRadius: "18px",
+ color: textBase,
+ cursor: "pointer",
+ display: "inline-flex",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 600,
+ gap: "6px",
+ height: spaceTouchTargetSize,
+ justifyContent: "center",
+ lineHeight: "18px",
+ pointerEvents: "auto",
+ px: "14px",
+ whiteSpace: "nowrap",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ "&:hover": {
+ bgcolor: "#E8E8E8",
+ },
}}
>
- <HugeiconsIcon
- icon={Navigation03Icon}
- size={24}
- strokeWidth={1.8}
- />
+ <ShareIcon />
+ Invite friends
</Box>
- </Box>
+ )}
</Box>
- </Box>
- )}
- </>
- ) : (
- <>
- {isConversationsLoading ? (
- <Box
- sx={{
- alignItems: "center",
- boxSizing: "border-box",
- display: "flex",
- inset: 0,
- justifyContent: "center",
- pointerEvents: "none",
- position: "absolute",
- }}
- >
- <SpaceLoadingSpinner ariaLabel="Loading messages" />
- </Box>
- ) : conversations.length == 0 ? (
- <Box
- sx={{
- alignItems: "center",
- boxSizing: "border-box",
- display: "flex",
- flexDirection: "column",
- gap: "22px",
- inset: 0,
- justifyContent: "center",
- pointerEvents: "none",
- position: "absolute",
- px: 3,
- textAlign: "center",
- }}
- >
+ ) : (
<Box
- component="p"
sx={{
- color: textSecondary,
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 500,
- lineHeight: "20px",
+ boxSizing: "border-box",
m: 0,
- maxWidth: 260,
+ p: "6px 16px 28px",
}}
>
- {emptyConversationsCopy}
+ {conversationSections.map((section) => (
+ <ConversationSection
+ key={section.title}
+ onOpenThread={onOpenThread}
+ profile={profile}
+ section={section}
+ />
+ ))}
</Box>
- {showInviteEmptyState && (
- <Box
- component="button"
- type="button"
- onClick={openInviteDialog}
- sx={{
- alignItems: "center",
- bgcolor: "#F2F2F2",
- border: 0,
- borderRadius: "18px",
- color: textBase,
- cursor: "pointer",
- display: "inline-flex",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 600,
- gap: "6px",
- height: spaceTouchTargetSize,
- justifyContent: "center",
- lineHeight: "18px",
- pointerEvents: "auto",
- px: "14px",
- whiteSpace: "nowrap",
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- "&:hover": { bgcolor: "#E8E8E8" },
- }}
- >
- <ShareIcon />
- Invite friends
- </Box>
- )}
- </Box>
- ) : (
- <Box
- sx={{
- boxSizing: "border-box",
- m: 0,
- p: "6px 16px 28px",
- }}
- >
- {conversationSections.map((section) => (
- <ConversationSection
- key={section.title}
- onOpenThread={onOpenThread}
- profile={profile}
- section={section}
- />
- ))}
- </Box>
- )}
- </>
- )}
+ )}
+ </>
+ )}
+ </Box>
</Box>
- <SpaceInviteFriendsDialog
- errorMessage={inviteShareError}
- open={isInviteDialogOpen}
- sharing={isInviteSharing}
- onClose={closeInviteDialog}
- onShare={() => void shareInviteLink()}
- />
- </Box>
+ {showInviteEmptyState && (
+ <SpaceInviteFriendsDialog
+ errorMessage={inviteShareError}
+ open={isInviteDialogOpen}
+ sharing={isInviteSharing}
+ onClose={closeInviteDialog}
+ onShare={() => void shareInviteLink()}
+ />
+ )}
+ </>
);
};
diff --git a/web/apps/space/src/screens/NotificationsScreen.tsx b/web/apps/space/src/screens/NotificationsScreen.tsx
deleted file mode 100644
index 20a154beb7..0000000000
--- a/web/apps/space/src/screens/NotificationsScreen.tsx
+++ /dev/null
@@ -1,686 +0,0 @@
-import { ArrowLeft02Icon, FavouriteIcon } from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { Box } from "@mui/material";
-import { SpaceInviteFriendsDialog } from "components/SpaceInviteFriendsDialog";
-import { SpaceLoadingSpinner } from "components/SpaceRouteFallback";
-import { formatTimeAgo } from "ente-base/date";
-import React from "react";
-import { ShareIcon } from "screens/ShareProfileLinkScreen";
-import type { SpaceNotification } from "services/space";
-import { spaceTouchTargetSize } from "styles/touchTargets";
-
-export const notificationsBackground = "#FFFFFF";
-
-const green = "#08C225";
-const avatarSkeletonBackground = "#E6E6E6";
-const textBase = "#000000";
-const textSecondary = "#777777";
-const dayMs = 24 * 60 * 60 * 1000;
-
-const microsForTimestamp = (timestampMs: number) => timestampMs * 1000;
-
-interface NotificationsScreenProps {
- friendsCount?: number;
- isLoading?: boolean;
- notifications: SpaceNotification[];
- onBack?: () => void;
- onOpenFriendMessages?: (spaceId: string) => void;
- onOpenPost?: (spaceId: string, postId: number) => void;
- onShareProfileLink?: () => Promise<string>;
-}
-
-interface NotificationSection {
- items: NotificationGroup[];
- title: string;
-}
-
-interface NotificationGroup {
- actors: SpaceNotification["actor"][];
- createdAtMs: number;
- id: string;
- post?: SpaceNotification["post"];
- type: SpaceNotification["type"];
- unread: boolean;
-}
-
-const fullName = (actor: SpaceNotification["actor"]) =>
- actor.fullName.trim() || actor.username.trim() || "Someone";
-
-const actorSpaceId = (actor: SpaceNotification["actor"]) =>
- actor.spaceId ?? actor.id;
-
-const ActorName: React.FC<{ actor: SpaceNotification["actor"] }> = ({
- actor,
-}) => (
- <Box component="span" sx={{ fontWeight: 700 }}>
- {fullName(actor)}
- </Box>
-);
-
-const PostLikeText: React.FC<{ actors: SpaceNotification["actor"][] }> = ({
- actors,
-}) => {
- if (actors.length == 1) {
- return (
- <>
- <ActorName actor={actors[0]!} /> liked your post.
- </>
- );
- }
- if (actors.length == 2) {
- return (
- <>
- <ActorName actor={actors[0]!} /> and{" "}
- <ActorName actor={actors[1]!} /> liked your post.
- </>
- );
- }
- return (
- <>
- <ActorName actor={actors[0]!} /> and{" "}
- <Box component="span" sx={{ fontWeight: 700 }}>
- {actors.length - 1} others
- </Box>{" "}
- liked your post.
- </>
- );
-};
-
-const NotificationText: React.FC<{ group: NotificationGroup }> = ({
- group,
-}) => {
- const actor = group.actors[0]!;
- switch (group.type) {
- case "friend_add":
- return (
- <>
- <ActorName actor={actor} /> is now a friend.
- </>
- );
- case "friend_remove":
- return (
- <>
- <ActorName actor={actor} /> is no longer friends with you.
- </>
- );
- case "post_like":
- return <PostLikeText actors={group.actors} />;
- }
-};
-
-const AvatarStack: React.FC<{
- actors: SpaceNotification["actor"][];
- showPostLikeBadge?: boolean;
-}> = ({ actors, showPostLikeBadge = false }) => {
- const isPair = actors.length == 2;
- const displayedActors = isPair
- ? [actors[1]!, actors[0]!]
- : actors.slice(0, 3);
- const stackSize = isPair ? 48 : 44;
-
- return (
- <Box
- sx={{
- flexShrink: 0,
- height: stackSize,
- position: "relative",
- width: stackSize,
- }}
- >
- {displayedActors.map((actor, index) => {
- const isSingle = actors.length == 1;
- const avatarSize = isSingle ? 44 : isPair ? 34 : 30;
- const offset = isPair ? (index == 0 ? 0 : 12) : index * 6;
- const top = isPair ? (index == 0 ? 0 : 12) : index * 5;
- const zIndex = isPair ? index + 1 : 3 - index;
-
- return (
- <Box
- key={`${actor.spaceId ?? actor.id}-${index}`}
- sx={{
- bgcolor: avatarSkeletonBackground,
- border: `2px solid ${notificationsBackground}`,
- borderRadius: "50%",
- height: avatarSize,
- left: isSingle ? 0 : offset,
- overflow: "hidden",
- position: "absolute",
- top: isSingle ? 0 : top,
- width: avatarSize,
- zIndex,
- }}
- >
- {actor.avatarUrl && (
- <Box
- component="img"
- alt=""
- src={actor.avatarUrl}
- sx={{
- display: "block",
- height: "100%",
- objectFit: "cover",
- objectPosition: "center",
- width: "100%",
- }}
- />
- )}
- </Box>
- );
- })}
- {showPostLikeBadge && (
- <Box
- aria-hidden
- className="green-bg"
- sx={{
- alignItems: "center",
- border: `2px solid ${notificationsBackground}`,
- borderRadius: "50%",
- bottom: -1,
- display: "flex",
- height: 18,
- justifyContent: "center",
- position: "absolute",
- right: -1,
- width: 18,
- zIndex: 10,
- }}
- >
- <HugeiconsIcon
- fill="#FFFFFF"
- icon={FavouriteIcon}
- primaryColor="#FFFFFF"
- size={9}
- strokeWidth={2.4}
- />
- </Box>
- )}
- </Box>
- );
-};
-
-const groupNotifications = (notifications: SpaceNotification[]) => {
- const groups = new Map<string, NotificationGroup>();
- for (const notification of notifications) {
- const key =
- notification.type == "post_like" && notification.post
- ? `post_like:${notification.post.postId}`
- : notification.id;
- const existing = groups.get(key);
- if (existing) {
- if (notification.createdAtMs > existing.createdAtMs) {
- existing.actors.unshift(notification.actor);
- } else {
- existing.actors.push(notification.actor);
- }
- existing.createdAtMs = Math.max(
- existing.createdAtMs,
- notification.createdAtMs,
- );
- existing.unread ||= notification.unread;
- continue;
- }
- groups.set(key, {
- actors: [notification.actor],
- createdAtMs: notification.createdAtMs,
- id: key,
- post: notification.post,
- type: notification.type,
- unread: notification.unread,
- });
- }
- return [...groups.values()].sort((a, b) => b.createdAtMs - a.createdAtMs);
-};
-
-const timeSections = (groups: NotificationGroup[]) => {
- 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 sections: NotificationSection[] = [
- { title: "New", items: [] },
- { title: "Today", items: [] },
- { title: "Yesterday", items: [] },
- { title: "Last 7 days", items: [] },
- { title: "Last 30 days", items: [] },
- { title: "Older", items: [] },
- ];
-
- for (const group of groups) {
- if (group.unread) {
- sections[0]!.items.push(group);
- continue;
- }
- if (group.createdAtMs >= startOfTodayMs) {
- sections[1]!.items.push(group);
- continue;
- }
- if (group.createdAtMs >= startOfYesterdayMs) {
- sections[2]!.items.push(group);
- continue;
- }
-
- const ageMs = Math.max(0, now - group.createdAtMs);
- if (ageMs <= 7 * dayMs) {
- sections[3]!.items.push(group);
- continue;
- }
- if (ageMs <= 30 * dayMs) {
- sections[4]!.items.push(group);
- continue;
- }
- sections[5]!.items.push(group);
- }
- return sections;
-};
-
-const NotificationRow: React.FC<{
- group: NotificationGroup;
- onOpenFriendMessages?: (spaceId: string) => void;
- onOpenPost?: (spaceId: string, postId: number) => void;
-}> = ({ group, onOpenFriendMessages, onOpenPost }) => {
- const postImageUrl = group.post?.imageUrl;
- const avatarActors =
- group.type == "post_like" && group.actors.length > 2
- ? group.actors.slice(0, 1)
- : group.actors;
- const avatarColumnWidth = avatarActors.length == 2 ? 52 : 44;
- const friendActivityActor =
- group.type == "post_like" ? undefined : group.actors[0];
- const friendActivitySpaceId = friendActivityActor
- ? actorSpaceId(friendActivityActor)
- : undefined;
- const canOpenFriendMessages = Boolean(
- friendActivitySpaceId && onOpenFriendMessages,
- );
- const canOpenPost = Boolean(
- group.type == "post_like" &&
- group.post &&
- !group.post.isDeleted &&
- onOpenPost,
- );
- const canOpen = canOpenFriendMessages || canOpenPost;
-
- const openFriendMessages = () => {
- if (!friendActivitySpaceId) return;
- onOpenFriendMessages?.(friendActivitySpaceId);
- };
-
- const openRow = () => {
- if (canOpenPost && group.post) {
- onOpenPost?.(group.post.spaceId, group.post.postId);
- return;
- }
- if (canOpenFriendMessages) openFriendMessages();
- };
-
- return (
- <Box component="li">
- <Box
- component={canOpen ? "button" : "div"}
- type={canOpen ? "button" : undefined}
- onClick={canOpen ? openRow : undefined}
- sx={{
- alignItems: "center",
- appearance: "none",
- bgcolor: "transparent",
- border: 0,
- borderRadius: "8px",
- color: textBase,
- cursor: canOpen ? "pointer" : "default",
- display: "grid",
- gap: "10px",
- gridTemplateColumns: postImageUrl
- ? `${avatarColumnWidth}px minmax(0, 1fr) 44px`
- : `${avatarColumnWidth}px minmax(0, 1fr)`,
- minHeight: 64,
- p: "8px 0",
- textAlign: "left",
- width: "100%",
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- }}
- >
- <AvatarStack
- actors={avatarActors}
- showPostLikeBadge={group.type == "post_like"}
- />
- <Box sx={{ minWidth: 0 }}>
- <Box
- component="p"
- sx={{
- color: textBase,
- fontFamily: '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 500,
- lineHeight: "20px",
- m: 0,
- }}
- >
- <NotificationText group={group} />
- </Box>
- <Box
- component="p"
- sx={{
- color: textSecondary,
- fontFamily: '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 500,
- lineHeight: "18px",
- m: 0,
- }}
- >
- {formatTimeAgo(microsForTimestamp(group.createdAtMs))}
- </Box>
- </Box>
- {postImageUrl && (
- <Box
- component="img"
- alt=""
- src={postImageUrl}
- sx={{
- borderRadius: "6px",
- display: "block",
- height: 44,
- objectFit: "cover",
- objectPosition: "center",
- width: 44,
- }}
- />
- )}
- </Box>
- </Box>
- );
-};
-
-const NotificationSection: React.FC<{
- onOpenFriendMessages?: (spaceId: string) => void;
- onOpenPost?: (spaceId: string, postId: number) => void;
- section: NotificationSection;
-}> = ({ onOpenFriendMessages, onOpenPost, section }) => {
- if (section.items.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",
- }}
- >
- {section.title}
- </Box>
- <Box component="ul" sx={{ listStyle: "none", m: 0, p: 0 }}>
- {section.items.map((group) => (
- <NotificationRow
- key={group.id}
- group={group}
- onOpenFriendMessages={onOpenFriendMessages}
- onOpenPost={onOpenPost}
- />
- ))}
- </Box>
- </Box>
- );
-};
-
-export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
- friendsCount,
- isLoading = false,
- notifications,
- onBack,
- onOpenFriendMessages,
- onOpenPost,
- onShareProfileLink,
-}) => {
- const [isInviteDialogOpen, setIsInviteDialogOpen] = React.useState(false);
- const [isInviteSharing, setIsInviteSharing] = React.useState(false);
- const [inviteShareError, setInviteShareError] = React.useState<
- string | null
- >(null);
- const groups = React.useMemo(
- () => groupNotifications(notifications),
- [notifications],
- );
- const sections = React.useMemo(() => timeSections(groups), [groups]);
- const showInviteEmptyState =
- friendsCount == 0 && Boolean(onShareProfileLink);
- const emptyStateCopy =
- friendsCount == 0
- ? "No notifications yet. Once you add friends, you'll see likes on posts and friend updates here."
- : "No notifications yet. You'll see likes on posts and friend updates here.";
-
- const openInviteDialog = () => {
- setInviteShareError(null);
- setIsInviteDialogOpen(true);
- };
-
- const closeInviteDialog = () => {
- if (isInviteSharing) return;
- setIsInviteDialogOpen(false);
- };
-
- const shareInviteLink = async () => {
- if (!onShareProfileLink || isInviteSharing) return;
- setIsInviteSharing(true);
- setInviteShareError(null);
-
- try {
- const profileLink = await onShareProfileLink();
- if (typeof navigator.share == "function") {
- try {
- await navigator.share({ url: profileLink });
- setIsInviteDialogOpen(false);
- return;
- } catch (error) {
- if (
- error instanceof DOMException &&
- error.name == "AbortError"
- )
- return;
- }
- }
-
- await navigator.clipboard.writeText(profileLink);
- setIsInviteDialogOpen(false);
- } catch (error) {
- console.error("Failed to share space invite", error);
- setInviteShareError("Couldn't share invite. Please try again.");
- } finally {
- setIsInviteSharing(false);
- }
- };
-
- return (
- <Box
- sx={{
- bgcolor: notificationsBackground,
- color: textBase,
- minHeight: "100svh",
- }}
- >
- <Box
- sx={{
- bgcolor: notificationsBackground,
- boxSizing: "border-box",
- minHeight: "100svh",
- mx: "auto",
- width: "100%",
- "@media (min-width: 600px)": { maxWidth: 390 },
- }}
- >
- <Box
- component="header"
- sx={{
- alignItems: "center",
- bgcolor: notificationsBackground,
- boxSizing: "border-box",
- display: "grid",
- gridTemplateColumns: `${spaceTouchTargetSize}px 1fr ${spaceTouchTargetSize}px`,
- height: 56,
- px: 2,
- position: "sticky",
- top: 0,
- width: "100%",
- zIndex: 2,
- }}
- >
- <Box
- component="button"
- type="button"
- aria-label="Back"
- onClick={onBack}
- sx={{
- alignItems: "center",
- appearance: "none",
- bgcolor: "transparent",
- border: 0,
- color: textBase,
- cursor: onBack ? "pointer" : "default",
- display: "flex",
- height: spaceTouchTargetSize,
- justifyContent: "flex-start",
- ml: "-2px",
- p: 0,
- width: spaceTouchTargetSize,
- "&:focus-visible": {
- borderRadius: "50%",
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- }}
- >
- <HugeiconsIcon
- icon={ArrowLeft02Icon}
- size={24}
- strokeWidth={1.8}
- />
- </Box>
- <Box
- component="h1"
- sx={{
- color: textBase,
- fontFamily: '"Inter Variable", Inter, sans-serif',
- fontSize: 18,
- fontWeight: 750,
- lineHeight: "24px",
- m: 0,
- textAlign: "center",
- }}
- >
- Notifications
- </Box>
- </Box>
- <Box sx={{ boxSizing: "border-box", px: "16px", pb: "28px" }}>
- {isLoading ? (
- <Box
- sx={{
- alignItems: "center",
- display: "flex",
- height: "calc(100svh - 58px)",
- justifyContent: "center",
- }}
- >
- <SpaceLoadingSpinner ariaLabel="Loading notifications" />
- </Box>
- ) : notifications.length == 0 ? (
- <Box
- sx={{
- alignItems: "center",
- display: "flex",
- flexDirection: "column",
- gap: "22px",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- height: "calc(100svh - 58px)",
- justifyContent: "center",
- px: 3,
- textAlign: "center",
- }}
- >
- <Box
- component="p"
- sx={{
- color: textSecondary,
- fontSize: 14,
- fontWeight: 500,
- lineHeight: "20px",
- m: 0,
- maxWidth: 292,
- }}
- >
- {emptyStateCopy}
- </Box>
- {showInviteEmptyState && (
- <Box
- component="button"
- type="button"
- onClick={openInviteDialog}
- sx={{
- alignItems: "center",
- bgcolor: "#F2F2F2",
- border: 0,
- borderRadius: "18px",
- color: textBase,
- cursor: "pointer",
- display: "inline-flex",
- fontFamily:
- '"Inter Variable", Inter, sans-serif',
- fontSize: 13,
- fontWeight: 600,
- gap: "6px",
- height: spaceTouchTargetSize,
- justifyContent: "center",
- lineHeight: "18px",
- px: "14px",
- whiteSpace: "nowrap",
- "&:focus-visible": {
- outline: `2px solid ${green}`,
- outlineOffset: 2,
- },
- "&:hover": { bgcolor: "#E8E8E8" },
- }}
- >
- <ShareIcon />
- Invite friends
- </Box>
- )}
- </Box>
- ) : (
- sections.map((section) => (
- <NotificationSection
- key={section.title}
- onOpenFriendMessages={onOpenFriendMessages}
- onOpenPost={onOpenPost}
- section={section}
- />
- ))
- )}
- </Box>
- </Box>
- <SpaceInviteFriendsDialog
- errorMessage={inviteShareError}
- open={isInviteDialogOpen}
- sharing={isInviteSharing}
- onClose={closeInviteDialog}
- onShare={() => void shareInviteLink()}
- />
- </Box>
- );
-};
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 90f699b625..5226ab269a 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -88,15 +88,13 @@ interface SpacePostLikersPageResponse {
}
type SpaceMessageConversationActivityType =
+ | "friend_add"
+ | "friend_remove"
| "message"
| "message_like"
+ | "post_like"
| "post_reply";
-export type SpaceNotificationType =
- | "friend_add"
- | "friend_remove"
- | "post_like";
-
interface SpaceMessageConversationPostResponse {
isDeleted?: boolean;
objects?: SpacePostObject[];
@@ -158,7 +156,8 @@ interface SpaceMessagePageResponse {
interface SpaceMessageConversationResponse {
friend: SpaceActor;
- latestActivity?: SpaceMessageConversationActivity;
+ latestActivity: SpaceMessageConversationActivity;
+ notificationUnread?: boolean;
unread?: boolean;
unreadCount: number;
}
@@ -168,20 +167,6 @@ interface SpaceMessageConversationPageResponse {
nextCursor?: string;
}
-interface SpaceNotificationResponse {
- actor: SpaceActor;
- createdAt: string;
- id: string;
- post?: SpaceMessageConversationPostResponse;
- type: SpaceNotificationType;
- unread?: boolean;
-}
-
-interface SpaceNotificationPageResponse {
- items?: SpaceNotificationResponse[];
- nextCursor?: string;
-}
-
interface SpacePostBase {
avatarObjectKey?: string;
avatarSize?: number;
@@ -320,7 +305,8 @@ export interface SpaceMessagePage {
export interface SpaceMessageConversation {
friend: FriendProfile;
- latestActivity?: SpaceMessageActivity;
+ latestActivity: SpaceMessageActivity;
+ notificationUnread: boolean;
unread: boolean;
unreadCount: number;
}
@@ -330,30 +316,11 @@ export interface SpaceMessageConversationPage {
nextCursor?: string;
}
-export interface SpaceNotification {
- actor: FriendProfile;
- createdAt: string;
- createdAtMs: number;
- id: string;
- post?: SpaceMessageActivityPost;
- type: SpaceNotificationType;
- unread: boolean;
-}
-
-export interface SpaceNotificationPage {
- items: SpaceNotification[];
- nextCursor?: string;
-}
-
export interface SpaceUnreadStatus {
- messageLikesUnread: boolean;
messagesUnread: boolean;
- notificationsUnread: boolean;
}
interface SpaceUnreadStatusResponse {
- messageLikesUnread?: boolean;
- messagesUnread?: boolean;
notificationsUnread: boolean;
}
@@ -890,9 +857,8 @@ const messageActivityPostFromSpacePost = async (
const messageActivityFromSpaceActivity = async (
ctx: SpaceAccountCtxHandle,
- activity?: SpaceMessageConversationActivity,
-): Promise<SpaceMessageActivity | undefined> => {
- if (!activity) return undefined;
+ activity: SpaceMessageConversationActivity,
+): Promise<SpaceMessageActivity> => {
const [message, post] = await Promise.all([
activity.message
? messageFromSpaceMessage(ctx, activity.message, false)
@@ -909,31 +875,6 @@ const messageActivityFromSpaceActivity = async (
};
};
-const notificationFromSpaceNotification = async (
- ctx: SpaceAccountCtxHandle,
- notification: SpaceNotificationResponse,
-): Promise<SpaceNotification> => {
- const actor = actorProfile(notification.actor);
- const [avatarUrl, post] = await Promise.all([
- accountAvatarURL(
- ctx,
- notification.actor.spaceId,
- notification.actor.avatar,
- ),
- messageActivityPostFromSpacePost(ctx, notification.post),
- ]);
- actor.avatarUrl = avatarUrl;
- return {
- actor,
- createdAt: notification.createdAt,
- createdAtMs: timestampMsFromSpaceDate(notification.createdAt),
- id: notification.id,
- post,
- type: notification.type,
- unread: Boolean(notification.unread),
- };
-};
-
export const createCurrentProfileLink = async (
spaceId: string,
): Promise<SpaceLink> => {
@@ -1065,12 +1006,8 @@ export const loadCurrentUnreadStatus = async (): Promise<SpaceUnreadStatus> => {
const ctx = await ensureCurrentSpaceContext();
try {
const status = (await ctx.unread_status()) as SpaceUnreadStatusResponse;
- const messagesUnread = Boolean(status.messagesUnread);
- const messageLikesUnread = Boolean(status.messageLikesUnread);
return {
- messageLikesUnread,
- messagesUnread,
- notificationsUnread: Boolean(status.notificationsUnread),
+ messagesUnread: status.notificationsUnread,
};
} finally {
releaseCurrentSpaceContext(ctx);
@@ -1343,6 +1280,9 @@ export const loadCurrentMessageConversations =
ctx,
conversation.latestActivity,
),
+ notificationUnread: Boolean(
+ conversation.notificationUnread,
+ ),
unread: Boolean(conversation.unread),
unreadCount: conversation.unreadCount,
};
@@ -1354,25 +1294,6 @@ export const loadCurrentMessageConversations =
}
};
-export const loadCurrentNotifications =
- async (): Promise<SpaceNotificationPage> => {
- const ctx = await ensureCurrentSpaceContext();
- try {
- const page = (await ctx.list_notifications(
- null,
- 100,
- )) as SpaceNotificationPageResponse;
- const items = await Promise.all(
- (page.items ?? []).map((notification) =>
- notificationFromSpaceNotification(ctx, notification),
- ),
- );
- return { items, nextCursor: page.nextCursor || undefined };
- } finally {
- releaseCurrentSpaceContext(ctx);
- }
- };
-
export const loadCurrentMessageThread = async (
spaceId: string,
): Promise<SpaceMessagePage> => {
@@ -1400,25 +1321,7 @@ export const markCurrentMessagesRead = async (friendSpaceId: string) => {
if (!friendSpaceId.trim()) return;
const ctx = await ensureCurrentSpaceContext();
try {
- await ctx.mark_message_thread_read(friendSpaceId);
- } finally {
- releaseCurrentSpaceContext(ctx);
- }
-};
-
-export const markCurrentNotificationsRead = async (readAt?: string) => {
- const ctx = await ensureCurrentSpaceContext();
- try {
- await ctx.mark_notifications_read(readAt ?? null);
- } finally {
- releaseCurrentSpaceContext(ctx);
- }
-};
-
-export const markCurrentMessageLikesRead = async () => {
- const ctx = await ensureCurrentSpaceContext();
- try {
- await ctx.mark_message_likes_read();
+ await ctx.mark_notifications_read(friendSpaceId);
} finally {
releaseCurrentSpaceContext(ctx);
}
diff --git a/web/apps/space/src/utils/spaceRouteTransitions.tsx b/web/apps/space/src/utils/spaceRouteTransitions.tsx
index 010b8f5ab6..6ffeebe07c 100644
--- a/web/apps/space/src/utils/spaceRouteTransitions.tsx
+++ b/web/apps/space/src/utils/spaceRouteTransitions.tsx
@@ -30,14 +30,13 @@ const parentRoutePaths = (path: string) => {
if (/^\/app\/friends\/[^/]+$/.test(path)) return ["/app/friends"];
if (/^\/app\/messages\/[^/]+$/.test(path)) return ["/app/messages"];
if (/^\/app\/posts\/[^/]+\/[^/]+$/.test(path)) {
- return ["/app", "/app/notifications"];
+ return ["/app"];
}
return (
{
"/app/friends": ["/app/profile"],
"/app/messages": ["/app"],
- "/app/notifications": ["/app"],
"/app/profile": ["/app"],
"/app/profile/cover": ["/app/profile"],
"/app/profile/cover-edit": ["/app/profile/cover"],
diff --git a/web/apps/space/src/utils/spaceRoutes.ts b/web/apps/space/src/utils/spaceRoutes.ts
index 6feba99893..1047d967f1 100644
--- a/web/apps/space/src/utils/spaceRoutes.ts
+++ b/web/apps/space/src/utils/spaceRoutes.ts
@@ -1,7 +1,5 @@
export type SetupProfileSource = "login" | "verify";
export type ProfileImageFlowSource = "profile" | "settings";
-export type MessageThreadSource = "messages" | "notifications";
-export type PostRouteSource = "default" | "notifications";
export type VerifyFlow = "login" | "signup";
const valueFromQuery = (value: string | string[] | undefined) =>
@@ -20,17 +18,12 @@ export const spaceRoutes = {
login: "/login",
message: (spaceId: string) =>
`/app/messages/${encodeURIComponent(spaceId)}`,
- messageFromNotifications: (spaceId: string) =>
- `/app/messages/${encodeURIComponent(spaceId)}?from=notifications`,
messages: "/app/messages",
- notifications: "/app/notifications",
onboarding: "/",
passkeysFinish: "/passkeys/finish",
passkeysVerify: "/passkeys/verify",
post: (spaceId: string, postId: number) =>
`/app/posts/${encodeURIComponent(spaceId)}/${encodeURIComponent(String(postId))}`,
- postFromNotifications: (spaceId: string, postId: number) =>
- `/app/posts/${encodeURIComponent(spaceId)}/${encodeURIComponent(String(postId))}?from=notifications`,
editProfileCover: "/app/profile/cover-edit",
editProfileCoverFrom: (source?: ProfileImageFlowSource) =>
routeWithProfileImageFlowSource("/app/profile/cover-edit", source),
@@ -69,15 +62,5 @@ export const profileImageFlowSourceFromQuery = (
): ProfileImageFlowSource =>
valueFromQuery(value) == "settings" ? "settings" : "profile";
-export const messageThreadSourceFromQuery = (
- value: string | string[] | undefined,
-): MessageThreadSource =>
- valueFromQuery(value) == "notifications" ? "notifications" : "messages";
-
-export const postRouteSourceFromQuery = (
- value: string | string[] | undefined,
-): PostRouteSource =>
- valueFromQuery(value) == "notifications" ? "notifications" : "default";
-
export const friendSpaceIdFromQuery = (value: string | string[] | undefined) =>
valueFromQuery(value) ?? "";