Fix attributeChangedCallback when calling setValidity #136
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 (specificallyaria-invalid
).In comparison to other attribute modification methods (
removeAttribute
andtoggleAttribute
),setAttribute
always triggersattributeChangedCallback
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:
This approach works perfect with a native
ElementInternals
but with polyfill it resolves into infinite loop. Every call tosetValidity
hasref.setAttribute('aria-invalid', `${!valid}`)
inside which triggers anotherattributeChangedCallback
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 triggerattributeChangedCallback
.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.