# Autocomplete

An input that suggests completions as you type, and keeps whatever text you enter.

- Page: https://www.effectcn.com/components/autocomplete
- Kind: Headless component with parts
- File: `src/ui/autocomplete.ts`
- Built on: `Autocomplete` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/autocomplete.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/autocomplete.ts`

```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))
```

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

## Usage

Suggestions filter as you type. Nothing is selected: the text is the value, suggested or not.

```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.

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

const countries = [
  "Australia", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Iceland",
  "Ireland", "Italy", "Japan", "Netherlands", "New Zealand", "Norway", "Portugal", "Spain", "Sweden",
  "Switzerland", "United Kingdom", "United States"
].map((label) => ({ value: label, label }))

const AutocompleteInlineMessage = UiSchema.TaggedEnum({
  RequestedOpenCountries: {},
  RequestedCloseCountries: {},
  UpdatedCountry: { country: Schema.String }
})

export const AutocompleteInline = Html.component({
  name: "AutocompleteInline",
  model: Schema.Struct({ open: Schema.Boolean, country: Schema.String }),
  message: AutocompleteInlineMessage
}).make({
  init: () => ({ open: false, country: "" }),
  update: {
    RequestedOpenCountries: ($) => $.evolve({ open: true }),
    RequestedCloseCountries: ($) => $.evolve({ open: false }),
    UpdatedCountry: ($, { country }) => $.evolve({ country })
  },
  view: (h, model) =>
    // `mode: "both"` filters the list and shows the highlighted label in the input, the completed part selected.
    Autocomplete(h, {
      props: {
        open: model.open,
        value: model.country,
        items: countries,
        mode: "both",
        filter: "startsWith",
        autoHighlight: true,
        sideOffset: 6
      },
      onEmit: {
        RequestedOpen: () => AutocompleteInlineMessage.RequestedOpenCountries(),
        RequestedClose: () => AutocompleteInlineMessage.RequestedCloseCountries(),
        Updated: ({ value }) => AutocompleteInlineMessage.UpdatedCountry({ country: value }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (autocomplete) =>
        h.div.class("flex flex-col").children(
          AutocompleteLabel(h, autocomplete).children("Country"),
          AutocompleteInputGroup(h, autocomplete).children(
            AutocompleteInput(h, autocomplete).attr("placeholder", "Type “n” and press ↓"),
            AutocompleteTrigger(h, autocomplete).attr("aria-label", "Show countries")
          ),
          AutocompletePositioner(h, autocomplete).children(
            AutocompletePopup(h, autocomplete).children(
              AutocompleteEmpty(h, autocomplete).children("No country starts with that."),
              AutocompleteList(h, autocomplete).children(
                autocomplete.items.map(({ label, value }) =>
                  AutocompleteItem(h, autocomplete, { value }).children(label)
                )
              )
            )
          )
        )
    })
})
```

### Groups

autocomplete.groups splits the filtered items by their group.

```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,
  AutocompleteGroup,
  AutocompleteGroupLabel,
  AutocompleteInput,
  AutocompleteInputGroup,
  AutocompleteItem,
  AutocompleteList,
  AutocompletePopup,
  AutocompletePositioner
} from "#ui/autocomplete"

const groupNames: Record<string, string> = {
  recent: "Recent searches",
  docs: "Documentation",
  api: "API reference"
}

const suggestions = [
  { value: "recent-1", label: "keep-alive children", group: "recent" },
  { value: "recent-2", label: "command modes", group: "recent" },
  { value: "docs-1", label: "Getting started", group: "docs" },
  { value: "docs-2", label: "Composing headless components", group: "docs" },
  { value: "docs-3", label: "Who owns the state", group: "docs" },
  { value: "docs-4", label: "Server rendering", group: "docs" },
  { value: "api-1", label: "Html.component", group: "api" },
  { value: "api-2", label: "Command.make", group: "api" },
  { value: "api-3", label: "Router.subscription", group: "api" },
  { value: "api-4", label: "UiSchema.TaggedEnum", group: "api" }
]

const AutocompleteGroupsMessage = UiSchema.TaggedEnum({
  RequestedOpenSuggestions: {},
  RequestedCloseSuggestions: {},
  UpdatedQuery: { query: Schema.String }
})

export const AutocompleteGroups = Html.component({
  name: "AutocompleteGroups",
  model: Schema.Struct({ open: Schema.Boolean, query: Schema.String }),
  message: AutocompleteGroupsMessage
}).make({
  init: () => ({ open: false, query: "" }),
  update: {
    RequestedOpenSuggestions: ($) => $.evolve({ open: true }),
    RequestedCloseSuggestions: ($) => $.evolve({ open: false }),
    UpdatedQuery: ($, { query }) => $.evolve({ query })
  },
  view: (h, model) =>
    Autocomplete(h, {
      props: { open: model.open, value: model.query, items: suggestions, openOnInputClick: true, sideOffset: 6 },
      onEmit: {
        RequestedOpen: () => AutocompleteGroupsMessage.RequestedOpenSuggestions(),
        RequestedClose: () => AutocompleteGroupsMessage.RequestedCloseSuggestions(),
        Updated: ({ value }) => AutocompleteGroupsMessage.UpdatedQuery({ query: value }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (autocomplete) =>
        h.div.children(
          AutocompleteInputGroup(h, autocomplete).children(
            AutocompleteInput(h, autocomplete).attrs({ placeholder: "Search the docs", "aria-label": "Search the docs" }),
            AutocompleteClear(h, autocomplete)
          ),
          AutocompletePositioner(h, autocomplete).children(
            AutocompletePopup(h, autocomplete).children(
              AutocompleteEmpty(h, autocomplete).children("No pages match."),
              AutocompleteList(h, autocomplete).children(
                autocomplete.groups.map(({ items, key = "" }) =>
                  AutocompleteGroup(h, autocomplete, { group: key }).children(
                      AutocompleteGroupLabel(h, autocomplete, { group: key }).children(groupNames[key] ?? key),
                      items.map(({ label, value }) =>
                        AutocompleteItem(h, autocomplete, { value }).children(label)
                      )
                    )
                )
              )
            )
          )
        )
    })
})
```

### Search form with an empty state

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

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

const products = [
  "Mechanical keyboard", "Mechanical pencil", "Monitor arm", "Monitor light bar", "Mouse pad", "Laptop stand",
  "Laptop sleeve", "USB-C hub", "USB-C cable", "Webcam", "Desk mat", "Desk lamp", "Noise-cancelling headphones"
].map((label) => ({ value: label, label }))

const AutocompleteSearchMessage = UiSchema.TaggedEnum({
  RequestedOpenSuggestions: {},
  RequestedCloseSuggestions: {},
  UpdatedQuery: { query: Schema.String },
  SubmittedSearch: { query: Schema.String }
})

export const AutocompleteSearch = Html.component({
  name: "AutocompleteSearch",
  model: Schema.Struct({ open: Schema.Boolean, query: Schema.String, searched: Schema.NullOr(Schema.String) }),
  message: AutocompleteSearchMessage
}).make({
  init: () => ({ open: false, query: "", searched: null }),
  update: {
    RequestedOpenSuggestions: ($) => $.evolve({ open: true }),
    RequestedCloseSuggestions: ($) => $.evolve({ open: false }),
    UpdatedQuery: ($, { query }) => $.evolve({ query }),
    SubmittedSearch: ($, { query }) => $.evolve({ searched: query, open: false })
  },
  view: (h, model) =>
    h.form
      .class("flex flex-col items-start gap-3.5")
      .attr("role", "search")
      .on("submit", ({ fields }) => AutocompleteSearchMessage.SubmittedSearch({ query: fields.q ?? "" }))
      .children(
        // The input is the form field. `submitOnItemClick` submits the form once a picked label is in it.
        Autocomplete(h, {
          props: {
            open: model.open,
            value: model.query,
            items: products,
            name: "q",
            limit: 6,
            submitOnItemClick: true,
            sideOffset: 6
          },
          onEmit: {
            RequestedOpen: () => AutocompleteSearchMessage.RequestedOpenSuggestions(),
            RequestedClose: () => AutocompleteSearchMessage.RequestedCloseSuggestions(),
            Updated: ({ value }) => AutocompleteSearchMessage.UpdatedQuery({ query: value }),
            Highlighted: () => undefined,
            Settled: () => undefined
          },
          view: (autocomplete) =>
            h.div.class("flex flex-wrap items-center gap-2.5").children(
              AutocompleteInputGroup(h, autocomplete).children(
                AutocompleteSearchIcon(h),
                AutocompleteInput(h, autocomplete).attrs({
                    type: "search",
                    placeholder: "Search products",
                    "aria-label": "Search products"
                  }),
                AutocompleteClear(h, autocomplete)
              ),
              Button(h, { props: { type: "submit" } }).children("Search"),
              AutocompletePositioner(h, autocomplete).children(
                AutocompletePopup(h, autocomplete).children(
                  AutocompleteEmpty(h, autocomplete).children(
                    `No suggestions. Press Enter to search for “${model.query}”.`
                  ),
                  AutocompleteList(h, autocomplete).children(
                    autocomplete.items.map(({ label, value }) =>
                      AutocompleteItem(h, autocomplete, { value }).children(label)
                    )
                  )
                )
              )
            )
        }),
        h.p.class("text-xs text-muted-foreground tabular-nums").children(
          model.searched === null ? "Nothing searched yet" : `Searched for “${model.searched}”`
        )
      )
})
```

### Command palette

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Autocomplete } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  AutocompleteEmpty,
  AutocompleteGroup,
  AutocompleteGroupLabel,
  AutocompleteInput,
  AutocompleteInputGroup,
  AutocompleteItem,
  AutocompleteList,
  AutocompletePanel,
  AutocompleteSearchIcon,
  AutocompleteSeparator,
  AutocompleteShortcut
} from "#ui/autocomplete"

const groupNames: Record<string, string> = {
  suggestions: "Suggestions",
  settings: "Settings"
}

const commands = [
  { value: "calendar", label: "Calendar", group: "suggestions", shortcut: "" },
  { value: "emoji", label: "Search emoji", group: "suggestions", shortcut: "" },
  { value: "calculator", label: "Calculator", group: "suggestions", shortcut: "" },
  { value: "profile", label: "Profile", group: "settings", shortcut: "⌘P" },
  { value: "billing", label: "Billing", group: "settings", shortcut: "⌘B" },
  { value: "preferences", label: "Preferences", group: "settings", shortcut: "⌘," }
]

const shortcuts = new Map(commands.map((command) => [command.value, command.shortcut]))

const AutocompleteCommandMessage = UiSchema.TaggedEnum({
  RequestedOpenCommands: {},
  RequestedCloseCommands: {},
  UpdatedQuery: { query: Schema.String },
  PickedCommand: { command: Schema.String }
})

export const AutocompleteCommand = Html.component({
  name: "AutocompleteCommand",
  model: Schema.Struct({ open: Schema.Boolean, query: Schema.String, ran: Schema.NullOr(Schema.String) }),
  message: AutocompleteCommandMessage
}).make({
  init: () => ({ open: false, query: "", ran: null }),
  update: {
    RequestedOpenCommands: ($) => $.evolve({ open: true }),
    RequestedCloseCommands: ($) => $.evolve({ open: false }),
    UpdatedQuery: ($, { query }) => $.evolve({ query }),
    PickedCommand: ($, { command }) => $.evolve({ ran: command, query: "" })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      // `inline` draws the list in place, always expanded, so no positioner or popup is needed.
      Autocomplete(h, {
        props: {
          open: model.open,
          value: model.query,
          items: commands.map(({ group, label, value }) => ({ value, label, group })),
          inline: true,
          autoHighlight: true,
          keepHighlight: true
        },
        onEmit: {
          RequestedOpen: () => AutocompleteCommandMessage.RequestedOpenCommands(),
          RequestedClose: () => AutocompleteCommandMessage.RequestedCloseCommands(),
          // A pick asks for the picked label as the text: run the command instead.
          Updated: ({ reason, value }) =>
            reason === "item-press"
              ? AutocompleteCommandMessage.PickedCommand({ command: value })
              : AutocompleteCommandMessage.UpdatedQuery({ query: value }),
          Highlighted: () => undefined,
          Settled: () => undefined
        },
        view: (autocomplete) =>
          AutocompletePanel(h).children(
            AutocompleteInputGroup(h, autocomplete, { variant: "command" }).children(
              AutocompleteSearchIcon(h),
              AutocompleteInput(h, autocomplete).attrs({
                  placeholder: "Type a command or search…",
                  "aria-label": "Command"
                })
            ),
            AutocompleteEmpty(h, autocomplete).children("No commands found."),
            AutocompleteList(h, autocomplete).children(
              autocomplete.groups.flatMap(({ items, key = "" }, index) => [
                index > 0 && AutocompleteSeparator(h, autocomplete, { key: `separator-${key}` }),
                AutocompleteGroup(h, autocomplete, { group: key }).children(
                    AutocompleteGroupLabel(h, autocomplete, { group: key }).children(groupNames[key] ?? key),
                    items.map(({ label, value }) =>
                      AutocompleteItem(h, autocomplete, { value }).children(
                        label,
                        AutocompleteShortcut(h).children(shortcuts.get(value))
                      )
                    )
                  )
              ])
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(model.ran === null ? "Pick a command" : `Ran “${model.ran}”`)
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `inputGroup` | A <div> around the input and its buttons. The popup is placed against it. |
| `input` | The <input>, which is the combobox and the form field. |
| `trigger` | A <button> that toggles the popup. |
| `icon` | A <span> in the trigger. |
| `clear({ element })` | A <button> that clears the text. undefined while the text is empty. |
| `label` | A <div> that names the input, the list and the popup. |
| `positioner` | A <div> the autocomplete places, a manual popover in the top layer. |
| `popup` | A <div> in the positioner: the box to style. |
| `list` | A <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. |
| `separator` | A <div> between items. |
| `empty` | A <div> whose children show only while no item matches. |
| `status` | A <div> live region, for a message such as a count. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the popup shows. Required. |
| `value` | `string` | The input's text. Required. |
| `items` | `ReadonlyArray<{ 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". |
| `filteredItems` | `ReadonlyArray<AutocompleteItem>` | The items to draw, from your own filter. |
| `limit` | `number` | The most items drawn. |
| `autoHighlight` | `boolean \| "always"` | Typing highlights the first match. "always" also does whenever the list shows. |
| `keepHighlight` | `boolean` | The highlight stays when the pointer leaves the list. |
| `openOnInputClick` | `boolean` | A press on the input opens the popup. Default false. |
| `submitOnItemClick` | `boolean` | Picking an item submits the autocomplete's form. |
| `inline` | `boolean` | The list is drawn without a popup and is always expanded. |
| `disabled / readOnly / required / name / form` | `as on <input>` | Put on the input. |
| `side / align / sideOffset` | `Positioning` | Where the popup goes. side defaults to "bottom". |

### Events

| Event | Description |
| --- | --- |
| `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

| Attribute | Description |
| --- | --- |
| `data-popup-open` | On the input, the input group, the trigger, the icon and the clear button while open. |
| `data-list-empty` | On the input, the input group and the trigger while no item matches. |
| `data-disabled / data-readonly` | On the input, the input group and the trigger. |
| `data-open / data-closed` | On the positioner and the popup. |
| `data-starting-style / data-ending-style` | On the popup for the first frame after it opens, and while it closes. |
| `data-side / data-align` | On the positioner and the popup: where it ended up. |
| `data-empty` | On the positioner, the popup and the list while no item matches. |
| `data-highlighted / data-disabled` | On an item. |
| `--anchor-width / --available-height` | CSS variables on the positioner, for sizing the popup. |
| `--transform-origin` | CSS variable on the popup: the point it grows from. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
