Compare commits

..

1 Commits

Author SHA1 Message Date
Tim cf4ca89e19 feat: show channel unread indicator 2025-08-23 02:05:39 +08:00
5 changed files with 91 additions and 109 deletions
+11 -12
View File
@@ -7,7 +7,7 @@
<i class="fas fa-bars"></i> <i class="fas fa-bars"></i>
</button> </button>
<span <span
v-if="isMobile && (unreadMessageCount > 0 || hasChannelUnread)" v-if="isMobile && (messageUnreadCount > 0 || channelUnreadCount > 0)"
class="menu-unread-dot" class="menu-unread-dot"
></span> ></span>
</div> </div>
@@ -53,10 +53,10 @@
<ToolTip v-if="isLogin" content="站内信和频道" placement="bottom"> <ToolTip v-if="isLogin" content="站内信和频道" placement="bottom">
<div class="messages-icon" @click="goToMessages"> <div class="messages-icon" @click="goToMessages">
<i class="fas fa-comments"></i> <i class="fas fa-comments"></i>
<span v-if="unreadMessageCount > 0" class="unread-badge">{{ <span v-if="messageUnreadCount > 0" class="unread-badge">
unreadMessageCount {{ messageUnreadCount }}
}}</span> </span>
<span v-else-if="hasChannelUnread" class="unread-dot"></span> <span v-else-if="channelUnreadCount > 0" class="messages-unread-dot"></span>
</div> </div>
</ToolTip> </ToolTip>
@@ -89,7 +89,6 @@ import ToolTip from '~/components/ToolTip.vue'
import SearchDropdown from '~/components/SearchDropdown.vue' import SearchDropdown from '~/components/SearchDropdown.vue'
import { authState, clearToken, loadCurrentUser } from '~/utils/auth' import { authState, clearToken, loadCurrentUser } from '~/utils/auth'
import { useUnreadCount } from '~/composables/useUnreadCount' import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelUnread } from '~/composables/useChannelUnread'
import { useIsMobile } from '~/utils/screen' import { useIsMobile } from '~/utils/screen'
import { themeState, cycleTheme, ThemeMode } from '~/utils/theme' import { themeState, cycleTheme, ThemeMode } from '~/utils/theme'
import { toast } from '~/main' import { toast } from '~/main'
@@ -107,8 +106,10 @@ const props = defineProps({
const isLogin = computed(() => authState.loggedIn) const isLogin = computed(() => authState.loggedIn)
const isMobile = useIsMobile() const isMobile = useIsMobile()
const { count: unreadMessageCount, fetchUnreadCount } = useUnreadCount() const { count: totalUnreadCount, channelUnreadCount, fetchUnreadCount } = useUnreadCount()
const { hasUnread: hasChannelUnread, fetchChannelUnread } = useChannelUnread() const messageUnreadCount = computed(() =>
Math.max(totalUnreadCount.value - channelUnreadCount.value, 0),
)
const avatar = ref('') const avatar = ref('')
const showSearch = ref(false) const showSearch = ref(false)
const searchDropdown = ref(null) const searchDropdown = ref(null)
@@ -233,10 +234,8 @@ onMounted(async () => {
} }
const updateUnread = async () => { const updateUnread = async () => {
if (authState.loggedIn) { if (authState.loggedIn) {
// Initialize the unread count composable
fetchUnreadCount() fetchUnreadCount()
fetchChannelUnread()
} else {
fetchChannelUnread()
} }
} }
@@ -421,7 +420,7 @@ onMounted(async () => {
box-sizing: border-box; box-sizing: border-box;
} }
.unread-dot { .messages-unread-dot {
position: absolute; position: absolute;
top: -2px; top: -2px;
right: -4px; right: -4px;
@@ -1,38 +0,0 @@
import { ref } from 'vue'
import { getToken } from '~/utils/auth'
const hasUnread = ref(false)
export function useChannelUnread() {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const setFromList = (channels) => {
hasUnread.value = Array.isArray(channels) && channels.some((c) => c.unreadCount > 0)
}
const fetchChannelUnread = async () => {
const token = getToken()
if (!token) {
hasUnread.value = false
return
}
try {
const response = await fetch(`${API_BASE_URL}/api/channels`, {
headers: { Authorization: `Bearer ${token}` },
})
if (response.ok) {
const data = await response.json()
setFromList(data)
}
} catch (e) {
console.error('Failed to fetch channel unread status:', e)
}
}
return {
hasUnread,
fetchChannelUnread,
setFromList,
}
}
+75 -45
View File
@@ -1,93 +1,123 @@
import { ref, watch, onMounted } from 'vue'; import { ref, watch } from 'vue'
import { useWebSocket } from './useWebSocket'; import { useWebSocket } from './useWebSocket'
import { getToken } from '~/utils/auth'; import { getToken } from '~/utils/auth'
const count = ref(0); const count = ref(0)
let isInitialized = false; const channelUnreadCount = ref(0)
let wsSubscription = null; let isInitialized = false
let wsSubscription = null
export function useUnreadCount() { export function useUnreadCount() {
const config = useRuntimeConfig(); const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl; const API_BASE_URL = config.public.apiBaseUrl
const { subscribe, isConnected, connect } = useWebSocket(); const { subscribe, isConnected, connect } = useWebSocket()
const fetchUnreadCount = async () => { const fetchTotalUnreadCount = async () => {
const token = getToken(); const token = getToken()
if (!token) { if (!token) {
count.value = 0; count.value = 0
return; return
} }
try { try {
const response = await fetch(`${API_BASE_URL}/api/messages/unread-count`, { const response = await fetch(`${API_BASE_URL}/api/messages/unread-count`, {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
}); })
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json()
count.value = data; count.value = data
} }
} catch (error) { } catch (error) {
console.error('Failed to fetch unread count:', error); console.error('Failed to fetch unread count:', error)
} }
}; }
const fetchChannelUnreadCount = async () => {
const token = getToken()
if (!token) {
channelUnreadCount.value = 0
return
}
try {
const response = await fetch(`${API_BASE_URL}/api/channels`, {
headers: { Authorization: `Bearer ${token}` },
})
if (response.ok) {
const channels = await response.json()
channelUnreadCount.value = channels.reduce((sum, ch) => sum + (ch.unreadCount || 0), 0)
}
} catch (error) {
console.error('Failed to fetch channel unread count:', error)
}
}
const fetchUnreadCount = async () => {
await Promise.all([fetchTotalUnreadCount(), fetchChannelUnreadCount()])
}
const initialize = async () => { const initialize = async () => {
const token = getToken(); const token = getToken()
if (!token) { if (!token) {
count.value = 0; count.value = 0
return; channelUnreadCount.value = 0
return
} }
// 总是获取最新的未读数量 // 总是获取最新的未读数量
fetchUnreadCount(); fetchUnreadCount()
// 确保WebSocket连接 // 确保WebSocket连接
if (!isConnected.value) { if (!isConnected.value) {
connect(token); connect(token)
} }
// 设置WebSocket监听 // 设置WebSocket监听
await setupWebSocketListener(); await setupWebSocketListener()
}; }
const setupWebSocketListener = async () => { const setupWebSocketListener = async () => {
// 只有在还没有订阅的情况下才设置监听 // 只有在还没有订阅的情况下才设置监听
if (!wsSubscription) { if (!wsSubscription) {
watch(
watch(isConnected, (newValue) => { isConnected,
if (newValue && !wsSubscription) { (newValue) => {
const destination = `/user/queue/unread-count`; if (newValue && !wsSubscription) {
wsSubscription = subscribe(destination, (message) => { const destination = `/user/queue/unread-count`
const unreadCount = parseInt(message.body, 10); wsSubscription = subscribe(destination, (message) => {
if (!isNaN(unreadCount)) { const unreadCount = parseInt(message.body, 10)
count.value = unreadCount; if (!isNaN(unreadCount)) {
} count.value = unreadCount
}); fetchChannelUnreadCount()
} }
}, { immediate: true }); })
}
},
{ immediate: true },
)
} }
}; }
// 自动初始化逻辑 - 确保每次调用都能获取到未读数量并设置监听 // 自动初始化逻辑 - 确保每次调用都能获取到未读数量并设置监听
const token = getToken(); const token = getToken()
if (token) { if (token) {
if (!isInitialized) { if (!isInitialized) {
isInitialized = true; isInitialized = true
initialize(); // 完整初始化,包括WebSocket监听 initialize() // 完整初始化,包括WebSocket监听
} else { } else {
// 即使已经初始化,也要确保获取最新的未读数量并确保WebSocket监听存在 // 即使已经初始化,也要确保获取最新的未读数量并确保WebSocket监听存在
fetchUnreadCount(); fetchUnreadCount()
// 确保WebSocket连接和监听都存在 // 确保WebSocket连接和监听都存在
if (!isConnected.value) { if (!isConnected.value) {
connect(token); connect(token)
} }
setupWebSocketListener(); setupWebSocketListener()
} }
} }
return { return {
count, count,
channelUnreadCount,
fetchUnreadCount, fetchUnreadCount,
initialize, initialize,
}; }
} }
-3
View File
@@ -69,7 +69,6 @@ import { renderMarkdown } from '~/utils/markdown'
import MessageEditor from '~/components/MessageEditor.vue' import MessageEditor from '~/components/MessageEditor.vue'
import { useWebSocket } from '~/composables/useWebSocket' import { useWebSocket } from '~/composables/useWebSocket'
import { useUnreadCount } from '~/composables/useUnreadCount' import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelUnread } from '~/composables/useChannelUnread'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
import BaseTimeline from '~/components/BaseTimeline.vue' import BaseTimeline from '~/components/BaseTimeline.vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue' import BasePlaceholder from '~/components/BasePlaceholder.vue'
@@ -79,7 +78,6 @@ const route = useRoute()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const { connect, disconnect, subscribe, isConnected } = useWebSocket() const { connect, disconnect, subscribe, isConnected } = useWebSocket()
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount() const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
const { fetchChannelUnread: refreshChannelUnread } = useChannelUnread()
let subscription = null let subscription = null
const messages = ref([]) const messages = ref([])
@@ -260,7 +258,6 @@ async function markConversationAsRead() {
}) })
// After marking as read, refresh the global unread count // After marking as read, refresh the global unread count
refreshGlobalUnreadCount() refreshGlobalUnreadCount()
refreshChannelUnread()
} catch (e) { } catch (e) {
console.error('Failed to mark conversation as read', e) console.error('Failed to mark conversation as read', e)
} }
+1 -7
View File
@@ -117,7 +117,6 @@ import { getToken, fetchCurrentUser } from '~/utils/auth'
import { toast } from '~/main' import { toast } from '~/main'
import { useWebSocket } from '~/composables/useWebSocket' import { useWebSocket } from '~/composables/useWebSocket'
import { useUnreadCount } from '~/composables/useUnreadCount' import { useUnreadCount } from '~/composables/useUnreadCount'
import { useChannelUnread } from '~/composables/useChannelUnread'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
import { stripMarkdownLength } from '~/utils/markdown' import { stripMarkdownLength } from '~/utils/markdown'
import SearchPersonDropdown from '~/components/SearchPersonDropdown.vue' import SearchPersonDropdown from '~/components/SearchPersonDropdown.vue'
@@ -132,8 +131,6 @@ const currentUser = ref(null)
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const { connect, disconnect, subscribe, isConnected } = useWebSocket() const { connect, disconnect, subscribe, isConnected } = useWebSocket()
const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount() const { fetchUnreadCount: refreshGlobalUnreadCount } = useUnreadCount()
const { fetchChannelUnread: refreshChannelUnread, setFromList: setChannelUnreadFromList } =
useChannelUnread()
let subscription = null let subscription = null
const activeTab = ref('messages') const activeTab = ref('messages')
@@ -192,9 +189,7 @@ async function fetchChannels() {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
}) })
if (!response.ok) throw new Error('无法加载频道') if (!response.ok) throw new Error('无法加载频道')
const data = await response.json() channels.value = await response.json()
channels.value = data
setChannelUnreadFromList(data)
} catch (e) { } catch (e) {
toast.error(e.message) toast.error(e.message)
} finally { } finally {
@@ -233,7 +228,6 @@ onActivated(async () => {
if (currentUser.value) { if (currentUser.value) {
await fetchConversations() await fetchConversations()
refreshGlobalUnreadCount() // Refresh global count when entering the list refreshGlobalUnreadCount() // Refresh global count when entering the list
refreshChannelUnread()
const token = getToken() const token = getToken()
if (token && !isConnected.value) { if (token && !isConnected.value) {
connect(token) connect(token)