# Switch A toggle switch (on/off). Renders as a hidden `` with a styled track and thumb driven by JavaScript. Fires no custom events — read the underlying checkbox value in form submissions. --- ## HTML structure ``` label[for={id}].flex.items-center.gap-3.cursor-pointer div.switch-root.relative.w-11.h-6.rounded-full ← outer track input[type=checkbox, id, name, class="sr-only", $$Checked$$] ← hidden; holds true state div.switch-thumb.absolute.top-0.5.left-0.5... ← animated thumb span.text-sm.select-none ← label text (omitted when empty) {label} ``` --- ## CSS mechanics | Class | Effect | |---|---| | `sr-only` | Hides the real checkbox visually but keeps it accessible | | `switch-root` | `bg-input` (off) / `bg-primary` (on) — toggled by JS adding `switch-on` class | | `switch-thumb` | `h-5 w-5 rounded-full bg-background shadow transition-transform` | | `translate-x-5` | Added to thumb by JS when switch is on (slides right) | --- ## JavaScript (`initSwitch` in `components.js`) Runs on `DOMContentLoaded` and `htmx:afterSwap`. **Per-switch initialization:** 1. Guard `_switchInit` prevents double-binding 2. Sync visual state from the hidden checkbox `checked` property on load 3. On `label` click: toggle `checked`, toggle `switch-on` on the track, toggle `translate-x-5` on the thumb --- ## Constructor signature ```csharp public Switch( string id, string label = "", string name = "", bool isChecked = false) ``` | Parameter | Description | |---|---| | `id` | Element id for the hidden checkbox; label's `for` attribute | | `label` | Optional visible text to the right of the toggle | | `name` | Form field name for the hidden checkbox | | `isChecked` | Initial on/off state | --- ## Usage examples ### Basic on/off toggle ```csharp new Switch( id: "notifications", label: "Enable notifications", name: "enableNotifications", isChecked: true) ``` ### Toggle without label ```csharp new Switch(id: "darkMode", name: "darkMode") ``` ### Reading in a form handler ```csharp public record Command( [property: FromForm] string? EnableNotifications = null ); bool notificationsOn = command.EnableNotifications != null; ``` > Like all checkboxes, an unchecked switch is not included in the form submission. Use `null` as the default in your command record. ### HTMX auto-save on change ```csharp // The hidden checkbox is named, so wrap in a form or use hx-include: new Switch( id: "maintenance", name: "maintenanceMode", label: "Maintenance mode", isChecked: currentState) ``` ```html ``` --- ## Tips and tricks - The hidden checkbox carries the value `"on"` when checked (standard checkbox default). If you need `"true"`, add `value="true"` by subclassing or via a wrapper form. - Because the click is handled on the `