本机收藏标签与批量管理 #45

Merged
xhgit merged 1 commits from xhgit/favorite-management into main 2026-11-15 23:03:03 +08:00
7 changed files with 218 additions and 39 deletions

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@
| 加密附件 | 两端可在私聊和群聊多选或拖入文件,每批最多 8 个,每个最大 8 MiB。图片、视频在本机预览,群聊支持按附件类型查看。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 |
| 本机收藏 | 在同一个入口查看私聊与群聊收藏,按来源和内容类型筛选。支持本机搜索、预览媒体、播放语音、下载加密附件和取消收藏。 |
| 本机收藏 | 汇总私聊与群聊收藏,支持本机搜索、按来源、内容类型和标签筛选。可预览媒体、播放语音、下载加密附件或批量取消收藏。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+2
View File
@@ -226,3 +226,5 @@ Windows 与 Edge 验证多选、拖拽、移除、清空和数量上限。第二
## 本机收藏中心
Windows 和 Web 可从工作区进入收藏,查看当前设备本机密文库中的私聊和群聊收藏,按消息时间倒序分页。可按来源和文字、网页、图片、视频、语音、文件筛选。本机搜索匹配消息文字、引用、文件名及会话名称。复用聊天内的安全链接处理、媒体解密预览、语音播放和附件下载,附件仍受服务端访问权限和保留期限约束。取消收藏保留原消息,收藏状态按本机设备隔离。
收藏标签与消息一起保存在本机加密库,可筛选和搜索。批量管理支持选择当前列表和逐条选择,确认后在一次本机写入中清除收藏与关联标签。已撤回消息也会移出收藏。
+29 -1
View File
@@ -420,8 +420,21 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
assert.deepEqual(await readFile(await (await favoriteDownload).path()), Buffer.from(remainingFile))
await webFavorites.getByRole('button', { name: '取消收藏', exact: true }).click()
await web.getByText('没有匹配的收藏。', { exact: true }).waitFor()
await web.getByLabel('内容类型').selectOption('link')
await webFavorites.getByRole('button', { name: '编辑标签', exact: true }).click()
await web.getByLabel('收藏标签').fill('验收资料,DOC,Doc')
await webFavorites.getByRole('button', { name: '保存标签', exact: true }).click()
await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor()
assert.equal(await webFavorites.locator('.favorite-tags button').count(), 2)
await web.getByLabel('标签筛选', { exact: true }).selectOption('doc')
await search.fill('dOc')
await webFavorites.getByRole('link', { name: link, exact: true }).waitFor()
await work(web).getByRole('link', { name: '联系人', exact: true }).click()
await work(web).getByRole('link', { name: '收藏', exact: true }).click()
await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor()
web.off('request', trackFavorites)
assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body && !url.includes(encodeURIComponent(marker))))
assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body &&
!url.includes(encodeURIComponent(marker)) && !url.includes(encodeURIComponent('验收资料'))))
await windows.getByLabel('内容类型').selectOption('image')
await windowsFavorites.getByRole('button', { name: '预览 加密预览.png', exact: true }).click()
@@ -430,6 +443,21 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
await windowsFavorites.getByRole('button', { name: '播放语音', exact: true }).click()
await windows.waitForFunction(() => document.querySelector('.favorite-card audio')?.currentTime > 0)
assert.equal(await windowsFavorites.getByRole('link', { name: link, exact: true }).count(), 0)
await windows.getByLabel('内容类型').selectOption('all')
await windows.getByRole('button', { name: '批量管理', exact: true }).click()
await windows.getByRole('button', { name: '选择当前列表', exact: true }).click()
const bulk = windows.getByRole('button', { name: '取消所选收藏(2)', exact: true })
await bulk.click()
const confirmation = windows.getByRole('region', { name: '确认取消收藏' })
await confirmation.getByRole('button', { name: '返回', exact: true }).click()
assert.equal(await windowsFavorites.getByRole('listitem').count(), 2)
await bulk.click()
await confirmation.getByRole('button', { name: '确认取消收藏', exact: true }).click()
await windows.getByText('本机还没有收藏。', { exact: true }).waitFor()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
await windows.getByRole('button', { name: '预览 加密预览.png', exact: true }).waitFor()
await windows.getByRole('button', { name: '播放语音', exact: true }).waitFor()
} finally {
await desktop?.close()
await browser.close()
+8 -4
View File
@@ -6,6 +6,8 @@ import { withVault } from './vault'
import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readForwardedFile, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment, Mutation } from './attachments'
import type { GroupChatState } from './group-chat'
import { clearFavorite } from './favorites'
import type { FavoriteFields } from './favorites'
export interface Peer {
id: string
@@ -23,13 +25,12 @@ export interface Package { package: string; signature: string }
interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: string; silent?: boolean }
interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string }
export interface ChatLine {
export interface ChatLine extends FavoriteFields {
id: string
peer: string
text: string
attachment?: Attachment
quote?: string
favorite?: boolean
recalled?: boolean
edited?: boolean
read?: boolean
@@ -174,13 +175,14 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
return unavailable
}
export function applyMutation(line: Pick<ChatLine, 'text' | 'attachment' | 'quote' | 'recalled' | 'edited'>, mutation: Mutation) {
export function applyMutation(line: Pick<ChatLine, 'text' | 'attachment' | 'quote' | 'recalled' | 'edited'> & FavoriteFields, mutation: Mutation) {
if (line.recalled) return
if (mutation.action === 'recall') {
line.recalled = true
line.text = ''
delete line.attachment
delete line.quote
clearFavorite(line)
} else if (!line.attachment && mutation.text) {
line.text = mutation.text
line.edited = true
@@ -276,7 +278,9 @@ export function localMessageAction(identity: ChatIdentity, line: ChatLine, actio
}
state.lines.splice(index, 1)
} else {
state.lines[index]!.favorite = !state.lines[index]!.favorite
const target = state.lines[index]!
if (target.favorite) clearFavorite(target)
else if (!target.recalled) target.favorite = true
}
await save(state)
})
+64 -13
View File
@@ -12,7 +12,9 @@ type CommonFavorite = {
quote?: string
time: string
attachment?: Attachment
tags: string[]
}
export type FavoriteFields = { favorite?: boolean; favoriteTags?: string[] }
export type Favorite = CommonFavorite & (
{ kind: 'private'; contact?: string; peer: string; own: boolean; id: string } |
{ kind: 'group'; group: string; sender: string; epoch?: string; id: string }
@@ -21,6 +23,28 @@ export type Favorite = CommonFavorite & (
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
}
export function favoriteTagKey(tag: string) {
return tag.normalize('NFKC').toLowerCase()
}
function normalizedTags(tags: string[]) {
const values = new Map<string, string>()
for (const tag of tags) {
const label = tag.trim()
if (!label) continue
if ([...label].length > 24 || /\p{C}/u.test(label)) throw new Error('每个标签最多 24 个字符,请移除不可见字符')
const key = favoriteTagKey(label)
if (!values.has(key)) values.set(key, label)
}
if (values.size > 8) throw new Error('每条收藏最多使用 8 个标签')
return [...values.values()]
}
function favoriteType(line: Pick<ChatLine, 'attachment' | 'text'>): FavoriteType {
if (line.attachment?.voice) return 'voice'
if (line.attachment?.media?.startsWith('image/')) return 'image'
@@ -34,13 +58,15 @@ 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, attachment })
favorites.push({ kind: 'private', key: privateKey(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, time, attachment })
favorites.push({ kind: 'group', key: groupKey(group, line), type: favoriteType(line), id, group, epoch, sender, text, quote,
time, attachment, tags: line.favoriteTags ?? [] })
}
}
return favorites.sort((a, b) => b.time.localeCompare(a.time) || a.key.localeCompare(b.key))
@@ -50,19 +76,44 @@ export function listFavorites(device: string) {
return withVault<ChatState, Favorite[]>(device, async (state) => entries(state), true)
}
export function removeFavorite(device: string, key: string) {
function changeFavorites(device: string, change: (state: ChatState) => boolean) {
return withVault<ChatState, Favorite[]>(device, async (state, save) => {
if (!state) return []
let line: ChatLine | GroupLine | undefined
if (key.startsWith('private/')) line = state.lines.find((item) => privateKey(item) === key)
else {
const groupID = key.split('/')[1] ?? ''
line = state.groupChats?.[groupID]?.lines.find((item) => groupKey(groupID, item) === key)
}
if (line?.favorite) {
delete line.favorite
await save(state)
}
if (change(state)) await save(state)
return entries(state)
}, true)
}
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))) {
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))) {
clearFavorite(line)
changed = true
}
}
}
return changed
})
}
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)
if (!line?.favorite || line.recalled) throw new Error('此消息已不在本机收藏')
const labels = normalizedTags(tags)
if (labels.length) line.favoriteTags = labels
else delete line.favoriteTags
return true
})
}
+5 -4
View File
@@ -4,6 +4,8 @@ import { applyMutation, replenishPackages, send, update, verifiedPeer, verify }
import type { Call, ChatIdentity, Package, Peer } from './chat'
import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, readForwardedFile, sealAttachment } from './attachments'
import type { Attachment, Mutation } from './attachments'
import { clearFavorite } from './favorites'
import type { FavoriteFields } from './favorites'
export type GroupMember = { id: string; username: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member' }
export type GroupDetail = { id: string; membershipVersion: string; members: GroupMember[]; role: GroupMember['role'] }
@@ -15,9 +17,9 @@ type Epoch = { id: string; creatorDevice: string; membershipVersion: string; wel
type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] }
type Outgoing = { id: string; epoch: string; wire: string }
type Packet = Outgoing & { sequence: string; senderDevice: string; createdAt: string; attachmentId?: string }
export type GroupLine = {
export type GroupLine = FavoriteFields & {
id: string; user: string; sender: string; name: string; text: string; time: string; epoch?: string
attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean; favorite?: boolean
attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean
}
type LineRef = Pick<GroupLine, 'id' | 'sender' | 'epoch'>
export type ForwardDestination = { group: string } | { user: string; device: Peer }
@@ -62,7 +64,6 @@ function applyGroupMutation(chat: GroupChatState, epoch: string, sender: string,
const target = chat.lines.find((line) => line.id === mutation.id && line.epoch === epoch && line.sender === sender)
if (!target) return
applyMutation(target, mutation)
if (target.recalled) delete target.favorite
}
function trimHistory(chat: GroupChatState) {
@@ -76,7 +77,7 @@ export function setGroupFavorite(identity: ChatIdentity, group: GroupDetail, mes
const line = chat?.lines.find((item) => item.id === message.id && item.epoch === message.epoch && item.sender === message.sender)
if (!chat || !line || line.recalled) throw new Error('此群消息无法收藏')
if (favorite) line.favorite = true
else delete line.favorite
else clearFavorite(line)
trimHistory(chat)
await save(state)
return chat.lines
+109 -16
View File
@@ -2,7 +2,7 @@
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useSession } from '../session'
import { downloadAttachment } from '../chat/attachments'
import { listFavorites, removeFavorite } from '../chat/favorites'
import { favoriteTagKey, listFavorites, removeFavorites, setFavoriteTags } from '../chat/favorites'
import type { Favorite } from '../chat/favorites'
import { groupAttachmentPath } from '../chat/group-chat'
import type { ListedGroup } from '../chat/group-chat'
@@ -17,6 +17,12 @@ const groups = ref<Record<string, string>>({})
const query = ref('')
const type = ref('all')
const source = ref('all')
const tag = ref('')
const editor = ref('')
const tagDraft = ref('')
const selecting = ref(false)
const selected = ref(new Set<string>())
const confirmingBulk = ref(false)
const limit = ref(30)
const loading = ref(true)
const busy = ref(false)
@@ -29,14 +35,27 @@ function title(item: Favorite) {
return item.kind === 'group' ? groups.value[item.group] ?? '群聊' : contacts.value[item.contact ?? ''] ?? '私聊'
}
const normalize = (value: string) => value.normalize('NFKC').toLowerCase()
const results = computed(() => {
const term = normalize(query.value.trim())
return favorites.value.filter((item) => (type.value === 'all' || item.type === type.value) &&
(source.value === 'all' || item.kind === source.value) && (!term ||
[item.text, item.quote, item.attachment?.name, title(item)].some((value) => value && normalize(value).includes(term))))
const tags = computed(() => {
const options = new Map<string, string>()
for (const item of favorites.value) {
for (const label of item.tags) {
const key = favoriteTagKey(label)
if (!options.has(key)) options.set(key, label)
}
}
return [...options.entries()].sort(([, a], [, b]) => a.localeCompare(b, 'zh-CN'))
})
const results = computed(() => {
const term = favoriteTagKey(query.value.trim())
return favorites.value.filter((item) => (type.value === 'all' || item.type === type.value) &&
(source.value === 'all' || item.kind === source.value) && (!tag.value || item.tags.some((label) => favoriteTagKey(label) === tag.value)) &&
(!term || [item.text, item.quote, item.attachment?.name, title(item), ...item.tags]
.some((value) => value && favoriteTagKey(value).includes(term))))
})
const visible = computed(() => results.value.slice(0, limit.value))
const allVisibleSelected = computed(() => visible.value.length > 0 && visible.value.every((item) => selected.value.has(item.key)))
function path(item: Favorite) {
return item.kind === 'group' && item.attachment ? groupAttachmentPath({ id: item.group }, item.attachment.id) : undefined
}
@@ -62,22 +81,58 @@ async function loadNames() {
if (conversations.status === 'fulfilled') groups.value = Object.fromEntries(conversations.value.map((item) => [item.id, item.name]))
}
async function cancelFavorite(item: Favorite) {
async function change(action: (device: string) => Promise<Favorite[]>) {
const device = session.identity?.device.id
if (!device || busy.value) return
if (!device || busy.value) return false
busy.value = true
error.value = ''
revision++
try {
const items = await removeFavorite(device, item.key)
const items = await action(device)
if (active) favorites.value = items
return active
} catch (cause) {
if (active) error.value = cause instanceof Error ? cause.message : '无法取消收藏'
if (active) error.value = cause instanceof Error ? cause.message : '无法更新本机收藏'
return false
} finally {
busy.value = false
}
}
function editTags(item: Favorite) {
error.value = ''
editor.value = item.key
tagDraft.value = item.tags.join(',')
}
async function saveTags() {
const key = editor.value
if (await change((device) => setFavoriteTags(device, key, tagDraft.value.split(/[,,]/u)))) editor.value = ''
}
function toggleBatch() {
selecting.value = !selecting.value
editor.value = ''
confirmingBulk.value = false
selected.value.clear()
}
function selectItem(key: string, enabled: boolean) {
if (enabled) selected.value.add(key)
else selected.value.delete(key)
confirmingBulk.value = false
}
function selectVisible() {
const enabled = !allVisibleSelected.value
for (const item of visible.value) selectItem(item.key, enabled)
}
async function cancelSelected() {
const keys = new Set(selected.value)
if (keys.size && await change((device) => removeFavorites(device, keys))) toggleBatch()
}
async function download(item: Favorite) {
if (!item.attachment || busy.value) return
busy.value = true
@@ -91,7 +146,13 @@ async function download(item: Favorite) {
}
}
watch([query, source, type], () => { limit.value = 30 })
watch([query, source, type, tag], () => {
limit.value = 30
selected.value.clear()
confirmingBulk.value = false
editor.value = ''
})
watch(tags, (options) => { if (tag.value && !options.some(([key]) => key === tag.value)) tag.value = '' })
watch(() => [session.contactChanges, session.groupListChanges], () => void loadNames())
onMounted(() => {
void refresh()
@@ -106,22 +167,38 @@ onBeforeUnmount(() => {
<template>
<section class="device-page">
<header class="page-header"><h1>收藏</h1></header>
<header class="page-header"><h1>收藏</h1>
<button v-if="favorites.length" type="button" class="plain" :aria-pressed="selecting" :disabled="busy" @click="toggleBatch">批量管理</button>
</header>
<div class="device-content favorites">
<div class="favorite-filters">
<label>搜索本机收藏<input v-model="query" type="search" maxlength="120" placeholder="文字、链接、文件名或会话"></label>
<label>搜索本机收藏<input v-model="query" type="search" maxlength="120" placeholder="消息、文件名、会话或标签"></label>
<label><span id="favorite-type-label">内容类型</span><select v-model="type" aria-labelledby="favorite-type-label"><option value="all">全部类型</option>
<option v-for="(label, value) in types" :key="value" :value="value">{{ label }}</option>
</select></label>
<label><span id="favorite-source-label">来源</span><select v-model="source" aria-labelledby="favorite-source-label"><option value="all">全部会话</option>
<option value="private">私聊</option><option value="group">群聊</option>
</select></label>
<label v-if="tags.length"><span id="favorite-tag-label">标签筛选</span><select v-model="tag" aria-labelledby="favorite-tag-label">
<option value="">全部标签</option><option v-for="[key, label] in tags" :key="key" :value="key">{{ label }}</option>
</select></label>
</div>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<div v-if="selecting && visible.length" class="message-actions" aria-label="批量收藏操作">
<button type="button" class="plain" :disabled="busy" @click="selectVisible">{{ allVisibleSelected ? '取消全选' : '选择当前列表' }}</button>
<button type="button" class="plain" :disabled="busy || !selected.size" @click="confirmingBulk = true">取消所选收藏({{ selected.size }})</button>
</div>
<section v-if="confirmingBulk && selected.size" class="confirmation" aria-label="确认取消收藏">
<p>取消这 {{ selected.size }} 条收藏?原消息仍保留在会话历史中。</p>
<button type="button" class="plain danger" :disabled="busy" @click="cancelSelected">确认取消收藏</button>
<button type="button" class="plain" :disabled="busy" @click="confirmingBulk = false">返回</button>
</section>
<p v-if="loading" role="status">正在读取本机收藏…</p>
<p v-else-if="!results.length" class="muted" role="status">{{ favorites.length ? '没有匹配的收藏。' : '本机还没有收藏。' }}</p>
<ul v-else class="favorite-list" aria-label="本机收藏">
<li v-for="item in results.slice(0, limit)" :key="item.key" class="favorite-card">
<li v-for="item in visible" :key="item.key" class="favorite-card">
<label v-if="selecting" class="chat-checkbox"><input type="checkbox" :checked="selected.has(item.key)" :disabled="busy"
@change="selectItem(item.key, ($event.target as HTMLInputElement).checked)">选择此条收藏</label>
<small>{{ title(item) }} · {{ types[item.type] }} · {{ new Date(item.time).toLocaleString('zh-CN') }}</small>
<blockquote v-if="item.quote">{{ item.quote }}</blockquote>
<template v-if="item.attachment">
@@ -130,7 +207,20 @@ onBeforeUnmount(() => {
<button type="button" class="plain" :disabled="busy" @click="download(item)">下载 {{ item.attachment.name }}</button>
</template>
<p v-else class="favorite-text"><MessageText :text="item.text" @error="error = $event" /></p>
<div class="message-actions"><button type="button" class="plain" :disabled="busy" @click="cancelFavorite(item)">取消收藏</button></div>
<div v-if="item.tags.length" class="favorite-tags">
<button v-for="label in item.tags" :key="label" type="button" class="plain" @click="tag = favoriteTagKey(label)">{{ label }}</button>
</div>
<form v-if="editor === item.key" class="favorite-tag-editor" @submit.prevent="saveTags">
<label>收藏标签<input v-model="tagDraft" maxlength="240" placeholder="用逗号分隔多个标签"></label>
<div class="message-actions">
<button type="submit" class="plain" :disabled="busy">保存标签</button>
<button type="button" class="plain" :disabled="busy" @click="editor = ''">取消</button>
</div>
</form>
<div v-if="!selecting && editor !== item.key" class="message-actions">
<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>
</li>
</ul>
<button v-if="results.length > limit" type="button" class="plain" @click="limit += 30">加载更多收藏</button>
@@ -147,4 +237,7 @@ onBeforeUnmount(() => {
.favorite-card { width: 100%; padding: .85rem; border: 1px solid var(--line); border-radius: .5rem; overflow-wrap: anywhere; }
.favorite-card blockquote { margin: 0; border-inline-start: 2px solid var(--line); padding-inline-start: .55rem; color: var(--muted); }
.favorite-text { white-space: pre-wrap; }
.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); }
</style>