Combobox
An input that filters a list of options as you type, and picks one or more of them.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxClear,
ComboboxEmpty,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxTrigger
} from "#ui/combobox"
const frameworks = [
{ value: "next", label: "Next.js" },
{ value: "sveltekit", label: "SvelteKit" },
{ value: "nuxt", label: "Nuxt" },
{ value: "remix", label: "Remix" },
{ value: "astro", label: "Astro" },
{ value: "solidstart", label: "SolidStart" }
]
const ComboboxBasicMessage = UiSchema.TaggedEnum({
RequestedOpenFramework: {},
RequestedCloseFramework: {},
PickedFramework: { framework: Schema.NullOr(Schema.String) },
RequestedInputValueFramework: { text: Schema.String }
})
export const ComboboxBasic = Html.component({
name: "ComboboxBasic",
model: Schema.Struct({
open: Schema.Boolean,
framework: Schema.NullOr(Schema.String),
text: Schema.String
}),
message: ComboboxBasicMessage
}).make({
init: () => ({ open: false, framework: null, text: "" }),
update: {
RequestedOpenFramework: ($) => $.evolve({ open: true }),
RequestedCloseFramework: ($) => $.evolve({ open: false }),
PickedFramework: ($, { framework }) => $.evolve({ framework }),
RequestedInputValueFramework: ($, { text }) => $.evolve({ text })
},
view: (h, model) =>
Combobox(h, {
props: {
open: model.open,
value: model.framework,
inputValue: model.text,
items: frameworks,
autoHighlight: true,
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxBasicMessage.RequestedOpenFramework(),
RequestedClose: () => ComboboxBasicMessage.RequestedCloseFramework(),
Picked: ({ value }) =>
ComboboxBasicMessage.PickedFramework({ framework: typeof value === "string" ? value : null }),
RequestedInputValue: ({ inputValue }) =>
ComboboxBasicMessage.RequestedInputValueFramework({ text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.children(
ComboboxInputGroup(h, combobox).children(
ComboboxInput(h, combobox).attrs({ placeholder: "Select a framework", "aria-label": "Framework" }),
ComboboxClear(h, combobox),
ComboboxTrigger(h, combobox)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxEmpty(h, combobox).children("No framework found."),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
})
Installation
Set up the project
Once per project: the packages, Tailwind CSS, the theme tokens and the
cnhelper. Follow Installation.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/combobox.ts import type { Component } from "@effect/ui" import type { Html } from "@effect/ui/html" import type { Combobox } from "@effect/ui-kit" import { cn } from "#lib/cn" /** What the `view` closure of the kit's `Combobox` receives. */ export type ComboboxParts = Component.Headless.Parts<typeof Combobox> 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" /** The text above the input, or above the trigger with `inputInPopup`. */ export const ComboboxLabel = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.label(h.div.class(cn("mb-1.5 cursor-default text-[13px] leading-snug font-medium", options.class))) /** The bordered box around the input and its buttons. The popup is placed against it. */ export const ComboboxInputGroup = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.inputGroup( h.div.class(cn( "flex min-h-8.5 w-60 items-center 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", "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[readonly]:bg-muted", options.class )) ) /** The text input. Chain `.attr("placeholder", ...)` and an `aria-label` when there is no label. */ export const ComboboxInput = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.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", "group-data-[slot=combobox-chips]/chips:h-6 group-data-[slot=combobox-chips]/chips:min-w-16", "group-data-[slot=combobox-chips]/chips:px-1", options.class )) ) /** The button that clears the text and the value. `undefined` while there is nothing to clear. */ export const ComboboxClear = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.clear({ element: h.button.class(cn(iconButton, options.class)) })?.children( icon(h, "M18 6L6 18M6 6l12 12") ) /** The chevron button at the end of the input group. */ export const ComboboxTrigger = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.trigger(h.button.class(cn(iconButton, options.class))).children( combobox.icon(h.span.class("grid place-items-center")).children(icon(h, "M6 9l6 6 6-6")) ) /** With `inputInPopup`: the button that is the combobox. It shows the selected label and a chevron. */ export const ComboboxButton = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.trigger( h.button.class(cn( "inline-flex h-8.5 w-56 items-center justify-between gap-2 rounded-md border border-input bg-background", "pr-2 pl-3 text-start text-[13px] whitespace-nowrap text-foreground shadow-sm select-none", "transition-colors duration-150 hover:bg-accent data-[popup-open]:bg-accent", "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:size-3.5", options.class )) ).children( combobox.value(h.span.class("min-w-0 truncate data-[placeholder]:text-muted-foreground")), combobox.icon(h.span.class("grid shrink-0 place-items-center text-muted-foreground")).children( icon(h, "M7 15l5 5 5-5M7 9l5-5 5 5") ) ) /** With `multiple`: the row of chips, with the input as its last child. Goes inside the input group. */ export const ComboboxChips = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.chips( h.div.attr("data-slot", "combobox-chips").class( cn("group/chips flex min-w-0 flex-1 flex-wrap items-center gap-1 py-1 pl-1", options.class) ) ) /** One selected value. Put its label and a `ComboboxChipRemove` inside. */ export const ComboboxChip = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly value: string } ) => combobox.chip({ element: h.div.class(cn( "inline-flex h-6 cursor-default items-center gap-0.5 rounded-sm bg-secondary pr-0.5 pl-2 text-xs font-medium", "text-secondary-foreground outline-none select-none focus:bg-brand focus:text-brand-foreground", "data-[disabled]:opacity-60", options.class )), value: options.value }) export const ComboboxChipRemove = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly value: string; readonly label?: string | undefined } ) => combobox.chipRemove({ element: h.button .attr("aria-label", options.label) .class(cn( "grid size-5 place-items-center rounded-xs text-current opacity-60 transition-opacity duration-150", "hover:opacity-100 [&_svg]:size-3", options.class )), value: options.value }).children(icon(h, "M18 6L6 18M6 6l12 12")) /** The element the kit places, in the top layer. Put `ComboboxPopup` inside. */ export const ComboboxPositioner = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.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 ComboboxPopup = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.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 )) ) /** With `inputInPopup`: the search row at the top of the popup, holding the input. */ export const ComboboxSearchInput = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly placeholder?: string | undefined } = {} ) => h.div.class(cn("flex shrink-0 items-center border-b pl-3 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"), combobox.input( h.input .attrs({ placeholder: options.placeholder, "aria-label": options.placeholder }) .class( "h-9 min-w-0 flex-1 bg-transparent px-2 text-[13px] text-foreground outline-none " + "placeholder:text-muted-foreground" ) ) ) /** The scrolling list of options. */ export const ComboboxList = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.list( h.div.class(cn("min-h-0 flex-1 scroll-py-1 overflow-y-auto p-1 outline-none data-[empty]:p-0", options.class)) ) /** One option. Put its label and a `ComboboxItemIndicator` inside. */ export const ComboboxItem = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly value: string } ) => combobox.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-[selected]:font-medium data-[disabled]:text-muted-foreground data-[disabled]:opacity-60", options.class )), value: options.value }) /** The tick of a selected option. `undefined` for the others. */ export const ComboboxItemIndicator = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly value: string } ) => combobox.itemIndicator({ element: h.span.class(cn( "mr-1.5 mb-0.5 ml-2.5 h-[9px] w-[5px] shrink-0 rotate-45 border-r-[1.5px] border-b-[1.5px] border-brand", options.class )), value: options.value }) /** A run of options under a `ComboboxGroupLabel`. `group` is the `group` of the items inside. */ export const ComboboxGroup = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly group: string } ) => combobox.group({ element: h.div.key(options.group).class(cn(options.class)), group: options.group }) export const ComboboxGroupLabel = <Msg>( h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption & { readonly group: string } ) => combobox.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 ComboboxSeparator = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.separator(h.div.class(cn("-mx-1 my-1 h-px bg-border", options.class))) /** The message shown while no option matches. Its children are dropped while there are options. */ export const ComboboxEmpty = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.empty(h.div.class(cn("px-3 py-5 text-center text-muted-foreground empty:hidden", options.class))) /** A live region above the list, for a message such as "Searching…". */ export const ComboboxStatus = <Msg>(h: Html.H<Msg>, combobox: ComboboxParts, options: ClassOption = {}) => combobox.status(h.div.class(cn("px-3 py-2.5 text-muted-foreground empty:hidden", options.class))) /** A spinner for the input group while results load. */ export const ComboboxSpinner = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.span.attr("aria-hidden", "true").class(cn( "mx-1.5 size-3.5 shrink-0 animate-spin rounded-full border-2 border-muted-foreground border-r-transparent", options.class ))Import it
import { ComboboxLabel, ComboboxInputGroup, ComboboxInput, ComboboxClear, ComboboxTrigger, ComboboxButton, ComboboxChips, ComboboxChip, ComboboxChipRemove, ComboboxPositioner, ComboboxPopup, ComboboxSearchInput, ComboboxList, ComboboxItem, ComboboxItemIndicator, ComboboxGroup, ComboboxGroupLabel, ComboboxSeparator, ComboboxEmpty, ComboboxStatus, ComboboxSpinner } from "#ui/combobox"
Usage
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxClear,
ComboboxEmpty,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxTrigger
} from "#ui/combobox"
const frameworks = [
{ value: "next", label: "Next.js" },
{ value: "sveltekit", label: "SvelteKit" },
{ value: "nuxt", label: "Nuxt" },
{ value: "remix", label: "Remix" },
{ value: "astro", label: "Astro" },
{ value: "solidstart", label: "SolidStart" }
]
const ComboboxBasicMessage = UiSchema.TaggedEnum({
RequestedOpenFramework: {},
RequestedCloseFramework: {},
PickedFramework: { framework: Schema.NullOr(Schema.String) },
RequestedInputValueFramework: { text: Schema.String }
})
export const ComboboxBasic = Html.component({
name: "ComboboxBasic",
model: Schema.Struct({
open: Schema.Boolean,
framework: Schema.NullOr(Schema.String),
text: Schema.String
}),
message: ComboboxBasicMessage
}).make({
init: () => ({ open: false, framework: null, text: "" }),
update: {
RequestedOpenFramework: ($) => $.evolve({ open: true }),
RequestedCloseFramework: ($) => $.evolve({ open: false }),
PickedFramework: ($, { framework }) => $.evolve({ framework }),
RequestedInputValueFramework: ($, { text }) => $.evolve({ text })
},
view: (h, model) =>
Combobox(h, {
props: {
open: model.open,
value: model.framework,
inputValue: model.text,
items: frameworks,
autoHighlight: true,
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxBasicMessage.RequestedOpenFramework(),
RequestedClose: () => ComboboxBasicMessage.RequestedCloseFramework(),
Picked: ({ value }) =>
ComboboxBasicMessage.PickedFramework({ framework: typeof value === "string" ? value : null }),
RequestedInputValue: ({ inputValue }) =>
ComboboxBasicMessage.RequestedInputValueFramework({ text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.children(
ComboboxInputGroup(h, combobox).children(
ComboboxInput(h, combobox).attrs({ placeholder: "Select a framework", "aria-label": "Framework" }),
ComboboxClear(h, combobox),
ComboboxTrigger(h, combobox)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxEmpty(h, combobox).children("No framework found."),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
})
Examples
Multiple with chips
Each value is a chip in front of the input. Backspace removes the last one, and ArrowLeft moves onto the chips.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxChip,
ComboboxChipRemove,
ComboboxChips,
ComboboxEmpty,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxLabel,
ComboboxList,
ComboboxPopup,
ComboboxPositioner
} from "#ui/combobox"
const labels = [
{ value: "bug", label: "Bug" },
{ value: "feature", label: "Feature" },
{ value: "docs", label: "Documentation" },
{ value: "design", label: "Design" },
{ value: "performance", label: "Performance" },
{ value: "security", label: "Security" },
{ value: "good-first-issue", label: "Good first issue" }
]
const ComboboxMultipleMessage = UiSchema.TaggedEnum({
RequestedOpenLabels: {},
RequestedCloseLabels: {},
PickedLabels: { labels: Schema.Array(Schema.String) },
RequestedInputValueLabels: { text: Schema.String }
})
export const ComboboxMultiple = Html.component({
name: "ComboboxMultiple",
model: Schema.Struct({
open: Schema.Boolean,
labels: Schema.Array(Schema.String),
text: Schema.String
}),
message: ComboboxMultipleMessage
}).make({
init: () => ({ open: false, labels: ["bug", "design"], text: "" }),
update: {
RequestedOpenLabels: ($) => $.evolve({ open: true }),
RequestedCloseLabels: ($) => $.evolve({ open: false }),
PickedLabels: ($, { labels }) => $.evolve({ labels }),
RequestedInputValueLabels: ($, { text }) => $.evolve({ text })
},
view: (h, model) =>
Combobox(h, {
props: {
open: model.open,
value: model.labels,
inputValue: model.text,
items: labels,
multiple: true,
autoHighlight: true,
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxMultipleMessage.RequestedOpenLabels(),
RequestedClose: () => ComboboxMultipleMessage.RequestedCloseLabels(),
Picked: ({ value }) => ComboboxMultipleMessage.PickedLabels({ labels: Array.isArray(value) ? value : [] }),
RequestedInputValue: ({ inputValue }) => ComboboxMultipleMessage.RequestedInputValueLabels({ text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.class("flex flex-col").children(
ComboboxLabel(h, combobox).children("Labels"),
ComboboxInputGroup(h, combobox).children(
// Backspace in the empty input removes the last chip, and ArrowLeft moves onto the chips.
ComboboxChips(h, combobox).children(
combobox.selectedItems.map(({ label, value }) =>
ComboboxChip(h, combobox, { value }).children(
label,
ComboboxChipRemove(h, combobox, { value, label: `Remove ${label}` })
)
),
ComboboxInput(h, combobox).attr("placeholder", model.labels.length === 0 ? "Add labels" : undefined)
)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxEmpty(h, combobox).children("No labels found."),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
})
Groups
combobox.groups splits the filtered items by their group and drops the empty ones.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxClear,
ComboboxEmpty,
ComboboxGroup,
ComboboxGroupLabel,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxTrigger
} from "#ui/combobox"
const groupNames: Record<string, string> = {
fruit: "Fruit",
vegetables: "Vegetables",
herbs: "Herbs"
}
const produce = [
{ value: "apple", label: "Apple", group: "fruit" },
{ value: "apricot", label: "Apricot", group: "fruit" },
{ value: "blueberry", label: "Blueberry", group: "fruit" },
{ value: "pear", label: "Pear", group: "fruit" },
{ value: "asparagus", label: "Asparagus", group: "vegetables" },
{ value: "beetroot", label: "Beetroot", group: "vegetables" },
{ value: "carrot", label: "Carrot", group: "vegetables" },
{ value: "parsnip", label: "Parsnip", group: "vegetables" },
{ value: "basil", label: "Basil", group: "herbs" },
{ value: "coriander", label: "Coriander", group: "herbs" },
{ value: "parsley", label: "Parsley", group: "herbs" }
]
const ComboboxGroupsMessage = UiSchema.TaggedEnum({
RequestedOpenProduce: {},
RequestedCloseProduce: {},
PickedProduce: { produce: Schema.NullOr(Schema.String) },
RequestedInputValueProduce: { text: Schema.String }
})
export const ComboboxGroups = Html.component({
name: "ComboboxGroups",
model: Schema.Struct({
open: Schema.Boolean,
produce: Schema.NullOr(Schema.String),
text: Schema.String
}),
message: ComboboxGroupsMessage
}).make({
init: () => ({ open: false, produce: null, text: "" }),
update: {
RequestedOpenProduce: ($) => $.evolve({ open: true }),
RequestedCloseProduce: ($) => $.evolve({ open: false }),
PickedProduce: ($, { produce }) => $.evolve({ produce }),
RequestedInputValueProduce: ($, { text }) => $.evolve({ text })
},
view: (h, model) =>
Combobox(h, {
props: {
open: model.open,
value: model.produce,
inputValue: model.text,
items: produce,
autoHighlight: true,
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxGroupsMessage.RequestedOpenProduce(),
RequestedClose: () => ComboboxGroupsMessage.RequestedCloseProduce(),
Picked: ({ value }) => ComboboxGroupsMessage.PickedProduce({ produce: typeof value === "string" ? value : null }),
RequestedInputValue: ({ inputValue }) => ComboboxGroupsMessage.RequestedInputValueProduce({ text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.children(
ComboboxInputGroup(h, combobox).children(
ComboboxInput(h, combobox).attrs({ placeholder: "Search produce", "aria-label": "Produce" }),
ComboboxClear(h, combobox),
ComboboxTrigger(h, combobox)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxEmpty(h, combobox).children("Nothing in season matches."),
ComboboxList(h, combobox).children(
// `groups` is the filtered list split by each item's `group`; empty groups are dropped.
combobox.groups.map(({ items, key = "" }) =>
ComboboxGroup(h, combobox, { group: key }).children(
ComboboxGroupLabel(h, combobox, { group: key }).children(groupNames[key] ?? key),
items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
)
)
})
})
Input inside the popup
With inputInPopup a button shows the value, and the search input opens with the list.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxButton,
ComboboxEmpty,
ComboboxItem,
ComboboxItemIndicator,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxSearchInput
} from "#ui/combobox"
const assignees = [
{ value: "ada", label: "Ada Lovelace" },
{ value: "alan", label: "Alan Turing" },
{ value: "barbara", label: "Barbara Liskov" },
{ value: "edsger", label: "Edsger Dijkstra" },
{ value: "grace", label: "Grace Hopper" },
{ value: "ken", label: "Ken Thompson" },
{ value: "margaret", label: "Margaret Hamilton" }
]
const ComboboxPopupInputMessage = UiSchema.TaggedEnum({
RequestedOpenAssignee: {},
RequestedCloseAssignee: {},
PickedAssignee: { assignee: Schema.NullOr(Schema.String) },
RequestedInputValueAssignee: { text: Schema.String }
})
export const ComboboxPopupInput = Html.component({
name: "ComboboxPopupInput",
model: Schema.Struct({
open: Schema.Boolean,
assignee: Schema.NullOr(Schema.String),
text: Schema.String
}),
message: ComboboxPopupInputMessage
}).make({
init: () => ({ open: false, assignee: null, text: "" }),
update: {
RequestedOpenAssignee: ($) => $.evolve({ open: true }),
RequestedCloseAssignee: ($) => $.evolve({ open: false }),
PickedAssignee: ($, { assignee }) => $.evolve({ assignee }),
RequestedInputValueAssignee: ($, { text }) => $.evolve({ text })
},
view: (h, model) =>
// With `inputInPopup` the trigger is the combobox, the popup is a dialog, and opening focuses the input inside.
Combobox(h, {
props: {
open: model.open,
value: model.assignee,
inputValue: model.text,
items: assignees,
inputInPopup: true,
placeholder: "Assign to…",
autoHighlight: true,
align: "start",
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxPopupInputMessage.RequestedOpenAssignee(),
RequestedClose: () => ComboboxPopupInputMessage.RequestedCloseAssignee(),
Picked: ({ value }) =>
ComboboxPopupInputMessage.PickedAssignee({ assignee: typeof value === "string" ? value : null }),
RequestedInputValue: ({ inputValue }) =>
ComboboxPopupInputMessage.RequestedInputValueAssignee({ text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.children(
ComboboxButton(h, combobox).attr("aria-label", "Assignee"),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxSearchInput(h, combobox, { placeholder: "Search people" }),
ComboboxEmpty(h, combobox).children("No one found."),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
})
Async results
With filter "none" the consumer supplies the items: here a Command answers after a delay, and the status part reports progress.
import { Command, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Effect, Schema } from "effect"
import {
ComboboxClear,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxLabel,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxSpinner,
ComboboxStatus
} from "#ui/combobox"
const cities = [
"Amsterdam", "Athens", "Barcelona", "Berlin", "Bergen", "Brussels", "Budapest", "Copenhagen", "Dublin",
"Edinburgh", "Geneva", "Hamburg", "Helsinki", "Lisbon", "London", "Lyon", "Madrid", "Milan", "Munich",
"Oslo", "Paris", "Porto", "Prague", "Reykjavik", "Rome", "Stockholm", "Tallinn", "Vienna", "Warsaw", "Zurich"
].map((label) => ({ value: label.toLowerCase(), label }))
const City = Schema.Struct({ value: Schema.String, label: Schema.String })
const ComboboxAsyncMessage = UiSchema.TaggedEnum({
RequestedOpenCity: {},
RequestedCloseCity: {},
PickedCity: { city: Schema.NullOr(City) },
RequestedInputValueCity: { text: Schema.String, typed: Schema.Boolean },
CompletedSearchCities: { results: Schema.Array(City) }
})
// Stands in for a request to a server. `switch` drops the answer to an older query.
const SearchCities = Command.make(
"SearchCities",
{ args: { query: Schema.String }, mode: "switch" },
({ query }) =>
Effect.sleep("450 millis").pipe(
Effect.as(
ComboboxAsyncMessage.CompletedSearchCities({
results: cities.filter((city) => city.label.toLowerCase().includes(query.toLowerCase())).slice(0, 8)
})
)
)
)
export const ComboboxAsync = Html.component({
name: "ComboboxAsync",
model: Schema.Struct({
open: Schema.Boolean,
city: Schema.NullOr(City),
text: Schema.String,
results: Schema.Array(City),
searching: Schema.Boolean
}),
message: ComboboxAsyncMessage
}).make({
init: () => ({ open: false, city: null, text: "", results: [], searching: false }),
update: {
RequestedOpenCity: ($) => $.evolve({ open: true }),
RequestedCloseCity: ($) => $.evolve({ open: false }),
PickedCity: ($, { city }) => $.evolve({ city }),
RequestedInputValueCity: ($, { text, typed }) =>
!typed
? $.evolve({ text, results: (results) => $.model.city?.label === text ? [$.model.city] : results })
: text.trim() === ""
? $.evolve({ text, results: [], searching: false })
: $.evolve({ text, searching: true }).run(SearchCities.make({ query: text.trim() })),
CompletedSearchCities: ($, { results }) => $.model.searching ? $.evolve({ results, searching: false }) : $.model
},
view: (h, model) => {
// The selected city stays in `items` so its label is known after the results change.
const items = model.city === null || model.results.some((item) => item.value === model.city?.value)
? model.results
: [...model.results, model.city]
return Combobox(h, {
props: {
open: model.open,
value: model.city?.value ?? null,
inputValue: model.text,
items,
filteredItems: model.results,
filter: "none",
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxAsyncMessage.RequestedOpenCity(),
RequestedClose: () => ComboboxAsyncMessage.RequestedCloseCity(),
Picked: ({ value }) =>
ComboboxAsyncMessage.PickedCity({ city: items.find((item) => item.value === value) ?? null }),
RequestedInputValue: ({ inputValue, reason }) =>
ComboboxAsyncMessage.RequestedInputValueCity({ text: inputValue, typed: reason === "input-change" }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.class("flex flex-col").children(
ComboboxLabel(h, combobox).children("Destination"),
ComboboxInputGroup(h, combobox).children(
ComboboxInput(h, combobox).attr("placeholder", "Type to search cities"),
model.searching && ComboboxSpinner(h),
ComboboxClear(h, combobox)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxStatus(h, combobox).children(
model.searching
? "Searching…"
: model.text.trim() === ""
? "Start typing to search 30 cities."
: model.results.length === 0
? `No city matches “${model.text.trim()}”.`
: undefined
),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
}
})
Disabled and read-only
A disabled option can be highlighted but not picked. A read-only combobox opens and can be browsed, not changed.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Combobox } from "@effect/ui-kit"
import { Schema } from "effect"
import {
ComboboxEmpty,
ComboboxInput,
ComboboxInputGroup,
ComboboxItem,
ComboboxItemIndicator,
ComboboxLabel,
ComboboxList,
ComboboxPopup,
ComboboxPositioner,
ComboboxTrigger
} from "#ui/combobox"
const plans = [
{ value: "hobby", label: "Hobby" },
{ value: "pro", label: "Pro" },
{ value: "team", label: "Team" },
{ value: "enterprise", label: "Enterprise (contact sales)", disabled: true }
]
const fields = [
{ key: "options", label: "Disabled option", disabled: false, readOnly: false },
{ key: "disabled", label: "Disabled", disabled: true, readOnly: false },
{ key: "read-only", label: "Read-only", disabled: false, readOnly: true }
]
const ComboboxDisabledMessage = UiSchema.TaggedEnum({
RequestedOpenPlan: { key: Schema.String },
RequestedClosePlan: { key: Schema.String },
PickedPlan: { plan: Schema.NullOr(Schema.String) },
RequestedInputValuePlan: { key: Schema.String, text: Schema.String }
})
export const ComboboxDisabled = Html.component({
name: "ComboboxDisabled",
model: Schema.Struct({
open: Schema.NullOr(Schema.String),
plan: Schema.NullOr(Schema.String),
texts: Schema.Record(Schema.String, Schema.String)
}),
message: ComboboxDisabledMessage
}).make({
init: () => ({ open: null, plan: "pro", texts: { options: "Pro", disabled: "Pro", "read-only": "Pro" } }),
update: {
RequestedOpenPlan: ($, { key }) => $.evolve({ open: key }),
RequestedClosePlan: ($, { key }) => $.model.open === key ? $.evolve({ open: null }) : $.model,
PickedPlan: ($, { plan }) => {
const text = plans.find((item) => item.value === plan)?.label ?? ""
return $.evolve({ plan, texts: Object.fromEntries(fields.map(({ key }) => [key, text])) })
},
RequestedInputValuePlan: ($, { key, text }) => $.evolve({ texts: (texts) => ({ ...texts, [key]: text }) })
},
view: (h, model) =>
h.div.class("flex flex-wrap items-center gap-2.5").children(
fields.map(({ disabled, key, label, readOnly }) =>
Combobox(h, {
key,
props: {
open: model.open === key,
value: model.plan,
inputValue: model.texts[key] ?? "",
items: plans,
disabled,
readOnly,
sideOffset: 6
},
onEmit: {
RequestedOpen: () => ComboboxDisabledMessage.RequestedOpenPlan({ key }),
RequestedClose: () => ComboboxDisabledMessage.RequestedClosePlan({ key }),
Picked: ({ value }) => ComboboxDisabledMessage.PickedPlan({ plan: typeof value === "string" ? value : null }),
RequestedInputValue: ({ inputValue }) =>
ComboboxDisabledMessage.RequestedInputValuePlan({ key, text: inputValue }),
Highlighted: () => undefined,
Settled: () => undefined
},
view: (combobox) =>
h.div.class("flex flex-col").children(
ComboboxLabel(h, combobox).children(label),
ComboboxInputGroup(h, combobox, { class: "w-44" }).children(
ComboboxInput(h, combobox).attr("placeholder", "Select a plan"),
ComboboxTrigger(h, combobox)
),
ComboboxPositioner(h, combobox).children(
ComboboxPopup(h, combobox).children(
ComboboxEmpty(h, combobox).children("No plan found."),
ComboboxList(h, combobox).children(
combobox.items.map(({ label, value }) =>
ComboboxItem(h, combobox, { value }).children(
label,
ComboboxItemIndicator(h, combobox, { value })
)
)
)
)
)
)
})
)
)
})
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. Focus stays here while the list is used. |
trigger | A <button> that toggles the popup. With inputInPopup it is the combobox. |
icon | A <span> in the trigger. |
clear({ element }) | A <button> that clears the text and the value. undefined while there is nothing to clear. |
chips | A <div> around the chips and the input, with multiple. |
chip({ element, value }) | A <div> per selected value. Draw combobox.selectedItems. |
chipRemove({ element, value }) | A <button> in a chip that removes its value. |
label | A <div> that names the input, the list and the popup. |
value | A <span> in the trigger with the selected label, with inputInPopup. |
positioner | A <div> the combobox 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 option. Draw combobox.items, the filtered list. |
itemIndicator({ element, value }) | A <span> in an item, undefined unless it is selected. |
group / groupLabel({ element, group }) | A <div> around the items of one of combobox.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 or "Searching". |
API reference
Props
| Prop | Type | Description |
|---|---|---|
open | boolean | Whether the popup shows. Required. |
inputValue | string | The input's text. Required. |
items | ReadonlyArray<{ value, label, disabled?, group? }> | Every option, in drawing order. |
value | string | ReadonlyArray<string> | null | The selected value, or the values with multiple. |
multiple | boolean | More than one option can be selected. Default false. |
filter | "contains" | "startsWith" | "endsWith" | "none" | How the text matches labels. Default "contains". |
filteredItems | ReadonlyArray<ComboboxItem> | The items to draw, from your own filter. |
limit | number | The most items drawn. |
autoHighlight | boolean | Typing highlights the first match, so Enter picks it. Default false. |
inputInPopup | boolean | The input is drawn inside the popup and the trigger is the combobox. |
inline | boolean | The list is drawn without a popup and is always expanded. |
openOnInputClick | boolean | A press on the input opens the popup. Default true. |
disabled / readOnly / required | boolean | As on a native <input>. |
name / form | string | Adds a hidden input, so a form submits the value. |
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. |
Picked({ value, reason }) | Asks for value to be the whole new selection. |
RequestedInputValue({ inputValue, reason }) | Asks for inputValue: what was typed, the picked label, or the selected label put back on close. |
Highlighted({ value, index, reason }) | The highlighted item changed. For a virtualized list to scroll to it. |
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-placeholder | On the trigger and the value while nothing is selected. |
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-selected / 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. |