index.js 59 KB

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