# Switch

A control that turns a setting on or off.

- Page: https://www.effectcn.com/components/switch
- Kind: View function
- File: `src/ui/switch.ts`
- Built on: `Switch` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/switch.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/switch.ts`

```ts
import type { Html } from "@effect/ui/html"
import { Switch as KitSwitch, type SwitchProps } from "@effect/ui-kit"
import { cn } from "#lib/cn"

const sizes = {
  sm: { root: "h-3.5 w-6.5", thumb: "size-2.5 data-[checked]:translate-x-3" },
  default: { root: "h-4.5 w-8", thumb: "size-3.5 data-[checked]:translate-x-3.5" },
  lg: { root: "h-6 w-10.5 p-[3px]", thumb: "size-4.5 data-[checked]:translate-x-4.5" }
} as const

export type SwitchSize = keyof typeof sizes

/**
 * The kit's Switch, drawn: a track with its thumb. Pass the value as
 * `props.checked` and store what `onToggle` reports. It returns the root
 * button, so chain an `id` or `aria-label` on it, or wrap it in a label.
 */
export const Switch = <Msg>(
  h: Html.H<Msg>,
  options: {
    readonly size?: SwitchSize | undefined
    readonly class?: string | undefined
    readonly props: SwitchProps
    readonly onToggle?: ((event: { readonly checked: boolean }) => NoInfer<Msg> | undefined) | undefined
  }
) => {
  const size = sizes[options.size ?? "default"]
  return KitSwitch(h, {
    props: options.props,
    onToggle: options.onToggle,
    view: (parts) =>
      parts
        .root(
          h.button.class(cn(
            "inline-flex shrink-0 items-center rounded-full border-0 bg-input p-0.5 transition-colors duration-150 " +
              "data-[checked]:bg-brand data-[readonly]:cursor-default " +
              "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
            size.root,
            options.class
          ))
        )
        .children(
          parts.thumb(
            h.span.class(cn(
              "rounded-full bg-background shadow-sm transition-[translate,background-color] duration-150 " +
                "dark:bg-foreground data-[checked]:bg-brand-foreground dark:data-[checked]:bg-brand-foreground",
              size.thumb
            ))
          )
        )
  })
}

/** A label for the switch: around it, or beside it with `for`. It dims with a disabled switch inside it. */
export const SwitchLabel = <Msg>(h: Html.H<Msg>, options: { readonly class?: string | undefined } = {}) =>
  h.label.class(cn(
    "inline-flex cursor-pointer items-center gap-2.5 text-[13px] leading-4.5 font-medium select-none " +
      "has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:text-muted-foreground",
    options.class
  ))
```

```ts
import { Switch, SwitchLabel } from "#ui/switch"
```

## Usage

A label around the root names the switch and toggles it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchBasicMessage = UiSchema.TaggedEnum({ ToggledAirplaneMode: { checked: Schema.Boolean } })

export const SwitchBasic = Html.component({
  name: "SwitchBasic",
  model: Schema.Struct({ airplaneMode: Schema.Boolean }),
  message: SwitchBasicMessage
}).make({
  init: () => ({ airplaneMode: false }),
  update: {
    ToggledAirplaneMode: ($, { checked }) => $.evolve({ airplaneMode: checked })
  },
  view: (h, model) =>
    SwitchLabel(h).children(
      Switch(h, {
        props: { checked: model.airplaneMode },
        onToggle: ({ checked }) => SwitchBasicMessage.ToggledAirplaneMode({ checked })
      }),
      "Airplane mode"
    )
})
```

## Examples

### Sizes

Small, default and large, set with data-size on the root.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchSizesMessage = UiSchema.TaggedEnum({
  ToggledSwitch: { size: Schema.String, checked: Schema.Boolean }
})

const sizes = [
  { size: "sm", label: "Small" },
  { size: "default", label: "Default" },
  { size: "lg", label: "Large" }
] as const

