桌面文件搜索小组件
1.支持暗黑、明亮。跟随电脑三种主题模式;同时支持透明背景。
2.支持快捷打开文件。
3.按照文件类型进行分类。


<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>桌面文件</title>
<style>
* { box-sizing: border-box; }
html, body {
width: 100%; height: 100%; margin: 0; overflow: hidden;
background: transparent;
font-family: "Microsoft YaHei", sans-serif;
font-size: 13px;
color: var(--text);
}
body {
--text:#2c3e50; --text2:#6b7a89; --muted:#9aa7b3;
--item-bg:rgba(255,255,255,.92); --item-border:#e3e9ef; --item-border-hover:#c4d2e0;
--input-bg:rgba(255,255,255,.9); --input-border:#d4dbe3;
--btn-bg:rgba(255,255,255,.9); --btn-border:#d4dbe3;
--btn-hover-bg:#f0f5fa; --btn-hover-border:#b3c0cf; --btn-active:#e2ebf4;
--accent:#4a90d9; --accent-hover:#3d80c6; --accent-active:#3470ad;
--tab-active-bg:#e3eefb; --tab-active-color:#2c6cb0; --tab-active-border:#c3daf5;
--err-bg:#fbeceb; --err-border:#f2d4d2; --err-color:#a8413a;
--scroll:#c9d4df; --warn:#b07a28;
--card-border:rgba(44,62,80,.16); --card-bg:rgba(255,255,255,.97);
}
body.dark {
--text:#dbe4ee; --text2:#9fb0c0; --muted:#7a8a99;
--item-bg:rgba(34,41,50,.92); --item-border:#3a4552; --item-border-hover:#4d5b6b;
--input-bg:rgba(34,41,50,.9); --input-border:#414d5b;
--btn-bg:rgba(34,41,50,.9); --btn-border:#414d5b;
--btn-hover-bg:#2c3642; --btn-hover-border:#556679; --btn-active:#26303c;
--accent:#4a90d9; --accent-hover:#5aa2e8; --accent-active:#6cb0ef;
--tab-active-bg:#26405c; --tab-active-color:#8ec2f2; --tab-active-border:#33547a;
--err-bg:#3a2a2a; --err-border:#5c3a3a; --err-color:#f0a5a0;
--scroll:#414d5b; --warn:#e8b45c;
--card-border:rgba(255,255,255,.14); --card-bg:rgba(30,36,44,.97);
}
.app {
display: flex; flex-direction: column; width: 100%; height: 100%;
padding: 10px; gap: 7px;
border: 1px solid var(--card-border); border-radius: 14px;
background: transparent;
box-shadow: 0 4px 16px rgba(0,0,0,.08);
}
body.bg-opaque .app { background: var(--card-bg); }
.head-row { display: flex; align-items: center; gap: 6px; }
.title {
flex: 1; min-width: 0; font-weight: 600; font-size: 13px;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
button {
font-family: inherit; font-size: 13px;
border: 1px solid var(--btn-border); border-radius: 8px;
background: var(--btn-bg); color: var(--text);
cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 4px;
transition: background .15s, border-color .15s, opacity .15s;
}
button:hover:not(:disabled) { background: var(--btn-hover-bg); border-color: var(--btn-hover-border); }
button:active:not(:disabled) { background: var(--btn-active); }
button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
button:disabled { opacity: .45; cursor: not-allowed; }
.icon-btn { flex: none; width: 26px; height: 26px; padding: 0; border-radius: 8px; color: var(--text2); }
.theme-group { display: flex; gap: 3px; flex: none; }
.theme-btn {
width: 26px; height: 24px; padding: 0; border-radius: 7px;
color: var(--muted); background: transparent; border-color: transparent;
}
.theme-btn.active { color: var(--tab-active-color); background: var(--tab-active-bg); border-color: var(--tab-active-border); }
.search-row { display: flex; gap: 6px; }
.search-row input[type="text"] {
flex: 1; min-width: 0; padding: 6px 9px;
border: 1px solid var(--input-border); border-radius: 8px;
background: var(--input-bg); color: var(--text);
font-size: 13px; font-family: inherit; outline: none;
transition: border-color .15s, box-shadow .15s;
}
.search-row input[type="text"]:hover { border-color: var(--btn-hover-border); }
.search-row input[type="text"]:focus { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(74,144,217,.18); }
.search-row input[type="text"]::placeholder { color: var(--muted); }
.clear-search { flex: none; padding: 5px 10px; border-radius: 8px; font-size: 12px; color: var(--text2); }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; }
.tab {
padding: 3px 10px; border-radius: 999px; font-size: 12px;
background: transparent; border: 1px solid transparent; color: var(--text2);
}
.tab.active { background: var(--tab-active-bg); color: var(--tab-active-color); border-color: var(--tab-active-border); font-weight: 600; }
.list {
flex: 1; min-height: 0; overflow-y: auto;
display: flex; flex-direction: column; gap: 4px; padding: 2px;
}
.list::-webkit-scrollbar { width: 6px; }
.list::-webkit-scrollbar-thumb { background: var(--scroll); border-radius: 3px; }
.row {
display: flex; align-items: center; gap: 8px;
padding: 6px 9px;
background: var(--item-bg); border: 1px solid var(--item-border); border-radius: 8px;
cursor: pointer; transition: border-color .15s;
min-width: 0;
}
.row:hover { border-color: var(--item-border-hover); }
.row:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.row .type-badge {
flex: none; min-width: 36px; height: 21px; padding: 0 5px;
border-radius: 6px; background: var(--accent); color: #fff;
font-size: 10px; font-weight: 700; letter-spacing: .5px;
display: inline-flex; align-items: center; justify-content: center;
}
.row .name-wrap { flex: 1; min-width: 0; }
.row .name {
display: block;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.row.is-folder .name { font-weight: 600; }
.row .sub { display: block; font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
.row .meta { flex: none; font-size: 11px; color: var(--muted); white-space: nowrap; }
.empty { flex: 1; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 12px; text-align: center; padding: 12px; }
.status { flex: none; display: flex; align-items: center; gap: 8px; font-size: 11px; color: var(--muted); min-height: 16px; }
.status .grow { flex: 1; }
.status .warn { color: var(--warn); }
.err { flex: none; display: none; padding: 5px 9px; border-radius: 8px; background: var(--err-bg); border: 1px solid var(--err-border); color: var(--err-color); font-size: 12px; word-break: break-all; }
.err.show { display: block; }
</style>
</head>
<body>
<div class="app">
<div class="head-row">
<button class="icon-btn" id="backBtn" title="返回上一级" aria-label="返回上一级">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 5l-7 7 7 7"/></svg>
</button>
<span class="title" id="title">桌面</span>
<div class="theme-group">
<button class="theme-btn" id="bgBtn" title="背景:不透明" aria-label="切换背景透明/不透明">
<svg width="14" height="14" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M5 12h14v5a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2z" fill="currentColor"/></svg>
</button>
<button class="theme-btn" id="themeLight" title="明亮主题" aria-label="明亮主题">
<svg width="14" height="14" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" fill="currentColor"/><path d="M12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>
</button>
<button class="theme-btn" id="themeDark" title="暗色主题" aria-label="暗色主题">
<svg width="14" height="14" viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" fill="currentColor"/></svg>
</button>
<button class="theme-btn" id="themeSystem" title="跟随系统" aria-label="跟随系统">
<svg width="14" height="14" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8 21h8M12 17v4" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>
</button>
</div>
<button class="icon-btn" id="refreshBtn" title="刷新" aria-label="刷新">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 11a8 8 0 1 0-2.3 6.3"/><path d="M20 4v7h-7"/></svg>
</button>
<button class="icon-btn" id="openDesktopBtn" title="在资源管理器中打开桌面" aria-label="在资源管理器中打开桌面">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v6M20 4l-9 9"/><path d="M19 13v6a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h6"/></svg>
</button>
</div>
<div class="search-row">
<input type="text" id="searchInput" placeholder="搜索桌面文件(含子文件夹)…" maxlength="100">
<button class="clear-search" id="clearSearchBtn" title="清除搜索">清除</button>
</div>
<div class="tabs" id="catTabs"></div>
<div class="list" id="list"></div>
<div class="status"><span id="statusText">正在加载…</span><span class="grow"></span><span class="warn" id="warnText"></span></div>
<div class="err" id="errBar"></div>
</div>
<script>
(function () {
var host = window.widgetHost;
var backBtn = document.getElementById('backBtn');
var titleEl = document.getElementById('title');
var refreshBtn = document.getElementById('refreshBtn');
var openDesktopBtn = document.getElementById('openDesktopBtn');
var themeLight = document.getElementById('themeLight');
var themeDark = document.getElementById('themeDark');
var themeSystem = document.getElementById('themeSystem');
var bgBtn = document.getElementById('bgBtn');
var searchInput = document.getElementById('searchInput');
var clearSearchBtn = document.getElementById('clearSearchBtn');
var catTabs = document.getElementById('catTabs');
var list = document.getElementById('list');
var statusText = document.getElementById('statusText');
var warnText = document.getElementById('warnText');
var errBar = document.getElementById('errBar');
/* ---------- 文件类型分类 ---------- */
var CATS = [
{ code: 'all', label: '全部', exts: null },
{ code: 'img', label: '图片', exts: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'ico', 'tif', 'tiff', 'svg'] },
{ code: 'pdf', label: 'PDF', exts: ['pdf'] },
{ code: 'xls', label: 'Excel', exts: ['xls', 'xlsx', 'xlsm', 'csv'] },
{ code: 'doc', label: 'Word', exts: ['doc', 'docx', 'rtf'] },
{ code: 'ppt', label: 'PPT', exts: ['ppt', 'pptx'] },
{ code: 'txt', label: '文本', exts: ['txt', 'md', 'log', 'ini', 'json'] },
{ code: 'zip', label: '压缩包', exts: ['zip', 'rar', '7z', 'tar', 'gz'] },
{ code: 'other', label: '其他', exts: [] }
];
function catByCode(code) {
for (var i = 0; i < CATS.length; i++) if (CATS[i].code === code) return CATS[i];
return CATS[0];
}
function extOf(name) {
var s = String(name || '');
var i = s.lastIndexOf('.');
return i >= 0 ? s.slice(i + 1).toLowerCase() : '';
}
function matchCat(item, cat) {
if (!cat || cat.code === 'all') return true;
if (item.type === 'folder') return false; // 分类视图只看文件
var ext = extOf(item.name);
if (cat.code === 'other') {
for (var i = 1; i < CATS.length - 1; i++) {
if (CATS[i].exts.indexOf(ext) >= 0) return false;
}
return true;
}
return cat.exts.indexOf(ext) >= 0;
}
var desktopPath = null;
var currentPath = null;
var cat = 'all'; // 当前文件类型分类
var themeMode = 'system'; // light | dark | system
var searchToken = 0;
var searchTimer = null;
function showError(err) {
var msg = String((err && err.message) || err || '未知错误');
errBar.textContent = '出错了:' + msg;
errBar.title = msg;
errBar.classList.add('show');
}
function clearError() { errBar.classList.remove('show'); errBar.textContent = ''; errBar.title = ''; }
function setStatus(t) { statusText.textContent = t; }
function setWarn(t) { warnText.textContent = t || ''; }
async function readState(key, def) {
if (!host || !host.state) return def;
try { return await host.state.read(key, def); } catch (e) { showError(e); return def; }
}
async function writeState(key, value) {
if (!host || !host.state) return;
try { await host.state.write(key, value); } catch (e) { showError(e); }
}
/* ---------- 三套主题(与待办清单一致) ---------- */
var mql = (typeof window.matchMedia === 'function') ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function applyTheme() {
var dark = themeMode === 'dark' || (themeMode === 'system' && mql && mql.matches);
document.body.classList.toggle('dark', dark);
themeLight.classList.toggle('active', themeMode === 'light');
themeDark.classList.toggle('active', themeMode === 'dark');
themeSystem.classList.toggle('active', themeMode === 'system');
}
function setTheme(mode) {
themeMode = mode;
void writeState('theme', mode);
applyTheme();
}
if (mql && typeof mql.addEventListener === 'function') {
mql.addEventListener('change', function () { if (themeMode === 'system') applyTheme(); });
}
themeLight.addEventListener('click', function () { setTheme('light'); });
themeDark.addEventListener('click', function () { setTheme('dark'); });
themeSystem.addEventListener('click', function () { setTheme('system'); });
/* ---------- 背景透明 / 不透明 ---------- */
var opaque = true; // 默认不透明,避免与桌面内容混在一起
function applyBg() {
document.body.classList.toggle('bg-opaque', opaque);
bgBtn.classList.toggle('active', opaque);
bgBtn.title = opaque ? '背景:不透明(点击切换为透明)' : '背景:透明(点击切换为不透明)';
}
function setOpaque(v) {
opaque = !!v;
void writeState('opaque', opaque);
applyBg();
}
bgBtn.addEventListener('click', function () { setOpaque(!opaque); });
/* ---------- 分类 Tab ---------- */
function renderTabs() {
catTabs.textContent = '';
CATS.forEach(function (c) {
var b = document.createElement('button');
b.className = 'tab' + (cat === c.code ? ' active' : '');
b.textContent = c.label;
b.addEventListener('click', function () {
cat = c.code;
void writeState('cat', cat);
renderTabs();
rerunView();
});
catTabs.appendChild(b);
});
}
function fmtSize(bytes) {
if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) return '';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
if (bytes < 1024 * 1024 * 1024) return (bytes / 1024 / 1024).toFixed(1) + ' MB';
return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}
function fmtDate(ts) {
if (typeof ts !== 'number' || !ts) return '';
try {
var d = new Date(ts);
function p(n) { return (n < 10 ? '0' : '') + n; }
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
} catch (e) { return ''; }
}
function baseName(p) {
if (typeof p !== 'string' || !p) return '';
var parts = p.replace(/[\\/]+$/, '').split(/[\\/]/);
return parts[parts.length - 1] || p;
}
function relPath(p) {
if (typeof p !== 'string') return '';
if (desktopPath && p.toLowerCase().indexOf(desktopPath.toLowerCase()) === 0) {
var rel = p.slice(desktopPath.length).replace(/^[\\/]+/, '');
return rel || p;
}
return p;
}
function sortItems(items) {
return items.slice().sort(function (a, b) {
var fa = a.type === 'folder' ? 0 : 1;
var fb = b.type === 'folder' ? 0 : 1;
if (fa !== fb) return fa - fb;
return String(a.name || '').localeCompare(String(b.name || ''), 'zh-Hans-CN');
});
}
function filterByCat(items) {
var c = catByCode(cat);
if (c.code === 'all') return items;
return items.filter(function (it) { return matchCat(it, c); });
}
function badgeFor(item) {
if (item.type === 'folder') return 'DIR';
var ext = extOf(item.name);
if (!ext) return 'FILE';
return ext.slice(0, 4).toUpperCase();
}
function buildRow(item, opts) {
var isFolder = item.type === 'folder';
var row = document.createElement('div');
row.className = 'row' + (isFolder ? ' is-folder' : '');
row.tabIndex = 0;
row.title = (isFolder ? '双击进入:' : '双击打开:') + item.path;
var badge = document.createElement('span');
badge.className = 'type-badge';
badge.textContent = badgeFor(item);
var nameWrap = document.createElement('span');
nameWrap.className = 'name-wrap';
var name = document.createElement('span');
name.className = 'name';
name.textContent = item.name || baseName(item.path);
nameWrap.appendChild(name);
if (opts && opts.showSub) {
var sub = document.createElement('span');
sub.className = 'sub';
sub.textContent = relPath(item.path);
nameWrap.appendChild(sub);
}
var meta = document.createElement('span');
meta.className = 'meta';
if (isFolder) {
meta.textContent = fmtDate(item.modifiedAt) || '文件夹';
} else {
var s = fmtSize(item.size);
meta.textContent = [s, fmtDate(item.modifiedAt)].filter(Boolean).join(' · ') || '';
}
row.appendChild(badge);
row.appendChild(nameWrap);
row.appendChild(meta);
function activate() {
if (isFolder && !opts.searchMode) {
navigate(item.path);
} else {
openPath(item.path);
}
}
row.addEventListener('dblclick', activate);
row.addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); activate(); }
});
return row;
}
function renderList(items, opts) {
list.textContent = '';
if (!items.length) {
var empty = document.createElement('div');
empty.className = 'empty';
empty.textContent = (opts && opts.emptyText) || '这里什么都没有';
list.appendChild(empty);
return;
}
items.forEach(function (it) { list.appendChild(buildRow(it, opts || {})); });
}
function updateHead() {
titleEl.textContent = currentPath === desktopPath ? '桌面' : baseName(currentPath);
backBtn.disabled = !currentPath || !desktopPath || currentPath === desktopPath;
}
function rerunView() {
if (searchInput.value.trim()) { doSearch(); } else { listDir(currentPath || desktopPath); }
}
async function listDir(path) {
clearError();
setWarn('');
setStatus('正在加载…');
updateHead();
try {
var res = await host.fs.list({
path: path,
includeFiles: true,
includeFolders: true,
includeHidden: false,
maxItems: 3000
});
var items = filterByCat(sortItems((res && res.items) || []));
var emptyText = '桌面上没有文件';
if (cat !== 'all') emptyText = '该分类下没有文件';
renderList(items, { emptyText: emptyText });
setStatus(items.length + ' 项' + (res && res.truncated ? '(结果不完整)' : ''));
if (res && res.truncated) setWarn('文件过多,仅显示前 ' + items.length + ' 项');
} catch (e) {
renderList([], { emptyText: '加载失败' });
setStatus('');
showError(e);
}
}
async function doSearch() {
var kw = searchInput.value.trim().toLowerCase();
if (!kw) { listDir(currentPath); return; }
var token = ++searchToken;
clearError();
setWarn('');
setStatus('正在搜索…');
updateHead();
try {
var res = await host.fs.list({
path: desktopPath,
recursive: true,
includeFiles: true,
includeFolders: false,
includeHidden: false,
maxItems: 5000
});
if (token !== searchToken) return;
var c = catByCode(cat);
var all = (res && res.items) || [];
var hits = all.filter(function (it) {
return String(it.name || '').toLowerCase().indexOf(kw) >= 0 && matchCat(it, c);
});
hits = sortItems(hits).slice(0, 500);
renderList(hits, { searchMode: true, showSub: true, emptyText: '没有找到匹配“' + searchInput.value.trim() + '”的文件' });
var extra = (res && res.truncated) ? '(桌面文件过多,结果可能不完整)' : '';
setStatus('找到 ' + hits.length + ' 项' + extra);
if (res && res.truncated) setWarn('桌面文件过多,仅扫描了前 ' + all.length + ' 个文件');
} catch (e) {
if (token !== searchToken) return;
renderList([], { emptyText: '搜索失败' });
setStatus('');
showError(e);
}
}
function navigate(path) {
currentPath = path;
searchInput.value = '';
void writeState('path', path);
listDir(path);
}
async function openPath(p) {
clearError();
try {
await host.path.open({ path: p, hideAfterOpen: true });
} catch (e) {
showError(e);
}
}
backBtn.addEventListener('click', function () {
if (!currentPath || currentPath === desktopPath) return;
var idx = currentPath.replace(/[\\/]+$/, '').lastIndexOf('\\');
var parent = idx > desktopPath.length ? currentPath.slice(0, idx + 1) : desktopPath;
navigate(parent);
});
refreshBtn.addEventListener('click', rerunView);
openDesktopBtn.addEventListener('click', function () {
if (desktopPath) openPath(desktopPath);
});
clearSearchBtn.addEventListener('click', function () {
searchInput.value = '';
listDir(currentPath || desktopPath);
});
searchInput.addEventListener('input', function () {
if (searchTimer) clearTimeout(searchTimer);
searchTimer = setTimeout(doSearch, 250);
});
searchInput.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
if (searchTimer) clearTimeout(searchTimer);
doSearch();
}
});
(async function () {
try {
var th = await readState('theme', 'system');
themeMode = ['light', 'dark', 'system'].indexOf(th) >= 0 ? th : 'system';
applyTheme();
var ob = await readState('opaque', true);
opaque = !!ob;
applyBg();
var savedCat = await readState('cat', 'all');
cat = catByCode(savedCat).code;
renderTabs();
if (!host || !host.fs) {
setStatus('');
renderList([], { emptyText: '宿主接口不可用,无法读取桌面(预览环境属正常现象)' });
return;
}
var kf = await host.fs.getKnownFolders();
desktopPath = kf && kf.desktop;
if (!desktopPath) throw new Error('无法获取桌面目录路径');
var saved = await readState('path', desktopPath);
currentPath = (typeof saved === 'string' && saved.toLowerCase().indexOf(desktopPath.toLowerCase()) === 0)
? saved : desktopPath;
await listDir(currentPath);
} catch (e) {
applyTheme();
applyBg();
renderTabs();
setStatus('');
renderList([], { emptyText: '初始化失败' });
showError(e);
}
})();
})();
</script>
</body>
</html>