Skip to content

Refine UI Styles, Improve Theme Detection & Cleanup Console Logs #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({ leetcodeProblems: data });
})
.catch((error) => {
console.error(error);
console.error('Failed to load problem data:', error);
});

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

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

chrome.runtime.onMessage.addListener((request) => {
// Direct path for settings updates
if (request.action === 'settingsUpdate') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs[0];
if (tab?.id && tab.url?.includes('leetcode.com/problems/')) {
chrome.tabs.sendMessage(tab.id, {
action: 'updateDescription',
title: tab.title || 'title',
isSettingsUpdate: true
});
}
});
return;
}

// Existing message handlers
if (request.action === 'openCompanyPage') {
chrome.storage.local.set({ clickedCompany: request.company });
chrome.tabs.create({
Expand Down Expand Up @@ -152,7 +168,6 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
isViewChange ? 'View Changed' :
isActualRefresh ? 'Page Refresh' :
'Page Load';
console.log(`State change detected - ${changeType}`);

// Update last state
lastState.problemPath = problemPath;
Expand Down
4 changes: 2 additions & 2 deletions src/content-script/get-user-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function getProblem() {
// Get test cases, output, and expected output
const consoleData = getConsoleData();
if (consoleData.length > 0) {
console.log('Console Data:', consoleData);
//console.log('Console Data:', consoleData);
collectedData.push("\n--- Test Cases and Results ---\n" + consoleData.join('\n'));
}

Expand All @@ -79,7 +79,7 @@ function getProblem() {
if (errorPanel) {
const errorText = errorPanel.textContent?.trim();
if (errorText) {
console.log('Error from LeetCode:', errorText);
//console.log('Error from LeetCode:', errorText);
collectedData.push("\n--- LeetCode Error Message ---\n" + errorText);
collectedData.push("\nPlease fix the above error in the code.");
}
Expand Down
2 changes: 0 additions & 2 deletions src/content-script/themeDetector.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ function isColorDark(color) {
// Extract RGB values
const rgb = color.match(/\d+/g);
if (!rgb || rgb.length < 3) {
console.log('Could not extract RGB values from color:', color);
return true; // Default to dark if can't extract
}

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

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

// Return true for dark colors (lower luminance)
return luminance < 0.5;
Expand Down
126 changes: 95 additions & 31 deletions src/content-script/update-description-tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ function detectAndSyncTheme() {
isDarkTheme: leetcodeTheme === 'dark'
});

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

// Set up observer for future theme changes
observeThemeChanges();
Expand All @@ -70,7 +70,7 @@ function observeThemeChanges() {
chrome.storage.local.set({
isDarkTheme: leetcodeTheme === 'dark'
});
console.log(`Theme changed to: ${leetcodeTheme}`);
//console.log(`Theme changed to: ${leetcodeTheme}`);
}
});
});
Expand Down Expand Up @@ -162,16 +162,21 @@ function showRating(problemTitle: string) {
// show the company tags if the user has enabled it in the settings
function showCompanyTags(problemTitle: string) {
chrome.storage.local.get(['showCompanyTags'], (result) => {
if (!result.showCompanyTags) {
return;
}

// Check if we're on the description tab before proceeding
const isDescriptionPage = !window.location.href.includes('/solutions');
if (!isDescriptionPage) {
return;
}

// Remove existing container if setting is disabled
const existingContainer = document.getElementById('companyTagContainer');
if (!result.showCompanyTags) {
if (existingContainer) {
existingContainer.remove();
}
return;
}

// Try to find the description element with retries
const maxRetries = 10;
const baseDelay = 300;
Expand Down Expand Up @@ -209,13 +214,11 @@ function showCompanyTags(problemTitle: string) {
// Use exponential backoff for retry delay
const delay = baseDelay * Math.pow(1.5, retryCount);
retryCount++;
console.log(`Attempt ${retryCount}: Waiting for description element to load... Retrying in ${delay}ms`);
setTimeout(tryInsertCompanyTags, delay);
return;
}

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

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

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'updateDescription') {
// For settings updates, bypass the state checks
if (request.isSettingsUpdate) {
console.log('Updating description tab due to settings change...');
updatePageContent();
return true;
}

// Only detect theme on first load, problem change, or refresh
if (!request.isProblemChange && !request.isRefresh) {
console.log('Skipping theme detection for internal navigation');
return;
return true;
}

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

// Get the problem title from the page
const problemTitle = document.title.replace(' - LeetCode', '');

// Apply all enhancements
showDifficulty();
showRating(problemTitle);
showCompanyTags(problemTitle);
showExamples();
// Initial load of enhancements
updatePageContent();

// Set up a MutationObserver to detect tab changes
// Set up URL change detection using History API
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;

history.pushState = function(data: any, unused: string, url?: string | URL) {
originalPushState.call(this, data, unused, url);
handleUrlChange();
};

history.replaceState = function(data: any, unused: string, url?: string | URL) {
originalReplaceState.call(this, data, unused, url);
handleUrlChange();
};

window.addEventListener('popstate', handleUrlChange);

// Set up a MutationObserver to detect tab and content changes
const observer = new MutationObserver((mutations) => {
let shouldUpdate = false;

mutations.forEach((mutation) => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// Check if we're on the description tab
const descriptionTab = document.querySelector('[data-cy="description-tab"]');
if (descriptionTab && descriptionTab.classList.contains('active')) {
// Re-apply company tags when switching to description tab
const problemTitle = document.title.replace(' - LeetCode', '');
showCompanyTags(problemTitle);
// Check for tab changes
if (mutation.target instanceof HTMLElement) {
const isTabChange = mutation.target.getAttribute('role') === 'tab' ||
mutation.target.closest('[role="tab"]');
if (isTabChange) {
shouldUpdate = true;
}
}

// Check for content changes in the main container
if (mutation.type === 'childList' &&
((mutation.target instanceof HTMLElement && mutation.target.classList?.contains('elfjS')) ||
mutation.addedNodes.length > 0)) {
shouldUpdate = true;
}
});

if (shouldUpdate) {
// Small delay to ensure DOM is fully updated
setTimeout(updatePageContent, 100);
}
});

// Start observing the tab container
const tabContainer = document.querySelector('[role="tablist"]');
if (tabContainer) {
observer.observe(tabContainer, { childList: true, subtree: true });
}
// Observe both the tab container and the main content area
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'data-cy']
});
}
}

// Update all page content
function updatePageContent() {
const problemTitle = document.title.replace(' - LeetCode', '').split('-')[0].trim();
const isDescriptionTab = isOnDescriptionTab();

if (isDescriptionTab) {
showCompanyTags(problemTitle);
showDifficulty();
showRating(problemTitle);
showExamples();
}
}

// Check if we're on the description tab
function isOnDescriptionTab() {
// Check multiple conditions to determine if we're on the description tab
const descriptionTab = document.querySelector('[data-cy="description-tab"]');
const isDescriptionActive = descriptionTab?.classList.contains('active');
const notOnSolutions = !window.location.href.includes('/solutions');
const hasDescriptionContent = !!document.getElementsByClassName('elfjS')[0];

return (isDescriptionActive || notOnSolutions) && hasDescriptionContent;
}

// Handle URL changes
function handleUrlChange() {
// Small delay to ensure DOM is updated
setTimeout(updatePageContent, 200);
}

// Initialize the content script
initializeDescriptionTab();

Loading