Tag

No tag yet

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/autocomplete.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { Autocomplete } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    /** What the `view` closure of the kit's `Autocomplete` receives. */
    export type AutocompleteParts = Component.Headless.Parts<typeof Autocomplete>
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const icon = <Msg>(h: Html.H<Msg>, path: string) =>
      h.el("svg")
        .attrs({
          viewBox: "0 0 24 24",
          fill: "none",
          stroke: "currentColor",
          "stroke-width": "2",
          "stroke-linecap": "round",
          "stroke-linejoin": "round",
          "aria-hidden": "true"
        })
        .children(h.el("path").attr("d", path))
    
    const iconButton =
      "grid size-6 shrink-0 place-items-center rounded-sm text-muted-foreground transition-colors duration-150 " +
      "hover:bg-accent hover:text-foreground data-[disabled]:pointer-events-none [&_svg]:size-3.5"
    
    const inputGroups = {
      default: "min-h-8.5 w-64 rounded-md border border-input bg-background pr-1 shadow-sm " +
        "transition-[border-color,box-shadow] duration-150 " +
        "focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/15",
      command: "h-10 w-full border-b pr-2"
    } as const
    
    /** The text above the input. */
    export const AutocompleteLabel = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.label(h.div.class(cn("mb-1.5 cursor-default text-[13px] leading-snug font-medium", options.class)))
    
    /**
     * The box around the input and its buttons, which the popup is placed against.
     * `variant: "command"` is the borderless row at the top of an `AutocompletePanel`.
     */
    export const AutocompleteInputGroup = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption & { readonly variant?: keyof typeof inputGroups | undefined } = {}
    ) =>
      autocomplete.inputGroup(
        h.div.class(cn(
          "flex items-center data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[readonly]:bg-muted",
          inputGroups[options.variant ?? "default"],
          options.class
        ))
      )
    
    /** A magnifier in front of the input. */
    export const AutocompleteSearchIcon = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.span.attrs({ "aria-hidden": "true", "data-slot": "autocomplete-search-icon" }).class(
        cn("ml-3 grid shrink-0 place-items-center text-muted-foreground [&_svg]:size-3.5", options.class)
      ).children(icon(h, "M21 21l-4.3-4.3M11 18a7 7 0 100-14 7 7 0 000 14z"))
    
    /** The text input. Chain `.attr("placeholder", ...)` and an `aria-label` when there is no label. */
    export const AutocompleteInput = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.input(
        h.input.class(cn(
          "h-8 min-w-0 flex-1 bg-transparent px-3 text-[13px] text-foreground outline-none",
          "placeholder:text-muted-foreground disabled:cursor-not-allowed [&::-webkit-search-cancel-button]:hidden",
          "[[data-slot=autocomplete-search-icon]+&]:pl-2",
          options.class
        ))
      )
    
    /** The button that clears the text. `undefined` while the input is empty. */
    export const AutocompleteClear = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.clear({ element: h.button.class(cn(iconButton, options.class)) })?.children(
        icon(h, "M18 6L6 18M6 6l12 12")
      )
    
    /** A chevron button that shows every suggestion. Give it an `aria-label`. */
    export const AutocompleteTrigger = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.trigger(h.button.class(cn(iconButton, options.class))).children(
        autocomplete.icon(h.span.class("grid place-items-center")).children(icon(h, "M6 9l6 6 6-6"))
      )
    
    /** The element the kit places, in the top layer. Put `AutocompletePopup` inside. */
    export const AutocompletePositioner = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption = {}
    ) => autocomplete.positioner(h.div.class(cn("outline-none", options.class)))
    
    /** The box under the input: as wide as the input group, at most 20rem tall. */
    export const AutocompletePopup = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.popup(
        h.div.class(cn(
          "box-border flex max-h-[min(var(--available-height),20rem)] w-[var(--anchor-width)] min-w-48 flex-col",
          "max-w-[var(--available-width)] overflow-hidden rounded-lg border bg-popover text-[13px] text-foreground",
          "shadow-float outline-none",
          "origin-[var(--transform-origin)] transition-[opacity,scale] duration-150",
          "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
          "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
          options.class
        ))
      )
    
    /** The scrolling list of suggestions. */
    export const AutocompleteList = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.list(
        h.div.class(
          cn("min-h-0 flex-1 scroll-py-1 overflow-y-auto p-1 text-[13px] outline-none data-[empty]:p-0", options.class)
        )
      )
    
    /** One suggestion. Picking it puts its label in the input. */
    export const AutocompleteItem = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption & { readonly value: string }
    ) =>
      autocomplete.item({
        element: h.div.class(cn(
          "flex min-h-7.5 cursor-default items-center justify-between gap-2 rounded-sm px-2 py-1 leading-snug",
          "select-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",
          "data-[disabled]:text-muted-foreground data-[disabled]:opacity-60",
          options.class
        )),
        value: options.value
      })
    
    /** A run of suggestions under an `AutocompleteGroupLabel`. `group` is the `group` of the items inside. */
    export const AutocompleteGroup = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption & { readonly group: string }
    ) => autocomplete.group({ element: h.div.key(options.group).class(cn(options.class)), group: options.group })
    
    export const AutocompleteGroupLabel = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption & { readonly group: string }
    ) =>
      autocomplete.groupLabel({
        element: h.div.class(cn("px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground", options.class)),
        group: options.group
      })
    
    export const AutocompleteSeparator = <Msg>(
      h: Html.H<Msg>,
      autocomplete: AutocompleteParts,
      options: ClassOption & { readonly key?: string | undefined } = {}
    ) => {
      const element = h.div.class(cn("-mx-1 my-1 h-px bg-border", options.class))
      return autocomplete.separator(options.key === undefined ? element : element.key(options.key))
    }
    
    /** The message shown while nothing matches. Its children are dropped while there are suggestions. */
    export const AutocompleteEmpty = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.empty(
        h.div.class(cn("px-3 py-5 text-center text-[13px] text-muted-foreground empty:hidden", options.class))
      )
    
    /** A live region above the list, for a message such as a result count. */
    export const AutocompleteStatus = <Msg>(h: Html.H<Msg>, autocomplete: AutocompleteParts, options: ClassOption = {}) =>
      autocomplete.status(h.div.class(cn("px-3 py-2.5 text-[13px] text-muted-foreground empty:hidden", options.class)))
    
    /** The card of an `inline` autocomplete: a command palette with the input on top and the list below. */
    export const AutocompletePanel = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.div.class(cn(
        "flex max-h-80 w-88 max-w-full flex-col overflow-hidden rounded-lg border bg-popover text-foreground shadow-sm",
        options.class
      ))
    
    /** A keyboard shortcut at the end of an item. */
    export const AutocompleteShortcut = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.kbd.class(cn("font-sans text-xs tracking-widest text-muted-foreground", options.class))
    
  3. Import it

    import { AutocompleteLabel, AutocompleteInputGroup, AutocompleteSearchIcon, AutocompleteInput, AutocompleteClear, AutocompleteTrigger, AutocompletePositioner, AutocompletePopup, AutocompleteList, AutocompleteItem, AutocompleteGroup, AutocompleteGroupLabel, AutocompleteSeparator, AutocompleteEmpty, AutocompleteStatus, AutocompletePanel, AutocompleteShortcut } from "#ui/autocomplete"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Autocomplete } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AutocompleteClear,
  AutocompleteEmpty,
  AutocompleteInput,
  AutocompleteInputGroup,
  AutocompleteItem,
  AutocompleteLabel,
  AutocompleteList,
  AutocompletePopup,
  AutocompletePositioner
} from "#ui/autocomplete"

