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

feat: hyphenated attributes in custom elements #7638

Conversation

WIStudent
Copy link

While creating web components with svelte I noticed that it is not possible to use hyphenated (kebab-case) attributes.

Others described some workarounds by extending the web component again after it was created by svelte (#3852 (comment)), but as far as I could see no one proposed a solution for this problem in svelte itself yet. So I thought I give it a try.

This PR adds a mapping between kebab-case web component attributes and camel-case svelte properties.

A svelte property like this

<svelte:options tag="custom-element"/>

<script>
  export let customAttribute;
</script>

<p>{customAttribute}</p>

can then be set like this:

<custom-element custom-attribute="some value"></custom-element>

Before submitting the PR, please make sure you do the following

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • Prefix your PR title with [feat], [fix], [chore], or [docs].
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with npm test and lint the project with npm run lint

@WIStudent
Copy link
Author

Also I just saw that the kebab to camel-case mapping was also proposed in #875 but was never implemented. Not sure why though.

@taylorylee
Copy link

Hi, I am reopening this thread. I am running into similar problems and was wondering when kebab-case will be supported in Svelte. I am running into the same problem as https://github.com/sveltejs/svelte/issues/3852[Issue 3852](#3852)

I am using VSCode right now

@joelhickok
Copy link

This is one of those things... where if you just ignore it long enough, maybe it will go away? But it is NOT going away,. People are still trying to use hyphenated attributes, since it is the way that HTML Elements are specified, after all. This has always driven me crazy about Svelte, but I love Svelte and forgive it for it's occasional flaws.

Still, PLEASE, can't a solution be agreed on here?

@joelhickok
Copy link

joelhickok commented Jan 11, 2023

Whoops, I meant to post in my last post to, for people forced to use hyphenated props for some reason, and still want reactivity, you can watch the $$props value in your child component. This does work, and you can reassign the $$props properties to internal component variables.

let myValue = null

$: {
    console.log($$props)
    myValue = $$props['my-value']
}

@baseballyama baseballyama added this to the 4.x milestone Feb 26, 2023
@benmccann benmccann changed the title [feat] Support hyphenated attributes in custom elements feat: hyphenated attributes in custom elements Mar 14, 2023
@dummdidumm dummdidumm mentioned this pull request Apr 11, 2023
5 tasks
@benmccann benmccann changed the base branch from master to version-4 April 11, 2023 21:06
@vercel
Copy link

vercel bot commented Apr 19, 2023

@benmccann is attempting to deploy a commit to the Svelte Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Member

@benmccann benmccann left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it matters for this PR as it will be superseded by #8457, but next time you should use snake_case for internal variable names to match the existing code style

dummdidumm added a commit that referenced this pull request May 2, 2023
This is an overhaul of custom elements in Svelte. Instead of compiling to a custom element class, the Svelte component class is mostly preserved as-is. Instead a wrapper is introduced which wraps a Svelte component constructor and returns a HTML element constructor. This has a couple of advantages:

- component can be used both as a custom element as well as a regular component. This allows creating one wrapper custom element and using regular Svelte components inside. Fixes #3594, fixes #3128, fixes #4274, fixes #5486, fixes #3422, fixes #2969, helps with sveltejs/kit#4502
- all components are compiled with injected styles (inlined through Javascript), fixes #4274
- the wrapper instantiates the component in `connectedCallback` and disconnects it in `disconnectedCallback` (but only after one tick, because this could be a element move). Mount/destroy works as expected inside, fixes #5989, fixes #8191
- the wrapper forwards `addEventListener` calls to `component.$on`, which allows to listen to custom events, fixes #3119, closes #4142 
- some things are hard to auto-configure, like attribute hyphen preferences or whether or not setting a property should reflect back to the attribute. This is why `<svelte:options customElement={..}>` can also take an object to modify such aspects. This option allows to specify whether setting a prop should be reflected back to the attribute (default `false`), what to use when converting the property to the attribute value and vice versa (through `type`, default `String`, or when `export let prop = false` then `Boolean`), and what the corresponding attribute for the property is (`attribute`, default lowercased prop name). These options are heavily inspired by lit: https://lit.dev/docs/components/properties. Closes #7638, fixes #5705
- adds a `shadowdom` option to control whether or not encapsulate the custom element. Closes #4330, closes #1748 

Breaking changes:
- Wrapped Svelte component now stays as a regular Svelte component (invokeing it like before with `new Component({ target: ..})` won't create a custom element). Its custom element constructor is now a static property named `element` on the class (`Component.element`) and should be regularly invoked through setting it in the html.
- The timing of mount/destroy/update is different. Mount/destroy/updating a prop all happen after a tick, so `shadowRoot.innerHTML` won't immediately reflect the change (Lit does this too). If you rely on it, you need to await a promise
@dummdidumm
Copy link
Member

Closed via #8457, to be released in Svelte 4

@patricknelson
Copy link

For clarity and for my future reference (and anyone else landing here): The kebab-case to camelCase conversion will not happen automatically but must instead be explicitly mapped. However, lowercase to camelCase conversion will be done by default (as inspired by Lit per #8457).

For example (tested in svelte@next currently mapped to [email protected]):

<svelte:options
	customElement={{
		tag: "custom-element",
		props: {
			camelCase1: { attribute: "camel-case1" },
		},
	}}
/>

<script>
	export let camelCase1;
	export let camelCase2;
</script>

<h1>{camelCase1} {camelCase2}</h1>

In HTML:

<custom-element camel-case1="hello" camelcase2="world"></custom-element>

In other Svelte components, you'd can still use the typical component and property syntax as usual (which you can now do in v4 even though you're compiling it as a custom element):

<CustomElement camelCase1="hello" camelCase2="world"/>

Resources: Figured this out after some research and testing. See the unit test, the docs (currently in code) and the main comment on #8457.

Finally, thank you so much @dummdidumm et al. for the work on custom elements. This is huge for those of us on alternative/hybrid stacks looking to seamlessly integrate Svelte into our projects! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants