mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 23:06:59 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b6394e61f | ||
|
|
ba1c429508 | ||
|
|
69ef9c5bbb | ||
|
|
e91c08548a |
No files matched your search
@@ -99,11 +99,14 @@ public class LzTool extends PanBase {
|
||||
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
||||
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
||||
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
||||
/** 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123 */
|
||||
/**
|
||||
* 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123。
|
||||
* 文件名有 ajaxm / ajaxfile / ajaxfiles 三种,2026-11 起文件页 iframe 改用 ajaxfiles.php。
|
||||
*/
|
||||
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
||||
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|file)\\.php\\?file=\\d+)['\"]",
|
||||
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|files?)\\.php\\?file=\\d+)['\"]",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|file)\\.php\\?file=\\d+)");
|
||||
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|files?)\\.php\\?file=\\d+)");
|
||||
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
||||
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
||||
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* 蓝奏文件页离线回归:2026-11 起文件页 iframe 的下载 ajax 改名为 ajaxfiles.php,
|
||||
* 其余字段(wp_sign / ajaxdata / kd / ves)不变。本地模拟 分享页 → /fn iframe → ajaxfiles.php → 下载域 302。
|
||||
*/
|
||||
public class LzToolAjaxfilesTest {
|
||||
|
||||
private static final String SHARE_KEY = "winx123";
|
||||
private static final String FILE_ID = "333017612";
|
||||
|
||||
private Vertx vertx;
|
||||
private HttpServer server;
|
||||
private final List<String> ajaxPaths = new CopyOnWriteArrayList<>();
|
||||
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
String path = req.path();
|
||||
if ("GET".equals(req.method().name()) && path.equals("/" + SHARE_KEY)) {
|
||||
html(req.response(), sharePage());
|
||||
} else if ("GET".equals(req.method().name()) && path.equals("/fn")) {
|
||||
html(req.response(), iframePage());
|
||||
} else if ("POST".equals(req.method().name()) && path.startsWith("/ajax")) {
|
||||
req.setExpectMultipart(true);
|
||||
req.endHandler(v -> {
|
||||
ajaxPaths.add(req.uri());
|
||||
ajaxForms.add(MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes()));
|
||||
String dom = "http://127.0.0.1:" + server.actualPort();
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end("{\"zt\":1,\"dom\":\"" + dom + "\",\"url\":\"?mock-token\",\"inf\":0}");
|
||||
});
|
||||
} else if (path.equals("/file/")) {
|
||||
req.response().setStatusCode(302)
|
||||
.putHeader("Location", "http://cdn.test/2026/11/25/steam.zip")
|
||||
.end();
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() throws Exception {
|
||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filePageWithAjaxfilesIframeResolvesDirectLink() throws Exception {
|
||||
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
|
||||
.shareUrl(url).standardUrl(url).build();
|
||||
|
||||
String link = new LzTool(info).parse().toCompletionStage().toCompletableFuture()
|
||||
.get(30, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("http://cdn.test/2026/11/25/steam.zip", link);
|
||||
assertEquals(List.of("/ajaxfiles.php?file=" + FILE_ID), ajaxPaths);
|
||||
MultiMap form = ajaxForms.get(0);
|
||||
assertEquals("downprocess", form.get("action"));
|
||||
assertEquals("test-wp-sign", form.get("sign"));
|
||||
assertEquals("test-ajaxdata", form.get("websignkey"));
|
||||
assertEquals("test-ajaxdata", form.get("signs"));
|
||||
assertEquals("1", form.get("ves"));
|
||||
}
|
||||
|
||||
private static void html(io.vertx.core.http.HttpServerResponse res, String body) {
|
||||
res.putHeader("Content-Type", "text/html; charset=utf-8").end(body);
|
||||
}
|
||||
|
||||
private static String sharePage() {
|
||||
return """
|
||||
<!DOCTYPE html><html><head><title>steam.zip - 蓝奏云</title>
|
||||
<meta name="description" content="文件大小:1.1 M" /></head><body>
|
||||
<div class="n_box_3fn" id="filenajax">steam.zip</div>
|
||||
<div class="n_file"><div class="n_filesize">大小:1.1 M</div>
|
||||
<iframe class="n_downlink" name="1795620352" src="/fn?mock-fn-query" frameborder="0" scrolling="no"></iframe></div>
|
||||
</body></html>
|
||||
""";
|
||||
}
|
||||
|
||||
private static String iframePage() {
|
||||
return """
|
||||
<html><body><div id="tourl"></div>
|
||||
<script type="text/javascript">
|
||||
var wsk_sign = 'c20230908';
|
||||
var wp_sign = 'test-wp-sign';
|
||||
var ajaxdata = 'test-ajaxdata';
|
||||
var kdns =1;
|
||||
$.ajax({
|
||||
type : 'post',
|
||||
url : '/ajaxfiles.php?file=%s',
|
||||
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
|
||||
dataType : 'json'
|
||||
});
|
||||
</script></body></html>
|
||||
""".formatted(FILE_ID);
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,16 @@ public class LzToolShareUrlTest {
|
||||
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ajaxfilesEndpointIsRecognized() {
|
||||
assertEquals("/ajaxfiles.php?file=333017612",
|
||||
LzTool.fileAjaxTarget("url : '/ajaxfiles.php?file=333017612',"));
|
||||
assertEquals("https://apifile.lanzouw.com/ajaxfiles.php?file=7",
|
||||
LzTool.fileAjaxTarget("url : 'https://apifile.lanzouw.com/ajaxfiles.php?file=7',"));
|
||||
assertEquals("/ajaxm.php?file=5", LzTool.fileAjaxTarget("url : '/ajaxm.php?file=5',"));
|
||||
assertNull(LzTool.fileAjaxTarget("url : '/ajaxfilex.php?file=5',"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
||||
String html = "url : '/ajaxfile.php?file=150233466',";
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
||||
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
||||
"lint": "vue-cli-service lint",
|
||||
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js"
|
||||
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js src/utils/nameFilter.spec.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.1",
|
||||
|
||||
+152
-31
@@ -315,6 +315,73 @@
|
||||
opacity: .6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.name-filter-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px 14px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 24px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #eaeaea;
|
||||
}
|
||||
|
||||
.name-filter-input {
|
||||
flex: 1 1 220px;
|
||||
max-width: 420px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: 1px solid #dcdfe6;
|
||||
border-radius: 6px;
|
||||
padding: 0 10px;
|
||||
min-height: 36px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.name-filter-input i {
|
||||
color: #909399;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.name-filter-input input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
outline: none;
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
padding: 8px 0;
|
||||
background: transparent;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.filter-hint {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.name-filter-bar {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
padding: 10px 12px;
|
||||
gap: 6px;
|
||||
}
|
||||
.name-filter-input,
|
||||
.filter-hint {
|
||||
flex: 0 0 auto;
|
||||
max-width: none;
|
||||
width: 100%;
|
||||
}
|
||||
.name-filter-input {
|
||||
min-height: 40px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -328,6 +395,14 @@
|
||||
<div class="breadcrumb" id="breadcrumb">
|
||||
<!-- 面包屑导航会通过JS动态生成 -->
|
||||
</div>
|
||||
|
||||
<div class="name-filter-bar">
|
||||
<label class="name-filter-input">
|
||||
<i class="fas fa-search" aria-hidden="true"></i>
|
||||
<input id="name-filter" type="search" placeholder="按文件名筛选" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="按文件名筛选" />
|
||||
</label>
|
||||
<span id="filter-hint" class="filter-hint" hidden></span>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="grid-view" id="file-grid">
|
||||
@@ -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 = `
|
||||
<div class="empty-state">
|
||||
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
|
||||
? `<div class="empty-state">
|
||||
<i class="fas fa-search"></i>
|
||||
<h3>没有匹配的文件</h3>
|
||||
<p>换个关键字,或加载更多后再筛</p>
|
||||
</div>`
|
||||
: `<div class="empty-state">
|
||||
<i class="fas fa-folder-open"></i>
|
||||
<h3>此文件夹为空</h3>
|
||||
<p>暂无文件或文件夹</p>
|
||||
</div>
|
||||
`;
|
||||
</div>`;
|
||||
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 = `
|
||||
<div class="item-icon">
|
||||
@@ -645,16 +755,12 @@
|
||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||
`;
|
||||
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 = `
|
||||
<div class="item-icon">
|
||||
@@ -664,19 +770,34 @@
|
||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||
`;
|
||||
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();
|
||||
}
|
||||
|
||||
// 获取文件扩展名
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
<template>
|
||||
<div class="main-container">
|
||||
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
||||
<div class="dir-filter-bar">
|
||||
<el-input
|
||||
v-model="nameFilter"
|
||||
class="dir-name-filter"
|
||||
clearable
|
||||
placeholder="按文件名筛选"
|
||||
aria-label="按文件名筛选"
|
||||
>
|
||||
<template #prefix>
|
||||
<i class="fas fa-search" aria-hidden="true"></i>
|
||||
</template>
|
||||
</el-input>
|
||||
<p v-if="nameQuery" class="dir-filter-hint">仅筛选已加载的 {{ loadedCount }} 项,匹配 {{ matchedCount }} 项</p>
|
||||
</div>
|
||||
<template v-if="viewMode === 'pane'">
|
||||
<!-- 窗格模式(原有) -->
|
||||
<div class="breadcrumb">
|
||||
@@ -18,7 +32,7 @@
|
||||
</div>
|
||||
<div class="file-grid" v-loading="loading">
|
||||
<div
|
||||
v-for="file in currentFileList"
|
||||
v-for="file in visibleFileList"
|
||||
:key="fileKey(file)"
|
||||
class="file-item"
|
||||
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
||||
@@ -36,10 +50,10 @@
|
||||
{{ fileMetaText(file) }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!loading && (!currentFileList || currentFileList.length === 0)" class="empty-state">
|
||||
<i class="fas fa-folder-open"></i>
|
||||
<h3>此文件夹为空</h3>
|
||||
<p>暂无文件或文件夹</p>
|
||||
<div v-if="!loading && visibleFileList.length === 0" class="empty-state">
|
||||
<i class="fas" :class="nameQuery && currentFileList.length ? 'fa-search' : 'fa-folder-open'"></i>
|
||||
<h3>{{ nameQuery && currentFileList.length ? '没有匹配的文件' : '此文件夹为空' }}</h3>
|
||||
<p>{{ nameQuery && currentFileList.length ? '换个关键字,或加载更多后再筛' : '暂无文件或文件夹' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="paneMore" ref="loadMoreBar" class="load-more-bar">
|
||||
@@ -126,6 +140,11 @@
|
||||
</span>
|
||||
</div>
|
||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
||||
<i class="fas fa-search"></i>
|
||||
<h3>没有匹配的文件</h3>
|
||||
<p>换个关键字,或加载更多后再筛</p>
|
||||
</div>
|
||||
<el-tree
|
||||
ref="fileTree"
|
||||
:data="treeData"
|
||||
@@ -136,16 +155,20 @@
|
||||
:highlight-current="!batchMode"
|
||||
:show-checkbox="batchMode"
|
||||
:check-strictly="false"
|
||||
:filter-node-method="filterTreeNode"
|
||||
@node-click="onNodeClick"
|
||||
@check="onTreeCheck"
|
||||
@check-change="onTreeCheckChange"
|
||||
:default-expand-all="false"
|
||||
:default-expanded-keys="['root']"
|
||||
:render-content="renderContent"
|
||||
style="background:transparent;"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="batchMode" class="tree-sidebar-footer">
|
||||
<div class="tree-select-row">
|
||||
<el-button size="small" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
||||
</div>
|
||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||
<div class="tree-sidebar-actions">
|
||||
<el-button
|
||||
@@ -276,6 +299,11 @@
|
||||
</span>
|
||||
</div>
|
||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
||||
<i class="fas fa-search"></i>
|
||||
<h3>没有匹配的文件</h3>
|
||||
<p>换个关键字,或加载更多后再筛</p>
|
||||
</div>
|
||||
<el-tree
|
||||
ref="fileTree"
|
||||
:data="treeData"
|
||||
@@ -286,11 +314,11 @@
|
||||
:highlight-current="!batchMode"
|
||||
:show-checkbox="batchMode"
|
||||
:check-strictly="false"
|
||||
:filter-node-method="filterTreeNode"
|
||||
@node-click="onNodeClick"
|
||||
@check="onTreeCheck"
|
||||
@check-change="onTreeCheckChange"
|
||||
:default-expand-all="false"
|
||||
:default-expanded-keys="['root']"
|
||||
:render-content="renderContent"
|
||||
style="background:transparent;"
|
||||
/>
|
||||
@@ -366,6 +394,10 @@
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-if="batchMode" class="mobile-batch-footer">
|
||||
<div class="tree-select-row">
|
||||
<el-button size="small" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
||||
</div>
|
||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||
<div class="tree-sidebar-actions">
|
||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user