Compare commits

...

1 Commits

Author SHA1 Message Date
Tim
640fbd6ea4 feat: add paginated notifications with infinite scroll 2025-08-19 13:56:36 +08:00
5 changed files with 217 additions and 174 deletions

View File

@@ -24,8 +24,10 @@ public class NotificationController {
@GetMapping @GetMapping
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read, public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "pageSize", defaultValue = "50") int pageSize,
Authentication auth) { Authentication auth) {
return notificationService.listNotifications(auth.getName(), read).stream() return notificationService.listNotifications(auth.getName(), read, page, pageSize).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@@ -5,6 +5,7 @@ import com.openisle.model.User;
import com.openisle.model.Post; import com.openisle.model.Post;
import com.openisle.model.Comment; import com.openisle.model.Comment;
import com.openisle.model.NotificationType; import com.openisle.model.NotificationType;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
@@ -13,6 +14,9 @@ import java.util.List;
public interface NotificationRepository extends JpaRepository<Notification, Long> { public interface NotificationRepository extends JpaRepository<Notification, Long> {
List<Notification> findByUserOrderByCreatedAtDesc(User user); List<Notification> findByUserOrderByCreatedAtDesc(User user);
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read); List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
List<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
long countByUserAndRead(User user, boolean read); long countByUserAndRead(User user, boolean read);
List<Notification> findByPost(Post post); List<Notification> findByPost(Post post);
List<Notification> findByComment(Comment comment); List<Notification> findByComment(Comment comment);

View File

@@ -8,6 +8,8 @@ import com.openisle.repository.UserRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import com.openisle.service.EmailSender; import com.openisle.service.EmailSender;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -180,15 +182,16 @@ public class NotificationService {
userRepository.save(user); userRepository.save(user);
} }
public List<Notification> listNotifications(String username, Boolean read) { public List<Notification> listNotifications(String username, Boolean read, int page, int pageSize) {
User user = userRepository.findByUsername(username) User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found")); .orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes(); Set<NotificationType> disabled = user.getDisabledNotificationTypes();
Pageable pageable = PageRequest.of(page, pageSize);
List<Notification> list; List<Notification> list;
if (read == null) { if (read == null) {
list = notificationRepository.findByUserOrderByCreatedAtDesc(user); list = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
} else { } else {
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read); list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
} }
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList()); return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
} }

View File

@@ -48,7 +48,7 @@
</div> </div>
<template v-else> <template v-else>
<div v-if="isLoadingMessage" class="loading-message"> <div v-if="isLoadingMessage && filteredNotifications.length === 0" class="loading-message">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch> <l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
</div> </div>
@@ -58,7 +58,7 @@
icon="fas fa-inbox" icon="fas fa-inbox"
/> />
<div class="timeline-container" v-if="filteredNotifications.length > 0"> <div v-else class="timeline-container">
<BaseTimeline :items="filteredNotifications"> <BaseTimeline :items="filteredNotifications">
<template #item="{ item }"> <template #item="{ item }">
<div class="notif-content" :class="{ read: item.read }"> <div class="notif-content" :class="{ read: item.read }">
@@ -505,13 +505,17 @@
</div> </div>
</template> </template>
</BaseTimeline> </BaseTimeline>
<div v-if="isLoadingMessage" class="loading-message">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
</div>
</div> </div>
</template> </template>
</div> </div>
</template> </template>
<script setup> <script setup>
import { computed, onMounted, ref } from 'vue' import { computed, onActivated, ref } from 'vue'
import { useScrollLoadMore } from '~/utils/loadMore'
import BasePlaceholder from '~/components/BasePlaceholder.vue' import BasePlaceholder from '~/components/BasePlaceholder.vue'
import BaseTimeline from '~/components/BaseTimeline.vue' import BaseTimeline from '~/components/BaseTimeline.vue'
import NotificationContainer from '~/components/NotificationContainer.vue' import NotificationContainer from '~/components/NotificationContainer.vue'
@@ -525,6 +529,9 @@ import {
markRead, markRead,
notifications, notifications,
markAllRead, markAllRead,
allLoaded,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification' } from '~/utils/notification'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
@@ -547,7 +554,7 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled) const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) { if (ok) {
pref.enabled = !pref.enabled pref.enabled = !pref.enabled
await fetchNotifications() await fetchNotifications(true)
await fetchUnreadCount() await fetchUnreadCount()
} else { } else {
toast.error('操作失败') toast.error('操作失败')
@@ -627,8 +634,14 @@ const formatType = (t) => {
} }
} }
const loadMore = async () => {
if (allLoaded.value) return
await fetchNotifications()
}
useScrollLoadMore(loadMore)
onActivated(() => { onActivated(() => {
fetchNotifications() fetchNotifications(true)
fetchPrefs() fetchPrefs()
}) })
</script> </script>

View File

@@ -118,175 +118,190 @@ export async function updateNotificationPreference(type, enabled) {
function createFetchNotifications() { function createFetchNotifications() {
const notifications = ref([]) const notifications = ref([])
const isLoadingMessage = ref(false) const isLoadingMessage = ref(false)
const fetchNotifications = async () => { const page = ref(0)
const pageSize = 50
const allLoaded = ref(false)
const fetchNotifications = async (reset = false) => {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
if (isLoadingMessage && notifications && markRead) { if (isLoadingMessage.value || (allLoaded.value && !reset)) return
try { try {
const token = getToken() const token = getToken()
if (!token) { if (!token) {
toast.error('请先登录') toast.error('请先登录')
return return
} }
isLoadingMessage.value = true if (reset) {
notifications.value = [] notifications.value = []
const res = await fetch(`${API_BASE_URL}/api/notifications`, { page.value = 0
allLoaded.value = false
}
isLoadingMessage.value = true
const res = await fetch(
`${API_BASE_URL}/api/notifications?page=${page.value}&pageSize=${pageSize}`,
{
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}) },
isLoadingMessage.value = false )
if (!res.ok) { isLoadingMessage.value = false
toast.error('获取通知失败') if (!res.ok) {
return toast.error('获取通知失败')
} return
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'REACTION') {
notifications.value.push({
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_VIEWED') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'USER_ACTIVITY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'FOLLOWED_POST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
} catch (e) {
console.error(e)
} }
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'REACTION') {
notifications.value.push({
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_VIEWED') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'USER_ACTIVITY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'FOLLOWED_POST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
if (data.length < pageSize) {
allLoaded.value = true
} else {
page.value++
}
} catch (e) {
console.error(e)
} }
} }
@@ -335,10 +350,16 @@ function createFetchNotifications() {
markRead, markRead,
notifications, notifications,
isLoadingMessage, isLoadingMessage,
markRead,
markAllRead, markAllRead,
allLoaded,
} }
} }
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } = export const {
createFetchNotifications() fetchNotifications,
markRead,
notifications,
isLoadingMessage,
markAllRead,
allLoaded,
} = createFetchNotifications()