// Funktion, die die aktive Seite anzeigt und alle anderen ausblendet function showPage(pageId: string): void { // Alle Seiten ausblenden const pages: NodeListOf<HTMLDivElement> = document.querySelectorAll('.page'); pages.forEach((page: HTMLDivElement) => { page.classList.remove('active'); }); // Die ausgewählte Seite anzeigen const activePage: HTMLElement | null = document.getElementById(pageId); if (activePage) { activePage.classList.add('active'); } else { console.error(`Seite mit der ID "${pageId}" wurde nicht gefunden.`); } } // Event-Listener für die Initialisierung beim Laden der Seite document.addEventListener('DOMContentLoaded', () => { showPage('reisen'); // Standardmäßig die Seite "Reisen" anzeigen }); interface User { user_id: number; firstName: string; lastName: string; eMail: string; adress: string; role: string; } let modalEl: bootstrap.Modal document.addEventListener("DOMContentLoaded", (): void => { modalEl = new bootstrap.Modal("#edit-user-modal"); //--- check, if user is already logged in (e.g. after refresh) ------------------------------------------------------- checkLogin(); //--- Form Eventhandlers ------------------------------------------------------- document.getElementById("add-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => { event.preventDefault(); const emailEl: HTMLInputElement = document.getElementById("add-user-email") as HTMLInputElement; const passwordEl: HTMLInputElement = document.getElementById("add-user-password") as HTMLInputElement; const firstNameEl: HTMLInputElement = document.getElementById("add-user-first-name") as HTMLInputElement; const lastNameEl: HTMLInputElement = document.getElementById("add-user-last-name") as HTMLInputElement; const email: string = emailEl.value; const password: string = passwordEl.value; const firstName: string = firstNameEl.value; const lastName: string = lastNameEl.value; // Check, if any given value is empty. // Don't allow creation of users without given name or family name. if (firstName.length == 0 || lastName.length == 0 || email.length == 0 || password.length == 0) { addMessage("The given name or family name is empty."); return; } // Send user data via http to server using the route /user const res: Response = await fetch('/user', { method: 'post', headers: { "Content-type": "application/json" }, body: JSON.stringify({ firstName, lastName, email, password}) }); const data: any = await res.json(); addMessage(data.message); // Update the html readUsers(); // Clear the input fields emailEl.value = ""; passwordEl.value = ""; firstNameEl.value = ""; lastNameEl.value = ""; }); document.getElementById("edit-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => { event.preventDefault(); let idEl: HTMLInputElement = document.getElementById("edit-user-id") as HTMLInputElement; let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement; let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement; // Read the user's id from the hidden field. let userId: number = parseInt(idEl.value); let firstName: string = firstNameEl.value; let lastName: string = lastNameEl.value; const res: Response = await fetch('/user/' + userId, { method: 'put', headers: { "Content-type": "application/json" }, body: JSON.stringify({ firstName, lastName }), }); const data: any = await res.json(); addMessage(data.message); // Hide the modal window modalEl.hide(); // Update the html readUsers(); }); document.getElementById("login-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => { event.preventDefault(); const emailInput: HTMLInputElement = document.getElementById('login-user-email-input') as HTMLInputElement; const passwordInput: HTMLInputElement = document.getElementById('login-user-password-input') as HTMLInputElement; const email: string = emailInput.value; const password: string = passwordInput.value; const response: Response = await fetch('http://localhost:8080/login', { method: "POST", headers: { "Content-type": "application/json" }, body: JSON.stringify({email, password}), } ); if (response.status === 400 || response.status === 401) { const data: any = await response.json(); addMessage(data.message); } else if (response.status === 200) { const data: any = await response.json(); addMessage(data.message); showLoggedInStatus(data.user); } else { console.warn(`Unhandled response code (${response.status}).`) } }); document.getElementById("logout-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => { event.preventDefault(); await fetch('http://localhost:8080/logout', { method: "POST", } ); showLoggedOutStatus() }); }); /** * Checks if user might be logged */ async function checkLogin(): Promise<void> { const response: Response = await fetch('/login', { method: "GET" } ); if (response.status === 200) { const data: any = await response.json(); showLoggedInStatus(data.user); } } /** * Gets and displays all users */ async function readUsers(): Promise<void> { const res: Response = await fetch('/users', { method: "GET" } ); const data: any = await res.json(); renderList(data.userList); } /** * Displays the logged in username */ function showLoggedInStatus(user: User): void { const email: HTMLElement = document.getElementById('current-user-email')!; email.innerHTML = `Hello ${user.firstName}`; const addUserForm: HTMLElement = document.getElementById('add-user-container')!; addUserForm.classList.remove("d-none"); // show content area const contentArea: HTMLElement = document.getElementById('user-list-container')!; contentArea.classList.remove("d-none"); // show content area const login: HTMLElement = document.getElementById('login-container')!; login.classList.add("d-none"); // hide login const logout: HTMLElement = document.getElementById('logout-container')!; logout.classList.remove("d-none"); // show logout (document.getElementById('login-form') as HTMLFormElement).reset(); readUsers(); } /** * Resets the site to the logged-out state. * Clears user list, shows login form, hides logout form- */ function showLoggedOutStatus(): void { const email: HTMLElement = document.getElementById('current-user-email')!; email.innerHTML = ``; const addUserForm: HTMLElement = document.getElementById('add-user-container')!; addUserForm.classList.add("d-none"); // hide content area const contentArea: HTMLElement = document.getElementById('user-list-container')!; contentArea.classList.add("d-none"); // hide content area const login: HTMLElement = document.getElementById('login-container')!; login.classList.remove("d-none"); // show login const logout: HTMLElement = document.getElementById('logout-container')!; logout.classList.add("d-none"); // hide logout (document.getElementById('add-user-form') as HTMLFormElement).reset(); } /** * 1) Clears the user table. * 2) Adds all users to the table. */ function renderList(userList: User[]): void { let userListEl: HTMLElement = document.getElementById("user-list")!; // Remove all entries from the table userListEl.replaceChildren(); for (let user of userList) { // The new table row let tr: HTMLTableRowElement = document.createElement("tr"); // ID cell let tdUser_id: HTMLTableCellElement = document.createElement("td"); tdUser_id.textContent = user.user_id.toString(); // Given name cell let tdFirstName: HTMLTableCellElement = document.createElement("td"); tdFirstName.textContent = user.firstName; // Family name cell let tdLastName: HTMLTableCellElement = document.createElement("td"); tdLastName.textContent = user.lastName; // email cell let tdEmail: HTMLTableCellElement = document.createElement("td"); tdEmail.textContent = user.eMail; // adress cell let tdAdress: HTMLTableCellElement = document.createElement("td"); tdAdress.textContent = user.adress; // role cell let tdRole: HTMLTableCellElement = document.createElement("td"); tdRole.textContent = user.role; // Buttons cell let tdButtons: HTMLTableCellElement = document.createElement("td"); // Delete button let deleteButton: HTMLButtonElement = document.createElement("button"); deleteButton.className = "btn btn-danger"; deleteButton.addEventListener("click", async () => { const res: Response = await fetch('/user/' + user.user_id, { method: 'DELETE' }); const data: any = await res.json(); addMessage(data.message); readUsers(); }); // Delete button icon let deleteButtonIcon: HTMLElement = document.createElement("i"); deleteButtonIcon.className = "fa-solid fa-trash"; deleteButton.append(deleteButtonIcon); // Edit button let editButton: HTMLButtonElement = document.createElement("button"); editButton.className = "btn btn-primary ms-3"; editButton.addEventListener("click", () => { showEditModal(user); }); // Edit button icon let editButtonIcon: HTMLElement = document.createElement("i"); editButtonIcon.className = "fa-solid fa-pen"; editButton.append(editButtonIcon); // Adds the buttons to the button cell tdButtons.append(deleteButton, editButton); // Add the cells to the table row tr.append(tdUser_id, tdFirstName, tdLastName, tdEmail,tdAdress, tdRole, tdButtons); // Add the table row to the table userListEl.append(tr); } } /** * 1) Fills the modal window with the given user's data. * 2) Opens the modal window. */ function showEditModal(user: User): void { let user_idEl: HTMLInputElement = document.getElementById("edit-user-user_id") as HTMLInputElement; let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement; let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement; // Write the user's id into the hidden field. user_idEl.value = user.user_id.toString(); // Write the user's data into the text fields. firstNameEl.value = user.firstName; lastNameEl.value = user.lastName; // Show the modal window. modalEl.show(); } /** * Creates a new alert message. */ function addMessage(message: string): void { const messagesEl: HTMLElement = document.getElementById('messages')!; // The alert element let alertEl: HTMLElement = document.createElement('div'); alertEl.classList.add('alert', 'alert-warning', 'alert-dismissible', 'fade', 'show'); alertEl.setAttribute('role', 'alert'); alertEl.textContent = message; // Close button let buttonEl: HTMLElement = document.createElement("button"); // btn-close changes the button into an 'X' icon. buttonEl.className = "btn-close"; // data-bs-dismiss enables the button to automatically close the alert on click. buttonEl.setAttribute("data-bs-dismiss", "alert"); // Add the close button to the alert. alertEl.appendChild(buttonEl); // Convert to Bootstrap Alert type const alert: bootstrap.Alert = new bootstrap.Alert(alertEl); // Add message to DOM messagesEl.appendChild(alertEl); // Auto-remove message after 5 seconds (5000ms) setTimeout(() => { alert.close(); }, 5000); }