mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-26 16:10:49 +08:00
Compare commits
18 Commits
codex/add-
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd9ce67d4b | ||
|
|
2b242367d7 | ||
|
|
3f0cd2bf0f | ||
|
|
a98a631378 | ||
|
|
7701d359dc | ||
|
|
ffd9ef8a32 | ||
|
|
36cd5ab171 | ||
|
|
58d86fa065 | ||
|
|
df71cf901b | ||
|
|
ac3fc6702a | ||
|
|
b0eef220a6 | ||
|
|
02d366e2c7 | ||
|
|
6409531a64 | ||
|
|
175ab79b27 | ||
|
|
b543953d22 | ||
|
|
b4fef68af5 | ||
|
|
6c48a38212 | ||
|
|
8a3e4d8e98 |
@@ -5,7 +5,6 @@ import com.openisle.dto.ConversationDto;
|
|||||||
import com.openisle.dto.CreateConversationRequest;
|
import com.openisle.dto.CreateConversationRequest;
|
||||||
import com.openisle.dto.CreateConversationResponse;
|
import com.openisle.dto.CreateConversationResponse;
|
||||||
import com.openisle.dto.MessageDto;
|
import com.openisle.dto.MessageDto;
|
||||||
import com.openisle.dto.UserSummaryDto;
|
|
||||||
import com.openisle.model.Message;
|
import com.openisle.model.Message;
|
||||||
import com.openisle.model.MessageConversation;
|
import com.openisle.model.MessageConversation;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
@@ -55,16 +54,16 @@ public class MessageController {
|
|||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<MessageDto> sendMessage(@RequestBody MessageRequest req, Authentication auth) {
|
public ResponseEntity<MessageDto> sendMessage(@RequestBody MessageRequest req, Authentication auth) {
|
||||||
Message message = messageService.sendMessage(getCurrentUserId(auth), req.getRecipientId(), req.getContent());
|
Message message = messageService.sendMessage(getCurrentUserId(auth), req.getRecipientId(), req.getContent(), req.getReplyToId());
|
||||||
return ResponseEntity.ok(toDto(message));
|
return ResponseEntity.ok(messageService.toDto(message));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/conversations/{conversationId}/messages")
|
@PostMapping("/conversations/{conversationId}/messages")
|
||||||
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
public ResponseEntity<MessageDto> sendMessageToConversation(@PathVariable Long conversationId,
|
||||||
@RequestBody ChannelMessageRequest req,
|
@RequestBody ChannelMessageRequest req,
|
||||||
Authentication auth) {
|
Authentication auth) {
|
||||||
Message message = messageService.sendMessageToConversation(getCurrentUserId(auth), conversationId, req.getContent());
|
Message message = messageService.sendMessageToConversation(getCurrentUserId(auth), conversationId, req.getContent(), req.getReplyToId());
|
||||||
return ResponseEntity.ok(toDto(message));
|
return ResponseEntity.ok(messageService.toDto(message));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/conversations/{conversationId}/read")
|
@PostMapping("/conversations/{conversationId}/read")
|
||||||
@@ -79,23 +78,6 @@ public class MessageController {
|
|||||||
return ResponseEntity.ok(new CreateConversationResponse(conversation.getId()));
|
return ResponseEntity.ok(new CreateConversationResponse(conversation.getId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private MessageDto toDto(Message message) {
|
|
||||||
MessageDto dto = new MessageDto();
|
|
||||||
dto.setId(message.getId());
|
|
||||||
dto.setContent(message.getContent());
|
|
||||||
dto.setCreatedAt(message.getCreatedAt());
|
|
||||||
|
|
||||||
dto.setConversationId(message.getConversation().getId());
|
|
||||||
|
|
||||||
UserSummaryDto senderDto = new UserSummaryDto();
|
|
||||||
senderDto.setId(message.getSender().getId());
|
|
||||||
senderDto.setUsername(message.getSender().getUsername());
|
|
||||||
senderDto.setAvatar(message.getSender().getAvatar());
|
|
||||||
dto.setSender(senderDto);
|
|
||||||
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/unread-count")
|
@GetMapping("/unread-count")
|
||||||
public ResponseEntity<Long> getUnreadCount(Authentication auth) {
|
public ResponseEntity<Long> getUnreadCount(Authentication auth) {
|
||||||
return ResponseEntity.ok(messageService.getUnreadMessageCount(getCurrentUserId(auth)));
|
return ResponseEntity.ok(messageService.getUnreadMessageCount(getCurrentUserId(auth)));
|
||||||
@@ -105,6 +87,7 @@ public class MessageController {
|
|||||||
static class MessageRequest {
|
static class MessageRequest {
|
||||||
private Long recipientId;
|
private Long recipientId;
|
||||||
private String content;
|
private String content;
|
||||||
|
private Long replyToId;
|
||||||
|
|
||||||
public Long getRecipientId() {
|
public Long getRecipientId() {
|
||||||
return recipientId;
|
return recipientId;
|
||||||
@@ -121,10 +104,19 @@ public class MessageController {
|
|||||||
public void setContent(String content) {
|
public void setContent(String content) {
|
||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Long getReplyToId() {
|
||||||
|
return replyToId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setReplyToId(Long replyToId) {
|
||||||
|
this.replyToId = replyToId;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static class ChannelMessageRequest {
|
static class ChannelMessageRequest {
|
||||||
private String content;
|
private String content;
|
||||||
|
private Long replyToId;
|
||||||
|
|
||||||
public String getContent() {
|
public String getContent() {
|
||||||
return content;
|
return content;
|
||||||
@@ -133,5 +125,13 @@ public class MessageController {
|
|||||||
public void setContent(String content) {
|
public void setContent(String content) {
|
||||||
this.content = content;
|
this.content = content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Long getReplyToId() {
|
||||||
|
return replyToId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setReplyToId(Long replyToId) {
|
||||||
|
this.replyToId = replyToId;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,4 +57,17 @@ public class ReactionController {
|
|||||||
pointService.awardForReactionOfComment(auth.getName(), commentId);
|
pointService.awardForReactionOfComment(auth.getName(), commentId);
|
||||||
return ResponseEntity.ok(dto);
|
return ResponseEntity.ok(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/messages/{messageId}/reactions")
|
||||||
|
public ResponseEntity<ReactionDto> reactToMessage(@PathVariable Long messageId,
|
||||||
|
@RequestBody ReactionRequest req,
|
||||||
|
Authentication auth) {
|
||||||
|
Reaction reaction = reactionService.reactToMessage(auth.getName(), messageId, req.getType());
|
||||||
|
if (reaction == null) {
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
ReactionDto dto = reactionMapper.toDto(reaction);
|
||||||
|
dto.setReward(levelService.awardForReaction(auth.getName()));
|
||||||
|
return ResponseEntity.ok(dto);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,6 +105,17 @@ public class UserController {
|
|||||||
.collect(java.util.stream.Collectors.toList());
|
.collect(java.util.stream.Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{identifier}/subscribed-posts")
|
||||||
|
public java.util.List<PostMetaDto> subscribedPosts(@PathVariable("identifier") String identifier,
|
||||||
|
@RequestParam(value = "limit", required = false) Integer limit) {
|
||||||
|
int l = limit != null ? limit : defaultPostsLimit;
|
||||||
|
User user = userService.findByIdentifier(identifier).orElseThrow();
|
||||||
|
return subscriptionService.getSubscribedPosts(user.getUsername()).stream()
|
||||||
|
.limit(l)
|
||||||
|
.map(userMapper::toMetaDto)
|
||||||
|
.collect(java.util.stream.Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/{identifier}/replies")
|
@GetMapping("/{identifier}/replies")
|
||||||
public java.util.List<CommentInfoDto> userReplies(@PathVariable("identifier") String identifier,
|
public java.util.List<CommentInfoDto> userReplies(@PathVariable("identifier") String identifier,
|
||||||
@RequestParam(value = "limit", required = false) Integer limit) {
|
@RequestParam(value = "limit", required = false) Integer limit) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.openisle.dto;
|
|||||||
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class MessageDto {
|
public class MessageDto {
|
||||||
@@ -10,4 +11,6 @@ public class MessageDto {
|
|||||||
private UserSummaryDto sender;
|
private UserSummaryDto sender;
|
||||||
private Long conversationId;
|
private Long conversationId;
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
private MessageDto replyTo;
|
||||||
|
private List<ReactionDto> reactions;
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ import com.openisle.model.ReactionType;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DTO representing a reaction on a post or comment.
|
* DTO representing a reaction on a post, comment or message.
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class ReactionDto {
|
public class ReactionDto {
|
||||||
@@ -13,6 +13,7 @@ public class ReactionDto {
|
|||||||
private String user;
|
private String user;
|
||||||
private Long postId;
|
private Long postId;
|
||||||
private Long commentId;
|
private Long commentId;
|
||||||
|
private Long messageId;
|
||||||
private int reward;
|
private int reward;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ public class ReactionMapper {
|
|||||||
if (reaction.getComment() != null) {
|
if (reaction.getComment() != null) {
|
||||||
dto.setCommentId(reaction.getComment().getId());
|
dto.setCommentId(reaction.getComment().getId());
|
||||||
}
|
}
|
||||||
|
if (reaction.getMessage() != null) {
|
||||||
|
dto.setMessageId(reaction.getMessage().getId());
|
||||||
|
}
|
||||||
dto.setReward(0);
|
dto.setReward(0);
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ public class Message {
|
|||||||
@Column(nullable = false, columnDefinition = "TEXT")
|
@Column(nullable = false, columnDefinition = "TEXT")
|
||||||
private String content;
|
private String content;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "reply_to_id")
|
||||||
|
private Message replyTo;
|
||||||
|
|
||||||
@CreationTimestamp
|
@CreationTimestamp
|
||||||
@Column(nullable = false, updatable = false)
|
@Column(nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import lombok.Setter;
|
|||||||
import org.hibernate.annotations.CreationTimestamp;
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reaction entity representing a user's reaction to a post or comment.
|
* Reaction entity representing a user's reaction to a post, comment or message.
|
||||||
*/
|
*/
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
@@ -16,7 +16,8 @@ import org.hibernate.annotations.CreationTimestamp;
|
|||||||
@Table(name = "reactions",
|
@Table(name = "reactions",
|
||||||
uniqueConstraints = {
|
uniqueConstraints = {
|
||||||
@UniqueConstraint(columnNames = {"user_id", "post_id", "type"}),
|
@UniqueConstraint(columnNames = {"user_id", "post_id", "type"}),
|
||||||
@UniqueConstraint(columnNames = {"user_id", "comment_id", "type"})
|
@UniqueConstraint(columnNames = {"user_id", "comment_id", "type"}),
|
||||||
|
@UniqueConstraint(columnNames = {"user_id", "message_id", "type"})
|
||||||
})
|
})
|
||||||
public class Reaction {
|
public class Reaction {
|
||||||
@Id
|
@Id
|
||||||
@@ -39,6 +40,10 @@ public class Reaction {
|
|||||||
@JoinColumn(name = "comment_id")
|
@JoinColumn(name = "comment_id")
|
||||||
private Comment comment;
|
private Comment comment;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "message_id")
|
||||||
|
private Message message;
|
||||||
|
|
||||||
@CreationTimestamp
|
@CreationTimestamp
|
||||||
@Column(nullable = false, updatable = false,
|
@Column(nullable = false, updatable = false,
|
||||||
columnDefinition = "DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)")
|
columnDefinition = "DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.openisle.repository;
|
package com.openisle.repository;
|
||||||
|
|
||||||
import com.openisle.model.Comment;
|
import com.openisle.model.Comment;
|
||||||
|
import com.openisle.model.Message;
|
||||||
import com.openisle.model.Post;
|
import com.openisle.model.Post;
|
||||||
import com.openisle.model.Reaction;
|
import com.openisle.model.Reaction;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
@@ -15,8 +16,10 @@ import java.util.Optional;
|
|||||||
public interface ReactionRepository extends JpaRepository<Reaction, Long> {
|
public interface ReactionRepository extends JpaRepository<Reaction, Long> {
|
||||||
Optional<Reaction> findByUserAndPostAndType(User user, Post post, com.openisle.model.ReactionType type);
|
Optional<Reaction> findByUserAndPostAndType(User user, Post post, com.openisle.model.ReactionType type);
|
||||||
Optional<Reaction> findByUserAndCommentAndType(User user, Comment comment, com.openisle.model.ReactionType type);
|
Optional<Reaction> findByUserAndCommentAndType(User user, Comment comment, com.openisle.model.ReactionType type);
|
||||||
|
Optional<Reaction> findByUserAndMessageAndType(User user, Message message, com.openisle.model.ReactionType type);
|
||||||
List<Reaction> findByPost(Post post);
|
List<Reaction> findByPost(Post post);
|
||||||
List<Reaction> findByComment(Comment comment);
|
List<Reaction> findByComment(Comment comment);
|
||||||
|
List<Reaction> findByMessage(Message message);
|
||||||
|
|
||||||
@Query("SELECT r.post.id FROM Reaction r WHERE r.post IS NOT NULL AND r.post.author.username = :username AND r.type = com.openisle.model.ReactionType.LIKE GROUP BY r.post.id ORDER BY COUNT(r.id) DESC")
|
@Query("SELECT r.post.id FROM Reaction r WHERE r.post IS NOT NULL AND r.post.author.username = :username AND r.type = com.openisle.model.ReactionType.LIKE GROUP BY r.post.id ORDER BY COUNT(r.id) DESC")
|
||||||
List<Long> findTopPostIds(@Param("username") String username, Pageable pageable);
|
List<Long> findTopPostIds(@Param("username") String username, Pageable pageable);
|
||||||
|
|||||||
@@ -4,14 +4,18 @@ import com.openisle.model.Message;
|
|||||||
import com.openisle.model.MessageConversation;
|
import com.openisle.model.MessageConversation;
|
||||||
import com.openisle.model.MessageParticipant;
|
import com.openisle.model.MessageParticipant;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
|
import com.openisle.model.Reaction;
|
||||||
import com.openisle.repository.MessageConversationRepository;
|
import com.openisle.repository.MessageConversationRepository;
|
||||||
import com.openisle.repository.MessageParticipantRepository;
|
import com.openisle.repository.MessageParticipantRepository;
|
||||||
import com.openisle.repository.MessageRepository;
|
import com.openisle.repository.MessageRepository;
|
||||||
import com.openisle.repository.UserRepository;
|
import com.openisle.repository.UserRepository;
|
||||||
|
import com.openisle.repository.ReactionRepository;
|
||||||
import com.openisle.dto.ConversationDetailDto;
|
import com.openisle.dto.ConversationDetailDto;
|
||||||
import com.openisle.dto.ConversationDto;
|
import com.openisle.dto.ConversationDto;
|
||||||
import com.openisle.dto.MessageDto;
|
import com.openisle.dto.MessageDto;
|
||||||
|
import com.openisle.dto.ReactionDto;
|
||||||
import com.openisle.dto.UserSummaryDto;
|
import com.openisle.dto.UserSummaryDto;
|
||||||
|
import com.openisle.mapper.ReactionMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
@@ -34,9 +38,11 @@ public class MessageService {
|
|||||||
private final MessageParticipantRepository participantRepository;
|
private final MessageParticipantRepository participantRepository;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final SimpMessagingTemplate messagingTemplate;
|
private final SimpMessagingTemplate messagingTemplate;
|
||||||
|
private final ReactionRepository reactionRepository;
|
||||||
|
private final ReactionMapper reactionMapper;
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Message sendMessage(Long senderId, Long recipientId, String content) {
|
public Message sendMessage(Long senderId, Long recipientId, String content, Long replyToId) {
|
||||||
log.info("Attempting to send message from user {} to user {}", senderId, recipientId);
|
log.info("Attempting to send message from user {} to user {}", senderId, recipientId);
|
||||||
User sender = userRepository.findById(senderId)
|
User sender = userRepository.findById(senderId)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Sender not found"));
|
.orElseThrow(() -> new IllegalArgumentException("Sender not found"));
|
||||||
@@ -51,6 +57,11 @@ public class MessageService {
|
|||||||
message.setConversation(conversation);
|
message.setConversation(conversation);
|
||||||
message.setSender(sender);
|
message.setSender(sender);
|
||||||
message.setContent(content);
|
message.setContent(content);
|
||||||
|
if (replyToId != null) {
|
||||||
|
Message replyTo = messageRepository.findById(replyToId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Message not found"));
|
||||||
|
message.setReplyTo(replyTo);
|
||||||
|
}
|
||||||
message = messageRepository.save(message);
|
message = messageRepository.save(message);
|
||||||
log.info("Message saved with ID: {}", message.getId());
|
log.info("Message saved with ID: {}", message.getId());
|
||||||
|
|
||||||
@@ -83,7 +94,7 @@ public class MessageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Message sendMessageToConversation(Long senderId, Long conversationId, String content) {
|
public Message sendMessageToConversation(Long senderId, Long conversationId, String content, Long replyToId) {
|
||||||
User sender = userRepository.findById(senderId)
|
User sender = userRepository.findById(senderId)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Sender not found"));
|
.orElseThrow(() -> new IllegalArgumentException("Sender not found"));
|
||||||
MessageConversation conversation = conversationRepository.findById(conversationId)
|
MessageConversation conversation = conversationRepository.findById(conversationId)
|
||||||
@@ -102,6 +113,11 @@ public class MessageService {
|
|||||||
message.setConversation(conversation);
|
message.setConversation(conversation);
|
||||||
message.setSender(sender);
|
message.setSender(sender);
|
||||||
message.setContent(content);
|
message.setContent(content);
|
||||||
|
if (replyToId != null) {
|
||||||
|
Message replyTo = messageRepository.findById(replyToId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Message not found"));
|
||||||
|
message.setReplyTo(replyTo);
|
||||||
|
}
|
||||||
message = messageRepository.save(message);
|
message = messageRepository.save(message);
|
||||||
|
|
||||||
conversation.setLastMessage(message);
|
conversation.setLastMessage(message);
|
||||||
@@ -128,7 +144,7 @@ public class MessageService {
|
|||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
private MessageDto toDto(Message message) {
|
public MessageDto toDto(Message message) {
|
||||||
MessageDto dto = new MessageDto();
|
MessageDto dto = new MessageDto();
|
||||||
dto.setId(message.getId());
|
dto.setId(message.getId());
|
||||||
dto.setContent(message.getContent());
|
dto.setContent(message.getContent());
|
||||||
@@ -141,6 +157,25 @@ public class MessageService {
|
|||||||
userSummaryDto.setAvatar(message.getSender().getAvatar());
|
userSummaryDto.setAvatar(message.getSender().getAvatar());
|
||||||
dto.setSender(userSummaryDto);
|
dto.setSender(userSummaryDto);
|
||||||
|
|
||||||
|
if (message.getReplyTo() != null) {
|
||||||
|
Message reply = message.getReplyTo();
|
||||||
|
MessageDto replyDto = new MessageDto();
|
||||||
|
replyDto.setId(reply.getId());
|
||||||
|
replyDto.setContent(reply.getContent());
|
||||||
|
UserSummaryDto replySender = new UserSummaryDto();
|
||||||
|
replySender.setId(reply.getSender().getId());
|
||||||
|
replySender.setUsername(reply.getSender().getUsername());
|
||||||
|
replySender.setAvatar(reply.getSender().getAvatar());
|
||||||
|
replyDto.setSender(replySender);
|
||||||
|
dto.setReplyTo(replyDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
java.util.List<Reaction> reactions = reactionRepository.findByMessage(message);
|
||||||
|
java.util.List<ReactionDto> reactionDtos = reactions.stream()
|
||||||
|
.map(reactionMapper::toDto)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
dto.setReactions(reactionDtos);
|
||||||
|
|
||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,12 @@ import com.openisle.model.Reaction;
|
|||||||
import com.openisle.model.ReactionType;
|
import com.openisle.model.ReactionType;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
import com.openisle.model.NotificationType;
|
import com.openisle.model.NotificationType;
|
||||||
|
import com.openisle.model.Message;
|
||||||
import com.openisle.repository.CommentRepository;
|
import com.openisle.repository.CommentRepository;
|
||||||
import com.openisle.repository.PostRepository;
|
import com.openisle.repository.PostRepository;
|
||||||
import com.openisle.repository.ReactionRepository;
|
import com.openisle.repository.ReactionRepository;
|
||||||
import com.openisle.repository.UserRepository;
|
import com.openisle.repository.UserRepository;
|
||||||
|
import com.openisle.repository.MessageRepository;
|
||||||
import com.openisle.service.NotificationService;
|
import com.openisle.service.NotificationService;
|
||||||
import com.openisle.service.EmailSender;
|
import com.openisle.service.EmailSender;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -24,6 +26,7 @@ public class ReactionService {
|
|||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PostRepository postRepository;
|
private final PostRepository postRepository;
|
||||||
private final CommentRepository commentRepository;
|
private final CommentRepository commentRepository;
|
||||||
|
private final MessageRepository messageRepository;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
private final EmailSender emailSender;
|
private final EmailSender emailSender;
|
||||||
|
|
||||||
@@ -77,6 +80,26 @@ public class ReactionService {
|
|||||||
return reaction;
|
return reaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Reaction reactToMessage(String username, Long messageId, ReactionType type) {
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
|
Message message = messageRepository.findById(messageId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Message not found"));
|
||||||
|
java.util.Optional<Reaction> existing =
|
||||||
|
reactionRepository.findByUserAndMessageAndType(user, message, type);
|
||||||
|
if (existing.isPresent()) {
|
||||||
|
reactionRepository.delete(existing.get());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Reaction reaction = new Reaction();
|
||||||
|
reaction.setUser(user);
|
||||||
|
reaction.setMessage(message);
|
||||||
|
reaction.setType(type);
|
||||||
|
reaction = reactionRepository.save(reaction);
|
||||||
|
return reaction;
|
||||||
|
}
|
||||||
|
|
||||||
public java.util.List<Reaction> getReactionsForPost(Long postId) {
|
public java.util.List<Reaction> getReactionsForPost(Long postId) {
|
||||||
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"));
|
||||||
|
|||||||
@@ -107,6 +107,11 @@ public class SubscriptionService {
|
|||||||
return commentSubRepo.findByComment(c).stream().map(CommentSubscription::getUser).toList();
|
return commentSubRepo.findByComment(c).stream().map(CommentSubscription::getUser).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Post> getSubscribedPosts(String username) {
|
||||||
|
User user = userRepo.findByUsername(username).orElseThrow();
|
||||||
|
return postSubRepo.findByUser(user).stream().map(PostSubscription::getPost).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public long countSubscribers(String username) {
|
public long countSubscribers(String username) {
|
||||||
User user = userRepo.findByUsername(username).orElseThrow();
|
User user = userRepo.findByUsername(username).orElseThrow();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.openisle.model.Post;
|
|||||||
import com.openisle.model.Reaction;
|
import com.openisle.model.Reaction;
|
||||||
import com.openisle.model.ReactionType;
|
import com.openisle.model.ReactionType;
|
||||||
import com.openisle.model.User;
|
import com.openisle.model.User;
|
||||||
|
import com.openisle.model.Message;
|
||||||
import com.openisle.service.ReactionService;
|
import com.openisle.service.ReactionService;
|
||||||
import com.openisle.service.LevelService;
|
import com.openisle.service.LevelService;
|
||||||
import com.openisle.mapper.ReactionMapper;
|
import com.openisle.mapper.ReactionMapper;
|
||||||
@@ -78,6 +79,27 @@ class ReactionControllerTest {
|
|||||||
.andExpect(jsonPath("$.commentId").value(2));
|
.andExpect(jsonPath("$.commentId").value(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reactToMessage() throws Exception {
|
||||||
|
User user = new User();
|
||||||
|
user.setUsername("u3");
|
||||||
|
Message message = new Message();
|
||||||
|
message.setId(3L);
|
||||||
|
Reaction reaction = new Reaction();
|
||||||
|
reaction.setId(3L);
|
||||||
|
reaction.setUser(user);
|
||||||
|
reaction.setMessage(message);
|
||||||
|
reaction.setType(ReactionType.LIKE);
|
||||||
|
Mockito.when(reactionService.reactToMessage(eq("u3"), eq(3L), eq(ReactionType.LIKE))).thenReturn(reaction);
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/messages/3/reactions")
|
||||||
|
.contentType("application/json")
|
||||||
|
.content("{\"type\":\"LIKE\"}")
|
||||||
|
.principal(new UsernamePasswordAuthenticationToken("u3", "p")))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.messageId").value(3));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void listReactionTypes() throws Exception {
|
void listReactionTypes() throws Exception {
|
||||||
mockMvc.perform(get("/api/reaction-types"))
|
mockMvc.perform(get("/api/reaction-types"))
|
||||||
|
|||||||
@@ -136,6 +136,30 @@ class UserControllerTest {
|
|||||||
.andExpect(jsonPath("$[0].title").value("hello"));
|
.andExpect(jsonPath("$[0].title").value("hello"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listSubscribedPosts() throws Exception {
|
||||||
|
User user = new User();
|
||||||
|
user.setUsername("bob");
|
||||||
|
com.openisle.model.Category cat = new com.openisle.model.Category();
|
||||||
|
cat.setName("tech");
|
||||||
|
com.openisle.model.Post post = new com.openisle.model.Post();
|
||||||
|
post.setId(6L);
|
||||||
|
post.setTitle("fav");
|
||||||
|
post.setCreatedAt(java.time.LocalDateTime.now());
|
||||||
|
post.setCategory(cat);
|
||||||
|
post.setAuthor(user);
|
||||||
|
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
|
||||||
|
Mockito.when(subscriptionService.getSubscribedPosts("bob")).thenReturn(java.util.List.of(post));
|
||||||
|
PostMetaDto meta = new PostMetaDto();
|
||||||
|
meta.setId(6L);
|
||||||
|
meta.setTitle("fav");
|
||||||
|
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/users/bob/subscribed-posts"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].title").value("fav"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void listUserReplies() throws Exception {
|
void listUserReplies() throws Exception {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ class ReactionServiceTest {
|
|||||||
UserRepository userRepo = mock(UserRepository.class);
|
UserRepository userRepo = mock(UserRepository.class);
|
||||||
PostRepository postRepo = mock(PostRepository.class);
|
PostRepository postRepo = mock(PostRepository.class);
|
||||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||||
|
MessageRepository messageRepo = mock(MessageRepository.class);
|
||||||
NotificationService notif = mock(NotificationService.class);
|
NotificationService notif = mock(NotificationService.class);
|
||||||
EmailSender email = mock(EmailSender.class);
|
EmailSender email = mock(EmailSender.class);
|
||||||
ReactionService service = new ReactionService(reactionRepo, userRepo, postRepo, commentRepo, notif, email);
|
ReactionService service = new ReactionService(reactionRepo, userRepo, postRepo, commentRepo, messageRepo, notif, email);
|
||||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||||
|
|
||||||
User user = new User();
|
User user = new User();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div id="app">
|
<div id="app">
|
||||||
<div class="header-container">
|
<div v-if="!isFloatMode" class="header-container">
|
||||||
<HeaderComponent
|
<HeaderComponent
|
||||||
ref="header"
|
ref="header"
|
||||||
@toggle-menu="menuVisible = !menuVisible"
|
@toggle-menu="menuVisible = !menuVisible"
|
||||||
@@ -9,20 +9,28 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="main-container">
|
<div class="main-container">
|
||||||
<div class="menu-container" v-click-outside="handleMenuOutside">
|
<div v-if="!isFloatMode" class="menu-container" v-click-outside="handleMenuOutside">
|
||||||
<MenuComponent :visible="!hideMenu && menuVisible" @item-click="menuVisible = false" />
|
<MenuComponent :visible="!hideMenu && menuVisible" @item-click="menuVisible = false" />
|
||||||
</div>
|
</div>
|
||||||
<div class="content" :class="{ 'menu-open': menuVisible && !hideMenu }">
|
<div
|
||||||
|
class="content"
|
||||||
|
:class="{ 'menu-open': menuVisible && !hideMenu && !isFloatMode }"
|
||||||
|
:style="isFloatMode ? { paddingTop: '0px', minHeight: '100vh' } : {}"
|
||||||
|
>
|
||||||
<NuxtPage keepalive />
|
<NuxtPage keepalive />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="showNewPostIcon && isMobile" class="app-new-post-icon" @click="goToNewPost">
|
<div
|
||||||
|
v-if="showNewPostIcon && isMobile && !isFloatMode"
|
||||||
|
class="app-new-post-icon"
|
||||||
|
@click="goToNewPost"
|
||||||
|
>
|
||||||
<i class="fas fa-edit"></i>
|
<i class="fas fa-edit"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<GlobalPopups />
|
<GlobalPopups />
|
||||||
<ConfirmDialog />
|
<ConfirmDialog />
|
||||||
<ChatFloating />
|
<MessageFloatWindow v-if="!isFloatMode" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -31,7 +39,7 @@ 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 ConfirmDialog from '~/components/ConfirmDialog.vue'
|
||||||
import ChatFloating from '~/components/ChatFloating.vue'
|
import MessageFloatWindow from '~/components/MessageFloatWindow.vue'
|
||||||
import { useIsMobile } from '~/utils/screen'
|
import { useIsMobile } from '~/utils/screen'
|
||||||
|
|
||||||
const isMobile = useIsMobile()
|
const isMobile = useIsMobile()
|
||||||
@@ -54,6 +62,7 @@ const hideMenu = computed(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const header = useTemplateRef('header')
|
const header = useTemplateRef('header')
|
||||||
|
const isFloatMode = computed(() => useRoute().query.float !== undefined)
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div v-if="chatFloating" class="chat-floating">
|
|
||||||
<iframe :src="iframeSrc" class="chat-frame"></iframe>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup>
|
|
||||||
import { computed } from 'vue'
|
|
||||||
|
|
||||||
const chatFloating = useState('chatFloating', () => false)
|
|
||||||
const chatPath = useState('chatPath', () => '/message-box')
|
|
||||||
|
|
||||||
const iframeSrc = computed(() =>
|
|
||||||
chatPath.value.includes('?') ? `${chatPath.value}&float=1` : `${chatPath.value}?float=1`,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (process.client) {
|
|
||||||
window.addEventListener('message', (event) => {
|
|
||||||
if (event.data?.type === 'maximize-chat') {
|
|
||||||
chatFloating.value = false
|
|
||||||
navigateTo(event.data.path || chatPath.value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.chat-floating {
|
|
||||||
position: fixed;
|
|
||||||
bottom: 20px;
|
|
||||||
right: 20px;
|
|
||||||
width: 400px;
|
|
||||||
height: 70vh;
|
|
||||||
max-height: 600px;
|
|
||||||
background: var(--background-color);
|
|
||||||
border: 1px solid var(--normal-border-color);
|
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
|
|
||||||
z-index: 2000;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-frame {
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 500px) {
|
|
||||||
.chat-floating {
|
|
||||||
right: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 60vh;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
101
frontend_nuxt/components/MessageFloatWindow.vue
Normal file
101
frontend_nuxt/components/MessageFloatWindow.vue
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
<template>
|
||||||
|
<div v-if="floatRoute" class="message-float-window" :style="{ height: floatHeight }">
|
||||||
|
<iframe :src="iframeSrc" frameborder="0"></iframe>
|
||||||
|
|
||||||
|
<div class="float-actions">
|
||||||
|
<i
|
||||||
|
class="fas fa-chevron-down"
|
||||||
|
v-if="floatHeight !== MINI_HEIGHT"
|
||||||
|
title="收起至 100px"
|
||||||
|
@click="collapseToMini"
|
||||||
|
></i>
|
||||||
|
<!-- 回弹:60vh -->
|
||||||
|
<i
|
||||||
|
class="fas fa-chevron-up"
|
||||||
|
v-if="floatHeight !== DEFAULT_HEIGHT"
|
||||||
|
title="回弹至 60vh"
|
||||||
|
@click="reboundToDefault"
|
||||||
|
></i>
|
||||||
|
<!-- 全屏打开(原有逻辑) -->
|
||||||
|
<i class="fas fa-expand" title="在页面中打开" @click="expand"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
const floatRoute = useState('messageFloatRoute')
|
||||||
|
|
||||||
|
const DEFAULT_HEIGHT = '60vh'
|
||||||
|
const MINI_HEIGHT = '45px'
|
||||||
|
const floatHeight = ref(DEFAULT_HEIGHT)
|
||||||
|
|
||||||
|
const iframeSrc = computed(() => {
|
||||||
|
if (!floatRoute.value) return ''
|
||||||
|
return floatRoute.value + (floatRoute.value.includes('?') ? '&' : '?') + 'float=1'
|
||||||
|
})
|
||||||
|
|
||||||
|
function collapseToMini() {
|
||||||
|
floatHeight.value = MINI_HEIGHT
|
||||||
|
}
|
||||||
|
|
||||||
|
function reboundToDefault() {
|
||||||
|
floatHeight.value = DEFAULT_HEIGHT
|
||||||
|
}
|
||||||
|
|
||||||
|
function expand() {
|
||||||
|
if (!floatRoute.value) return
|
||||||
|
const target = floatRoute.value
|
||||||
|
floatRoute.value = null
|
||||||
|
navigateTo(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当浮窗重新出现时,恢复默认高度
|
||||||
|
watch(
|
||||||
|
() => floatRoute.value,
|
||||||
|
(v) => {
|
||||||
|
if (v) floatHeight.value = DEFAULT_HEIGHT
|
||||||
|
},
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.message-float-window {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 0;
|
||||||
|
right: 0;
|
||||||
|
width: 400px;
|
||||||
|
/* 高度由内联样式绑定控制:60vh / 100px */
|
||||||
|
max-height: 90vh;
|
||||||
|
background-color: var(--background-color);
|
||||||
|
border: 1px solid var(--normal-border-color);
|
||||||
|
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||||
|
z-index: 2000;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
transition: height 0.25s ease; /* 平滑过渡 */
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-float-window iframe {
|
||||||
|
width: 100%;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-actions {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
right: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-actions i {
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-actions i:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="reactions-viewer-item placeholder" @click="openPanel">
|
<div class="reactions-viewer-item placeholder" @click="openPanel">
|
||||||
<i class="far fa-smile"></i>
|
<i class="far fa-smile reactions-viewer-item-placeholder-icon"></i>
|
||||||
<!-- <span class="reactions-viewer-item-placeholder-text">点击以表态</span> -->
|
<!-- <span class="reactions-viewer-item-placeholder-text">点击以表态</span> -->
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -37,7 +37,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="make-reaction-container">
|
<div class="make-reaction-container">
|
||||||
<div class="make-reaction-item like-reaction" @click="toggleReaction('LIKE')">
|
<div
|
||||||
|
v-if="props.contentType !== 'message'"
|
||||||
|
class="make-reaction-item like-reaction"
|
||||||
|
@click="toggleReaction('LIKE')"
|
||||||
|
>
|
||||||
<i v-if="!userReacted('LIKE')" class="far fa-heart"></i>
|
<i v-if="!userReacted('LIKE')" class="far fa-heart"></i>
|
||||||
<i v-else class="fas fa-heart"></i>
|
<i v-else class="fas fa-heart"></i>
|
||||||
<span class="reactions-count" v-if="likeCount">{{ likeCount }}</span>
|
<span class="reactions-count" v-if="likeCount">{{ likeCount }}</span>
|
||||||
@@ -138,7 +142,9 @@ const toggleReaction = async (type) => {
|
|||||||
const url =
|
const url =
|
||||||
props.contentType === 'post'
|
props.contentType === 'post'
|
||||||
? `${API_BASE_URL}/api/posts/${props.contentId}/reactions`
|
? `${API_BASE_URL}/api/posts/${props.contentId}/reactions`
|
||||||
: `${API_BASE_URL}/api/comments/${props.contentId}/reactions`
|
: props.contentType === 'comment'
|
||||||
|
? `${API_BASE_URL}/api/comments/${props.contentId}/reactions`
|
||||||
|
: `${API_BASE_URL}/api/messages/${props.contentId}/reactions`
|
||||||
|
|
||||||
// optimistic update
|
// optimistic update
|
||||||
const existingIdx = reactions.value.findIndex(
|
const existingIdx = reactions.value.findIndex(
|
||||||
@@ -236,6 +242,10 @@ onMounted(async () => {
|
|||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.reactions-viewer-item-placeholder-icon {
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
.reactions-viewer-item-placeholder-text {
|
.reactions-viewer-item-placeholder-text {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
padding-left: 5px;
|
padding-left: 5px;
|
||||||
|
|||||||
@@ -125,6 +125,7 @@
|
|||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, onBeforeUnmount, nextTick, ref, watch } from 'vue'
|
import { computed, onMounted, onBeforeUnmount, nextTick, ref, watch } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
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'
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="chat-container">
|
<div class="chat-container" :class="{ float: isFloatMode }">
|
||||||
<div v-if="!loading" class="chat-header">
|
<div v-if="!loading" class="chat-header">
|
||||||
<NuxtLink to="/message-box" class="back-button">
|
<div class="header-main">
|
||||||
<i class="fas fa-arrow-left"></i>
|
<div class="back-button" @click="goBack">
|
||||||
</NuxtLink>
|
<i class="fas fa-arrow-left"></i>
|
||||||
<h2 class="participant-name">
|
</div>
|
||||||
{{ isChannel ? conversationName : otherParticipant?.username }}
|
<h2 class="participant-name">
|
||||||
</h2>
|
{{ isChannel ? conversationName : otherParticipant?.username }}
|
||||||
<div class="chat-controls">
|
</h2>
|
||||||
<i v-if="!isFloat" class="fas fa-window-minimize control-icon" @click="minimizeChat"></i>
|
</div>
|
||||||
<i v-else class="fas fa-expand control-icon" @click="maximizeChat"></i>
|
<div v-if="!isFloatMode" class="float-control">
|
||||||
|
<i class="fas fa-compress" @click="minimize" title="最小化"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -34,9 +35,21 @@
|
|||||||
{{ TimeManager.format(item.createdAt) }}
|
{{ TimeManager.format(item.createdAt) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="item.replyTo" class="reply-preview">
|
||||||
|
<div class="reply-author">{{ item.replyTo.sender.username }}</div>
|
||||||
|
<div class="reply-content" v-html="renderMarkdown(item.replyTo.content)"></div>
|
||||||
|
</div>
|
||||||
<div class="message-content">
|
<div class="message-content">
|
||||||
<div class="info-content-text" v-html="renderMarkdown(item.content)"></div>
|
<div class="info-content-text" v-html="renderMarkdown(item.content)"></div>
|
||||||
</div>
|
</div>
|
||||||
|
<ReactionsGroup
|
||||||
|
:model-value="item.reactions"
|
||||||
|
content-type="message"
|
||||||
|
:content-id="item.id"
|
||||||
|
@update:modelValue="(v) => (item.reactions = v)"
|
||||||
|
>
|
||||||
|
<i class="fas fa-reply reply-btn" @click="setReply(item)"> 写个回复...</i>
|
||||||
|
</ReactionsGroup>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
<div class="empty-container">
|
<div class="empty-container">
|
||||||
@@ -50,6 +63,11 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="message-input-area">
|
<div class="message-input-area">
|
||||||
|
<div v-if="replyTo" class="active-reply">
|
||||||
|
正在回复 {{ replyTo.sender.username }}:
|
||||||
|
{{ stripMarkdownLength(replyTo.content, 50) }}
|
||||||
|
<i class="fas fa-times close-reply" @click="replyTo = null"></i>
|
||||||
|
</div>
|
||||||
<MessageEditor :loading="sending" @submit="sendMessage" />
|
<MessageEditor :loading="sending" @submit="sendMessage" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -69,8 +87,9 @@ import {
|
|||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { getToken, fetchCurrentUser } from '~/utils/auth'
|
import { getToken, fetchCurrentUser } from '~/utils/auth'
|
||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { renderMarkdown } from '~/utils/markdown'
|
import { renderMarkdown, stripMarkdownLength } from '~/utils/markdown'
|
||||||
import MessageEditor from '~/components/MessageEditor.vue'
|
import MessageEditor from '~/components/MessageEditor.vue'
|
||||||
|
import ReactionsGroup from '~/components/ReactionsGroup.vue'
|
||||||
import { useWebSocket } from '~/composables/useWebSocket'
|
import { useWebSocket } from '~/composables/useWebSocket'
|
||||||
import { useUnreadCount } from '~/composables/useUnreadCount'
|
import { useUnreadCount } from '~/composables/useUnreadCount'
|
||||||
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
|
import { useChannelsUnreadCount } from '~/composables/useChannelsUnreadCount'
|
||||||
@@ -86,10 +105,6 @@ const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
|
|||||||
const { fetchChannelUnread: refreshChannelUnread } = useChannelsUnreadCount()
|
const { fetchChannelUnread: refreshChannelUnread } = useChannelsUnreadCount()
|
||||||
let subscription = null
|
let subscription = null
|
||||||
|
|
||||||
const chatFloating = useState('chatFloating', () => false)
|
|
||||||
const chatPath = useState('chatPath', () => '/message-box')
|
|
||||||
const isFloat = computed(() => route.query.float === '1')
|
|
||||||
|
|
||||||
const messages = ref([])
|
const messages = ref([])
|
||||||
const participants = ref([])
|
const participants = ref([])
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
@@ -105,6 +120,9 @@ const loadingMore = ref(false)
|
|||||||
let scrollInterval = null
|
let scrollInterval = null
|
||||||
const conversationName = ref('')
|
const conversationName = ref('')
|
||||||
const isChannel = ref(false)
|
const isChannel = ref(false)
|
||||||
|
const isFloatMode = computed(() => route.query.float !== undefined)
|
||||||
|
const floatRoute = useState('messageFloatRoute')
|
||||||
|
const replyTo = ref(null)
|
||||||
|
|
||||||
const hasMoreMessages = computed(() => currentPage.value < totalPages.value - 1)
|
const hasMoreMessages = computed(() => currentPage.value < totalPages.value - 1)
|
||||||
|
|
||||||
@@ -123,22 +141,8 @@ function handleAvatarError(event) {
|
|||||||
event.target.src = '/default-avatar.svg'
|
event.target.src = '/default-avatar.svg'
|
||||||
}
|
}
|
||||||
|
|
||||||
function minimizeChat() {
|
function setReply(message) {
|
||||||
chatPath.value = route.fullPath
|
replyTo.value = message
|
||||||
chatFloating.value = true
|
|
||||||
navigateTo('/')
|
|
||||||
}
|
|
||||||
|
|
||||||
function maximizeChat() {
|
|
||||||
if (window.parent) {
|
|
||||||
window.parent.postMessage(
|
|
||||||
{
|
|
||||||
type: 'maximize-chat',
|
|
||||||
path: route.fullPath.replace('?float=1', '').replace('&float=1', ''),
|
|
||||||
},
|
|
||||||
'*',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// No changes needed here, as renderMarkdown is now imported.
|
// No changes needed here, as renderMarkdown is now imported.
|
||||||
@@ -182,7 +186,7 @@ async function fetchMessages(page = 0) {
|
|||||||
...item,
|
...item,
|
||||||
src: item.sender.avatar,
|
src: item.sender.avatar,
|
||||||
iconClick: () => {
|
iconClick: () => {
|
||||||
navigateTo(`/users/${item.sender.id}`, { replace: true })
|
openUser(item.sender.id)
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -234,7 +238,7 @@ async function sendMessage(content, clearInput) {
|
|||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ content }),
|
body: JSON.stringify({ content, replyToId: replyTo.value?.id }),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
@@ -252,6 +256,7 @@ async function sendMessage(content, clearInput) {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
recipientId: recipient.id,
|
recipientId: recipient.id,
|
||||||
content: content,
|
content: content,
|
||||||
|
replyToId: replyTo.value?.id,
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -262,10 +267,11 @@ async function sendMessage(content, clearInput) {
|
|||||||
...newMessage,
|
...newMessage,
|
||||||
src: newMessage.sender.avatar,
|
src: newMessage.sender.avatar,
|
||||||
iconClick: () => {
|
iconClick: () => {
|
||||||
navigateTo(`/users/${newMessage.sender.id}`, { replace: true })
|
openUser(newMessage.sender.id)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
clearInput()
|
clearInput()
|
||||||
|
replyTo.value = null
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
}, 100)
|
}, 100)
|
||||||
@@ -348,7 +354,7 @@ watch(isConnected, (newValue) => {
|
|||||||
...message,
|
...message,
|
||||||
src: message.sender.avatar,
|
src: message.sender.avatar,
|
||||||
iconClick: () => {
|
iconClick: () => {
|
||||||
navigateTo(`/users/${message.sender.id}`, { replace: true })
|
openUser(message.sender.id)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
// 实时收到消息时自动标记为已读
|
// 实时收到消息时自动标记为已读
|
||||||
@@ -402,6 +408,28 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
disconnect()
|
disconnect()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function minimize() {
|
||||||
|
floatRoute.value = route.fullPath
|
||||||
|
navigateTo('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
function openUser(id) {
|
||||||
|
if (isFloatMode.value) {
|
||||||
|
// 先不处理...
|
||||||
|
// navigateTo(`/users/${id}?float=1`)
|
||||||
|
} else {
|
||||||
|
navigateTo(`/users/${id}`, { replace: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function goBack() {
|
||||||
|
if (isFloatMode.value) {
|
||||||
|
navigateTo('/message-box?float=1')
|
||||||
|
} else {
|
||||||
|
navigateTo('/message-box')
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@@ -414,8 +442,13 @@ onUnmounted(() => {
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.chat-container.float {
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
.chat-header {
|
.chat-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 0;
|
top: 0;
|
||||||
z-index: 100;
|
z-index: 100;
|
||||||
@@ -426,6 +459,24 @@ onUnmounted(() => {
|
|||||||
backdrop-filter: var(--blur-10);
|
backdrop-filter: var(--blur-10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.header-main {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-control {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
text-align: right;
|
||||||
|
padding: 12px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-control i {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
.back-button {
|
.back-button {
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
color: var(--text-color-primary);
|
color: var(--text-color-primary);
|
||||||
@@ -437,7 +488,6 @@ onUnmounted(() => {
|
|||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
flex: 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.messages-list {
|
.messages-list {
|
||||||
@@ -541,25 +591,57 @@ onUnmounted(() => {
|
|||||||
color: var(--text-color-secondary);
|
color: var(--text-color-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
.messages-list {
|
|
||||||
padding: 10px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.message-input-area {
|
.message-input-area {
|
||||||
margin-left: 10px;
|
margin-left: 10px;
|
||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-controls {
|
.reply-preview {
|
||||||
margin-left: auto;
|
padding: 5px 10px;
|
||||||
cursor: pointer;
|
border-left: 5px solid var(--primary-color);
|
||||||
display: flex;
|
margin-bottom: 5px;
|
||||||
align-items: center;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.control-icon {
|
.reply-author {
|
||||||
font-size: 16px;
|
font-weight: bold;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reply-btn {
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 4px;
|
||||||
|
opacity: 0.6;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reply-btn:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.active-reply {
|
||||||
|
background-color: var(--bg-color-soft);
|
||||||
|
padding: 5px 10px;
|
||||||
|
border-left: 5px solid var(--primary-color);
|
||||||
|
margin-bottom: 5px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.close-reply {
|
||||||
|
margin-left: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-height: 200px) {
|
||||||
|
.messages-list,
|
||||||
|
.message-input-area {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.messages-list {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="messages-container">
|
<div class="messages-container">
|
||||||
<div class="chat-controls">
|
<div class="page-title">
|
||||||
<i v-if="!isFloat" class="fas fa-window-minimize control-icon" @click="minimizeChat"></i>
|
<i class="fas fa-comments"></i>
|
||||||
<i v-else class="fas fa-expand control-icon" @click="maximizeChat"></i>
|
<span class="page-title-text">选择聊天</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="!isFloatMode" class="float-control">
|
||||||
|
<i class="fas fa-compress" @click="minimize" title="最小化"></i>
|
||||||
</div>
|
</div>
|
||||||
<div class="tabs">
|
<div class="tabs">
|
||||||
<div :class="['tab', { active: activeTab === 'messages' }]" @click="activeTab = 'messages'">
|
<div :class="['tab', { active: activeTab === 'messages' }]" @click="switchToMessage">
|
||||||
站内信
|
站内信
|
||||||
</div>
|
</div>
|
||||||
<div :class="['tab', { active: activeTab === 'channels' }]" @click="switchToChannels">
|
<div :class="['tab', { active: activeTab === 'channels' }]" @click="switchToChannels">
|
||||||
@@ -22,7 +25,7 @@
|
|||||||
<div class="error-text">{{ error }}</div>
|
<div class="error-text">{{ error }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="!loading" class="search-container">
|
<div v-if="!loading && !isFloatMode" class="search-container">
|
||||||
<SearchPersonDropdown />
|
<SearchPersonDropdown />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -119,7 +122,7 @@
|
|||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onUnmounted, watch, onActivated, computed } from 'vue'
|
import { ref, onUnmounted, watch, onActivated, computed } from 'vue'
|
||||||
import { useRouter, useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { getToken, fetchCurrentUser } from '~/utils/auth'
|
import { getToken, fetchCurrentUser } from '~/utils/auth'
|
||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { useWebSocket } from '~/composables/useWebSocket'
|
import { useWebSocket } from '~/composables/useWebSocket'
|
||||||
@@ -134,7 +137,7 @@ const config = useRuntimeConfig()
|
|||||||
const conversations = ref([])
|
const conversations = ref([])
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
const error = ref(null)
|
const error = ref(null)
|
||||||
const router = useRouter()
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const currentUser = ref(null)
|
const currentUser = ref(null)
|
||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
@@ -144,13 +147,11 @@ const { fetchChannelUnread: refreshChannelUnread, setFromList: setChannelUnreadF
|
|||||||
useChannelsUnreadCount()
|
useChannelsUnreadCount()
|
||||||
let subscription = null
|
let subscription = null
|
||||||
|
|
||||||
const chatFloating = useState('chatFloating', () => false)
|
const activeTab = ref('channels')
|
||||||
const chatPath = useState('chatPath', () => '/message-box')
|
|
||||||
const isFloat = computed(() => route.query.float === '1')
|
|
||||||
|
|
||||||
const activeTab = ref('messages')
|
|
||||||
const channels = ref([])
|
const channels = ref([])
|
||||||
const loadingChannels = ref(false)
|
const loadingChannels = ref(false)
|
||||||
|
const isFloatMode = computed(() => route.query.float === '1')
|
||||||
|
const floatRoute = useState('messageFloatRoute')
|
||||||
|
|
||||||
async function fetchConversations() {
|
async function fetchConversations() {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
@@ -158,6 +159,7 @@ async function fetchConversations() {
|
|||||||
toast.error('请先登录')
|
toast.error('请先登录')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE_URL}/api/messages/conversations`, {
|
const response = await fetch(`${API_BASE_URL}/api/messages/conversations`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -214,11 +216,14 @@ async function fetchChannels() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function switchToMessage() {
|
||||||
|
activeTab.value = 'messages'
|
||||||
|
fetchConversations()
|
||||||
|
}
|
||||||
|
|
||||||
function switchToChannels() {
|
function switchToChannels() {
|
||||||
activeTab.value = 'channels'
|
activeTab.value = 'channels'
|
||||||
if (channels.value.length === 0) {
|
fetchChannels()
|
||||||
fetchChannels()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function goToChannel(id) {
|
async function goToChannel(id) {
|
||||||
@@ -232,37 +237,26 @@ async function goToChannel(id) {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
})
|
})
|
||||||
router.push(`/message-box/${id}`)
|
if (isFloatMode.value) {
|
||||||
|
navigateTo(`/message-box/${id}?float=1`)
|
||||||
|
} else {
|
||||||
|
navigateTo(`/message-box/${id}`)
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error(e.message)
|
toast.error(e.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function minimizeChat() {
|
|
||||||
chatPath.value = route.fullPath
|
|
||||||
chatFloating.value = true
|
|
||||||
navigateTo('/')
|
|
||||||
}
|
|
||||||
|
|
||||||
function maximizeChat() {
|
|
||||||
if (window.parent) {
|
|
||||||
window.parent.postMessage(
|
|
||||||
{
|
|
||||||
type: 'maximize-chat',
|
|
||||||
path: route.fullPath.replace('?float=1', '').replace('&float=1', ''),
|
|
||||||
},
|
|
||||||
'*',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onActivated(async () => {
|
onActivated(async () => {
|
||||||
loading.value = true
|
|
||||||
currentUser.value = await fetchCurrentUser()
|
currentUser.value = await fetchCurrentUser()
|
||||||
|
|
||||||
if (currentUser.value) {
|
if (currentUser.value) {
|
||||||
await fetchConversations()
|
if (activeTab.value === 'messages') {
|
||||||
refreshGlobalUnreadCount() // Refresh global count when entering the list
|
await fetchConversations()
|
||||||
|
} else {
|
||||||
|
await fetchChannels()
|
||||||
|
}
|
||||||
|
refreshGlobalUnreadCount()
|
||||||
refreshChannelUnread()
|
refreshChannelUnread()
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (token && !isConnected.value) {
|
if (token && !isConnected.value) {
|
||||||
@@ -299,7 +293,16 @@ onUnmounted(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
function goToConversation(id) {
|
function goToConversation(id) {
|
||||||
router.push(`/message-box/${id}`)
|
if (isFloatMode.value) {
|
||||||
|
navigateTo(`/message-box/${id}?float=1`)
|
||||||
|
} else {
|
||||||
|
navigateTo(`/message-box/${id}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function minimize() {
|
||||||
|
floatRoute.value = route.fullPath
|
||||||
|
navigateTo('/')
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -308,6 +311,18 @@ function goToConversation(id) {
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.float-control {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
text-align: right;
|
||||||
|
padding: 12px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.float-control i {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
.tabs {
|
.tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
border-bottom: 1px solid var(--normal-border-color);
|
border-bottom: 1px solid var(--normal-border-color);
|
||||||
@@ -341,6 +356,21 @@ function goToConversation(id) {
|
|||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.page-title {
|
||||||
|
padding: 12px;
|
||||||
|
display: none;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-title-text {
|
||||||
|
margin-left: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-title-text:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.messages-title {
|
.messages-title {
|
||||||
font-size: 28px;
|
font-size: 28px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
@@ -465,19 +495,21 @@ function goToConversation(id) {
|
|||||||
margin-left: 4px;
|
margin-left: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-controls {
|
@media (max-height: 200px) {
|
||||||
position: absolute;
|
.page-title {
|
||||||
top: 10px;
|
display: block;
|
||||||
right: 10px;
|
}
|
||||||
cursor: pointer;
|
|
||||||
z-index: 10;
|
.tabs,
|
||||||
|
.loading-message,
|
||||||
|
.error-container,
|
||||||
|
.search-container,
|
||||||
|
.empty-container,
|
||||||
|
.conversation-item {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.control-icon {
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 响应式设计 */
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.conversation-item {
|
.conversation-item {
|
||||||
margin-left: 10px;
|
margin-left: 10px;
|
||||||
|
|||||||
@@ -260,7 +260,6 @@ import { getMedalTitle } from '~/utils/medal'
|
|||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { getToken, authState } from '~/utils/auth'
|
import { getToken, authState } from '~/utils/auth'
|
||||||
import TimeManager from '~/utils/time'
|
import TimeManager from '~/utils/time'
|
||||||
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'
|
||||||
@@ -272,7 +271,6 @@ const API_BASE_URL = config.public.apiBaseUrl
|
|||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const postId = route.params.id
|
const postId = route.params.id
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
const title = ref('')
|
const title = ref('')
|
||||||
const author = ref('')
|
const author = ref('')
|
||||||
|
|||||||
@@ -94,6 +94,13 @@
|
|||||||
<i class="fas fa-user-plus"></i>
|
<i class="fas fa-user-plus"></i>
|
||||||
<div class="profile-tabs-item-label">关注</div>
|
<div class="profile-tabs-item-label">关注</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
:class="['profile-tabs-item', { selected: selectedTab === 'favorites' }]"
|
||||||
|
@click="selectedTab = 'favorites'"
|
||||||
|
>
|
||||||
|
<i class="fas fa-bookmark"></i>
|
||||||
|
<div class="profile-tabs-item-label">收藏</div>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
:class="['profile-tabs-item', { selected: selectedTab === 'achievements' }]"
|
:class="['profile-tabs-item', { selected: selectedTab === 'achievements' }]"
|
||||||
@click="selectedTab = 'achievements'"
|
@click="selectedTab = 'achievements'"
|
||||||
@@ -318,6 +325,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="selectedTab === 'favorites'" class="favorites-container">
|
||||||
|
<div v-if="favoritePosts.length > 0">
|
||||||
|
<BaseTimeline :items="favoritePosts">
|
||||||
|
<template #item="{ item }">
|
||||||
|
<NuxtLink :to="`/posts/${item.post.id}`" class="timeline-link">
|
||||||
|
{{ item.post.title }}
|
||||||
|
</NuxtLink>
|
||||||
|
<div class="timeline-snippet">
|
||||||
|
{{ stripMarkdown(item.post.snippet) }}
|
||||||
|
</div>
|
||||||
|
<div class="timeline-date">{{ formatDate(item.post.createdAt) }}</div>
|
||||||
|
</template>
|
||||||
|
</BaseTimeline>
|
||||||
|
</div>
|
||||||
|
<div v-else class="summary-empty">暂无收藏文章</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div v-else-if="selectedTab === 'achievements'" class="achievements-container">
|
<div v-else-if="selectedTab === 'achievements'" class="achievements-container">
|
||||||
<AchievementList :medals="medals" :can-select="isMine" />
|
<AchievementList :medals="medals" :can-select="isMine" />
|
||||||
</div>
|
</div>
|
||||||
@@ -328,7 +352,7 @@
|
|||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, ref, watch } from 'vue'
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import AchievementList from '~/components/AchievementList.vue'
|
import AchievementList from '~/components/AchievementList.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'
|
||||||
@@ -346,13 +370,13 @@ definePageMeta({
|
|||||||
alias: ['/users/:id/'],
|
alias: ['/users/:id/'],
|
||||||
})
|
})
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
|
||||||
const username = route.params.id
|
const username = route.params.id
|
||||||
|
|
||||||
const user = ref({})
|
const user = ref({})
|
||||||
const hotPosts = ref([])
|
const hotPosts = ref([])
|
||||||
const hotReplies = ref([])
|
const hotReplies = ref([])
|
||||||
const hotTags = ref([])
|
const hotTags = ref([])
|
||||||
|
const favoritePosts = ref([])
|
||||||
const timelineItems = ref([])
|
const timelineItems = ref([])
|
||||||
const timelineFilter = ref('all')
|
const timelineFilter = ref('all')
|
||||||
const filteredTimelineItems = computed(() => {
|
const filteredTimelineItems = computed(() => {
|
||||||
@@ -370,7 +394,7 @@ const subscribed = ref(false)
|
|||||||
const isLoading = ref(true)
|
const isLoading = ref(true)
|
||||||
const tabLoading = ref(false)
|
const tabLoading = ref(false)
|
||||||
const selectedTab = ref(
|
const selectedTab = ref(
|
||||||
['summary', 'timeline', 'following', 'achievements'].includes(route.query.tab)
|
['summary', 'timeline', 'following', 'favorites', 'achievements'].includes(route.query.tab)
|
||||||
? route.query.tab
|
? route.query.tab
|
||||||
: 'summary',
|
: 'summary',
|
||||||
)
|
)
|
||||||
@@ -407,7 +431,7 @@ const fetchUser = async () => {
|
|||||||
user.value = data
|
user.value = data
|
||||||
subscribed.value = !!data.subscribed
|
subscribed.value = !!data.subscribed
|
||||||
} else if (res.status === 404) {
|
} else if (res.status === 404) {
|
||||||
router.replace('/404')
|
navigateTo('/404')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,6 +497,16 @@ const fetchFollowUsers = async () => {
|
|||||||
followings.value = followingRes.ok ? await followingRes.json() : []
|
followings.value = followingRes.ok ? await followingRes.json() : []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fetchFavorites = async () => {
|
||||||
|
const res = await fetch(`${API_BASE_URL}/api/users/${username}/subscribed-posts`)
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json()
|
||||||
|
favoritePosts.value = data.map((p) => ({ icon: 'fas fa-bookmark', post: p }))
|
||||||
|
} else {
|
||||||
|
favoritePosts.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const loadSummary = async () => {
|
const loadSummary = async () => {
|
||||||
tabLoading.value = true
|
tabLoading.value = true
|
||||||
await fetchSummary()
|
await fetchSummary()
|
||||||
@@ -491,6 +525,12 @@ const loadFollow = async () => {
|
|||||||
tabLoading.value = false
|
tabLoading.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const loadFavorites = async () => {
|
||||||
|
tabLoading.value = true
|
||||||
|
await fetchFavorites()
|
||||||
|
tabLoading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
const fetchAchievements = async () => {
|
const fetchAchievements = async () => {
|
||||||
const res = await fetch(`${API_BASE_URL}/api/medals?userId=${user.value.id}`)
|
const res = await fetch(`${API_BASE_URL}/api/medals?userId=${user.value.id}`)
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
@@ -558,7 +598,7 @@ const sendMessage = async () => {
|
|||||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||||
})
|
})
|
||||||
const result = await response.json()
|
const result = await response.json()
|
||||||
router.push(`/message-box/${result.conversationId}`)
|
navigateTo(`/message-box/${result.conversationId}`)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error('无法发起私信')
|
toast.error('无法发起私信')
|
||||||
console.error(e)
|
console.error(e)
|
||||||
@@ -579,6 +619,8 @@ const init = async () => {
|
|||||||
await loadTimeline()
|
await loadTimeline()
|
||||||
} else if (selectedTab.value === 'following') {
|
} else if (selectedTab.value === 'following') {
|
||||||
await loadFollow()
|
await loadFollow()
|
||||||
|
} else if (selectedTab.value === 'favorites') {
|
||||||
|
await loadFavorites()
|
||||||
} else if (selectedTab.value === 'achievements') {
|
} else if (selectedTab.value === 'achievements') {
|
||||||
await loadAchievements()
|
await loadAchievements()
|
||||||
}
|
}
|
||||||
@@ -592,11 +634,13 @@ const init = async () => {
|
|||||||
onMounted(init)
|
onMounted(init)
|
||||||
|
|
||||||
watch(selectedTab, async (val) => {
|
watch(selectedTab, async (val) => {
|
||||||
// router.replace({ query: { ...route.query, tab: val } })
|
// navigateTo({ query: { ...route.query, tab: val } }, { replace: true })
|
||||||
if (val === 'timeline' && timelineItems.value.length === 0) {
|
if (val === 'timeline' && timelineItems.value.length === 0) {
|
||||||
await loadTimeline()
|
await loadTimeline()
|
||||||
} else if (val === 'following' && followers.value.length === 0 && followings.value.length === 0) {
|
} else if (val === 'following' && followers.value.length === 0 && followings.value.length === 0) {
|
||||||
await loadFollow()
|
await loadFollow()
|
||||||
|
} else if (val === 'favorites' && favoritePosts.value.length === 0) {
|
||||||
|
await loadFavorites()
|
||||||
} else if (val === 'achievements' && medals.value.length === 0) {
|
} else if (val === 'achievements' && medals.value.length === 0) {
|
||||||
await loadAchievements()
|
await loadAchievements()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user