从收藏跳转并定位私聊和群聊原消息

This commit is contained in:
xhgit committed 2026-11-15 23:02:52 +08:00
1 parent f923b0ca7b
commit 7717120bac
11 files changed
+150 -22

No files matched your search

+25 -2
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { APIError } from '../api'
import { downloadAttachment, maxAttachmentSize } from './attachments'
@@ -12,10 +13,15 @@ import VoiceRecorder from './VoiceRecorder.vue'
import { enableChat, trust } from './chat'
import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, groupQuote, publishGroup, removeLocalGroupMessage, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat'
import { focusMessage, groupMessageFocus, groupMessageKey } from './message-key'
const props = defineProps<{ group: GroupDetail }>()
const emit = defineEmits<{ seen: [] }>()
const session = useSession()
const route = useRoute()
const history = ref<HTMLUListElement>()
const openedMessage = ref('')
const requestedMessage = computed(() => groupMessageFocus(route.query.message, props.group.id))
const view = ref<Awaited<ReturnType<typeof synchronizeGroup>>>()
const code = ref('')
const codes = ref<Record<string, string>>({})
@@ -63,6 +69,8 @@ const lines = computed(() => {
return mode === 'messages' ? matches : matches.reverse()
})
const visibleLines = computed(() => historyView.value.id === 'messages' ? lines.value : lines.value.slice(0, mediaLimit.value))
const highlighted = computed(() => requestedMessage.value && visibleLines.value.find((line) =>
!line.recalled && groupMessageKey(props.group.id, line) === requestedMessage.value))
const members = computed(() => props.group.members.filter((member) => member.state === 'active' && member.id !== session.identity?.user.id))
const canPublish = computed(() => Boolean(view.value && !view.value.current && members.value.every((member) =>
view.value?.devices.some((device) => device.user === member.id && device.id === selected.value[member.id] && pinned(device)))))
@@ -317,6 +325,19 @@ function discard() {
watch(() => props.group.membershipVersion, queueRefresh)
watch([historyView, search, favoritesOnly], () => { mediaLimit.value = mediaPageSize })
watch(requestedMessage, (key) => {
openedMessage.value = ''
if (!key) return
historyView.value = historyViews[0]
search.value = ''
favoritesOnly.value = false
if (code.value) queueRefresh()
else enable()
}, { immediate: true })
watch([highlighted, history], () => {
const key = requestedMessage.value
if (key && key !== openedMessage.value && highlighted.value && focusMessage(history.value)) openedMessage.value = key
}, { flush: 'post' })
watch(() => session.groupChange, (event) => { if (event?.groupId === props.group.id) queueRefresh() })
watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() })
watch(currentEpoch, (epoch, previous) => {
@@ -364,6 +385,7 @@ onBeforeUnmount(() => {
<button v-if="!code" class="primary" :disabled="busy" @click="enable">启用本机群聊</button>
<template v-else>
<p v-if="view?.warning" class="muted" role="status">{{ view.warning }}</p>
<p v-if="requestedMessage && view && !highlighted && !openedMessage && !busy" class="muted" role="status">原消息当前无法定位。</p>
<p v-if="ready" role="status">群加密已建立</p>
<p v-else-if="view?.current && !view.current.welcome">当前设备未获分配群密钥。</p>
<p v-else-if="!view?.current && group.role !== 'owner'">等待群主建立群加密会话。</p>
@@ -419,9 +441,10 @@ onBeforeUnmount(() => {
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
</div>
<p v-if="!lines.length && (historyView.id !== 'messages' || search.trim() || favoritesOnly)" class="muted" role="status">{{ historyView.empty }}</p>
<ul v-if="visibleLines.length" class="group-chat-lines" :class="{ 'group-media': historyView.id !== 'messages' }"
<ul v-if="visibleLines.length" ref="history" class="group-chat-lines" :class="{ 'group-media': historyView.id !== 'messages' }"
:aria-label="historyView.id === 'messages' ? '群消息记录' : historyView.label">
<li v-for="line in visibleLines" :key="[historyView.id, line.epoch, line.sender, line.id].join('/')">
<li v-for="line in visibleLines" :key="[historyView.id, line.epoch, line.sender, line.id].join('/')"
:aria-current="highlighted === line ? 'true' : undefined" :tabindex="highlighted === line ? -1 : undefined">
<small>{{ line.name }} · {{ new Date(line.time).toLocaleString() }}</small>
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<p v-if="line.recalled" class="muted">消息已撤回</p>
+2 -1
View File
@@ -271,7 +271,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
export function localMessageAction(identity: ChatIdentity, line: ChatLine, action: 'favorite' | 'remove') {
return update(identity, async (state, save) => {
const index = state.lines.findIndex((item) => item.id === line.id && item.peer === line.peer && item.own === line.own)
if (index < 0) return
if (index < 0) return state.lines
if (action === 'remove') {
if (state.outbox.some((item) => (item.mutationTarget ?? item.messageId) === line.id && item.recipientDevice === line.peer)) {
throw new Error('待发送消息暂不能删除')
@@ -283,6 +283,7 @@ export function localMessageAction(identity: ChatIdentity, line: ChatLine, actio
else if (!target.recalled) target.favorite = true
}
await save(state)
return state.lines
})
}
+7 -10
View File
@@ -1,7 +1,7 @@
import type { Attachment } from './attachments'
import type { ChatLine, ChatState } from './chat'
import type { GroupLine } from './group-chat'
import { splitChatText } from './links'
import { groupMessageKey, privateMessageKey } from './message-key'
import { withVault } from './vault'
type FavoriteType = 'text' | 'link' | 'image' | 'video' | 'voice' | 'file'
@@ -20,9 +20,6 @@ export type Favorite = CommonFavorite & (
{ kind: 'group'; group: string; sender: string; epoch?: string; id: string }
)
const privateKey = (line: ChatLine) => ['private', line.peer, line.own ? 'own' : 'remote', line.id].join('/')
const groupKey = (group: string, line: GroupLine) => ['group', group, line.epoch, line.sender, line.id].join('/')
export function clearFavorite(line: FavoriteFields) {
delete line.favorite
delete line.favoriteTags
@@ -58,14 +55,14 @@ function entries(state?: ChatState): Favorite[] {
for (const line of state?.lines ?? []) {
if (!line.favorite || line.recalled) continue
const { id, peer, own, contact, text, quote, time, attachment } = line
favorites.push({ kind: 'private', key: privateKey(line), type: favoriteType(line), id, peer, own, contact, text, quote, time,
favorites.push({ kind: 'private', key: privateMessageKey(line), type: favoriteType(line), id, peer, own, contact, text, quote, time,
attachment, tags: line.favoriteTags ?? [] })
}
for (const [group, chat] of Object.entries(state?.groupChats ?? {})) {
for (const line of chat.lines) {
if (!line.favorite || line.recalled) continue
const { id, epoch, sender, text, quote, time, attachment } = line
favorites.push({ kind: 'group', key: groupKey(group, line), type: favoriteType(line), id, group, epoch, sender, text, quote,
favorites.push({ kind: 'group', key: groupMessageKey(group, line), type: favoriteType(line), id, group, epoch, sender, text, quote,
time, attachment, tags: line.favoriteTags ?? [] })
}
}
@@ -88,14 +85,14 @@ export function removeFavorites(device: string, keys: ReadonlySet<string>) {
return changeFavorites(device, (state) => {
let changed = false
for (const line of state.lines) {
if (line.favorite && keys.has(privateKey(line))) {
if (line.favorite && keys.has(privateMessageKey(line))) {
clearFavorite(line)
changed = true
}
}
for (const [group, chat] of Object.entries(state.groupChats ?? {})) {
for (const line of chat.lines) {
if (line.favorite && keys.has(groupKey(group, line))) {
if (line.favorite && keys.has(groupMessageKey(group, line))) {
clearFavorite(line)
changed = true
}
@@ -108,8 +105,8 @@ export function removeFavorites(device: string, keys: ReadonlySet<string>) {
export function setFavoriteTags(device: string, key: string, tags: string[]) {
return changeFavorites(device, (state) => {
const group = key.split('/')[1] ?? ''
const line = key.startsWith('private/') ? state.lines.find((item) => privateKey(item) === key) :
state.groupChats?.[group]?.lines.find((item) => groupKey(group, item) === key)
const line = key.startsWith('private/') ? state.lines.find((item) => privateMessageKey(item) === key) :
state.groupChats?.[group]?.lines.find((item) => groupMessageKey(group, item) === key)
if (!line?.favorite || line.recalled) throw new Error('此消息已不在本机收藏')
const labels = normalizedTags(tags)
if (labels.length) line.favoriteTags = labels
+36
View File
@@ -0,0 +1,36 @@
import type { ChatLine } from './chat'
import type { GroupLine } from './group-chat'
const uuid = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
export function privateMessageKey(line: Pick<ChatLine, 'id' | 'peer' | 'own'>) {
return ['private', line.peer, line.own ? 'own' : 'remote', line.id].join('/')
}
export function groupMessageKey(group: string, line: Pick<GroupLine, 'id' | 'sender' | 'epoch'>) {
return ['group', group, line.epoch, line.sender, line.id].join('/')
}
export function privateMessageFocus(value: unknown) {
if (typeof value !== 'string' || value.length > 100) return
const [kind, device, side, id, extra] = value.split('/')
if (kind !== 'private' || !device || !uuid.test(device) || (side !== 'own' && side !== 'remote') ||
!id || !uuid.test(id) || extra !== undefined) return
return { key: value, device }
}
export function groupMessageFocus(value: unknown, group: string) {
if (typeof value !== 'string' || value.length > 160) return
const [kind, scope, epoch, sender, id, extra] = value.split('/')
if (kind !== 'group' || scope !== group || !uuid.test(group) || (epoch !== '' && (!epoch || !uuid.test(epoch))) ||
!sender || !uuid.test(sender) || !id || !uuid.test(id) || extra !== undefined) return
return value
}
export function focusMessage(history?: HTMLElement) {
const row = history?.querySelector<HTMLElement>('li[aria-current="true"]')
if (!row) return false
row.scrollIntoView({ block: 'center', inline: 'nearest' })
row.focus({ preventScroll: true })
return true
}
+1
View File
@@ -91,6 +91,7 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.chat-lines { list-style: none; padding: 0; margin: 0; min-height: 90px; max-height: 45vh; overflow: auto; display: flex; flex-direction: column; gap: 8px; }
.chat-lines li { align-self: start; border-radius: 9px; background: var(--base); padding: 8px 11px; max-width: 85%; white-space: pre-wrap; overflow-wrap: anywhere; }
.chat-lines li.own { align-self: end; background: var(--green-soft); }
.chat-lines li[aria-current='true'], .group-chat-lines li[aria-current='true'] { outline: 2px solid var(--green); outline-offset: -2px; }
.chat-lines small { display: block; text-align: end; }
.chat-lines audio { display: block; width: min(260px, 100%); }
.media-preview { display: grid; gap: 5px; justify-items: start; margin-bottom: 5px; }
+43 -6
View File
@@ -15,6 +15,7 @@ import VoiceRecorder from '../chat/VoiceRecorder.vue'
import VoiceMessage from '../chat/VoiceMessage.vue'
import MediaPreview from '../chat/MediaPreview.vue'
import MessageText from '../chat/MessageText.vue'
import { focusMessage, privateMessageFocus, privateMessageKey } from '../chat/message-key'
const session = useSession()
const route = useRoute()
@@ -37,6 +38,7 @@ const recent = ref<Record<string, string>>({})
const unread = ref<Record<string, number>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const openedMessage = ref('')
const shareRead = ref(false)
const pendingVoice = ref<File>()
const files = ref<File[]>([])
@@ -45,6 +47,7 @@ const batchProgress = ref('')
const maxBatchFiles = 8
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
const requestedMessage = computed(() => target.value ? privateMessageFocus(route.query.message) : undefined)
const activeContact = computed(() => contacts.value.find((item) => item.id === target.value && item.state === 'friend'))
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)
@@ -62,6 +65,8 @@ const lines = computed(() => {
(!favoritesOnly.value || line.favorite) &&
(!query || [line.text, line.attachment?.name, line.quote].some((part) => part?.toLowerCase().includes(query))))
})
const highlighted = computed(() => trusted.value && requestedMessage.value ? lines.value.find((line) =>
!line.recalled && privateMessageKey(line) === requestedMessage.value?.key) : undefined)
let timer: ReturnType<typeof setInterval>
let receiptTimer: ReturnType<typeof setTimeout> | undefined
let seenTimer: ReturnType<typeof setTimeout> | undefined
@@ -70,6 +75,8 @@ let unreadVersion = 0
let conversationVersion = 0
let markingSeen = false
let active = true
let refreshRequested = false
let refreshTimer: ReturnType<typeof setTimeout> | undefined
const seen = new Map<string, string>()
async function loadConversations() {
@@ -134,6 +141,7 @@ async function execute(action: () => Promise<void>) {
} finally {
busy.value = false
scheduleReceipt()
if (refreshRequested && active) sync()
}
}
@@ -142,7 +150,7 @@ async function refresh() {
if (!identity || !target.value || !ownCode.value) return
const contact = target.value
const current = await synchronize(identity, contact, session.authorized)
if (target.value !== contact) return
if (!active || target.value !== contact) return
view.value = current
shareRead.value = current.shareRead
for (const line of current.lines) {
@@ -150,7 +158,12 @@ async function refresh() {
recent.value[line.contact] = line.time
}
}
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
const requested = requestedMessage.value
if (requested && openedMessage.value !== requested.key && current.peers.some((device) => device.id === requested.device)) {
selected.value = requested.device
} else if (!current.peers.some((device) => device.id === selected.value)) {
selected.value = current.peers[0]?.id ?? ''
}
queueSeen()
}
@@ -335,10 +348,11 @@ function saveAttachment(attachment: Attachment) {
function localAction(line: ChatLine, action: 'favorite' | 'remove') {
void execute(async () => {
if (!session.identity) return
await localMessageAction(session.identity, line, action)
const current = view.value
const updated = await localMessageAction(session.identity, line, action)
if (current && view.value === current) current.lines = updated
deleting.value = undefined
if (action === 'remove' && reply.value?.id === line.id) reply.value = undefined
await refresh()
})
}
@@ -361,7 +375,15 @@ function submitForward(destination: ForwardDestination) {
}
function sync() {
if (ownCode.value) void execute(refresh)
if (!active || !ownCode.value || !target.value) return
refreshRequested = true
if (busy.value || refreshTimer) return
refreshTimer = setTimeout(() => {
refreshTimer = undefined
if (busy.value) return
refreshRequested = false
void execute(refresh)
}, 180)
}
watch(target, () => {
@@ -391,6 +413,18 @@ watch(() => [session.inboxChanges, session.contactChanges, session.connection],
watch(() => [session.inboxChanges, session.contactChanges, session.connection], queueUnread)
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
watch([search, favoritesOnly], scheduleReceipt)
watch(requestedMessage, (message) => {
openedMessage.value = ''
if (!message) return
search.value = ''
favoritesOnly.value = false
if (ownCode.value) sync()
else enable()
}, { immediate: true })
watch([highlighted, history], () => {
const key = requestedMessage.value?.key
if (key && key !== openedMessage.value && highlighted.value && focusMessage(history.value)) openedMessage.value = key
}, { flush: 'post' })
onMounted(() => {
void loadConversations()
queueUnread()
@@ -406,6 +440,7 @@ onBeforeUnmount(() => {
clearTimeout(receiptTimer)
clearTimeout(seenTimer)
clearTimeout(unreadTimer)
clearTimeout(refreshTimer)
unreadVersion++
window.removeEventListener('focus', scheduleReceipt)
window.removeEventListener('focus', queueSeen)
@@ -422,7 +457,7 @@ onBeforeUnmount(() => {
@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>
<button v-if="ownCode" class="plain" :disabled="busy" @click="execute(refresh)">刷新</button>
</header>
<div class="conversation-layout">
<aside class="conversation-list" aria-label="会话列表">
@@ -458,6 +493,7 @@ onBeforeUnmount(() => {
</label>
<p v-else>对方设备出现后可开始验证。</p>
<p v-if="changed" class="error" role="alert">设备身份已变更,请重新核验。</p>
<p v-if="requestedMessage && view && !highlighted && !openedMessage && !busy" class="muted" role="status">原消息当前无法定位。</p>
<p v-if="peer && !peer.mls">等待对方启用本机加密聊天。</p>
<form v-if="peer?.mls && !trusted" class="contact-preferences" @submit.prevent="confirm">
<label>对方安全码<input v-model="code" required maxlength="100" autocomplete="off"></label>
@@ -474,6 +510,7 @@ onBeforeUnmount(() => {
</div>
<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 }"
:aria-current="highlighted === line ? 'true' : undefined" :tabindex="highlighted === line ? -1 : undefined"
: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>
+12 -2
View File
@@ -35,6 +35,12 @@ function title(item: Favorite) {
return item.kind === 'group' ? groups.value[item.group] ?? '群聊' : contacts.value[item.contact ?? ''] ?? '私聊'
}
function originalPath(item: Favorite) {
if (item.kind === 'group' && groups.value[item.group]) return '/groups/' + item.group
if (item.kind === 'private' && item.contact && contacts.value[item.contact]) return '/chat/' + item.contact
return ''
}
const tags = computed(() => {
const options = new Map<string, string>()
for (const item of favorites.value) {
@@ -77,8 +83,10 @@ async function refresh() {
async function loadNames() {
const [people, conversations] = await Promise.allSettled([session.contacts(), session.authorized<ListedGroup[]>('/groups')])
if (!active) return
if (people.status === 'fulfilled') contacts.value = Object.fromEntries(people.value.map((item) => [item.id, item.alias || item.username]))
if (conversations.status === 'fulfilled') groups.value = Object.fromEntries(conversations.value.map((item) => [item.id, item.name]))
if (people.status === 'fulfilled') contacts.value = Object.fromEntries(people.value.filter((item) => item.state === 'friend')
.map((item) => [item.id, item.alias || item.username]))
if (conversations.status === 'fulfilled') groups.value = Object.fromEntries(conversations.value.filter((item) => item.state === 'active')
.map((item) => [item.id, item.name]))
}
async function change(action: (device: string) => Promise<Favorite[]>) {
@@ -218,6 +226,7 @@ onBeforeUnmount(() => {
</div>
</form>
<div v-if="!selecting && editor !== item.key" class="message-actions">
<RouterLink v-if="originalPath(item)" class="plain favorite-original" :to="{ path: originalPath(item), query: { message: item.key } }">查看原消息</RouterLink>
<button type="button" class="plain" :disabled="busy" @click="editTags(item)">编辑标签</button>
<button type="button" class="plain" :disabled="busy" @click="change((device) => removeFavorites(device, new Set([item.key])))">取消收藏</button>
</div>
@@ -240,4 +249,5 @@ onBeforeUnmount(() => {
.favorite-tags { display: flex; flex-wrap: wrap; gap: .3rem; }
.favorite-tags button { padding: .15rem .45rem; background: var(--green-soft); color: var(--green); white-space: normal; }
.favorite-tag-editor { width: min(100%, 25rem); }
.favorite-original { text-decoration: none; }
</style>