# Autocomplete

> A text field that suggests as you type and keeps what you write, from a list or looked up as the text changes.

Page: https://uicontext.com/docs/components/autocomplete

Group: Primitives.

## When to use

A text field that suggests as you type and keeps what you write, from a list or looked up as the text changes. Use [Combobox](https://uicontext.com/docs/components/combobox.md) instead when people must pick from the list, not type their own value.

## Usage

```ts
import { Autocomplete } from "./ui/uicontext/components/Autocomplete.ts"

const Message = UiSchema.TaggedEnum({ ChangedCity: { value: Schema.String } })

const cities = ["Lisbon", "London", "Los Angeles", "Lyon"].map((label) => ({ value: label, label }))

export const City = (h: Html.H<typeof Message.Type>, city: string) =>
	Autocomplete(h, { key: "city", props: { label: "City", value: city, suggestions: cities }, onEmit: { Changed: ({ value }) => Message.ChangedCity({ value }) } })
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### A job title

The example the page opens with: Autocomplete in “A job title”.

```ts title="src/demo.ts" source="www/src/examples/autocomplete/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Autocomplete } from "./ui/uicontext/components/Autocomplete.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const styles = stylex.create({ wrap: { inlineSize: "min(100%, 22rem)" } })

const titles = [
	"Product designer",
	"Product manager",
	"Product marketing manager",
	"Software engineer",
	"Senior software engineer",
	"Staff engineer",
	"Engineering manager",
	"Data analyst",
	"Data scientist",
	"Customer success manager",
	"Support engineer",
	"Account executive",
].map((label) => ({ value: label, label }))

const Message = UiSchema.TaggedEnum({ Changed: { value: Schema.String } })

// a profile's job title: suggestions from titles people use, but any title is fine
export const JobTitle = Html.component({
	name: "JobTitle",
	model: Schema.Struct({ title: Schema.String }),
	message: Message,
}).make({
	init: () => ({ title: "" }),
	update: { Changed: ($, { value }) => $.evolve({ title: value }) },
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			Autocomplete(h, {
				key: "title",
				props: { label: "Job title", value: model.title, suggestions: titles, placeholder: "e.g. Product designer", name: "title", autocomplete: "organization-title" },
				onEmit: { Changed: ({ value }) => Message.Changed({ value }) },
			}),
		),
})
```

### Looked up as you type

`remote` shows the suggestions the app gives, unfiltered; `loading` says it's looking. A newer query replaces an older one.

```ts title="src/address.ts" source="www/src/examples/autocomplete/address.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import { Autocomplete, AutocompleteSuggestion } from "./ui/uicontext/components/Autocomplete.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const styles = stylex.create({ wrap: { inlineSize: "min(100%, 26rem)" } })

const addresses = [
	["12 Rua das Flores", "Porto, 4050-262, Portugal"],
	["12 Rue de Rivoli", "75004 Paris, France"],
	["120 Regent Street", "London W1B 5RL, United Kingdom"],
	["1200 Market Street", "San Francisco, CA 94102, USA"],
	["128 Queen Street West", "Toronto, ON M5H 2N2, Canada"],
	["12 Rosenthaler Straße", "10119 Berlin, Germany"],
	["121 Collins Street", "Melbourne VIC 3000, Australia"],
	["1 Raffles Place", "Singapore 048616"],
] as const

const Message = UiSchema.TaggedEnum({ Changed: { value: Schema.String }, Found: { query: Schema.String, results: Schema.Array(AutocompleteSuggestion) } })

// stands in for an address API: answers after a moment, and a newer query replaces an older one
const Lookup = Command.make("Example.LookupAddress", { args: { query: Schema.String }, mode: "switch" }, ({ query }) =>
	Effect.sleep(450).pipe(
		Effect.as(
			Message.Found({
				query,
				results: addresses
					.filter(([street, place]) => `${street} ${place}`.toLowerCase().includes(query.trim().toLowerCase()))
					.map(([street, place]) => ({ value: street, label: street, description: place })),
			}),
		),
	),
)

// a checkout's street address: the app looks it up as you type
export const StreetAddress = Html.component({
	name: "StreetAddress",
	model: Schema.Struct({ value: Schema.String, results: Schema.Array(AutocompleteSuggestion), loading: Schema.Boolean }),
	message: Message,
}).make({
	init: () => ({ value: "", results: [], loading: false }),
	update: {
		Changed: ($, { value }) =>
			value.trim().length < 2 ? $.evolve({ value, results: [], loading: false }) : $.evolve({ value, loading: true }).run(Lookup.make({ query: value })),
		Found: ($, { query, results }) => (query === $.model.value ? $.evolve({ results, loading: false }) : $.model),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			Autocomplete(h, {
				key: "address",
				props: {
					label: "Street address",
					value: model.value,
					suggestions: model.results,
					remote: true,
					loading: model.loading,
					placeholder: "Start typing, e.g. 12 R",
					autocomplete: "street-address",
					empty: model.value.trim().length < 2 ? "Type two letters or more" : "No addresses match. You can still type it in full.",
				},
				onEmit: { Changed: ({ value }) => Message.Changed({ value }) },
			}),
		),
})
```

## API reference

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | Names the field; shown above it unless `hideLabel` |
| `hideLabel` | `boolean` | — |
| `value` (required) | `string` | — |
| `suggestions` (required) | `AutocompleteSuggestion[]` | — |
| `remote` | `boolean` | The app filters: the list shows `suggestions` as given, for a lookup as the text changes |
| `loading` | `boolean` | The app is still looking: "Looking…" shows in the list |
| `placeholder` | `string` | — |
| `name` | `string` | Submits the text under this name |
| `autocomplete` | `string` | The browser's own autofill hint: "address-level2" for a city |
| `empty` | `string` | What the list says when nothing matches; "No suggestions" by default |
| `disabled` | `boolean` | — |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `Changed` | `{ value: string }` | The text, typed or filled in by a suggestion |

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| A–Z | Type; the suggestions follow |
| Down arrow, Up arrow | Open the suggestions, and move through them |
| Enter | Fill in the highlighted suggestion |
| Escape | Close the suggestions; again, clear the text |

On a Mac, Control is Command and Alt is Option. Left and Right trade places in right-to-left text.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/autocomplete
```

With npm: `npx shadcn@latest add checkfu/uicontext/autocomplete`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/autocomplete`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/autocomplete`.

It writes these files:

- `src/ui/uicontext/components/Autocomplete.ts`
- `src/ui/uicontext/components/Motion.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/Autocomplete.ts](https://github.com/checkfu/uicontext/blob/main/src/Autocomplete.ts)

## Related

- [Button](https://uicontext.com/docs/components/button.md) (`button`): A button, and a link that looks like one, in every tone and three sizes.
- [Toggle](https://uicontext.com/docs/components/toggle.md) (`toggle`): A button that stays pressed, such as Bold or Pin.
- [Toggle Group](https://uicontext.com/docs/components/toggle-group.md) (`toggle-group`): Buttons that stay pressed and share one value, such as text styles.
- [Input](https://uicontext.com/docs/components/input.md) (`input`): Text inputs, selects and textareas in a labeled field with a hint and an error, and their styles for controls you lay out yourself.
- [Status](https://uicontext.com/docs/components/status.md) (`status`): Status badges and tags for runs and records.
- [Glyphs](https://uicontext.com/docs/components/glyphs.md) (`glyphs`): Small marks for status, priority, color and people.
