Skip to content

Instantly share code, notes, and snippets.

@ef4
Created November 29, 2022 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ef4/67569b763249a6c3d9561360eb10ac51 to your computer and use it in GitHub Desktop.
Save ef4/67569b763249a6c3d9561360eb10ac51 to your computer and use it in GitHub Desktop.
Ember ShadowRoot component that works in a single render pass
import Component from '@glimmer/component';
// This component renders its contents in a shadow root:
//
// <ShadowRoot>stuff</ShadowRoot>
//
// Critically, it renders in a single render pass. The more natural
// modifier-based solutions do not.
//
// The "trick" we're relying on here is the little-known feature that helpers
// can return DOM elements. Thus our helper can create an element and prepare
// the shadow root synchronously before in-element tries to render into it.
export default class ShadowRootComponent extends Component {
<template>
{{ (this.createShadowRoot) }}
{{#in-element this.shadowRoot}}
{{yield}}
{{/in-element}}
</template>
createShadowRoot = () => {
if (!this.stableElement) {
this.stableElement = document.createElement('div');
this.shadowRoot = this.stableElement.attachShadow({ mode: 'open' });
}
return this.stableElement;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment