/** * 资源助手统一文件列表(文献/模板/工具/教程/数据集/程序代码) * 可与 IARStatCards 联动:connectStatCards(scopeId, statScopeId, opts) */ (function (global) { 'use strict'; var _registry = {}; var _items = {}; var _selected = {}; var _statFilter = {}; var _searchMode = {}; function _cfg(scopeId) { return _registry[scopeId] || null; } function _listEl(scopeId) { var cfg = _cfg(scopeId); if (!cfg) return null; return document.getElementById(cfg.listId); } function _searchEl(scopeId) { var cfg = _cfg(scopeId); if (!cfg || !cfg.searchInputId) return null; return document.getElementById(cfg.searchInputId); } function _normalize(item) { if (item && typeof item === 'object' && ('path' in item || 'filename' in item)) { var path = item.path || ''; var filename = item.filename || (path ? String(path).split(/[/\\]/).pop() : ''); return { path: path, filename: filename, mtime: item.mtime || 0, mtimeStr: item.mtime_str || item.mtimeStr || '-', sizeStr: item.size_str || item.sizeStr || '-', typeVal: item.type || item.typeVal || (path ? (String(path).split('.').pop() || '') : ''), raw: item }; } var p = typeof item === 'string' ? item : ''; return { path: p, filename: p ? String(p).split(/[/\\]/).pop() : '', mtime: 0, mtimeStr: '-', sizeStr: '-', typeVal: p ? (String(p).split('.').pop() || '') : '', raw: item }; } function register(scopeId, cfg) { if (!scopeId) return; var prev = _registry[scopeId] || {}; _registry[scopeId] = Object.assign({ listId: 'fileList', searchInputId: scopeId + 'SearchInput', sortByMtime: false, showTooltip: false, selectedClass: ['font-bold', 'text-blue-600', 'is-selected'], getItems: null, filterItems: null, onSelect: null, onDblClick: null, showActions: false, renderActions: null, onReset: null, onAll: null, matchItem: null, matchItemExact: null, matchItemFuzzy: null, matchItemKeyword: null, similarThreshold: 0.6, getStatus: null, statusField: 'status', statScopeId: null }, prev, cfg || {}); if (_items[scopeId] === undefined) _items[scopeId] = []; if (_statFilter[scopeId] === undefined) _statFilter[scopeId] = 'all'; } function connect(scopeId, cfg) { register(scopeId, cfg); } function setItems(scopeId, items) { _items[scopeId] = Array.isArray(items) ? items.slice() : []; _syncStatCounts(scopeId); render(scopeId); } function getItems(scopeId) { var cfg = _cfg(scopeId); if (cfg && typeof cfg.getItems === 'function') { var live = cfg.getItems(); if (Array.isArray(live)) return live; } return _items[scopeId] || []; } function getSelectedPath(scopeId) { return _selected[scopeId] || ''; } function setSelectedPath(scopeId, path) { _selected[scopeId] = path || ''; } function _applyFilters(scopeId, list) { var cfg = _cfg(scopeId); var items = Array.isArray(list) ? list : getItems(scopeId); if (cfg && typeof cfg.filterItems === 'function') { items = cfg.filterItems(items) || []; } var key = _statFilter[scopeId]; if (key && key !== 'all' && cfg) { var getStatus = cfg.getStatus || function (item) { var n = _normalize(item); var raw = n.raw && typeof n.raw === 'object' ? n.raw : item; var field = cfg.statusField || 'status'; return raw && raw[field] != null ? String(raw[field]) : ''; }; items = items.filter(function (item) { return getStatus(item) === key; }); } return items; } function _syncStatCounts(scopeId) { var cfg = _cfg(scopeId); if (!cfg || !cfg.statScopeId || !global.IARStatCards) return; try { global.IARStatCards.updateCounts(cfg.statScopeId, getItems(scopeId), cfg.statusField); } catch (e) { /* ignore */ } } function render(scopeId, fileList) { var cfg = _cfg(scopeId); var ul = _listEl(scopeId); if (!cfg || !ul) return; var list = fileList !== undefined && fileList !== null ? (Array.isArray(fileList) ? fileList : []) : _applyFilters(scopeId); var items = list.map(_normalize); if (cfg.sortByMtime) { items.sort(function (a, b) { return (b.mtime || 0) - (a.mtime || 0); }); } ul.innerHTML = ''; var selectedPath = _selected[scopeId] || ''; items.forEach(function (item) { var li = document.createElement('li'); var label = item.filename || item.path || '(未命名)'; li.classList.add('cursor-pointer', 'py-0.5'); if (cfg.showActions) { li.classList.add('iar-res-file-list-row'); var nameEl = document.createElement('span'); nameEl.className = 'iar-res-file-list-name'; nameEl.textContent = label; var opsEl = document.createElement('span'); opsEl.className = 'iar-res-file-list-ops iar-entity-list-actions'; if (typeof cfg.renderActions === 'function') { opsEl.innerHTML = cfg.renderActions(item) || ''; } li.appendChild(nameEl); li.appendChild(opsEl); } else { li.textContent = label; } li.dataset.path = item.path; if (cfg.showTooltip) { li.title = [ '路径:' + (item.path || '-'), '文件名:' + (item.filename || '-'), '修改时间:' + (item.mtimeStr || '-'), '类型:' + (item.typeVal || '-'), '大小:' + (item.sizeStr || '-') ].join('\n'); } else if (item.path) { li.title = item.path; } if (selectedPath && selectedPath === item.path) { cfg.selectedClass.forEach(function (c) { li.classList.add(c); }); } li.onclick = function () { _selected[scopeId] = item.path; ul.querySelectorAll('li').forEach(function (f) { cfg.selectedClass.forEach(function (c) { f.classList.remove(c); }); }); cfg.selectedClass.forEach(function (c) { li.classList.add(c); }); if (typeof cfg.onSelect === 'function') { cfg.onSelect(item.path, item.raw !== undefined ? item.raw : item, li); } }; if (typeof cfg.onDblClick === 'function') { li.ondblclick = function () { _selected[scopeId] = item.path; cfg.onDblClick(item.path, item.raw !== undefined ? item.raw : item, li); }; } ul.appendChild(li); }); } function _defaultMatchExact(item, kw) { var n = _normalize(item); var name = (n.filename || '').toLowerCase(); var path = (n.path || '').toLowerCase().replace(/\\/g, '/'); if (name === kw || path === kw) return true; // 无扩展名时也允许与去扩展名后的文件名精确匹配 var dot = name.lastIndexOf('.'); if (dot > 0 && name.slice(0, dot) === kw) return true; return false; } function _defaultMatchKeyword(item, kw) { var n = _normalize(item); var name = (n.filename || '').toLowerCase(); var path = (n.path || '').toLowerCase(); return name.indexOf(kw) >= 0 || path.indexOf(kw) >= 0; } /** 与 Python difflib.SequenceMatcher.ratio 近似:2*LCS/(lenA+lenB) */ function _lcsLength(a, b) { var m = a.length; var n = b.length; if (!m || !n) return 0; var prev = new Array(n + 1); var cur = new Array(n + 1); var i; var j; for (j = 0; j <= n; j++) prev[j] = 0; for (i = 1; i <= m; i++) { cur[0] = 0; for (j = 1; j <= n; j++) { if (a.charAt(i - 1) === b.charAt(j - 1)) cur[j] = prev[j - 1] + 1; else cur[j] = prev[j] > cur[j - 1] ? prev[j] : cur[j - 1]; } var tmp = prev; prev = cur; cur = tmp; } return prev[n]; } function similarityRatio(a, b) { var sa = String(a == null ? '' : a).trim().toLowerCase(); var sb = String(b == null ? '' : b).trim().toLowerCase(); if (!sa && !sb) return 1; if (!sa || !sb) return 0; return (2 * _lcsLength(sa, sb)) / (sa.length + sb.length); } function _filenameStem(name) { var s = String(name || ''); var i = s.lastIndexOf('.'); return i > 0 ? s.slice(0, i) : s; } function _itemSimilarity(item, query) { var n = _normalize(item); var name = n.filename || ''; var stem = _filenameStem(name); var r1 = similarityRatio(query, name); var r2 = similarityRatio(query, stem); return r1 > r2 ? r1 : r2; } /** * @param {string} scopeId * @param {'exact'|'keyword'|'similar'|'fuzzy'} [mode] fuzzy 为 keyword 别名;省略时沿用上次,默认 keyword * @param {number} [threshold] similar 模式阈值,默认 0.6 */ function search(scopeId, mode, threshold) { var cfg = _cfg(scopeId); if (!cfg) return; var m = mode || _searchMode[scopeId] || 'keyword'; if (m === 'fuzzy') m = 'keyword'; if (m !== 'exact' && m !== 'keyword' && m !== 'similar') m = 'keyword'; _searchMode[scopeId] = m; var input = _searchEl(scopeId); var rawKw = input ? String(input.value || '').trim() : ''; var keyword = rawKw.toLowerCase(); var base = _applyFilters(scopeId, getItems(scopeId)); if (!rawKw) { render(scopeId, base); return; } if (m === 'similar') { var thr = typeof threshold === 'number' ? threshold : (cfg.similarThreshold != null ? cfg.similarThreshold : 0.6); var scored = []; base.forEach(function (item) { var score = _itemSimilarity(item, rawKw); if (score >= thr) scored.push({ item: item, score: score }); }); scored.sort(function (a, b) { return b.score - a.score; }); var list = scored.map(function (s) { var n = _normalize(s.item); var pct = Math.round(s.score * 100); var label = (n.filename || n.path || '(未命名)') + '(相似度 ' + pct + '%)'; if (s.item && typeof s.item === 'object') { return Object.assign({}, s.item, { path: n.path, filename: label, _similarity: s.score }); } return { path: n.path, filename: label, mtime: 0, mtime_str: '-', size_str: '-', type: n.typeVal, _similarity: s.score }; }); render(scopeId, list); return; } var match; if (m === 'exact') { match = cfg.matchItemExact || cfg.matchItem || _defaultMatchExact; } else { match = cfg.matchItemKeyword || cfg.matchItemFuzzy || cfg.matchItem || _defaultMatchKeyword; } render(scopeId, base.filter(function (item) { return match(item, keyword); })); } function searchExact(scopeId) { return search(scopeId, 'exact'); } /** 关键字包含匹配(原「模糊搜索」行为) */ function searchKeyword(scopeId) { return search(scopeId, 'keyword'); } /** @deprecated 请使用 searchKeyword;保留兼容旧调用 */ function searchFuzzy(scopeId) { return searchKeyword(scopeId); } /** 文件名相似度搜索(默认阈值 60%) */ function searchSimilar(scopeId, threshold) { return search(scopeId, 'similar', threshold); } function reset(scopeId) { var cfg = _cfg(scopeId); if (!cfg) return; var input = _searchEl(scopeId); if (input) input.value = ''; _statFilter[scopeId] = 'all'; if (cfg.statScopeId && global.IARStatCards) { try { global.IARStatCards.setFilter(cfg.statScopeId, 'all'); global.IARStatCards.setActive(cfg.statScopeId, 'all'); } catch (e) { /* ignore */ } } if (typeof cfg.onReset === 'function') { return cfg.onReset(); } render(scopeId); } function all(scopeId) { var cfg = _cfg(scopeId); if (!cfg) return; var input = _searchEl(scopeId); if (input) input.value = ''; if (typeof cfg.onAll === 'function') { return cfg.onAll(); } render(scopeId, getItems(scopeId)); } function highlight(scopeId, path) { var cfg = _cfg(scopeId); var ul = _listEl(scopeId); if (!cfg || !ul) return; _selected[scopeId] = path || ''; ul.querySelectorAll('li').forEach(function (li) { cfg.selectedClass.forEach(function (c) { li.classList.remove(c); }); if (path && li.dataset.path === path) { cfg.selectedClass.forEach(function (c) { li.classList.add(c); }); } }); } function selectPath(scopeId, path, fireSelect) { highlight(scopeId, path); if (!fireSelect) return; var cfg = _cfg(scopeId); if (!cfg || typeof cfg.onSelect !== 'function') return; var found = null; getItems(scopeId).forEach(function (item) { var n = _normalize(item); if (n.path === path) found = item; }); cfg.onSelect(path, found != null ? found : path, null); } function withProgress(scopeId, message, asyncFn) { var cfg = _cfg(scopeId) || {}; var progressId = cfg.progressId || (scopeId + 'List'); var msg = message || '加载中...'; if (!global.IARProgress) { return Promise.resolve(asyncFn()); } if (cfg.progressWrapId || cfg.progressBarId || cfg.progressTextId) { IARProgress.bind(progressId, { wrapId: cfg.progressWrapId || (progressId + 'ProgressWrap'), barId: cfg.progressBarId || (progressId + 'ProgressBar'), msgId: cfg.progressTextId || (progressId + 'ProgressMsg'), }); } var started = IARProgress.startAuto(progressId, { message: msg, maxPercent: 92, intervalMs: 160, step: 4, }); if (!started) { return Promise.resolve(asyncFn()); } return Promise.resolve() .then(function () { return asyncFn(); }) .then(function (result) { IARProgress.done(progressId, { hideAfterMs: 220 }); return result; }) .catch(function (e) { console.error(e); IARProgress.stopAuto(progressId); IARProgress.set(progressId, { message: '加载失败,请稍后重试', percent: 0 }); setTimeout(function () { IARProgress.hide(progressId); }, 800); throw e; }); } /** * 与统计卡联动:点击统计卡筛选列表并更新计数。 * opts: { getStatus, statusField, defaultFilter } */ function connectStatCards(scopeId, statScopeId, opts) { opts = opts || {}; register(scopeId, { statScopeId: statScopeId, getStatus: opts.getStatus || null, statusField: opts.statusField || 'status' }); if (!global.IARStatCards) { console.warn('IARResFileList.connectStatCards: IARStatCards 未加载'); return; } global.IARStatCards.connect(statScopeId, { statusField: opts.statusField || 'status', getStatus: opts.getStatus, defaultFilter: opts.defaultFilter || 'all', onFilter: function (statusKey) { _statFilter[scopeId] = statusKey || 'all'; var input = _searchEl(scopeId); if (input && input.value) { search(scopeId, _searchMode[scopeId] || 'fuzzy'); } else { render(scopeId); } if (typeof opts.onFilter === 'function') opts.onFilter(statusKey); } }); _syncStatCounts(scopeId); } function applyStatFilter(scopeId, statusKey) { _statFilter[scopeId] = statusKey || 'all'; render(scopeId); } global.IARResFileList = { register: register, connect: connect, setItems: setItems, getItems: getItems, getSelectedPath: getSelectedPath, setSelectedPath: setSelectedPath, render: render, search: search, searchExact: searchExact, searchKeyword: searchKeyword, searchFuzzy: searchFuzzy, searchSimilar: searchSimilar, similarityRatio: similarityRatio, reset: reset, all: all, highlight: highlight, selectPath: selectPath, withProgress: withProgress, connectStatCards: connectStatCards, applyStatFilter: applyStatFilter }; })(typeof window !== 'undefined' ? window : this);