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
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) {
return notificationService.listNotifications(auth.getName(), read).stream()
return notificationService.listNotifications(auth.getName(), read, page, pageSize).stream()
.map(notificationMapper::toDto)
.collect(Collectors.toList());
}

View File

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

View File

@@ -8,6 +8,8 @@ import com.openisle.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import com.openisle.service.EmailSender;
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 com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.transaction.annotation.Transactional;
@@ -180,15 +182,16 @@ public class NotificationService {
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)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
Pageable pageable = PageRequest.of(page, pageSize);
List<Notification> list;
if (read == null) {
list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
list = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
} else {
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
}
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
}

View File

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

View File

@@ -118,175 +118,190 @@ export async function updateNotificationPreference(type, enabled) {
function createFetchNotifications() {
const notifications = ref([])
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 API_BASE_URL = config.public.apiBaseUrl
if (isLoadingMessage && notifications && markRead) {
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return
}
isLoadingMessage.value = true
if (isLoadingMessage.value || (allLoaded.value && !reset)) return
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return
}
if (reset) {
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: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
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)
},
)
isLoadingMessage.value = false
if (!res.ok) {
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],
})
}
}
if (data.length < pageSize) {
allLoaded.value = true
} else {
page.value++
}
} catch (e) {
console.error(e)
}
}
@@ -335,10 +350,16 @@ function createFetchNotifications() {
markRead,
notifications,
isLoadingMessage,
markRead,
markAllRead,
allLoaded,
}
}
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
createFetchNotifications()
export const {
fetchNotifications,
markRead,
notifications,
isLoadingMessage,
markAllRead,
allLoaded,
} = createFetchNotifications()