Toggle
An accessible switch bound to a boolean in state. It uses role="switch" with
aria-checked, and a method that returns the full class string so the track and
knob restyle on every toggle.
Markup
<button
type="button"
role="switch"
data-bind="class:sw(emails), aria-checked:ac(emails)"
@click="toggle('emails')"
aria-label="Email notifications"
>
<span data-bind="class:knob(emails)"></span>
</button>
Component
Micra.define("toggle", {
state: { emails: true, weekly: false },
ac(on) {
return on ? "true" : "false";
},
sw(on) {
const base =
"relative inline-flex h-6 w-11 items-center rounded-full transition-colors ";
return base + (on ? "bg-indigo-600" : "bg-zinc-200");
},
knob(on) {
const base =
"inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ";
return base + (on ? "translate-x-6" : "translate-x-1");
},
toggle(key) {
this.state[key] = !this.state[key];
},
});
The handler writes a top-level key (this.state[key] = ...), so the shallow
proxy fires one render and every binding that reads it updates.