chore: refactor and optimize code for better performance and readability

This commit is contained in:
Chneemann 2025-03-30 10:04:51 +02:00
parent e995696882
commit a00690ffae
4 changed files with 29 additions and 135 deletions

View file

@ -89,7 +89,9 @@
@if(selectedUser.isOnline) {
<span>{{ "contacts.contactLastOnlineTxt" | translate }}</span>
} @else {
<span>{{ convertTimestamp(selectedUser.lastLogin) }}</span>
<span
>{{ selectedUser.lastLogin | date : "dd. MMM yyyy, HH:mm:ss" }}
</span>
} }
</div>
</div>

View file

@ -25,7 +25,7 @@ import { User } from '../../../interfaces/user.interface';
styleUrl: './contact-detail.component.scss',
})
export class ContactDetailComponent {
@Input() selectedUserId: string | undefined;
@Input() selectedUserId: string | null = null;
@Input() currentUser: User | null = null;
@Output() closeContactEmitter = new EventEmitter<boolean>();
@ -33,11 +33,9 @@ export class ContactDetailComponent {
selectedUser: User | null = null;
constructor(
private router: Router,
public sharedService: SharedService,
public firebaseService: FirebaseService,
private userService: UserService,
private languageService: LanguageService
private userService: UserService
) {}
ngOnChanges(changes: SimpleChanges) {
@ -110,89 +108,6 @@ export class ContactDetailComponent {
this.sharedService.isMobileNavbarOpen = false;
}
/**
* Converts a given timestamp to a human-readable date string.
* @param timestamp the timestamp to convert
* @returns a string in the format "DD. MMM. YYYY - HH:mm" in German or "MMM. DD, YYYY - hh:mm A" in English
*/
convertTimestamp(timestamp: number) {
const date = new Date(timestamp);
const monthsEN = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const monthsDE = [
'Jan',
'Feb',
'Mär',
'Apr',
'Mai',
'Jun',
'Jul',
'Aug',
'Sep',
'Okt',
'Nov',
'Dez',
];
const months =
this.languageService.currentLang === 'de' ? monthsDE : monthsEN;
const year = date.getFullYear();
const month = months[date.getMonth()];
const day = date.getDate();
if (this.languageService.currentLang === 'de') {
const time = `${day}. ${month}. ${year}`;
return `${time} - ${this.convertTimestampHourDE(timestamp)}`;
} else {
const time = `${month}. ${day}, ${year}`;
return `${time} - ${this.convertTimestampHourEN(timestamp)}`;
}
}
/**
* Converts a given timestamp to a human-readable time string in English.
* @param timestamp the timestamp to convert
* @returns a string in the format "hh:mm:ss AM/PM"
*/
convertTimestampHourEN(timestamp: number) {
const date = new Date(timestamp * 1000);
let hour = date.getHours();
const minute = ('0' + date.getMinutes()).slice(-2);
const second = ('0' + date.getMinutes()).slice(-2);
const period = hour >= 12 ? 'PM' : 'AM';
hour = hour % 12 || 12;
let hourWithNull = ('0' + hour).slice(-2);
return `${hourWithNull}:${minute}:${second} ${period}`;
}
/**
* Converts a given timestamp to a human-readable time string in German.
*
* @param timestamp The timestamp to convert, in seconds.
* @returns A string in the format "HH:mm:ss Uhr".
*/
convertTimestampHourDE(timestamp: number) {
const date = new Date(timestamp * 1000);
let hour = date.getHours();
const minute = ('0' + date.getMinutes()).slice(-2);
const second = ('0' + date.getMinutes()).slice(-2);
return `${hour}:${minute}:${second} Uhr`;
}
@HostListener('document:click', ['$event'])
/**
* Handles the opening of the contact edit, new contact, and delete contact

View file

@ -2,7 +2,7 @@
<div
class="left-frame"
[ngClass]="{
'd-none': !showAllUsers && selectedUserId != undefined
'd-none': !showAllUsers && selectedUserId != null
}"
>
<button class="btn-new" type="submit" (click)="openNewContactDialog()">
@ -15,14 +15,14 @@
</div>
</button>
<div class="content">
@for (sortLetter of this.sortFirstLetter(); track sortLetter) {
@for (sortLetter of this.getUniqueFirstLetters(); track sortLetter) {
<div class="first-letter">{{ sortLetter }}</div>
<div class="line"></div>
@for (user of this.sortUsersByFirstLetter(sortLetter); track user; let
@for (user of this.filterUsersByFirstLetter(sortLetter); track user; let
index = $index) {
<div
class="contact"
(click)="showUserId(user.id)"
(click)="openUserDetails(user.id)"
[ngClass]="{
'contact-active': selectedUserId === user.id
}"
@ -67,7 +67,7 @@
<div class="right-frame">
<app-contact-detail
[ngClass]="{
'd-none': !showAllUsers && selectedUserId == undefined
'd-none': !showAllUsers && selectedUserId == null
}"
[selectedUserId]="selectedUserId"
[currentUser]="currentUser"

View file

@ -20,9 +20,7 @@ import { finalize } from 'rxjs';
export class ContactsComponent {
allUsers: User[] = [];
currentUser: User | null = null;
selectedUserId: string | undefined;
usersFirstLetter: string[] = [];
usersByFirstLetter: { [key: string]: string[] } = {};
selectedUserId: string | null = null;
showAllUsers: boolean = false;
isLoading: boolean = false;
@ -41,23 +39,6 @@ export class ContactsComponent {
this.loadCurrentUser();
}
@HostListener('window:resize', ['$event'])
/**
* Toggles the showAllUsers variable based on the window width and the
* currentUserId of the shared service.
*
* If the window width is less than or equal to 1150px and the currentUserId
* is not empty, showAllUsers is set to false. Otherwise, showAllUsers is set
* to true.
*/
onResize() {
if (window.innerWidth <= 1150 && this.selectedUserId != undefined) {
this.showAllUsers = false;
} else {
this.showAllUsers = true;
}
}
loadAllUsers(): void {
this.isLoading = true;
@ -85,7 +66,7 @@ export class ContactsComponent {
* If the parameter is not given, it resets the current user id to an empty string.
* @param userId - the id of the user to be set as the current user id
*/
showUserId(userId: string = '') {
openUserDetails(userId: string = '') {
this.selectedUserId = userId;
this.onResize();
}
@ -94,37 +75,24 @@ export class ContactsComponent {
* Triggers the resize function to adjust UI elements based on the current state.
*/
closeContactEmitter() {
this.selectedUserId = undefined;
this.selectedUserId = null;
this.onResize();
}
/**
* Sorts the users array by the first letter of the user's initials, and filters it by the given sort letter.
* @param sortLetter - the letter to filter the users by
* @returns An array of users with the given sort letter
*/
sortUsersByFirstLetter(sortLetter: string) {
filterUsersByFirstLetter(filterLetter: string) {
return this.allUsers.filter(
(user) => user.initials.substring(0, 1) === sortLetter
(user) => user.initials.substring(0, 1) === filterLetter
);
}
/**
* Returns an array of unique first letters from the sorted array of users.
* The users array is first sorted by the first letter of the user's first name,
* and then the first letter of each user's first name is extracted and
* converted to uppercase. The resulting array is then deduplicated with a
* Set, and the unique letters are returned in an array.
* @returns An array of unique first letters
*/
sortFirstLetter() {
let filterteArray = this.allUsers.sort((a, b) =>
getUniqueFirstLetters() {
let sortedUsers = this.allUsers.sort((a, b) =>
a.firstName.localeCompare(b.firstName)
);
let usersFirstLetter = Array.from(
new Set(filterteArray.map((user) => user.firstName[0].toUpperCase()))
let uniqueFirstLetters = Array.from(
new Set(sortedUsers.map((user) => user.firstName[0].toUpperCase()))
);
return usersFirstLetter;
return uniqueFirstLetters;
}
/**
@ -137,4 +105,13 @@ export class ContactsComponent {
this.sharedService.isAnyDialogOpen = true;
this.sharedService.isNewContactDialogOpen = true;
}
@HostListener('window:resize', ['$event'])
onResize() {
if (window.innerWidth <= 1150 && this.selectedUserId != undefined) {
this.showAllUsers = false;
} else {
this.showAllUsers = true;
}
}
}