mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-20 14:00:56 +08:00
Compare commits
41 Commits
codex/fix-
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0fa08e2260 | ||
|
|
38a49f7414 | ||
|
|
fb89c9fb25 | ||
|
|
e9458f5419 | ||
|
|
2d87c8f23d | ||
|
|
cb281e4030 | ||
|
|
9b85d77158 | ||
|
|
a3b28eafe4 | ||
|
|
805a8df7d3 | ||
|
|
02be045f55 | ||
|
|
ac3c7b7bec | ||
|
|
c344b5b4ae | ||
|
|
e7a1e1d159 | ||
|
|
30b56e54cf | ||
|
|
cc525c1c27 | ||
|
|
3f2829cd37 | ||
|
|
3258a42b44 | ||
|
|
a64fd71bbe | ||
|
|
1a12bec7b1 | ||
|
|
fbca19791a | ||
|
|
10b6fdd1cb | ||
|
|
7dd1f1b3d0 | ||
|
|
df92ff664c | ||
|
|
73168c1859 | ||
|
|
77856ff9af | ||
|
|
df49b21620 | ||
|
|
fbe2c66955 | ||
|
|
df7ca77652 | ||
|
|
fe84e3f2fa | ||
|
|
c307732696 | ||
|
|
35bcd2cdc2 | ||
|
|
a29bf7d860 | ||
|
|
27393c15f2 | ||
|
|
c91a787f29 | ||
|
|
6096712291 | ||
|
|
6d20addcde | ||
|
|
d8f9fd670c | ||
|
|
5ebe739917 | ||
|
|
022edc866a | ||
|
|
b06815cc59 | ||
|
|
f1b223a3c9 |
@@ -23,9 +23,19 @@ public class NotificationController {
|
|||||||
private final NotificationMapper notificationMapper;
|
private final NotificationMapper notificationMapper;
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||||
|
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||||
Authentication auth) {
|
Authentication auth) {
|
||||||
return notificationService.listNotifications(auth.getName(), read).stream()
|
return notificationService.listNotifications(auth.getName(), null, page, size).stream()
|
||||||
|
.map(notificationMapper::toDto)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/unread")
|
||||||
|
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||||
|
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||||
|
Authentication auth) {
|
||||||
|
return notificationService.listNotifications(auth.getName(), false, page, size).stream()
|
||||||
.map(notificationMapper::toDto)
|
.map(notificationMapper::toDto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,16 @@ public class PostController {
|
|||||||
postService.deletePost(id, auth.getName());
|
postService.deletePost(id, auth.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{id}/close")
|
||||||
|
public PostSummaryDto close(@PathVariable Long id, Authentication auth) {
|
||||||
|
return postMapper.toSummaryDto(postService.closePost(id, auth.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{id}/reopen")
|
||||||
|
public PostSummaryDto reopen(@PathVariable Long id, Authentication auth) {
|
||||||
|
return postMapper.toSummaryDto(postService.reopenPost(id, auth.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
public ResponseEntity<PostDetailDto> getPost(@PathVariable Long id, Authentication auth) {
|
public ResponseEntity<PostDetailDto> getPost(@PathVariable Long id, Authentication auth) {
|
||||||
String viewer = auth != null ? auth.getName() : null;
|
String viewer = auth != null ? auth.getName() : null;
|
||||||
|
|||||||
@@ -32,5 +32,6 @@ public class PostSummaryDto {
|
|||||||
private PostType type;
|
private PostType type;
|
||||||
private LotteryDto lottery;
|
private LotteryDto lottery;
|
||||||
private boolean rssExcluded;
|
private boolean rssExcluded;
|
||||||
|
private boolean closed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ public class PostMapper {
|
|||||||
dto.setStatus(post.getStatus());
|
dto.setStatus(post.getStatus());
|
||||||
dto.setPinnedAt(post.getPinnedAt());
|
dto.setPinnedAt(post.getPinnedAt());
|
||||||
dto.setRssExcluded(post.getRssExcluded() == null || post.getRssExcluded());
|
dto.setRssExcluded(post.getRssExcluded() == null || post.getRssExcluded());
|
||||||
|
dto.setClosed(post.isClosed());
|
||||||
|
|
||||||
List<ReactionDto> reactions = reactionService.getReactionsForPost(post.getId())
|
List<ReactionDto> reactions = reactionService.getReactionsForPost(post.getId())
|
||||||
.stream()
|
.stream()
|
||||||
|
|||||||
@@ -64,6 +64,9 @@ public class Post {
|
|||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
private PostType type = PostType.NORMAL;
|
private PostType type = PostType.NORMAL;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private boolean closed = false;
|
||||||
|
|
||||||
@Column
|
@Column
|
||||||
private LocalDateTime pinnedAt;
|
private LocalDateTime pinnedAt;
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ 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.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -13,7 +15,12 @@ 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);
|
||||||
|
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
|
||||||
|
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
|
||||||
|
Page<Notification> findByUserAndTypeNotInOrderByCreatedAtDesc(User user, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||||
|
Page<Notification> findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(User user, boolean read, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||||
long countByUserAndRead(User user, boolean read);
|
long countByUserAndRead(User user, boolean read);
|
||||||
|
long countByUserAndReadAndTypeNotIn(User user, boolean read, java.util.Collection<NotificationType> types);
|
||||||
List<Notification> findByPost(Post post);
|
List<Notification> findByPost(Post post);
|
||||||
List<Notification> findByComment(Comment comment);
|
List<Notification> findByComment(Comment comment);
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ public class CommentService {
|
|||||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
Post post = postRepository.findById(postId)
|
Post post = postRepository.findById(postId)
|
||||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||||
|
if (post.isClosed()) {
|
||||||
|
throw new IllegalStateException("Post closed");
|
||||||
|
}
|
||||||
Comment comment = new Comment();
|
Comment comment = new Comment();
|
||||||
comment.setAuthor(author);
|
comment.setAuthor(author);
|
||||||
comment.setPost(post);
|
comment.setPost(post);
|
||||||
@@ -94,6 +97,9 @@ public class CommentService {
|
|||||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
Comment parent = commentRepository.findById(parentId)
|
Comment parent = commentRepository.findById(parentId)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Comment not found"));
|
.orElseThrow(() -> new IllegalArgumentException("Comment not found"));
|
||||||
|
if (parent.getPost().isClosed()) {
|
||||||
|
throw new IllegalStateException("Post closed");
|
||||||
|
}
|
||||||
Comment comment = new Comment();
|
Comment comment = new Comment();
|
||||||
comment.setAuthor(author);
|
comment.setAuthor(author);
|
||||||
comment.setPost(parent.getPost());
|
comment.setPost(parent.getPost());
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import java.util.HashSet;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/** Service for creating and retrieving notifications. */
|
/** Service for creating and retrieving notifications. */
|
||||||
@Service
|
@Service
|
||||||
@@ -180,17 +179,26 @@ 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 size) {
|
||||||
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();
|
||||||
List<Notification> list;
|
org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
|
||||||
|
org.springframework.data.domain.Page<Notification> result;
|
||||||
if (read == null) {
|
if (read == null) {
|
||||||
list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
|
if (disabled.isEmpty()) {
|
||||||
|
result = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
|
||||||
|
} else {
|
||||||
|
result = notificationRepository.findByUserAndTypeNotInOrderByCreatedAtDesc(user, disabled, pageable);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
|
if (disabled.isEmpty()) {
|
||||||
|
result = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
|
||||||
|
} else {
|
||||||
|
result = notificationRepository.findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(user, read, disabled, pageable);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
return result.getContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void markRead(String username, List<Long> ids) {
|
public void markRead(String username, List<Long> ids) {
|
||||||
@@ -209,8 +217,10 @@ public class NotificationService {
|
|||||||
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();
|
||||||
return notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, false).stream()
|
if (disabled.isEmpty()) {
|
||||||
.filter(n -> !disabled.contains(n.getType())).count();
|
return notificationRepository.countByUserAndRead(user, false);
|
||||||
|
}
|
||||||
|
return notificationRepository.countByUserAndReadAndTypeNotIn(user, false, disabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
|
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
|
||||||
|
|||||||
@@ -512,6 +512,30 @@ public class PostService {
|
|||||||
return postRepository.save(post);
|
return postRepository.save(post);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Post closePost(Long id, String username) {
|
||||||
|
Post post = postRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
|
if (!user.getId().equals(post.getAuthor().getId()) && user.getRole() != Role.ADMIN) {
|
||||||
|
throw new IllegalArgumentException("Unauthorized");
|
||||||
|
}
|
||||||
|
post.setClosed(true);
|
||||||
|
return postRepository.save(post);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Post reopenPost(Long id, String username) {
|
||||||
|
Post post = postRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
|
if (!user.getId().equals(post.getAuthor().getId()) && user.getRole() != Role.ADMIN) {
|
||||||
|
throw new IllegalArgumentException("Unauthorized");
|
||||||
|
}
|
||||||
|
post.setClosed(false);
|
||||||
|
return postRepository.save(post);
|
||||||
|
}
|
||||||
|
|
||||||
@org.springframework.transaction.annotation.Transactional
|
@org.springframework.transaction.annotation.Transactional
|
||||||
public Post updatePost(Long id,
|
public Post updatePost(Long id,
|
||||||
String username,
|
String username,
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ class NotificationControllerTest {
|
|||||||
p.setId(2L);
|
p.setId(2L);
|
||||||
n.setPost(p);
|
n.setPost(p);
|
||||||
n.setCreatedAt(LocalDateTime.now());
|
n.setCreatedAt(LocalDateTime.now());
|
||||||
when(notificationService.listNotifications("alice", null))
|
when(notificationService.listNotifications("alice", null, 0, 30))
|
||||||
.thenReturn(List.of(n));
|
.thenReturn(List.of(n));
|
||||||
|
|
||||||
NotificationDto dto = new NotificationDto();
|
NotificationDto dto = new NotificationDto();
|
||||||
@@ -62,6 +62,24 @@ class NotificationControllerTest {
|
|||||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
.andExpect(jsonPath("$[0].post.id").value(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listUnreadNotifications() throws Exception {
|
||||||
|
Notification n = new Notification();
|
||||||
|
n.setId(5L);
|
||||||
|
n.setType(NotificationType.POST_VIEWED);
|
||||||
|
when(notificationService.listNotifications("alice", false, 0, 30))
|
||||||
|
.thenReturn(List.of(n));
|
||||||
|
|
||||||
|
NotificationDto dto = new NotificationDto();
|
||||||
|
dto.setId(5L);
|
||||||
|
when(notificationMapper.toDto(n)).thenReturn(dto);
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/notifications/unread")
|
||||||
|
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].id").value(5));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void markReadEndpoint() throws Exception {
|
void markReadEndpoint() throws Exception {
|
||||||
mockMvc.perform(post("/api/notifications/read")
|
mockMvc.perform(post("/api/notifications/read")
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ import org.mockito.Mockito;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -62,15 +65,17 @@ class NotificationServiceTest {
|
|||||||
User user = new User();
|
User user = new User();
|
||||||
user.setId(2L);
|
user.setId(2L);
|
||||||
user.setUsername("bob");
|
user.setUsername("bob");
|
||||||
|
user.setDisabledNotificationTypes(new HashSet<>());
|
||||||
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
Notification n = new Notification();
|
Notification n = new Notification();
|
||||||
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(n)));
|
||||||
|
|
||||||
List<Notification> list = service.listNotifications("bob", null);
|
List<Notification> list = service.listNotifications("bob", null, 0, 10);
|
||||||
|
|
||||||
assertEquals(1, list.size());
|
assertEquals(1, list.size());
|
||||||
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -87,6 +92,7 @@ class NotificationServiceTest {
|
|||||||
User user = new User();
|
User user = new User();
|
||||||
user.setId(3L);
|
user.setId(3L);
|
||||||
user.setUsername("carl");
|
user.setUsername("carl");
|
||||||
|
user.setDisabledNotificationTypes(new HashSet<>());
|
||||||
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
||||||
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
||||||
|
|
||||||
@@ -96,6 +102,56 @@ class NotificationServiceTest {
|
|||||||
verify(nRepo).countByUserAndRead(user, false);
|
verify(nRepo).countByUserAndRead(user, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listNotificationsFiltersDisabledTypes() {
|
||||||
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
UserRepository uRepo = mock(UserRepository.class);
|
||||||
|
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||||
|
EmailSender email = mock(EmailSender.class);
|
||||||
|
PushNotificationService push = mock(PushNotificationService.class);
|
||||||
|
Executor executor = Runnable::run;
|
||||||
|
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||||
|
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setId(4L);
|
||||||
|
user.setUsername("dana");
|
||||||
|
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
|
Notification n = new Notification();
|
||||||
|
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(n)));
|
||||||
|
|
||||||
|
List<Notification> list = service.listNotifications("dana", null, 0, 10);
|
||||||
|
|
||||||
|
assertEquals(1, list.size());
|
||||||
|
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void countUnreadFiltersDisabledTypes() {
|
||||||
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
UserRepository uRepo = mock(UserRepository.class);
|
||||||
|
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||||
|
EmailSender email = mock(EmailSender.class);
|
||||||
|
PushNotificationService push = mock(PushNotificationService.class);
|
||||||
|
Executor executor = Runnable::run;
|
||||||
|
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||||
|
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setId(5L);
|
||||||
|
user.setUsername("erin");
|
||||||
|
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
|
||||||
|
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
|
||||||
|
.thenReturn(2L);
|
||||||
|
|
||||||
|
long count = service.countUnread("erin");
|
||||||
|
|
||||||
|
assertEquals(2L, count);
|
||||||
|
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void createRegisterRequestNotificationsDeletesOldOnes() {
|
void createRegisterRequestNotificationsDeletesOldOnes() {
|
||||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<GlobalPopups />
|
<GlobalPopups />
|
||||||
|
<ConfirmDialog />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
import HeaderComponent from '~/components/HeaderComponent.vue'
|
import HeaderComponent from '~/components/HeaderComponent.vue'
|
||||||
import MenuComponent from '~/components/MenuComponent.vue'
|
import MenuComponent from '~/components/MenuComponent.vue'
|
||||||
import GlobalPopups from '~/components/GlobalPopups.vue'
|
import GlobalPopups from '~/components/GlobalPopups.vue'
|
||||||
|
import ConfirmDialog from '~/components/ConfirmDialog.vue'
|
||||||
import { useIsMobile } from '~/utils/screen'
|
import { useIsMobile } from '~/utils/screen'
|
||||||
|
|
||||||
const isMobile = useIsMobile()
|
const isMobile = useIsMobile()
|
||||||
|
|||||||
@@ -90,7 +90,8 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.vditor-toolbar--pin {
|
.vditor-toolbar--pin {
|
||||||
top: var(--header-height) !important;
|
top: calc(var(--header-height) + 1px) !important;
|
||||||
|
z-index: 2000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-panel {
|
.vditor-panel {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
getEditorTheme as getEditorThemeUtil,
|
getEditorTheme as getEditorThemeUtil,
|
||||||
getPreviewTheme as getPreviewThemeUtil,
|
getPreviewTheme as getPreviewThemeUtil,
|
||||||
} from '~/utils/vditor'
|
} from '~/utils/vditor'
|
||||||
|
import '~/assets/global.css'
|
||||||
import LoginOverlay from '~/components/LoginOverlay.vue'
|
import LoginOverlay from '~/components/LoginOverlay.vue'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
|
|||||||
@@ -57,7 +57,7 @@
|
|||||||
v-if="showEditor"
|
v-if="showEditor"
|
||||||
@submit="submitReply"
|
@submit="submitReply"
|
||||||
:loading="isWaitingForReply"
|
:loading="isWaitingForReply"
|
||||||
:disabled="!loggedIn"
|
:disabled="!loggedIn || postClosed"
|
||||||
:show-login-overlay="!loggedIn"
|
:show-login-overlay="!loggedIn"
|
||||||
:parent-user-name="comment.userName"
|
:parent-user-name="comment.userName"
|
||||||
/>
|
/>
|
||||||
@@ -76,6 +76,7 @@
|
|||||||
:level="level + 1"
|
:level="level + 1"
|
||||||
:default-show-replies="item.openReplies"
|
:default-show-replies="item.openReplies"
|
||||||
:post-author-id="postAuthorId"
|
:post-author-id="postAuthorId"
|
||||||
|
:post-closed="postClosed"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
@@ -122,6 +123,10 @@ const props = defineProps({
|
|||||||
type: [Number, String],
|
type: [Number, String],
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
postClosed: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits(['deleted'])
|
const emit = defineEmits(['deleted'])
|
||||||
@@ -148,6 +153,7 @@ const toggleReplies = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const toggleEditor = () => {
|
const toggleEditor = () => {
|
||||||
|
if (props.postClosed) return
|
||||||
showEditor.value = !showEditor.value
|
showEditor.value = !showEditor.value
|
||||||
if (showEditor.value) {
|
if (showEditor.value) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -213,6 +219,10 @@ const deleteComment = async () => {
|
|||||||
}
|
}
|
||||||
const submitReply = async (parentUserName, text, clear) => {
|
const submitReply = async (parentUserName, text, clear) => {
|
||||||
if (!text.trim()) return
|
if (!text.trim()) return
|
||||||
|
if (props.postClosed) {
|
||||||
|
toast.error('帖子已关闭')
|
||||||
|
return
|
||||||
|
}
|
||||||
isWaitingForReply.value = true
|
isWaitingForReply.value = true
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (!token) {
|
if (!token) {
|
||||||
|
|||||||
71
frontend_nuxt/components/ConfirmDialog.vue
Normal file
71
frontend_nuxt/components/ConfirmDialog.vue
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<template>
|
||||||
|
<BasePopup :visible="visible" @close="onCancel">
|
||||||
|
<div class="confirm-dialog" role="dialog" aria-modal="true">
|
||||||
|
<h3 class="confirm-title">{{ title }}</h3>
|
||||||
|
<p class="confirm-message">{{ message }}</p>
|
||||||
|
<div class="confirm-actions">
|
||||||
|
<div class="cancel-button" @click="onCancel">取消</div>
|
||||||
|
<div class="confirm-button" @click="onConfirm">确认</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BasePopup>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import BasePopup from '~/components/BasePopup.vue'
|
||||||
|
import { useConfirm } from '~/composables/useConfirm'
|
||||||
|
|
||||||
|
const { visible, title, message, onConfirm, onCancel } = useConfirm()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.confirm-dialog {
|
||||||
|
padding: 20px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.confirm-title {
|
||||||
|
margin-top: 0;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.confirm-message {
|
||||||
|
margin: 16px 0 20px;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: var(--text-secondary, #666);
|
||||||
|
}
|
||||||
|
.confirm-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.confirm-button,
|
||||||
|
.cancel-button {
|
||||||
|
min-width: 88px;
|
||||||
|
height: 36px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
}
|
||||||
|
.confirm-button {
|
||||||
|
background: var(--primary-color);
|
||||||
|
color: #fff;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.confirm-button:hover {
|
||||||
|
background: var(--primary-color-hover);
|
||||||
|
}
|
||||||
|
.cancel-button {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--primary-color);
|
||||||
|
border-color: currentColor;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.cancel-button:hover {
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
102
frontend_nuxt/components/InfiniteLoadMore.vue
Normal file
102
frontend_nuxt/components/InfiniteLoadMore.vue
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<template>
|
||||||
|
<!-- 当 done 后整个容器自动隐藏,不再占位 -->
|
||||||
|
<div v-show="!done" class="infinite-loadmore">
|
||||||
|
<div v-show="isLoading" class="loading-container bottom-loading" aria-live="polite">
|
||||||
|
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||||
|
</div>
|
||||||
|
<!-- 永久存在的底部触发器(由组件内部持有与观察) -->
|
||||||
|
<div ref="sentinel" class="load-more-trigger" aria-hidden="true"></div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
/** 父组件提供:执行“加载下一页”的函数
|
||||||
|
* 返回:
|
||||||
|
* - boolean:true 表示“已经没有更多数据(done)”
|
||||||
|
* - { done: boolean }:同上
|
||||||
|
*/
|
||||||
|
onLoad: { type: Function, required: true },
|
||||||
|
/** pause=true 时暂停观察(例如首屏/筛选加载过程) */
|
||||||
|
pause: { type: Boolean, default: false },
|
||||||
|
/** 预取范围,默认 200px */
|
||||||
|
rootMargin: { type: String, default: '200px 0px' },
|
||||||
|
/** 触发阈值 */
|
||||||
|
threshold: { type: Number, default: 0 },
|
||||||
|
})
|
||||||
|
|
||||||
|
const isLoading = ref(false)
|
||||||
|
const done = ref(false)
|
||||||
|
const sentinel = ref(null)
|
||||||
|
let io = null
|
||||||
|
|
||||||
|
const stopObserver = () => {
|
||||||
|
if (io) {
|
||||||
|
io.disconnect()
|
||||||
|
io = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const startObserver = () => {
|
||||||
|
if (!process.client || props.pause || done.value) return
|
||||||
|
stopObserver()
|
||||||
|
io = new IntersectionObserver(
|
||||||
|
async (entries) => {
|
||||||
|
const e = entries[0]
|
||||||
|
if (!e?.isIntersecting || isLoading.value || done.value) return
|
||||||
|
isLoading.value = true
|
||||||
|
try {
|
||||||
|
const res = await props.onLoad()
|
||||||
|
const finished = typeof res === 'boolean' ? res : !!(res && res.done)
|
||||||
|
if (finished) {
|
||||||
|
done.value = true
|
||||||
|
stopObserver()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ root: null, rootMargin: props.rootMargin, threshold: props.threshold },
|
||||||
|
)
|
||||||
|
if (sentinel.value) io.observe(sentinel.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
nextTick(startObserver)
|
||||||
|
})
|
||||||
|
onBeforeUnmount(stopObserver)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.pause,
|
||||||
|
(p) => {
|
||||||
|
if (p) stopObserver()
|
||||||
|
else nextTick(startObserver)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 父组件可选择性调用,用于外部强制重置(一般直接用 :key 重建更简单) */
|
||||||
|
const reset = () => {
|
||||||
|
done.value = false
|
||||||
|
nextTick(startObserver)
|
||||||
|
}
|
||||||
|
defineExpose({ reset })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.infinite-loadmore {
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 100px; /* 与原样式匹配 */
|
||||||
|
}
|
||||||
|
|
||||||
|
.load-more-trigger {
|
||||||
|
width: 100%;
|
||||||
|
height: 1px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
getEditorTheme as getEditorThemeUtil,
|
getEditorTheme as getEditorThemeUtil,
|
||||||
getPreviewTheme as getPreviewThemeUtil,
|
getPreviewTheme as getPreviewThemeUtil,
|
||||||
} from '~/utils/vditor'
|
} from '~/utils/vditor'
|
||||||
|
import '~/assets/global.css'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'PostEditor',
|
name: 'PostEditor',
|
||||||
|
|||||||
@@ -51,6 +51,10 @@ import { computed, onMounted, ref, watch } from 'vue'
|
|||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { authState, getToken } from '~/utils/auth'
|
import { authState, getToken } from '~/utils/auth'
|
||||||
import { reactionEmojiMap } from '~/utils/reactions'
|
import { reactionEmojiMap } from '~/utils/reactions'
|
||||||
|
import { useReactionTypes } from '~/composables/useReactionTypes'
|
||||||
|
|
||||||
|
const { reactionTypes, initialize } = useReactionTypes()
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
const emit = defineEmits(['update:modelValue'])
|
const emit = defineEmits(['update:modelValue'])
|
||||||
@@ -66,30 +70,6 @@ watch(
|
|||||||
)
|
)
|
||||||
|
|
||||||
const reactions = ref(props.modelValue)
|
const reactions = ref(props.modelValue)
|
||||||
const reactionTypes = ref([])
|
|
||||||
|
|
||||||
let cachedTypes = null
|
|
||||||
const fetchTypes = async () => {
|
|
||||||
if (cachedTypes) return cachedTypes
|
|
||||||
try {
|
|
||||||
const token = getToken()
|
|
||||||
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
|
|
||||||
headers: { Authorization: token ? `Bearer ${token}` : '' },
|
|
||||||
})
|
|
||||||
if (res.ok) {
|
|
||||||
cachedTypes = await res.json()
|
|
||||||
} else {
|
|
||||||
cachedTypes = []
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
cachedTypes = []
|
|
||||||
}
|
|
||||||
return cachedTypes
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(async () => {
|
|
||||||
reactionTypes.value = await fetchTypes()
|
|
||||||
})
|
|
||||||
|
|
||||||
const counts = computed(() => {
|
const counts = computed(() => {
|
||||||
const c = {}
|
const c = {}
|
||||||
@@ -200,6 +180,10 @@ const toggleReaction = async (type) => {
|
|||||||
toast.error('操作失败')
|
toast.error('操作失败')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await initialize()
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@@ -253,7 +237,7 @@ const toggleReaction = async (type) => {
|
|||||||
|
|
||||||
.make-reaction-item {
|
.make-reaction-item {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
padding: 10px;
|
padding: 4px;
|
||||||
opacity: 0.5;
|
opacity: 0.5;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
|
|||||||
52
frontend_nuxt/composables/useConfirm.ts
Normal file
52
frontend_nuxt/composables/useConfirm.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
// composables/useConfirm.ts
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
// 全局单例(SPA 下即可;Nuxt/SSR 下见文末“SSR 提醒”)
|
||||||
|
const visible = ref(false)
|
||||||
|
const title = ref('')
|
||||||
|
const message = ref('')
|
||||||
|
|
||||||
|
let resolver: ((ok: boolean) => void) | null = null
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
visible.value = false
|
||||||
|
title.value = ''
|
||||||
|
message.value = ''
|
||||||
|
resolver = null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useConfirm() {
|
||||||
|
/**
|
||||||
|
* 打开确认框,返回 Promise<boolean>
|
||||||
|
* - 确认 => resolve(true)
|
||||||
|
* - 取消/关闭 => resolve(false)
|
||||||
|
* 若并发调用,以最后一次为准(更简单直观)
|
||||||
|
*/
|
||||||
|
const confirm = (t: string, m: string) => {
|
||||||
|
title.value = t
|
||||||
|
message.value = m
|
||||||
|
visible.value = true
|
||||||
|
return new Promise<boolean>((resolve) => {
|
||||||
|
resolver = resolve
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const onConfirm = () => {
|
||||||
|
resolver?.(true)
|
||||||
|
reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onCancel = () => {
|
||||||
|
resolver?.(false)
|
||||||
|
reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
visible,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirm,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
}
|
||||||
|
}
|
||||||
52
frontend_nuxt/composables/useReactionTypes.js
Normal file
52
frontend_nuxt/composables/useReactionTypes.js
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const reactionTypes = ref([])
|
||||||
|
let isLoading = false
|
||||||
|
let isInitialized = false
|
||||||
|
|
||||||
|
export function useReactionTypes() {
|
||||||
|
const config = useRuntimeConfig()
|
||||||
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
|
|
||||||
|
const fetchReactionTypes = async () => {
|
||||||
|
if (isInitialized || isLoading) {
|
||||||
|
reactionTypes.value = [...(window.reactionTypes || [])]
|
||||||
|
return reactionTypes.value
|
||||||
|
}
|
||||||
|
|
||||||
|
isLoading = true
|
||||||
|
try {
|
||||||
|
const token = getToken()
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
|
||||||
|
headers: { Authorization: token ? `Bearer ${token}` : '' },
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
reactionTypes.value = await res.json()
|
||||||
|
window.reactionTypes = [...reactionTypes.value]
|
||||||
|
isInitialized = true
|
||||||
|
} else {
|
||||||
|
reactionTypes.value = []
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch reaction types:', error)
|
||||||
|
reactionTypes.value = []
|
||||||
|
} finally {
|
||||||
|
isLoading = false
|
||||||
|
}
|
||||||
|
return reactionTypes.value
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialize = async () => {
|
||||||
|
if (!isInitialized) {
|
||||||
|
await fetchReactionTypes()
|
||||||
|
}
|
||||||
|
return reactionTypes.value
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
reactionTypes: readonly(reactionTypes),
|
||||||
|
fetchReactionTypes,
|
||||||
|
initialize,
|
||||||
|
isInitialized: readonly(isInitialized)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -102,25 +102,33 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div v-else-if="selectedTopic === '热门'" class="placeholder-container">
|
<div v-else-if="selectedTopic === '热门'" class="placeholder-container">
|
||||||
热门帖子功能开发中,敬请期待。
|
热门帖子功能开发中,敬请期待。
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="placeholder-container">分类浏览功能开发中,敬请期待。</div>
|
<div v-else class="placeholder-container">分类浏览功能开发中,敬请期待。</div>
|
||||||
<div v-if="isLoadingMore && articles.length > 0" class="loading-container bottom-loading">
|
|
||||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
<!-- ✅ 通用“底部加载更多”组件(自管 loading/observer/并发) -->
|
||||||
</div>
|
<InfiniteLoadMore
|
||||||
|
v-if="articles.length > 0"
|
||||||
|
:key="ioKey"
|
||||||
|
:on-load="fetchNextPage"
|
||||||
|
:pause="pendingFirst"
|
||||||
|
root-margin="200px 0px"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, ref, watch } from 'vue'
|
import { computed, onMounted, onBeforeUnmount, nextTick, ref, watch } from 'vue'
|
||||||
import ArticleCategory from '~/components/ArticleCategory.vue'
|
import ArticleCategory from '~/components/ArticleCategory.vue'
|
||||||
import ArticleTags from '~/components/ArticleTags.vue'
|
import ArticleTags from '~/components/ArticleTags.vue'
|
||||||
import CategorySelect from '~/components/CategorySelect.vue'
|
import CategorySelect from '~/components/CategorySelect.vue'
|
||||||
import SearchDropdown from '~/components/SearchDropdown.vue'
|
import SearchDropdown from '~/components/SearchDropdown.vue'
|
||||||
import TagSelect from '~/components/TagSelect.vue'
|
import TagSelect from '~/components/TagSelect.vue'
|
||||||
|
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||||
import { getToken } from '~/utils/auth'
|
import { getToken } from '~/utils/auth'
|
||||||
import { useScrollLoadMore } from '~/utils/loadMore'
|
|
||||||
import { stripMarkdown } from '~/utils/markdown'
|
import { stripMarkdown } from '~/utils/markdown'
|
||||||
import { useIsMobile } from '~/utils/screen'
|
import { useIsMobile } from '~/utils/screen'
|
||||||
import TimeManager from '~/utils/time'
|
import TimeManager from '~/utils/time'
|
||||||
@@ -144,8 +152,6 @@ const route = useRoute()
|
|||||||
const tagOptions = ref([])
|
const tagOptions = ref([])
|
||||||
const categoryOptions = ref([])
|
const categoryOptions = ref([])
|
||||||
|
|
||||||
const isLoadingMore = ref(false)
|
|
||||||
|
|
||||||
const topics = ref(['最新回复', '最新', '排行榜' /*, '热门', '类别'*/])
|
const topics = ref(['最新回复', '最新', '排行榜' /*, '热门', '类别'*/])
|
||||||
const selectedTopicCookie = useCookie('homeTab')
|
const selectedTopicCookie = useCookie('homeTab')
|
||||||
const selectedTopic = ref(
|
const selectedTopic = ref(
|
||||||
@@ -162,7 +168,6 @@ const articles = ref([])
|
|||||||
const page = ref(0)
|
const page = ref(0)
|
||||||
const pageSize = 10
|
const pageSize = 10
|
||||||
const isMobile = useIsMobile()
|
const isMobile = useIsMobile()
|
||||||
const allLoaded = ref(false)
|
|
||||||
|
|
||||||
/** URL 参数 -> 本地筛选值 **/
|
/** URL 参数 -> 本地筛选值 **/
|
||||||
const selectedCategorySet = (category) => {
|
const selectedCategorySet = (category) => {
|
||||||
@@ -286,80 +291,54 @@ const {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
/** 首屏/筛选变更:重置分页并灌入 firstPage **/
|
/** 首屏/筛选变更:重置分页并灌入 firstPage(InfiniteLoadMore 会凭 key 重建状态) **/
|
||||||
watch(
|
watch(
|
||||||
firstPage,
|
firstPage,
|
||||||
(data) => {
|
(data) => {
|
||||||
page.value = 0
|
page.value = 0
|
||||||
articles.value = [...(data || [])]
|
articles.value = [...(data || [])]
|
||||||
allLoaded.value = (data?.length || 0) < pageSize
|
|
||||||
},
|
},
|
||||||
{ immediate: true },
|
{ immediate: true },
|
||||||
)
|
)
|
||||||
|
|
||||||
/** —— 滚动加载更多 —— **/
|
/** —— 提供给 InfiniteLoadMore 的加载函数 —— **/
|
||||||
let inflight = null
|
|
||||||
const fetchNextPage = async () => {
|
const fetchNextPage = async () => {
|
||||||
if (allLoaded.value || pendingFirst.value || inflight) return
|
// 若首屏仍在 pending,由组件 pause 控制,这里兜底返回“未完成”
|
||||||
|
if (pendingFirst.value) return false
|
||||||
|
|
||||||
const nextPage = page.value + 1
|
const nextPage = page.value + 1
|
||||||
isLoadingMore.value = true
|
const res = await $fetch(buildUrl({ pageNo: nextPage }), { headers: tokenHeader.value })
|
||||||
inflight = $fetch(buildUrl({ pageNo: nextPage }), { headers: tokenHeader.value })
|
const data = Array.isArray(res) ? res : []
|
||||||
.then((res) => {
|
const mapped = data.map((p) => ({
|
||||||
const data = Array.isArray(res) ? res : []
|
id: p.id,
|
||||||
const mapped = data.map((p) => ({
|
title: p.title,
|
||||||
id: p.id,
|
description: p.content,
|
||||||
title: p.title,
|
category: p.category,
|
||||||
description: p.content,
|
tags: p.tags || [],
|
||||||
category: p.category,
|
members: (p.participants || []).map((m) => ({ id: m.id, avatar: m.avatar })),
|
||||||
tags: p.tags || [],
|
comments: p.commentCount,
|
||||||
members: (p.participants || []).map((m) => ({ id: m.id, avatar: m.avatar })),
|
views: p.views,
|
||||||
comments: p.commentCount,
|
time: TimeManager.format(
|
||||||
views: p.views,
|
selectedTopic.value === '最新回复' ? p.lastReplyAt || p.createdAt : p.createdAt,
|
||||||
time: TimeManager.format(
|
),
|
||||||
selectedTopic.value === '最新回复' ? p.lastReplyAt || p.createdAt : p.createdAt,
|
pinned: Boolean(p.pinned ?? p.pinnedAt ?? p.pinned_at),
|
||||||
),
|
type: p.type,
|
||||||
pinned: Boolean(p.pinned ?? p.pinnedAt ?? p.pinned_at),
|
}))
|
||||||
type: p.type,
|
articles.value.push(...mapped)
|
||||||
}))
|
|
||||||
articles.value.push(...mapped)
|
const done = data.length < pageSize
|
||||||
if (data.length < pageSize) {
|
if (!done) page.value = nextPage
|
||||||
allLoaded.value = true
|
return done // ✅ 返回给组件,决定是否停止观察
|
||||||
} else {
|
|
||||||
page.value = nextPage
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
inflight = null
|
|
||||||
isLoadingMore.value = false
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 绑定滚动加载(避免挂载瞬间触发) **/
|
/** 选项首屏加载与状态持久 **/
|
||||||
let initialReady = false
|
|
||||||
const loadMoreGuarded = async () => {
|
|
||||||
if (!initialReady) return
|
|
||||||
await fetchNextPage()
|
|
||||||
}
|
|
||||||
useScrollLoadMore(loadMoreGuarded)
|
|
||||||
watch(
|
|
||||||
articles,
|
|
||||||
() => {
|
|
||||||
if (!initialReady && articles.value.length) initialReady = true
|
|
||||||
},
|
|
||||||
{ immediate: true },
|
|
||||||
)
|
|
||||||
|
|
||||||
/** 切换分类/标签/Tab:useAsyncData 已 watch,这里只需确保 options 加载 **/
|
|
||||||
watch([selectedCategory, selectedTags], () => {
|
watch([selectedCategory, selectedTags], () => {
|
||||||
loadOptions()
|
loadOptions()
|
||||||
})
|
})
|
||||||
watch(selectedTopic, (val) => {
|
watch(selectedTopic, (val) => {
|
||||||
// 仅当需要额外选项时加载
|
|
||||||
loadOptions()
|
loadOptions()
|
||||||
selectedTopicCookie.value = val
|
selectedTopicCookie.value = val
|
||||||
if (process.client) {
|
if (process.client) localStorage.setItem('homeTab', val)
|
||||||
localStorage.setItem('homeTab', val)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
/** 选项首屏加载:服务端执行一次;客户端兜底 **/
|
/** 选项首屏加载:服务端执行一次;客户端兜底 **/
|
||||||
@@ -368,9 +347,14 @@ if (import.meta.server) {
|
|||||||
}
|
}
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
if (categoryOptions.value.length === 0 && tagOptions.value.length === 0) loadOptions()
|
if (categoryOptions.value.length === 0 && tagOptions.value.length === 0) loadOptions()
|
||||||
|
|
||||||
window.addEventListener('refresh-home', refreshFirst)
|
window.addEventListener('refresh-home', refreshFirst)
|
||||||
})
|
})
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('refresh-home', refreshFirst)
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 供 InfiniteLoadMore 重建用的 key:筛选/Tab 改变即重建内部状态 */
|
||||||
|
const ioKey = computed(() => asyncKey.value.join('::'))
|
||||||
|
|
||||||
/** 其他工具函数 **/
|
/** 其他工具函数 **/
|
||||||
const sanitizeDescription = (text) => stripMarkdown(text)
|
const sanitizeDescription = (text) => stripMarkdown(text)
|
||||||
@@ -407,6 +391,7 @@ const sanitizeDescription = (text) => stripMarkdown(text)
|
|||||||
height: 200px;
|
height: 200px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 这里的 bottom-loading 可保留给首屏 loading 使用;InfiniteLoadMore 自带同名样式也兼容 */
|
||||||
.bottom-loading {
|
.bottom-loading {
|
||||||
height: 100px;
|
height: 100px;
|
||||||
}
|
}
|
||||||
@@ -550,6 +535,7 @@ const sanitizeDescription = (text) => stripMarkdown(text)
|
|||||||
}
|
}
|
||||||
|
|
||||||
.article-item-description {
|
.article-item-description {
|
||||||
|
max-width: 100%;
|
||||||
margin-top: 10px;
|
margin-top: 10px;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: gray;
|
color: gray;
|
||||||
|
|||||||
@@ -35,7 +35,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="other-login-page-content">
|
<div class="other-login-page-content">
|
||||||
<div class="login-page-button" @click="googleAuthorize">
|
<div class="login-page-button" @click="loginWithGoogle">
|
||||||
<img class="login-page-button-icon" src="../assets/icons/google.svg" alt="Google Logo" />
|
<img class="login-page-button-icon" src="../assets/icons/google.svg" alt="Google Logo" />
|
||||||
<div class="login-page-button-text">Google 登录</div>
|
<div class="login-page-button-text">Google 登录</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -106,6 +106,9 @@ const submitLogin = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const loginWithGoogle = () => {
|
||||||
|
googleAuthorize()
|
||||||
|
}
|
||||||
const loginWithGithub = () => {
|
const loginWithGithub = () => {
|
||||||
githubAuthorize()
|
githubAuthorize()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,13 +53,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<BasePlaceholder
|
<BasePlaceholder
|
||||||
v-else-if="filteredNotifications.length === 0"
|
v-else-if="notifications.length === 0"
|
||||||
text="暂时没有消息 :)"
|
text="暂时没有消息 :)"
|
||||||
icon="fas fa-inbox"
|
icon="fas fa-inbox"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div class="timeline-container" v-if="filteredNotifications.length > 0">
|
<div class="timeline-container" v-if="notifications.length > 0">
|
||||||
<BaseTimeline :items="filteredNotifications">
|
<BaseTimeline :items="notifications">
|
||||||
<template #item="{ item }">
|
<template #item="{ item }">
|
||||||
<div class="notif-content" :class="{ read: item.read }">
|
<div class="notif-content" :class="{ read: item.read }">
|
||||||
<span v-if="!item.read" class="unread-dot"></span>
|
<span v-if="!item.read" class="unread-dot"></span>
|
||||||
@@ -505,16 +505,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
|
<InfiniteLoadMore :key="selectedTab" :on-load="loadMore" :pause="isLoadingMessage" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { ref, watch, onActivated } from 'vue'
|
||||||
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'
|
||||||
|
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { authState, getToken } from '~/utils/auth'
|
import { authState, getToken } from '~/utils/auth'
|
||||||
import { stripMarkdownLength } from '~/utils/markdown'
|
import { stripMarkdownLength } from '~/utils/markdown'
|
||||||
@@ -525,6 +527,9 @@ import {
|
|||||||
markRead,
|
markRead,
|
||||||
notifications,
|
notifications,
|
||||||
markAllRead,
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
|
fetchNotificationPreferences,
|
||||||
|
updateNotificationPreference,
|
||||||
} from '~/utils/notification'
|
} from '~/utils/notification'
|
||||||
import TimeManager from '~/utils/time'
|
import TimeManager from '~/utils/time'
|
||||||
|
|
||||||
@@ -535,9 +540,25 @@ const selectedTab = ref(
|
|||||||
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
||||||
)
|
)
|
||||||
const notificationPrefs = ref([])
|
const notificationPrefs = ref([])
|
||||||
const filteredNotifications = computed(() =>
|
const page = ref(0)
|
||||||
selectedTab.value === 'all' ? notifications.value : notifications.value.filter((n) => !n.read),
|
const pageSize = 30
|
||||||
)
|
|
||||||
|
const loadMore = async () => {
|
||||||
|
if (!hasMore.value) return true
|
||||||
|
page.value++
|
||||||
|
await fetchNotifications({
|
||||||
|
page: page.value,
|
||||||
|
size: pageSize,
|
||||||
|
unread: selectedTab.value === 'unread',
|
||||||
|
append: true,
|
||||||
|
})
|
||||||
|
return !hasMore.value
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(selectedTab, async (tab) => {
|
||||||
|
page.value = 0
|
||||||
|
await fetchNotifications({ page: 0, size: pageSize, unread: tab === 'unread' })
|
||||||
|
})
|
||||||
|
|
||||||
const fetchPrefs = async () => {
|
const fetchPrefs = async () => {
|
||||||
notificationPrefs.value = await fetchNotificationPreferences()
|
notificationPrefs.value = await fetchNotificationPreferences()
|
||||||
@@ -547,7 +568,11 @@ 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({
|
||||||
|
page: page.value,
|
||||||
|
size: pageSize,
|
||||||
|
unread: selectedTab.value === 'unread',
|
||||||
|
})
|
||||||
await fetchUnreadCount()
|
await fetchUnreadCount()
|
||||||
} else {
|
} else {
|
||||||
toast.error('操作失败')
|
toast.error('操作失败')
|
||||||
@@ -627,8 +652,9 @@ const formatType = (t) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onActivated(() => {
|
onActivated(async () => {
|
||||||
fetchNotifications()
|
page.value = 0
|
||||||
|
await fetchNotifications({ page: 0, size: pageSize, unread: selectedTab.value === 'unread' })
|
||||||
fetchPrefs()
|
fetchPrefs()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
@@ -644,8 +670,6 @@ onActivated(() => {
|
|||||||
.message-page {
|
.message-page {
|
||||||
background-color: var(--background-color);
|
background-color: var(--background-color);
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
height: calc(100vh - var(--header-height));
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.message-page-header {
|
.message-page-header {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
<div class="article-title-container-right">
|
<div class="article-title-container-right">
|
||||||
<div v-if="status === 'PENDING'" class="article-pending-button">审核中</div>
|
<div v-if="status === 'PENDING'" class="article-pending-button">审核中</div>
|
||||||
<div v-if="status === 'REJECTED'" class="article-block-button">已拒绝</div>
|
<div v-if="status === 'REJECTED'" class="article-block-button">已拒绝</div>
|
||||||
|
<div v-if="closed" class="article-closed-button">已关闭</div>
|
||||||
<div
|
<div
|
||||||
v-if="loggedIn && !isAuthor && !subscribed"
|
v-if="loggedIn && !isAuthor && !subscribed"
|
||||||
class="article-subscribe-button"
|
class="article-subscribe-button"
|
||||||
@@ -171,7 +172,7 @@
|
|||||||
<CommentEditor
|
<CommentEditor
|
||||||
@submit="postComment"
|
@submit="postComment"
|
||||||
:loading="isWaitingPostingComment"
|
:loading="isWaitingPostingComment"
|
||||||
:disabled="!loggedIn"
|
:disabled="!loggedIn || closed"
|
||||||
:show-login-overlay="!loggedIn"
|
:show-login-overlay="!loggedIn"
|
||||||
:parent-user-name="author.username"
|
:parent-user-name="author.username"
|
||||||
/>
|
/>
|
||||||
@@ -196,6 +197,7 @@
|
|||||||
:level="0"
|
:level="0"
|
||||||
:default-show-replies="item.openReplies"
|
:default-show-replies="item.openReplies"
|
||||||
:post-author-id="author.id"
|
:post-author-id="author.id"
|
||||||
|
:post-closed="closed"
|
||||||
@deleted="onCommentDeleted"
|
@deleted="onCommentDeleted"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
@@ -232,7 +234,16 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch, watchEffect } from 'vue'
|
import {
|
||||||
|
ref,
|
||||||
|
computed,
|
||||||
|
onMounted,
|
||||||
|
onBeforeUnmount,
|
||||||
|
nextTick,
|
||||||
|
watch,
|
||||||
|
watchEffect,
|
||||||
|
onActivated,
|
||||||
|
} from 'vue'
|
||||||
import VueEasyLightbox from 'vue-easy-lightbox'
|
import VueEasyLightbox from 'vue-easy-lightbox'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import CommentItem from '~/components/CommentItem.vue'
|
import CommentItem from '~/components/CommentItem.vue'
|
||||||
@@ -251,6 +262,8 @@ import { useRouter } from 'vue-router'
|
|||||||
import { useIsMobile } from '~/utils/screen'
|
import { useIsMobile } from '~/utils/screen'
|
||||||
import Dropdown from '~/components/Dropdown.vue'
|
import Dropdown from '~/components/Dropdown.vue'
|
||||||
import { ClientOnly } from '#components'
|
import { ClientOnly } from '#components'
|
||||||
|
import { useConfirm } from '~/composables/useConfirm'
|
||||||
|
const { confirm } = useConfirm()
|
||||||
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
@@ -267,6 +280,7 @@ const tags = ref([])
|
|||||||
const postReactions = ref([])
|
const postReactions = ref([])
|
||||||
const comments = ref([])
|
const comments = ref([])
|
||||||
const status = ref('PUBLISHED')
|
const status = ref('PUBLISHED')
|
||||||
|
const closed = ref(false)
|
||||||
const pinnedAt = ref(null)
|
const pinnedAt = ref(null)
|
||||||
const rssExcluded = ref(false)
|
const rssExcluded = ref(false)
|
||||||
const isWaitingPostingComment = ref(false)
|
const isWaitingPostingComment = ref(false)
|
||||||
@@ -349,7 +363,12 @@ const articleMenuItems = computed(() => {
|
|||||||
const items = []
|
const items = []
|
||||||
if (isAuthor.value || isAdmin.value) {
|
if (isAuthor.value || isAdmin.value) {
|
||||||
items.push({ text: '编辑文章', onClick: () => editPost() })
|
items.push({ text: '编辑文章', onClick: () => editPost() })
|
||||||
items.push({ text: '删除文章', color: 'red', onClick: () => deletePost() })
|
items.push({ text: '删除文章', color: 'red', onClick: deletePost })
|
||||||
|
if (closed.value) {
|
||||||
|
items.push({ text: '重新打开帖子', onClick: () => reopenPost() })
|
||||||
|
} else {
|
||||||
|
items.push({ text: '关闭帖子', onClick: () => closePost() })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (isAdmin.value) {
|
if (isAdmin.value) {
|
||||||
if (pinnedAt.value) {
|
if (pinnedAt.value) {
|
||||||
@@ -485,6 +504,7 @@ watchEffect(() => {
|
|||||||
postReactions.value = data.reactions || []
|
postReactions.value = data.reactions || []
|
||||||
subscribed.value = !!data.subscribed
|
subscribed.value = !!data.subscribed
|
||||||
status.value = data.status
|
status.value = data.status
|
||||||
|
closed.value = data.closed
|
||||||
pinnedAt.value = data.pinnedAt
|
pinnedAt.value = data.pinnedAt
|
||||||
rssExcluded.value = data.rssExcluded
|
rssExcluded.value = data.rssExcluded
|
||||||
postTime.value = TimeManager.format(data.createdAt)
|
postTime.value = TimeManager.format(data.createdAt)
|
||||||
@@ -544,6 +564,10 @@ const onSliderInput = (e) => {
|
|||||||
|
|
||||||
const postComment = async (parentUserName, text, clear) => {
|
const postComment = async (parentUserName, text, clear) => {
|
||||||
if (!text.trim()) return
|
if (!text.trim()) return
|
||||||
|
if (closed.value) {
|
||||||
|
toast.error('帖子已关闭')
|
||||||
|
return
|
||||||
|
}
|
||||||
console.debug('Posting comment', { postId, text })
|
console.debug('Posting comment', { postId, text })
|
||||||
isWaitingPostingComment.value = true
|
isWaitingPostingComment.value = true
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
@@ -682,24 +706,62 @@ const includeRss = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const closePost = async () => {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) return
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}/close`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
closed.value = true
|
||||||
|
toast.success('已关闭')
|
||||||
|
await refreshPost()
|
||||||
|
} else {
|
||||||
|
toast.error('操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const reopenPost = async () => {
|
||||||
|
const token = getToken()
|
||||||
|
if (!token) return
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}/reopen`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
closed.value = false
|
||||||
|
toast.success('已重新打开')
|
||||||
|
await refreshPost()
|
||||||
|
} else {
|
||||||
|
toast.error('操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const editPost = () => {
|
const editPost = () => {
|
||||||
navigateTo(`/posts/${postId}/edit`, { replace: true })
|
navigateTo(`/posts/${postId}/edit`, { replace: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const deletePost = async () => {
|
const deletePost = async () => {
|
||||||
const token = getToken()
|
try {
|
||||||
if (!token) {
|
const ok = await confirm('删除帖子', '此操作不可恢复,确认要删除吗?')
|
||||||
toast.error('请先登录')
|
if (!ok) return
|
||||||
return
|
const token = getToken()
|
||||||
}
|
if (!token) {
|
||||||
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}`, {
|
toast.error('请先登录')
|
||||||
method: 'DELETE',
|
return
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
}
|
||||||
})
|
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}`, {
|
||||||
if (res.ok) {
|
method: 'DELETE',
|
||||||
toast.success('已删除')
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
navigateTo('/', { replace: true })
|
})
|
||||||
} else {
|
if (res.ok) {
|
||||||
|
toast.success('已删除')
|
||||||
|
navigateTo('/', { replace: true })
|
||||||
|
} else {
|
||||||
|
toast.error('操作失败')
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
toast.error('操作失败')
|
toast.error('操作失败')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -812,6 +874,11 @@ const gotoProfile = () => {
|
|||||||
navigateTo(`/users/${author.value.id}`, { replace: true })
|
navigateTo(`/users/${author.value.id}`, { replace: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onActivated(async () => {
|
||||||
|
await refreshPost()
|
||||||
|
await fetchComments()
|
||||||
|
})
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await fetchComments()
|
await fetchComments()
|
||||||
const hash = location.hash
|
const hash = location.hash
|
||||||
@@ -845,6 +912,10 @@ onMounted(async () => {
|
|||||||
width: calc(85% - 40px);
|
width: calc(85% - 40px);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.info-content-text p code {
|
||||||
|
padding: 2px 4px;
|
||||||
|
}
|
||||||
|
|
||||||
.post-page-scroller-container {
|
.post-page-scroller-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -1024,6 +1095,15 @@ onMounted(async () => {
|
|||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.article-closed-button {
|
||||||
|
background-color: var(--background-color);
|
||||||
|
color: gray;
|
||||||
|
border: 1px solid gray;
|
||||||
|
padding: 5px 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
.article-title {
|
.article-title {
|
||||||
font-size: 30px;
|
font-size: 30px;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
import { ref, onMounted, onUnmounted, onActivated, nextTick } from 'vue'
|
|
||||||
|
|
||||||
export function useScrollLoadMore(loadMore, offset = 50) {
|
|
||||||
const savedScrollTop = ref(0)
|
|
||||||
|
|
||||||
const handleScroll = () => {
|
|
||||||
if (!process.client) return
|
|
||||||
const scrollTop = window.scrollY || document.documentElement.scrollTop
|
|
||||||
const scrollHeight = document.documentElement.scrollHeight
|
|
||||||
const windowHeight = window.innerHeight
|
|
||||||
savedScrollTop.value = scrollTop
|
|
||||||
if (scrollHeight - (scrollTop + windowHeight) <= offset) {
|
|
||||||
loadMore()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
if (process.client) {
|
|
||||||
window.addEventListener('scroll', handleScroll, { passive: true })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
if (process.client) {
|
|
||||||
window.removeEventListener('scroll', handleScroll)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
onActivated(() => {
|
|
||||||
if (process.client) {
|
|
||||||
nextTick(() => {
|
|
||||||
window.scrollTo({ top: savedScrollTop.value })
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return { savedScrollTop }
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import hljs from 'highlight.js'
|
import hljs from 'highlight.js/lib/common'
|
||||||
|
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
const theme =
|
const theme =
|
||||||
document.documentElement.dataset.theme ||
|
document.documentElement.dataset.theme ||
|
||||||
|
|||||||
@@ -118,175 +118,162 @@ 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 hasMore = ref(true)
|
||||||
|
|
||||||
|
const fetchNotifications = async ({
|
||||||
|
page = 0,
|
||||||
|
size = 30,
|
||||||
|
unread = false,
|
||||||
|
append = 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) {
|
try {
|
||||||
try {
|
const token = getToken()
|
||||||
const token = getToken()
|
if (!token) {
|
||||||
if (!token) {
|
toast.error('请先登录')
|
||||||
toast.error('请先登录')
|
return
|
||||||
return
|
}
|
||||||
}
|
if (!append) notifications.value = []
|
||||||
isLoadingMessage.value = true
|
isLoadingMessage.value = true
|
||||||
notifications.value = []
|
const res = await fetch(
|
||||||
const res = await fetch(`${API_BASE_URL}/api/notifications`, {
|
`${API_BASE_URL}/api/notifications${unread ? '/unread' : ''}?page=${page}&size=${size}`,
|
||||||
|
{
|
||||||
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()
|
||||||
|
const arr = []
|
||||||
|
|
||||||
|
for (const n of data) {
|
||||||
|
if (n.type === 'COMMENT_REPLY') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.comment.author.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'REACTION') {
|
||||||
|
arr.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') {
|
||||||
|
arr.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' || n.type === 'LOTTERY_DRAW') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.post) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/posts/${n.post.id}`)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'POST_UPDATED' || n.type === 'USER_ACTIVITY') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.comment.author.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'MENTION') {
|
||||||
|
arr.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') {
|
||||||
|
arr.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' ||
|
||||||
|
n.type === 'POST_SUBSCRIBED' ||
|
||||||
|
n.type === 'POST_UNSUBSCRIBED'
|
||||||
|
) {
|
||||||
|
arr.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') {
|
||||||
|
arr.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') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (append) notifications.value.push(...arr)
|
||||||
|
else notifications.value = arr
|
||||||
|
hasMore.value = data.length === size
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
isLoadingMessage.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -335,10 +322,16 @@ function createFetchNotifications() {
|
|||||||
markRead,
|
markRead,
|
||||||
notifications,
|
notifications,
|
||||||
isLoadingMessage,
|
isLoadingMessage,
|
||||||
markRead,
|
|
||||||
markAllRead,
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
|
export const {
|
||||||
createFetchNotifications()
|
fetchNotifications,
|
||||||
|
markRead,
|
||||||
|
notifications,
|
||||||
|
isLoadingMessage,
|
||||||
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
|
} = createFetchNotifications()
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import Vditor from 'vditor'
|
|||||||
import { getToken, authState } from './auth'
|
import { getToken, authState } from './auth'
|
||||||
import { searchUsers, fetchFollowings, fetchAdmins } from './user'
|
import { searchUsers, fetchFollowings, fetchAdmins } from './user'
|
||||||
import { tiebaEmoji } from './tiebaEmoji'
|
import { tiebaEmoji } from './tiebaEmoji'
|
||||||
import '~/assets/global.css'
|
|
||||||
|
|
||||||
export function getEditorTheme() {
|
export function getEditorTheme() {
|
||||||
return document.documentElement.dataset.theme === 'dark' ? 'dark' : 'classic'
|
return document.documentElement.dataset.theme === 'dark' ? 'dark' : 'classic'
|
||||||
|
|||||||
Reference in New Issue
Block a user