Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
259 lines (233 loc) · 7.95 KB
/
Copy pathbackground.js
File metadata and controls
259 lines (233 loc) · 7.95 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// Default settings
const defaultSettings = {
isActive: true,
autoStart: false,
translateOnHover: true,
keyboardShortcutActivation: false,
hoverDelay: 300,
targetLanguage: 'en',
autoDetectLanguage: true,
sourceLanguages: ['en', 'es', 'fr', 'de', 'zh', 'ru'],
translationProvider: 'google',
popupStyle: 'minimal',
popupPosition: 'cursor',
fontSize: 'medium',
showSourceLanguage: true,
activationKey: 'none',
useSystemNotifications: false
};
// Initialize settings
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.get(Object.keys(defaultSettings), (savedSettings) => {
// Only set defaults for settings that don't exist yet
const newSettings = { ...defaultSettings };
for (const key in savedSettings) {
if (savedSettings[key] !== undefined) {
newSettings[key] = savedSettings[key];
}
}
chrome.storage.sync.set(newSettings, () => {
if (chrome.runtime.lastError) {
console.error('Failed to save initial settings:', chrome.runtime.lastError);
return;
}
// Create context menu
chrome.contextMenus.create({
id: 'translateSelection',
title: 'Translate "%s"',
contexts: ['selection']
});
// Update extension icon based on active state
updateIcon(newSettings.isActive);
// Notify all tabs about the initial state
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: 'toggleActive',
isActive: newSettings.isActive
}).catch(() => {
// Ignore errors for tabs that don't have the content script running
});
});
});
});
});
});
// Update extension icon based on active state
function updateIcon(isActive) {
const iconPath = isActive ?
{
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
} :
{
"16": "icons/icon16_disabled.png",
"48": "icons/icon48_disabled.png",
"128": "icons/icon128_disabled.png"
};
chrome.action.setIcon({ path: iconPath });
}
// Listen for messages from content script and popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'translate') {
handleTranslation(message.text, message.sourceLanguage, message.targetLanguage)
.then(result => sendResponse(result))
.catch(error => sendResponse({ error: error.message }));
return true; // Keep the message channel open for async response
}
else if (message.action === 'getSettings') {
chrome.storage.sync.get(null, (settings) => {
sendResponse(settings);
});
return true;
}
else if (message.action === 'saveSettings') {
chrome.storage.sync.set(message.settings, () => {
// Update icon if active state changed
if (message.settings.isActive !== undefined) {
updateIcon(message.settings.isActive);
}
sendResponse({ success: true });
});
return true;
}
else if (message.action === 'setActive') {
chrome.storage.sync.set({ isActive: message.isActive }, () => {
updateIcon(message.isActive);
// Send message to all tabs to update their active state
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: 'toggleActive',
isActive: message.isActive
}).catch(() => {
// Ignore errors for tabs that don't have the content script running
});
});
});
sendResponse({ success: true });
// Show notification if enabled
chrome.storage.sync.get(['useSystemNotifications'], (settings) => {
if (settings.useSystemNotifications) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title: 'CurSlate',
message: message.isActive ? 'Translation activated' : 'Translation deactivated'
});
}
});
});
return true;
}
});
// Context menu handler
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'translateSelection') {
chrome.storage.sync.get(['targetLanguage'], (settings) => {
handleTranslation(info.selectionText, 'auto', settings.targetLanguage)
.then(result => {
// Send the translation to the content script to display
chrome.tabs.sendMessage(tab.id, {
action: 'showContextMenuTranslation',
originalText: info.selectionText,
translatedText: result.translatedText,
sourceLanguage: result.detectedSourceLanguage || 'auto'
});
})
.catch(error => {
console.error('Translation error:', error);
});
});
}
});
// Handle browser action click (toolbar icon)
chrome.action.onClicked.addListener(() => {
chrome.storage.sync.get(['isActive'], (settings) => {
const newState = !settings.isActive;
chrome.storage.sync.set({ isActive: newState }, () => {
updateIcon(newState);
// Send message to all tabs to update their active state
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: 'toggleActive',
isActive: newState
}).catch(() => {
// Ignore errors for tabs that don't have the content script running
});
});
});
// Show notification if enabled
chrome.storage.sync.get(['useSystemNotifications'], (settings) => {
if (settings.useSystemNotifications) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title: 'CurSlate',
message: newState ? 'Translation activated' : 'Translation deactivated'
});
}
});
});
});
});
// Import ARML translation service
const { translateText } = require('./translate');
// Translation handler function with rate limiting and improved error handling
let lastTranslationTime = 0;
const MIN_TRANSLATION_INTERVAL = 500; // Minimum time between translations in ms
async function handleTranslation(text, sourceLanguage, targetLanguage) {
if (!text || text.trim() === '') {
return { error: 'No text to translate' };
}
// Placeholder for new translation service implementation
return { error: 'Translation service not implemented yet' };
// Rate limiting
const now = Date.now();
const timeSinceLastTranslation = now - lastTranslationTime;
if (timeSinceLastTranslation < MIN_TRANSLATION_INTERVAL) {
await new Promise(resolve => setTimeout(resolve, MIN_TRANSLATION_INTERVAL - timeSinceLastTranslation));
}
lastTranslationTime = Date.now();
try {
const result = await translateText(text, {
from: sourceLanguage === 'auto' ? 'auto' : sourceLanguage,
to: targetLanguage
});
// Save translation to history if it was successful
if (result.translatedText) {
saveTranslationHistory(
text,
result.translatedText,
result.detectedSourceLanguage,
targetLanguage
);
}
return result;
} catch (error) {
console.error('Translation error:', error);
return { error: error.message || 'Translation failed' };
}
}
// Save translation to history
function saveTranslationHistory(originalText, translatedText, sourceLanguage, targetLanguage) {
// Limit history to last 100 entries
chrome.storage.local.get(['translationHistory'], (result) => {
let history = result.translationHistory || [];
// Add new entry at the beginning
history.unshift({
originalText,
translatedText,
sourceLanguage,
targetLanguage,
timestamp: new Date().toISOString()
});
// Keep only the latest 100 entries
if (history.length > 100) {
history = history.slice(0, 100);
}
chrome.storage.local.set({ translationHistory: history });
});
}