const tags = [
  "accessibility", "animation", "components", "css", "design-systems", "effect", "forms", "headless",
  "performance", "schema", "server-rendering", "testing", "typescript"
].map((label) => ({ value: label, label }))

const AutocompleteBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenTags: {},
  RequestedCloseTags: {},
  UpdatedTag: { tag: Schema.String }
})

export const AutocompleteBasic = Html.component({
  name: "AutocompleteBasic",
  model: Schema.Struct({ open: Schema.Boolean, tag: Schema.String }),
  message: AutocompleteBasicMessage
}).make({
  init: () => ({ open: false, tag: "" }),
  update: {
    RequestedOpenTags: ($) => $.evolve({ open: true }),
    RequestedCloseTags: ($) => $.evolve({ open: false }),
    UpdatedTag: ($, { tag }) => $.evolve({ tag })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-start gap-3.5").children(
      Autocomplete(h, {
        props: { open: model.open, value: model.tag, items: tags, openOnInputClick: true, sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => AutocompleteBasicMessage.RequestedOpenTags(),
          RequestedClose: () => AutocompleteBasicMessage.RequestedCloseTags(),
          Updated: ({ value }) => AutocompleteBasicMessage.UpdatedTag({ tag: value }),
          Highlighted: () => undefined,
          Settled: () => undefined
        },
        view: (autocomplete) =>
          h.div.class("flex flex-col").children(
            AutocompleteLabel(h, autocomplete).children("Tag"),
            AutocompleteInputGroup(h, autocomplete).children(
              AutocompleteInput(h, autocomplete).attr("placeholder", "e.g. typescript"),
              AutocompleteClear(h, autocomplete)
            ),
            AutocompletePositioner(h, autocomplete).children(
              AutocompletePopup(h, autocomplete).children(
                AutocompleteEmpty(h, autocomplete).children("No suggestions. Keep your own tag."),
                AutocompleteList(h, autocomplete).children(
                  autocomplete.items.map(({ label, value }) =>
                    AutocompleteItem(h, autocomplete, { value }).children(label)
                  )
                )
              )
            )
          )
      }),
      // Unlike a combobox, nothing is selected: the text is the value, suggested or not.
      h.p.class("text-xs text-muted-foreground tabular-nums").children(model.tag === "" ? "No tag yet" : `Tag: ${model.tag}`)
    )
})

