Skip to content

Create an EventTarget associated with the adorned element that can hold scoped state.

License

Notifications You must be signed in to change notification settings

bahrus/be-scoped

Repository files navigation

be-scoped [TODO]

be-scoped has been deprecate for now.

Use be-gingerly instead.

Sometimes when we are generating a loop of HTML on the server or on the client, we need a convenient place to pass the view model responsible for generating the data that gets interspersed into the HTML section of the loop.

One way this can be done is with an extremely light-weight rendering from the looping code (again, either on the server or the client) -- just rendering a single tag of a custom element for each iteration of the loop, and passing in the data for the view model, and let the custom element take care of the rest:

${myList.map(item => html`
    <my-item .vm=${item}></my-item>
`)}

Now our custom element can go in one of two ways: It can use Shadow DOM or not use Shadow DOM. If using Shadow DOM, the division of labor between the looping code and the custom element is pretty clear -- the looping code is expected to generate any light children, if applicable. The custom element generates all the content inside the ShadowRoot, and takes a hands-off approach towards the light children.

Things become much more ambiguous if no ShadowDOM is used. In my view, if the custom element chooses to generate its own children, that should work fine so long as the "framework" takes a "mind your own business, and don't do unnecessary work" approach to rendering. The code snippet above, which uses the "framework built into the browser" would certainly do that. It's unclear to me how uniformly that fundamental tenet is adhered to with modern frameworks. In the past, during the heyday of VDOM hype, I would see instances where the framework would appear to go through the thought process: "hey, I didn't generate those child elements, how dare anything give birth to elements I didn't give permission to? I am going to blow that all away" on a re-render. I can't vouch for what the latest state of the art frameworks do, just be forewarned.

Anyway, for the scenarios listed above, this custom enhancement doesn't add any value.

Where this enhancement may help is with another approach to looping. Let's consider first a scenario where we are almost forced to adopt an alternative approach: Where the looping code is generating rows (tr elements) of the HTMLTable element:

html`
<table>
    <thead><th>Name</th><th>SSN Number</thead>
    <tbody>
${myList.map(item => html`
    <tr>
        <td>${item.name}</td>
        <td>${item.ssn}</td>
    </tr>
`)}
    </tbody>
</table>
`

While the example above so far poses no issues, we start to immediately get a sense of unease the moment we need to start performing intimate actions on individual rows / items of the view model. How do we get access to the view model item associated with the row? We start inventing ways to handle this, with id's, lots of ugly look ups, etc. So we could have the fleeting thought "Hey, why don't I create a web component to contain each row, that can encapsulate the view model for each item of the list"? But of course the HTML decorum for tables doesn't allow us to do that.

I would venture that this problem space accounts for part of the appeal that frameworks bring to the table, beyond what can be handled by custom elements alone. Lack of an interoperable solution to this fundamental problem may be partly to blame for causing this framework "lock-in." We need an interoperable solution to this problem.

Initially, this enhancement was designed to solve that problem, by providing access to that view model via the custom enhancement protocol:

oTR.beEnhanced.beScoped.scope

But that approach felt kind of clunky to me (not to mention how wildly beyond the capabilities of any framework in use today to be able to leverage).

In addition, this doesn't provide a clean way for developers to add their own custom logic as needed into the view model, like they can do with custom elements.

So the new approach this enhancement takes is to work in conjunction with recent enhancements to the DSS, is to do the following:

We push the standard HTML vocabulary a tad in order to be as transparent as possible as far as what is happening, stretching the boolean itemscope attribute a little beyond its recognized platform role:

html`
<table>
    <thead><th>Name</th><th>SSN Number</thead>
    <tbody>
${myList.map(item => html`
    <tr itemscope=my-item>
        <td>
            <my-item .item=${item}></my-item>
            ${item.name}
        </td>
        <td>${item.ssn}</td>
`)}
    </tbody>
</table>
`

So then if the libraries we work with have an easy-to-reproduce-in-any-framework "virtual host" getter that includes logic something like this:

async function getHostish(el: Element){
    const closestItemScope = el.closest('itemscope');
    if(closestItemScope !== null){
        if(closestItemScope.localName.indexOf('-')){
            //it's a custom element so this is probably our host
            return closestItemScope;
        }
        const attr = closestItemScope.getAttribute('itemscope');
        return closestItemScope.querySelector(attr);
    }
    //get shadow root host
    return el.getRootNode().host;
}

then anywhere we would want to do: el.getRootNode().host we instead call the function above, then we can work with any combination of solution -- with ShadowDOM, without ShadowDOM, as well as scenarios where neither works, because we can't contain each HTML item, as discussed above.

In other words, having established this protocol by necessity, we can then go back to other scenarios where HTML decorum would allow for Shadowless containers, but with the ambiguity of responsibility issue listed above, and use a non visual view model custom element as our general solution, that can then circumvent some of the sticky questions regarding division of responsibility.

So what does be-scoped do?

It commits a secondary sin, and attaches a property getter, "assignGingerly" to elements that commit the cardinal sin of adding attribute "itemscope" that has a value pointing to the name of an inner custom element.

Frameworks can then pass objects (not primitives) directly to the element:

html`
<table>
    <thead><th>Name</th><th>SSN Number</thead>
    <tbody>
${myList.map(item => html`
    <tr itemscope=my-item be-scoped .assignGingerly=${item}>
        <td>
            <my-item></my-item>
            ${item.name}
        </td>
        <td>${item.ssn}</td>
`)}
    </tbody>
</table>
`

which will end up doing an Object.assign (gingerly) of the item object to the my-item custom element.

It can also do the same for server generated JSON attributes:

<table>
    <thead><th>Name</th><th>SSN Number</thead>
    <tbody>
    <tr itemscope=my-item be-scoped assign-gingerly='{"name": "Burt", "ssn": "123-45-6789"}'>
        <td>
            <my-item></my-item>
            Burt
        </td>
        <td>123-45-6789</td>
    </tbody>
</table>

Playwright Tests NPM version

Size of package, including custom element behavior framework (be-enhanced/be-hive):

How big is this package in your project?

Size of new code in this package:

Viewing Locally

  1. Install git.
  2. Fork/clone this repo.
  3. Install node.
  4. Open command window to folder where you cloned this repo.
  5. npm install

  6. npm run serve

  7. Open http://localhost:3030/demo/ in a modern browser.

Importing in ES Modules:

import 'be-exportable/be-scoped.js';

Using from CDN:

<script type=module crossorigin=anonymous>
    import 'https://esm.run/be-scoped';
</script>

About

Create an EventTarget associated with the adorned element that can hold scoped state.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published