232 lines
8.5 KiB
HTML
232 lines
8.5 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Firebase Firestore CRUD App</title>
|
|
<style>
|
|
/* (Keep all your existing CSS styles the same) */
|
|
body {
|
|
font-family: 'Inter', sans-serif;
|
|
display: flex;
|
|
flex-direction: column;
|
|
justify-content: center;
|
|
align-items: center;
|
|
min-height: 100vh;
|
|
background-color: #f0f2f5;
|
|
margin: 0;
|
|
box-sizing: border-box;
|
|
}
|
|
/* ... (rest of your CSS remains identical) ... */
|
|
</style>
|
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap">
|
|
</head>
|
|
<body>
|
|
<!-- (Keep all your HTML the same) -->
|
|
<h1>User Management</h1>
|
|
<form id="userForm" action="">
|
|
<label for="name">Name: <input type="text" name="name" id="name" required> </label>
|
|
<label for="email">Email: <input type="email" name="email" id="email" required> </label>
|
|
<input type="hidden" id="userId">
|
|
<button type="submit" id="submitButton">Add User</button>
|
|
<button type="button" id="cancelEdit" style="display: none; background-color: #6c757d;">Cancel Edit</button>
|
|
</form>
|
|
|
|
<div class="crud-section">
|
|
<h2>User List</h2>
|
|
<button id="refreshUsers">Refresh List</button>
|
|
<div class="user-list" id="userList"></div>
|
|
</div>
|
|
|
|
<div id="customAlertModal" class="modal-overlay">
|
|
<div class="modal-content">
|
|
<h2 id="modalTitle"></h2>
|
|
<p id="modalMessage"></p>
|
|
<button id="modalCloseButton">OK</button>
|
|
</div>
|
|
</div>
|
|
|
|
<script type="module">
|
|
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
|
|
import {
|
|
getFirestore,
|
|
collection,
|
|
addDoc,
|
|
getDocs,
|
|
doc,
|
|
updateDoc,
|
|
deleteDoc,
|
|
onSnapshot,
|
|
serverTimestamp
|
|
} from "https://www.gstatic.com/firebasejs/9.6.0/firebase-firestore.js";
|
|
|
|
// Your Firebase configuration
|
|
const firebaseConfig = {
|
|
apiKey: "AIzaSyDoRv9_xpy19uoyVRVEjGYB-Ckr3ZyruTE",
|
|
authDomain: "nosql-demo-bd597.firebaseapp.com",
|
|
projectId: "nosql-demo-bd597",
|
|
storageBucket: "nosql-demo-bd597.appspot.com",
|
|
messagingSenderId: "813176623239",
|
|
appId: "1:813176623239:web:aa855f2e3fe29dfc3ca822"
|
|
};
|
|
|
|
// Initialize Firebase
|
|
const app = initializeApp(firebaseConfig);
|
|
const db = getFirestore(app);
|
|
const usersCollection = collection(db, "users");
|
|
|
|
// Modal functions (keep the same)
|
|
function showCustomAlert(title, message) {
|
|
const modal = document.getElementById('customAlertModal');
|
|
document.getElementById('modalTitle').textContent = title;
|
|
document.getElementById('modalMessage').textContent = message;
|
|
modal.classList.add('visible');
|
|
}
|
|
|
|
document.getElementById('modalCloseButton').addEventListener('click', () => {
|
|
document.getElementById('customAlertModal').classList.remove('visible');
|
|
});
|
|
|
|
// DOM Elements (keep the same)
|
|
const form = document.getElementById('userForm');
|
|
const submitButton = document.getElementById('submitButton');
|
|
const cancelEdit = document.getElementById('cancelEdit');
|
|
const userList = document.getElementById('userList');
|
|
const refreshButton = document.getElementById('refreshUsers');
|
|
let isEditing = false;
|
|
let currentEditId = null;
|
|
|
|
// Form submission - Firestore version
|
|
form.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const name = document.getElementById('name').value;
|
|
const email = document.getElementById('email').value;
|
|
|
|
const userData = {
|
|
name,
|
|
email,
|
|
updatedAt: serverTimestamp()
|
|
};
|
|
|
|
try {
|
|
if (isEditing) {
|
|
// Update existing user
|
|
const userRef = doc(db, "users", currentEditId);
|
|
await updateDoc(userRef, userData);
|
|
showCustomAlert('✅ Success!', 'User updated successfully!');
|
|
} else {
|
|
// Create new user
|
|
userData.createdAt = serverTimestamp();
|
|
const docRef = await addDoc(usersCollection, userData);
|
|
showCustomAlert('✅ Success!', `User created with ID: ${docRef.id}`);
|
|
}
|
|
form.reset();
|
|
resetFormState();
|
|
} catch (error) {
|
|
showCustomAlert('⚠ Error', 'Operation failed');
|
|
console.error('Firestore error:', error);
|
|
}
|
|
});
|
|
|
|
// Cancel edit (keep the same)
|
|
cancelEdit.addEventListener('click', resetFormState);
|
|
|
|
// Reset form (keep the same)
|
|
function resetFormState() {
|
|
isEditing = false;
|
|
currentEditId = null;
|
|
submitButton.textContent = 'Add User';
|
|
cancelEdit.style.display = 'none';
|
|
document.getElementById('userId').value = '';
|
|
}
|
|
|
|
// Display users - Firestore version
|
|
function displayUsers(users) {
|
|
userList.innerHTML = '';
|
|
|
|
if (users.empty) {
|
|
userList.innerHTML = '<p>No users found</p>';
|
|
return;
|
|
}
|
|
|
|
users.forEach((doc) => {
|
|
const user = doc.data();
|
|
const userCard = document.createElement('div');
|
|
userCard.className = 'user-card';
|
|
userCard.innerHTML = `
|
|
<div>
|
|
<strong>${user.name}</strong>
|
|
<p>${user.email}</p>
|
|
<small>ID: ${doc.id}</small>
|
|
</div>
|
|
<div class="user-actions">
|
|
<button class="edit" data-id="${doc.id}">Edit</button>
|
|
<button class="delete" data-id="${doc.id}">Delete</button>
|
|
</div>
|
|
`;
|
|
userList.appendChild(userCard);
|
|
});
|
|
|
|
// Add event listeners
|
|
document.querySelectorAll('.user-actions .edit').forEach(button => {
|
|
button.addEventListener('click', (e) => editUser(e.target.dataset.id));
|
|
});
|
|
|
|
document.querySelectorAll('.user-actions .delete').forEach(button => {
|
|
button.addEventListener('click', (e) => deleteUser(e.target.dataset.id));
|
|
});
|
|
}
|
|
|
|
// Load users - Firestore version
|
|
async function loadUsers() {
|
|
const querySnapshot = await getDocs(usersCollection);
|
|
displayUsers(querySnapshot);
|
|
}
|
|
|
|
// Edit user - Firestore version
|
|
async function editUser(id) {
|
|
const userRef = doc(db, "users", id);
|
|
const userSnap = await getDoc(userRef);
|
|
|
|
if (userSnap.exists()) {
|
|
const user = userSnap.data();
|
|
document.getElementById('name').value = user.name;
|
|
document.getElementById('email').value = user.email;
|
|
document.getElementById('userId').value = id;
|
|
|
|
isEditing = true;
|
|
currentEditId = id;
|
|
submitButton.textContent = 'Update User';
|
|
cancelEdit.style.display = 'inline-block';
|
|
} else {
|
|
showCustomAlert('⚠ Error', 'User not found');
|
|
}
|
|
}
|
|
|
|
// Delete user - Firestore version
|
|
async function deleteUser(id) {
|
|
if (!confirm('Are you sure you want to delete this user?')) return;
|
|
|
|
try {
|
|
await deleteDoc(doc(db, "users", id));
|
|
showCustomAlert('✅ Success!', 'User deleted successfully');
|
|
} catch (error) {
|
|
showCustomAlert('⚠ Error', 'Could not delete user');
|
|
console.error('Delete error:', error);
|
|
}
|
|
}
|
|
|
|
// Real-time listener - Firestore version
|
|
onSnapshot(usersCollection, (querySnapshot) => {
|
|
displayUsers(querySnapshot);
|
|
});
|
|
|
|
// Initial load
|
|
loadUsers();
|
|
|
|
// Refresh button
|
|
document.getElementById('refreshUsers').addEventListener('click', loadUsers);
|
|
</script>
|
|
</body>
|
|
</html>
|