Skip to content

Instantly share code, notes, and snippets.

@thomasloven
Last active August 15, 2023 06:09
Show Gist options
  • Save thomasloven/5f965bd26e5f69876890886c09dd9ba8 to your computer and use it in GitHub Desktop.
Save thomasloven/5f965bd26e5f69876890886c09dd9ba8 to your computer and use it in GitHub Desktop.
How to use ha elements when using ScopedRegistry
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import { ScopedRegistryHost } from "@lit-labs/scoped-registry-mixin";
@customElement("customelement-test")
class CustomElementTest extends ScopedRegistryHost(LitElement) {
@property() hass;
static elementDefinitions = {
"ha-card": customElements.get("ha-card"), // This works because ha-card is ALWAYS loaded before custom cards (for now)
};
setConfig(config) {}
firstUpdated() {
// Elements can only be added to the local customElement registry after
// createRenderRoot has run(which ScopedRegistryRoot handles).
// It's definitely run before first render, so firstUpdated can be a good
// place to start loading elements.
this.loadEntityPicker();
}
async loadEntityPicker() {
// Get the local customElement registry
const registry = (this.shadowRoot as any)?.customElements;
if (!registry) return;
// Check if the element we want is already defined in the local scope
if (registry.get("ha-entity-picker")) return;
// Load in ha-entity-picker
// This part will differ for every element you want
const ch = await (window as any).loadCardHelpers();
const c = await ch.createCardElement({ type: "entities", entities: [] });
await c.constructor.getConfigElement();
// Since ha-elements are not using scopedRegistry we can get a reference to
// the newly loaded element from the global customElement registry...
const haEntityPicker = window.customElements.get("ha-entity-picker");
// ... and use that reference to register the same element in the local registry
registry.define("ha-entity-picker", haEntityPicker);
}
render() {
return html`
<ha-card>
Hello! <ha-entity-picker .hass=${this.hass}></ha-entity-picker>
</ha-card>
`;
}
}
@Makin-Things
Copy link

@thomasloven this no longer appears to work with 2022.11bx. The call to window.customElements.get("ha-entity-picker"); returns undefined.

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