added comments

This commit is contained in:
grata
2023-04-28 09:10:11 +02:00
parent bcb14a61de
commit 19d86de285
4 changed files with 46 additions and 14 deletions

View File

@@ -8,13 +8,14 @@ import {ReadTranslateJsonService} from "../service/readTranslateJsonService";
import {homeTranslations} from "../interface/translations"; import {homeTranslations} from "../interface/translations";
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
templateUrl: './home.component.html', templateUrl: './home.component.html',
styleUrls: ['./home.component.css'] styleUrls: ['./home.component.css']
}) })
export class HomeComponent implements OnInit, AfterViewInit, OnDestroy { export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('myInput') myInput?: ElementRef; @ViewChild('myInput') myInput?: ElementRef;
public locationsPopup: Subject<Locations[]> = new Subject<Locations[]>() public locationsPopup: Subject<Locations[]> = new Subject<Locations[]>()
@@ -34,6 +35,7 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
constructor(private readjsonService: ReadjsonService, private router: Router, private translateService: TranslateService, private readTranslationJsonService: ReadTranslateJsonService) { constructor(private readjsonService: ReadjsonService, private router: Router, private translateService: TranslateService, private readTranslationJsonService: ReadTranslateJsonService) {
} }
// Initializes the component and loads translations and locations
ngOnInit(): void { ngOnInit(): void {
this.translations = this.readTranslationJsonService.getHomeTranslations(); this.translations = this.readTranslationJsonService.getHomeTranslations();
console.log("translations loaded", this.translations) console.log("translations loaded", this.translations)
@@ -55,6 +57,7 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
} }
//This method sets up event listeners for input field changes to filter locations.
ngAfterViewInit() { ngAfterViewInit() {
if (this.locations != undefined) { if (this.locations != undefined) {
@@ -75,21 +78,30 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
}) })
} }
// Filters locations based on user input and shows suggestions
cercaLuogo(locations: string) { cercaLuogo(locations: string) {
// Delay for 1 second
setTimeout(() => { setTimeout(() => {
}, 1000); }, 1000);
// Filter locations and store in a variable
this.locationsFiltrati = this.locations.filter((l: Locations) => l.location.toLowerCase().startsWith(locations.toLowerCase())); this.locationsFiltrati = this.locations.filter((l: Locations) => l.location.toLowerCase().startsWith(locations.toLowerCase()));
if (this.locationsFiltrati.length > 0) { if (this.locationsFiltrati.length > 0) {
// Show suggestion if at least one location is found
this.suggerimentoAttivo = true; this.suggerimentoAttivo = true;
this.suggerimento = this.locationsFiltrati[0].location; this.suggerimento = this.locationsFiltrati[0].location;
// Find the difference between user input and suggestion
this.completamento = stringDifference(locations, this.suggerimento); this.completamento = stringDifference(locations, this.suggerimento);
} else { } else {
// Hide suggestion if no location is found
this.suggerimentoAttivo = false; this.suggerimentoAttivo = false;
this.suggerimento = ''; this.suggerimento = '';
} }
// Focus on input field
this.myInput?.nativeElement.focus(); this.myInput?.nativeElement.focus();
} }
// Selects the suggestion if the user presses "Tab" or "Enter" keys and if there is an active suggestion.
// The selected location is then assigned to the "luogoSelezionato" variable, and the suggestion is cleared.
selezionaSuggerimento(event: KeyboardEvent) { selezionaSuggerimento(event: KeyboardEvent) {
if (event.key === 'Tab' || event.key === 'Enter') { if (event.key === 'Tab' || event.key === 'Enter') {
if (this.suggerimentoAttivo) { if (this.suggerimentoAttivo) {
@@ -100,11 +112,9 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
} }
} }
//Method to handle search functionality.
luoghiNear() { // If the selected location is empty, an alert is displayed for 3 seconds.
return null; // Otherwise, the selected location is encoded and used to navigate to the corresponding location page using Angular router.
}
onSearch(): void { onSearch(): void {
if (this.luogoSelezionato === '') { if (this.luogoSelezionato === '') {
this.allert = true; this.allert = true;
@@ -118,6 +128,10 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
} }
} }
// This async function is used to switch the language of the application.
// It takes a language code as input and updates the translations object with new translations for various UI elements.
// The getData() method of the translateService is called with the current translations and the new language code.
// The translateService returns the translated data which is then assigned to the corresponding properties of the translations object.
async switchLanguage(lang: string) { async switchLanguage(lang: string) {
this.translations.translate = await this.translateService.getData(this.translations.translate, lang); this.translations.translate = await this.translateService.getData(this.translations.translate, lang);
this.translations.menuPlaces = await this.translateService.getData(this.translations.menuPlaces, lang); this.translations.menuPlaces = await this.translateService.getData(this.translations.menuPlaces, lang);
@@ -128,6 +142,12 @@ export class HomeComponent implements OnInit, AfterViewInit, OnDestroy {
} }
/**
* Returns the difference between two strings, by comparing their characters one by one.
* @param str1 - First string to compare
* @param str2 - Second string to compare
* @returns The difference between the two strings
*/
function stringDifference(str1: string, str2: string): string { function stringDifference(str1: string, str2: string): string {
let diff = ''; let diff = '';
for (let i = 0; i < str2.length; i++) { for (let i = 0; i < str2.length; i++) {

View File

@@ -8,17 +8,22 @@ import { environment } from '../../environments/environment';
}) })
export class DeepLService { export class DeepLService {
// Define the base URL for the DeepL API and the API key, taken from the environment configuration
private apiUrl = 'https://api-free.deepl.com/v2/translate'; private apiUrl = 'https://api-free.deepl.com/v2/translate';
private apiKey = environment.deepLApiKey; private apiKey = environment.deepLApiKey;
constructor(private http: HttpClient) { } constructor(private http: HttpClient) {
}
// Define the method for translating text, which takes the text to be translated and the target language as parameters
translate(text: string, targetLang: string): Observable<any> { translate(text: string, targetLang: string): Observable<any> {
// Define the parameters to be passed to the API, including the API key and the text and target language to be translated
const params = new HttpParams() const params = new HttpParams()
.set('auth_key', this.apiKey) .set('auth_key', this.apiKey)
.set('text', text) .set('text', text)
.set('target_lang', targetLang); .set('target_lang', targetLang);
// Make a POST request to the API using the HttpClient and the defined parameters, and return the response as an Observable
return this.http.post(this.apiUrl, params); return this.http.post(this.apiUrl, params);
} }

View File

@@ -7,10 +7,11 @@ import {listTranslations} from "../interface/translations";
providedIn: 'root' providedIn: 'root'
}) })
export class ReadTranslateJsonService { export class ReadTranslateJsonService {
private homeTranslations: homeTranslations = {} as homeTranslations; private homeTranslations: homeTranslations = {} as homeTranslations; // declares a private object to hold the home translations
private listTranslation: listTranslations = {} as listTranslations; private listTranslation: listTranslations = {} as listTranslations; // declares a private object to hold the list translations
constructor(private http: HttpClient) { constructor(private http: HttpClient) {
// loads the home translations from the assets file for the English language
this.http.get<homeTranslations>('assets/i18n/home/en.json').subscribe(data => { this.http.get<homeTranslations>('assets/i18n/home/en.json').subscribe(data => {
this.homeTranslations.alertMessage = data.alertMessage; this.homeTranslations.alertMessage = data.alertMessage;
this.homeTranslations.translate = data.translate; this.homeTranslations.translate = data.translate;
@@ -20,6 +21,7 @@ export class ReadTranslateJsonService {
console.log("data loaded", this.homeTranslations) console.log("data loaded", this.homeTranslations)
}); });
// loads the list translations from the assets file for the English language
this.http.get<listTranslations>('assets/i18n/list/en.json').subscribe(data => { this.http.get<listTranslations>('assets/i18n/list/en.json').subscribe(data => {
this.listTranslation.translate = data.translate; this.listTranslation.translate = data.translate;
this.listTranslation.distance = data.distance; this.listTranslation.distance = data.distance;
@@ -29,10 +31,12 @@ export class ReadTranslateJsonService {
}); });
} }
// returns the home translations object
getHomeTranslations(): homeTranslations { getHomeTranslations(): homeTranslations {
return this.homeTranslations; return this.homeTranslations;
} }
// returns the list translations object
getListTransaltions(): listTranslations { getListTransaltions(): listTranslations {
return this.listTranslation; return this.listTranslation;
} }

View File

@@ -7,8 +7,11 @@ import {Injectable} from "@angular/core";
export class TranslateService { export class TranslateService {
constructor(private deepLService: DeepLService) {} constructor(private deepLService: DeepLService) {}
// Method for translating the given input to the given language
async getData(input: string, lang: string): Promise<string> { async getData(input: string, lang: string): Promise<string> {
// Translating the input using the DeepLService and waiting for the response
const response = await this.deepLService.translate(input, lang).toPromise(); const response = await this.deepLService.translate(input, lang).toPromise();
// Returning the translated text from the response
return response.translations[0].text; return response.translations[0].text;
} }
} }