Custom Attributes

The app below writes its own three attributes, lvt-x:rating, lvt-x:copy and lvt-x:hotkey, in an inline <script>. The custom attributes guide explains the interface; the source is examples/custom-attributes/.

Try it

Rate this recipe

Not rated yet.

https://livetemplate.fly.dev/recipes/custom-attributes

Press 1–5 to rate.

Click a star, or press 1 to 5. Copy the link and check the number on the end. Then turn shortcuts off and press a key.

The markup

<main class="container">
    <h1>Rate this recipe</h1>
    <div class="stars" lvt-x:rating="SetRating">
        {{range .Stars}}<button type="button" data-star="{{.}}" aria-label="{{.}} stars"{{if $.Shortcuts}} lvt-x:hotkey="{{.}}"{{end}}{{if ge $.Rating .}} class="on"{{end}}>★</button>{{end}}
    </div>
    <p id="rating">{{if .Rating}}Rated {{.Rating}} of 5.{{else}}Not rated yet.{{end}}</p>
    <p>
        <button type="button" id="copy" class="outline" lvt-x:copy="{{.ShareURL}}">Copy link</button>
        <small id="share">{{.ShareURL}}</small>
    </p>
    <p>
        <button type="button" id="shortcuts" class="secondary" lvt-on:click="ToggleShortcuts">{{if .Shortcuts}}Turn shortcuts off{{else}}Turn shortcuts on{{end}}</button>
        <small id="shortcut-state">{{if .Shortcuts}}Press <kbd>1</kbd>–<kbd>5</kbd> to rate.{{else}}Keys 1–5 do nothing.{{end}}</small>
    </p>
</main>

custom-attributes.tmpl:91-105

The server renders lvt-x:rating="SetRating" like any other attribute, and renders lvt-x:hotkey only while .Shortcuts is true.

A rating that sends an action

(window.lvtAttributes ||= []).push(
    {
        // Declarative, sends an action. ctx.value is the action name.
        attribute: "lvt-x:rating",
        needsServerChannel: true,
        onElementAdded(el, ctx) {
            el.addEventListener("click", (e) => {
                const star = e.target.closest("[data-star]");
                if (!star) return;
                ctx.send?.({ action: ctx.value, data: { stars: Number(star.dataset.star) } });
            }, { signal: ctx.signal });
        },
    },

custom-attributes.tmpl:22-34

// SetRating is the action lvt-x:rating dispatches. It is an ordinary action:
// nothing here can tell it came from a custom attribute rather than a button.
func (c *Controller) SetRating(s State, ctx *livetemplate.Context) (State, error) {
	stars := ctx.GetInt("stars")
	if stars < 1 || stars > 5 {
		return s, fmt.Errorf("stars must be 1 to 5, got %d", stars)
	}
	s.Rating = stars
	return s, nil
}

controller.go:34-43

Anyone can send {"stars": 9000} from the console, so the action checks the range like any other input.

A copy button that reads the current value

    {
        // Declarative, visual only. ctx.value is read at click time,
        // so it is the link for the current rating.
        attribute: "lvt-x:copy",
        onElementAdded(el, ctx) {
            el.addEventListener("click", async () => {
                await navigator.clipboard.writeText(ctx.value);
                el.textContent = "Copied";
                setTimeout(() => { el.textContent = "Copy link"; }, 1500);
            }, { signal: ctx.signal });
        },
    },
);

custom-attributes.tmpl:35-47

The link includes the rating, which changes after the handler attaches, so the click reads ctx.value when it runs.

Shortcuts the server can take away

// Low-level: one keydown listener for the whole page, mapping each key
// to the element that claims it. That shared state is what the
// declarative layer has no place for.
(() => {
    // One key map per client: the registry is shared by every
    // client on the page, and setup() runs for each one's renders.
    const keysByRoot = new Map();
    const onKey = (e) => {
        if (e.ctrlKey || e.metaKey || e.altKey) return;
        if (e.target.closest?.("input, textarea, select, [contenteditable]")) return;
        for (const keys of keysByRoot.values()) {
            const el = keys.get(e.key);
            if (el) return el.click();
        }
    };
    window.lvtAttributes.push({
        name: "lvt-x:hotkey",
        selectors: ["[lvt-x\\:hotkey]"],
        claims: ["lvt-x:hotkey"],
        runOnConnect: true,
        setup({ wrapperRoot }) {
            // Sweep and re-arm in one step: rebuild this client's map
            // from what its page carries now. A key whose attribute
            // the server removed is simply not in it.
            const keys = new Map();
            for (const el of wrapperRoot.querySelectorAll("[lvt-x\\:hotkey]")) {
                keys.set(el.getAttribute("lvt-x:hotkey"), el);
            }
            keysByRoot.set(wrapperRoot, keys);
            // setup() runs after every render. Adding the same function
            // again is a no-op in the DOM, so this never stacks.
            document.addEventListener("keydown", onKey);
        },
        teardown(root) {
            keysByRoot.delete(root);
        },
        dispose() {
            document.removeEventListener("keydown", onKey);
        },
    });
})();

custom-attributes.tmpl:49-89

Turning shortcuts off re-renders the stars without lvt-x:hotkey. setup() then rebuilds this client's map from the page, finds no keys, and the shortcuts stop. The server never tells the handler.

What the test checks

TestCustomAttributesE2E drives the page through a real Chrome:

The test runs over plain HTTP, where navigator.clipboard does not exist, so it stubs the clipboard and records what each click copies.

source: livetemplate/docs · path: content/recipes/custom-attributes.md