trusktr trusktr - 21 days ago 4
HTML Question

How do we detect if a shadow root was made with v0 or v1 API?

Suppose a JS module exports

shadowRoot
which was created with either
el.createShadowRoot
or
el.attachShadow
(we don't know which). How do we detect if the root is a v0 shadow root or a v1 shadow root (i.e. how do we detect which method was used to create the root)?

f.e., What would I fill in the following conditional statements?

// for argument's sake, we don't create the root, we only get a reference
// to it:
import shadowRoot from 'somewhere'

function getShadowRootVersion(root) {
if ( ... )
return 'v0'

if ( ... )
return 'v1'
}

console.log(getShadowRootVersion(shadowRoot)) // should output "v0" or "v1".


More info:

We want to find out if a shadow root was created from
createShadowRoot
or from
attachShadow
. The resulting roots are different: in the root created with
createShadowRoot
,
<content>
elements are used for distributing elements. In roots created with
attachShadow
,
<content>
elements don't do anything, and
<slot>
elements are used instead. How do we detect which method was used to create a root (i.e. whether we have a v0 root or a v1 root)?

Answer

The following hack should work:

function isV1(shadowRoot) {
  const slot = document.createElement('slot');
  shadowRoot.appendChild(slot);
  slot.appendChild(document.createElement('div'));
  const assignedNodes = slot.assignedNodes({ flatten: true });
  slot.remove();
  return assignedNodes.length == 0;
}

IMO, there is something wrong when you have to detect it.