An open API service indexing awesome lists of open source software.

https://github.com/tram-one/shadowroot-injector

🪡 declaratively define shadowroots to repeat in HTML templates
https://github.com/tram-one/shadowroot-injector

Last synced: 9 months ago
JSON representation

🪡 declaratively define shadowroots to repeat in HTML templates

Awesome Lists containing this project

README

          

# ShadowRoot Injector

_🪡 declaratively define shadowroots to repeat in HTML templates_

## What is ShadowRoot Injector?

ShadowRoot Injector lets you define templates for elements using HTML. When those elements appear in the DOM, the
library will automatically insert a template into the element. You can then, optionally, upgrade the element using
native web-component definitions (either inline in a script tag, or imported as a separate component definition).

### Example

The example below shows a markdown callout. You can see a running example live on
[codepen](https://codepen.io/JRJurman/pen/MYaKErE).

```html



:host,
slot {
display: block;
}

details {
display: block;
border-left: solid 3px rgb(var(--callout-color));
background: rgba(var(--callout-color), 0.1);
padding: 0.5em;
}

summary {
font-weight: bold;
color: rgb(var(--callout-color));
list-style: none;
}






ShadowRoot Injector lets you repeat templates easily, no JS required!


Pro Tip!
If you want to add more behavior, you can upgrade custom-elements into web-components any time with JavaScript!

You can check out the repository on Github.


PRs Welcome!
You can make git issues or pull requests for any issues you find.

```

### Why?

Today, there isn't a native or elegant way to repeat HTML content across the document without building a javascript
component definition. For many simple authoring use-cases, just having a template that should appear is all that web
authors need. This library gives you an easy and elegant way to do that, without the boilerplate or complexities
associated with building javascript class definitions.

## How to use

You can include ShadowRoot Injector by using a CDN of your choice.

```html

```

You can also use the minified version by pointing to the minified asset

```html

```

### HTML API

The HTML API is completely driven by attributes on the `` web component. When you include both of the
following attributes, ShadowRoot Injector will automatically kick off and register a child template node to be used for
new and existing elements in the document.


selector

The CSS selector to look for to attach shadow roots on. When these elements appear in the DOM, we'll automatically inject a template into them. The selector must point to an element that can accept shadow roots (see Elements you can attach a shadow root to).

mode

The ShadowRoot mode property. This must be defined as a valid value for ShadowRoot modes, either open or closed.

You may also include any valid
[ShadowRoot template properties](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#attributes)
on the child template element. This includes `shadowrootdelegatesfocus`, `shadowrootclonable`, or even
`shadowrootcustomelementregistry`.

### JS API

While not required, you can use the JavaScript API to interface directly with a ShadowRoot Injector instance. This can
also be useful when you need to control when the shadow root is injected in defined web components.

All the API methods below are method calls you can make on an instance of the `ShadowRootInjector` class.

```html
...

injector.injectRegisteredTemplate(myTestNode);

```


shadowRootInjector.injectRegisteredTemplate(node: HTMLElement)

This function takes in an HTML Element, and injects the ShadowRoot template associated with the existing instance of the shadow root injector.

## Task List Example

To see these APIs come together, lets look at a more complex Task List example, step by step (you can see the entire
file in `example/task-list.html`). You can see it live on [codepen](https://codepen.io/JRJurman/pen/JoYGrpe).

First, we'll import the library and build a template definition for a single `task-item`. It has some styles, and some
basic markup.

```html



:host {
display: list-item;
}
li {
display: flex;
gap: 12px;
}



  • remove

  • ```

    We'll create a list to hold some hard-coded task items.

    ```html


      Add Items
      Remove Items

    ```

    If we stopped here, the task items would present as we'd expect, but wouldn't be interactive. To make it interactive,
    we'll upgrade our `task-item` custom element into a web component, with event listeners and all. Any existing
    `task-item` elements in the page will upgrade automatically.

    > [!important]
    > In the `connectedCallback`, we call `shadowRootInjector.injectRegisteredTemplate(this);`. By doing this,
    > we'll ensure that we have access to shadowRoot elements for the rest of the function.

    ```html

    const taskItemShadowRootInjector = document.querySelector('shadowroot-for[selector="task-item"]');

    customElements.define(
    'task-item',
    class extends HTMLElement {
    connectedCallback() {
    taskItemShadowRootInjector.injectRegisteredTemplate(this);
    this.shadowRoot.querySelector('button').addEventListener('click', () => {
    this.remove();
    });
    }
    },
    );

    ```

    Finally we add a control to create new `task-item` elements. Any new `task-items` created will be defined by the class
    definition above.

    > [!note]
    > If we hadn't called `taskItemShadowRootInjector.injectRegisteredTemplate` directly, the ShadowRootInjector library would still
    > inject shadowRoot templates after the element was attached to the page.

    ```html

    Add Task

    addTaskInput.addEventListener('keyup', (event) => {
    if (event.code === 'Enter') {
    const newListItem = document.createElement('task-item');
    newListItem.textContent = addTaskInput.value;
    addTaskInput.value = '';
    taskList.append(newListItem);
    }
    });

    ```

    ## Contributions / Discussions

    If you think this is useful or interesting, I'd love to hear your thoughts! Feel free to
    [reach out to me on mastodon](https://fosstodon.org/@jrjurman), or join the
    [Tram-One discord](https://discord.gg/dpBXAQC).