Skip to content

Commit

Permalink
refactor: some improvements + not only add listener on required fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Nakahiru committed Sep 18, 2024
1 parent b72234a commit 8ee4827
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,50 +40,50 @@ export default class NavbarFormErrorHandler {

private readonly navbarHandler: NavbarHandler;

private firstInvalidField: HTMLElement | null = null;

constructor(options: NavbarFormErrorHandlerType) {
this.navbarHandler = options.navbarHandler;
this.form = options.form;

this.initListener();
this.resetInvalidField();
}

private findRequiredFieldsFromForm(): NodeListOf<HTMLElement> {
return this.form.querySelectorAll('[required]');
private findAllFormFields(): NodeListOf<HTMLElement> {
return this.form.querySelectorAll('input, select, textarea');
}

private initListener(): void {
this.findRequiredFieldsFromForm().forEach((field) => {
field.addEventListener('invalid', () => {
if (!this.firstInvalidField) {
this.firstInvalidField = field;
let isFirstInvalidField = false;

const tab = field.closest('[role="tabpanel"]');
this.findAllFormFields().forEach((field) => {
field.addEventListener('invalid', () => {
if (isFirstInvalidField) {
return;
}

if (!tab || typeof tab === null) {
throw new Error('NavbarFormErrorHandler: Cannot find the tab that contains some form fields in error.');
}
isFirstInvalidField = true;

if (!('id' in tab)) {
throw new Error('NavbarFormErrorHandler: Id missing from the tab.');
}
const tab = field.closest('[role="tabpanel"]');

this.navbarHandler.switchToTarget(`#${tab.id}`);
if (!tab || typeof tab === null) {
throw new Error('NavbarFormErrorHandler: Cannot find the tab that contains some form fields in error.');
}

field.scrollIntoView({
behavior: 'smooth',
block: 'end',
});
if (!('id' in tab)) {
throw new Error('NavbarFormErrorHandler: Id missing from the tab.');
}

this.navbarHandler.switchToTarget(`#${tab.id}`);

field.scrollIntoView({
behavior: 'smooth',
block: 'end',
});

// Set a timeout to reset the flag after the current event loop
setTimeout(() => {
isFirstInvalidField = false;
}, 0);
});
});
}

private resetInvalidField() {
this.form.addEventListener('click', () => {
this.firstInvalidField = null;
}, true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export default {
freeShippingInput: 'input[name="carrier[shipping_settings][is_free]"]',
zonesInput: '#carrier_shipping_settings_zones',
zoneIdOption: (zoneId: number|string): string => `option[value="${zoneId}"]`,
navigationBar: '#form-nav',
rangesInput: '#carrier_shipping_settings_ranges_data',
rangesSelectionAppId: '#carrier_shipping_settings_ranges-app',
addRangeButton: '.js-add-carrier-ranges-btn',
Expand Down

0 comments on commit 8ee4827

Please sign in to comment.