2024-06-07 10:06:40 +02:00
|
|
|
import { httpRequest } from '@utils';
|
2022-12-20 17:51:36 +01:00
|
|
|
import { show, hide } from '@utils';
|
|
|
|
import { ApplicationController } from './application_controller';
|
|
|
|
|
2024-06-07 10:06:40 +02:00
|
|
|
type checkEmailResponse = {
|
|
|
|
success: boolean;
|
2024-07-01 10:38:43 +02:00
|
|
|
suggestions: string[];
|
2024-06-07 10:06:40 +02:00
|
|
|
};
|
|
|
|
|
2022-12-20 17:51:36 +01:00
|
|
|
export class EmailInputController extends ApplicationController {
|
|
|
|
static targets = ['ariaRegion', 'suggestion', 'input'];
|
|
|
|
|
2024-06-07 10:06:40 +02:00
|
|
|
static values = {
|
|
|
|
url: String
|
|
|
|
};
|
|
|
|
|
|
|
|
declare readonly urlValue: string;
|
|
|
|
|
2022-12-20 17:51:36 +01:00
|
|
|
declare readonly ariaRegionTarget: HTMLElement;
|
|
|
|
declare readonly suggestionTarget: HTMLElement;
|
|
|
|
declare readonly inputTarget: HTMLInputElement;
|
|
|
|
|
2024-06-07 10:06:40 +02:00
|
|
|
async checkEmail() {
|
2024-06-11 10:17:27 +02:00
|
|
|
if (
|
|
|
|
!this.inputTarget.value ||
|
|
|
|
this.inputTarget.value.length < 5 ||
|
|
|
|
!this.inputTarget.value.includes('@')
|
|
|
|
) {
|
2024-06-07 10:06:40 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = new URL(this.urlValue, document.baseURI);
|
|
|
|
url.searchParams.append('email', this.inputTarget.value);
|
|
|
|
|
|
|
|
const data: checkEmailResponse | null = await httpRequest(
|
|
|
|
url.toString()
|
|
|
|
).json();
|
|
|
|
|
2024-07-01 10:38:43 +02:00
|
|
|
if (data && data.suggestions && data.suggestions.length > 0) {
|
|
|
|
this.suggestionTarget.innerHTML = data.suggestions[0];
|
2022-12-20 17:51:36 +01:00
|
|
|
show(this.ariaRegionTarget);
|
2024-07-29 18:09:15 +02:00
|
|
|
this.ariaRegionTarget.focus();
|
2022-12-20 17:51:36 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
accept() {
|
|
|
|
hide(this.ariaRegionTarget);
|
|
|
|
this.inputTarget.value = this.suggestionTarget.innerHTML;
|
|
|
|
this.suggestionTarget.innerHTML = '';
|
2024-09-19 11:31:06 +02:00
|
|
|
const nextTarget = document.querySelector<HTMLElement>(
|
|
|
|
'[data-email-input-target="next"]'
|
|
|
|
);
|
|
|
|
if (nextTarget) {
|
|
|
|
nextTarget.focus();
|
|
|
|
}
|
2022-12-20 17:51:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
discard() {
|
|
|
|
hide(this.ariaRegionTarget);
|
|
|
|
this.suggestionTarget.innerHTML = '';
|
2024-09-19 11:31:06 +02:00
|
|
|
const nextTarget = document.querySelector<HTMLElement>(
|
|
|
|
'[data-email-input-target="next"]'
|
|
|
|
);
|
|
|
|
if (nextTarget) {
|
|
|
|
nextTarget.focus();
|
|
|
|
}
|
2022-12-20 17:51:36 +01:00
|
|
|
}
|
|
|
|
}
|