npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

be-switched

v0.0.113

Published

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

Downloads

335

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 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 Playwright Tests NPM version How big is this package in your project?

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

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.

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:

<ways-of-science itemscope>
    <carrot-nosed-woman></carrot-nosed-woman>
    <a-duck></a-duck>
    <template
        be-switched='On based on ~carrotNosedWoman::weight-change and ~aDuck::molting.'
        onchange="event.r = Math.abs(event.args[0] - event.args[1]) < 10"
    >
        <div>A witch!</div>
        <div>Burn her!</div>
    </template>
</ways-of-science>

Our expression can alternatively be more expressive:

<ways-of-science itemscope>
    <carrot-nosed-woman></carrot-nosed-woman>
    <a-duck></a-duck>
    <template
        be-switched='On based on ~carrotNosedWoman::weight-change and ~aDuck::molting.'
        onchange="event.r = Math.abs(event.f.carrotNosedWoman - event.f.aDuck) < 10"
    >
        <div>A witch!</div>
        <div>Burn her!</div>
    </template>
</ways-of-science>

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.

Adding a local, unique anonymous conditional expression "safely"

The example above will break the moment typically minimal CSP security checks are put into place.

One way to overcome this unfortunate obstacle is by programmatically adding the 'change' event handler to the template via a framework, or a custom element host.

An alternative way is a bit verbose, but benefits more from "locality of behavior". We utilize a helper enhancement:

<ways-of-science itemscope>
    <carrot-nosed-woman></carrot-nosed-woman>
    <a-duck></a-duck>
    <template
        defer-be-switched
        be-switched='On based on ~carrotNosedWoman::weight-change and ~aDuck::molting.'
    >
        <div>A witch!</div>
        <div>Burn her!</div>
    </template>
    <script be-eventing=be-switched>document.currentScript.on={
        change: e => e.r = Math.abs(e.f.carrotNosedWoman - e.f.aDuck) < 10
    }</script>
</ways-of-science>

It's the best I could do to ensure everything works reliably.

Registering a named, global event handler

This also works, and can survive CSP scrutiny:

<script type=module blocking=defer>
    import {register} from 'be-switched/emc.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>

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

<script type=module blocking=render>
    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)
    );
</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 --

  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:

<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

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:

  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)

<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 the "chained accessor" symbol (?.) 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>

There's a lot to unpack here:

This assumes ideally that the host custom element conforms to the "RoundaboutReady" 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:

<ways-of-science>
    <carrot-nosed-woman weight=92></carrot-nosed-woman>
    <a-duck weight=82></a-duck>
    <template 
        🎚️='
            On when ~carrotNosedWoman@weight equals ~aDuck@weight.
     '>
        <div>A witch!</div>
        <div>Burn her!</div>
    </template>
</ways-of-science>

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 &lt; 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 &gt; RHS</div>
</template>

Up and down searches using ^{()} Y{} expressions. [TODO]

<input type=number>
<template 🎚️='on when ^{(*)} gt Y{*}.'>
    <div>Previous input &gt; 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...

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

  6. npm run serve

  7. Open http://localhost:8000/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.