refactor: declarative context-menu registry; named selection threshold

CONTEXT_MENU_ENTRIES maps every menu id to {action, style, parentId,
title}, replacing the split('-') id parsing that only worked because no
name contained a hyphen. Foreign menu ids are now ignored explicitly.
Parity pinned by tests enumerating all 30 previous ids. The 10-char
toolbar trigger threshold is now the named MIN_SELECTION_LENGTH.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
john kevin asprec
2026-07-14 21:44:16 +08:00
parent f0962471b4
commit d0c4cc947d
4 changed files with 100 additions and 21 deletions

View File

@@ -1,6 +1,6 @@
import { defineBackground } from 'wxt/utils/define-background';
import type { AnalyzePayload, LexAIConfig, LexAIResponse } from '@lib/types';
import { ACTIONS, ACTION_LABELS, CONTEXT_MENU_STYLES } from '@lib/actions';
import { CONTEXT_MENU_ENTRIES, findContextMenuEntry } from '@lib/actions';
import { decryptApiKey } from '@lib/crypto';
import { callProvider, getSystemPrompt, listModels } from '@lib/providers';
@@ -40,35 +40,26 @@ export default defineBackground(() => {
// ─── Context menus ───────────────────────────────────────────────────────
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(() => {
ACTIONS.forEach(action => {
CONTEXT_MENU_ENTRIES.forEach((entry) => {
chrome.contextMenus.create({
id: `lexai-${action}`,
title: `⚡ LexAI: ${ACTION_LABELS[action]}`,
id: entry.id,
parentId: entry.parentId,
title: entry.title,
contexts: ['selection'],
});
CONTEXT_MENU_STYLES.forEach(style => {
chrome.contextMenus.create({
id: `lexai-${action}-${style.toLowerCase()}`,
parentId: `lexai-${action}`,
title: style,
contexts: ['selection'],
});
});
});
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (!info.selectionText || !tab?.id) return;
// Parse action and style from menuItemId e.g. "lexai-fix-formal"
const parts = info.menuItemId.toString().replace('lexai-', '').split('-');
const action = parts[0];
const style = parts[1] ? parts[1].charAt(0).toUpperCase() + parts[1].slice(1) : 'Default';
const entry = findContextMenuEntry(info.menuItemId.toString());
if (!entry) return;
chrome.tabs.sendMessage(tab.id, {
type: 'lexai-context-menu',
action,
action: entry.action,
text: info.selectionText,
style,
style: entry.style,
});
});