Debian Codegraph @

packages/labs/scoped-registry-mixin/src/scoped-registry-mixin.ts

raw
1 /**
2 * @license
3 * Copyright 2021 Google LLC
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 import type {LitElement} from 'lit';
8 import {adoptStyles} from '@lit/reactive-element/css-tag.js';
9
10 // Proposed interface changes
11 declare global {
12 interface ShadowRootInit {
13 customElements?: CustomElementRegistry;
14 }
15 interface ShadowRoot {
16 importNode(node: Node, deep?: boolean): Node;
17 }
18 }
19
20 // eslint-disable-next-line @typescript-eslint/no-explicit-any
21 type LitElementConstructor = new (...args: any[]) => LitElement;
22
23 export type ElementDefinitionsMap = {
24 [key: string]: typeof HTMLElement;
25 };
26
27 export function ScopedRegistryHost<SuperClass extends LitElementConstructor>(
28 superclass: SuperClass
29 ): SuperClass {
30 return class ScopedRegistryMixin extends superclass {
31 /**
32 * Obtains the scoped elements definitions map
33 */
34 static elementDefinitions?: ElementDefinitionsMap;
35 static registry?: CustomElementRegistry;
36
37 override createRenderRoot() {
38 const constructor = this.constructor as typeof ScopedRegistryMixin &
39 typeof LitElement;
40
41 const {registry, elementDefinitions, shadowRootOptions} = constructor;
42
43 if (elementDefinitions && !registry) {
44 constructor.registry = new CustomElementRegistry();
45
46 Object.entries(elementDefinitions).forEach(([tagName, klass]) =>
47 constructor.registry!.define(tagName, klass)
48 );
49 }
50
51 const renderRoot = (this.renderOptions.creationScope = this.attachShadow({
52 ...shadowRootOptions,
53 customElements: constructor.registry,
54 }));
55
56 adoptStyles(
57 renderRoot,
58 (this.constructor as typeof LitElement).elementStyles!
59 );
60
61 return renderRoot;
62 }
63 };
64 }