dom icon indicating copy to clipboard operation
dom copied to clipboard

feature: `element.getShadow(opts)`

Open trusktr opened this issue 4 years ago • 3 comments

This would be an alternative to element.attachShadow(opts). It would be similar to canvas.getContext in that if a root is not already created/attached, it will create/attach the root before returning the root. If a root is already created, the existing root will be returned. This would make it easier to write code like this:

class MyEl extends HTMLElement {
  connectedCallback() {
    this.getShadow(opts).innerHTML = `...`
  }
}

without having to write extra code to handle whether or not a root already exists.

On a related note, maybe a similar utility would be nice for ElementInternals?

trusktr avatar Jan 14 '22 21:01 trusktr

Hmm, that makes closed roots easy to get, doesn't it. Who actually uses closed roots?

Maybe this is better as an ElementInternals API? For example:

#internals = this.attachInternals()

connectedCallback() {
  this.#internals.getShadow(opts).innerHTML = `...`
}

trusktr avatar Jan 14 '22 21:01 trusktr

Why create it on document connection and not when the element is created?

annevk avatar Jan 17 '22 11:01 annevk

You could just do the following right? (See here)

const shadowRoot = this.#internals.shadowRoot ?? this.attachShadow({ ...opts });

Whether it is worth abstracting this into a new method I'm not sure. Although I would ask are empty shadow roots really so expensive that you can't just attach them unconditionally in the constructor? i.e.:

#internals = this.attachInternals();

constructor() {
    this.attachShadow({ ...opts });
}

connectedCallback() {
    this.#internals.shadowRoot.innerHTML = `...`;
}

Jamesernator avatar Jan 31 '22 02:01 Jamesernator