Newer
Older
// 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
});
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 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"
},
});
const data: any = await res.json();
addMessage(data.message);
// Update the html
readUsers();
// Clear the input fields
});
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"
},
});
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 password: string = passwordInput.value;
const response: Response = await fetch('http://localhost:8080/login', {
method: "POST",
headers: {
"Content-type": "application/json"
},
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
}
);
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 = ``;
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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();
let tdFirstName: HTMLTableCellElement = document.createElement("td");
tdFirstName.textContent = user.firstName;
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 () => {
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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;
firstNameEl.value = user.firstName;
lastNameEl.value = user.lastName;
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// 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);
}