Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix attributeChangedCallback when calling setValidity #136

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Yavanosta
Copy link

Context

Polyfill works differently than native implementation because it is limited by browser capabilities. Specifically polyfill lacks special interaction of ElementInternals with a11y tools (like screen readers).

Native ElementInternals reports validity status to screen readers without using aria-* attributes (specifically aria-invalid).

In comparison to other attribute modification methods (removeAttribute and toggleAttribute), setAttribute always triggers attributeChangedCallback even if the actual value has not changed.

Problem

In my code I call setValidity from attribute changed callback. My component's validation relies on attributes, so when they have changed it makes sense to revalidate it.

Simplifying I can illustrate the problem with the following code:

class MyComponent extends HTMLElement {
  // ...
  attributeChangedCallback() {
    this.internals.setValidity(this.validate(), 'error message');
  }
  
  private validate() {
    const maxLength = Number(this.getAttribute('max-length'))
    return {tooLong: (this.value.length > maxLength)}
  }
  // ...
}
<my-component max-length="50" value="hello"></my-component>

This approach works perfect with a native ElementInternals but with polyfill it resolves into infinite loop. Every call to setValidity has ref.setAttribute('aria-invalid', `${!valid}`) inside which triggers another attributeChangedCallback and so on.

While it is easy to fix the problem in my code (i can filter which attributes will trigger revalidation) I think it worth it to fix the library as well.

It took me quite some time to find this bug because it only reproducible with the polyfill and the root cause is behaviour difference between Polyfill and native implementation. I absolutely did not expect ElementInternals to trigger attributeChangedCallback.

While I understand the need to do that, I think with this additional check we can limit the impact of this difference and at least avoid infinite loops.

@Yavanosta Yavanosta marked this pull request as ready for review October 17, 2024 06:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant