Packages

Cloves catalog

ajo-cloves: ready-made behaviors for interaction, focus and sensing.

A gilded garlic bulb with three separated cloves on the sand.A gilded garlic bulb with three separated cloves on the sand.

ajo-cloves is a catalog of ready-made cloves: plain functions that attach one behavior to a stateful Ajo component and return a live view of it. Controlled state, dismissal, keyboard movement, timers, media queries and storage each come as a separate function, so a component takes only what it needs. The catalog is also the behavior layer under ajo-ui.

Every clove follows the pattern described in Cloves: it takes the component host, cleans up through host.signal, re-renders through host.next(), and returns an object whose identity never changes. Call cloves before the render loop; there are no call-order rules.

Install

Terminal
pnpm add ajo@0.2.0 ajo-cloves@0.2.1

The package requires ajo ^0.2.0, has a single root entry point, and is side-effect-free, so a bundle keeps only the cloves you import.

Compose two behaviors

A details button for a note shows the pattern. controlled lets the parent own the open state or leave it to the component; dismiss closes the panel on Escape or on a pointer press outside it. Neither knows anything about the markup.

src/notes/details.tsx
import type { Stateful } from 'ajo'
import { controlled, dismiss } from 'ajo-cloves'

type Args = {
  label: string
  open?: boolean
  onOpenChange?: (open: boolean, event?: Event) => void
}

const Details: Stateful<Args> = function* (args) {

  let trigger: HTMLButtonElement | null = null
  let panel: HTMLDivElement | null = null

  const open = controlled(this, {
    fallback: false,
    onChange: (value, event) => args.onOpenChange?.(value, event),
  })

  dismiss(this, {
    active: () => open.value,
    inside: () => [trigger, panel],
    outside: true,
    onDismiss: event => open.set(false, event),
  })

  for (args of this) {
    open.sync(args.open) // undefined leaves the component in charge

    yield (
      <>
        <button
          type="button"
          ref={el => trigger = el}
          aria-expanded={open.value ? 'true' : 'false'}
          set:onclick={event => open.set(!open.value, event)}
        >
          {args.label}
        </button>
        {open.value && <div ref={el => panel = el}>Created on Tuesday · 3 revisions</div>}
      </>
    )
  }
}

export default Details

Options that are functions, such as active and inside, are read when the behavior runs, so they always see the latest state and arguments. Reassigning args in for (args of this) keeps the onChange closure current too.

What the catalog holds

Every clove takes the host first and, when it has options, one options object. The package README lists each one with its options and view; they fall into four groups:

  • Interaction: controlled state, dismissal, hover intent, timers, roving focus, typeahead, selection, pointer drags, keyboard shortcuts and screen-reader announcements.
  • Positioning: indicator writes a marked child’s box to its container as --indicator-* variables, so a theme can glide an active marker between tabs instead of jumping. This site’s documentation sidebar uses it for the current page.
  • Sensors: media queries, localStorage that follows other tabs, scrolling, resizing, overflow and document visibility.
  • Infrastructure: small helpers such as browser(), listen() and frame() for writing cloves of your own.

Cloves with a target option observe an element you hold in a ref. Call sync() in the render loop, after the ref may have changed, and the clove moves its listeners to the new element.

Attr bags

When a behavior needs several attributes and handlers on one rendered element, its view exposes an attr bag to spread in JSX. A bag holds HTML attributes such as id, role, tabindex, aria-* and data-*, plus Ajo set:on* handlers. ajo/html renders the attributes on the server and the client attaches the handlers during hydration. Ajo reapplies a bag when keyed reconciliation reuses an element.

ajo-ui’s Field works this way: its context carries controlAttrs, buttonAttrs and groupAttrs, and a custom control inside a Field spreads one of them to get its id, aria-describedby and, when invalid, aria-invalid and aria-errormessage.

src/notes/title-field.tsx
import { Field, FieldContext, FieldError, FieldLabel } from 'ajo-ui/field'

const TitleInput = () => <input name="title" {...FieldContext()?.controlAttrs} />

export default ({ error }: { error?: string }) => (
  <Field name="title" invalid={Boolean(error)}>
    <FieldLabel>Title</FieldLabel>
    <TitleInput />
    <FieldError>{error}</FieldError>
  </Field>
)

Runtime behavior

  • Work attached to a host stops when host.signal aborts: on unmount, and on a reset that restarts the generator, after which the cloves set up again. APIs that accept a caller signal stop when either signal aborts.
  • State changes run inside host.next(), so they re-render the component and are ignored after it ends. Views such as timer and storage also become inert once their host has ended.
  • Sensors subscribe per host: each view adds its own listener and removes it when its host ends.
  • DOM behavior follows native browser behavior and accessible interaction patterns. Cloves compute movement and state; your component decides where focus goes and what renders.

More examples

A theme toggle

media follows the system preference and storage remembers an explicit choice, in every open tab. The component writes to the document only in a browser.

src/theme-toggle.tsx
import type { Stateful } from 'ajo'
import { browser, media, storage } from 'ajo-cloves'

const ThemeToggle: Stateful = function* () {

  const system = media(this, { query: () => '(prefers-color-scheme: dark)' })
  const saved = storage(this, { key: 'theme', fallback: 'system' })

  while (true) {
    const dark = saved.value === 'dark' || (saved.value !== 'light' && system.matches)

    if (browser()) document.documentElement.dataset.theme = dark ? 'dark' : 'light'

    yield (
      <button
        type="button"
        aria-pressed={dark ? 'true' : 'false'}
        set:onclick={() => saved.set(dark ? 'light' : 'dark')}
      >
        Dark theme
      </button>
    )
  }
}

export default ThemeToggle

A keyboard shortcut

hotkey listens on the window for one chord: modifiers mod, ctrl, meta, alt and shift joined with + to one key. mod matches Ctrl or Meta, but not both at once. A match always calls preventDefault(), and active can switch the shortcut off.

src/notes/quick-note.tsx
import type { Stateful } from 'ajo'
import { hotkey } from 'ajo-cloves'

const QuickNote: Stateful = function* () {

  let input: HTMLInputElement | null = null

  hotkey(this, { keys: () => 'mod+k', onPress: () => input?.focus() })

  while (true) yield (
    <>
      <label for="quick-note">New note</label>
      <input id="quick-note" name="text" ref={el => input = el} />
    </>
  )
}

export default QuickNote

Full reference: ajo-kit packages/ajo-cloves/README.md