-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.ts
More file actions
175 lines (156 loc) · 5.67 KB
/
background.ts
File metadata and controls
175 lines (156 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { MessageSchema } from "@/schemas";
import { ACTIONS, DEFAULT_CONTEXT_MENU_ITEMS, STORAGE_KEYS } from "@/constants";
import { getActiveAiProviderConfig, getStorageData, sendContentMessageToTab } from "@/utils";
import { createAiProvider } from "@/data";
const commonInstruction =
"Format your response in markdown. Use markdown features where appropriate to improve readability making it clear and well-structured. Don't say 'Here's a ...' or anything like that. Just return the text.";
const getCustomContextMenuItems = async () => {
try {
const res = await getStorageData([STORAGE_KEYS.CUSTOM_CONTEXT_MENU_ITEMS]);
if (!res.success) return [];
return res.data[STORAGE_KEYS.CUSTOM_CONTEXT_MENU_ITEMS] || [];
} catch (error) {
console.log("Error loading custom menu items:", error);
return [];
}
};
const createContextMenu = async () => {
// Clear existing menu items
await browser.contextMenus.removeAll();
// Create parent menu
browser.contextMenus.create({
id: "ait-context-menu",
title: browser.runtime.getManifest().name,
contexts: ["selection"],
});
// Add default menu items
DEFAULT_CONTEXT_MENU_ITEMS.forEach((item) => {
browser.contextMenus.create({
id: item.id,
parentId: "ait-context-menu",
title: item.title,
contexts: ["selection"],
});
});
// Add custom menu items
const customContextMenuItems = await getCustomContextMenuItems();
if (customContextMenuItems.length > 0) {
// Add separator
browser.contextMenus.create({
id: "ait-custom-context-menu-separator",
parentId: "ait-context-menu",
type: "separator",
contexts: ["selection"],
});
customContextMenuItems.forEach((item) => {
browser.contextMenus.create({
id: item.id,
parentId: "ait-context-menu",
title: item.title,
contexts: ["selection"],
});
});
}
browser.contextMenus.create({
id: "ait-add-custom-instruction-separator",
parentId: "ait-context-menu",
type: "separator",
contexts: ["selection"],
});
browser.contextMenus.create({
id: "ait-add-custom-instruction",
parentId: "ait-context-menu",
title: "✨ Add custom instruction...",
contexts: ["selection"],
});
};
browser.runtime.onInstalled.addListener(createContextMenu);
browser.storage.onChanged.addListener((changes) => {
if (changes[STORAGE_KEYS.CUSTOM_CONTEXT_MENU_ITEMS]) createContextMenu();
});
browser.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.selectionText && tab?.id) {
// Handle custom instructions menu item
if (info.menuItemId === "ait-add-custom-instruction") {
browser.runtime.openOptionsPage();
// Send a message to the options page to switch to the "Context Menu Items" tab
setTimeout(() => {
browser.runtime.sendMessage({ action: ACTIONS.SWITCH_TO_CONTEXT_MENU_ITEMS_OPTIONS_TAB });
}, 100);
return;
}
// Check default menu items first
try {
const contextMenuItems = [
...DEFAULT_CONTEXT_MENU_ITEMS,
...(await getCustomContextMenuItems()),
];
const contextMenuItem = contextMenuItems.find((item) => item.id === info.menuItemId);
if (contextMenuItem) {
sendContentMessageToTab(tab.id, {
action: ACTIONS.PROCESS_TEXT,
operation: contextMenuItem.title,
originalText: info.selectionText,
instruction: contextMenuItem.instruction + " " + commonInstruction,
instructionType: contextMenuItem.id,
});
return;
}
} catch (error) {
console.log("Error handling custom menu item:", error);
}
}
});
let abortController: AbortController | null = null;
let debounceTimeout: ReturnType<typeof setTimeout> | null = null;
// Listen for messages from content script
browser.runtime.onMessage.addListener((message: unknown, sender) => {
try {
const { success, data } = MessageSchema.safeParse(message);
if (!success) throw new Error("Invalid message received");
if (data.action === ACTIONS.OPEN_SETTINGS_PAGE) {
browser.runtime.openOptionsPage();
return true;
}
if (data.action === ACTIONS.CALL_AI_API && sender.tab?.id) {
if (debounceTimeout) clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(async () => {
abortController?.abort();
abortController = new AbortController();
const tabId = sender.tab?.id;
if (!tabId) return;
try {
const config = await getActiveAiProviderConfig();
const result = await createAiProvider(config.type, config).callApi(
data.originalText,
data.instruction,
abortController?.signal
);
sendContentMessageToTab(tabId, {
action: ACTIONS.SHOW_PROCESSED_TEXT,
operation: data.operation,
result,
originalText: data.originalText,
instruction: data.instruction,
instructionType: data.instructionType,
});
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
console.log("Error getting active AI provider config:", error);
const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";
sendContentMessageToTab(tabId, {
action: ACTIONS.MODAL_SHOW_ERROR,
error: errorMessage,
instructionType: data.instructionType,
instruction: data.instruction,
operation: data.operation,
originalText: data.originalText,
});
}
}, 300);
}
} catch (error) {
console.log("Invalid message received:", error);
}
return true;
});