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

https://github.com/bahrus/be-switched

be-switched is a template behavior that lazy loads content when conditions are met.
https://github.com/bahrus/be-switched

behavior conditional-rendering custom-element custom-elements web-component web-components

Last synced: about 2 months ago
JSON representation

be-switched is a template behavior that lazy loads content when conditions are met.

Awesome Lists containing this project

README

        

# be-switched ( 🎚️ ) [WIP]

*be-switched* is a template element enhancement that lazy loads content when conditions are met.

It is a member of the [be-enhanced](https://github.com/bahrus/be-enhanced) family of enhancements, that can "cast spells" on server rendered content, but also apply the same logic quietly during template instantiation.

[![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://www.webcomponents.org/element/be-switched)
[![Playwright Tests](https://github.com/bahrus/be-switched/actions/workflows/CI.yml/badge.svg)](https://github.com/bahrus/be-switched/actions/workflows/CI.yml)
[![NPM version](https://badge.fury.io/js/be-switched.png)](http://badge.fury.io/js/be-switched)
[![How big is this package in your project?](https://img.shields.io/bundlephobia/minzip/be-switched?style=for-the-badge)](https://bundlephobia.com/result?p=be-switched)

## The basic functionality

be-switched can be used in three modes:

1. It can switch the template "on and off" based on comparing two values (lhs and rhs), or multiple such comparisons, declaratively.
2. Or it can switch the template "on and off" based on a single value. Or multiple such binary conditions.
3. Or, with the help of JavaScript, we can evaluate a complex expression that is automatically recalculated anytime any of its n dependencies change, where n can be as high as needed.

The values to compare can come from peer microdata or form elements, or "boolish" properties coming from the host or peer (custom) elements, as well as data attributes adorning the template.

We will look at all three options closely, starting with...

# Part I

Comparing two values via JavaScriptObjectNotation

## A single lhs/rhs comparison

```html

lhs === rhs

Set lhs = "hello"

function setLHS(){
template.beEnhanced.beSwitched.lhs = 'hello';
}

```

"lhs" stands for left-hand-side. "rhs" stands for "right-hand-side".

The default values for these two properties is lhs=false/rhs=true. So this allows for a simple, single "if" statement, as well as an "if not" statement.

> [!NOTE]
> By default, property "beBoolish" is set to true, which means that if either the lhs or rhs value is a boolean, the equality check is made using truthy/falsy criteria, rather than an exact match of boolean values.

Since the lhs (37) doesn't equal the rhs ("hello"), the content inside the template remains inside the template. The moment the lhs equals the rhs, the content inside the template is appended adjacent to the template element. If the lhs later becomes unequal to the rhs again, the live DOM content that came from the template is hidden via css.

Now how can we change the values of the lhs and rhs? Normally, a framework can pass values to the top level of a web component / built-in element. Some frameworks may be able to pass values to sub properties. With such frameworks, they could, theoretically, pass updated values like so (under the hood):

```JavaScript
await customElements.whenDefined('be-enhanced');
oTemplate.beEnhanced.by.beSwitched.rhs = 37;
```

The extra ".by" is necessary just in case beSwitched hasn't been attached to the element yet.

The first line can be avoided if we already know be-enhanced has been registered.

Another way to pass in the value reliably is thusly:

```JavaScript
if(oTemplate.beEnhanced === undefined) oTemplate.beEnhanced = {};
if(oTemplate.beEnhanced.beSwitched === undefined) oTemplate.beEnhanced.beSwitched = {};
oTemplate.beEnhanced.beSwitched.rhs = 37;
```

All of this is to say, most frameworks probably don't and won't be able to make it trivially easy to pass values to the enhancement, especially for unbundled applications that make use of the dynamic import(), so that the timing of when dependencies load is unpredictable.

Frameworks fail us, yet again!

... And for that reason*, among others, an alternative way of "pulling in" values to compare is provided via:

# Part II - Comparing multiple values with Hemingway Notation

We will take a bit of an unusual approach to our explication -- we will document "harder" cases first, leading to simpler and simpler cases, as you continue reading below.

This enhancement takes the view that the [rule of least power](https://en.wikipedia.org/wiki/Rule_of_least_power) is the surest way to heaven. If you get anxious from complex code-centric overkill, fear not, the examples will only get easier as you read through, so enjoy the liberating feeling that comes with that.

But for those power hungry developers who want full, unfettered access to the JavaScript runtime in their binding expressions, we start...

## With XOXO's to the Reactive JS-firsters

Due primarily to the platform not playing very nice with progressive enhancement needs, this integration isn't as seamless as I would like. Here's to hoping (despite all the evidence) that the platform will show some HTML love sometime in the distant future. But for now, this will have to do.

### Adding a local, unique anonymous conditional expression "unsafely"

If your production web site runs in a setting without CSP checks (or allows for inline expressions), then this works just fine, and is supported:

```html




A witch!

Burn her!

```

Our expression can alternatively be more expressive:

```html




A witch!

Burn her!

```

Here, we are attempting to keep our expressions short, which means some abbreviations are used:

1. event.r means "the return value of the result should be..."
2. The "f" in event.f stands for "factors" in the conditional evaluation -- factors derived from what the be-switched expression is "based on".

What this is saying:

> Find peer elements *carrot-nosed-woman* and *a-duck* within the itemscope'd attributed ways-of-science element. Listen to weight-changed and molting events, respectively, and when those events happen, evaluate the JavaScript event handler referenced in the onchange attribute. If event.r is set to true, display the contents within the template. If event.r is set to false, hide it. Also, evaluate the expression immediately at the outset.

> [!NOTE]
> This enhancement shines best when the adorned template contains a significant amount of HTML, especially rich HTML involving significant JavaScript manipulation. If all you need to do is conditionally display a small amount of content, as the examples in this document do, it may be more effective to simply use css to hide/display the content, and avoid this enhancement altogether. Similar advice has been issued [elsewhere](https://polymer-library.polymer-project.org/2.0/docs/devguide/templates#dom-if).

### Adding "View Transition" support

When using this enhancement in the recommended way, as described by the note above, where the "on" condition results in displaying a significant amount of new content it may make sense to apply "view transition" support to the view change.

```html




A witch!

Burn her!

::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 2s;
}

```

and/or:

```html




A witch!

Burn her!

body{
--be-transitional: true;
}
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 2s;
}

```

### Adding a local, unique anonymous conditional expression "CSP safely"

```html




A witch!

Burn her!

```

Variables that are available inside these -js expressions:

| Variable Name | Meaning |
|-------------------|---------------------------|
| e | The change event |
| f | Factors of the expression |
| args | Array of the factors |

## Registering a named, global event handler

This also works, and can survive CSP scrutiny:

```html

import {register} from 'be-switched/emc.js';
register('isMadeOfWood', e => e.r = Math.abs(e.args[0] - e.args[1]) < 10));




A witch!

Burn her!

```

Our event handler can reference the adorned element, so that we can remove the hardcoding of 10:

```html

import {register} from 'be-switched/emc.js';
register('isMadeOfWood',
e => e.r = Math.abs(e.args[0] - e.args[1]) < Number(e.target.dataset.maxDiff)
);




A witch!

Burn her!

```

This is, in fact, such a useful pattern, that "isMadeOfWood" is built into this package, so no JS is actually necessary. Sorry, JS-firsters!

```html




A witch!

Burn her!

```

Here is another, less cinematic example, also baked in, so no JS needed:

```html
LHS:

RHS:

LHS === RHS

```

As you have probably noticed, we are starting to introduce special symbols for finding peer elements.

We call this syntax [Directed Scoped Specifiers, or DSS](https://github.com/bahrus/trans-render/tree/baseline/dss#readme), inspired by, but not to be confused with, CSS selectors. It is optimized for the problem at hand -- binding to nearby, relative elements (or the host), with an eye towards encouraging semantic HTML markup.

We are often (but not always in the case of 2. below) making some assumptions about the elements we are comparing --

1. The value of the elements we are comparing are primitive JS types that are either inferrable, or specified by a property path.
2. The values of the elements we are comparing change in conjunction with a (user-initiated) event.

## Bye JavaScript, nice knowin' ya!

What follows quickly moves outside the domain of JavaScript, so if JS is your only game, you have passed the course and are ready to code to your heart's content! Supporting the declarative bindings as described below won't be loaded unless actually used, so little to no harm done if you don't choose to use what follows.

We start by looking at pairs of comparisons between the "lhs" (left hand side) and the "rhs" (right hand side).

These statements don't invoke the onchange event at all, and are purely declarative. But we can list a number of comparisons, some of which add to an "or" statement, others to an "and" condition, others can act as a negation, etc. So we will get much the same power as we get with JavaScript, but declaratively, with no possible side effects (and be less prone to catastrophic errors).

### ID Referencing

Let's start with the most elementary two value switch:

```html
LHS:

RHS:

LHS === RHS

```

> [!NOTE]
> For id based matches (which is what we have above), the search is done within the root node of the element, i.e. the ShadowDOM container or the document if outside any ShadowDOM.

> [!NOTE]
> The comparison condition is re-evaluated on the input events of the lhs and rhs elements by default. See below for how to specify alternate event names.

> [!NOTE]
> For the power user: Replace "equals" with "eq" and impress your friends with your prowess using this library.

In applications that use be-switched frequently, where concerns about clashing with already registered packages in npm isn't a concern, it might make development more productive to utilize a shorter name. The best alternative name is probably "turn", and it does seem unlikely to me that the platform would ever add attribute "turn" to the template element, but you never know, I guess.

This package does provide an alternative name you can use, which seems quite future-proof and succinct: 🎚️ via this [file](https://github.com/bahrus/be-switched/blob/baseline/%F0%9F%8E%9A%EF%B8%8F.ts).

I think you will agree, looking at that file, how easy it is to define your own name (like "turn", but don't sue me if the platform "turns" on you).

The remaining examples will use this symbol (🎚️), so please translate that symbol to "be-switched" or "turn" or "switch" in your mind when you see it below. Note that on Windows, to select this emoji, type flying window + . and search for "sli". It should retain in memory for a while after that once you use it.

### Type casting

```html
LHS:

RHS:

LHS === RHS

```

### Use View Transitions

Just as before, we can do some in one of two ways:

```html
LHS:

RHS:

LHS === RHS

::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 2s;
}

```

To apply the transitional setting more globally, use a css property as follows, for whatever css selector where it should be applied:

```css
body{
--be-transitional: true;
}
```

### By N@me

```html


LHS:




RHS:




LHS === RHS

```

Here, the search for matching names is done within a containing form, and if no form is found, within the root node.

However, if that is not sufficient, we can specify a "scoping" perimeter via a "closest" query. Symbolically, we use the "^" symbol to indicate this:

### "Closest" Scoping

```html
These should be ignored:



LHS:




RHS:




These should be active:


LHS:



RHS:




LHS === RHS

```

We can apply such closest queries to either the LHS or the RHS, or both, as shown above.

If we use the same closest query for both, we can reduce typing / increase readability and reduce the amount of DOM traversing thusly:

## W/I (within) scoping

```html
These should be ignored:



LHS:




RHS:




These should be active:


LHS:



RHS:




LHS === RHS

```

### By the itemprop microdata attribute

```html







LHS === RHS



```

Here the search is done within the nearest itemscope, and if no itemscope is found, within the root node.

Again, if that proves inadequate, use the ^ character to indicate the closest peer/parent to search within.

### By Hierarchical itemscope

```html









lhs === rhs






customElements.define('parent-scope', class extends HTMLElement {});
customElements.define('child-scope', class extends HTMLElement {});

```

Why not use ^{}? Because itemscope hierarchy can't really be expressed easily with css. I.e. this syntax supports "flat" hierarchies via itemref.

```html







lhs === rhs






```

### By ~ tagName

In the brave new world that custom elements has opened up, we can make our markup beautifully expressive, and tap into that with our binding expressions.

```html




A witch!

Burn her!

```

What this does:

1. Finds carrot-nosed-woman element within itemscope, and if not found, within root node.
2. If not found within root node, see if the host element has a property with name carrotNosedWoman that is an instance of eventTarget. [TODO: verify this is still working]
3. Waits for customElements.whenDefined('carrot-nosed-woman') if applicable.
4. Attempts to infer the value of the element.
1. If 'value' in oCarrotNosedWoman, use that.
2. If not, use ariaValueNow if present.
3. If not, check if 'checked' in oCarrotNosedWoman, use that.
4. Try ariaChecked.
5. Check if 'href' in oCarrotNosedWoman, use that.
6. As a last resort attempt at mind reading, use the string obtained from textContent.
5. Finds element a-duck, same as above.
6. Waits for customElements.whenDefined('a-duck') if applicable.
7. Attempts to infer the value of the element, same as 4 above.
8. Compares the values.
9. Listens for input event (by default, but see below for custom event names), and re-evaluates (skipping some steps if found in weak reference based cache).

### Specifying event name(s)

```html




A witch!

Burn her!

```

Remember that if the event name is not specified, the input event is assumed, when elements are found by name or by id or by tag name, and if no prop name is specified (see below). Regardless of the event names specified, the developer uses the built in "oninput" attribute to provide a custom script to evaluate whether the condition is met.

### Specify property path to compare

Use the "chained accessor" symbol (?.) for specifying a property path.

```html




A witch!

Burn her!

```

There's a lot to unpack here:

This assumes ideally that the host custom element conforms to the ["RoundaboutReady"](https://github.com/bahrus/trans-render/wiki/II.--Signals-vs-Roundabouts#how-to-be-roundabout-ready) interface -- in particular, has a "propagator" property that emits events "weight" when the weight property changes for *carrot-nosed-woman* and *a-duck*.

If no such interface is detected, this will instead override the setter for the "weight" property which may not always work or feel very resilient.

Also, note that this can actually be a chain of accessors n-levels deep.

## Specify Source of Truth attributes [TODO]

If the elements being observed don't have propagators to subscribe to, and the thought of overriding a setter feels wrong or simply doesn't work, but the property happens to have a corresponding attribute that serves as a "source of truth" corresponding to the property, then we can take advantage of that:

```html




A witch!

Burn her!

```

### Specify less than

"Less than" is supported:

```html
LHS:

RHS:

LHS < RHS

```

### Specify greater than

This is supported:

```html
LHS:

RHS:

LHS > RHS

```

### Up and down searches using ^{()} Y{} expressions.

```html

Previous input > next input

```

### Grouping previous element sibling selectors

Prepare yourself for some turbulence ahead:

With hard coded indexes in the expression:

```html






lhs == rhs








lhs == rhs



```

## Simpler, more powerful syntax:

```html






lhs == rhs









lhs == rhs





```

## And now for something completely different

The previous group of examples all focused on comparing two values.

But what if we just want to lazy load content when a single value goes from "falsy" to "truthy"? This package supports that as well.

## Boolean conditions based on peer elements or host

### By itemprop

```html


...

...




```

Searches within nearest itemscope, else from rootNode.

### By name

Can also reference form element, or [form associated custom elements](https://bennypowers.dev/posts/form-associated-custom-elements/)

```html

...

...


```

Checks for $0.checked, if undefined, checks for $0.ariaChecked. Listens for input events.

### By id

```html

...

...


```

### By Id with and-like condition

```html

...

...


```

This is an "and" condition due to the presence of "only".

### Condition coming from host

### With / symbol

"/" refers to the host.

```html

#shadow



```

This also works:

/ is considered the "default" symbol, so it actually doesn't need to be specified:

### The bare specifier

```html

#shadow



```

### Referring to previous element sibling

```html


...
Yes




```

The standalone ^{(*)} is indicating to just look at the previous element sibling.

### Example 3b Referring to next element sibling with yertdrift symbol

```html


...






```

### Up searching [Untested]

```html


...






```

## Example 3c

### Example 3c Comparison to a constant

```html
lhs


```

Can have multiple such statements -- or condition. Each sentence can begin with "on" or "On", whichever seems more readable.

If no itemscope container is present and there's some ambiguity use [TODOORNOTTODO]:

```html

...

...


```

```html

...

...





```

### Example 3e => 3g [TODO] binding based on part attribute

```html




```

### Example 3f => void binding based on class attribute. [NOTTODO?]

So this is where we have a clash between Hemingway and CSS. The most natural symbol to use for a class selector would be the period ("."). However, because the period is used to break up statements, that would require an escape character of some sort, or using some other symbol to represent the class query.

After staring at my keyboard for several hours, I have decided that maybe this is for the best. Using css classes for purposes of binding may cross a barrier into "hackish" territory, especially when there are so many attractive alternatives that we've discussed above. The part attribute is already skating on thin ice, but I think, in the context of a web component, may make sense to use sometimes, as the purpose of the part is more "public" and I think will tend to be more semantic as far as the nature of the element it adorns.

### Example !2a - !4a [Not Fully Tested]

All the examples above also work, but instead of "on", use "off", which of course means the negation is performed.

## Viewing Locally

Any web server that serves static files with server-side includes will do but...

1. Install git.
2. Fork/clone this repo.
3. Install node.
4. Install Python 3 or later.
5. Open command window to folder where you cloned this repo.
6. > npm install
7. > npm run serve
8. Open http://localhost:8000/demo in a modern browser.

## Running Tests

```
> npm run test
```

## Using from ESM Module:

```JavaScript
import 'be-switched/be-switched.js';
```

## Using from CDN:

```html

import 'https://esm.run/be-switched';

```

P.S.

## Compatibility with server-side-rendering

*be-switched* is compatible with server-side-rendering if the following approach is used:

If, during the time the SSR is taking place, the desire is not to display the content, but rely on the client to lazy load when conditions warrant, then the syntax above is exactly what the SSR should generate.

If, however, the content should display initially, but we want the client-side JavaScript to be able to hide / disable the content when conditions in the browser change, the server should render the contents adjacent to the template, and leverage standard microdata attributes, to establish artificial hierarchies.

```html








A witch!

Burn her!


A witch!

Burn her!

```

We are using built-in support for microdata to signify a hierarchical relationship with a flat list of DOM elements.

In this scenario, repeating the content inside the template is unnecessary, unless the optional setting: deleteWhenInvalid is set to true.

## Throwing elements out of scope away [Untested]

An option, minMem, allows for completely wiping away content derived from the template when conditions are no longer met. This *might* be better on a low memory device, especially if the content has no support for be-oosoom (see below).

## NBs

> [!NOTE]
> If using this enhancement as part of a repeating [*xtal-element*](https://github.com/bahrus/xtal-element) web component, my performance experiments indicate it is best to extract the contents of the template into a shared location, rather than cloning the template within each web component template instance. This is accomplished by adding attribute *blow-dry* or *data-blow-dry* to the template element:

```html


...

...

...


```

## Additional conditions

*be-switched* can work in tandem with another enhancement, [https://github.com/bahrus/mt-si](mt-si) to add common additional conditions before the template *be-switched* adorns becomes active. One example would be media queries:

```html

{
"whereMediaMatches": "..."
}

...

```