Client Elements
This is the client portion of the Ride The Streetcar paradigm. Get familiar with the basic premise here, then read on for installation & usage documentation.
While any backend is capable of powering Streetcar, we offer two out-of-the-box backend libraries for enhanced DX:
Installation #
npm i @heartml/streetcar-elements
import StreetcarElements from "@heartml/streetcar-elements"
// basic example using fetch:
async function exampleRequestResponse() {
const html = await fetch("/path/of/backend/fragment").then(r => r.text())
StreetcarElements.run(html)
// or if you have a DocumentFragment already parsed:
// StreetcarElements.runFragment(doc)
}
Conceptually, Streetcar is rather straightforward. It is a protocol of sorts built out of HTML and custom elements. You can read a Streetcar payload and immediately make sense of what it does, as it essentially is a subset of common JavaScript/DOM operations encoded into markup.
<sc-line>
<sc-query-selector selectors="#ident_abc123"><sc-inner-html><template><p>New HTML content.</p></template></sc-inner-html></sc-query-selector>
<sc-console log="✔ outputs to the console"></sc-console>
<sc-query-selector selectors="--named-query">
<sc-outer-html><template><p>Kewl</p><div>
<template shadowrootmode="open">
<p>I'm in the shadow DOM!</p>
</template>
</div></template></sc-outer-html>
<sc-class-list toggle="success" force="true"></sc-class-list>
</sc-query-selector>
<sc-apply method="window.testChain.funkyTown" arguments='["take", "me", 2]'></sc-apply>
<sc-query-selector selectors="#delete-me"><sc-remove></sc-remove></sc-query-selector>
<sc-query-selector selectors="ul"><sc-append><template>
<li>Item 2</li>
</template></sc-append></sc-query-selector>
<sc-query-selector selectors="[name=set_value]">
<sc-set-property name="value" value='"input text"'></sc-set-property>
</sc-query-selector>
<sc-query-selector all selectors="ol > li, ul > li">
<sc-set-attribute name="list-item"></sc-set-attribute>
</sc-query-selector>
<sc-query-selector selectors="h1">
<sc-set-style name="backgroundColor" value="rebeccapurple"></sc-set-style>
</sc-query-selector>
</sc-line>
All of the available Streetcar commands are “inert” until two things happen: they are placed within a Streetcar line element (<sc-line>) and that element is appended to the end of <body>. Once this happens, all of the commands are run in sequence and then the line element auto-removes itself. <sc-line> is styled as display: none so nothing visually changes. All of these web components are “under the hood” as it were.
The benefit to this approach is no JavaScript is sent over the wire and interpreted in any way. 100% of the Streetcar JS code is part of the library loaded at application start. Once a payload comes in from a server request (or possibly async via Server-Sent Events or Websockets), the HTML-based custom elements will inform the resulting logic executed by the Streetcar runtime.
Quick Examples #
….
Advanced Usage #
….