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

Custom Elements - Property reflection in attributes #7535

Closed
itutto opened this issue May 16, 2022 · 1 comment
Closed

Custom Elements - Property reflection in attributes #7535

itutto opened this issue May 16, 2022 · 1 comment

Comments

@itutto
Copy link

itutto commented May 16, 2022

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

@baseballyama
Copy link
Member

Duplicate of #5705

@baseballyama baseballyama marked this as a duplicate of #5705 Feb 26, 2023
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

No branches or pull requests

2 participants