增加私聊置顶和按设备统计未读

This commit is contained in:
xhgit committed 2026-11-15 22:35:45 +08:00
1 parent 7e165ba9b4
commit ec2679b991
19 files changed
+312 -52

No files matched your search

+4 -1
View File
@@ -42,6 +42,7 @@ interface ChatState {
engine: string
cursor: string
pending: Incoming[]
received?: Record<string, string>
outbox: Outgoing[]
lines: ChatLine[]
pinned: Record<string, string>
@@ -331,6 +332,7 @@ export function setReadReceipts(identity: ChatIdentity, enabled: boolean) {
export function synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => {
const received = state.received ??= {}
const peers = await directory(call, user)
const peerIDs = new Set(peers.map((peer) => peer.id))
let backfilled = false
@@ -385,6 +387,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
} finally {
engine.free()
}
received[peer.id] = item.sequence
state.pending = state.pending.filter((pending) => pending.sequence !== item.sequence)
await save(state)
}
@@ -405,7 +408,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
engine.free()
}
}
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, shareRead: state.shareRead === true,
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, received, shareRead: state.shareRead === true,
unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) }
})
}
+2 -1
View File
@@ -5,6 +5,7 @@ export interface Contact {
alias: string
category: string
muted: boolean
pinned: boolean
}
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences' | 'mute' | 'unmute'
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences' | 'mute' | 'unmute' | 'pin' | 'unpin'
+12
View File
@@ -65,6 +65,18 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.contact-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; padding: 8px; border-radius: 8px; border: 0; background: transparent; color: var(--text); overflow-wrap: anywhere; }
.contact-item[aria-pressed="true"] { background: var(--green-soft); }
.contact-item small { display: block; }
.unread-badge {
margin-inline-start: auto;
min-width: 1.5rem;
padding-inline: .35rem;
border-radius: 1rem;
background: var(--green-soft);
color: var(--green);
font-size: .8rem;
text-align: center;
}
.unread-badge.muted { background: var(--base); color: var(--muted); }
.unread-label { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.contact-detail { padding: 24px clamp(12px, 4vw, 36px); min-width: 0; overflow-wrap: anywhere; }
.contact-heading, .contact-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
.contact-heading h1 { font-size: 22px; }
+76 -7
View File
@@ -2,6 +2,7 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { APIError } from '../api'
import { enableChat, localMessageAction, markRead, mutateMessage, readPrivateForward, recentConversations, send, setReadReceipts, synchronize, trust } from '../chat/chat'
import type { ChatLine } from '../chat/chat'
import { forwardContent } from '../chat/group-chat'
@@ -33,6 +34,7 @@ const error = ref('')
const busy = ref(false)
const contacts = ref<Contact[]>([])
const recent = ref<Record<string, string>>({})
const unread = ref<Record<string, number>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const shareRead = ref(false)
@@ -47,7 +49,7 @@ const conversations = computed(() => {
const query = conversationQuery.value.trim().toLowerCase()
return contacts.value.filter((item) => item.state === 'friend' &&
[item.alias, item.username].some((value) => value.toLowerCase().includes(query)))
.sort((a, b) => (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
.sort((a, b) => Number(b.pinned) - Number(a.pinned) || (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
(a.alias || a.username).localeCompare(b.alias || b.username))
})
const lines = computed(() => {
@@ -58,13 +60,21 @@ const lines = computed(() => {
})
let timer: ReturnType<typeof setInterval>
let receiptTimer: ReturnType<typeof setTimeout> | undefined
let seenTimer: ReturnType<typeof setTimeout> | undefined
let unreadTimer: ReturnType<typeof setTimeout> | undefined
let unreadVersion = 0
let conversationVersion = 0
let markingSeen = false
let active = true
const seen = new Map<string, string>()
async function loadConversations() {
const identity = session.identity
if (!identity) return
const version = ++conversationVersion
try {
const [people, dates] = await Promise.all([session.contacts(), recentConversations(identity)])
if (session.identity?.device.id !== identity.device.id) return
if (version !== conversationVersion || session.identity?.device.id !== identity.device.id) return
contacts.value = people
recent.value = dates
} catch (cause) {
@@ -72,6 +82,43 @@ async function loadConversations() {
}
}
function queueUnread() {
if (!active) return
clearTimeout(unreadTimer)
const version = ++unreadVersion
unreadTimer = setTimeout(async () => {
try {
const counts = await session.authorized<Record<string, number>>('/inbox/unread')
if (version === unreadVersion) unread.value = counts
} catch {
// Retain the latest badges while the service is unavailable.
}
}, 200)
}
function queueSeen() {
if (!active) return
clearTimeout(seenTimer)
seenTimer = setTimeout(async () => {
const device = peer.value?.id
const sequence = device && view.value?.received[device]
if (!device || !sequence || !trusted.value || markingSeen || seen.get(device) === sequence ||
document.visibilityState !== 'visible' || !document.hasFocus()) return
markingSeen = true
try {
await session.authorized('/inbox/seen', 'POST', { senderDevice: device, sequence })
seen.set(device, sequence)
queueUnread()
queueSeen()
} catch (error) {
// The server may expire a delivery before the device reports it as seen.
if (error instanceof APIError && error.status === 404) seen.set(device, sequence)
} finally {
markingSeen = false
}
}, 200)
}
async function execute(action: () => Promise<void>) {
if (busy.value || !session.identity) return
busy.value = true
@@ -100,13 +147,15 @@ async function refresh() {
}
}
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
queueSeen()
}
function toggleMute() {
function togglePreference(preference: 'mute' | 'pin') {
const contact = activeContact.value
if (!contact) return
const enabled = preference === 'mute' ? contact.muted : contact.pinned
void execute(async () => {
await session.changeContact(contact.id, contact.muted ? 'unmute' : 'mute')
await session.changeContact(contact.id, enabled ? `un${preference}` : preference)
await loadConversations()
})
}
@@ -275,21 +324,32 @@ watch(selected, () => {
pendingFile.value = undefined
draft.value = ''
scheduleReceipt()
queueSeen()
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
watch(() => [session.inboxChanges, session.contactChanges, session.connection], queueUnread)
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
watch([search, favoritesOnly], scheduleReceipt)
onMounted(() => {
void loadConversations()
timer = setInterval(sync, 10_000)
queueUnread()
timer = setInterval(() => { sync(); queueUnread() }, 10_000)
window.addEventListener('focus', scheduleReceipt)
window.addEventListener('focus', queueSeen)
document.addEventListener('visibilitychange', scheduleReceipt)
document.addEventListener('visibilitychange', queueSeen)
})
onBeforeUnmount(() => {
active = false
clearInterval(timer)
clearTimeout(receiptTimer)
clearTimeout(seenTimer)
clearTimeout(unreadTimer)
unreadVersion++
window.removeEventListener('focus', scheduleReceipt)
window.removeEventListener('focus', queueSeen)
document.removeEventListener('visibilitychange', scheduleReceipt)
document.removeEventListener('visibilitychange', queueSeen)
})
</script>
@@ -298,7 +358,9 @@ onBeforeUnmount(() => {
<header class="page-header">
<h1>加密聊天</h1>
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.muted" :disabled="busy"
@click="toggleMute">消息免打扰</button>
@click="togglePreference('mute')">消息免打扰</button>
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.pinned" :disabled="busy"
@click="togglePreference('pin')">会话置顶</button>
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
</header>
<div class="conversation-layout">
@@ -306,7 +368,14 @@ onBeforeUnmount(() => {
<label>查找会话<input v-model="conversationQuery" type="search" maxlength="120"></label>
<RouterLink v-for="contact in conversations" :key="contact.id" class="contact-item" :to="'/chat/' + contact.id">
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
<span><strong>{{ contact.alias || contact.username }}</strong><small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small></span>
<span><strong>{{ contact.alias || contact.username }}</strong>
<small v-if="contact.pinned">已置顶</small>
<small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small>
</span>
<span v-if="unread[contact.id]" class="unread-badge" :class="{ muted: contact.muted }">
<span aria-hidden="true">{{ unread[contact.id]! >= 100 ? '99+' : unread[contact.id] }}</span>
<span class="unread-label">{{ unread[contact.id]! >= 100 ? '99 条以上未读' : unread[contact.id] + ' 条未读' }}</span>
</span>
</RouterLink>
<p v-if="!conversations.length" class="muted">{{ conversationQuery ? '没有匹配的会话。' : '添加好友后可开始聊天。' }}</p>
</aside>
+1 -16
View File
@@ -182,7 +182,7 @@ onBeforeUnmount(() => {
<strong>{{ group.name }}</strong>
<small>{{ group.state === 'invited' ? '待接受邀请' : roles[group.role] }}<template v-if="group.pinned"> · 已置顶</template><template v-if="group.muted"> · 免打扰</template></small>
</span>
<span v-if="group.unread" class="group-unread" :class="{ muted: group.muted }">
<span v-if="group.unread" class="unread-badge" :class="{ muted: group.muted }">
<span aria-hidden="true">{{ group.unread >= 100 ? '99+' : group.unread }}</span>
<span class="unread-label">{{ group.unread >= 100 ? '99 条以上未读' : group.unread + ' 条未读' }}</span>
</span>
@@ -252,18 +252,3 @@ onBeforeUnmount(() => {
</div>
</section>
</template>
<style scoped>
.group-unread {
margin-inline-start: auto;
min-width: 1.5rem;
padding-inline: .35rem;
border-radius: 1rem;
background: var(--green-soft);
color: var(--green);
font-size: .8rem;
text-align: center;
}
.group-unread.muted { background: var(--base); color: var(--muted); }
.unread-label { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
</style>