Created
November 29, 2022 19:05
-
-
Save ef4/67569b763249a6c3d9561360eb10ac51 to your computer and use it in GitHub Desktop.
Ember ShadowRoot component that works in a single render pass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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