Skip to content

Commit 56f2fe6

Browse files
authored
Merge pull request #68 from zubyj/small-ui-updates
Refine UI Styles, Improve Theme Detection & Cleanup Console Logs
2 parents d7d664c + 979d10e commit 56f2fe6

File tree

12 files changed

+296
-118
lines changed

12 files changed

+296
-118
lines changed

src/background/background.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ chrome.runtime.onInstalled.addListener(() => {
2525
chrome.storage.local.set({ leetcodeProblems: data });
2626
})
2727
.catch((error) => {
28-
console.error(error);
28+
console.error('Failed to load problem data:', error);
2929
});
3030

3131
// Load problems by company JSON file into storage
@@ -36,7 +36,7 @@ chrome.runtime.onInstalled.addListener(() => {
3636
chrome.storage.local.set({ companyProblems: data });
3737
})
3838
.catch((error) => {
39-
console.error(error);
39+
console.error('Failed to load company problems:', error);
4040
});
4141

4242
// Load default settings
@@ -51,6 +51,22 @@ chrome.runtime.onInstalled.addListener(() => {
5151
});
5252

5353
chrome.runtime.onMessage.addListener((request) => {
54+
// Direct path for settings updates
55+
if (request.action === 'settingsUpdate') {
56+
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
57+
const tab = tabs[0];
58+
if (tab?.id && tab.url?.includes('leetcode.com/problems/')) {
59+
chrome.tabs.sendMessage(tab.id, {
60+
action: 'updateDescription',
61+
title: tab.title || 'title',
62+
isSettingsUpdate: true
63+
});
64+
}
65+
});
66+
return;
67+
}
68+
69+
// Existing message handlers
5470
if (request.action === 'openCompanyPage') {
5571
chrome.storage.local.set({ clickedCompany: request.company });
5672
chrome.tabs.create({
@@ -152,7 +168,6 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
152168
isViewChange ? 'View Changed' :
153169
isActualRefresh ? 'Page Refresh' :
154170
'Page Load';
155-
console.log(`State change detected - ${changeType}`);
156171

157172
// Update last state
158173
lastState.problemPath = problemPath;

src/content-script/get-user-code.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ function getProblem() {
7070
// Get test cases, output, and expected output
7171
const consoleData = getConsoleData();
7272
if (consoleData.length > 0) {
73-
console.log('Console Data:', consoleData);
73+
//console.log('Console Data:', consoleData);
7474
collectedData.push("\n--- Test Cases and Results ---\n" + consoleData.join('\n'));
7575
}
7676

@@ -79,7 +79,7 @@ function getProblem() {
7979
if (errorPanel) {
8080
const errorText = errorPanel.textContent?.trim();
8181
if (errorText) {
82-
console.log('Error from LeetCode:', errorText);
82+
//console.log('Error from LeetCode:', errorText);
8383
collectedData.push("\n--- LeetCode Error Message ---\n" + errorText);
8484
collectedData.push("\nPlease fix the above error in the code.");
8585
}

src/content-script/themeDetector.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ function isColorDark(color) {
8282
// Extract RGB values
8383
const rgb = color.match(/\d+/g);
8484
if (!rgb || rgb.length < 3) {
85-
console.log('Could not extract RGB values from color:', color);
8685
return true; // Default to dark if can't extract
8786
}
8887

@@ -93,7 +92,6 @@ function isColorDark(color) {
9392

9493
// Weighted luminance formula (human eye is more sensitive to green)
9594
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
96-
console.log(`Color luminance: ${luminance} (< 0.5 is dark)`);
9795

9896
// Return true for dark colors (lower luminance)
9997
return luminance < 0.5;

src/content-script/update-description-tab.ts

Lines changed: 95 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ function detectAndSyncTheme() {
4545
isDarkTheme: leetcodeTheme === 'dark'
4646
});
4747

48-
console.log(`Theme auto-detected: ${leetcodeTheme}`);
48+
//console.log(`Theme auto-detected: ${leetcodeTheme}`);
4949

5050
// Set up observer for future theme changes
5151
observeThemeChanges();
@@ -70,7 +70,7 @@ function observeThemeChanges() {
7070
chrome.storage.local.set({
7171
isDarkTheme: leetcodeTheme === 'dark'
7272
});
73-
console.log(`Theme changed to: ${leetcodeTheme}`);
73+
//console.log(`Theme changed to: ${leetcodeTheme}`);
7474
}
7575
});
7676
});
@@ -162,16 +162,21 @@ function showRating(problemTitle: string) {
162162
// show the company tags if the user has enabled it in the settings
163163
function showCompanyTags(problemTitle: string) {
164164
chrome.storage.local.get(['showCompanyTags'], (result) => {
165-
if (!result.showCompanyTags) {
166-
return;
167-
}
168-
169165
// Check if we're on the description tab before proceeding
170166
const isDescriptionPage = !window.location.href.includes('/solutions');
171167
if (!isDescriptionPage) {
172168
return;
173169
}
174170

171+
// Remove existing container if setting is disabled
172+
const existingContainer = document.getElementById('companyTagContainer');
173+
if (!result.showCompanyTags) {
174+
if (existingContainer) {
175+
existingContainer.remove();
176+
}
177+
return;
178+
}
179+
175180
// Try to find the description element with retries
176181
const maxRetries = 10;
177182
const baseDelay = 300;
@@ -209,13 +214,11 @@ function showCompanyTags(problemTitle: string) {
209214
// Use exponential backoff for retry delay
210215
const delay = baseDelay * Math.pow(1.5, retryCount);
211216
retryCount++;
212-
console.log(`Attempt ${retryCount}: Waiting for description element to load... Retrying in ${delay}ms`);
213217
setTimeout(tryInsertCompanyTags, delay);
214218
return;
215219
}
216220

217221
if (!description) {
218-
console.log('Failed to find description element after all retries');
219222

220223
// If still not found, set up a MutationObserver to watch for DOM changes
221224
const observer = new MutationObserver((mutations, obs) => {
@@ -373,10 +376,16 @@ function setupDescriptionThemeListener() {
373376

374377
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
375378
if (request.action === 'updateDescription') {
379+
// For settings updates, bypass the state checks
380+
if (request.isSettingsUpdate) {
381+
console.log('Updating description tab due to settings change...');
382+
updatePageContent();
383+
return true;
384+
}
385+
376386
// Only detect theme on first load, problem change, or refresh
377387
if (!request.isProblemChange && !request.isRefresh) {
378-
console.log('Skipping theme detection for internal navigation');
379-
return;
388+
return true;
380389
}
381390

382391
console.log('Updating description tab...');
@@ -412,38 +421,93 @@ function initializeDescriptionTab() {
412421
// Set up theme detection and synchronization
413422
setupDescriptionThemeListener();
414423

415-
// Get the problem title from the page
416-
const problemTitle = document.title.replace(' - LeetCode', '');
417-
418-
// Apply all enhancements
419-
showDifficulty();
420-
showRating(problemTitle);
421-
showCompanyTags(problemTitle);
422-
showExamples();
424+
// Initial load of enhancements
425+
updatePageContent();
423426

424-
// Set up a MutationObserver to detect tab changes
427+
// Set up URL change detection using History API
428+
const originalPushState = history.pushState;
429+
const originalReplaceState = history.replaceState;
430+
431+
history.pushState = function(data: any, unused: string, url?: string | URL) {
432+
originalPushState.call(this, data, unused, url);
433+
handleUrlChange();
434+
};
435+
436+
history.replaceState = function(data: any, unused: string, url?: string | URL) {
437+
originalReplaceState.call(this, data, unused, url);
438+
handleUrlChange();
439+
};
440+
441+
window.addEventListener('popstate', handleUrlChange);
442+
443+
// Set up a MutationObserver to detect tab and content changes
425444
const observer = new MutationObserver((mutations) => {
445+
let shouldUpdate = false;
446+
426447
mutations.forEach((mutation) => {
427-
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
428-
// Check if we're on the description tab
429-
const descriptionTab = document.querySelector('[data-cy="description-tab"]');
430-
if (descriptionTab && descriptionTab.classList.contains('active')) {
431-
// Re-apply company tags when switching to description tab
432-
const problemTitle = document.title.replace(' - LeetCode', '');
433-
showCompanyTags(problemTitle);
448+
// Check for tab changes
449+
if (mutation.target instanceof HTMLElement) {
450+
const isTabChange = mutation.target.getAttribute('role') === 'tab' ||
451+
mutation.target.closest('[role="tab"]');
452+
if (isTabChange) {
453+
shouldUpdate = true;
434454
}
435455
}
456+
457+
// Check for content changes in the main container
458+
if (mutation.type === 'childList' &&
459+
((mutation.target instanceof HTMLElement && mutation.target.classList?.contains('elfjS')) ||
460+
mutation.addedNodes.length > 0)) {
461+
shouldUpdate = true;
462+
}
436463
});
464+
465+
if (shouldUpdate) {
466+
// Small delay to ensure DOM is fully updated
467+
setTimeout(updatePageContent, 100);
468+
}
437469
});
438470

439-
// Start observing the tab container
440-
const tabContainer = document.querySelector('[role="tablist"]');
441-
if (tabContainer) {
442-
observer.observe(tabContainer, { childList: true, subtree: true });
443-
}
471+
// Observe both the tab container and the main content area
472+
observer.observe(document.body, {
473+
childList: true,
474+
subtree: true,
475+
attributes: true,
476+
attributeFilter: ['class', 'data-cy']
477+
});
478+
}
479+
}
480+
481+
// Update all page content
482+
function updatePageContent() {
483+
const problemTitle = document.title.replace(' - LeetCode', '').split('-')[0].trim();
484+
const isDescriptionTab = isOnDescriptionTab();
485+
486+
if (isDescriptionTab) {
487+
showCompanyTags(problemTitle);
488+
showDifficulty();
489+
showRating(problemTitle);
490+
showExamples();
444491
}
445492
}
446493

494+
// Check if we're on the description tab
495+
function isOnDescriptionTab() {
496+
// Check multiple conditions to determine if we're on the description tab
497+
const descriptionTab = document.querySelector('[data-cy="description-tab"]');
498+
const isDescriptionActive = descriptionTab?.classList.contains('active');
499+
const notOnSolutions = !window.location.href.includes('/solutions');
500+
const hasDescriptionContent = !!document.getElementsByClassName('elfjS')[0];
501+
502+
return (isDescriptionActive || notOnSolutions) && hasDescriptionContent;
503+
}
504+
505+
// Handle URL changes
506+
function handleUrlChange() {
507+
// Small delay to ensure DOM is updated
508+
setTimeout(updatePageContent, 200);
509+
}
510+
447511
// Initialize the content script
448512
initializeDescriptionTab();
449513

0 commit comments

Comments
 (0)