market.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. import Awesome from '../background/awesome.js'
  2. import MSG_TYPE from '../static/js/common.js';
  3. import Settings from './settings.js';
  4. import Statistics from '../background/statistics.js';
  5. // 工具分类定义
  6. const TOOL_CATEGORIES = [
  7. { key: 'dev', name: '开发工具类', tools: ['json-format', 'json-diff', 'code-beautify', 'code-compress', 'postman', 'websocket', 'regexp','page-timing'] },
  8. { key: 'encode', name: '编解码转换类', tools: ['en-decode', 'trans-radix', 'timestamp', 'trans-color'] },
  9. { key: 'image', name: '图像处理类', tools: ['qr-code', 'image-base64', 'svg-converter', 'chart-maker', 'poster-maker' ,'screenshot', 'color-picker'] },
  10. { key: 'productivity', name: '效率工具类', tools: ['aiagent', 'sticky-notes', 'html2markdown', 'page-monkey'] },
  11. { key: 'calculator', name: '计算工具类', tools: ['crontab', 'loan-rate', 'password'] },
  12. { key: 'other', name: '其他工具', tools: [] }
  13. ];
  14. // Vue实例
  15. new Vue({
  16. el: '#marketContainer',
  17. data: {
  18. manifest: { version: '0.0.0' },
  19. searchKey: '',
  20. currentCategory: '',
  21. sortType: 'default',
  22. viewMode: 'list', // 默认网格视图
  23. categories: TOOL_CATEGORIES,
  24. favorites: new Set(),
  25. recentUsed: [],
  26. loading: true,
  27. originalTools: {}, // 保存原始工具数据
  28. currentView: 'all', // 当前视图类型(all/installed/favorites/recent)
  29. activeTools: {}, // 当前显示的工具列表
  30. installedCount: 0, // 已安装工具数量
  31. // 版本相关
  32. latestVersion: '', // 最新版本号
  33. needUpdate: false, // 是否需要更新
  34. // 设置相关
  35. showSettingsModal: false,
  36. defaultKey: 'Alt+Shift+J', // 默认快捷键
  37. countDown: 0, // 夜间模式倒计时
  38. selectedOpts: [], // 选中的选项
  39. menuDownloadCrx: false, // 菜单-插件下载
  40. menuFeHelperSeting: false, // 菜单-FeHelper设置
  41. isFirefox: false, // 是否Firefox浏览器
  42. // 打赏相关
  43. showDonateModal: false,
  44. donate: {
  45. text: '感谢你对FeHelper的认可和支持!',
  46. image: './donate.jpeg'
  47. },
  48. // 确认对话框
  49. confirmDialog: {
  50. show: false,
  51. title: '操作确认',
  52. message: '',
  53. callback: null,
  54. data: null
  55. },
  56. recentCount: 0,
  57. },
  58. async created() {
  59. await this.initData();
  60. this.recentCount = (await Statistics.getRecentUsedTools(10)).length;
  61. // 初始化后更新已安装工具数量
  62. this.updateInstalledCount();
  63. // 恢复用户的视图模式设置
  64. this.loadViewMode();
  65. // 加载设置项
  66. this.loadSettings();
  67. // 检查浏览器类型
  68. this.checkBrowserType();
  69. // 检查版本更新
  70. this.checkVersionUpdate();
  71. // 检查URL中是否有donate_from参数
  72. this.checkDonateParam();
  73. },
  74. computed: {
  75. filteredTools() {
  76. if (this.loading) {
  77. return [];
  78. }
  79. // 获取当前工具列表
  80. let result = Object.values(this.activeTools).map(tool => ({
  81. ...tool,
  82. favorite: this.favorites.has(tool.key)
  83. }));
  84. // 搜索过滤
  85. if (this.searchKey) {
  86. const key = this.searchKey.toLowerCase();
  87. result = result.filter(tool =>
  88. tool.name.toLowerCase().includes(key) ||
  89. tool.tips.toLowerCase().includes(key)
  90. );
  91. }
  92. // 分类过滤,在所有视图下生效
  93. if (this.currentCategory) {
  94. const category = TOOL_CATEGORIES.find(c => c.key === this.currentCategory);
  95. const categoryTools = category ? category.tools : [];
  96. result = result.filter(tool => categoryTools.includes(tool.key));
  97. }
  98. // 排序
  99. switch (this.sortType) {
  100. case 'newest':
  101. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  102. break;
  103. case 'hot':
  104. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  105. break;
  106. default:
  107. const allTools = TOOL_CATEGORIES.reduce((acc, category) => {
  108. acc.push(...category.tools);
  109. return acc;
  110. }, []);
  111. result.sort((a, b) => {
  112. const indexA = allTools.indexOf(a.key);
  113. const indexB = allTools.indexOf(b.key);
  114. // 如果工具不在任何类别中,放到最后
  115. if (indexA === -1 && indexB === -1) {
  116. return a.key.localeCompare(b.key); // 字母顺序排序
  117. }
  118. if (indexA === -1) return 1;
  119. if (indexB === -1) return -1;
  120. return indexA - indexB;
  121. });
  122. }
  123. return result;
  124. }
  125. },
  126. methods: {
  127. async initData() {
  128. try {
  129. this.loading = true;
  130. // 获取manifest信息
  131. const manifest = await chrome.runtime.getManifest();
  132. this.manifest = manifest;
  133. // 从 Awesome.getAllTools 获取工具列表
  134. const tools = await Awesome.getAllTools();
  135. // 获取收藏数据
  136. const favorites = await this.getFavoritesData();
  137. this.favorites = new Set(favorites);
  138. // 获取最近使用数据
  139. const recentUsed = await this.getRecentUsedData();
  140. this.recentUsed = recentUsed;
  141. this.recentCount = recentUsed.length;
  142. // 获取已安装工具列表
  143. const installedTools = await Awesome.getInstalledTools();
  144. // 处理工具数据
  145. const processedTools = {};
  146. Object.entries(tools).forEach(([key, tool]) => {
  147. // 检查工具是否已安装
  148. const isInstalled = installedTools.hasOwnProperty(key);
  149. // 检查是否有右键菜单
  150. const hasMenu = tool.menu || false;
  151. processedTools[key] = {
  152. ...tool,
  153. key, // 添加key到工具对象中
  154. updateTime: Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000,
  155. installed: isInstalled, // 使用实时安装状态
  156. inContextMenu: hasMenu, // 使用实时菜单状态
  157. systemInstalled: tool.systemInstalled || false, // 是否系统预装
  158. favorite: this.favorites.has(key)
  159. };
  160. });
  161. this.originalTools = processedTools;
  162. // 初始化activeTools为所有工具
  163. this.activeTools = { ...processedTools };
  164. // 更新"其他工具"类别
  165. this.updateOtherCategory(Object.keys(processedTools));
  166. // 默认选中"全部分类"
  167. this.currentCategory = '';
  168. } catch (error) {
  169. console.error('初始化数据失败:', error);
  170. } finally {
  171. this.loading = false;
  172. }
  173. },
  174. // 更新"其他工具"类别,将未分类的工具添加到此类别
  175. updateOtherCategory(allToolKeys) {
  176. // 获取所有已分类的工具
  177. const categorizedTools = new Set();
  178. TOOL_CATEGORIES.forEach(category => {
  179. if (category.key !== 'other') {
  180. category.tools.forEach(tool => categorizedTools.add(tool));
  181. }
  182. });
  183. // 找出未分类的工具
  184. const uncategorizedTools = allToolKeys.filter(key => !categorizedTools.has(key));
  185. // 更新"其他工具"类别
  186. const otherCategory = TOOL_CATEGORIES.find(category => category.key === 'other');
  187. if (otherCategory) {
  188. otherCategory.tools = uncategorizedTools;
  189. }
  190. },
  191. // 检查版本更新
  192. async checkVersionUpdate() {
  193. try {
  194. // 获取已安装的版本号
  195. const currentVersion = this.manifest.version;
  196. // 尝试从本地存储获取最新版本信息,避免频繁请求
  197. const cachedData = await new Promise(resolve => {
  198. chrome.storage.local.get('fehelper_latest_version_data', data => {
  199. resolve(data.fehelper_latest_version_data || null);
  200. });
  201. });
  202. // 检查是否需要重新获取版本信息:
  203. // 1. 缓存不存在
  204. // 2. 缓存已过期(超过24小时)
  205. // 3. 缓存的当前版本与实际版本不同(说明插件已更新)
  206. const now = Date.now();
  207. const cacheExpired = !cachedData || !cachedData.timestamp || (now - cachedData.timestamp > 24 * 60 * 60 * 1000);
  208. const versionChanged = cachedData && cachedData.currentVersion !== currentVersion;
  209. if (cacheExpired || versionChanged) {
  210. try {
  211. console.log('开始获取最新版本信息...');
  212. // 使用shields.io的JSON API获取最新版本号
  213. const response = await fetch('https://img.shields.io/chrome-web-store/v/pkgccpejnmalmdinmhkkfafefagiiiad.json');
  214. if (!response.ok) {
  215. throw new Error(`HTTP错误:${response.status}`);
  216. }
  217. const data = await response.json();
  218. // 提取版本号 - shields.io返回的数据中包含版本信息
  219. let latestVersion = '';
  220. if (data && data.value) {
  221. // 去掉版本号前的'v'字符(如果有)
  222. latestVersion = data.value.replace(/^v/, '');
  223. console.log('获取到最新版本号:', latestVersion);
  224. }
  225. // 比较版本号
  226. const needUpdate = this.compareVersions(currentVersion, latestVersion) < 0;
  227. console.log('当前版本:', currentVersion, '最新版本:', latestVersion, '需要更新:', needUpdate);
  228. // 保存到本地存储中
  229. await chrome.storage.local.set({
  230. 'fehelper_latest_version_data': {
  231. timestamp: now,
  232. currentVersion, // 保存当前检查时的版本号
  233. latestVersion,
  234. needUpdate
  235. }
  236. });
  237. this.latestVersion = latestVersion;
  238. this.needUpdate = needUpdate;
  239. } catch (fetchError) {
  240. console.error('获取最新版本信息失败:', fetchError);
  241. // 获取失败时不显示更新按钮
  242. this.needUpdate = false;
  243. // 如果是版本变更导致的重新检查,但获取失败,则使用缓存数据
  244. if (versionChanged && cachedData) {
  245. this.latestVersion = cachedData.latestVersion || '';
  246. // 比较新的currentVersion和缓存的latestVersion
  247. this.needUpdate = this.compareVersions(currentVersion, cachedData.latestVersion) < 0;
  248. }
  249. }
  250. } else {
  251. // 使用缓存数据
  252. console.log('使用缓存的版本信息');
  253. this.latestVersion = cachedData.latestVersion || '';
  254. this.needUpdate = cachedData.needUpdate || false;
  255. }
  256. } catch (error) {
  257. console.error('检查版本更新失败:', error);
  258. this.needUpdate = false; // 出错时不显示更新提示
  259. }
  260. },
  261. // 比较版本号:如果v1 < v2返回-1,v1 = v2返回0,v1 > v2返回1
  262. compareVersions(v1, v2) {
  263. // 将版本号拆分为数字数组
  264. const v1Parts = v1.split('.').map(Number);
  265. const v2Parts = v2.split('.').map(Number);
  266. // 计算两个版本号中较长的长度
  267. const maxLength = Math.max(v1Parts.length, v2Parts.length);
  268. // 比较每一部分
  269. for (let i = 0; i < maxLength; i++) {
  270. // 获取当前部分,如果不存在则视为0
  271. const part1 = v1Parts[i] || 0;
  272. const part2 = v2Parts[i] || 0;
  273. // 比较当前部分
  274. if (part1 < part2) return -1;
  275. if (part1 > part2) return 1;
  276. }
  277. // 所有部分都相等
  278. return 0;
  279. },
  280. // 打开Chrome商店页面
  281. openStorePage() {
  282. try {
  283. console.log('开始请求检查更新...');
  284. // 使用Chrome Extension API请求检查更新
  285. // Manifest V3中requestUpdateCheck返回Promise,结果是一个对象而不是数组
  286. chrome.runtime.requestUpdateCheck().then(result => {
  287. // 正确获取status和details,它们是result对象的属性
  288. console.log('更新检查结果:', result);
  289. const status = result.status;
  290. const details = result.details;
  291. console.log('更新检查状态:', status, '详情:', details);
  292. this.handleUpdateStatus(status, details);
  293. }).catch(error => {
  294. console.error('更新检查失败:', error);
  295. this.handleUpdateError(error);
  296. });
  297. } catch (error) {
  298. console.error('请求更新出错:', error);
  299. this.handleUpdateError(error);
  300. }
  301. },
  302. // 处理更新状态
  303. handleUpdateStatus(status, details) {
  304. console.log(`处理更新状态: ${status}`, details);
  305. if (status === 'update_available') {
  306. console.log('发现更新:', details);
  307. // 显示更新通知
  308. this.showNotification({
  309. title: 'FeHelper 更新',
  310. message: '已发现新版本,正在更新...'
  311. });
  312. // 重新加载扩展以应用更新
  313. setTimeout(() => {
  314. console.log('重新加载扩展...');
  315. chrome.runtime.reload();
  316. }, 1000);
  317. } else if (status === 'no_update') {
  318. // 如果没有可用更新,但用户点击了更新按钮
  319. this.showNotification({
  320. title: 'FeHelper 更新',
  321. message: '您的FeHelper已经是最新版本。'
  322. });
  323. } else {
  324. // 其他情况,如更新检查失败等
  325. console.log('其他更新状态:', status);
  326. // 备选方案:跳转到官方网站
  327. chrome.tabs.create({
  328. url: 'https://baidufe.com/fehelper'
  329. });
  330. this.showNotification({
  331. title: 'FeHelper 更新',
  332. message: '自动更新失败,请访问FeHelper官网手动获取最新版本。'
  333. });
  334. }
  335. },
  336. // 处理更新错误
  337. handleUpdateError(error) {
  338. console.error('更新过程中出错:', error);
  339. // 出错时跳转到官方网站
  340. chrome.tabs.create({
  341. url: 'https://baidufe.com/fehelper'
  342. });
  343. this.showNotification({
  344. title: 'FeHelper 更新错误',
  345. message: '更新过程中出现错误,请手动检查更新。'
  346. });
  347. },
  348. // 显示通知的统一方法
  349. showNotification(options) {
  350. try {
  351. console.log('准备显示通知:', options);
  352. // 定义通知ID,方便后续关闭
  353. const notificationId = 'fehelper-update-notification';
  354. const simpleNotificationId = 'fehelper-simple-notification';
  355. // 直接尝试创建通知,不检查权限
  356. // Chrome扩展在manifest中已声明notifications权限,应该可以直接使用
  357. const notificationOptions = {
  358. type: 'basic',
  359. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  360. title: options.title || 'FeHelper',
  361. message: options.message || '',
  362. priority: 2,
  363. requireInteraction: false, // 改为false,因为我们会手动关闭
  364. silent: false // 播放音效
  365. };
  366. console.log('通知选项:', notificationOptions);
  367. // 首先尝试直接创建通知
  368. chrome.notifications.create(notificationId, notificationOptions, (createdId) => {
  369. const error = chrome.runtime.lastError;
  370. if (error) {
  371. console.error('创建通知出错:', error);
  372. // 通知创建失败,尝试使用alert作为备选方案
  373. alert(`${options.title}: ${options.message}`);
  374. // 再尝试使用不同的选项创建通知
  375. const simpleOptions = {
  376. type: 'basic',
  377. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  378. title: options.title || 'FeHelper',
  379. message: options.message || ''
  380. };
  381. // 使用简化选项再次尝试
  382. chrome.notifications.create(simpleNotificationId, simpleOptions, (simpleId) => {
  383. if (chrome.runtime.lastError) {
  384. console.error('简化通知创建也失败:', chrome.runtime.lastError);
  385. } else {
  386. console.log('简化通知已创建,ID:', simpleId);
  387. // 3秒后自动关闭简化通知
  388. setTimeout(() => {
  389. chrome.notifications.clear(simpleId, (wasCleared) => {
  390. console.log('简化通知已关闭:', wasCleared);
  391. });
  392. }, 3000);
  393. }
  394. });
  395. } else {
  396. console.log('通知已成功创建,ID:', createdId);
  397. // 3秒后自动关闭通知
  398. setTimeout(() => {
  399. chrome.notifications.clear(createdId, (wasCleared) => {
  400. console.log('通知已关闭:', wasCleared);
  401. });
  402. }, 3000);
  403. }
  404. });
  405. // 同时使用内置UI显示消息
  406. this.showInPageNotification(options);
  407. } catch (error) {
  408. console.error('显示通知时出错:', error);
  409. // 降级为alert
  410. alert(`${options.title}: ${options.message}`);
  411. }
  412. },
  413. // 在页面内显示通知消息
  414. showInPageNotification(options) {
  415. try {
  416. // 创建一个通知元素
  417. const notificationEl = document.createElement('div');
  418. notificationEl.className = 'in-page-notification';
  419. notificationEl.innerHTML = `
  420. <div class="notification-content">
  421. <div class="notification-title">${options.title || 'FeHelper'}</div>
  422. <div class="notification-message">${options.message || ''}</div>
  423. </div>
  424. <button class="notification-close">×</button>
  425. `;
  426. // 添加样式
  427. const style = document.createElement('style');
  428. style.textContent = `
  429. .in-page-notification {
  430. position: fixed;
  431. bottom: 20px;
  432. right: 20px;
  433. background-color: #4285f4;
  434. color: white;
  435. padding: 15px;
  436. border-radius: 8px;
  437. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  438. z-index: 9999;
  439. display: flex;
  440. align-items: center;
  441. justify-content: space-between;
  442. min-width: 300px;
  443. animation: slideIn 0.3s ease-out;
  444. }
  445. .notification-content {
  446. flex: 1;
  447. }
  448. .notification-title {
  449. font-weight: bold;
  450. margin-bottom: 5px;
  451. }
  452. .notification-message {
  453. font-size: 14px;
  454. }
  455. .notification-close {
  456. background: none;
  457. border: none;
  458. color: white;
  459. font-size: 20px;
  460. cursor: pointer;
  461. margin-left: 10px;
  462. padding: 0 5px;
  463. }
  464. @keyframes slideIn {
  465. from { transform: translateX(100%); opacity: 0; }
  466. to { transform: translateX(0); opacity: 1; }
  467. }
  468. @keyframes slideOut {
  469. from { transform: translateX(0); opacity: 1; }
  470. to { transform: translateX(100%); opacity: 0; }
  471. }
  472. `;
  473. // 添加到页面
  474. document.head.appendChild(style);
  475. document.body.appendChild(notificationEl);
  476. // 点击关闭按钮移除通知
  477. const closeBtn = notificationEl.querySelector('.notification-close');
  478. if (closeBtn) {
  479. closeBtn.addEventListener('click', () => {
  480. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  481. notificationEl.addEventListener('animationend', () => {
  482. notificationEl.remove();
  483. });
  484. });
  485. }
  486. // 3秒后自动移除(从5秒改为3秒)
  487. setTimeout(() => {
  488. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  489. notificationEl.addEventListener('animationend', () => {
  490. notificationEl.remove();
  491. });
  492. }, 3000);
  493. console.log('页内通知已显示,将在3秒后自动关闭');
  494. } catch (error) {
  495. console.error('创建页内通知出错:', error);
  496. }
  497. },
  498. async getFavoritesData() {
  499. return new Promise((resolve) => {
  500. chrome.storage.local.get('favorites', (result) => {
  501. resolve(result.favorites || []);
  502. });
  503. });
  504. },
  505. async getRecentUsedData() {
  506. // 直接从Statistics模块获取最近使用的工具
  507. return await Statistics.getRecentUsedTools(10);
  508. },
  509. async saveFavorites() {
  510. try {
  511. await chrome.storage.local.set({
  512. favorites: Array.from(this.favorites)
  513. });
  514. // 更新工具的收藏状态
  515. Object.keys(this.originalTools).forEach(key => {
  516. this.originalTools[key].favorite = this.favorites.has(key);
  517. });
  518. } catch (error) {
  519. console.error('保存收藏失败:', error);
  520. }
  521. },
  522. handleSearch() {
  523. // 搜索时不重置视图类型,允许在已过滤的结果中搜索
  524. },
  525. handleCategoryChange(category) {
  526. // 切换到全部工具视图
  527. if (this.currentView !== 'all') {
  528. this.currentView = 'all';
  529. this.updateActiveTools('all');
  530. }
  531. this.currentCategory = category;
  532. this.searchKey = '';
  533. // 确保工具显示正确
  534. this.activeTools = { ...this.originalTools };
  535. },
  536. handleSort() {
  537. // 排序逻辑已在computed中实现
  538. },
  539. getCategoryCount(categoryKey) {
  540. const category = TOOL_CATEGORIES.find(c => c.key === categoryKey);
  541. const categoryTools = category ? category.tools : [];
  542. return categoryTools.length;
  543. },
  544. async getInstalledCount() {
  545. try {
  546. // 使用Awesome.getInstalledTools实时获取已安装工具数量
  547. const installedTools = await Awesome.getInstalledTools();
  548. return Object.keys(installedTools).length;
  549. } catch (error) {
  550. console.error('获取已安装工具数量失败:', error);
  551. // 回退到本地数据
  552. return Object.values(this.originalTools).filter(tool =>
  553. tool.installed || tool.systemInstalled || false
  554. ).length;
  555. }
  556. },
  557. getFavoritesCount() {
  558. return this.favorites.size;
  559. },
  560. getToolCategory(toolKey) {
  561. for (const category of TOOL_CATEGORIES) {
  562. if (category.tools.includes(toolKey)) {
  563. return category.key;
  564. }
  565. }
  566. return 'other';
  567. },
  568. async showMyInstalled() {
  569. this.currentView = 'installed';
  570. this.currentCategory = '';
  571. this.searchKey = '';
  572. await this.updateActiveTools('installed');
  573. // 更新已安装工具数量
  574. await this.updateInstalledCount();
  575. },
  576. showMyFavorites() {
  577. this.currentView = 'favorites';
  578. this.currentCategory = '';
  579. this.searchKey = '';
  580. this.updateActiveTools('favorites');
  581. },
  582. async showRecentUsed() {
  583. this.currentView = 'recent';
  584. this.currentCategory = '';
  585. this.searchKey = '';
  586. // 实时获取最近使用
  587. this.recentUsed = await Statistics.getRecentUsedTools(10);
  588. this.recentCount = this.recentUsed.length;
  589. await this.updateActiveTools('recent');
  590. },
  591. // 重置工具列表到原始状态
  592. resetTools() {
  593. this.currentView = 'all';
  594. },
  595. // 安装工具
  596. async installTool(toolKey) {
  597. try {
  598. // 查找可能存在的按钮元素
  599. const btnElement = document.querySelector(`button[data-tool="${toolKey}"]`);
  600. let elProgress = null;
  601. // 如果是通过按钮点击调用的,获取进度条元素
  602. if (btnElement) {
  603. if (btnElement.getAttribute('data-undergoing') === '1') {
  604. return false;
  605. }
  606. btnElement.setAttribute('data-undergoing', '1');
  607. elProgress = btnElement.querySelector('span.x-progress');
  608. }
  609. // 显示安装进度
  610. let pt = 1;
  611. await Awesome.install(toolKey);
  612. // 只有当进度条元素存在时才更新文本内容
  613. if (elProgress) {
  614. elProgress.textContent = `(${pt}%)`;
  615. let ptInterval = setInterval(() => {
  616. elProgress.textContent = `(${pt}%)`;
  617. pt += Math.floor(Math.random() * 20);
  618. if(pt > 100) {
  619. clearInterval(ptInterval);
  620. elProgress.textContent = ``;
  621. // 在进度条完成后显示安装成功的通知
  622. this.showInPageNotification({
  623. message: `${this.originalTools[toolKey].name} 安装成功!`,
  624. type: 'success',
  625. duration: 3000
  626. });
  627. }
  628. }, 100);
  629. } else {
  630. // 如果没有进度条元素,直接显示通知
  631. this.showInPageNotification({
  632. message: `${this.originalTools[toolKey].name} 安装成功!`,
  633. type: 'success',
  634. duration: 3000
  635. });
  636. }
  637. // 更新原始数据和当前活动数据
  638. this.originalTools[toolKey].installed = true;
  639. if (this.activeTools[toolKey]) {
  640. this.activeTools[toolKey].installed = true;
  641. }
  642. // 更新已安装工具数量
  643. this.updateInstalledCount();
  644. // 如果按钮存在,更新其状态
  645. if (btnElement) {
  646. btnElement.setAttribute('data-undergoing', '0');
  647. }
  648. // 发送消息通知后台更新
  649. chrome.runtime.sendMessage({
  650. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  651. toolName: toolKey,
  652. action: 'install',
  653. showTips: true
  654. });
  655. } catch (error) {
  656. console.error('安装工具失败:', error);
  657. // 显示安装失败的通知
  658. this.showInPageNotification({
  659. message: `安装失败:${error.message || '未知错误'}`,
  660. type: 'error',
  661. duration: 5000
  662. });
  663. }
  664. },
  665. // 卸载工具
  666. async uninstallTool(toolKey) {
  667. try {
  668. // 使用自定义确认对话框而非浏览器原生的confirm
  669. this.showConfirm({
  670. title: '卸载确认',
  671. message: `确定要卸载"${this.originalTools[toolKey].name}"工具吗?`,
  672. callback: async (key) => {
  673. try {
  674. await chrome.runtime.sendMessage({
  675. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  676. toolName: key,
  677. action: 'offload',
  678. showTips: true
  679. });
  680. // 调用Awesome.offLoad卸载工具
  681. await Awesome.offLoad(key);
  682. // 更新原始数据和当前活动数据
  683. this.originalTools[key].installed = false;
  684. this.originalTools[key].inContextMenu = false;
  685. if (this.activeTools[key]) {
  686. this.activeTools[key].installed = false;
  687. this.activeTools[key].inContextMenu = false;
  688. }
  689. // 更新已安装工具数量
  690. this.updateInstalledCount();
  691. // 显示卸载成功的通知
  692. this.showInPageNotification({
  693. message: `${this.originalTools[key].name} 已成功卸载!`,
  694. type: 'success',
  695. duration: 3000
  696. });
  697. } catch (error) {
  698. console.error('卸载工具失败:', error);
  699. // 显示卸载失败的通知
  700. this.showInPageNotification({
  701. message: `卸载失败:${error.message || '未知错误'}`,
  702. type: 'error',
  703. duration: 5000
  704. });
  705. }
  706. },
  707. data: toolKey
  708. });
  709. } catch (error) {
  710. console.error('准备卸载过程中出错:', error);
  711. }
  712. },
  713. // 切换右键菜单
  714. async toggleContextMenu(toolKey) {
  715. try {
  716. const tool = this.originalTools[toolKey];
  717. const newState = !tool.inContextMenu;
  718. // 更新菜单状态
  719. await Awesome.menuMgr(toolKey, newState ? 'install' : 'offload');
  720. // 更新原始数据和当前活动数据
  721. tool.inContextMenu = newState;
  722. if (this.activeTools[toolKey]) {
  723. this.activeTools[toolKey].inContextMenu = newState;
  724. }
  725. // 发送消息通知后台更新右键菜单
  726. chrome.runtime.sendMessage({
  727. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  728. action: `menu-${newState ? 'install' : 'offload'}`,
  729. showTips: false,
  730. menuOnly: true
  731. });
  732. } catch (error) {
  733. console.error('切换右键菜单失败:', error);
  734. }
  735. },
  736. // 切换收藏状态
  737. async toggleFavorite(toolKey) {
  738. try {
  739. if (this.favorites.has(toolKey)) {
  740. this.favorites.delete(toolKey);
  741. // 更新原始数据和当前活动数据
  742. this.originalTools[toolKey].favorite = false;
  743. if (this.activeTools[toolKey]) {
  744. this.activeTools[toolKey].favorite = false;
  745. }
  746. } else {
  747. this.favorites.add(toolKey);
  748. // 更新原始数据和当前活动数据
  749. this.originalTools[toolKey].favorite = true;
  750. if (this.activeTools[toolKey]) {
  751. this.activeTools[toolKey].favorite = true;
  752. }
  753. }
  754. await this.saveFavorites();
  755. // 如果是在收藏视图,需要更新视图
  756. if (this.currentView === 'favorites') {
  757. this.updateActiveTools('favorites');
  758. }
  759. } catch (error) {
  760. console.error('切换收藏状态失败:', error);
  761. }
  762. },
  763. async updateActiveTools(view) {
  764. if (this.loading || Object.keys(this.originalTools).length === 0) {
  765. return;
  766. }
  767. switch (view) {
  768. case 'installed':
  769. // 使用Awesome.getInstalledTools实时获取已安装工具
  770. try {
  771. const installedTools = await Awesome.getInstalledTools();
  772. // 合并installedTools与originalTools的数据
  773. this.activeTools = Object.fromEntries(
  774. Object.entries(this.originalTools).filter(([key]) =>
  775. installedTools.hasOwnProperty(key)
  776. )
  777. );
  778. } catch (error) {
  779. console.error('获取已安装工具失败:', error);
  780. // 回退到本地数据
  781. this.activeTools = Object.fromEntries(
  782. Object.entries(this.originalTools).filter(([_, tool]) =>
  783. tool.installed || tool.systemInstalled || false
  784. )
  785. );
  786. }
  787. break;
  788. case 'favorites':
  789. this.activeTools = Object.fromEntries(
  790. Object.entries(this.originalTools).filter(([key]) => this.favorites.has(key))
  791. );
  792. break;
  793. case 'recent':
  794. // 切换recent时,recentUsed已在showRecentUsed中实时拉取
  795. this.activeTools = Object.fromEntries(
  796. Object.entries(this.originalTools).filter(([key]) => this.recentUsed.includes(key))
  797. );
  798. break;
  799. case 'all':
  800. default:
  801. this.activeTools = { ...this.originalTools };
  802. // 分类过滤在computed属性中处理
  803. break;
  804. }
  805. },
  806. // 新增更新已安装工具数量的方法
  807. async updateInstalledCount() {
  808. this.installedCount = await this.getInstalledCount();
  809. },
  810. // 加载用户保存的视图模式
  811. async loadViewMode() {
  812. try {
  813. const result = await new Promise(resolve => {
  814. chrome.storage.local.get('fehelper_view_mode', result => {
  815. resolve(result.fehelper_view_mode);
  816. });
  817. });
  818. if (result) {
  819. this.viewMode = result;
  820. }
  821. } catch (error) {
  822. console.error('加载视图模式失败:', error);
  823. }
  824. },
  825. // 保存用户的视图模式选择
  826. async saveViewMode(mode) {
  827. try {
  828. this.viewMode = mode;
  829. await chrome.storage.local.set({
  830. 'fehelper_view_mode': mode
  831. });
  832. } catch (error) {
  833. console.error('保存视图模式失败:', error);
  834. }
  835. },
  836. // 加载设置项
  837. async loadSettings() {
  838. try {
  839. Settings.getOptions(async (opts) => {
  840. let selectedOpts = [];
  841. Object.keys(opts).forEach(key => {
  842. if(String(opts[key]) === 'true') {
  843. selectedOpts.push(key);
  844. }
  845. });
  846. this.selectedOpts = selectedOpts;
  847. // 加载右键菜单设置
  848. this.menuDownloadCrx = await Awesome.menuMgr('download-crx', 'get') === '1';
  849. this.menuFeHelperSeting = await Awesome.menuMgr('fehelper-setting', 'get') !== '0';
  850. // 获取快捷键
  851. chrome.commands.getAll((commands) => {
  852. for (let command of commands) {
  853. if (command.name === '_execute_action') {
  854. this.defaultKey = command.shortcut || 'Alt+Shift+J';
  855. break;
  856. }
  857. }
  858. });
  859. });
  860. } catch (error) {
  861. console.error('加载设置项失败:', error);
  862. }
  863. },
  864. // 检查浏览器类型
  865. checkBrowserType() {
  866. try {
  867. this.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  868. } catch (error) {
  869. console.error('检查浏览器类型失败:', error);
  870. this.isFirefox = false;
  871. }
  872. },
  873. // 显示设置模态框
  874. showSettings() {
  875. this.showSettingsModal = true;
  876. },
  877. // 关闭设置模态框
  878. closeSettings() {
  879. this.showSettingsModal = false;
  880. },
  881. // 显示打赏模态框
  882. openDonateModal() {
  883. this.showDonateModal = true;
  884. },
  885. // 关闭打赏模态框
  886. closeDonateModal() {
  887. this.showDonateModal = false;
  888. },
  889. // 显示确认对话框
  890. showConfirm(options) {
  891. this.confirmDialog = {
  892. show: true,
  893. title: options.title || '操作确认',
  894. message: options.message || '确定要执行此操作吗?',
  895. callback: options.callback || null,
  896. data: options.data || null
  897. };
  898. },
  899. // 确认操作
  900. confirmAction() {
  901. if (this.confirmDialog.callback) {
  902. this.confirmDialog.callback(this.confirmDialog.data);
  903. }
  904. this.confirmDialog.show = false;
  905. },
  906. // 取消确认
  907. cancelConfirm() {
  908. this.confirmDialog.show = false;
  909. },
  910. // 保存设置
  911. async saveSettings() {
  912. try {
  913. // 构建设置对象
  914. let opts = {};
  915. ['OPT_ITEM_CONTEXTMENUS', 'FORBID_OPEN_IN_NEW_TAB', 'CONTENT_SCRIPT_ALLOW_ALL_FRAMES',
  916. 'JSON_PAGE_FORMAT', 'AUTO_DARK_MODE', 'ALWAYS_DARK_MODE'].forEach(key => {
  917. opts[key] = this.selectedOpts.includes(key).toString();
  918. });
  919. // 保存设置 - 直接传递对象,settings.js已增加对对象类型的支持
  920. Settings.setOptions(opts, async () => {
  921. try {
  922. // 处理右键菜单
  923. const crxAction = this.menuDownloadCrx ? 'install' : 'offload';
  924. const settingAction = this.menuFeHelperSeting ? 'install' : 'offload';
  925. await Promise.all([
  926. Awesome.menuMgr('download-crx', crxAction),
  927. Awesome.menuMgr('fehelper-setting', settingAction)
  928. ]);
  929. // 通知后台更新右键菜单
  930. chrome.runtime.sendMessage({
  931. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  932. action: 'menu-change',
  933. menuOnly: true
  934. });
  935. // 关闭弹窗
  936. this.closeSettings();
  937. // 显示提示
  938. this.showNotification({
  939. title: 'FeHelper 设置',
  940. message: '设置已保存!'
  941. });
  942. } catch (innerError) {
  943. console.error('保存菜单设置失败:', innerError);
  944. this.showNotification({
  945. title: 'FeHelper 设置错误',
  946. message: '保存菜单设置失败: ' + innerError.message
  947. });
  948. }
  949. });
  950. } catch (error) {
  951. console.error('保存设置失败:', error);
  952. this.showNotification({
  953. title: 'FeHelper 设置错误',
  954. message: '保存设置失败: ' + error.message
  955. });
  956. }
  957. },
  958. // 设置快捷键
  959. setShortcuts() {
  960. chrome.tabs.create({
  961. url: 'chrome://extensions/shortcuts'
  962. });
  963. },
  964. // 体验夜间模式
  965. turnLight(event) {
  966. event.preventDefault();
  967. // 获取body元素
  968. const body = document.body;
  969. // 切换夜间模式
  970. if (body.classList.contains('dark-mode')) {
  971. body.classList.remove('dark-mode');
  972. } else {
  973. body.classList.add('dark-mode');
  974. // 设置倒计时
  975. this.countDown = 10;
  976. // 启动倒计时
  977. const timer = setInterval(() => {
  978. this.countDown--;
  979. if (this.countDown <= 0) {
  980. clearInterval(timer);
  981. body.classList.remove('dark-mode');
  982. }
  983. }, 1000);
  984. }
  985. },
  986. // 检查URL中的donate_from参数并显示打赏弹窗
  987. checkDonateParam() {
  988. try {
  989. const urlParams = new URLSearchParams(window.location.search);
  990. const donateFrom = urlParams.get('donate_from');
  991. if (donateFrom) {
  992. console.log('检测到打赏来源参数:', donateFrom);
  993. // 记录打赏来源
  994. chrome.storage.local.set({
  995. 'fehelper_donate_from': donateFrom,
  996. 'fehelper_donate_time': Date.now()
  997. });
  998. // 等待工具数据加载完成
  999. this.$nextTick(() => {
  1000. // 在所有工具中查找匹配项
  1001. let matchedTool = null;
  1002. // 首先尝试直接匹配工具key
  1003. if (this.originalTools && this.originalTools[donateFrom]) {
  1004. matchedTool = this.originalTools[donateFrom];
  1005. } else if (this.originalTools) {
  1006. // 如果没有直接匹配,尝试在所有工具中查找部分匹配
  1007. for (const [key, tool] of Object.entries(this.originalTools)) {
  1008. if (key.includes(donateFrom) || donateFrom.includes(key) ||
  1009. (tool.name && tool.name.includes(donateFrom)) ||
  1010. (donateFrom && donateFrom.includes(tool.name))) {
  1011. matchedTool = tool;
  1012. break;
  1013. }
  1014. }
  1015. }
  1016. // 更新打赏文案
  1017. if (matchedTool) {
  1018. this.donate.text = `看起来【${matchedTool.name}】工具帮助到了你,感谢你的认可!`;
  1019. } else {
  1020. // 没有匹配到特定工具,使用通用文案
  1021. this.donate.text = `感谢你对FeHelper的认可和支持!`;
  1022. }
  1023. // 显示打赏弹窗
  1024. this.showDonateModal = true;
  1025. });
  1026. }
  1027. } catch (error) {
  1028. console.error('处理打赏参数时出错:', error);
  1029. }
  1030. },
  1031. // 补充 getRecentCount,保证模板调用不报错,且数据源唯一
  1032. async getRecentCount() {
  1033. const recent = await Statistics.getRecentUsedTools(10);
  1034. return recent.length;
  1035. },
  1036. },
  1037. watch: {
  1038. // 监听currentView变化
  1039. currentView: {
  1040. immediate: true,
  1041. handler(newView) {
  1042. this.updateActiveTools(newView);
  1043. }
  1044. },
  1045. // 监听currentCategory变化
  1046. currentCategory: {
  1047. handler(newCategory) {
  1048. // 保证在视图模式之外的分类切换也能正确显示
  1049. if (this.currentView === 'all') {
  1050. this.activeTools = { ...this.originalTools };
  1051. }
  1052. // 重置搜索条件
  1053. if (this.searchKey) {
  1054. this.searchKey = '';
  1055. }
  1056. }
  1057. }
  1058. }
  1059. });
  1060. // 添加滚动事件监听
  1061. window.addEventListener('scroll', () => {
  1062. const header = document.querySelector('.market-header');
  1063. const sidebar = document.querySelector('.market-sidebar');
  1064. if (window.scrollY > 10) {
  1065. header.classList.add('scrolled');
  1066. sidebar && sidebar.classList.add('scrolled');
  1067. } else {
  1068. header.classList.remove('scrolled');
  1069. sidebar && sidebar.classList.remove('scrolled');
  1070. }
  1071. });