[WICG/webcomponents] [declarative-custom-elements] do we need DOM parts or any template mechanism in spec? (Issue #1090)

Thinking about declarative custom elements and playing with a polyfill that does load a file using the fetch API to create a shadow DOM root, I'm wondering if we absolutely need to have DOM parts, at least initially, for declarative custom elements.

My take on this is that you can have declarative custom elements without any form of templating:

- the main document includes a custom elements declared in an inline template or in an external file that is taken as template content
- when the custom elements is used, the template in put as it is as shadow root without any templating whatsoever
- slots can be used for minimal templating needs
- any inline script tag within the template is executed when the template is instanciated as a shadow root, this script can perform DOM transformations to adjust the markup on the context
- the script can use the `slotchange` event to detect if the content of a slot is changed to adjust the DOM

Example:

```html
<head>
  <link rel="custom-element" href="custom-element.html" />
</head>
<body>
  <custom-element>
    <span slot="data" data-title="Abc" data-code="123"></span>
  </custom-element>
</body>
```

and in custom-element.html:

```html
<template element="custom-element">
  <div>
    <slot name="data"></slot><!-- display none on this seems to block slot filling -->
    <h1>This is custom element title <span class="title">unknown</span></h1>
    <p>Code is <span class="code">000</span></p>
    <script>
      (() => {
        let titleElem = document.currentScript.parentElement.querySelector('.title')
        let codeElem = document.currentScript.parentElement.querySelector('.code')
        let dataSlot = document.currentScript.parentElement.querySelector('slot[name=data]')

        dataSlot.addEventListener('slotchange', (e) => bindData())
        bindData()

        function bindData(){
          let dataset = dataSlot.assignedNodes()[0]?.dataset
          titleElem.textContent = dataset?.title
          codeElem.textContent = dataset?.code
        }
      })()
    </script>
  </div>
</template>
```

Here, vanilla javascript is used to perform templating, but any templating library can be used in the same way as long as the template respects standard HTML syntax.

DOM Parts can be used later to incrementally improve on this.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/1090
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/1090@github.com>

Received on Friday, 6 December 2024 00:26:20 UTC