实现浏览器下载管理和本地下载记录

This commit is contained in:
xhgit committed 2026-11-13 19:23:20 +08:00
1 parent ae04cc9494
commit 9b8c2026ea
8 files changed
+155 -13

No files matched your search

+6 -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><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button></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><button id="show-downloads">下载</button></div>
<form id="address-form">
<button type="button" data-action="back" aria-label="后退">←</button>
<button type="button" data-action="forward" aria-label="前进">→</button>
@@ -30,5 +30,10 @@
<section><h1>书签</h1><ul id="bookmarks"></ul></section>
<section><h1>浏览历史</h1><ul id="history"></ul></section>
</main>
<section id="download-panel" hidden>
<h1>下载记录</h1>
<button data-action="clearDownloads">清除下载记录</button>
<ul id="download-list"></ul>
</section>
</body>
</html>
+5
View File
@@ -23,4 +23,9 @@ input { flex: 1; min-width: 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; }
#download-panel { padding: 18px; }
#download-panel h1 { margin: 0 0 10px; font-size: 18px; }
#download-list { list-style: none; padding: 0; }
#download-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 8px; }
#download-list strong { overflow-wrap: anywhere; }
@media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } }
+51 -3
View File
@@ -4,6 +4,37 @@ const address = document.querySelector('#address')
const status = document.querySelector('#status')
const button = (action) => document.querySelector(`[data-action="${action}"]`)
let current
let panel = 'library'
function renderDownloads(entries) {
const rows = entries.map((item) => {
const row = document.createElement('li')
const name = document.createElement('strong')
const state = document.createElement('span')
name.textContent = item.name
const labels = { progressing: '下载中', paused: '已暂停', completed: '已完成', cancelled: '已取消', interrupted: '已中断' }
state.textContent = labels[item.state] ?? item.state
if (item.total > 0 && item.state === 'progressing') state.textContent += ' · ' + Math.floor(100 * item.received / item.total) + '%'
row.append(name, state)
function add(label, action) {
const button = document.createElement('button')
button.textContent = label
button.onclick = () => void command(action, item.id)
row.append(button)
}
if (item.state === 'progressing') add('暂停', 'downloadPause')
if (item.resumable) add('继续', 'downloadResume')
if (['progressing', 'paused'].includes(item.state)) add('取消', 'downloadCancel')
if (item.state === 'completed') add('在文件夹中显示', 'showDownload')
return row
})
if (!rows.length) {
const empty = document.createElement('li')
empty.textContent = '暂无下载记录'
rows.push(empty)
}
document.querySelector('#download-list').replaceChildren(...rows)
}
function renderEntries(selector, entries, removable) {
const container = document.querySelector(selector)
@@ -60,12 +91,16 @@ function render(state) {
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) {
document.querySelector('#show-downloads').hidden = state.privateMode
button('library').setAttribute('aria-pressed', String(state.libraryMode && panel === 'library'))
document.querySelector('#show-downloads').setAttribute('aria-pressed', String(state.libraryMode && panel === 'downloads'))
document.querySelector('#library').hidden = !(state.libraryMode && panel === 'library')
document.querySelector('#download-panel').hidden = !(state.libraryMode && panel === 'downloads')
if (state.libraryMode && panel === 'library') {
renderEntries('#bookmarks', state.bookmarks, true)
renderEntries('#history', state.history, false)
}
if (state.libraryMode && panel === 'downloads') renderDownloads(state.downloads)
status.textContent = state.error
}
@@ -84,6 +119,19 @@ for (const element of document.querySelectorAll('[data-action]')) {
}
}
function showPanel(next) {
if (current?.libraryMode && panel !== next) {
panel = next
render(current)
} else {
panel = next
void command('library')
}
}
button('library').onclick = () => showPanel('library')
document.querySelector('#show-downloads').onclick = () => showPanel('downloads')
document.querySelector('#address-form').onsubmit = (event) => {
event.preventDefault()
const value = address.value
+16 -3
View File
@@ -4,7 +4,8 @@ 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[] }
export type DownloadRecord = { id: string; name: string; path: string; state: 'completed' | 'cancelled' | 'interrupted'; time: number }
type Library = { bookmarks: Entry[]; history: Entry[]; downloads: DownloadRecord[] }
let cache: Library | undefined
const file = () => join(app.getPath('userData'), 'browser-library.json')
@@ -13,9 +14,12 @@ 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) }
cache = { bookmarks: parseEntries(saved.bookmarks), history: parseEntries(saved.history),
downloads: Array.isArray(saved.downloads) ? saved.downloads.slice(0, 150).filter((item) =>
typeof item?.id === 'string' && typeof item.name === 'string' && typeof item.path === 'string' &&
typeof item.time === 'number' && ['completed', 'cancelled', 'interrupted'].includes(item.state)) : [] }
} catch {
cache = { bookmarks: [], history: [] }
cache = { bookmarks: [], history: [], downloads: [] }
}
return cache
}
@@ -64,3 +68,12 @@ export function removeBookmark(id: string) {
export function clearHistory() {
persist({ ...library(), history: [] })
}
export function recordDownload(record: DownloadRecord) {
const previous = library()
persist({ ...previous, downloads: [record, ...previous.downloads].slice(0, 150) })
}
export function clearDownloads() {
persist({ ...library(), downloads: [] })
}
+49 -3
View File
@@ -1,8 +1,8 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, WebContentsView } from 'electron'
import type { Session } from 'electron'
import type { DownloadItem, Session } from 'electron'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { clearHistory, library, removeBookmark, toggleBookmark, visit } from './browser-library'
import { clearDownloads, clearHistory, library, recordDownload, removeBookmark, toggleBookmark, visit } from './browser-library'
const browserURL = 'xhchat://app/browser'
const height = 102
@@ -19,6 +19,7 @@ type BrowserWindowState = {
}
const windows = new Map<number, BrowserWindowState>()
const downloads = new Map<string, DownloadItem>()
export function website(value: string): URL | undefined {
try {
@@ -41,7 +42,7 @@ function address(value: string): URL | undefined {
function state(browser: BrowserWindowState) {
const contents = browser.active?.view.webContents
const collection = browser.privateMode ? { bookmarks: [], history: [] } : library()
const collection = browser.privateMode ? { bookmarks: [], history: [], downloads: [] } : library()
return {
privateMode: browser.privateMode,
active: browser.active?.id,
@@ -54,6 +55,13 @@ function state(browser: BrowserWindowState) {
libraryMode: browser.libraryMode,
bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()),
...collection,
downloads: browser.privateMode ? [] : [
...[...downloads].map(([id, item]) => ({
id, name: item.getFilename(), state: item.isPaused() ? 'paused' : item.getState(),
received: item.getReceivedBytes(), total: item.getTotalBytes(), resumable: item.canResume(),
})),
...collection.downloads,
],
}
}
@@ -188,6 +196,21 @@ function configureSites(sites: Session, privateMode: boolean) {
return
}
item.setSaveDialogOptions({ title: '保存网页下载', buttonLabel: '保存' })
const id = randomUUID()
downloads.set(id, item)
item.on('updated', updateNormalWindows)
item.once('done', (_event, result) => {
downloads.delete(id)
if (result === 'completed' || result === 'cancelled' || result === 'interrupted') {
try {
recordDownload({ id, name: item.getFilename(), path: item.getSavePath(), state: result, time: Date.now() })
} catch {
if (browser.active) browser.active.error = '无法保存下载记录'
}
}
updateNormalWindows()
})
updateNormalWindows()
})
}
@@ -280,6 +303,29 @@ export function registerBrowserHandlers(trusted: Session) {
updateNormalWindows()
break
}
case 'downloadPause':
case 'downloadResume':
case 'downloadCancel': {
if (browser.privateMode || typeof value !== 'string') break
const item = downloads.get(value)
if (action === 'downloadPause' && item?.getState() === 'progressing') item.pause()
if (action === 'downloadResume' && item?.canResume()) item.resume()
if (action === 'downloadCancel') item?.cancel()
updateNormalWindows()
break
}
case 'showDownload': {
if (browser.privateMode || typeof value !== 'string') break
const item = library().downloads.find((entry) => entry.id === value && entry.state === 'completed')
if (item?.path) shell.showItemInFolder(item.path)
break
}
case 'clearDownloads': {
if (browser.privateMode) break
clearDownloads()
updateNormalWindows()
break
}
case 'openEntry': {
if (browser.privateMode || typeof value !== 'string') break
const { bookmarks, history } = library()