export const SwitchSizes = Html.component({
  name: "SwitchSizes",
  model: Schema.Struct({ on: Schema.Array(Schema.String) }),
  message: SwitchSizesMessage
}).make({
  init: () => ({ on: ["default"] }),
  update: {
    ToggledSwitch: ($, { checked, size }) =>
      $.evolve({ on: (on) => checked ? [...on, size] : on.filter((other) => other !== size) })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-center gap-7").children(
      // Switch is a view function, so several in one view need no key.
      sizes.map(({ label, size }) =>
        SwitchLabel(h).children(
          Switch(h, {
            size,
            props: { checked: model.on.includes(size) },
            onToggle: ({ checked }) => SwitchSizesMessage.ToggledSwitch({ size, checked })
          }),
          label
        )
      )
    )
})
```

### Settings list

Each row has a label and a description, with the switch on the right.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchSettingsMessage = UiSchema.TaggedEnum({
  ToggledSetting: { setting: Schema.String, checked: Schema.Boolean }
})

const settings = [
  { value: "mentions", label: "Mentions", description: "When someone mentions you in a comment." },
  { value: "digest", label: "Weekly digest", description: "A summary of your team's activity, every Monday." },
  { value: "marketing", label: "Product news", description: "New features and the occasional announcement." }
]

export const SwitchSettings = Html.component({
  name: "SwitchSettings",
  model: Schema.Struct({ enabled: Schema.Array(Schema.String) }),
  message: SwitchSettingsMessage
}).make({
  init: () => ({ enabled: ["mentions", "digest"] }),
  update: {
    ToggledSetting: ($, { checked, setting }) =>
      $.evolve({
        enabled: (enabled) =>
          checked ? [...enabled, setting] : enabled.filter((other) => other !== setting)
      })
  },
  view: (h, model) =>
    h.div.class("w-full max-w-md divide-y rounded-lg border bg-card").children(
      settings.map(({ description, label, value }) =>
        h.div.class("flex items-center justify-between gap-6 px-4 py-3.5").children(
          h.div.class("grid gap-0.5").children(
            SwitchLabel(h).attr("for", `switch-${value}`).children(label),
            h.p.class("text-[13px] text-muted-foreground").attr("id", `switch-${value}-description`).children(
              description
            )
          ),
          Switch(h, {
            props: { checked: model.enabled.includes(value) },
            onToggle: ({ checked }) => SwitchSettingsMessage.ToggledSetting({ setting: value, checked })
          }).attrs({ id: `switch-${value}`, "aria-describedby": `switch-${value}-description` })
        )
      )
    )
})
```

### Disabled and read-only

A disabled switch leaves the tab order. A read-only one keeps focus and ignores clicks.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchDisabledMessage = UiSchema.TaggedEnum({ ToggledSwitch: { checked: Schema.Boolean } })

const states = [
  { label: "Disabled", props: { checked: false, disabled: true } },
  { label: "Disabled and on", props: { checked: true, disabled: true } },
  { label: "Read-only, still focusable", props: { checked: true, readOnly: true } }
]

export const SwitchDisabled = Html.component({
  name: "SwitchDisabled",
  model: Schema.Struct({ toggles: Schema.Number }),
  message: SwitchDisabledMessage
}).make({
  init: () => ({ toggles: 0 }),
  update: {
    ToggledSwitch: ($) => $.evolve({ toggles: (toggles) => toggles + 1 })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-start gap-3.5").children(
      states.map(({ label, props }) =>
        SwitchLabel(h).children(
          Switch(h, {
            props,
            onToggle: ({ checked }) => SwitchDisabledMessage.ToggledSwitch({ checked })
          }),
          label
        )
      ),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`Toggled ${model.toggles} times`)
    )
})
```

### Card

The whole card is the label, and its text follows parts.checked.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch } from "#ui/switch"

const SwitchCardMessage = UiSchema.TaggedEnum({ ToggledSharing: { checked: Schema.Boolean } })

export const SwitchCard = Html.component({
  name: "SwitchCard",
  model: Schema.Struct({ sharing: Schema.Boolean }),
  message: SwitchCardMessage
}).make({
  init: () => ({ sharing: true }),
  update: {
    ToggledSharing: ($, { checked }) => $.evolve({ sharing: checked })
  },
  view: (h, model) =>
    h.label
      .class(
        "flex w-full max-w-sm cursor-pointer items-center justify-between gap-6 rounded-lg border bg-card px-4 py-3.5 transition-colors duration-150 select-none has-[[data-checked]]:border-brand has-[[data-checked]]:bg-brand-wash"
      )
      .children(
        h.span.class("grid gap-0.5").children(
          h.span.class("text-[13px] font-medium").children("Share across devices"),
          h.span.class("text-[13px] text-muted-foreground").children(
            model.sharing ? "Focus is shared with your other devices." : "Focus stays on this device only."
          )
        ),
        Switch(h, {
          props: { checked: model.sharing },
          onToggle: ({ checked }) => SwitchCardMessage.ToggledSharing({ checked })
        })
      )
})
```

