2024-10-22 22:09:43 +02:00
|
|
|
import { hide, httpRequest, show } from '@utils';
|
2022-12-20 17:51:36 +01:00
|
|
|
import { ApplicationController } from './application_controller';
|
|
|
|
|
2024-10-22 22:09:43 +02:00
|
|
|
type CheckEmailResponse =
|
|
|
|
| {
|
|
|
|
success: true;
|
2024-10-24 13:17:34 +02:00
|
|
|
suggestions?: string[];
|
2024-10-22 22:09:43 +02:00
|
|
|
}
|
|
|
|
| { success: false };
|
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);
|
|
|
|
|
2024-10-22 22:09:43 +02:00
|
|
|
const data = await httpRequest(url.toString())
|
|
|
|
.json<CheckEmailResponse>()
|
|
|
|
.catch(() => null);
|
2024-06-07 10:06:40 +02:00
|
|
|
|
2024-10-22 22:09:43 +02:00
|
|
|
if (data?.success) {
|
2024-10-24 13:17:34 +02:00
|
|
|
const suggestion = data.suggestions?.at(0);
|
2024-10-22 22:09:43 +02:00
|
|
|
if (suggestion) {
|
|
|
|
this.suggestionTarget.innerHTML = suggestion;
|
|
|
|
show(this.ariaRegionTarget);
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|