bold, aligned left, 3 edits

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/toolbar.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { ButtonElement, Toolbar } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    type ToolbarParts = Component.Headless.Parts<typeof Toolbar>
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const control =
      "inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-sm border-0 bg-transparent text-[13px] font-medium " +
      "whitespace-nowrap text-foreground no-underline select-none transition-colors duration-150 " +
      "hover:bg-accent hover:text-accent-foreground focus-visible:outline-offset-0 " +
      "[&_svg]:size-4 [&_svg]:shrink-0"
    
    const buttonSizes = {
      icon: "w-8 px-0",
      text: "px-2.5"
    } as const
    
    export type ToolbarButtonSize = keyof typeof buttonSizes
    
    /** The bar. The kit sets `data-orientation`, and a vertical toolbar becomes a column. */
    export const ToolbarRoot = <Msg>(
      h: Html.H<Msg>,
      toolbar: Pick<ToolbarParts, "root">,
      options: ClassOption & { readonly label: string }
    ) =>
      toolbar.root(
        h.div
          .class(cn(
            "group/toolbar inline-flex items-center gap-1 rounded-lg border bg-background p-1 shadow-sm",
            "data-[orientation=vertical]:flex-col",
            options.class
          ))
          .attr("aria-label", options.label)
      )
    
    /**
     * One button of the toolbar. To stack it on another kit part, pass that part as
     * `element`: a toggle group's item, `toggleGroup.item({ element: h.button, value })`,
     * which fills with the brand colour while pressed, or a menu's trigger.
     */
    export const ToolbarButton = <Msg>(
      h: Html.H<Msg>,
      toolbar: Pick<ToolbarParts, "button">,
      options: ClassOption & {
        readonly value: string
        readonly size?: ToolbarButtonSize | undefined
        readonly label?: string | undefined
        readonly element?: ButtonElement<Msg> | undefined
      }
    ) =>
      toolbar.button({
        element: (options.element ?? h.button)
          .class(cn(
            control,
            "group data-[disabled]:pointer-events-none data-[disabled]:opacity-45 data-[focusable]:pointer-events-auto",
            "data-[focusable]:data-[disabled]:cursor-not-allowed data-[focusable]:data-[disabled]:hover:bg-transparent",
            "data-[pressed]:bg-brand data-[pressed]:text-brand-foreground",
            "data-[popup-open]:bg-accent",
            buttonSizes[options.size ?? "icon"],
            options.class
          ))
          .attr("aria-label", options.label),
        value: options.value
      })
    
    /** A link among the toolbar's items. Chain `target` and `rel` on the result. */
    export const ToolbarLink = <Msg>(
      h: Html.H<Msg>,
      toolbar: Pick<ToolbarParts, "link">,
      options: ClassOption & { readonly value: string; readonly href: string }
    ) =>
      toolbar.link({
        element: h.a
          .class(cn(control, "px-2.5 font-normal text-muted-foreground", options.class))
          .attr("href", options.href),
        value: options.value
      })
    
    /** A text input, which goes last in a horizontal toolbar. Chain `.value(...)` and the `input` handler on the result. */
    export const ToolbarInput = <Msg>(
      h: Html.H<Msg>,
      toolbar: Pick<ToolbarParts, "input">,
      options: ClassOption & {
        readonly value: string
        readonly type?: string | undefined
        readonly placeholder?: string | undefined
        readonly label?: string | undefined
      }
    ) =>
      toolbar.input({
        element: h.input
          .class(cn(
            "h-8 w-44 rounded-sm border border-input bg-background px-2.5 text-[13px] text-foreground outline-none",
            "transition-colors duration-150 placeholder:text-muted-foreground focus-visible:border-ring",
            "data-[disabled]:opacity-50",
            options.class
          ))
          .attrs({
            type: options.type ?? "text",
            placeholder: options.placeholder,
            "aria-label": options.label ?? options.placeholder
          }),
        value: options.value
      })
    
    /** A group of items that can be disabled together, by its entry in the `groups` prop. */
    export const ToolbarGroup = <Msg>(
      h: Html.H<Msg>,
      toolbar: Pick<ToolbarParts, "group">,
      options: ClassOption & { readonly value: string; readonly label?: string | undefined }
    ) =>
      toolbar.group({
        element: h.div
          .class(cn("flex items-center gap-0.5 data-[orientation=vertical]:flex-col", options.class))
          .attr("aria-label", options.label),
        value: options.value
      })
    
    /** A line between items, across the toolbar's direction. */
    export const ToolbarSeparator = <Msg>(h: Html.H<Msg>, toolbar: Pick<ToolbarParts, "separator">, options: ClassOption = {}) =>
      toolbar.separator(
        h.div.class(cn(
          "shrink-0 bg-border data-[orientation=horizontal]:my-0.5 data-[orientation=horizontal]:h-px",
          "data-[orientation=horizontal]:w-6 data-[orientation=vertical]:mx-0.5 data-[orientation=vertical]:h-5",
          "data-[orientation=vertical]:w-px",
          options.class
        ))
      )
    
  3. Import it

    import { ToolbarRoot, ToolbarButton, ToolbarLink, ToolbarInput, ToolbarGroup, ToolbarSeparator } from "#ui/toolbar"
    

