fb-search.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. (function () {
  2. var form = document.getElementById('searchForm');
  3. var input = document.getElementById('q');
  4. var treeEl = document.getElementById('tree');
  5. var treeStatus = document.getElementById('treeStatus');
  6. var resultMeta = document.getElementById('resultMeta');
  7. var resultsEl = document.getElementById('results');
  8. var nodeState = new Map();
  9. var runningSearchId = 0;
  10. var HOME_SEARCH_CACHE_KEY = 'fb.home.search.q';
  11. function parseQuery() {
  12. var params = new URLSearchParams(location.search || '');
  13. return (params.get('q') || '').trim();
  14. }
  15. function readCachedQuery() {
  16. try {
  17. return (sessionStorage.getItem(HOME_SEARCH_CACHE_KEY) || '').trim();
  18. } catch (e) {
  19. return '';
  20. }
  21. }
  22. function writeCachedQuery(q) {
  23. try {
  24. sessionStorage.setItem(HOME_SEARCH_CACHE_KEY, (q || '').trim());
  25. } catch (e) {}
  26. }
  27. function encodePath(path) {
  28. var p = (path || '').replace(/^\/+|\/+$/g, '');
  29. if (!p) return '';
  30. return p.split('/').map(function (s) { return encodeURIComponent(s); }).join('/');
  31. }
  32. function fileLink(path) {
  33. return '/files/' + encodePath(path || '');
  34. }
  35. function apiUrl(path) {
  36. var p = encodePath(path || '');
  37. return '/api/resources/' + p;
  38. }
  39. function childPath(base, item) {
  40. if (item && typeof item.path === 'string' && item.path.length > 0) return item.path;
  41. var name = item && typeof item.name === 'string' ? item.name : '';
  42. if (!base) return name;
  43. return base + '/' + name;
  44. }
  45. function isDir(item) {
  46. return !!(item && (item.isDir || item.is_dir || item.dir || item.type === 'directory'));
  47. }
  48. function itemName(item) {
  49. return (item && (item.name || item.filename || item.basename || '')) || '';
  50. }
  51. async function getResource(path) {
  52. var res = await fetch(apiUrl(path), {
  53. credentials: 'include',
  54. headers: { 'Accept': 'application/json' }
  55. });
  56. if (res.status === 401) {
  57. location.href = '/login?redirect=' + encodeURIComponent('/search' + location.search);
  58. throw new Error('unauthorized');
  59. }
  60. if (!res.ok) throw new Error('HTTP ' + res.status);
  61. var data = await res.json();
  62. var items = [];
  63. if (Array.isArray(data && data.items)) items = data.items;
  64. else if (Array.isArray(data && data.children)) items = data.children;
  65. return items.map(function (it) {
  66. return {
  67. name: itemName(it),
  68. path: childPath(path || '', it),
  69. isDir: isDir(it),
  70. raw: it
  71. };
  72. }).filter(function (it) { return !!it.name; });
  73. }
  74. function makeNode(path, name, dir) {
  75. return { path: path || '', name: name || '/', isDir: !!dir, loaded: false, loading: false, children: [] };
  76. }
  77. function getNode(path) {
  78. var p = path || '';
  79. if (!nodeState.has(p)) {
  80. var name = p ? p.split('/').pop() : '/';
  81. nodeState.set(p, makeNode(p, name, true));
  82. }
  83. return nodeState.get(p);
  84. }
  85. async function loadNode(path) {
  86. var node = getNode(path);
  87. if (!node.isDir || node.loaded || node.loading) return node;
  88. node.loading = true;
  89. try {
  90. var children = await getResource(path);
  91. node.children = children.sort(function (a, b) {
  92. if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
  93. return a.name.localeCompare(b.name, 'zh-CN');
  94. });
  95. node.loaded = true;
  96. } finally {
  97. node.loading = false;
  98. }
  99. return node;
  100. }
  101. function renderTreeNode(node, parentUl) {
  102. var li = document.createElement('li');
  103. var row = document.createElement('div');
  104. row.className = 'tree-row';
  105. var tg = document.createElement('span');
  106. tg.className = 'tree-toggle';
  107. tg.textContent = node.isDir ? '▸' : '';
  108. var ic = document.createElement('span');
  109. ic.className = 'tree-icon';
  110. ic.textContent = node.isDir ? '📁' : '📄';
  111. var nm = document.createElement('span');
  112. nm.className = 'tree-name';
  113. nm.textContent = node.path ? node.name : '根目录';
  114. row.appendChild(tg);
  115. row.appendChild(ic);
  116. row.appendChild(nm);
  117. var childWrap = document.createElement('ul');
  118. childWrap.style.display = 'none';
  119. row.addEventListener('click', async function () {
  120. if (!node.isDir) {
  121. input.value = node.name;
  122. return;
  123. }
  124. var opening = childWrap.style.display === 'none';
  125. childWrap.style.display = opening ? 'block' : 'none';
  126. tg.textContent = opening ? '▾' : '▸';
  127. if (opening && childWrap.childElementCount === 0) {
  128. var children = [];
  129. try {
  130. await loadNode(node.path);
  131. children = getNode(node.path).children;
  132. } catch (e) {
  133. var err = document.createElement('li');
  134. err.className = 'hint';
  135. err.textContent = '加载失败: ' + (e.message || e);
  136. childWrap.appendChild(err);
  137. return;
  138. }
  139. children.forEach(function (ch) {
  140. var childNode = makeNode(ch.path, ch.name, ch.isDir);
  141. nodeState.set(ch.path, childNode);
  142. renderTreeNode(childNode, childWrap);
  143. });
  144. }
  145. });
  146. li.appendChild(row);
  147. li.appendChild(childWrap);
  148. parentUl.appendChild(li);
  149. }
  150. async function initTree() {
  151. treeStatus.textContent = '加载中...';
  152. treeEl.innerHTML = '';
  153. var root = getNode('');
  154. try {
  155. await loadNode('');
  156. var ul = document.createElement('ul');
  157. renderTreeNode(root, ul);
  158. treeEl.appendChild(ul);
  159. treeStatus.textContent = '仅显示当前账号有权限访问的目录和文件';
  160. } catch (e) {
  161. treeStatus.textContent = '文件树加载失败: ' + (e.message || e);
  162. }
  163. }
  164. function setResultMeta(text) {
  165. resultMeta.textContent = text;
  166. }
  167. function renderResults(items) {
  168. resultsEl.innerHTML = '';
  169. if (items.length === 0) {
  170. var empty = document.createElement('div');
  171. empty.className = 'hint';
  172. empty.textContent = '没有匹配结果';
  173. resultsEl.appendChild(empty);
  174. return;
  175. }
  176. items.forEach(function (it) {
  177. var box = document.createElement('div');
  178. box.className = 'result-item';
  179. var title = document.createElement('a');
  180. title.href = fileLink(it.path);
  181. title.textContent = (it.isDir ? '[目录] ' : '[文件] ') + it.name;
  182. var path = document.createElement('div');
  183. path.className = 'result-path';
  184. path.textContent = it.path || '/';
  185. box.appendChild(title);
  186. box.appendChild(path);
  187. resultsEl.appendChild(box);
  188. });
  189. }
  190. async function runSearch(q) {
  191. var id = ++runningSearchId;
  192. var query = (q || '').trim().toLowerCase();
  193. if (!query) {
  194. setResultMeta('输入关键字后开始搜索');
  195. resultsEl.innerHTML = '';
  196. return;
  197. }
  198. setResultMeta('搜索中...');
  199. var queue = [''];
  200. var visited = new Set();
  201. var matched = [];
  202. var scanned = 0;
  203. var maxNodes = 2500;
  204. while (queue.length > 0) {
  205. if (id !== runningSearchId) return;
  206. var current = queue.shift();
  207. if (visited.has(current)) continue;
  208. visited.add(current);
  209. var children = [];
  210. try {
  211. var node = await loadNode(current);
  212. children = node.children || [];
  213. } catch (e) {
  214. continue;
  215. }
  216. for (var i = 0; i < children.length; i += 1) {
  217. var it = children[i];
  218. scanned += 1;
  219. if (it.name.toLowerCase().indexOf(query) >= 0) matched.push(it);
  220. if (it.isDir) queue.push(it.path);
  221. if (scanned >= maxNodes) {
  222. setResultMeta('已扫描 ' + scanned + ' 项(达到上限),结果 ' + matched.length + ' 条');
  223. renderResults(matched);
  224. return;
  225. }
  226. }
  227. }
  228. setResultMeta('已扫描 ' + scanned + ' 项,结果 ' + matched.length + ' 条');
  229. renderResults(matched);
  230. }
  231. function syncQueryFromUrl() {
  232. var fromUrl = parseQuery();
  233. var q = fromUrl || readCachedQuery();
  234. input.value = q;
  235. if (q) {
  236. if (!fromUrl) {
  237. history.replaceState(null, '', '/search?q=' + encodeURIComponent(q));
  238. }
  239. runSearch(q);
  240. }
  241. }
  242. form.addEventListener('submit', function (e) {
  243. e.preventDefault();
  244. var q = (input.value || '').trim();
  245. writeCachedQuery(q);
  246. var url = '/search' + (q ? ('?q=' + encodeURIComponent(q)) : '');
  247. history.replaceState(null, '', url);
  248. runSearch(q);
  249. });
  250. input.addEventListener('keydown', function (e) {
  251. if (e.key === 'Escape') {
  252. input.value = '';
  253. writeCachedQuery('');
  254. history.replaceState(null, '', '/search');
  255. runSearch('');
  256. }
  257. });
  258. initTree();
  259. syncQueryFromUrl();
  260. })();