crisward / svelte-tag

MIT License
52 stars 8 forks source link

Interopability with HomeAssistant #9

Closed MichaelBrunn3r closed 2 years ago

MichaelBrunn3r commented 2 years ago

HomeAssistant allows you to add custom UI components by creating custom elements. Unfortunatelly, the API expects some extra class members (see docs):

class Cardextends HTMLElement {
    set hass(hass) {
        ...
    }

    setConfig(config) {
        ...
    }
}

Using the svelte builtin way of custom elements I just had to export a prop hass and a prop setConfig: () => {...} and and svelte generated the neccessary accessors (set/get) on the class. (Although some of these accessors are useless, setConfig is a function and does not need any, but this seems to be the only way to create custom class members)

It seems that svelte-tag does not create these accessors so HomeAssistant complains that setConfig does not exist. Is there any way we can generate these accessors?

crisward commented 2 years ago

Svelte tag isn't a build system or compiler (unlike svelte), so can't easily do this kind of thing. However you should be able to fork this repo and add any methods you like to the class. See https://github.com/crisward/svelte-tag/blob/fd61d4dd4d174f11cb88ab6af060ba22ba47dd78/index.js#L34

If you don't want the whole repo, just copying the index.js file should be enough.

Hope that helps.

MichaelBrunn3r commented 2 years ago

This seems to be the best solution. I didn't realy create a fork, but based my code on it. I also stumbled upon more complications that legitimize a custom solution. Once its more mature I might release it as a package. All plugins I have seen so far write LitElements by hand, kinda gnarly for reactivity. Since Svelte is compiled it was relatively "easy" to figure out how to insert a Svelte App as a CustomElement with an adapter for HomeAssistant.

Your code realy helped me understand all the magic happening in the background.

crisward commented 2 years ago

Thanks, good to know.

I got some of my code from previous bits shared by others. Also tried lit with similar issues. Used React, Preact, messed with Vue and Lit and svelte seems to have by far the simplest, easiest to use state management. Lit feels a lot closer to the standards, it's a shame its dev-ex isn't as nice.