@@ -438,6 +513,9 @@
let seenKeys = new Set();
let folderCount = 0;
let fileCount = 0;
+ // 已加载的完整列表。筛选只看这里,规则与 src/utils/nameFilter.js 一致。
+ let loadedFiles = [];
+ let nameFilter = '';
const moreEl = document.createElement('div');
moreEl.className = 'load-more';
moreEl.style.display = 'none';
@@ -471,7 +549,18 @@
}
function fileKey(file) {
- return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || ''}`;
+ return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || file.id || ''}`;
+ }
+
+ function normalizeQuery(keyword) {
+ return String(keyword == null ? '' : keyword).trim().toLowerCase();
+ }
+
+ function filterByFileName(list, keyword) {
+ const rows = list || [];
+ const query = normalizeQuery(keyword);
+ if (!query) return rows.slice();
+ return rows.filter(file => String((file && file.fileName) || '').toLowerCase().includes(query));
}
function renderMore() {
@@ -520,7 +609,8 @@
if (typeof IntersectionObserver !== 'undefined') {
new IntersectionObserver(entries => {
- if (more && !more.loading && !more.error && entries.some(e => e.isIntersecting)) loadMore();
+ // 有关键字时不自动翻页,避免筛选结果变短后把后续页一次拉完
+ if (more && !more.loading && !more.error && !normalizeQuery(nameFilter) && entries.some(e => e.isIntersecting)) loadMore();
}).observe(moreEl);
}
@@ -534,6 +624,13 @@
// 初始化
document.addEventListener('DOMContentLoaded', () => {
fileGridEl.insertAdjacentElement('afterend', moreEl);
+ const nameInput = document.getElementById('name-filter');
+ if (nameInput) {
+ nameInput.addEventListener('input', () => {
+ nameFilter = nameInput.value;
+ renderLoadedFiles();
+ });
+ }
renderBreadcrumb();
fetchFileList(currentDir.url);
@@ -605,37 +702,50 @@
}
}
- // 渲染文件列表
- function renderFileList(files, append = false) {
- if (!append) {
- fileGridEl.innerHTML = '';
- seenKeys = new Set();
- folderCount = 0;
- fileCount = 0;
+ function updateFilterHint(matchedCount) {
+ const hint = document.getElementById('filter-hint');
+ if (!hint) return;
+ const query = normalizeQuery(nameFilter);
+ if (!query) {
+ hint.hidden = true;
+ hint.textContent = '';
+ return;
}
-
- if (!append && (!files || files.length === 0)) {
- fileGridEl.innerHTML = `
-
+ hint.hidden = false;
+ hint.textContent = `仅筛选已加载的 ${loadedFiles.length} 项,匹配 ${matchedCount} 项`;
+ }
+
+ // 按当前关键字重绘已加载列表。加载更多按钮在网格外面,无匹配时仍然在。
+ function renderLoadedFiles() {
+ const visible = filterByFileName(loadedFiles, nameFilter);
+ fileGridEl.innerHTML = '';
+ folderCount = 0;
+ fileCount = 0;
+
+ if (!visible.length) {
+ const filtering = normalizeQuery(nameFilter) && loadedFiles.length;
+ fileGridEl.innerHTML = filtering
+ ? `
- `;
+
`;
folderCountEl.textContent = '0';
fileCountEl.textContent = '0';
+ updateFilterHint(0);
return;
}
-
- (files || []).forEach(file => {
- const key = fileKey(file);
- if (seenKeys.has(key)) return;
- seenKeys.add(key);
+
+ visible.forEach(file => {
const item = document.createElement('div');
const metaText = fileMetaText(file);
-
+
if (file.fileType === 'folder') {
- // 文件夹
item.className = 'item folder';
item.innerHTML = `
+
+
`
+ : `没有匹配的文件
+换个关键字,或加载更多后再筛
+此文件夹为空
暂无文件或文件夹
-
@@ -645,16 +755,12 @@
${metaText ? `
${metaText}
` : ''}
`;
folderCount++;
-
- // 添加点击事件
item.addEventListener('click', () => {
enterFolder(file);
});
} else {
- // 文件
const fileExt = getFileExtension(file.fileName);
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
-
item.className = `item ${fileTypeInfo.type}`;
item.innerHTML = `
@@ -664,19 +770,34 @@
${metaText ? `
${metaText}
` : ''}
`;
fileCount++;
-
- // 添加点击事件
item.addEventListener('click', () => {
handleFileClick(file);
});
}
-
+
fileGridEl.appendChild(item);
});
-
- // 更新统计信息
+
folderCountEl.textContent = folderCount;
fileCountEl.textContent = fileCount;
+ updateFilterHint(visible.length);
+ }
+
+ // 渲染文件列表
+ function renderFileList(files, append = false) {
+ if (!append) {
+ seenKeys = new Set();
+ loadedFiles = [];
+ }
+
+ (files || []).forEach(file => {
+ const key = fileKey(file);
+ if (seenKeys.has(key)) return;
+ seenKeys.add(key);
+ loadedFiles.push(file);
+ });
+
+ renderLoadedFiles();
}
// 获取文件扩展名
diff --git a/web-front/src/components/DirectoryTree.vue b/web-front/src/components/DirectoryTree.vue
index a718488..fc9e3df 100644
--- a/web-front/src/components/DirectoryTree.vue
+++ b/web-front/src/components/DirectoryTree.vue
@@ -1,6 +1,20 @@
+
-
+
+
+
+
+
+
仅筛选已加载的 {{ loadedCount }} 项,匹配 {{ matchedCount }} 项
+
@@ -18,7 +32,7 @@
-
-
此文件夹为空
-暂无文件或文件夹
+
+
+
{{ nameQuery && currentFileList.length ? '没有匹配的文件' : '此文件夹为空' }}
+{{ nameQuery && currentFileList.length ? '换个关键字,或加载更多后再筛' : '暂无文件或文件夹' }}
@@ -126,6 +140,11 @@
+
+
+
没有匹配的文件
+换个关键字,或加载更多后再筛
+
+
+ 全选
+ 取消全选
+
已勾选 {{ selectedFiles.length }} 个文件
+
@@ -366,6 +394,10 @@
+
+
没有匹配的文件
+换个关键字,或加载更多后再筛
+
+
浏览器下载
@@ -462,16 +494,26 @@ import DownloadDialog from '@/components/DownloadDialog.vue'
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
import batchTreeCollect from '@/utils/batchTreeCollect'
import folderPaging from '@/utils/folderPaging'
+import nameFilter from '@/utils/nameFilter'
import { openNoReferrer } from '@/utils/openNoReferrer'
const {
DEFAULT_BATCH_MAX_DEPTH,
getTreeNodeId,
normalizeTreeItem,
+ fileIdentity,
uniqueFiles,
collectFolderFiles
} = batchTreeCollect
const { toPageUrl, readPage, appendUnique, nextState, makeMoreNode, isMoreNode } = folderPaging
+const {
+ matchesFileName,
+ filterByFileName,
+ filterSummary,
+ selectMatching,
+ deselectMatching,
+ collectLoadedNodes
+} = nameFilter
export default {
name: 'DirectoryTree',
@@ -514,6 +556,9 @@ export default {
loading: false,
pathStack: [{ name: '全部文件', url: '' }],
currentFileList: [],
+ nameFilter: '',
+ rootLoadedFiles: [],
+ treeLoadVersion: 0,
// 当前窗格目录的下一页状态;null 表示已全部加载
paneMore: null,
rootMore: null,
@@ -549,11 +594,26 @@ export default {
}
},
computed: {
+ nameQuery() {
+ return String(this.nameFilter || '').trim()
+ },
+ visibleFileList() {
+ return filterByFileName(this.currentFileList, this.nameFilter)
+ },
+ loadedCount() {
+ return filterSummary(this.entriesForCount(), this.nameFilter).loaded
+ },
+ matchedCount() {
+ return filterSummary(this.entriesForCount(), this.nameFilter).matched
+ },
+ treeFilterEmpty() {
+ return this.viewMode === 'tree' && !!this.nameQuery && this.matchedCount === 0 && this.loadedCount > 0
+ },
folderCount() {
- return this.currentFileList.filter(file => file.fileType === 'folder').length
+ return this.visibleFileList.filter(file => file.fileType === 'folder').length
},
fileCount() {
- return this.currentFileList.filter(file => file.fileType !== 'folder').length
+ return this.visibleFileList.filter(file => file.fileType !== 'folder').length
},
batchProgressPercent() {
if (this.batchProgress.total === 0) return 0
@@ -591,8 +651,15 @@ export default {
paneMore() {
this.$nextTick(() => this.observeLoadMore())
},
- viewMode() {
- this.$nextTick(() => this.observeLoadMore())
+ viewMode(next, prev) {
+ if (prev === 'tree' && next !== 'tree') this.snapshotTreeRoot()
+ this.$nextTick(() => {
+ this.observeLoadMore()
+ if (next === 'tree') this.applyTreeFilter()
+ })
+ },
+ nameFilter() {
+ this.$nextTick(() => this.applyTreeFilter())
},
fileList: {
immediate: true,
@@ -600,23 +667,12 @@ export default {
this.rootExtra = []
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
this.treeMoreFolders = new Set()
- const children = (newList || []).map(item => normalizeTreeItem(item))
- if (this.rootMore) {
- children.push(makeMoreNode('root', { ...this.rootMore }))
- this.treeMoreFolders.add('root')
- }
- // 根节点children为当前目录下所有文件/文件夹
- this.treeData = [
- {
- id: 'root',
- fileName: '全部文件',
- fileType: 'folder',
- children,
- isLeaf: false
- }
- ]
+ this.rootLoadedFiles = (newList || []).slice()
+ this.nameFilter = ''
+ this.treeLoadVersion += 1
+ this.syncTreeDataChildren()
this.pathStack = [{ name: '全部文件', url: '' }]
- this.currentFileList = newList
+ this.currentFileList = newList || []
this.paneMore = this.rootMore
}
}
@@ -624,6 +680,7 @@ export default {
created() {
this.treeMoreFolders = this.treeMoreFolders || new Set()
this._paneLoadSeq = 0
+ this._syncingChecks = false
this.resetTreeCollectState()
},
methods: {
@@ -653,10 +710,106 @@ export default {
}
return this.withAuth(`${baseUrl}?${params.toString()}`)
},
+ entriesForCount() {
+ // 树节点不是响应式数据,翻页后靠 treeLoadVersion 让「已加载 / 匹配」重新计算
+ void this.treeLoadVersion
+ return this.activeLoadedEntries()
+ },
+ activeLoadedEntries() {
+ if (this.viewMode !== 'tree') return this.currentFileList || []
+ const tree = this.getFileTree()
+ const storeRoot = tree && tree.store ? tree.store.root : null
+ if (storeRoot) return collectLoadedNodes(storeRoot)
+ return this.rootLoadedFiles || []
+ },
+ // 加载更多占位和虚拟根始终留下,否则无匹配时无法继续翻页
+ filterTreeNode(value, data) {
+ if (!data || data.id === 'root') return false
+ if (isMoreNode(data) || !value) return true
+ return matchesFileName(data, value)
+ },
+ displayRootNodes() {
+ const nodes = (this.rootLoadedFiles || []).map(item => normalizeTreeItem(item))
+ if (this.rootMore) nodes.push(makeMoreNode('root', { ...this.rootMore }))
+ return nodes
+ },
+ revealFilter() {
+ const tree = this.getFileTree()
+ if (tree && typeof tree.filter === 'function') tree.filter(this.nameQuery || '')
+ },
+ applyTreeFilter() {
+ this.revealFilter()
+ this.syncChecksFromSelection()
+ },
+ syncTreeDataChildren() {
+ const children = this.displayRootNodes()
+ if (this.rootMore) {
+ if (this.treeMoreFolders) this.treeMoreFolders.add('root')
+ } else if (this.treeMoreFolders) {
+ this.treeMoreFolders.delete('root')
+ }
+ // 树的数据就是当前已加载列表,不包一层「全部文件」,避免懒加载把根节点再插进列表
+ this.treeData = children
+ },
+ snapshotTreeRoot() {
+ const tree = this.getFileTree()
+ const root = tree && tree.store ? tree.store.root : null
+ if (!root) return
+ const files = []
+ let more = null
+ let sawMore = false
+ const pushNode = (child) => {
+ if (!child || !child.data || isMoreNode(child.data)) {
+ if (child && child.data && isMoreNode(child.data)) {
+ sawMore = true
+ more = child.data.paging || null
+ }
+ return
+ }
+ if (child.data.id === 'root') {
+ for (const grand of child.childNodes || []) pushNode(grand)
+ return
+ }
+ files.push(child.data)
+ }
+ for (const child of root.childNodes || []) pushNode(child)
+ if (files.length || sawMore) {
+ this.rootLoadedFiles = appendUnique([], files)
+ this.rootMore = more
+ }
+ if (this.pathStack.length <= 1) {
+ this.currentFileList = (this.rootLoadedFiles || []).slice()
+ this.paneMore = this.rootMore
+ ? { ...this.rootMore, loading: false, error: this.rootMore.error || '' }
+ : null
+ }
+ this.$nextTick(() => {
+ if (this.viewMode !== 'tree') this.syncTreeDataChildren()
+ })
+ },
+ syncChecksFromSelection() {
+ const tree = this.getFileTree()
+ if (!tree || !this.batchMode || typeof tree.setChecked !== 'function') return
+ const root = tree.store ? tree.store.root : null
+ if (!root) return
+ this._syncingChecks = true
+ try {
+ const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
+ for (const file of collectLoadedNodes(root)) {
+ if (!this.isDownloadableFile(file)) continue
+ if (this.nameQuery && !matchesFileName(file, this.nameQuery)) continue
+ tree.setChecked(getTreeNodeId(file), selectedKeys.has(fileIdentity(file)), false)
+ }
+ } finally {
+ this._syncingChecks = false
+ }
+ },
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
loadNode(node, resolve) {
if (node.level === 0) {
- resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
+ resolve(this.displayRootNodes())
+ this.treeLoadVersion += 1
+ this.$nextTick(() => this.revealFilter())
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
const listUrl = this.withAuth(node.data.parserUrl)
const pageUrl = toPageUrl(listUrl, 1)
@@ -673,6 +826,8 @@ export default {
this.treeMoreFolders.delete(folderKey)
}
resolve(children)
+ this.treeLoadVersion += 1
+ this.$nextTick(() => this.revealFilter())
} else {
this.$message.error(res.data.msg || '获取子节点失败')
resolve([])
@@ -702,7 +857,8 @@ export default {
if (!this._moreObserver) {
this._moreObserver = new IntersectionObserver((entries) => {
const state = this.paneMore
- if (!state || state.loading || state.error || this.viewMode !== 'pane') return
+ // 有关键字时列表变短,哨兵会露出来;这时不自动翻页,避免把未加载页一次拉完
+ if (!state || state.loading || state.error || this.viewMode !== 'pane' || this.nameQuery) return
if (entries.some(e => e.isIntersecting)) this.loadMorePane()
})
}
@@ -735,8 +891,11 @@ export default {
if (this.pathStack.length === 1) {
this.rootExtra = appendUnique(this.rootExtra, added)
this.rootMore = next
+ this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, added)
+ if (this.viewMode !== 'tree') this.syncTreeDataChildren()
}
this.paneMore = next
+ this.treeLoadVersion += 1
} catch (error) {
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
@@ -753,25 +912,53 @@ export default {
const parent = moreNode?.parent
if (!parent) return
state.loading = true
+ state.error = ''
try {
const page = await this.fetchPage(state)
const parentKey = getTreeNodeId(parent.data) || 'root'
- const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
- tree.remove(moreNode)
- for (const item of page.list.map(normalizeTreeItem)) {
- if (existing.has(item.id)) continue
- existing.add(item.id)
- tree.append(item, parent)
- }
+ const parentIsRoot = parent.level === 0
const next = nextState(state.listUrl, page)
- if (next) {
- tree.append(makeMoreNode(parentKey, next), parent)
+ if (parentIsRoot) {
+ // 换一份根数据,而不是 append 到 el-tree 正在监听的数组上,避免根节点被插进两遍
+ this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, page.list)
+ this.rootMore = next
+ if (next) this.treeMoreFolders.add('root')
+ else this.treeMoreFolders.delete('root')
+ this.treeData = this.displayRootNodes()
} else {
- this.treeMoreFolders.delete(parentKey)
+ const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
+ const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
+ this._syncingChecks = true
+ try {
+ tree.remove(moreNode)
+ for (const item of page.list.map(normalizeTreeItem)) {
+ if (existing.has(item.id)) continue
+ existing.add(item.id)
+ tree.append(item, parent)
+ if (this.isDownloadableFile(item) && typeof tree.setChecked === 'function') {
+ tree.setChecked(item.id, selectedKeys.has(fileIdentity(item)), false)
+ }
+ }
+ if (next) {
+ tree.append(makeMoreNode(parentKey, next), parent)
+ this.treeMoreFolders.add(parentKey)
+ } else {
+ this.treeMoreFolders.delete(parentKey)
+ }
+ } finally {
+ this._syncingChecks = false
+ }
}
+ state.loading = false
+ this.treeLoadVersion += 1
+ this.$nextTick(() => {
+ this.revealFilter()
+ this.syncChecksFromSelection()
+ })
} catch (error) {
state.loading = false
- this.$message.error(`${error.response?.data?.msg || error.message || '加载下一页失败'},可再次点击「加载更多」重试`)
+ state.error = error.response?.data?.msg || error.message || '加载下一页失败'
+ this.$message.error(`${state.error},可再次点击「加载更多」重试`)
}
},
// 处理文件点击
@@ -1243,7 +1430,21 @@ export default {
const fromTree = tree
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
: []
- this.selectedFiles = uniqueFiles([...fromTree, ...extraFiles])
+ const visibleKeys = new Set(
+ filterByFileName(this.activeLoadedEntries(), this.nameFilter)
+ .filter(file => this.isDownloadableFile(file))
+ .map(fileIdentity)
+ )
+ const extraKeys = new Set((extraFiles || []).map(fileIdentity))
+ const kept = this.selectedFiles.filter(file => {
+ const key = fileIdentity(file)
+ return !visibleKeys.has(key) && !extraKeys.has(key)
+ })
+ const checkedVisible = fromTree.filter(file => {
+ const key = fileIdentity(file)
+ return visibleKeys.has(key) || extraKeys.has(key)
+ })
+ this.selectedFiles = uniqueFiles([...kept, ...checkedVisible, ...(extraFiles || [])])
},
enqueueFolderCollect(folderData) {
const key = getTreeNodeId(folderData)
@@ -1302,11 +1503,13 @@ export default {
}
},
isFileSelected(file) {
- return this.selectedFiles.some(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
+ const key = fileIdentity(file)
+ return this.selectedFiles.some(item => fileIdentity(item) === key)
},
toggleFileSelect(file) {
- if (file.fileType === 'folder') return
- const idx = this.selectedFiles.findIndex(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
+ if (!file || file.fileType === 'folder' || isMoreNode(file)) return
+ const key = fileIdentity(file)
+ const idx = this.selectedFiles.findIndex(item => fileIdentity(item) === key)
if (idx >= 0) {
this.selectedFiles.splice(idx, 1)
} else {
@@ -1323,16 +1526,32 @@ export default {
this.toggleFileSelect(file)
},
selectAll() {
- this.selectedFiles = this.currentFileList.filter(f => this.isDownloadableFile(f))
- if (this.paneMore) {
- this.$message.warning(`仅选中已加载的 ${this.selectedFiles.length} 个文件,当前目录还有未加载的分页`)
+ const loaded = this.activeLoadedEntries()
+ this.selectedFiles = selectMatching(
+ this.selectedFiles,
+ loaded,
+ this.nameFilter,
+ file => this.isDownloadableFile(file)
+ )
+ const hasMore = this.viewMode === 'tree'
+ ? !!(this.rootMore || (this.treeMoreFolders && this.treeMoreFolders.size))
+ : !!this.paneMore
+ if (hasMore) {
+ this.$message.warning('仅选中已加载且匹配筛选的文件,未继续拉取后续分页')
}
+ this.$nextTick(() => this.syncChecksFromSelection())
},
deselectAll() {
- this.selectedFiles = []
+ this.selectedFiles = deselectMatching(
+ this.selectedFiles,
+ this.activeLoadedEntries(),
+ this.nameFilter,
+ file => this.isDownloadableFile(file)
+ )
+ this.$nextTick(() => this.syncChecksFromSelection())
},
onTreeCheckChange() {
- if (!this.batchMode || this._treeCollecting) return
+ if (!this.batchMode || this._treeCollecting || this._syncingChecks) return
this.syncSelectedFilesFromTree()
},
extractTypeParam(file) {
@@ -1522,6 +1741,56 @@ html, body, #app, .main-container, .directory-tree, .content-card {
border: 1px solid #404040;
}
+.dir-filter-bar {
+ display: flex;
+ align-items: center;
+ gap: 10px 14px;
+ flex-wrap: wrap;
+ padding: 10px 12px;
+ background: #fff;
+ border-bottom: 1px solid #eaeaea;
+}
+
+.dark-theme .dir-filter-bar {
+ background: #2d2d2d;
+ border-bottom-color: #404040;
+}
+
+.dir-name-filter {
+ flex: 1 1 220px;
+ max-width: 420px;
+ min-width: 0;
+ height: auto;
+}
+
+.dir-name-filter .el-input__wrapper {
+ min-height: 36px;
+}
+
+.dir-filter-hint {
+ margin: 0;
+ flex: 1 1 200px;
+ min-width: 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: #909399;
+}
+
+.dark-theme .dir-filter-hint {
+ color: #bdc3c7;
+}
+
+.tree-filter-empty {
+ padding: 16px 8px 8px;
+}
+
+.tree-select-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+
.breadcrumb {
background: #f8f9fa;
padding: 16px 24px;
@@ -2354,6 +2623,27 @@ html, body, #app, .main-container, .directory-tree, .content-card {
}
@media (max-width: 768px) {
+ .dir-filter-bar {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 6px;
+ padding: 8px 10px;
+ }
+ .dir-name-filter {
+ flex: 0 0 auto;
+ max-width: none;
+ width: 100%;
+ height: auto;
+ }
+ .dir-name-filter .el-input__wrapper {
+ min-height: 40px;
+ }
+ .dir-filter-hint {
+ flex: none;
+ }
+ .tree-select-row .el-button {
+ flex: 1 1 0;
+ }
.file-grid {
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
gap: 8px;
diff --git a/web-front/src/utils/nameFilter.js b/web-front/src/utils/nameFilter.js
new file mode 100644
index 0000000..1ba5701
--- /dev/null
+++ b/web-front/src/utils/nameFilter.js
@@ -0,0 +1,155 @@
+/**
+ * 目录文件名筛选与批量勾选范围。
+ *
+ * 只处理已经加载的行,不发起下一页请求。分页仍由 folderPaging 的
+ * nextCursor / pageCursor 推进;这里只决定新页里哪些行可见、哪些会被全选。
+ */
+const { fileIdentity, uniqueFiles } = require('./batchTreeCollect')
+const { appendUnique, nextState } = require('./folderPaging')
+
+function normalizeQuery(keyword) {
+ return String(keyword == null ? '' : keyword).trim().toLowerCase()
+}
+
+function matchesFileName(file, keyword) {
+ const query = normalizeQuery(keyword)
+ if (!query) return true
+ return String((file && file.fileName) || '').toLowerCase().includes(query)
+}
+
+/** 空关键字返回副本,不清空调用方持有的已加载数组。 */
+function filterByFileName(list, keyword) {
+ const rows = list || []
+ const query = normalizeQuery(keyword)
+ if (!query) return rows.slice()
+ return rows.filter(file => matchesFileName(file, keyword))
+}
+
+function isSelectableFile(file) {
+ return !!(
+ file
+ && file.parserUrl
+ && file.fileType !== 'folder'
+ && file.fileType !== 'url'
+ && file.fileType !== 'more'
+ )
+}
+
+function countableEntries(list) {
+ return (list || []).filter(file => file && file.fileType !== 'more' && file.id !== 'root')
+}
+
+function filterSummary(loaded, keyword) {
+ const rows = countableEntries(loaded)
+ const matched = filterByFileName(rows, keyword)
+ return {
+ loaded: rows.length,
+ matched: matched.length,
+ text: `仅筛选已加载的 ${rows.length} 项,匹配 ${matched.length} 项`
+ }
+}
+
+/**
+ * 全选:只并入当前关键字命中的已加载可选文件。
+ * 不在这份可见集合里的原选择保留,隐藏项不会被加进来。
+ */
+function selectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
+ const visible = filterByFileName(loaded, keyword).filter(file => isSelectable(file))
+ const visibleKeys = new Set(visible.map(fileIdentity))
+ const kept = (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
+ return uniqueFiles(kept.concat(visible))
+}
+
+/** 取消全选:只移出当前可见可选文件,范围外的选择不动。 */
+function deselectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
+ const visibleKeys = new Set(
+ filterByFileName(loaded, keyword)
+ .filter(file => isSelectable(file))
+ .map(fileIdentity)
+ )
+ return (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
+}
+
+function toggleSelected(selected, file, isSelectable = isSelectableFile) {
+ const list = (selected || []).slice()
+ if (!isSelectable(file)) return list
+ const key = fileIdentity(file)
+ const index = list.findIndex(item => fileIdentity(item) === key)
+ if (index >= 0) {
+ list.splice(index, 1)
+ return list
+ }
+ list.push(file)
+ return list
+}
+
+function isSelected(selected, file) {
+ const key = fileIdentity(file)
+ return (selected || []).some(item => fileIdentity(item) === key)
+}
+
+/**
+ * 已加载树节点。未展开的文件夹不往下走,因此不会把未请求的子项算进全选范围。
+ * 「加载更多」占位节点跳过。
+ */
+function collectLoadedNodes(node) {
+ const out = []
+ for (const child of (node && node.childNodes) || []) {
+ const data = child && child.data
+ if (!data || data.fileType === 'more') continue
+ out.push(data)
+ if (child.loaded) {
+ out.push(...collectLoadedNodes(child))
+ }
+ }
+ return out
+}
+
+/**
+ * 用目录分页的 nextCursor 追加一页。
+ * 已有选择原样保留:新页即使命中关键字也不会被静默勾上。
+ */
+function applyCursorPage(state, page) {
+ const loaded = appendUnique(state.loaded, (page && page.list) || [])
+ const listUrl = (state.more && state.more.listUrl) || state.listUrl
+ return {
+ keyword: state.keyword,
+ view: state.view,
+ loaded,
+ selected: (state.selected || []).slice(),
+ listUrl,
+ more: nextState(listUrl, page)
+ }
+}
+
+function switchView(state, view) {
+ return {
+ ...state,
+ view,
+ keyword: state.keyword,
+ selected: (state.selected || []).slice()
+ }
+}
+
+function clearKeyword(state) {
+ return {
+ ...state,
+ keyword: ''
+ }
+}
+
+module.exports = {
+ normalizeQuery,
+ matchesFileName,
+ filterByFileName,
+ isSelectableFile,
+ filterSummary,
+ selectMatching,
+ deselectMatching,
+ toggleSelected,
+ isSelected,
+ collectLoadedNodes,
+ applyCursorPage,
+ switchView,
+ clearKeyword
+}
diff --git a/web-front/src/utils/nameFilter.spec.js b/web-front/src/utils/nameFilter.spec.js
new file mode 100644
index 0000000..67eeefc
--- /dev/null
+++ b/web-front/src/utils/nameFilter.spec.js
@@ -0,0 +1,237 @@
+const { describe, it } = require('node:test')
+const assert = require('node:assert/strict')
+
+const { readPage } = require('./folderPaging')
+const {
+ normalizeQuery,
+ filterByFileName,
+ filterSummary,
+ selectMatching,
+ deselectMatching,
+ toggleSelected,
+ isSelected,
+ collectLoadedNodes,
+ applyCursorPage,
+ switchView,
+ clearKeyword
+} = require('./nameFilter')
+
+function file(name, id, extra = {}) {
+ return {
+ fileName: name,
+ fileId: id,
+ fileType: 'file',
+ parserUrl: '/v2/redirectUrl/lz/same',
+ ...extra
+ }
+}
+
+function folder(name, id) {
+ return {
+ fileName: name,
+ fileId: id,
+ fileType: 'folder',
+ parserUrl: `/v2/getFileList?dir=${id}`
+ }
+}
+
+function baseState(overrides = {}) {
+ return {
+ keyword: '',
+ view: 'pane',
+ loaded: [],
+ selected: [],
+ listUrl: '/v2/getFileList?url=share',
+ more: null,
+ ...overrides
+ }
+}
+
+describe('filename filter', () => {
+ const loaded = [
+ file('Alpha.TXT', '1'),
+ file('notes.md', '2'),
+ file(' photo.JPG', '3'),
+ folder('Albums', '4')
+ ]
+
+ it('trims and matches a case-insensitive substring', () => {
+ assert.equal(normalizeQuery(' ApK '), 'apk')
+ const matched = filterByFileName(loaded, ' aL ')
+ assert.deepEqual(matched.map(item => item.fileId), ['1', '4'])
+ })
+
+ it('blank keyword restores the loaded list without dropping rows', () => {
+ const cleared = filterByFileName(loaded, ' ')
+ assert.deepEqual(cleared.map(item => item.fileId), ['1', '2', '3', '4'])
+ assert.notEqual(cleared, loaded)
+ })
+
+ it('describes loaded N and matched M', () => {
+ const summary = filterSummary(loaded, 'photo')
+ assert.equal(summary.loaded, 4)
+ assert.equal(summary.matched, 1)
+ assert.equal(summary.text, '仅筛选已加载的 4 项,匹配 1 项')
+ })
+})
+
+describe('select and deselect scope', () => {
+ const outside = file('kept.zip', 'out', { parserUrl: '/v2/redirectUrl/lz/out' })
+ const match = file('Alpha.TXT', '1')
+ const other = file('Beta.bin', '2')
+ const hiddenFolder = folder('Alpha-dir', '3')
+ const link = file('Alpha-link.url', '4', { fileType: 'url', parserUrl: '' })
+ const loaded = [match, other, hiddenFolder, link]
+
+ it('selects only loaded selectable files matching the keyword', () => {
+ const selected = selectMatching([outside], loaded, 'alpha')
+ assert.deepEqual(selected.map(item => item.fileId), ['out', '1'])
+ assert.equal(isSelected(selected, other), false)
+ assert.equal(isSelected(selected, hiddenFolder), false)
+ })
+
+ it('deselect removes only the current match and keeps selections outside it', () => {
+ const selected = deselectMatching([outside, match, other], loaded, 'alpha')
+ assert.deepEqual(selected.map(item => item.fileId), ['out', '2'])
+ })
+
+ it('does not select a loaded file hidden by the keyword', () => {
+ const selected = selectMatching([other], loaded, 'alpha')
+ assert.equal(isSelected(selected, other), true)
+ assert.equal(isSelected(selected, match), true)
+ const narrowed = selectMatching(selected, loaded, 'beta')
+ assert.deepEqual(narrowed.map(item => item.fileId).sort(), ['1', '2'])
+ })
+})
+
+describe('same name, different id', () => {
+ const first = file('Report.TXT', 'a')
+ const second = file('Report.TXT', 'b')
+
+ it('keeps both files when selecting and can toggle one without the other', () => {
+ const selected = selectMatching([], [first, second], 'report')
+ assert.equal(selected.length, 2)
+ assert.notEqual(selected[0], selected[1])
+ const onlySecond = toggleSelected(selected, first)
+ assert.deepEqual(onlySecond.map(item => item.fileId), ['b'])
+ assert.equal(isSelected(onlySecond, first), false)
+ assert.equal(isSelected(onlySecond, second), true)
+ })
+
+ it('distinguishes files that only differ by id when fileId is absent', () => {
+ const left = { fileName: 'Report.TXT', id: 'x', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
+ const right = { fileName: 'Report.TXT', id: 'y', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
+ const selected = toggleSelected([], left)
+ assert.equal(isSelected(selected, right), false)
+ assert.equal(toggleSelected(selected, right).length, 2)
+ })
+})
+
+describe('cursor page', () => {
+ it('shows new matches from the next cursor without selecting them', () => {
+ let state = baseState({
+ keyword: 'alpha',
+ loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')],
+ selected: [file('Beta.bin', '2')],
+ more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
+ })
+ assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
+
+ state = applyCursorPage(state, readPage({
+ list: [file('ALPHA-extra.txt', '3'), file('Gamma.bin', '4')],
+ paged: true,
+ hasMore: true,
+ nextPage: 3,
+ nextCursor: 'c2'
+ }))
+
+ assert.deepEqual(state.loaded.map(item => item.fileId), ['1', '2', '3', '4'])
+ assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1', '3'])
+ assert.deepEqual(state.selected.map(item => item.fileId), ['2'])
+ assert.equal(state.more.nextCursor, 'c2')
+ assert.equal(state.more.nextPage, 3)
+ })
+
+ it('keeps load-more available when nothing matches yet', () => {
+ let state = baseState({
+ keyword: 'zzzz',
+ loaded: [file('Alpha.TXT', '1')],
+ more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
+ })
+ assert.equal(filterByFileName(state.loaded, state.keyword).length, 0)
+ assert.equal(state.more.nextCursor, 'c1')
+
+ state = applyCursorPage(state, readPage({
+ list: [file('zzzz-found.txt', '9')],
+ hasMore: true,
+ nextPage: 3,
+ nextCursor: 'c2'
+ }))
+ assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['9'])
+ assert.equal(state.selected.length, 0)
+ assert.ok(state.more)
+ })
+})
+
+describe('view switch and clear', () => {
+ it('keeps the keyword and selected identities when the view changes', () => {
+ const chosen = file('Alpha.TXT', '1')
+ const state = baseState({
+ keyword: ' Alpha ',
+ view: 'pane',
+ loaded: [chosen, file('Beta.bin', '2')],
+ selected: [chosen]
+ })
+ const tree = switchView(state, 'tree')
+ assert.equal(tree.view, 'tree')
+ assert.equal(tree.keyword, ' Alpha ')
+ assert.deepEqual(tree.selected.map(item => item.fileId), ['1'])
+ const back = switchView(tree, 'pane')
+ assert.equal(back.keyword, state.keyword)
+ assert.equal(isSelected(back.selected, chosen), true)
+ })
+
+ it('clearing the keyword shows every loaded row again', () => {
+ const state = baseState({
+ keyword: 'alpha',
+ loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')]
+ })
+ assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
+ const cleared = clearKeyword(state)
+ assert.deepEqual(
+ filterByFileName(cleared.loaded, cleared.keyword).map(item => item.fileId),
+ ['1', '2']
+ )
+ })
+})
+
+describe('loaded tree nodes', () => {
+ it('skips unloaded folders, hidden placeholders, and does not invent a fetch', () => {
+ const secret = file('secret.txt', 'secret')
+ const more = { data: { fileType: 'more', fileName: '加载更多…' }, loaded: true, childNodes: [] }
+ const root = {
+ childNodes: [
+ { data: file('root.txt', 'root'), loaded: true, childNodes: [] },
+ {
+ data: folder('closed', 'closed'),
+ loaded: false,
+ childNodes: [{ data: secret, loaded: true, childNodes: [] }]
+ },
+ {
+ data: folder('open', 'open'),
+ loaded: true,
+ childNodes: [
+ { data: file('open-a.txt', 'oa'), loaded: true, childNodes: [] },
+ more
+ ]
+ },
+ more
+ ]
+ }
+ const loaded = collectLoadedNodes(root)
+ assert.deepEqual(loaded.map(item => item.fileId), ['root', 'closed', 'open', 'oa'])
+ const selected = selectMatching([], loaded, '')
+ assert.deepEqual(selected.map(item => item.fileId), ['root', 'oa'])
+ assert.equal(isSelected(selected, secret), false)
+ })
+})
+ 全选
+ 取消全选
+
已勾选 {{ selectedFiles.length }} 个文件