Usage

Text editor.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Button, ToggleGroup, Toolbar } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToolbarButton, ToolbarRoot, ToolbarSeparator } from "#ui/toolbar"

const ToolbarEditorMessage = UiSchema.TaggedEnum({
  ToggledMarks: { value: Schema.Array(Schema.String) },
  ToggledAlign: { value: Schema.Array(Schema.String) },
  PressedUndo: {},
  PressedRedo: {}
})

const marks = [
  { value: "bold", label: "Bold", glyph: "B" },
  { value: "italic", label: "Italic", glyph: "I" },
  { value: "underline", label: "Underline", glyph: "U" }
]

const alignments = [
  { value: "left", label: "Align left", icon: "M4 6h16M4 12h10M4 18h13" },
  { value: "center", label: "Align center", icon: "M4 6h16M7 12h10M5 18h14" },
  { value: "right", label: "Align right", icon: "M4 6h16M10 12h10M7 18h13" }
]

const items = [...marks, ...alignments, { value: "undo" }, { value: "redo" }].map(({ value }) => ({ value }))

export const ToolbarEditor = Html.component({
  name: "ToolbarEditor",
  model: Schema.Struct({
    marks: Schema.Array(Schema.String),
    align: Schema.String,
    edits: Schema.Number
  }),
  message: ToolbarEditorMessage
}).make({
  init: () => ({ marks: ["bold"], align: "left", edits: 3 }),
  update: {
    ToggledMarks: ($, { value }) => $.evolve({ marks: value, edits: (edits) => edits + 1 }),
    // One alignment always stays pressed.
    ToggledAlign: ($, { value }) => value[0] === undefined ? $.model : $.evolve({ align: value[0] }),
    PressedUndo: ($) => $.evolve({ edits: (edits) => Math.max(0, edits - 1) }),
    PressedRedo: ($) => $.evolve({ edits: (edits) => edits + 1 })
  },
  view: (h, model) => {
    const icon = (d: string) =>
      h.el("svg")
        .attrs({ viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "aria-hidden": "true" })
        .children(h.el("path").attrs({ d, "stroke-linecap": "round", "stroke-linejoin": "round" }))
    return h.div.class("flex flex-col items-center gap-4").children(
      Toolbar(h, {
        props: { items },
        view: (toolbar) =>
          ToolbarRoot(h, toolbar, { label: "Formatting" }).children(
            ToggleGroup(h, {
              key: "marks",
              props: { value: model.marks, items: marks.map(({ value }) => ({ value })), multiple: true },
              onEmit: ({ value }) => ToolbarEditorMessage.ToggledMarks({ value }),
              view: (toggleGroup) =>
                toggleGroup.root(h.div.class("flex items-center gap-0.5").attr("aria-label", "Text style")).children(
                  marks.map(({ glyph, label, value }) =>
                    // Stack the toolbar's button on the toggle group's item, with one value.
                    ToolbarButton(h, toolbar, {
                      value,
                      label,
                      class: "font-serif text-[15px]",
                      element: toggleGroup.item({ element: h.button, value })
                    }).children(glyph)
                  )
                )
            }),
            ToolbarSeparator(h, toolbar),
            ToggleGroup(h, {
              key: "align",
              props: { value: [model.align], items: alignments.map(({ value }) => ({ value })) },
              onEmit: ({ value }) => ToolbarEditorMessage.ToggledAlign({ value }),
              view: (toggleGroup) =>
                toggleGroup.root(h.div.class("flex items-center gap-0.5").attr("aria-label", "Alignment")).children(
                  alignments.map(({ icon: d, label, value }) =>
                    ToolbarButton(h, toolbar, { value, label, element: toggleGroup.item({ element: h.button, value }) }).children(icon(d))
                  )
                )
            }),
            ToolbarSeparator(h, toolbar),
            Button(h, {
              element: ToolbarButton(h, toolbar, { value: "undo", label: "Undo" }),
              onPress: ToolbarEditorMessage.PressedUndo()
            }).children(icon("M9 14 4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3")),
            Button(h, {
              element: ToolbarButton(h, toolbar, { value: "redo", label: "Redo" }),
              onPress: ToolbarEditorMessage.PressedRedo()
            }).children(icon("m15 14 5-5-5-5M20 9H10a6 6 0 0 0 0 12h3"))
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        `${model.marks.length === 0 ? "Plain" : model.marks.join(" + ")}, aligned ${model.align}, ${model.edits} edits`
      )
    )
  }
})

Examples

A Menu trigger is a toolbar button too. Buttons that reach their limit are disabled but stay focusable.

Vertical

A tool palette. ArrowDown and ArrowUp move through the tools and the zoom buttons.

select tool at 100%

Links and a search input are items as well. In the input the arrow keys move the caret and leave only from its ends.

0 created

Disabled group

A group disables its items together. Delete opts out of focusableWhenDisabled, so the arrow keys skip it.

Locked: the arrow keys still reach the clipboard buttons

Anatomy

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

PartDescription
rootThe <div> with role="toolbar".
buttonA <button> per button item, { element, value }. Stack it on a toggle group's item or a Menu, Select or Dialog trigger.
linkAn <a> per link item. A link is never disabled.
inputAn <input> per input item. Put at most one in a horizontal toolbar, as its last item.
groupA <div> around some items, { element, value }, that can disable them together.
separatorA <div> between items, across the toolbar's direction.
isDisabled(value)Whether an item is disabled, for a Menu or Select stacked inside it.

API reference

Props

PropTypeDescription
itemsArray<{ value, disabled?, focusableWhenDisabled?, group? }>Every button, link and input in the order they are drawn. Required.
groupsArray<{ value, disabled? }>Every group drawn with the group part.
disabledbooleanDisables every button and input.
orientation"horizontal" | "vertical"Right and Left move focus by default; "vertical" uses Down and Up.
loopFocusbooleanThe arrow keys wrap from the last item to the first. On by default.

Events

EventDescription
(none)The toolbar emits nothing: each control inside reports its own press, toggle or choice.

Data attributes

AttributeDescription
data-orientationOn every part. On the separator it is across the toolbar's: "vertical" in a horizontal toolbar.
data-disabledOn the root, a group, a button or an input that is disabled.
data-focusableOn a button or input that stays focusable while disabled.
data-pressedOn a toggle group item stacked on a toolbar button.

The components this page's file and examples import.

  • Menu: A button that opens a list of actions, links, checkbox and radio items, and submenus.

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