Merge pull request '增加加密引用回复和本机消息管理' (#9) from xhgit/chat-message-actions into main

Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/9
This commit was merged in pull request #9.
This commit is contained in:
xhgit committed 2026-11-14 00:11:57 +00:00
commit 43cc2a5a6f
14 files changed
+321 -14

No files matched your search

+5 -1
View File
@@ -9,7 +9,7 @@
</head>
<body>
<header>
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span></div>
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button></div>
<form id="address-form">
<button type="button" data-action="back" aria-label="后退">←</button>
<button type="button" data-action="forward" aria-label="前进">→</button>
@@ -26,5 +26,9 @@
</form>
<div id="status" role="status"></div>
</header>
<main id="library" hidden>
<section><h1>书签</h1><ul id="bookmarks"></ul></section>
<section><h1>浏览历史</h1><ul id="history"></ul></section>
</main>
</body>
</html>
+7
View File
@@ -16,4 +16,11 @@ form { padding: 6px 8px 2px; }
input { flex: 1; min-width: 0; }
#status { padding: 0 10px; color: light-dark(#943f42,#ffb3b9); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
#mode { margin-left: auto; white-space: nowrap; }
#library { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 18px; padding: 18px; }
#library[hidden] { display: none; }
#library h1 { font-size: 18px; margin: 0 0 10px; }
#library ul { list-style: none; margin: 0; padding: 0; }
#library li { display: flex; gap: 6px; align-items: start; margin-bottom: 6px; }
#library li button:first-child { display: grid; flex: 1; text-align: left; white-space: normal; overflow-wrap: anywhere; }
#library li span { font-size: 11px; opacity: .78; }
@media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } }
+38
View File
@@ -5,6 +5,34 @@ const status = document.querySelector('#status')
const button = (action) => document.querySelector(`[data-action="${action}"]`)
let current
function renderEntries(selector, entries, removable) {
const container = document.querySelector(selector)
const rows = entries.map((entry) => {
const row = document.createElement('li')
const open = document.createElement('button')
const title = document.createElement('strong')
const url = document.createElement('span')
title.textContent = entry.title || entry.url
url.textContent = entry.url
open.append(title, url)
open.onclick = () => void command('openEntry', entry.id)
row.append(open)
if (removable) {
const remove = document.createElement('button')
remove.textContent = '移除'
remove.onclick = () => void command('removeBookmark', entry.id)
row.append(remove)
}
return row
})
if (!rows.length) {
const empty = document.createElement('li')
empty.textContent = removable ? '暂无书签' : '暂无历史记录'
rows.push(empty)
}
container.replaceChildren(...rows)
}
function render(state) {
current = state
tabs.replaceChildren(...state.tabs.map((tab) => {
@@ -28,6 +56,16 @@ function render(state) {
button('reload').setAttribute('aria-label', state.loading ? '停止加载' : '刷新')
for (const action of ['copy', 'external', 'zoomIn', 'zoomOut']) button(action).disabled = !state.url
document.querySelector('#mode').textContent = state.privateMode ? '隐私窗口' : ''
button('bookmark').hidden = state.privateMode
button('bookmark').disabled = !state.url
button('bookmark').textContent = state.bookmarked ? '取消书签' : '添加书签'
button('library').hidden = state.privateMode
button('library').setAttribute('aria-pressed', String(state.libraryMode))
document.querySelector('#library').hidden = !state.libraryMode
if (state.libraryMode) {
renderEntries('#bookmarks', state.bookmarks, true)
renderEntries('#history', state.history, false)
}
status.textContent = state.error
}
+66
View File
@@ -0,0 +1,66 @@
import { app } from 'electron'
import { randomUUID } from 'node:crypto'
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
export type Entry = { id: string; url: string; title: string; time: number }
type Library = { bookmarks: Entry[]; history: Entry[] }
let cache: Library | undefined
const file = () => join(app.getPath('userData'), 'browser-library.json')
export function library(): Library {
if (cache) return cache
try {
const saved = JSON.parse(readFileSync(file(), 'utf8')) as Partial<Library>
cache = { bookmarks: parseEntries(saved.bookmarks), history: parseEntries(saved.history) }
} catch {
cache = { bookmarks: [], history: [] }
}
return cache
}
function parseEntries(value: unknown): Entry[] {
if (!Array.isArray(value)) return []
return value.slice(0, 250).filter((item): item is Entry =>
typeof item?.id === 'string' && typeof item.url === 'string' &&
typeof item.title === 'string' && typeof item.time === 'number')
}
function persist(next: Library) {
const target = file()
const temporary = target + '.tmp'
writeFileSync(temporary, JSON.stringify(next), { mode: 0o600 })
renameSync(temporary, target)
cache = next
}
function entry(url: string, title: string): Entry {
return { id: randomUUID(), url, title: title.trim().slice(0, 200), time: Date.now() }
}
export function visit(url: string, title: string) {
const previous = library()
const first = previous.history[0]
if (first?.url === url && first.title === title) return
const history = [entry(url, title), ...previous.history.filter((item) => item.url !== url)].slice(0, 250)
persist({ ...previous, history })
}
export function toggleBookmark(url: string, title: string) {
const previous = library()
const present = previous.bookmarks.some((item) => item.url === url)
if (!present && previous.bookmarks.length >= 250) throw new Error('书签数量已达上限')
const bookmarks = present ? previous.bookmarks.filter((item) => item.url !== url) :
[entry(url, title), ...previous.bookmarks]
persist({ ...previous, bookmarks })
}
export function removeBookmark(id: string) {
const previous = library()
persist({ ...previous, bookmarks: previous.bookmarks.filter((item) => item.id !== id) })
}
export function clearHistory() {
persist({ ...library(), history: [] })
}
+58 -3
View File
@@ -2,6 +2,7 @@ import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, W
import type { Session } from 'electron'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { clearHistory, library, removeBookmark, toggleBookmark, visit } from './browser-library'
const browserURL = 'xhchat://app/browser'
const height = 102
@@ -14,6 +15,7 @@ type BrowserWindowState = {
privateMode: boolean
tabs: Tab[]
active?: Tab
libraryMode: boolean
}
const windows = new Map<number, BrowserWindowState>()
@@ -39,6 +41,7 @@ function address(value: string): URL | undefined {
function state(browser: BrowserWindowState) {
const contents = browser.active?.view.webContents
const collection = browser.privateMode ? { bookmarks: [], history: [] } : library()
return {
privateMode: browser.privateMode,
active: browser.active?.id,
@@ -48,6 +51,9 @@ function state(browser: BrowserWindowState) {
forward: contents?.navigationHistory.canGoForward() ?? false,
loading: contents?.isLoading() ?? false,
error: browser.active?.error ?? '',
libraryMode: browser.libraryMode,
bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()),
...collection,
}
}
@@ -59,6 +65,7 @@ function resize(browser: BrowserWindowState) {
const [width, total] = browser.window.getContentSize()
const top = browser.window.isFullScreen() ? 0 : height
browser.active?.view.setBounds({ x: 0, y: top, width, height: Math.max(0, total - top) })
browser.active?.view.setVisible(!browser.libraryMode)
}
function activate(browser: BrowserWindowState, tab?: Tab) {
@@ -71,6 +78,10 @@ function activate(browser: BrowserWindowState, tab?: Tab) {
update(browser)
}
function updateNormalWindows() {
for (const browser of windows.values()) if (!browser.privateMode) update(browser)
}
async function navigate(tab: Tab, url: URL) {
tab.error = ''
try {
@@ -106,11 +117,23 @@ function addTab(browser: BrowserWindowState, url?: URL) {
if (mainFrame && code !== -3) tab.error = '网页加载失败,请检查地址或网络。'
update(browser)
})
function remember() {
const current = website(contents.getURL())
if (!browser.privateMode && current && current.href.length <= 4096) {
try {
visit(current.href, contents.getTitle())
updateNormalWindows()
} catch {
tab.error = '无法保存浏览历史'
}
}
update(browser)
}
contents.on('did-navigate', () => { tab.error = ''; update(browser) })
contents.on('did-navigate-in-page', () => update(browser))
contents.on('did-navigate-in-page', (_event, _url, mainFrame) => { if (mainFrame) remember() })
contents.on('page-title-updated', () => update(browser))
contents.on('did-start-loading', () => update(browser))
contents.on('did-stop-loading', () => update(browser))
contents.on('did-stop-loading', remember)
contents.on('enter-html-full-screen', () => resize(browser))
contents.on('leave-html-full-screen', () => resize(browser))
contents.on('before-input-event', (event, input) => {
@@ -179,7 +202,7 @@ export function openBrowser(trusted: Session, privateMode = false) {
sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false,
},
})
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [] }
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [], libraryMode: false }
const id = window.webContents.id
windows.set(id, browser)
window.setMenuBarVisibility(false)
@@ -225,6 +248,8 @@ export function registerBrowserHandlers(trusted: Session) {
case 'go': {
const target = typeof value === 'string' ? address(value) : undefined
if (!target) throw new Error('请输入 HTTPS 地址或搜索关键词。')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
@@ -237,6 +262,35 @@ export function registerBrowserHandlers(trusted: Session) {
case 'zoomIn': if (contents) contents.setZoomLevel(Math.min(4, contents.getZoomLevel() + 1)); break
case 'zoomOut': if (contents) contents.setZoomLevel(Math.max(-3, contents.getZoomLevel() - 1)); break
case 'fullscreen': browser.window.setFullScreen(!browser.window.isFullScreen()); break
case 'library': {
if (browser.privateMode) throw new Error('隐私窗口不记录浏览历史')
browser.libraryMode = !browser.libraryMode
resize(browser)
break
}
case 'bookmark': {
if (browser.privateMode || !current || current.href.length > 4096) throw new Error('此页面无法添加书签')
toggleBookmark(current.href, contents?.getTitle() ?? '')
updateNormalWindows()
break
}
case 'removeBookmark': {
if (browser.privateMode || typeof value !== 'string') break
removeBookmark(value)
updateNormalWindows()
break
}
case 'openEntry': {
if (browser.privateMode || typeof value !== 'string') break
const { bookmarks, history } = library()
const entry = [...bookmarks, ...history].find((item) => item.id === value)
const target = entry ? website(entry.url) : undefined
if (!target) throw new Error('该网址不可用')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
case 'clear': {
const answer = await dialog.showMessageBox(browser.window, {
type: 'question', message: '清除浏览器 Cookie、缓存和网站数据?',
@@ -244,6 +298,7 @@ export function registerBrowserHandlers(trusted: Session) {
})
if (answer.response === 1) {
await browser.sites.clearData()
if (!browser.privateMode) clearHistory()
for (const candidate of windows.values()) {
if (candidate.sites !== browser.sites) continue
for (const tab of candidate.tabs) tab.view.webContents.navigationHistory.clear()
+2 -1
View File
@@ -18,7 +18,8 @@
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索和隐私窗口,网页运行在独立会话中。 |
| 消息管理 | 支持引用回复、搜索本机历史、收藏和本机删除。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+2
View File
@@ -4,6 +4,8 @@
内置浏览器将以 Chromium 的真实 UA 追加 XHChat/版本,保留 UA-CH 默认协商并用测试站检查一致性。导航、重定向和新窗口只接受允许的网络协议。摄像头、麦克风、剪贴板、通知与位置默认拒绝,后续按可信 UI 中的顶级网站授权。下载由可信 UI 确认路径及来源。恶意站点警告机制需要评估信誉服务、误报与隐私影响。
普通窗口的书签和历史保存在 Electron 用户目录,独立于通讯存储。可信工具栏展示标题和地址时使用纯文本。打开收藏或历史项会在主进程重新校验 URL。隐私窗口使用临时分区,关闭后清理网站数据,不写入浏览记录。
聊天链接卡片由发送者主动请求预览。若采用代理,部署独立网络出口并在每次重定向及实际建连时校验公网目的地址,限制响应类型、体积、超时与跳转次数。代理只接收明确提交的 URL,卡片由客户端随 E2EE 消息传输。安全验收包含远程网页的权限拒绝、无特权对象、无通讯存储可见性和自定义协议隔离。
## 威胁模型
+9 -1
View File
@@ -21,7 +21,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
- 阶段二与三还需分片附件、消息操作、群聊、多设备可信授权、加密备份与跨设备历史同步。两设备文字和小附件私聊已进入开发预览。
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
- 阶段五还需持久书签和历史、下载记录、逐站授权、反钓鱼及聊天联动。
- 阶段五还需下载记录、逐站授权、反钓鱼及聊天联动。
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
## 联系人和 Chromium 浏览器
@@ -54,3 +54,11 @@ Edge 与 Electron 集成测试覆盖错误安全码、双向文字、网络封
## 端到端加密附件预览
Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度、密钥和 IV 位于 MLS 消息中,附件服务只存密文。下载先验证认证标签,再提供本地保存。跨端用例覆盖上传密文、篡改拒绝和下载字节一致性。对象存储、分片断点续传和媒体专用界面仍待完成。
## 消息管理
Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。远程撤回、编辑、转发与跨设备收藏同步待后续交付。
## 浏览器书签和历史
Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多 250 条。书签支持添加、打开和移除。清除站点数据会同时清除历史。隐私窗口不读写书签或历史,隔离测试验证其访问不会出现在普通窗口。
+18
View File
@@ -90,6 +90,24 @@ test('双端联系人实时同步,桌面浏览器独立分区与 UA', { timeou
const userAgent = requests.find((entry) => entry.path === '/first').userAgent
assert.ok(userAgent.includes('Chrome/' + site.version))
assert.match(userAgent, /XHChat\/0\.1\.0/)
await toolbar.getByRole('button', { name: '添加书签', exact: true }).click()
await toolbar.getByRole('button', { name: '取消书签', exact: true }).waitFor()
await toolbar.getByRole('button', { name: '书签与历史', exact: true }).click()
await toolbar.locator('#bookmarks').getByText(url + '/first', { exact: true }).waitFor()
await toolbar.locator('#history').getByText(url + '/first', { exact: true }).waitFor()
const openedPrivate = app.waitForEvent('window')
await toolbar.getByRole('button', { name: '隐私窗口', exact: true }).click()
const privateToolbar = await openedPrivate
const privateAddress = privateToolbar.getByRole('textbox', { name: '网址或搜索关键词' })
await privateAddress.fill(url + '/private')
await privateAddress.press('Enter')
await privateToolbar.getByRole('button', { name: '隔离测试站', exact: true }).waitFor()
assert.equal(await privateToolbar.getByRole('button', { name: '书签与历史' }).count(), 0)
assert.equal(await toolbar.locator('#history').getByText(url + '/private', { exact: true }).count(), 0)
await privateToolbar.close()
await toolbar.locator('#bookmarks').getByRole('button', { name: '移除' }).click()
await toolbar.getByText('暂无书签').waitFor()
await toolbar.getByRole('button', { name: '书签与历史', exact: true }).click()
await toolbar.getByRole('button', { name: '新建标签页' }).click()
await toolbar.getByRole('button', { name: '新标签页', exact: true }).waitFor()
await address.fill('file:///C:/Windows/win.ini')
+15
View File
@@ -103,8 +103,23 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice'])
await windows.getByText(text, { exact: true }).waitFor()
const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex')
await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click()
await send(windows, reply)
await web.getByText(reply, { exact: true }).waitFor()
await web.getByRole('listitem').filter({ hasText: reply }).locator('blockquote').getByText(text, { exact: true }).waitFor()
const original = web.getByRole('listitem').filter({ has: web.getByText(text, { exact: true }) }).filter({ hasNot: web.locator('blockquote') })
await original.getByRole('button', { name: '收藏', exact: true }).click()
await original.getByRole('button', { name: '取消收藏' }).waitFor()
await web.getByLabel('只看收藏').check()
assert.equal(await web.getByRole('listitem').count(), 1)
await web.getByLabel('搜索本机消息').fill('无匹配的搜索词')
await web.getByText('没有匹配的消息。').waitFor()
await web.getByLabel('搜索本机消息').clear()
await web.getByLabel('只看收藏').uncheck()
await original.getByRole('button', { name: '本机删除' }).click()
await web.getByRole('button', { name: '确认删除' }).click()
await original.waitFor({ state: 'detached' })
await windows.getByRole('listitem').filter({ hasText: text }).filter({ hasNot: windows.locator('blockquote') }).waitFor()
const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex'))
const fileName = '跨端验收.txt'
+18 -1
View File
@@ -53,8 +53,16 @@ export function encodeAttachment(attachment: Attachment) {
return message
}
export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment } {
export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment; quote?: string } {
if (message[0] !== 255) return { text: decoder.decode(message) }
if (message[1] === 2 && message.length <= 18_000) {
const value = JSON.parse(decoder.decode(message.subarray(2))) as { text?: unknown; quote?: unknown } | null
if (!value || typeof value.text !== 'string' || !value.text.trim() || typeof value.quote !== 'string' ||
!value.quote.trim() || value.quote.length > 240 || encoder.encode(value.text).length > 8000) {
throw new Error('引用消息格式无效')
}
return { text: value.text, quote: value.quote }
}
if (message[1] !== 1 || message.length > 4096) throw new Error('附件描述格式无效')
const value = JSON.parse(decoder.decode(message.subarray(2))) as Attachment | null
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
@@ -67,6 +75,15 @@ export function decodeMessage(message: Uint8Array): { text: string; attachment?:
return { text: '', attachment: value }
}
export function encodeReply(text: string, quote: string) {
const body = encoder.encode(JSON.stringify({ text, quote }))
if (body.length + 2 > 18_000) throw new Error('引用消息过长')
const message = new Uint8Array(body.length + 2)
message.set([255, 2])
message.set(body, 2)
return message
}
export async function downloadAttachment(attachment: Attachment, call: Call) {
const ciphertext = await call<ArrayBuffer>(attachmentPath(attachment.id), 'GET', undefined, true)
if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败')
+23 -3
View File
@@ -3,7 +3,7 @@ import { mlsBinding, signMls } from '../identity'
import { base64, decode, fingerprint, loadEngine } from './engine'
import type { DeviceMls } from './engine'
import { withVault } from './vault'
import { decodeMessage, encodeAttachment, sealAttachment, uploadAttachment } from './attachments'
import { decodeMessage, encodeAttachment, encodeReply, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment } from './attachments'
export interface Peer {
@@ -27,6 +27,8 @@ export interface ChatLine {
peer: string
text: string
attachment?: Attachment
quote?: string
favorite?: boolean
time: string
own: boolean
}
@@ -149,7 +151,7 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
return unavailable
}
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call) {
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call, reply?: ChatLine) {
return update(identity, async (state, save, factory) => {
const current = (await directory(call, user)).find((item) => item.id === peer.id)
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码')
@@ -162,6 +164,8 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
throw new Error('消息须为 1 至 8000 字节')
}
if (state.lines.length >= 1000) throw new Error('本机预览版消息容量已达上限')
const quote = reply && reply.peer === current.id ? (reply.text || reply.attachment?.name || '').slice(0, 240) : undefined
if (quote && typeof content === 'string') plaintext = encodeReply(text, quote)
const engine = factory.DeviceMls.restore(decode(state.engine))
try {
let group = state.groups[current.id] ? decode(state.groups[current.id]) : undefined
@@ -184,7 +188,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
const id = crypto.randomUUID()
const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext)
state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) })
state.lines.push({ id, peer: current.id, text, attachment, time: new Date().toISOString(), own: true })
state.lines.push({ id, peer: current.id, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
state.engine = base64(engine.snapshot())
await save(state)
await flush(state, save, call)
@@ -194,6 +198,22 @@ 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 (action === 'remove') {
if (state.outbox.some((item) => item.messageId === line.id && item.recipientDevice === line.peer)) {
throw new Error('待发送消息暂不能删除')
}
state.lines.splice(index, 1)
} else {
state.lines[index]!.favorite = !state.lines[index]!.favorite
}
await save(state)
})
}
export function synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => {
const peers = await directory(call, user)
+7
View File
@@ -85,6 +85,13 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.chat-lines small { display: block; text-align: end; }
.chat-compose { display: grid; gap: 8px; }
.chat-compose button { justify-self: end; }
.chat-filters, .chat-quote, .message-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: end; }
.chat-filters label:first-child { flex: 1 1 180px; }
.chat-checkbox { display: flex; align-items: center; gap: 6px; padding: 10px 4px; }
.chat-checkbox input { width: auto; }
.chat-lines blockquote { border-left: 2px solid var(--line); margin: 0 0 4px; padding: 0 6px; color: var(--muted); font-size: .9em; }
.message-actions { margin-top: 5px; }
.message-actions .plain { font-size: .78em; padding: 2px 6px; }
.account-footer { display: grid; gap: 12px; margin-top: auto; }
.account-footer p { color: var(--muted); font-size: 13px; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; }
+53 -4
View File
@@ -2,7 +2,8 @@
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { enableChat, send, synchronize, trust } from '../chat/chat'
import { enableChat, localMessageAction, send, synchronize, trust } from '../chat/chat'
import type { ChatLine } from '../chat/chat'
import { downloadAttachment } from '../chat/attachments'
import type { Attachment } from '../chat/attachments'
@@ -12,6 +13,10 @@ const ownCode = ref('')
const code = ref('')
const selected = ref('')
const draft = ref('')
const search = ref('')
const favoritesOnly = ref(false)
const reply = ref<ChatLine>()
const deleting = ref<ChatLine>()
const error = ref('')
const busy = ref(false)
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
@@ -19,7 +24,12 @@ const target = computed(() => typeof route.params.user === 'string' ? route.para
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 lines = computed(() => (view.value?.lines ?? []).filter((line) => line.peer === selected.value))
const lines = computed(() => {
const query = search.value.trim().toLowerCase()
return (view.value?.lines ?? []).filter((line) => line.peer === selected.value &&
(!favoritesOnly.value || line.favorite) &&
(!query || [line.text, line.attachment?.name, line.quote].some((part) => part?.toLowerCase().includes(query))))
})
let timer: ReturnType<typeof setInterval>
async function execute(action: () => Promise<void>) {
@@ -65,8 +75,9 @@ function confirm() {
function submit() {
void execute(async () => {
if (!session.identity || !peer.value) return
await send(session.identity, target.value, peer.value, draft.value, session.authorized)
await send(session.identity, target.value, peer.value, draft.value, session.authorized, reply.value)
draft.value = ''
reply.value = undefined
await refresh()
})
}
@@ -87,6 +98,16 @@ function saveAttachment(attachment: Attachment) {
void execute(() => downloadAttachment(attachment, session.authorized))
}
function localAction(line: ChatLine, action: 'favorite' | 'remove') {
void execute(async () => {
if (!session.identity) return
await localMessageAction(session.identity, line, action)
deleting.value = undefined
if (action === 'remove' && reply.value?.id === line.id) reply.value = undefined
await refresh()
})
}
function sync() {
if (ownCode.value) void execute(refresh)
}
@@ -98,6 +119,12 @@ watch(target, () => {
draft.value = ''
sync()
})
watch(selected, () => {
search.value = ''
favoritesOnly.value = false
reply.value = undefined
deleting.value = undefined
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
onMounted(() => { timer = setInterval(sync, 10_000) })
onBeforeUnmount(() => clearInterval(timer))
@@ -135,14 +162,36 @@ onBeforeUnmount(() => clearInterval(timer))
<p class="verified-label">设备已验证</p>
<p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p>
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</p>
<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>
</div>
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
<li v-for="line in lines" :key="line.id" :class="{ own: line.own }">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }">
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<button v-if="line.attachment" type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
<span v-else>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
<div class="message-actions">
<button type="button" class="plain" :disabled="busy" @click="reply = line">引用</button>
<button type="button" class="plain" :disabled="busy" @click="localAction(line, 'favorite')">
{{ line.favorite ? '取消收藏' : '收藏' }}
</button>
<button type="button" class="plain" :disabled="busy || view?.unsent.includes(line.id)" @click="deleting = line">本机删除</button>
</div>
</li>
</ol>
<p v-if="(search || favoritesOnly) && !lines.length" class="muted">没有匹配的消息。</p>
<div v-if="deleting" class="confirmation">
<p>从本机删除这条消息?</p>
<button type="button" class="plain" :disabled="busy" @click="localAction(deleting, 'remove')">确认删除</button>
<button type="button" class="plain" @click="deleting = undefined">取消</button>
</div>
<form class="chat-compose" @submit.prevent="submit">
<div v-if="reply" class="chat-quote">
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
<button type="button" class="plain" @click="reply = undefined">取消引用</button>
</div>
<label>发送附件<input type="file" :disabled="busy" @change="attach"></label>
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
<button class="primary" :disabled="busy || !draft.trim()">发送</button>