Config
By default, @beforesemicolon/web-component creates an encapsulated Shadow DOM for each component. You can customize the Shadow DOM configuration or completely opt out of it using the config class property.
Default Configuration
If you do not define a custom config property, the component defaults to the following settings:
1class MyComponent extends WebComponent {2 config = {3 shadow: true,4 mode: 'open',5 delegatesFocus: false,6 clonable: false,7 serializable: false,8 slotAssignment: 'named',9 }10}Disabling Shadow DOM
In some scenarios, you might want a component to render directly into the Light DOM (e.g. to inherit all global CSS stylesheets easily or to construct headless components). You can do this by setting shadow: false on the config object.
1import { WebComponent, html } from '@beforesemicolon/web-component'2 3class LightDomElement extends WebComponent {4 config = {5 shadow: false,6 }7 8 render() {9 return html` <p>I am rendered directly in the light DOM!</p> `10 }11}12 13customElements.define('light-dom-element', LightDomElement)[!NOTE] When
shadow: falseis configured,this.contentRootwill reference the component element itself rather than aShadowRoot. Dynamic stylesheets defined via thestylesheetproperty will not be scoped and may apply globally.
Shadow DOM Configuration Options
When shadow is set to true, the rest of the configuration properties are passed directly to the native Element.attachShadow() method.
| Option | Type | Default | Description |
|---|---|---|---|
shadow | boolean | true | Enables or disables Shadow DOM rendering. |
mode | 'open' | 'closed' | 'open' | Defines accessibility to the shadow root from outside JavaScript. If 'open', the shadow root is accessible via element.shadowRoot. |
delegatesFocus | boolean | false | When set to true, clicking a non-focusable part of the shadow DOM delegates focus to the first focusable element inside the shadow root. |
clonable | boolean | false | If set to true, the shadow root can be cloned using cloneNode() (supported in newer specifications). |
serializable | boolean | false | If set to true, the shadow root will be serialized when using APIs like getHTML() for Declarative Shadow DOM. |
slotAssignment | 'named' | 'manual' | 'named' | Controls how nodes are assigned to slots. 'named' assigns elements automatically based on their slot attribute. 'manual' requires programmatic node assignment. |
Example: Focus Delegation & Closed Shadow Root
Here is an example of configuring a closed shadow root with focus delegation enabled:
1import { WebComponent, html } from '@beforesemicolon/web-component'2 3class FocusInput extends WebComponent {4 config = {5 shadow: true,6 mode: 'closed',7 delegatesFocus: true,8 }9 10 render() {11 return html`12 <div class="wrapper">13 <label for="input">Enter text:</label>14 <input id="input" type="text" />15 </div>16 `17 }18}19 20customElements.define('focus-input', FocusInput)