### In a form

A switch with a name submits its value through a hidden input.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchFormMessage = UiSchema.TaggedEnum({
  ToggledAnalytics: { checked: Schema.Boolean },
  ToggledCrashReports: { checked: Schema.Boolean },
  SubmittedForm: { fields: Schema.Record(Schema.String, Schema.String) }
})

export const SwitchForm = Html.component({
  name: "SwitchForm",
  model: Schema.Struct({
    analytics: Schema.Boolean,
    crashReports: Schema.Boolean,
    saved: Schema.NullOr(Schema.String)
  }),
  message: SwitchFormMessage
}).make({
  init: () => ({ analytics: false, crashReports: true, saved: null }),
  update: {
    ToggledAnalytics: ($, { checked }) => $.evolve({ analytics: checked }),
    ToggledCrashReports: ($, { checked }) => $.evolve({ crashReports: checked }),
    SubmittedForm: ($, { fields }) => $.evolve({ saved: JSON.stringify(fields) })
  },
  view: (h, model) =>
    h.form
      .class("flex flex-col items-start gap-3.5")
      .on("submit", ({ fields }) => SwitchFormMessage.SubmittedForm({ fields }))
      .children(
        // The root carries a hidden input. An off switch submits its uncheckedValue, or nothing.
        SwitchLabel(h).children(
          Switch(h, {
            props: { checked: model.analytics, name: "analytics", value: "on", uncheckedValue: "off" },
            onToggle: ({ checked }) => SwitchFormMessage.ToggledAnalytics({ checked })
          }),
          "Usage analytics"
        ),
        SwitchLabel(h).children(
          Switch(h, {
            props: { checked: model.crashReports, name: "crashReports" },
            onToggle: ({ checked }) => SwitchFormMessage.ToggledCrashReports({ checked })
          }),
          "Crash reports"
        ),
        Button(h, { size: "sm", props: { type: "submit" } }).children("Save preferences"),
        h.p.class("text-xs text-muted-foreground").children(
          model.saved === null ? "Nothing submitted yet" : `Submitted ${model.saved}`
        )
      )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | The <button role="switch">. It adds the hidden input that carries the form value. |
| `thumb` | A <span> inside the root. |
| `checked, disabled, readOnly, required` | The state as booleans, for markup that depends on it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `checked` | `boolean` | Whether the switch is on. Required. |
| `disabled` | `boolean` | Sets the native disabled attribute: skipped by Tab, ignores clicks. |
| `readOnly` | `boolean` | Ignores clicks but stays focusable. |
| `required` | `boolean` | Sets aria-required and data-required. It doesn't block a submit. |
| `name` | `string` | The form field's name. Without it nothing is submitted. |
| `value` | `string` | What an on switch submits, "on" by default. |
| `uncheckedValue` | `string` | What an off switch submits. Nothing when unset. |

### Events

| Event | Description |
| --- | --- |
| `onToggle` | ({ checked }) => message: the value the user asked for. Store it and pass it back as checked. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-checked` | On root and thumb while on. |
| `data-unchecked` | On root and thumb while off. |
| `data-disabled` | On root and thumb while disabled. |
| `data-readonly` | On root and thumb while read-only. |
| `data-required` | On root and thumb while required. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
