bitovi / bitovi/react-to-web-component
Boolean attribute doesn't behave as might by expected for web component
- Dominant language
- TypeScript
- Stars
- 944
- Forks
- 52
- PR merge metrics
- No merged PRs in 30d
Description
Hi!
I noticed that the chosen behaviour for boolean transform is
https://github.com/bitovi/react-to-web-component/blob/1a6886a221e9f23710c7ba958d6d260bf8f7dc43/packages/core/src/transforms/boolean.ts#L3-L6
which is:
> it's `true` if value of attribute starts with `t`, `y` or a non-0 number.
and it's tested:
https://github.com/bitovi/react-to-web-component/blob/002a007c40fa67fc95c9cddbfde335b22a949ed8/tests/react-to-webcomponent.test.jsx#L352-L353
On the other hand HTML boolean (https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML) attribute is considered `true` just because it's present:
> If an HTML tag contains a boolean attribute - no matter the value of that attribute - the attribute is set to `true` on that element. If an HTML tag does not contain the attribute, the attribute is set to `false`.
That leads to interesting behaviour - if attribute is present, but not assigned a value (i.e. it's HTML Boolean), it's cast to `false` (not just `undefined` but actually the polar opposite)
I detected it wile using with Lit booleans (https://lit.dev/docs/templates/expressions/#boolean-attribute-expressions) - Lit implements HTML boolean.
---
I think it can be resolved in a backwards compatible way.
I see that transforms are given the attribute name as 2nd argument
- in constructor
https://github.com/bitovi/react-to-web-component/blob/002a007c40fa67fc95c9cddbfde335b22a949ed8/packages/core/src/core.ts#L100
- in `attributeChangedCallback`
https://github.com/bitovi/react-to-web-component/blob/002a007c40fa67fc95c9cddbfde335b22a949ed8/packages/core/src/core.ts#L130
So parse could be made into
```ts
parse: (value, attribute) =>
// Check if it's HTML boolean
value === undefined
|| value === ''
|| value === attribute
/// Check if it's boolean by value
|| /^[ty1-9]/i.test(value),
```
I don't have an idea for `stringify`, though. It would have to be a choice of the author (i.e. differently named transform) I guess
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.