A button that stays pressed, such as Bold or Pin.
- 1.2 kB JS 3.3 kB CSS gzipped
- No serious axe issues
- Server-rendered, hydrates
- 44px touch targets
- Right-to-left
import { UiSchema } from "effect/ui"import { Html } from "effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Schema } from "effect"import { Toggle } from "./ui/uicontext/components/Toggle.ts"import { sx } from "./ui/uicontext/components/Sx.ts"const styles = stylex.create({ bar: { display: "flex", gap: 4 },})const Mark = Schema.Literals(["bold", "italic", "code"])type Mark = typeof Mark.Typeconst Message = UiSchema.TaggedEnum({ ClickedMark: { mark: Mark } })export const FormatToggles = Html.component({ name: "FormatToggles", model: Schema.Struct({ marks: Schema.Array(Mark) }), message: Message,}).make({ init: () => ({ marks: ["bold"] }), update: { ClickedMark: ($, { mark }) => $.evolve({ marks: (marks) => (marks.includes(mark) ? marks.filter((m) => m !== mark) : [...marks, mark]) }), }, view: (h, { marks }) => h.div.attrs({ role: "toolbar", "aria-label": "Formatting", ...sx(styles.bar) }).children( ([["bold", "Bold"], ["italic", "Italic"], ["code", "Code"]] as const).map(([mark, label]) => // aria-pressed follows the Model; the toggle never flips itself Toggle(h, { pressed: marks.includes(mark), size: "sm" }).key(mark).on("click", Message.ClickedMark({ mark })).children(label)), ),})When to use
A button that stays pressed, such as Bold or Pin. Use Toggle Group instead when several pressed buttons share one value.
Usage
import { Toggle } from "./ui/uicontext/components/Toggle.ts"const Message = UiSchema.TaggedEnum({ ClickedPin: {} })// `pinned` lives in your Model; ClickedPin flips itexport const PinToggle = (h: Html.H<typeof Message.Type>, pinned: boolean) => Toggle(h, { pressed: pinned }).on("click", Message.ClickedPin()).children("Pin")API reference
Options
| Name | Type | Description |
|---|---|---|
pressedrequired | boolean | Whether it's on. The caller keeps it and flips it on click. |
Keyboard and accessibility
- Renders a native
<button>witharia-pressed, so Enter and Space press it and screen readers say whether it's on. - An icon-only toggle needs an
aria-label.
Installation
pnpm dlx shadcn@latest add checkfu/uicontext/toggle