Ver código fonte

market页面的最近使用,用真实历史来呈现

zxlie 5 meses atrás
pai
commit
5ed1f4c26c

+ 12 - 0
apps/background/background.js

@@ -507,6 +507,18 @@ let BgPageInstance = (function () {
                     case 'open-donate-modal':
                         chrome.gotoDonateModal(request.params.toolName);
                         break;
+                    case 'load-json-script':
+                        // 处理加载JSON格式化相关脚本的请求
+                        fetch(request.script)
+                            .then(response => response.text())
+                            .then(scriptContent => {
+                                callback && callback(scriptContent);
+                            })
+                            .catch(error => {
+                                console.error('加载脚本失败:', error);
+                                callback && callback(null);
+                            });
+                        return true; // 异步响应需要返回true
                 }
                 callback && callback(request.params);
             } else {

+ 27 - 1
apps/background/statistics.js

@@ -294,11 +294,37 @@ let Statistics = (function() {
         scheduleSyncStats();
     };
     
+    /**
+     * 获取最近使用的工具(按最近使用时间倒序,默认最近10个)
+     * @param {number} limit - 返回的最大数量
+     * @returns {Promise<string[]>} 工具名称数组
+     */
+    const getRecentUsedTools = async (limit = 10) => {
+        // 确保数据已加载
+        await loadUsageData();
+        // 收集所有日期,按新到旧排序
+        const dates = Object.keys(usageData.dailyUsage).sort((a, b) => b.localeCompare(a));
+        const toolSet = [];
+        for (const date of dates) {
+            const tools = Object.keys(usageData.dailyUsage[date].tools || {});
+            for (const tool of tools) {
+                if (!toolSet.includes(tool)) {
+                    toolSet.push(tool);
+                    if (toolSet.length >= limit) {
+                        return toolSet;
+                    }
+                }
+            }
+        }
+        return toolSet;
+    };
+    
     return {
         init,
         recordInstallation,
         recordUpdate,
-        recordToolUsage
+        recordToolUsage,
+        getRecentUsedTools
     };
 })();
 

+ 29 - 6
apps/json-format/content-script.js

