market.js 50 KB

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