-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
315 lines (272 loc) · 10 KB
/
Copy pathcontent.js
File metadata and controls
315 lines (272 loc) · 10 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"use strict";
let currentPopup = null;
let currentButton = null;
// Create message listener outside dblclick event to avoid memory leaks
let messageListener = null;
// Add input sanitization
const sanitizeInput = (text) => {
return text.replace(/[<>&'"]/g, "");
};
// Add security checks for popup creation
const createSecurePopup = (x, y) => {
const popup = document.createElement("div");
// Set fixed positioning for bottom-left corner
popup.style.position = "fixed"; // Changed from absolute
popup.style.bottom = "20px"; // Distance from bottom
popup.style.left = "20px"; // Distance from left
// Remove the dynamic x,y positioning since we're using fixed bottom-left
// popup.style.left = `${Math.max(0, Math.min(x, window.innerWidth - 300))}px`;
// popup.style.top = `${Math.max(0, Math.min(y, window.innerHeight - 200))}px`;
// Add security attributes
popup.setAttribute("data-origin", "extension");
popup.setAttribute("data-secure", "true");
return popup;
};
// Add at the top with other state variables
let currentEtymologyRequest = null;
// Add error handling helper function at the top with other functions
const handleExtensionError = (etymologyContent, button) => {
etymologyContent.classList.add("updating");
setTimeout(() => {
etymologyContent.textContent =
"Please reload your browser to continue using the extension";
etymologyContent.style.color = "#ff4444";
etymologyContent.classList.remove("updating");
}, 200);
if (button) {
setButtonLoadingState(button, false);
button.style.display = "none"; // Hide the button when extension is invalid
}
};
// Update the fetchEtymology function to handle extension invalidation
function fetchEtymology(word, etymologyContent, button) {
try {
//console.log("tf............", currentEtymologyRequest);
// Cancel any existing request
if (currentEtymologyRequest) {
chrome.runtime.sendMessage({
action: "cancelRequest",
requestId: currentEtymologyRequest,
});
}
// Generate new request ID
currentEtymologyRequest = Date.now().toString();
chrome.runtime.sendMessage(
{
action: "getPopupData",
text: word,
requestId: currentEtymologyRequest,
},
(response) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
handleExtensionError(etymologyContent, button);
return;
}
if (!response || !response.success) {
etymologyContent.classList.add("updating");
setTimeout(() => {
etymologyContent.textContent = "Error fetching etymology";
etymologyContent.classList.remove("updating");
}, 200);
console.log("tf............86", currentEtymologyRequest);
setButtonLoadingState(button, false);
return;
}
etymologyContent.classList.add("updating");
setTimeout(() => {
etymologyContent.textContent = response.etymology;
etymologyContent.classList.remove("updating");
}, 200);
console.log("tf............96", currentEtymologyRequest);
setButtonLoadingState(button, false);
}
);
} catch (error) {
if (error.message.includes("Extension context invalidated")) {
handleExtensionError(etymologyContent, button);
} else {
console.error("Unexpected error:", error);
etymologyContent.textContent = "An unexpected error occurred";
}
}
}
document.addEventListener("dblclick", (e) => {
// Remove existing popup if any
if (currentPopup) {
currentPopup.remove();
}
const selection = window.getSelection();
const selectedText = selection.toString().trim();
// Add input validation
if (!selectedText || selectedText.length > 100) return;
const sanitizedText = sanitizeInput(selectedText);
if (sanitizedText) {
// Create new popup - no need to pass mouse coordinates anymore
const popup = createSecurePopup();
popup.className = "etymology-word-popup";
// Calculate translation values from click position to final position
const clickX = e.clientX;
const clickY = e.clientY;
const finalX = 20; // left position
const finalY = window.innerHeight - 20; // bottom position
const translateX = finalX - clickX;
const translateY = finalY - clickY;
// Set CSS custom properties for the animation
popup.style.setProperty("--origin-x", `${-translateX}px`);
popup.style.setProperty("--origin-y", `${-translateY}px`);
// Create etymology content div
const etymologyDiv = document.createElement("div");
etymologyDiv.className = "etymology-content";
etymologyDiv.textContent = "Getting etymology...";
// Create button
const button = document.createElement("button");
button.textContent = "Open in Side Panel";
console.log("init disable............", button);
setButtonLoadingState(button, true); // Initially disabled while fetching popup data
currentButton = button;
button.addEventListener("click", () => {
setButtonLoadingState(button, true);
console.log("Sending openSidePanel request...");
chrome.runtime.sendMessage({
action: "openSidePanel",
word: sanitizedText,
});
});
// Remove previous listener to prevent duplicates
if (messageListener) {
chrome.runtime.onMessage.removeListener(messageListener);
}
// Create new listener for loading state updates
messageListener = (message, sender, sendResponse) => {
if (message.action === "updateLoadingStates" && currentButton) {
if (message.source === "sidepanel") {
// Add explicit handling for cancellation
if (message.cancelled) {
setButtonLoadingState(currentButton, false);
return;
}
const isAnyLoading =
message.states &&
Object.values(message.states).some((state) => state);
// Log when all data is loaded
if (!isAnyLoading && message.data) {
// console.log("✅ Side panel data fully loaded 172:", {
// etymology: message.data.etymology,
// usage: message.data.usage,
// synonyms: message.data.synonyms,
// });
//my fix
if (message.data.etymology.cancelled === true) {
setButtonLoadingState(currentButton, true);
} else {
setButtonLoadingState(currentButton, false);
}
} else {
setButtonLoadingState(currentButton, isAnyLoading);
}
if (message.error) {
// console.log("❌ Error loading side panel data:", message.error);
setButtonLoadingState(currentButton, false);
}
}
}
// Handle initial side panel open status
if (message.action === "sidePanelOpenStatus") {
// console.log(
// "🔄 Side panel opening status:",
// message.success ? "Success" : "Failed"
// );
if (!message.success) {
// console.error("Side panel failed to open:", message.error);
setButtonLoadingState(currentButton, false);
}
}
};
// Add the listener
chrome.runtime.onMessage.addListener(messageListener);
// Assemble popup
popup.appendChild(etymologyDiv);
popup.appendChild(button);
document.body.appendChild(popup);
currentPopup = popup;
const etymologyContent = popup.querySelector(".etymology-content");
fetchEtymology(selectedText, etymologyContent, button);
}
});
// Close popup and side panel when clicking outside
document.addEventListener("click", (e) => {
if (currentPopup) {
if (!currentPopup.contains(e.target)) {
currentPopup.classList.add("closing");
currentPopup.addEventListener(
"animationend",
() => {
currentPopup.remove();
currentPopup = null;
currentButton = null;
// We remove the listener here
if (messageListener && chrome.runtime?.onMessage) {
chrome.runtime.onMessage.removeListener(messageListener);
messageListener = null;
}
// And send close message
if (chrome.runtime?.id) {
chrome.runtime.sendMessage({
action: "closeSidePanel",
});
}
},
{ once: true }
);
}
} else {
// Check if chrome.runtime exists before sending message
if (chrome.runtime?.id) {
chrome.runtime.sendMessage({
action: "closeSidePanel",
});
}
}
});
/**
* Sets the loading state for the popup button
* @param {HTMLButtonElement} button - The button element to update
* @param {boolean} isLoading - Whether the button should show loading state
*/
function setButtonLoadingState(button, isLoading) {
// console.log("setButtonLoadingState............", isLoading);
button.disabled = isLoading;
button.textContent = isLoading ? "Loading data..." : "Open in Side Panel";
button.style.backgroundColor = isLoading ? "#cccccc" : "#48D1CC";
button.style.cursor = isLoading ? "not-allowed" : "pointer";
}
// Add cleanup function
function cleanup() {
if (currentPopup) {
currentPopup.remove();
currentPopup = null;
currentButton = null;
}
if (messageListener && chrome.runtime?.onMessage) {
chrome.runtime.onMessage.removeListener(messageListener);
messageListener = null;
}
}
// Add proper cleanup on unload
window.addEventListener("unload", cleanup);
function showPopup(event) {
const popup = document.createElement("div");
popup.className = "etymology-word-popup";
// Calculate translation values from click position to final position
const clickX = event.clientX;
const clickY = event.clientY;
const finalX = 20; // left position
const finalY = window.innerHeight - 20; // bottom position
const translateX = finalX - clickX;
const translateY = finalY - clickY;
// Set CSS custom properties for the animation
popup.style.setProperty("--origin-x", `${-translateX}px`);
popup.style.setProperty("--origin-y", `${-translateY}px`);
// ... rest of popup creation code ...
}