menuManager.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /**
  2. * 菜单管理模块 - 管理 data/config.json 中的 menuItems
  3. */
  4. // 菜单项列表 (从 config.json 读取)
  5. let configMenuItems = [];
  6. let currentConfig = {}; // 保存当前完整的配置
  7. // 创建menuManager对象
  8. const menuManager = {
  9. // 初始化菜单管理
  10. init: async function() {
  11. // console.log('初始化菜单管理 (config.json)...');
  12. this.renderMenuTableHeader(); // 渲染表头
  13. await this.loadMenuItems(); // 加载菜单项
  14. return Promise.resolve();
  15. },
  16. // 渲染菜单表格头部 (根据 config.json 结构调整)
  17. renderMenuTableHeader: function() {
  18. const menuTable = document.getElementById('menuTable');
  19. if (!menuTable) return;
  20. const thead = menuTable.querySelector('thead') || document.createElement('thead');
  21. thead.innerHTML = `
  22. <tr>
  23. <th style="width: 5%">#</th>
  24. <th style="width: 25%">文本 (Text)</th>
  25. <th style="width: 40%">链接 (Link)</th>
  26. <th style="width: 10%">新标签页 (New Tab)</th>
  27. <th style="width: 20%">操作</th>
  28. </tr>
  29. `;
  30. if (!menuTable.querySelector('thead')) {
  31. menuTable.appendChild(thead);
  32. }
  33. },
  34. // 加载菜单项 (从 /api/config 获取)
  35. loadMenuItems: async function() {
  36. try {
  37. const menuTableBody = document.getElementById('menuTableBody');
  38. if (menuTableBody) {
  39. menuTableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;"><i class="fas fa-spinner fa-spin"></i> 正在加载菜单项...</td></tr>';
  40. }
  41. const response = await fetch('/api/config'); // 请求配置接口
  42. if (!response.ok) {
  43. throw new Error(`获取配置失败: ${response.statusText || response.status}`);
  44. }
  45. currentConfig = await response.json(); // 保存完整配置
  46. configMenuItems = currentConfig.menuItems || []; // 提取菜单项,如果不存在则为空数组
  47. this.renderMenuItems();
  48. // console.log('成功从 /api/config 加载菜单项', configMenuItems);
  49. } catch (error) {
  50. // console.error('加载菜单项失败:', error);
  51. const menuTableBody = document.getElementById('menuTableBody');
  52. if (menuTableBody) {
  53. menuTableBody.innerHTML = `
  54. <tr>
  55. <td colspan="5" style="text-align: center; color: #ff4d4f;">
  56. <i class="fas fa-exclamation-circle"></i>
  57. 加载菜单项失败: ${error.message}
  58. <button onclick="menuManager.loadMenuItems()" class="retry-btn">
  59. <i class="fas fa-sync"></i> 重试
  60. </button>
  61. </td>
  62. </tr>
  63. `;
  64. }
  65. }
  66. },
  67. // 渲染菜单项 (根据 config.json 结构)
  68. renderMenuItems: function() {
  69. const menuTableBody = document.getElementById('menuTableBody');
  70. if (!menuTableBody) return;
  71. menuTableBody.innerHTML = ''; // 清空现有内容
  72. if (!Array.isArray(configMenuItems)) {
  73. // console.error("configMenuItems 不是一个数组:", configMenuItems);
  74. menuTableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #ff4d4f;">菜单数据格式错误</td></tr>';
  75. return;
  76. }
  77. configMenuItems.forEach((item, index) => {
  78. const row = document.createElement('tr');
  79. // 使用 index 作为临时 ID 进行操作
  80. row.innerHTML = `
  81. <td>${index + 1}</td>
  82. <td>${item.text || ''}</td>
  83. <td>${item.link || ''}</td>
  84. <td>${item.newTab ? '是' : '否'}</td>
  85. <td class="action-buttons">
  86. <button class="action-btn edit-btn" title="编辑菜单" onclick="menuManager.editMenuItem(${index})">
  87. <i class="fas fa-edit"></i>
  88. </button>
  89. <button class="action-btn delete-btn" title="删除菜单" onclick="menuManager.deleteMenuItem(${index})">
  90. <i class="fas fa-trash"></i>
  91. </button>
  92. </td>
  93. `;
  94. menuTableBody.appendChild(row);
  95. });
  96. },
  97. // 显示新菜单项行 (调整字段)
  98. showNewMenuItemRow: function() {
  99. const menuTableBody = document.getElementById('menuTableBody');
  100. if (!menuTableBody) return;
  101. // 如果已存在新行,则不重复添加
  102. if (document.getElementById('new-menu-item-row')) {
  103. document.getElementById('new-text').focus();
  104. return;
  105. }
  106. const newRow = document.createElement('tr');
  107. newRow.id = 'new-menu-item-row';
  108. newRow.className = 'new-item-row'; // 可以为此行添加特定样式
  109. newRow.innerHTML = `
  110. <td>#</td>
  111. <td><input type="text" id="new-text" class="form-control form-control-sm" placeholder="菜单文本"></td>
  112. <td><input type="text" id="new-link" class="form-control form-control-sm" placeholder="链接地址 (例如 /about 或 https://example.com)"></td>
  113. <td>
  114. <select id="new-newTab" class="form-select form-select-sm">
  115. <option value="false">否</option>
  116. <option value="true">是</option>
  117. </select>
  118. </td>
  119. <td class="action-buttons-new-menu">
  120. <button class="btn btn-sm btn-success save-new-menu-btn" onclick="menuManager.saveNewMenuItem()">
  121. <i class="fas fa-save"></i> 保存
  122. </button>
  123. <button class="btn btn-sm btn-danger cancel-new-menu-btn" onclick="menuManager.cancelNewMenuItem()">
  124. <i class="fas fa-times"></i> 取消
  125. </button>
  126. </td>
  127. `;
  128. // 将新行添加到表格体的最上方
  129. menuTableBody.insertBefore(newRow, menuTableBody.firstChild);
  130. document.getElementById('new-text').focus();
  131. },
  132. // 保存新菜单项 (更新整个配置)
  133. saveNewMenuItem: async function() {
  134. try {
  135. const text = document.getElementById('new-text').value.trim();
  136. const link = document.getElementById('new-link').value.trim();
  137. const newTab = document.getElementById('new-newTab').value === 'true';
  138. if (!text || !link) {
  139. throw new Error('文本和链接为必填项');
  140. }
  141. const newMenuItem = { text, link, newTab };
  142. // 创建更新后的配置对象
  143. const updatedConfig = {
  144. ...currentConfig,
  145. menuItems: [...(currentConfig.menuItems || []), newMenuItem] // 添加新项
  146. };
  147. // 调用API保存整个配置
  148. const response = await fetch('/api/config', {
  149. method: 'POST',
  150. headers: { 'Content-Type': 'application/json' },
  151. body: JSON.stringify(updatedConfig) // 发送更新后的完整配置
  152. });
  153. if (!response.ok) {
  154. const errorData = await response.json();
  155. throw new Error(`保存配置失败: ${errorData.details || response.statusText}`);
  156. }
  157. // 重新加载菜单项以更新视图和 currentConfig
  158. await this.loadMenuItems();
  159. this.cancelNewMenuItem(); // 移除编辑行
  160. core.showAlert('菜单项已添加', 'success');
  161. } catch (error) {
  162. // console.error('添加菜单项失败:', error);
  163. core.showAlert('添加菜单项失败: ' + error.message, 'error');
  164. }
  165. },
  166. // 取消新菜单项
  167. cancelNewMenuItem: function() {
  168. const newRow = document.getElementById('new-menu-item-row');
  169. if (newRow) {
  170. newRow.remove();
  171. }
  172. },
  173. // 编辑菜单项 (使用 index 定位)
  174. editMenuItem: function(index) {
  175. const item = configMenuItems[index];
  176. if (!item) {
  177. core.showAlert('找不到指定的菜单项', 'error');
  178. return;
  179. }
  180. Swal.fire({
  181. title: '<div class="edit-title"><i class="fas fa-edit"></i> 编辑菜单项</div>',
  182. html: `
  183. <div class="edit-menu-form">
  184. <div class="form-group">
  185. <label for="edit-text">
  186. <i class="fas fa-font"></i> 菜单文本
  187. </label>
  188. <div class="input-wrapper">
  189. <input type="text" id="edit-text" class="modern-input" value="${item.text || ''}" placeholder="请输入菜单文本">
  190. <span class="input-icon"><i class="fas fa-heading"></i></span>
  191. </div>
  192. <small class="form-hint">菜单项显示的文本,保持简洁明了</small>
  193. </div>
  194. <div class="form-group">
  195. <label for="edit-link">
  196. <i class="fas fa-link"></i> 链接地址
  197. </label>
  198. <div class="input-wrapper">
  199. <input type="text" id="edit-link" class="modern-input" value="${item.link || ''}" placeholder="请输入链接地址">
  200. <span class="input-icon"><i class="fas fa-globe"></i></span>
  201. </div>
  202. <small class="form-hint">完整URL路径(例如: https://example.com)或相对路径(例如: /docs)</small>
  203. </div>
  204. <div class="form-group toggle-switch">
  205. <label for="edit-newTab" class="toggle-label-text">
  206. <i class="fas fa-external-link-alt"></i> 在新标签页打开
  207. </label>
  208. <div class="toggle-switch-container">
  209. <input type="checkbox" id="edit-newTab" class="toggle-input" ${item.newTab ? 'checked' : ''}>
  210. <label for="edit-newTab" class="toggle-label"></label>
  211. <span class="toggle-status">${item.newTab ? '是' : '否'}</span>
  212. </div>
  213. </div>
  214. <div class="form-preview">
  215. <div class="preview-title"><i class="fas fa-eye"></i> 预览</div>
  216. <div class="preview-content">
  217. <a href="${item.link || '#'}" class="preview-link" target="${item.newTab ? '_blank' : '_self'}">
  218. <span class="preview-text">${item.text || '菜单项'}</span>
  219. ${item.newTab ? '<i class="fas fa-external-link-alt preview-icon"></i>' : ''}
  220. </a>
  221. </div>
  222. </div>
  223. </div>
  224. <style>
  225. .edit-title {
  226. font-size: 1.5rem;
  227. color: #3085d6;
  228. margin-bottom: 10px;
  229. }
  230. .edit-menu-form {
  231. text-align: left;
  232. padding: 0 15px;
  233. }
  234. .form-group {
  235. margin-bottom: 20px;
  236. position: relative;
  237. }
  238. .form-group label {
  239. display: block;
  240. margin-bottom: 8px;
  241. font-weight: 600;
  242. color: #444;
  243. font-size: 0.95rem;
  244. }
  245. .input-wrapper {
  246. position: relative;
  247. }
  248. .modern-input {
  249. width: 100%;
  250. padding: 12px 40px 12px 15px;
  251. border: 1px solid #ddd;
  252. border-radius: 8px;
  253. font-size: 1rem;
  254. transition: all 0.3s ease;
  255. box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  256. }
  257. .modern-input:focus {
  258. border-color: #3085d6;
  259. box-shadow: 0 0 0 3px rgba(48, 133, 214, 0.2);
  260. outline: none;
  261. }
  262. .input-icon {
  263. position: absolute;
  264. right: 12px;
  265. top: 50%;
  266. transform: translateY(-50%);
  267. color: #aaa;
  268. }
  269. .form-hint {
  270. display: block;
  271. font-size: 0.8rem;
  272. color: #888;
  273. margin-top: 5px;
  274. font-style: italic;
  275. }
  276. .toggle-switch {
  277. display: flex;
  278. justify-content: space-between;
  279. align-items: center;
  280. padding: 5px 0;
  281. }
  282. .toggle-label-text {
  283. margin-bottom: 0 !important;
  284. }
  285. .toggle-switch-container {
  286. display: flex;
  287. align-items: center;
  288. }
  289. .toggle-input {
  290. display: none;
  291. }
  292. .toggle-label {
  293. display: block;
  294. width: 52px;
  295. height: 26px;
  296. background: #e6e6e6;
  297. border-radius: 13px;
  298. position: relative;
  299. cursor: pointer;
  300. transition: background 0.3s ease;
  301. box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
  302. }
  303. .toggle-label:after {
  304. content: '';
  305. position: absolute;
  306. top: 3px;
  307. left: 3px;
  308. width: 20px;
  309. height: 20px;
  310. background: white;
  311. border-radius: 50%;
  312. transition: transform 0.3s ease, box-shadow 0.3s ease;
  313. box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  314. }
  315. .toggle-input:checked + .toggle-label {
  316. background: #3085d6;
  317. }
  318. .toggle-input:checked + .toggle-label:after {
  319. transform: translateX(26px);
  320. }
  321. .toggle-status {
  322. margin-left: 10px;
  323. font-size: 0.9rem;
  324. color: #666;
  325. min-width: 20px;
  326. }
  327. .form-preview {
  328. margin-top: 25px;
  329. border: 1px dashed #ccc;
  330. border-radius: 8px;
  331. padding: 15px;
  332. background-color: #f9f9f9;
  333. }
  334. .preview-title {
  335. font-size: 0.9rem;
  336. color: #666;
  337. margin-bottom: 10px;
  338. text-align: center;
  339. }
  340. .preview-content {
  341. display: flex;
  342. justify-content: center;
  343. padding: 10px;
  344. background: white;
  345. border-radius: 6px;
  346. box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  347. }
  348. .preview-link {
  349. display: flex;
  350. align-items: center;
  351. color: #3085d6;
  352. text-decoration: none;
  353. font-weight: 500;
  354. padding: 5px 10px;
  355. border-radius: 4px;
  356. transition: background 0.2s ease;
  357. }
  358. .preview-link:hover {
  359. background: #f0f7ff;
  360. }
  361. .preview-text {
  362. margin-right: 5px;
  363. }
  364. .preview-icon {
  365. font-size: 0.8rem;
  366. opacity: 0.7;
  367. }
  368. </style>
  369. `,
  370. showCancelButton: true,
  371. confirmButtonText: '<i class="fas fa-save"></i> 保存',
  372. cancelButtonText: '<i class="fas fa-times"></i> 取消',
  373. confirmButtonColor: '#3085d6',
  374. cancelButtonColor: '#6c757d',
  375. width: '550px',
  376. focusConfirm: false,
  377. customClass: {
  378. container: 'menu-edit-container',
  379. popup: 'menu-edit-popup',
  380. title: 'menu-edit-title',
  381. confirmButton: 'menu-edit-confirm',
  382. cancelButton: 'menu-edit-cancel'
  383. },
  384. didOpen: () => {
  385. // 添加输入监听,更新预览
  386. const textInput = document.getElementById('edit-text');
  387. const linkInput = document.getElementById('edit-link');
  388. const newTabToggle = document.getElementById('edit-newTab');
  389. const toggleStatus = document.querySelector('.toggle-status');
  390. const previewText = document.querySelector('.preview-text');
  391. const previewLink = document.querySelector('.preview-link');
  392. const previewIcon = document.querySelector('.preview-icon') || document.createElement('i');
  393. if (!previewIcon.classList.contains('fas')) {
  394. previewIcon.className = 'fas fa-external-link-alt preview-icon';
  395. }
  396. const updatePreview = () => {
  397. previewText.textContent = textInput.value || '菜单项';
  398. previewLink.href = linkInput.value || '#';
  399. previewLink.target = newTabToggle.checked ? '_blank' : '_self';
  400. if (newTabToggle.checked) {
  401. if (!previewLink.contains(previewIcon)) {
  402. previewLink.appendChild(previewIcon);
  403. }
  404. } else {
  405. if (previewLink.contains(previewIcon)) {
  406. previewLink.removeChild(previewIcon);
  407. }
  408. }
  409. };
  410. textInput.addEventListener('input', updatePreview);
  411. linkInput.addEventListener('input', updatePreview);
  412. newTabToggle.addEventListener('change', () => {
  413. toggleStatus.textContent = newTabToggle.checked ? '是' : '否';
  414. updatePreview();
  415. });
  416. },
  417. preConfirm: () => {
  418. const text = document.getElementById('edit-text').value.trim();
  419. const link = document.getElementById('edit-link').value.trim();
  420. const newTab = document.getElementById('edit-newTab').checked;
  421. if (!text) {
  422. Swal.showValidationMessage('<i class="fas fa-exclamation-circle"></i> 菜单文本不能为空');
  423. return false;
  424. }
  425. if (!link) {
  426. Swal.showValidationMessage('<i class="fas fa-exclamation-circle"></i> 链接地址不能为空');
  427. return false;
  428. }
  429. return { text, link, newTab };
  430. }
  431. }).then(async (result) => {
  432. if (!result.isConfirmed) return;
  433. try {
  434. // 显示保存中状态
  435. Swal.fire({
  436. title: '保存中...',
  437. html: '<i class="fas fa-spinner fa-spin"></i> 正在保存菜单项',
  438. showConfirmButton: false,
  439. allowOutsideClick: false,
  440. willOpen: () => {
  441. Swal.showLoading();
  442. }
  443. });
  444. // 更新配置中的菜单项
  445. configMenuItems[index] = result.value;
  446. // 创建更新后的配置对象
  447. const updatedConfig = {
  448. ...currentConfig,
  449. menuItems: configMenuItems // 更新后的菜单项数组
  450. };
  451. // 调用API保存整个配置
  452. const response = await fetch('/api/config', {
  453. method: 'POST',
  454. headers: { 'Content-Type': 'application/json' },
  455. body: JSON.stringify(updatedConfig) // 发送更新后的完整配置
  456. });
  457. if (!response.ok) {
  458. const errorData = await response.json();
  459. throw new Error(`保存配置失败: ${errorData.details || response.statusText}`);
  460. }
  461. // 重新渲染菜单项
  462. this.renderMenuItems();
  463. // 显示成功消息
  464. Swal.fire({
  465. icon: 'success',
  466. title: '保存成功',
  467. html: '<i class="fas fa-check-circle"></i> 菜单项已更新',
  468. timer: 1500,
  469. showConfirmButton: false
  470. });
  471. } catch (error) {
  472. // console.error('更新菜单项失败:', error);
  473. Swal.fire({
  474. icon: 'error',
  475. title: '保存失败',
  476. html: `<i class="fas fa-times-circle"></i> 更新菜单项失败: ${error.message}`,
  477. confirmButtonText: '确定'
  478. });
  479. }
  480. });
  481. },
  482. // 删除菜单项
  483. deleteMenuItem: function(index) {
  484. const item = configMenuItems[index];
  485. if (!item) {
  486. core.showAlert('找不到指定的菜单项', 'error');
  487. return;
  488. }
  489. Swal.fire({
  490. title: '确认删除',
  491. text: `确定要删除菜单项 "${item.text}" 吗?`,
  492. icon: 'warning',
  493. showCancelButton: true,
  494. confirmButtonText: '删除',
  495. cancelButtonText: '取消',
  496. confirmButtonColor: '#d33'
  497. }).then(async (result) => {
  498. if (!result.isConfirmed) return;
  499. try {
  500. // 从菜单项数组中移除指定项
  501. configMenuItems.splice(index, 1);
  502. // 创建更新后的配置对象
  503. const updatedConfig = {
  504. ...currentConfig,
  505. menuItems: configMenuItems // 更新后的菜单项数组
  506. };
  507. // 调用API保存整个配置
  508. const response = await fetch('/api/config', {
  509. method: 'POST',
  510. headers: { 'Content-Type': 'application/json' },
  511. body: JSON.stringify(updatedConfig) // 发送更新后的完整配置
  512. });
  513. if (!response.ok) {
  514. const errorData = await response.json();
  515. throw new Error(`保存配置失败: ${errorData.details || response.statusText}`);
  516. }
  517. // 重新渲染菜单项
  518. this.renderMenuItems();
  519. core.showAlert('菜单项已删除', 'success');
  520. } catch (error) {
  521. // console.error('删除菜单项失败:', error);
  522. core.showAlert('删除菜单项失败: ' + error.message, 'error');
  523. }
  524. });
  525. }
  526. };
  527. // 全局公开菜单管理模块
  528. window.menuManager = menuManager;