Aligned left

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/toggle-group.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { ToggleGroup } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    type ToggleGroupParts = Component.Headless.Parts<typeof ToggleGroup>
    
    export type ToggleGroupVariant = "default" | "outline"
    export type ToggleGroupSize = "default" | "sm" | "lg"
    
    /**
     * The group. `variant` and `size` are set once here, and the items follow
     * them: `outline` joins the items into one bordered control.
     */
    export const ToggleGroupRoot = <Msg>(
      h: Html.H<Msg>,
      toggleGroup: ToggleGroupParts,
      options: {
        readonly variant?: ToggleGroupVariant | undefined
        readonly size?: ToggleGroupSize | undefined
        readonly class?: string | undefined
      } = {}
    ) =>
      toggleGroup.root(
        h.div
          .class(cn(
            "group/toggle-group inline-flex items-center gap-0.5 rounded-md " +
              "data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch " +
              "data-[variant=outline]:gap-0 data-[variant=outline]:shadow-sm",
            options.class
          ))
          .attrs({ "data-variant": options.variant ?? "default", "data-size": options.size ?? "default" })
      )
    
    const item =
      "inline-flex h-8.5 min-w-8.5 shrink-0 items-center justify-center gap-1.5 rounded-md border border-transparent " +
      "bg-transparent px-2 text-[13px] leading-none font-medium whitespace-nowrap text-foreground select-none " +
      "transition-colors duration-150 hover:bg-muted hover:text-muted-foreground focus-visible:relative focus-visible:z-10 " +
      "data-[pressed]:bg-brand-soft data-[pressed]:text-brand-soft-foreground " +
      "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:size-[15px] [&_svg]:shrink-0 " +
      "group-data-[size=sm]/toggle-group:h-7 group-data-[size=sm]/toggle-group:min-w-7 " +
      "group-data-[size=sm]/toggle-group:px-1.5 group-data-[size=sm]/toggle-group:text-xs " +
      "group-data-[size=lg]/toggle-group:h-10 group-data-[size=lg]/toggle-group:min-w-10 " +
      "group-data-[size=lg]/toggle-group:px-3 group-data-[size=lg]/toggle-group:text-sm " +
      "group-data-[variant=outline]/toggle-group:rounded-none group-data-[variant=outline]/toggle-group:border-input"
    
    const joined = {
      horizontal: "group-data-[variant=outline]/toggle-group:not-first:-ml-px " +
        "group-data-[variant=outline]/toggle-group:first:rounded-l-md " +
        "group-data-[variant=outline]/toggle-group:last:rounded-r-md",
      vertical: "justify-start group-data-[variant=outline]/toggle-group:not-first:-mt-px " +
        "group-data-[variant=outline]/toggle-group:first:rounded-t-md " +
        "group-data-[variant=outline]/toggle-group:last:rounded-b-md"
    } as const
    
    /** One item, for the `value` of an entry in the group's `items` prop. Chain its label or icon as children. */
    export const ToggleGroupItem = <Msg>(
      h: Html.H<Msg>,
      toggleGroup: ToggleGroupParts,
      options: { readonly value: string; readonly class?: string | undefined }
    ) =>
      toggleGroup.item({
        element: h.button.class(cn(item, joined[toggleGroup.orientation], options.class)),
        value: options.value
      })
    
  3. Import it

    import { ToggleGroupRoot, ToggleGroupItem } from "#ui/toggle-group"
    

Usage

Single.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupSingleMessage = UiSchema.TaggedEnum({
  ToggledAlignment: { value: Schema.Array(Schema.String) }
})

const alignments = [
  { value: "left", label: "Align left", d: "M21 6H3M15 12H3M17 18H3" },
  { value: "center", label: "Align center", d: "M21 6H3M17 12H7M19 18H5" },
  { value: "right", label: "Align right", d: "M21 6H3M21 12H9M21 18H7" }
]

export const ToggleGroupSingle = Html.component({
  name: "ToggleGroupSingle",
  model: Schema.Struct({ alignment: Schema.Array(Schema.String) }),
  message: ToggleGroupSingleMessage
}).make({
  init: () => ({ alignment: ["left"] }),
  update: {
    ToggledAlignment: ($, { value }) => $.evolve({ alignment: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      ToggleGroup(h, {
        props: { value: model.alignment, items: alignments.map(({ value }) => ({ value })) },
        onEmit: { Toggled: ({ value }) => ToggleGroupSingleMessage.ToggledAlignment({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup).attr("aria-label", "Text alignment").children(
            alignments.map(({ d, label, value }) =>
              ToggleGroupItem(h, toggleGroup, { value })
                .attr("aria-label", label)
                .children(
                  h.el("svg")
                    .attrs({
                      viewBox: "0 0 24 24",
                      fill: "none",
                      stroke: "currentColor",
                      "stroke-width": "2",
                      "stroke-linecap": "round",
                      "aria-hidden": "true"
                    })
                    .children(h.el("path").attr("d", d))
                )
            )
          )
      }),
      // Pressing the pressed item releases it, so the value can be empty.
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.alignment.length === 0 ? "No alignment" : `Aligned ${model.alignment.join(", ")}`
      )
    )
})

Examples

Multiple

With multiple, several items stay pressed at once.

bold, italic

Outline

A joined, bordered control with text labels that always keeps one item pressed.

Showing the board

Sizes

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

Vertical

A column of items that moves with the Down and Up keys.

Disabled

One disabled item, and a group that is disabled as a whole.

Billing monthly. The region group is disabled.

Anatomy

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

PartDescription
rootA <div> with role="group". Add the items as its children.
itemitem({ element: h.button, value }): one <button> per entry in items. It writes the same attributes as Toggle.
value, disabled, multiple, orientationThe group's state, for markup that depends on it.

API reference

Props

PropTypeDescription
valueReadonlyArray<string>The values of the pressed items. Required.
itemsReadonlyArray<{ value: string; disabled?: boolean }>Every item, in the order they are drawn. Required.
disabledbooleanDisables every item.
multiplebooleanLets several items be pressed at once. Off by default.
orientation"horizontal" | "vertical"Which arrow keys move focus. "horizontal" by default.
loopFocusbooleanThe arrow keys wrap from the last item to the first. On by default.

Events

EventDescription
Toggled{ value }: the pressed values the user asked for. Empty when the pressed item was released.

Data attributes

AttributeDescription
data-orientationOn the root: "horizontal" or "vertical".
data-multipleOn the root when several items can be pressed.
data-disabledOn the root while the group is disabled, and on each disabled item.
data-pressedOn each pressed item.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.