be-switched
v0.0.111
Published
be-switched is a template behavior that lazy loads content when conditions are met.
Downloads
44
Maintainers
Readme
be-switched ( 🎚️ )
be-switched is a template element enhancement that lazy loads content when conditions are met.
It is a member of the be-enhanced family of enhancements, that can "cast spells" on server rendered content, but also apply the same logic quietly during template instantiation.
The basic functionality
be-switched can be used in three modes:
- It can switch the template "on and off" based on comparing two values (lhs and rhs), or multiple such comparisons, declaratively.
- Or it can switch the template "on and off" based on a single value. Or multiple such binary conditions.
- 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
A single lhs/rhs comparison
<!-- Example 1 -->
<template id=template be-switched='{
"lhs": 37,
"rhs": "hello"
}'>
<div>lhs === rhs</div>
</template>
<button onclick=setLHS()>Set lhs = "hello"</button>
<script>
function setLHS(){
template.beEnhanced.beSwitched.lhs = 'hello';
}
</script>
"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):
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:
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 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:
<script type=module>
import {register} from 'be-switched/behivior.js';
register('isMadeOfWood', e => e.r = Math.abs(e.args[0] - e.args[1]) < 10));
</script>
<ways-of-science itemscope>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template
be-switched='On if isMadeOfWood, based on ~carrotNosedWoman::weight-change and ~aDuck::molting.'
>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
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 after "On if". If e.r is set to true (where e is the name of the event), display the contents within the template. If e.r is set to false, hide it. Also, do this check on initialization.
[!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.
Our event handler can reference the adorned element, so that we can remove the hardcoding of 10:
<script type=module>
import {register} from 'be-switched/behivior.js';
register('isMadeOfWood',
e => e.r = Math.abs(e.args[0] - e.args[1]) < Number(e.target.dataset.maxDiff)
);
</script>
<ways-of-science itemscope>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template data-max-diff=10
be-switched='On if isMadeOfWood, based on ~carrotNosedWoman::weight-change and ~aDuck::molting .'
>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
This is, in fact, such a useful pattern, that "isMadeOfWood" is built into this package, so no JS is actually necessary. Sorry, JS-firsters!
<ways-of-science itemscope>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template data-max-diff=10
be-switched='On if nearlyEq, based on ~carrotNosedWoman::weight-change and ~aDuck::molting.'
>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
Here is another, less cinematic example, also baked in, so no JS needed:
<label for=lhs>LHS:</label>
<input id=lhs>
<label for=rhs>RHS:</label>
<input id=rhs>
<template
be-switched='on if eq, based on #lhs and #rhs.'
>
<div>LHS === RHS</div>
</template>
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, 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 --
- The value of the elements we are comparing are primitive JS types that are either inferrable, or specified by a property path.
- The values of the elements we are comparing change in conjunction with a (user-initiated) event.
Scoped, custom logic [Untested]
We can depend on any number of peer elements in our calculations, and we can limit the scope of our custom calculation function
<old-man-and-the-sea itemscope>
<script blow-dry type=module>
import {within} from 'be-switched/behivior.js';
within('old-man-and-the-sea', 'starsAligned', e => e.r = e.f.isANewDay && (e.f.ready || e.f.luckyIAm) && e.f.luckHasCome)
</script>
<label>
Today is a new day.
<input type=checkbox name=isANewDay>
</label>
<input aria-label="I could be lucky" type=checkbox id=luckyIAm>
<input aria-label="Would rather be" type=checkbox name=ready>
<data itemprop=luckHasCome value=true></data>
<template be-switched="on if starsAligned, based on @isANewDay and #lucky and #ready and |luckHasCome.">
<div>I am ready to benefit from such good luck.</div>
</template>
</old-man-and-the-sea>
What we've seen so far is we can take matters into our hands, and employ free form scripting to calculate whether to display the contents of the template.
However, there is one restriction -- There can only be one active sentence contained in the be-switched attribute that starts with "on if * based on". This seems reasonable, as the JavaScript logic can be as complex as we want it to be, applying whatever rules make sense to the various factors.
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 oninput 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:
<label for=lhs>LHS:</label>
<input id=lhs>
<label for=rhs>RHS:</label>
<input id=rhs>
<template be-switched='on when #lhs equals #rhs.'>
<div>LHS === RHS</div>
</template>
[!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.
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
<label for=lhs>LHS:</label>
<input id=lhs type=number>
<label for=rhs>RHS:</label>
<input id=rhs>
<template 🎚️='on when #lhs equals #rhs as number.'>
<div>LHS === RHS</div>
</template>
By N@me
<form>
<label>
LHS:
<input name=lhs>
</label>
<label>
RHS:
<input name=rhs>
</label>
<template 🎚️='on when @lhs equals @rhs.'>
<div>LHS === RHS</div>
</template>
</form>
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 an "closest" query. Symbolically, we use the "^" symbol to indicate this:
"Closest" Scoping
These should be ignored:
<div>
<label for=lhs>
LHS:
<input name=lhs>
</label>
<label for=rhs>
RHS:
<input name=rhs>
</label>
</div>
These should be active:
<section>
<label>
LHS:
<input name=lhs>
</label>
<label>RHS:
<input name=rhs>
</label>
<template 🎚️='on when ^{section}@lhs eq ^{section}@rhs.'>
<div>LHS === RHS</div>
</template>
</section>
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 [TODO]
These should be ignored:
<div>
<label for=lhs>
LHS:
<input name=lhs>
</label>
<label for=rhs>
RHS:
<input name=rhs>
</label>
</div>
These should be active:
<section>
<label>
LHS:
<input name=lhs>
</label>
<label>RHS:
<input name=rhs>
</label>
<template 🎚️='on when @lhs eq @rhs w/i ^{section}.'>
<div>LHS === RHS</div>
</template>
</section>
By the itemprop microdata attribute
<div itemscope>
<span itemprop=lhs contenteditable></span>
<span itemprop=rhs contenteditable></span>
<template 🎚️='on when |lhs equals |rhs.'>
<div>LHS === RHS</div>
</template>
</div>
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 ~ 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.
<ways-of-science itemscope>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template
🎚️='
On when ~carrotNosedWoman eq ~aDuck.
'>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
What this does:
- Finds carrot-nosed-woman element within itemscope, and if not found, within root node.
- 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]
- Waits for customElements.whenDefined('carrot-nosed-woman') if applicable.
- Attempts to infer the value of the element.
- If 'value' in oCarrotNosedWoman, use that.
- If not, use ariaValueNow if present.
- If not, check if 'checked' in oCarrotNosedWoman, use that.
- Try ariaChecked.
- Check if 'href' in oCarrotNosedWoman, use that.
- As a last resort attempt at mind reading, use the string obtained from textContent.
- Finds element a-duck, same as above.
- Waits for customElements.whenDefined('a-duck') if applicable.
- Attempts to infer the value of the element, same as 4 above.
- Compares the values.
- 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)
<ways-of-science itemscope>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template
🎚️='
On when ~carrotNosedWoman::weight-change equals ~aDuck::molting.
'>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
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 a single colon for specifying a property path.
<ways-of-science>
<carrot-nosed-woman></carrot-nosed-woman>
<a-duck></a-duck>
<template
🎚️='
On when ~carrotNosedWoman:weight equals ~aDuck:weight.
'>
<div>A witch!</div>
<div>Burn her!</div>
</template>
</ways-of-science>
Events are not used here, but rather propagating props.
Also, note that this can actually be a chain of accessors (that automatically inserts a chaining operator ?. without requiring the extra ? character).
The colon symbol is used instead of the period, since we are using periods to separate potentially multiple sentences contained within the attribute. be-switched supports multiple statements (or condition by default, unless the word "only" is inserted).
Specify less than
"Less than" is supported:
<label for=lhs>LHS:</label>
<input type=number id=lhs>
<label for=rhs>RHS:</label>
<input type=number id=rhs>
<template 🎚️='on when #lhs lt #rhs.'>
<div>LHS < RHS</div>
</template>
Specify greater than
This is supported:
<label for=lhs>LHS:</label>
<input type=number id=lhs>
<label for=rhs>RHS:</label>
<input type=number id=rhs>
<template 🎚️='on when #lhs gt #rhs.'>
<div>LHS > RHS</div>
</template>
Up and down searches using ^{()} Y{} expressions. [TODO]
<input type=number>
<template 🎚️='on when ^{(*)} gt Y{*}.'>
<div>Previous input > next input</div>
</template>
<input type=number>
Grouping previous element sibling selectors
Prepare yourself for some turbulence ahead:
With hard coded indexes in the expression:
<table>
<tbody>
<tr aria-rowindex=10><td><input name=lhs></td><td><input name=rhs></td></tr>
<tr aria-rowindex=10>
<td colspan=2>
<template data-idx=10 🎚️="on when ^{(tr[aria-rowindex='10'])}@lhs eq ^{(tr[aria-rowindex='10'])}@rhs">
<div>lhs == rhs</div>
</template>
</td>
</tr>
<tr aria-rowindex=11><td><input name=lhs></td><td><input name=rhs></td></tr>
<tr aria-rowindex=11>
<td colspan=2>
<template data-idx=11 🎚️="on when ^{(tr[aria-rowindex='11'])}@lhs eq ^{(tr[aria-rowindex='11'])}@rhs">
<div>lhs == rhs</div>
</template>
</td>
</tr>
</tbody>
</table>
Simpler, more powerful syntax:
<table>
<tbody>
<tr aria-rowindex=10><td><input name=lhs></td></tr>
<tr aria-rowindex=10>
<td>
<template 🎚️="on when @lhs eq @rhs w/i %[aria-rowindex].">
<div>lhs == rhs</div>
</template>
</td>
</tr>
<tr aria-rowindex=10><td><input name=rhs></td></tr>
<tr aria-rowindex=11><td><input name=lhs></td></tr>
<tr aria-rowindex=11>
<td>
<template 🎚️="on when @lhs eq @rhs w/i %[aria-rowindex].">
<div>lhs == rhs</div>
</template>
</td>
</tr>
<tr aria-rowindex=11><td><input name=rhs></td></tr>
</tbody>
</table>
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
<div itemscope>
...
<data value=true itemprop=isHappy hidden></data>
...
<template 🎚️='on when |isHappy.' >
<my-content></my-content>
</template>
</div>
Searches within nearest itemscope, else from rootNode.
By name
Can also reference form element, or form associated custom elements
<form>
...
<input name=isHappy type=checkbox>
...
<template 🎚️='on when @isHappy.'>
<my-content></my-content>
</template>
</form>
Checks for $0.checked, if undefined, checks for $0.ariaChecked. Listens for input events.
By id
<form>
...
<input id=isHappy type=checkbox>
...
<template 🎚️='on when #isHappy.'>
<my-content></my-content>
</template>
</form>
By Id with and-like condition
<form>
...
<input id=isHappy>
...
<template 🎚️='on only when #isHappy.'>
<my-content></my-content>
</template>
</form>
This is an "and" condition due to the presence of "only".
Condition coming from host
With / symbol
"/" refers to the host.
<mood-stone>
#shadow
<template 🎚️='on when /isHappy.'>
<my-content></my-content>
</template>
<be-hive></be-hive>
</mood-stone>
This also works:
/ is considered the "default" symbol, so it actually doesn't need to be specified:
The bare specifier
<mood-stone>
#shadow
<template 🎚️='on when isHappy.'>
<my-content></my-content>
</template>
<be-hive></be-hive>
</mood-stone>
Referring to previous element sibling [TODO]
<div itemscope>
...
<link itemprop=isHappy href=https://schema.org/True>
<template 🎚️='on when ^{(*)}.'>
<my-content></my-content>
</template>
</div>
The standalone ^{(*)} is indicating to just look at the previous element sibling.
Example 3b Referring to next element sibling with yertdrift symbol [TODO]
<div itemscope>
...
<template 🎚️='on when Y{*}.'>
<my-content></my-content>
</template>
<link itemprop=isHappy href=https://schema.org/True>
</div>
Up searching [Untested]
<div itemscope>
...
<link itemprop=isHappy href=https://schema.org/True>
<div></div>
<template 🎚️='on when ^{(link)}.'>
<my-content></my-content>
</template>
</div>
Example 3c
Example 3c Comparison to a constant
<label for=lhs>lhs</label>
<input id=lhs name=lhs type=number>
<template data-rhs=37 🎚️='on when @lhs eq $0:dataset:rhs as number.'>
<my-content></my-content>
</template>
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]:
<section part=myPart>
...
<link itemprop=isHappy href=https://schema.org/True>
...
<template be-switched="on when ^%[%myPart]|isHappy.">
<my-content></my-content>
</template>
</section>
<section itemscope itemprop=mySubObject itemref="id1 id2">
...
...
<div itemscope itemprop=mySubSubObject>
<template be-switched="on when %[$mySubObject]|isHappy.">
<my-content></my-content>
</template>
</div>
</section>
<section id=id1>
<link itemprop=isHappy href=https://schema.org/True>
</section>
Example 3e => 3g [TODO] binding based on part attribute
<form>
<input part=isHappy type="checkbox">
<template be-switched='on when %isHappy.'>
<my-content id=myContent></my-content>
</template>
</form>
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 Your Element Locally
Any web server that can serve static files will do, but...
- Install git.
- Fork/clone this repo.
- Install node.js
- Open command window to folder where you cloned this repo.
npm install
npm run serve
- Open http://localhost:3030/demo/ in a modern browser.
Running Tests
> npm run test
Using from ESM Module:
import 'be-switched/be-switched.js';
Using from CDN:
<script type=module crossorigin=anonymous>
import 'https://esm.run/be-switched';
</script>
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.
<ways-of-science>
<largest-scale>
<woman-with-carrot-attached-to-nose></woman-with-carrot-attached-to-nose>
</largest-scale>
<largest-scale>
<a-duck></a-duck>
</largest-scale>
<template blow-dry itemscope itemref="witch burn-her"
be-switched='
Off when value property of previous largest-scale element
having inner woman-with-carrot-attached-to-nose element
is not equal to the value property of previous largest-scale element
having inner a-duck element
.
'
>
<div>A witch!</div>
<div>Burn her!</div>
</template>
<div id=witch>A witch!</div>
<div id=burn-her>Burn her!</div>
</ways-of-science>
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 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:
<my-web-component>
<template shadowrootmode=open>
...
<template be-switched=... blow-dry>
...
</template>
...
<be-hive></be-hive>
<xtal-element></xtal-element>
</template>
</my-web-component>
Additional conditions be-switched supports [TODO]
In addition to "if" boolean checks, and equality checks using lhs and rhs keys, some additional "if" checks can be made:
Lazy Loading / Hibernating [Untested]
be-switched can "go to sleep" when the template it adorns goes out of view, if the template is also decorated by be-oosoom. be-switched provides an option to toggle the inert property when the conditions become false, in lieu of deleting the content.
* Expand section above for what that reason is.