Examples

Inline completion

With mode "both" the highlighted suggestion completes the text in the input, the added part selected.

Country

Groups

autocomplete.groups splits the filtered items by their group.

The input is the form field. Picking a suggestion submits the form, and so does Enter on text with no match.

Command palette

With inline the list is drawn in place, always expanded, and the arrow keys move through it from the input.

Calendar
Search emoji
Calculator
Profile⌘P
Billing⌘B
Preferences⌘,

Pick a command

Anatomy

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

PartDescription
inputGroupA <div> around the input and its buttons. The popup is placed against it.
inputThe <input>, which is the combobox and the form field.
triggerA <button> that toggles the popup.
iconA <span> in the trigger.
clear({ element })A <button> that clears the text. undefined while the text is empty.
labelA <div> that names the input, the list and the popup.
positionerA <div> the autocomplete places, a manual popover in the top layer.
popupA <div> in the positioner: the box to style.
listA <div> around the items: the listbox.
item({ element, value })A <div> per drawn suggestion. Draw autocomplete.items, the filtered list.
group / groupLabel({ element, group })A <div> around the items of one of autocomplete.groups, and its label.
separatorA <div> between items.
emptyA <div> whose children show only while no item matches.
statusA <div> live region, for a message such as a count.

API reference

Props

PropTypeDescription
openbooleanWhether the popup shows. Required.
valuestringThe input's text. Required.
itemsReadonlyArray<{ value, label, disabled?, group? }>Every suggestion, in drawing order.
mode"list" | "both" | "inline" | "none"Whether the text filters the list, and whether the highlighted label shows in the input. Default "list".
filter"contains" | "startsWith" | "endsWith" | "none"How the text matches labels. Default "contains".
filteredItemsReadonlyArray<AutocompleteItem>The items to draw, from your own filter.
limitnumberThe most items drawn.
autoHighlightboolean | "always"Typing highlights the first match. "always" also does whenever the list shows.
keepHighlightbooleanThe highlight stays when the pointer leaves the list.
openOnInputClickbooleanA press on the input opens the popup. Default false.
submitOnItemClickbooleanPicking an item submits the autocomplete's form.
inlinebooleanThe list is drawn without a popup and is always expanded.
disabled / readOnly / required / name / formas on <input>Put on the input.
side / align / sideOffsetPositioningWhere the popup goes. side defaults to "bottom".

Events

EventDescription
RequestedOpen({ reason })Asks for open to be true.
RequestedClose({ reason })Asks for open to be false.
Updated({ value, reason })Asks for value to be the new text. A pick asks for the picked label, with reason "item-press".
Highlighted({ value, index, reason })The highlighted item changed.
Settled({ open })The popup's transitions ended.

Data attributes

AttributeDescription
data-popup-openOn the input, the input group, the trigger, the icon and the clear button while open.
data-list-emptyOn the input, the input group and the trigger while no item matches.
data-disabled / data-readonlyOn the input, the input group and the trigger.
data-open / data-closedOn the positioner and the popup.
data-starting-style / data-ending-styleOn the popup for the first frame after it opens, and while it closes.
data-side / data-alignOn the positioner and the popup: where it ended up.
data-emptyOn the positioner, the popup and the list while no item matches.
data-highlighted / data-disabledOn an item.
--anchor-width / --available-heightCSS variables on the positioner, for sizing the popup.
--transform-originCSS variable on the popup: the point it grows from.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

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