增加会话导航与可选加密已读回执

This commit is contained in:
xhgit committed 2026-11-13 23:35:26 +08:00
1 parent 6786158a3e
commit 149028267e
8 files changed
+218 -17

No files matched your search

+104 -8
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { directory, enableChat, forwardMessage, localMessageAction, mutateMessage, send, synchronize, trust } from '../chat/chat'
import { directory, enableChat, forwardMessage, localMessageAction, markRead, mutateMessage, recentConversations, send, setReadReceipts, synchronize, trust } from '../chat/chat'
import type { ChatLine, Peer } from '../chat/chat'
import type { Contact } from '../contacts'
import { downloadAttachment } from '../chat/attachments'
@@ -27,11 +27,23 @@ const destinationDevice = ref('')
const forwardDevices = ref<Peer[]>([])
const error = ref('')
const busy = ref(false)
const contacts = ref<Contact[]>([])
const recent = ref<Record<string, string>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const shareRead = ref(false)
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
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] ?? '') ||
(a.alias || a.username).localeCompare(b.alias || b.username))
})
const lines = computed(() => {
const query = search.value.trim().toLowerCase()
return (view.value?.lines ?? []).filter((line) => line.peer === selected.value &&
@@ -64,6 +76,20 @@ function openLink(url: string) {
if (internalBrowser) void execute(() => internalBrowser(url))
}
let timer: ReturnType<typeof setInterval>
let receiptTimer: ReturnType<typeof setTimeout> | undefined
async function loadConversations() {
const identity = session.identity
if (!identity) return
try {
const [people, dates] = await Promise.all([session.contacts(), recentConversations(identity)])
if (session.identity?.device.id !== identity.device.id) return
contacts.value = people
recent.value = dates
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法加载会话'
}
}
async function execute(action: () => Promise<void>) {
if (busy.value || !session.identity) return
@@ -75,6 +101,7 @@ async function execute(action: () => Promise<void>) {
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
} finally {
busy.value = false
scheduleReceipt()
}
}
@@ -85,9 +112,52 @@ async function refresh() {
const current = await synchronize(identity, contact, session.authorized)
if (target.value !== contact) return
view.value = current
shareRead.value = current.shareRead
for (const line of current.lines) {
if (line.contact && (!recent.value[line.contact] || recent.value[line.contact] < line.time)) {
recent.value[line.contact] = line.time
}
}
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
}
function scheduleReceipt() {
clearTimeout(receiptTimer)
if (!view.value?.shareRead || busy.value || !trusted.value) return
receiptTimer = setTimeout(async () => {
await nextTick()
const identity = session.identity
const selectedPeer = peer.value
const list = history.value
if (busy.value || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
const bounds = list.getBoundingClientRect()
const ids = Array.from(list.querySelectorAll<HTMLElement>('[data-unread]')).filter((row) => {
const rect = row.getBoundingClientRect()
return Math.min(rect.bottom, bounds.bottom, innerHeight) - Math.max(rect.top, bounds.top, 0) >= Math.min(rect.height, 24)
}).map((row) => row.dataset.unread!).slice(0, 64)
if (!ids.length) return
await execute(async () => {
await markRead(identity, target.value, selectedPeer, ids, session.authorized)
await refresh()
})
}, 300)
}
function toggleReceipts(event: Event) {
const checked = (event.target as HTMLInputElement).checked
shareRead.value = checked
void execute(async () => {
if (!session.identity) return
try {
await setReadReceipts(session.identity, checked)
} catch (cause) {
shareRead.value = !checked
throw cause
}
await refresh()
})
}
function enable() {
void execute(async () => {
if (!session.identity) return
@@ -212,10 +282,23 @@ watch(selected, () => {
recalling.value = undefined
forwarding.value = undefined
draft.value = ''
scheduleReceipt()
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
onMounted(() => { timer = setInterval(sync, 10_000) })
onBeforeUnmount(() => clearInterval(timer))
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
watch([search, favoritesOnly], scheduleReceipt)
onMounted(() => {
void loadConversations()
timer = setInterval(sync, 10_000)
window.addEventListener('focus', scheduleReceipt)
document.addEventListener('visibilitychange', scheduleReceipt)
})
onBeforeUnmount(() => {
clearInterval(timer)
clearTimeout(receiptTimer)
window.removeEventListener('focus', scheduleReceipt)
document.removeEventListener('visibilitychange', scheduleReceipt)
})
</script>
<template>
@@ -224,7 +307,16 @@ onBeforeUnmount(() => clearInterval(timer))
<h1>加密聊天</h1>
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
</header>
<div class="device-content chat-page">
<div class="conversation-layout">
<aside class="conversation-list" aria-label="会话列表">
<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>
</RouterLink>
<p v-if="!conversations.length" class="muted">{{ conversationQuery ? '没有匹配的会话。' : '添加好友后可开始聊天。' }}</p>
</aside>
<div class="device-content chat-page">
<p v-if="error" class="error" role="alert">{{ error }}</p>
<button v-if="!ownCode" type="button" class="primary" :disabled="busy" @click="enable">启用本机加密聊天</button>
<template v-else>
@@ -253,9 +345,11 @@ onBeforeUnmount(() => clearInterval(timer))
<div class="chat-filters">
<label>搜索本机消息<input v-model="search" type="search" maxlength="120"></label>
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
<label class="chat-checkbox"><input type="checkbox" :checked="shareRead" :disabled="busy" @change="toggleReceipts">发送已读回执</label>
</div>
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }">
<ol ref="history" class="chat-lines" aria-label="消息记录" aria-live="polite" @scroll.passive="scheduleReceipt">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }"
:data-unread="!line.own && !line.read && !line.recalled ? line.id : undefined">
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<span v-if="line.recalled" class="muted">消息已撤回</span>
<button v-else-if="line.attachment" type="button" class="plain" :disabled="busy"
@@ -264,6 +358,7 @@ onBeforeUnmount(() => clearInterval(timer))
type="button" class="chat-link" @click="openLink(part.url)">{{ part.text }}</button><a v-else-if="part.url"
class="chat-link" :href="part.url" target="_blank" rel="noopener noreferrer">{{ part.text }}</a><template v-else>{{ part.text }}</template></template></span>
<small v-if="view?.unsent.includes(line.id)">待发送</small>
<small v-else-if="line.own && line.read && !line.recalled">已读</small>
<small v-if="line.edited && !line.recalled">已编辑</small>
<div class="message-actions">
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy || Boolean(editing)" @click="reply = line">引用</button>
@@ -319,8 +414,9 @@ onBeforeUnmount(() => clearInterval(timer))
</form>
</template>
</template>
<p v-else>在联系人详情打开聊天。</p>
<p v-else>选择一个联系人开始聊天。</p>
</template>
</div>
</div>
</section>
</template>