Shadow DOM form mixin

Hi,

This is really just a small extension of a previous Forum post (Into the shadow (DOM)) about using the shadow DOM. That previous Forum post concerned a component that enveloped its HTML in a shadow DOM. I’ve re-written that component to an Anvil form mixin (which feels more appropriate and elegant).

By letting an Anvil form inherit from the mixin (of course alongside HtmlTemplate or the form’s specific template) the form gets an additional ‘shadow_html’ property. This property works in parallel (or rather from the inside of) the form’s regular ‘html’.

self.shadow_html = """
  <style>
    button {
      color: red;
    }
  </style>
  <button>Shadow button</button>
  <div anvil-slot="shadow"></div>
"""

The content of the ‘shadow_html’ automatically gets wrapped in a shadow DOM and the elements inside ‘shadow_html’ can be accessed via the read-only ‘shadowRoot’ property, e.g.:

self.shadowRoot.querySelector('button')

By default, the shadow DOM is appended to the Anvil form’s HTML (i.e., at the bottom). You can, however, specify a specific location for the shadow DOM in the form’s ‘html’. This is done by creating an element in ‘html’ with the attribute ‘shadow-wrapper’ :

self.html = """
  <div shadow-wrapper></div>  <!-- The shadow DOM goes here -->
  <h1>Regular HTML</h1>
  <div anvil-slot="main"></div>
"""

You should not put anything inside of such ‘shadow-wrapper’ element (this is done via the ‘shadow_html’ attribute; if you do write something inside a ‘shadow-wrapper’ element it will just be ignored). Also, do not add more than one ‘shadow-wrapper’ element in ‘html’ (if you do, an ‘HtmlError’ exception will be raised).

HTML elements with the ‘anvil-slot’ attribute can be placed inside the ‘shadow-html’. This allows you to place Anvil component in the shadow DOM with the mixin method:

self.add_component_to_shadow(Label(text="Label in shadow"), slot='shadow')

Be aware, however, that due to the isolating nature of the shadow DOM, Anvil components in the shadow DOM may lose some of their (DOM class-based) properties, obviously including styling. For this reason, you’ll see a printed warning if you place one or more elements with the ‘anvil-slot’ attribute inside ‘shadow_html’. A similar warning will be triggered if you subsequently place Anvil components inside the shadow DOM (with the ‘add_component_to_shadow’).

Apologies for my “spam-level” focus on this subject. If it’s inappropriate to post such somewhat “specialized” stuff in this channel, please let me know. I’ll take no offense :blush:. Otherwise, any other feedback, recommendations and comments will be much appreciated. Thx.

Mixin and demo:
https://anvil.works/build#clone:VOD7FJZP2EJAS4H6=2T6CWQGYN5L3NAZJVK2DA5ZZ

2 Likes