@@ -14,13 +14,36 @@ window.JsonAutoFormat = (() => {
         if (location.protocol === 'chrome-extension:' || chrome.runtime && chrome.runtime.getURL) {
             url = chrome.runtime.getURL('json-format/' + filename);
         }
-        fetch(url).then(resp => resp.text()).then(jsText => {
-            if(window.evalCore && window.evalCore.getEvalInstance){
-                return window.evalCore.getEvalInstance(window)(jsText);
+        
+        // 使用chrome.runtime.sendMessage向background请求加载脚本
+        chrome.runtime.sendMessage({
+            type: 'fh-dynamic-any-thing',
+            thing: 'load-json-script',
+            script: url
+        }, (scriptContent) => {
+            if (!scriptContent) {
+                console.error('Failed to load script:', filename);
+                return;
+            }
+            
+            // 如果有evalCore则使用它
+            if (window.evalCore && window.evalCore.getEvalInstance) {
+                try {
+                    window.evalCore.getEvalInstance(window)(scriptContent);
+                } catch(e) {
+                    console.error('Failed to evaluate script using evalCore:', e);
+                }
+            } else {
+                // 创建一个函数来执行脚本
+                try {
+                    // 使用Function构造函数创建一个函数,并在当前窗口上下文中执行
+                    // 这比动态创建script元素更安全,因为它不涉及DOM操作
+                    const executeScript = new Function(scriptContent);
+                    executeScript.call(window);
+                } catch(e) {
+                    console.error('Failed to execute script:', filename, e);
+                }
             }
-            let el = document.createElement('script');
-            el.textContent = jsText;
-            document.head.appendChild(el);
         });
     };
 

+ 1 - 1
apps/options/index.html

@@ -273,7 +273,7 @@
                         </li>
                         <li @click="showRecentUsed">
                             最近使用
-                            <span class="count">({{getRecentCount()}})</span>
+                            <span class="count">({{recentCount}})</span>
                         </li>
                     </ul>
                 </div>

+ 19 - 38
apps/options/market.js

@@ -1,6 +1,7 @@
 import Awesome from '../background/awesome.js'
 import MSG_TYPE from '../static/js/common.js';
 import Settings from './settings.js';
+import Statistics from '../background/statistics.js';
 
 // 工具分类定义
 const TOOL_CATEGORIES = [
@@ -58,10 +59,13 @@ new Vue({
             callback: null,
             data: null
         },
+
+        recentCount: 0,
     },
 
     async created() {
         await this.initData();
+        this.recentCount = (await Statistics.getRecentUsedTools(10)).length;
         // 初始化后更新已安装工具数量
         this.updateInstalledCount();
         // 恢复用户的视图模式设置
@@ -157,6 +161,7 @@ new Vue({
                 // 获取最近使用数据
                 const recentUsed = await this.getRecentUsedData();
                 this.recentUsed = recentUsed;
+                this.recentCount = recentUsed.length;
 
                 // 获取已安装工具列表
                 const installedTools = await Awesome.getInstalledTools();
@@ -576,11 +581,8 @@ new Vue({
         },
 
         async getRecentUsedData() {
-            return new Promise((resolve) => {
-                chrome.storage.local.get('recentUsed', (result) => {
-                    resolve(result.recentUsed || []);
-                });
-            });
+            // 直接从Statistics模块获取最近使用的工具
+            return await Statistics.getRecentUsedTools(10);
         },
 
         async saveFavorites() {
@@ -597,12 +599,6 @@ new Vue({
             }
         },
 
-        async saveRecentUsed() {
-            await chrome.storage.local.set({
-                recentUsed: this.recentUsed
-            });
-        },
-
         handleSearch() {
             // 搜索时不重置视图类型,允许在已过滤的结果中搜索
         },
@@ -649,10 +645,6 @@ new Vue({
             return this.favorites.size;
         },
 
-        getRecentCount() {
-            return this.recentUsed.length;
-        },
-
         getToolCategory(toolKey) {
             for (const category of TOOL_CATEGORIES) {
                 if (category.tools.includes(toolKey)) {
@@ -678,11 +670,14 @@ new Vue({
             this.updateActiveTools('favorites');
         },
 
-        showRecentUsed() {
+        async showRecentUsed() {
             this.currentView = 'recent';
             this.currentCategory = '';
             this.searchKey = '';
-            this.updateActiveTools('recent');
+            // 实时获取最近使用
+            this.recentUsed = await Statistics.getRecentUsedTools(10);
+            this.recentCount = this.recentUsed.length;
+            await this.updateActiveTools('recent');
         },
 
         // 重置工具列表到原始状态
@@ -743,9 +738,6 @@ new Vue({
                     this.activeTools[toolKey].installed = true;
                 }
                 
-                // 添加到最近使用
-                this.addToRecentUsed(toolKey);
-                
                 // 更新已安装工具数量
                 this.updateInstalledCount();
                 
@@ -885,24 +877,6 @@ new Vue({
             }
         },
 
-        addToRecentUsed(toolKey) {
-            // 移除已存在的记录
-            const index = this.recentUsed.indexOf(toolKey);
-            if (index > -1) {
-                this.recentUsed.splice(index, 1);
-            }
-            
-            // 添加到开头
-            this.recentUsed.unshift(toolKey);
-            
-            // 限制最大记录数
-            if (this.recentUsed.length > 10) {
-                this.recentUsed.pop();
-            }
-            
-            this.saveRecentUsed();
-        },
-
         async updateActiveTools(view) {
             if (this.loading || Object.keys(this.originalTools).length === 0) {
                 return;
@@ -935,6 +909,7 @@ new Vue({
                     );
                     break;
                 case 'recent':
+                    // 切换recent时,recentUsed已在showRecentUsed中实时拉取
                     this.activeTools = Object.fromEntries(
                         Object.entries(this.originalTools).filter(([key]) => this.recentUsed.includes(key))
                     );
@@ -1205,6 +1180,12 @@ new Vue({
                 console.error('处理打赏参数时出错:', error);
             }
         },
+
+        // 补充 getRecentCount,保证模板调用不报错,且数据源唯一
+        async getRecentCount() {
+            const recent = await Statistics.getRecentUsedTools(10);
+            return recent.length;
+        },
     },
 
     watch: {