Description
Describe the problem
When creating web components with Svelte, the compiler does a good job of reflecting element attributes to properties, but not the other way around. Of course, this is only possible with limited types of data, but is preferable for producing optimised styling / output.
There are instance properties which are nice to have reflected for styling and searching.
<my-component selected></my-component>
<!-- this may render to `<my-component></my-component>` with the selected set as property -->
myComponent.selected = true; // this will not be reflected in attribute, therefore the `selected` css attribute selector will not match
:host([selected]) {
/* selected state styles: will not be applied if the property is not reflected */
}
It is also handy when it comes to finding custom elements with a certain state:
const selectedElement = myList.querySelector('my-component[selected]');
Describe the proposed solution
I would like to see a way to define properties / attribute-name map with optional value converters, which is considered when compiling to custom element.
<svelte:options
tag='my-tag'
reflections={
propertyName: 'attribute-name';
booleanPropertyName: { attribute: 'boolean-attribute-name', type: Boolean } // converts attribute value "" to `true` as property value and vice-versa
nonPrimitivePropertyName: {
attribute: 'non-primitive-attribute-name',
type: {
from: (propertyValue) => { return 'attribute-value' }
to: (attributeValue) => { return 'property-value' }
}
}
}
/>
There is a similar implementation in Lit
's property to attribute converter
Alternatives considered
Alternatively if when using custom elements as output, the rendered element's context could be accessed to set attributes on self.
edit: I've found out about get_current_component
internal function which can provide a way to actually reflect the selected properties.
Importance
would make my life easier