grvverma's picture
You are an experienced front-end developer. Implement functionality to automatically hide the login and signup modal once the user has successfully logged in or signed up.
d0145f4 verified
Raw History Blame Contribute Delete
9.25 kB
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDEXAMPLEEXAMPLEEXAMPLEEXAMPLE",
authDomain: "your-app.firebaseapp.com",
projectId: "your-app",
storageBucket: "your-app.appspot.com",
messagingSenderId: "1234567890",
appId: "1:1234567890:web:abcdef1234567890"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
// Dark mode toggle functionality
document.addEventListener('DOMContentLoaded', function() {
// Check for dark mode preference
if (localStorage.getItem('darkMode') === 'true' ||
(!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark');
}
// Initialize tooltips
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// Smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
// Handle auth state changes
auth.onAuthStateChanged(user => {
if (user) {
console.log('User logged in:', user);
// Update UI for logged-in user
document.querySelectorAll('.auth-buttons').forEach(el => {
el.innerHTML = `
<div class="flex items-center gap-2">
<img src="${user.photoURL || 'http://static.photos/people/40x40/1'}"
class="w-8 h-8 rounded-full" alt="Profile">
<button onclick="logout()" class="signup-btn">Logout</button>
</div>
`;
});
} else {
console.log('User logged out');
// Update UI for logged-out user
}
});
});
// Auth functions
async function loginWithGoogle() {
try {
const provider = new firebase.auth.GoogleAuthProvider();
await auth.signInWithPopup(provider);
} catch (error) {
const modal = document.querySelector('login-modal');
if (modal) modal.showErrorMessage(error.message || 'Google login failed');
}
}
async function loginWithMicrosoft() {
try {
const provider = new firebase.auth.OAuthProvider('microsoft.com');
provider.setCustomParameters({ prompt: 'select_account' });
await auth.signInWithPopup(provider);
} catch (error) {
const modal = document.querySelector('login-modal');
if (modal) modal.showErrorMessage(error.message || 'Microsoft login failed');
}
}
async function loginWithApple() {
try {
const provider = new firebase.auth.OAuthProvider('apple.com');
provider.addScope('email');
provider.addScope('name');
await auth.signInWithPopup(provider);
} catch (error) {
const modal = document.querySelector('login-modal');
if (modal) modal.showErrorMessage(error.message || 'Apple login failed');
}
}
async function loginWithEmail(email, password) {
return auth.signInWithEmailAndPassword(email, password);
}
async function signupWithEmail(name, email, password) {
const userCredential = await auth.createUserWithEmailAndPassword(email, password);
await userCredential.user.updateProfile({ displayName: name });
return userCredential;
}
function logout() {
auth.signOut()
.then(() => {
console.log('User logged out');
})
.catch(error => {
console.error('Logout error:', error);
});
}
// Flashcard deck options dropdown functionality
document.addEventListener('DOMContentLoaded', function() {
// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('.deck-options-btn')) {
document.querySelectorAll('.options-dropdown').forEach(dropdown => {
dropdown.classList.add('hidden');
});
}
});
// Toggle dropdowns
document.querySelectorAll('.deck-options-btn').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
const dropdown = this.nextElementSibling;
document.querySelectorAll('.options-dropdown').forEach(d => {
if (d !== dropdown) d.classList.add('hidden');
});
dropdown.classList.toggle('hidden');
});
});
});
// Example function for flashcard generation
function generateFlashcards(sourceType, content) {
console.log(`Generating flashcards from ${sourceType}: ${content}`);
// In a real app, this would call your backend/AI service
return new Promise((resolve) => {
setTimeout(() => {
const sampleFlashcards = [
{ front: "What is photosynthesis?", back: "The process by which green plants use sunlight to synthesize foods from carbon dioxide and water." },
{ front: "What are the reactants of photosynthesis?", back: "Carbon dioxide, water, and sunlight." },
{ front: "What are the products of photosynthesis?", back: "Glucose and oxygen." }
];
resolve(sampleFlashcards);
}, 1000);
});
}
// Show login modal with optional tab
function showLoginModal(tab = 'login') {
const modal = document.querySelector('login-modal');
if (modal) {
modal.open(tab);
}
}
// Quiz generation functions
function generateQuizFromFlashcards(deckId, difficulty, questionCount) {
// Implementation would call backend API
console.log(`Generating quiz from deck ${deckId} (${difficulty}, ${questionCount} questions)`);
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: 'quiz-' + Date.now(),
deckId,
difficulty,
questions: Array(questionCount).fill().map((_, i) => ({
id: 'q' + i,
question: `Sample question ${i+1} about ${deckId}`,
options: ['Option 1', 'Option 2', 'Option 3', 'Option 4'],
answer: Math.floor(Math.random() * 4)
}))
});
}, 1000);
});
}
function generateQuizFromTopic(topic, difficulty, questionCount) {
// Implementation would call backend API
console.log(`Generating quiz about ${topic} (${difficulty}, ${questionCount} questions)`);
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: 'quiz-' + Date.now(),
topic,
difficulty,
questions: Array(questionCount).fill().map((_, i) => ({
id: 'q' + i,
question: `Sample question ${i+1} about ${topic}`,
options: ['Option 1', 'Option 2', 'Option 3', 'Option 4'],
answer: Math.floor(Math.random() * 4)
}))
});
}, 1000);
});
}
// Note management functions
function createNewNote(title, content, topic, tags = [], generateFlashcards = false) {
console.log(`Creating new note: ${title} (${topic})`);
if (generateFlashcards) {
console.log(`Also generating flashcards for note`);
}
// Implementation would call backend API
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: 'note-' + Date.now(),
title,
content,
topic,
tags,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
});
}, 800);
});
}
// Example function for quiz generation
function generateQuiz(topic) {
console.log(`Generating quiz about ${topic}`);
// In a real app, this would call your backend/AI service
return new Promise((resolve) => {
setTimeout(() => {
const sampleQuiz = {
title: `Quiz about ${topic}`,
questions: [
{
question: "What is the main purpose of photosynthesis?",
options: [
"To produce oxygen",
"To create glucose for energy",
"To absorb sunlight",
"All of the above"
],
answer: 3
},
{
question: "Which organelle performs photosynthesis?",
options: [
"Mitochondria",
"Nucleus",
"Chloroplast",
"Ribosome"
],
answer: 2
}
]
};
resolve(sampleQuiz);
}, 1000);
});
}