-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
569 lines (492 loc) · 17.4 KB
/
content.js
File metadata and controls
569 lines (492 loc) · 17.4 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
class CodeClimaxContent {
constructor() {
this.isActive = true;
this.lastSubmissionTime = 0;
this.lastCelebrationTime = 0;
this.isShowingCelebration = false;
this.currentOverlay = null;
this.lastSuccessUrl = null;
this.submissionButtonClicked = false; // NEW: Track if user just submitted
this.init();
}
async init() {
// Check if extension is enabled
const settings = await this.getSettings();
if (!settings?.enabled) {
return;
}
// Start monitoring for successful submissions
this.monitorSubmissions();
// NEW: Listen for submit button clicks (both mouse and keyboard)
this.listenForSubmitButton();
// Listen for navigation changes
this.observePageChanges();
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'toggleExtension') {
this.isActive = request.enabled;
sendResponse({ success: true });
} else if (request.action === 'toggleApiMonitoring') {
sendResponse({ success: true });
}
});
}
async getSettings() {
try {
const result = await chrome.storage.local.get(['settings']);
return result.settings || {
enabled: true,
randomize: true,
defaultDuration: 5,
autoPlay: true,
volume: 0.5
};
} catch (error) {
console.error('Error getting settings:', error);
return null;
}
}
// NEW: Listen for submit button clicks and keyboard shortcuts
listenForSubmitButton() {
// Method 1: Listen for clicks on the Submit button
document.addEventListener('click', (event) => {
const target = event.target;
// Check if Submit button was clicked
const isSubmitButton =
target.textContent?.trim().toLowerCase() === 'submit' ||
target.getAttribute('data-e2e-locator') === 'console-submit-button' ||
target.closest('button')?.textContent?.trim().toLowerCase() === 'submit';
if (isSubmitButton) {
this.markSubmissionStarted();
}
}, true);
// Method 2: Listen for keyboard shortcuts (Cmd+Enter / Ctrl+Enter)
document.addEventListener('keydown', (event) => {
// Check for Cmd+Enter (Mac) or Ctrl+Enter (Windows/Linux)
const isSubmitShortcut =
(event.metaKey || event.ctrlKey) &&
event.key === 'Enter';
if (isSubmitShortcut) {
this.markSubmissionStarted();
}
}, true);
}
// NEW: Mark that a submission was started
markSubmissionStarted() {
this.submissionButtonClicked = true;
// Reset flag after 30 seconds (handles failed/incorrect submissions)
setTimeout(() => {
if (this.submissionButtonClicked) {
this.submissionButtonClicked = false;
}
}, 30000);
}
observePageChanges() {
// Reset state when navigating to a new problem
const currentUrl = window.location.href;
if (this.lastSuccessUrl && this.lastSuccessUrl !== currentUrl) {
this.isShowingCelebration = false;
this.currentOverlay = null;
this.submissionButtonClicked = false; // NEW: Reset submit flag on navigation
}
// Watch for URL changes (SPA navigation)
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
const detector = this;
history.pushState = function(...args) {
originalPushState.apply(this, args);
// Reset flag when navigating to prevent stale state
detector.submissionButtonClicked = false;
};
history.replaceState = function(...args) {
originalReplaceState.apply(this, args);
detector.submissionButtonClicked = false;
};
// Listen for browser back/forward
window.addEventListener('popstate', () => {
this.submissionButtonClicked = false;
if (this.isShowingCelebration) {
this.closeCurrentCelebration();
}
});
}
closeCurrentCelebration() {
if (this.currentOverlay) {
this.currentOverlay.remove();
this.currentOverlay = null;
}
this.isShowingCelebration = false;
}
monitorSubmissions() {
// Create a MutationObserver to watch for DOM changes (more efficient than polling)
const observer = new MutationObserver((mutations) => {
// Only check if there were actual node additions
const hasAddedNodes = mutations.some(mutation => mutation.addedNodes.length > 0);
if (hasAddedNodes) {
this.checkForSuccessNotification();
}
});
// Start observing the document body
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class'] // Watch for class changes (success indicators often change classes)
});
}
checkForSuccessNotification() {
// CRITICAL: Only detect if user just clicked submit
// This prevents triggering on old submissions in history
if (!this.submissionButtonClicked) {
return; // Don't detect unless user just submitted
}
if (!this.isActive || this.isShowingCelebration) return;
const now = Date.now();
// Check if extension is enabled via toggle
this.getSettings().then(settings => {
if (settings.apiMonitoringEnabled === false) {
return; // Skip if disabled by toggle
}
// Debounce - don't show multiple celebrations in quick succession
if (now - this.lastSubmissionTime < 8000) return;
// Look for various success indicators on LeetCode
const successSelectors = [
'[data-e2e-locator="submission-result"]',
'.success__3Ai7',
'[data-cy="submission-result"]',
'.text-success',
'#result-state',
'[class*="success"]',
'[class*="accepted"]'
];
let successFound = false;
for (const selector of successSelectors) {
const element = document.querySelector(selector);
if (element) {
const text = element.textContent.toLowerCase();
if (text.includes('accepted') || text.includes('success') || text.includes('passed')) {
successFound = true;
break;
}
}
}
// Check for normal problem success (specific check)
const successTag = document.querySelector('.success__3Ai7');
if (successTag && successTag.innerText.trim() === 'Success') {
successFound = true;
}
// Check for explore section success (specific check)
const resultState = document.getElementById('result-state');
if (resultState &&
resultState.className === 'text-success' &&
resultState.innerText === 'Accepted') {
successFound = true;
}
if (successFound) {
this.submissionButtonClicked = false; // Reset flag immediately
this.lastSubmissionTime = now;
this.lastSuccessUrl = window.location.href;
this.lastCelebrationTime = now;
this.showCelebration();
}
});
}
validateMedia(media) {
if (!media) {
console.error('CodeClimax: Media object is null or undefined');
return false;
}
if (!media.type || !media.data) {
console.error('CodeClimax: Media object missing required type or data property');
return false;
}
const validTypes = ['image', 'gif', 'video', 'youtube'];
if (!validTypes.includes(media.type)) {
console.error('CodeClimax: Invalid media type:', media.type);
return false;
}
if (typeof media.data !== 'string' || media.data.trim() === '') {
console.error('CodeClimax: Media data is not a valid string');
return false;
}
return true;
}
async showCelebration() {
// Don't show if already displaying a celebration
if (this.isShowingCelebration) {
return;
}
try {
this.isShowingCelebration = true;
// Check if extension context is still valid
if (!chrome.storage || !chrome.storage.local) {
console.error('CodeClimax: Extension context invalidated');
this.isShowingCelebration = false;
return;
}
const { celebrations, settings } = await chrome.storage.local.get(['celebrations', 'settings']);
// Only show user-uploaded media, skip if none available
if (!celebrations?.length) {
this.isShowingCelebration = false;
return;
}
// Filter to only user-uploaded media (exclude default celebrations)
const userUploaded = celebrations.filter(c => !c.id.startsWith('default-celebration-'));
if (userUploaded.length === 0) {
this.isShowingCelebration = false;
return;
}
let selectedMedia;
// First, check if user has specifically selected media that is user-uploaded
if (settings?.selectedMedia) {
selectedMedia = userUploaded.find(c => c.id === settings.selectedMedia);
}
// If no selected media found, prioritize favorited user-uploaded media
if (!selectedMedia) {
const favoriteUserMedia = userUploaded.find(c => c.isFavorite);
if (favoriteUserMedia) {
selectedMedia = favoriteUserMedia;
} else {
selectedMedia = userUploaded[0];
}
}
// Validate media before attempting to display
if (!this.validateMedia(selectedMedia)) {
console.error('CodeClimax: Selected media failed validation, skipping celebration');
this.isShowingCelebration = false;
return;
}
try {
this.createOverlay(selectedMedia);
} catch (overlayError) {
console.error('CodeClimax: Error creating overlay for custom media:', overlayError);
this.isShowingCelebration = false;
}
} catch (error) {
// Handle extension context invalidation gracefully
if (error.message && error.message.includes('Extension context invalidated')) {
console.error('CodeClimax: Extension context invalidated during celebration');
this.isActive = false;
this.isShowingCelebration = false;
return;
}
console.error('CodeClimax: Unexpected error showing celebration:', error);
this.isShowingCelebration = false;
}
}
showDefaultCelebration() {
// Don't show anything if no user-uploaded media is available
this.isShowingCelebration = false;
}
createOverlay(media) {
if (!media || !media.type || !media.data) {
console.error('CodeClimax: Invalid media object:', media);
throw new Error('Invalid media object');
}
// Create overlay container
const overlay = document.createElement('div');
overlay.className = 'codecclimax-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 999999;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn 0.3s ease;
background: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(5px);
`;
// Store reference to current overlay
this.currentOverlay = overlay;
// Create media container
const mediaContainer = document.createElement('div');
mediaContainer.style.cssText = `
position: relative;
z-index: 1;
max-width: 90vw;
max-height: 90vh;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0,0,0,0.5);
`;
let mediaElement = '';
switch (media.type) {
case 'image':
case 'gif':
mediaElement = `
<img
src="${media.data}"
alt="Celebration"
style="display: block; max-width: 100%; max-height: 90vh; object-fit: contain; background: #f0f0f0;"
loading="eager"
crossorigin="anonymous"
referrerpolicy="no-referrer"
onerror="this.style.display='none'; this.nextElementSibling.style.display='block';"
onload="this.style.display='block'; this.nextElementSibling.style.display='none';"
/>
<div style="display: none; padding: 20px; color: white; text-align: center; background: rgba(0,0,0,0.8); border-radius: 8px;">
<p style="margin: 0; font-size: 16px;">Failed to load celebration media</p>
<p style="margin: 10px 0 0 0; font-size: 14px; opacity: 0.7;">Please check the media URL</p>
<p style="margin: 10px 0 0 0; font-size: 12px; opacity: 0.5;">URL: ${media.data.substring(0, 50)}${media.data.length > 50 ? '...' : ''}</p>
</div>
`;
break;
case 'video':
// Check if this is an iframe embed (Vimeo) or direct video file
if (media.data.includes('player.vimeo.com') || media.data.includes('vimeo.com')) {
mediaElement = `
<iframe
src="${media.data}"
frameborder="0"
allow="autoplay; fullscreen; picture-in-picture"
allowfullscreen
style="width: 800px; height: 450px; max-width: 90vw; border: none; border-radius: 8px;"
></iframe>
`;
} else {
mediaElement = `
<video autoplay muted loop style="display: block; max-width: 100%; max-height: 90vh; object-fit: contain;">
<source src="${media.data}" type="video/mp4">
</video>
`;
}
break;
case 'youtube':
mediaElement = `
<iframe
src="https://www.youtube.com/embed/${media.data}?autoplay=1&mute=0&start=0&controls=1&rel=0&modestbranding=1"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen
style="width: 800px; height: 450px; max-width: 90vw; border: none;"
></iframe>
`;
break;
}
mediaContainer.innerHTML = mediaElement;
// Add close button positioned at top right of viewport
const closeBtn = document.createElement('button');
closeBtn.innerHTML = `
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 6L6 18M6 6l12 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;
closeBtn.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
width: 48px;
height: 48px;
border-radius: 50%;
background: rgba(0,0,0,0.6);
border: 2px solid rgba(255,255,255,0.3);
cursor: pointer;
transition: all 0.2s;
z-index: 1000000;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(10px);
`;
// Close function
const closeOverlay = (isManual = true) => {
this.isShowingCelebration = false;
this.currentOverlay = null;
if (isManual) {
// Instant removal for manual close
if (overlay.parentNode) {
overlay.remove();
}
if (style.parentNode) {
style.remove();
}
} else {
// Keep fade animation for auto-close
overlay.classList.add('fade-out');
setTimeout(() => {
if (overlay.parentNode) {
overlay.remove();
}
if (style.parentNode) {
style.remove();
}
}, 200); // Reduced from 500ms to 200ms
}
};
closeBtn.addEventListener('click', closeOverlay);
closeBtn.addEventListener('mouseenter', () => {
closeBtn.style.background = 'rgba(0,0,0,0.8)';
closeBtn.style.borderColor = 'rgba(255,255,255,0.5)';
closeBtn.style.transform = 'scale(1.1)';
});
closeBtn.addEventListener('mouseleave', () => {
closeBtn.style.background = 'rgba(0,0,0,0.6)';
closeBtn.style.borderColor = 'rgba(255,255,255,0.3)';
closeBtn.style.transform = 'scale(1)';
});
overlay.appendChild(mediaContainer);
overlay.appendChild(closeBtn);
// Add CSS animations
const style = document.createElement('style');
style.textContent = `
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
to { opacity: 0; }
}
.codecclimax-overlay.fade-out {
animation: fadeOut 0.2s ease forwards;
}
`;
document.head.appendChild(style);
document.body.appendChild(overlay);
// Auto-remove after reasonable time (media plays naturally, user controls when to close)
let autoCloseTime;
switch (media.type) {
case 'image':
autoCloseTime = 5000; // 5 seconds for images
break;
case 'gif':
autoCloseTime = 8000; // 8 seconds for GIFs (let them loop)
break;
case 'video':
autoCloseTime = 15000; // 15 seconds for videos
break;
case 'youtube':
autoCloseTime = 30000; // 30 seconds for YouTube (let users enjoy the video)
break;
default:
autoCloseTime = 5000;
}
const autoCloseTimer = setTimeout(() => {
if (this.currentOverlay === overlay) {
closeOverlay(false); // false = auto-close (not manual)
}
}, autoCloseTime);
// Click on backdrop to dismiss
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
clearTimeout(autoCloseTimer);
closeOverlay(true); // true = manual close
}
});
// Cleanup timer if overlay is manually closed
overlay.addEventListener('remove', () => {
clearTimeout(autoCloseTimer);
});
}
}
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
new CodeClimaxContent();
});
} else {
new CodeClimaxContent();
}