From c1795ee9639b56d14687416135c627bb99efbff2 Mon Sep 17 00:00:00 2001
From: Claire <claire.github-309c@sitedethib.com>
Date: Mon, 2 Sep 2024 22:14:04 +0200
Subject: [PATCH] Fix not being able to load more notifications after trimming
 (#31652)

---
 .../mastodon/reducers/notification_groups.ts  | 25 ++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/app/javascript/mastodon/reducers/notification_groups.ts b/app/javascript/mastodon/reducers/notification_groups.ts
index b3535d7b67..f3c83ccd8d 100644
--- a/app/javascript/mastodon/reducers/notification_groups.ts
+++ b/app/javascript/mastodon/reducers/notification_groups.ts
@@ -248,8 +248,9 @@ function processNewNotification(
 }
 
 function trimNotifications(state: NotificationGroupsState) {
-  if (state.scrolledToTop) {
+  if (state.scrolledToTop && state.groups.length > NOTIFICATIONS_TRIM_LIMIT) {
     state.groups.splice(NOTIFICATIONS_TRIM_LIMIT);
+    ensureTrailingGap(state.groups);
   }
 }
 
@@ -400,6 +401,28 @@ function ensureLeadingGap(
   }
 }
 
+// Ensure the groups list ends with a gap suitable for loading more, mutating it to append one if needed
+function ensureTrailingGap(
+  groups: NotificationGroupsState['groups'],
+): NotificationGap {
+  const groupOrGap = groups.at(-1);
+
+  if (groupOrGap?.type === 'gap') {
+    // We're expecting older notifications, so discard sinceId if it's set
+    groupOrGap.sinceId = undefined;
+
+    return groupOrGap;
+  } else {
+    const gap: NotificationGap = {
+      type: 'gap',
+      maxId: groupOrGap?.page_min_id,
+    };
+
+    groups.push(gap);
+    return gap;
+  }
+}
+
 export const notificationGroupsReducer = createReducer<NotificationGroupsState>(
   initialState,
   (builder) => {