Skip to content

Commit

Permalink
fix(input-field): avoid validating during render
Browse files Browse the repository at this point in the history
Avoids repeatedly checking validity while rendering, which might cause
`invalid` events to be emitted multiple times.
  • Loading branch information
vicgeralds committed May 14, 2024
1 parent 01ce9be commit 6e23563
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/components/input-field/input-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export class InputField {
private isFocused: boolean = false;

@State()
private isModified: boolean = false;
private wasInvalid: boolean = false;

@State()
public showCompletions: boolean = false;
Expand Down Expand Up @@ -356,6 +356,10 @@ export class InputField {
if (newValue !== this.mdcTextField.value) {
this.mdcTextField.value = newValue || '';
}

if (this.wasInvalid) {
this.validate();
}
}

@Watch('completions')
Expand Down Expand Up @@ -493,7 +497,7 @@ export class InputField {

private onBlur = () => {
this.isFocused = false;
this.isModified = true;
this.validate();
this.changeEmitter.flush();
};

Expand Down Expand Up @@ -582,16 +586,27 @@ export class InputField {
return true;
}

if (!this.isModified) {
return false;
return this.wasInvalid;
};

private validate = () => {
if (this.readonly || this.invalid) {
this.wasInvalid = false;

return;
}

const element = this.getInputElement();

return !(element && element.checkValidity());
if (element) {
this.wasInvalid = !element.checkValidity();
}
};

private getInputElement = (): HTMLInputElement | HTMLTextAreaElement => {
private getInputElement = ():
| HTMLInputElement
| HTMLTextAreaElement
| null => {
let elementName = 'input';
if (this.type === 'textarea') {
elementName = 'textarea';
Expand Down

0 comments on commit 6e23563

Please sign in to comment.