feat(M2.9): 图标显示开关 (v0.1.9)

- Popup 中添加'启用划词' Toggle 开关
- 开关状态保存到 chrome.storage.local
- 关闭开关后网页划词不再显示图标
- 配置管理统一封装到 src/shared/config.js
- ConfigManager 提供 get/set/onChange API
This commit is contained in:
李岩岩 2026-02-11 14:07:58 +08:00
parent 3c363a14b0
commit 725bf8fe71
9 changed files with 318 additions and 18 deletions

View File

@ -7,7 +7,7 @@
## 版本速查
### 当前版本
`0.1.8` → 下一目标 `0.1.9` ([M2.9](./M2.md))
`0.1.9` → 下一目标 `0.2.1` ([M3.1](./M3.md))
### 模块版本范围

View File

@ -65,9 +65,9 @@ M11.10完成 → 1.0.0 (正式发布)
## 当前状态
**当前版本**: `0.1.8`
**当前进度**: 13/97 (13%)
**下一任务**: [M2.9 图标显示开关](./M2.md#m29-图标显示开关--目标版本-0119)
**当前版本**: `0.1.9`
**当前进度**: 14/97 (14%)
**下一任务**: [M3.1 词典接口基类设计](./M3.md#m31-词典接口基类设计--目标版本-021)
---

View File

@ -28,7 +28,7 @@
| M2.6 | 0.1.6 | 基础面板组件 | ✅ | 2026-02-11 |
| M2.7 | 0.1.7 | 面板位置计算 | ✅ | 2026-02-09 |
| M2.8 | 0.1.8 | 图标-面板联动 | ✅ | 2026-02-09 |
| M2.9 | 0.1.9 | 图标显示开关 | ⬜ | - |
| M2.9 | 0.1.9 | 图标显示开关 | ✅ | 2026-02-09 |
---

View File

@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "沙拉查词",
"version": "0.1.8",
"version": "0.1.9",
"description": "聚合词典划词翻译",
"permissions": [
"storage",

View File

@ -1,6 +1,6 @@
{
"name": "salad-dict",
"version": "0.1.8",
"version": "0.1.9",
"description": "聚合词典划词翻译",
"private": true,
"type": "module",

View File

@ -6,6 +6,7 @@
import { logger } from './logger.js';
import { createSaladIcon } from './components/SaladIcon.js';
import { DictPanel } from './components/DictPanel.js';
import { ConfigManager, isSelectionEnabled } from '../shared/config.js';
let currentIcon = null;
let currentPanel = null;
@ -96,7 +97,14 @@ function handleMouseUp(event) {
}
// 延迟执行,等待选区完成
setTimeout(() => {
setTimeout(async () => {
// 检查划词功能是否启用
const enabled = await isSelectionEnabled();
if (!enabled) {
logger.info('Selection is disabled, skipping icon display');
return;
}
const selectedText = getSelectedText();
if (selectedText.length > 0) {
@ -192,6 +200,30 @@ function handleKeyDown(event) {
}
}
let unbindConfigListener = null;
/**
* 处理配置变更
* @param {Object} newConfig
*/
function handleConfigChange(newConfig) {
const enabled = newConfig?.general?.enableSelection ?? true;
logger.info('Config changed, selection enabled:', enabled);
// 如果禁用划词,隐藏当前图标和面板
if (!enabled) {
if (currentIcon) {
currentIcon.destroy();
currentIcon = null;
}
if (currentPanel) {
currentPanel.destroy();
currentPanel = null;
}
}
}
/**
* 初始化文本选择监听
*/
@ -206,6 +238,9 @@ export function initSelectionListener() {
document.addEventListener('click', handleDocumentClick);
}, 100);
// 监听配置变更
unbindConfigListener = ConfigManager.onChange(handleConfigChange);
logger.info('Selection listener initialized');
}
@ -216,5 +251,12 @@ export function destroySelectionListener() {
document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('click', handleDocumentClick);
document.removeEventListener('keydown', handleKeyDown);
// 取消配置监听
if (unbindConfigListener) {
unbindConfigListener();
unbindConfigListener = null;
}
logger.info('Selection listener destroyed');
}

View File

@ -5,23 +5,107 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>沙拉查词</title>
<style>
body {
* {
margin: 0;
padding: 16px;
padding: 0;
box-sizing: border-box;
}
body {
width: 400px;
min-height: 300px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
}
h1 {
margin: 0 0 16px 0;
.header {
background: #4CAF50;
color: white;
padding: 16px;
display: flex;
align-items: center;
justify-content: space-between;
}
.header h1 {
font-size: 18px;
font-weight: 500;
}
.content {
padding: 16px;
}
.setting-item {
background: white;
border-radius: 8px;
padding: 16px;
display: flex;
align-items: center;
justify-content: space-between;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.setting-label {
font-size: 14px;
color: #333;
}
/* Toggle Switch */
.toggle {
position: relative;
width: 48px;
height: 24px;
background: #ccc;
border-radius: 12px;
cursor: pointer;
transition: background 0.3s;
}
.toggle.active {
background: #4CAF50;
}
.toggle::after {
content: '';
position: absolute;
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
top: 2px;
left: 2px;
transition: transform 0.3s;
box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}
.toggle.active::after {
transform: translateX(24px);
}
.placeholder {
text-align: center;
color: #999;
margin-top: 60px;
}
</style>
</head>
<body>
<div class="header">
<h1>沙拉查词</h1>
<p>Popup 页面占位</p>
</div>
<div class="content">
<div class="setting-item">
<span class="setting-label">启用划词</span>
<div class="toggle" id="enableSelectionToggle"></div>
</div>
<div class="placeholder">
<p>在网页中划选文本即可查词</p>
</div>
</div>
<script type="module" src="./index.js"></script>
</body>
</html>

View File

@ -1,6 +1,37 @@
// Popup entry
console.log('[SaladDict] Popup opened')
import { ConfigManager } from '../shared/config.js';
document.addEventListener('DOMContentLoaded', () => {
console.log('[SaladDict] Popup DOM ready')
})
console.log('[SaladDict] Popup opened');
/**
* 初始化 Popup
*/
async function initPopup() {
const toggle = document.getElementById('enableSelectionToggle');
// 加载当前状态
const isEnabled = await ConfigManager.get('general.enableSelection', true);
// 设置开关状态
if (isEnabled) {
toggle.classList.add('active');
}
// 监听开关点击
toggle.addEventListener('click', async () => {
const newState = !toggle.classList.contains('active');
// 更新 UI
toggle.classList.toggle('active');
// 保存配置
await ConfigManager.set('general.enableSelection', newState);
console.log('[SaladDict] Selection enabled:', newState);
});
console.log('[SaladDict] Popup initialized, selection enabled:', isEnabled);
}
// DOM 就绪后初始化
document.addEventListener('DOMContentLoaded', initPopup);

143
src/shared/config.js Normal file
View File

@ -0,0 +1,143 @@
/**
* @file 配置管理模块
* @description 统一的配置读写和监听接口
*/
const STORAGE_KEY = 'salad_config';
const DEFAULT_CONFIG = {
general: {
enableSelection: true
}
};
/**
* 深度合并对象
*/
function deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
result[key] = deepMerge(result[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
return result;
}
/**
* 根据路径获取对象值
* @param {Object} obj - 对象
* @param {string} path - 路径 'general.enableSelection'
* @returns {any}
*/
function getByPath(obj, path) {
const keys = path.split('.');
let value = obj;
for (const key of keys) {
if (value === null || value === undefined) return undefined;
value = value[key];
}
return value;
}
/**
* 根据路径设置对象值
* @param {Object} obj - 对象
* @param {string} path - 路径
* @param {any} value -
*/
function setByPath(obj, path, value) {
const keys = path.split('.');
let target = obj;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (!(key in target) || typeof target[key] !== 'object') {
target[key] = {};
}
target = target[key];
}
target[keys[keys.length - 1]] = value;
}
/**
* 配置管理器
*/
export const ConfigManager = {
/**
* 获取完整配置
* @returns {Promise<Object>}
*/
async getConfig() {
try {
const result = await chrome.storage.local.get(STORAGE_KEY);
return deepMerge(DEFAULT_CONFIG, result[STORAGE_KEY] || {});
} catch (error) {
console.error('[ConfigManager] Failed to get config:', error);
return DEFAULT_CONFIG;
}
},
/**
* 保存完整配置
* @param {Object} config
*/
async saveConfig(config) {
try {
await chrome.storage.local.set({ [STORAGE_KEY]: config });
} catch (error) {
console.error('[ConfigManager] Failed to save config:', error);
}
},
/**
* 获取指定配置项
* @param {string} path - 路径 'general.enableSelection'
* @param {any} defaultValue - 默认值
* @returns {Promise<any>}
*/
async get(path, defaultValue) {
const config = await this.getConfig();
const value = getByPath(config, path);
return value !== undefined ? value : defaultValue;
},
/**
* 设置指定配置项
* @param {string} path - 路径
* @param {any} value -
*/
async set(path, value) {
const config = await this.getConfig();
setByPath(config, path, value);
await this.saveConfig(config);
},
/**
* 监听配置变更
* @param {Function} callback - 回调函数(changes, newConfig)
* @returns {Function} 取消监听的函数
*/
onChange(callback) {
const handler = (changes) => {
if (changes[STORAGE_KEY]) {
const newValue = changes[STORAGE_KEY].newValue;
const oldValue = changes[STORAGE_KEY].oldValue;
callback(newValue, oldValue);
}
};
chrome.storage.onChanged.addListener(handler);
// 返回取消监听的函数
return () => chrome.storage.onChanged.removeListener(handler);
}
};
/**
* 快速检查划词功能是否启用
* @returns {Promise<boolean>}
*/
export async function isSelectionEnabled() {
return ConfigManager.get('general.enableSelection', true);
}