Combobox
Autocomplete input with a list of suggestions.
Usage
Basic
ComboboxInput is the trigger: typing filters the list, the arrow keys move through it and Enter picks. Each item carries a native radio named after the root's name:, so the form submits the selection.
div(class: "w-64") do
Combobox(name: "framework") do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
With groups
ComboboxGroup and ComboboxLabel name a set of items; ComboboxSeparator divides them. Groups with no match hide while searching.
div(class: "w-64") do
Combobox(name: "food") do
ComboboxInput(placeholder: "Select a food")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxGroup do
ComboboxLabel { "Fruits" }
ComboboxItem(value: "apple") { "Apple" }
ComboboxItem(value: "banana") { "Banana" }
end
ComboboxSeparator()
ComboboxGroup do
ComboboxLabel { "Vegetables" }
ComboboxItem(value: "broccoli") { "Broccoli" }
ComboboxItem(value: "carrot") { "Carrot" }
end
end
end
end
end
Disabled items
div(class: "w-64") do
Combobox(name: "framework_disabled_items") do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit", disabled: true) { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix", disabled: true) { "Remix" }
end
end
end
end
Disabled
div(class: "w-64") do
Combobox(name: "framework_disabled", disabled: true) do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
end
end
end
end
Invalid
div(class: "w-64") do
Combobox(name: "framework_invalid") do
ComboboxInput(placeholder: "Select a framework", aria: {invalid: "true"})
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "remix") { "Remix" }
end
end
end
end
Side
side: (top, right, bottom, left) and align: (start, center, end) place the popup; side_offset: and align_offset: set the gap.
div(class: "w-64") do
Combobox(name: "framework_side") do
ComboboxInput(placeholder: "Opens above")
ComboboxContent(side: :top) do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
In a popup
ComboboxTrigger is a button that shows the value (ComboboxValue); the search input lives inside the popup (show_trigger: false).
div(class: "w-64") do
Combobox(name: "country") do
ComboboxTrigger { ComboboxValue(placeholder: "Select a country") }
ComboboxContent do
ComboboxInput(placeholder: "Search", show_trigger: false)
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "br", selected: true) { "Brazil" }
ComboboxItem(value: "ar") { "Argentina" }
ComboboxItem(value: "cl") { "Chile" }
ComboboxItem(value: "pt") { "Portugal" }
ComboboxItem(value: "us") { "United States" }
end
end
end
end
Multiple
multiple: true picks several items, shown as chips. Backspace on the empty input removes the last one.
div(class: "w-80") do
Combobox(name: "frameworks[]", multiple: true) do
ComboboxChips do
ComboboxChipsInput(placeholder: "Add framework")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next", selected: true) { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
Select all
RubyUI extras: ComboboxToggleAll is an option that selects every enabled item, or clears them when all are selected; it hides while searching and also works in a popup (next example). ComboboxChips(max: 3) keeps the box small: past three items the chips collapse into one "5 frameworks" chip (term: from the root), whose remove button, like Backspace, clears the selection.
div(class: "w-80") do
Combobox(name: "frameworks_all[]", multiple: true, term: "frameworks") do
ComboboxChips(max: 3) do
ComboboxChipsInput(placeholder: "Add framework")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxToggleAll { "Select all" }
ComboboxSeparator()
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
Multiple in a popup
The same in a popup. term: shows "2 fruits" in the trigger instead of the list of names (RubyUI extra).
div(class: "w-64") do
Combobox(name: "fruits[]", multiple: true, term: "fruits") do
ComboboxTrigger { ComboboxValue(placeholder: "Pick fruits") }
ComboboxContent do
ComboboxInput(placeholder: "Search", show_trigger: false)
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxToggleAll { "Select all" }
ComboboxSeparator()
ComboboxItem(value: "apple") { "Apple" }
ComboboxItem(value: "banana") { "Banana" }
ComboboxItem(value: "blueberry") { "Blueberry" }
ComboboxItem(value: "grapes") { "Grapes" }
end
end
end
end
Form
required: makes the browser validate the selection: one radio for a single combobox, at least one checkbox for multiple: true. FormField shows the message and marks the visible input invalid.
form(class: "flex w-80 flex-col gap-4") do
FormField do
FormFieldLabel(for: "framework-form-input") { "Framework" }
Combobox(name: "framework_form", required: true) do
ComboboxInput(id: "framework-form-input", placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next", input: {data: {value_missing: "Pick a framework"}}) { "Next.js" }
ComboboxItem(value: "remix", input: {data: {value_missing: "Pick a framework"}}) { "Remix" }
ComboboxItem(value: "astro", input: {data: {value_missing: "Pick a framework"}}) { "Astro" }
end
end
end
FormFieldError()
end
FormField do
FormFieldLabel(for: "stack-form-input") { "Stack" }
Combobox(name: "stack_form[]", multiple: true, required: true) do
ComboboxChips do
ComboboxChipsInput(id: "stack-form-input", placeholder: "Add a tool")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "rails", input: {data: {value_missing: "Pick at least one"}}) { "Rails" }
ComboboxItem(value: "hotwire", input: {data: {value_missing: "Pick at least one"}}) { "Hotwire" }
ComboboxItem(value: "phlex", input: {data: {value_missing: "Pick at least one"}}) { "Phlex" }
end
end
end
FormFieldError()
end
Button(type: "submit") { "Submit" }
end
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component Combobox
Manual installation
1
Add RubyUI::Combobox to app/components/ruby_ui/combobox/combobox.rb
# frozen_string_literal: true
require "securerandom"
module RubyUI
# Root of a combobox. Like Base UI's Combobox.Root it has no look of its own:
# it holds the Stimulus controller and shares name/multiple with the parts
# through the Phlex context, so each ComboboxItem renders the native
# radio/checkbox that carries its value in the form.
class Combobox < Base
def initialize(name: nil, multiple: false, term: nil, disabled: false, required: false, id: nil, **)
# Unnamed radios are separate groups, so a required one could never pass.
raise ArgumentError, "name: is required when required: is true" if required && name.to_s.empty?
@name = name
@multiple = multiple
@term = term
@disabled = disabled
@required = required
@id = id || "combobox-#{SecureRandom.hex(4)}"
super(**)
end
def view_template(&)
previous = context[:ruby_ui_combobox]
context[:ruby_ui_combobox] = {
id: @id, name: @name, multiple: @multiple, disabled: @disabled, required: @required,
content_id: "#{@id}-content", list_id: "#{@id}-list"
}
div(**attrs, &)
ensure
context[:ruby_ui_combobox] = previous
end
private
def default_attrs
{
id: @id,
data: {
slot: "combobox",
# A required multiple: combobox needs "at least one checked", which
# checkboxes don't do natively: CheckboxGroup's controller adds it.
controller: (@multiple && @required) ? "ruby-ui--combobox ruby-ui--checkbox-group" : "ruby-ui--combobox",
required: ((@multiple && @required) ? "" : nil),
ruby_ui__combobox_multiple_value: @multiple.to_s,
ruby_ui__combobox_term_value: @term,
disabled: (@disabled ? "true" : nil),
action: "turbo:morph@window->ruby-ui--combobox#refresh"
}
}
end
end
end
2
Add RubyUI::ComboboxChip to app/components/ruby_ui/combobox/combobox_chip.rb
# frozen_string_literal: true
module RubyUI
# One selected item inside ComboboxChips. Rendered by the controller from
# ComboboxChips' template; its text goes in the [data-text] span.
class ComboboxChip < Base
def initialize(show_remove: true, **)
@show_remove = show_remove
super(**)
end
def view_template(&)
div(**attrs) do
span(data: {text: ""}, &)
remove_button if @show_remove
end
end
private
def remove_button
render Button.new(
variant: :ghost, size: :xs, icon: true,
class: "-ml-1 opacity-50 hover:opacity-100",
aria: {label: "Remove"},
data: {slot!: "combobox-chip-remove", action: "click->ruby-ui--combobox#removeChip"}
) do
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true",
class: "pointer-events-none"
) do |s|
s.path(d: "M18 6 6 18")
s.path(d: "m6 6 12 12")
end
end
end
def default_attrs
{
data: {slot: "combobox-chip"},
class: [
"flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5",
"text-xs font-medium whitespace-nowrap text-foreground has-data-[slot=combobox-chip-remove]:pr-0",
"has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50"
]
}
end
end
end
3
Add RubyUI::ComboboxChips to app/components/ruby_ui/combobox/combobox_chips.rb
# frozen_string_literal: true
module RubyUI
# The trigger of a multiple: combobox: one chip per selected item, then a
# ComboboxChipsInput. The controller builds the chips from the checked items
# with the template below; the popup is anchored to this box.
#
# max: (RubyUI extra) caps the chips: past it they collapse into a single
# "<count> <term>" chip (term: from the root, "selected" without one) whose
# remove button, like Backspace, clears the whole selection.
class ComboboxChips < Base
def initialize(show_remove: true, max: nil, **)
@show_remove = show_remove
@max = max
super(**)
end
def view_template(&)
div(**attrs) do
template(data: {ruby_ui__combobox_target: "chipTemplate"}) do
render ComboboxChip.new(show_remove: @show_remove)
end
yield if block_given?
end
end
private
def default_attrs
{
data: {
slot: "combobox-chips",
ruby_ui__combobox_target: "chips",
max: @max,
action: "click->ruby-ui--combobox#focusInput"
},
class: [
"flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent bg-clip-padding",
"px-2.5 py-1.5 text-sm shadow-xs transition-[color,box-shadow] dark:bg-input/30 cursor-text",
"focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",
"has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20",
"dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",
"has-data-[slot=combobox-chip]:px-1.5"
]
}
end
end
end
4
Add RubyUI::ComboboxChipsInput to app/components/ruby_ui/combobox/combobox_chips_input.rb
# frozen_string_literal: true
module RubyUI
# The text input after the chips. Backspace on an empty input removes the
# last chip.
class ComboboxChipsInput < Base
include ComboboxContext
def initialize(placeholder: nil, disabled: false, **)
@placeholder = placeholder
@disabled = disabled
super(**)
end
def view_template
input(**with_combobox_defaults(disabled: @disabled || !!combobox[:disabled], aria: {controls: combobox[:list_id], required: (combobox[:required] ? "true" : nil)}))
end
private
def default_attrs
{
type: "text",
role: "combobox",
placeholder: @placeholder,
autocomplete: "off",
autocorrect: "off",
spellcheck: "false",
autocapitalize: "none",
aria: {autocomplete: "list", expanded: "false", haspopup: "listbox"},
class: "min-w-16 flex-1 border-0 bg-transparent p-0 text-sm outline-none ring-0 focus:ring-0 placeholder:text-muted-foreground disabled:cursor-not-allowed",
data: {
slot: "combobox-chip-input",
ruby_ui__combobox_target: "input",
action: "input->ruby-ui--combobox#filter keydown->ruby-ui--combobox#inputKeydown " \
"click->ruby-ui--combobox#inputClick"
}
}
end
end
end
5
Add RubyUI::ComboboxContent to app/components/ruby_ui/combobox/combobox_content.rb
# frozen_string_literal: true
module RubyUI
# The popup. A native popover (top layer), positioned next to the trigger,
# the input or the chips by Floating UI; side:/align: pick the placement,
# side_offset:/align_offset: the gap, as in shadcn's ComboboxContent.
class ComboboxContent < Base
include ComboboxContext
SIDES = %i[top right bottom left].freeze
ALIGNS = %i[start center end].freeze
def initialize(side: :bottom, side_offset: 6, align: :start, align_offset: 0, **)
@side = SIDES.include?(side.to_sym) ? side.to_sym : :bottom
@side_offset = side_offset
@align = ALIGNS.include?(align.to_sym) ? align.to_sym : :start
@align_offset = align_offset
super(**)
end
def view_template(&)
div(**with_combobox_defaults(id: combobox[:content_id], role: (combobox[:popup] == :dialog) ? "dialog" : nil), &)
end
private
def default_attrs
{
popover: "manual",
data: {
slot: "combobox-content",
ruby_ui__combobox_target: "content",
closed: "",
side: @side,
align: @align,
preferred_side: @side,
side_offset: @side_offset,
align_offset: @align_offset
},
class: [
"group/combobox-content fixed inset-auto m-0 border-0 p-0",
"bg-popover text-popover-foreground ring-1 ring-foreground/10 rounded-md shadow-md overflow-hidden",
"max-h-[min(--spacing(72),var(--available-height,100vh))] min-w-36",
"w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))]",
"data-[chips=true]:min-w-(--anchor-width) origin-(--transform-origin) duration-100",
"data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95",
"data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:fill-mode-forwards",
"data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2",
"data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
"*:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8",
"*:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30",
"*:data-[slot=input-group]:shadow-none"
]
}
end
end
end
6
Add RubyUI::ComboboxContext to app/components/ruby_ui/combobox/combobox_context.rb
# frozen_string_literal: true
module RubyUI
# Shared by the combobox parts: Base builds attrs in initialize, before the
# Phlex context exists, so values that come from the root (ids, name,
# multiple, disabled) are added while rendering. The caller's own attributes
# still win.
module ComboboxContext
private
def combobox = context[:ruby_ui_combobox] || {}
def with_combobox_defaults(defaults)
defaults.merge(attrs) { |_, ours, theirs| (ours.is_a?(Hash) && theirs.is_a?(Hash)) ? ours.merge(theirs) : theirs }
end
end
end
7
Add RubyUI::ComboboxDocs to app/components/ruby_ui/combobox/combobox_docs.rb
# frozen_string_literal: true
class Views::Docs::Combobox < Views::Base
def view_template
component = "Combobox"
div(class: "max-w-2xl mx-auto w-full py-10 space-y-10") do
render Docs::Header.new(title: component, description: "Autocomplete input with a list of suggestions.")
Heading(level: 2) { "Usage" }
render Docs::VisualCodeExample.new(title: "Basic", description: "ComboboxInput is the trigger: typing filters the list, the arrow keys move through it and Enter picks. Each item carries a native radio named after the root's name:, so the form submits the selection.", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework") do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With clear button", description: "show_clear: adds a button that clears the value; it shows while there is one.", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework_clear") do
ComboboxInput(placeholder: "Select a framework", show_clear: true)
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next", selected: true) { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With groups", description: "ComboboxGroup and ComboboxLabel name a set of items; ComboboxSeparator divides them. Groups with no match hide while searching.", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "food") do
ComboboxInput(placeholder: "Select a food")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxGroup do
ComboboxLabel { "Fruits" }
ComboboxItem(value: "apple") { "Apple" }
ComboboxItem(value: "banana") { "Banana" }
end
ComboboxSeparator()
ComboboxGroup do
ComboboxLabel { "Vegetables" }
ComboboxItem(value: "broccoli") { "Broccoli" }
ComboboxItem(value: "carrot") { "Carrot" }
end
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled items", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework_disabled_items") do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit", disabled: true) { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix", disabled: true) { "Remix" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework_disabled", disabled: true) do
ComboboxInput(placeholder: "Select a framework")
ComboboxContent do
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Invalid", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework_invalid") do
ComboboxInput(placeholder: "Select a framework", aria: {invalid: "true"})
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "remix") { "Remix" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Side", description: "side: (top, right, bottom, left) and align: (start, center, end) place the popup; side_offset: and align_offset: set the gap.", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "framework_side") do
ComboboxInput(placeholder: "Opens above")
ComboboxContent(side: :top) do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "In a popup", description: "ComboboxTrigger is a button that shows the value (ComboboxValue); the search input lives inside the popup (show_trigger: false).", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "country") do
ComboboxTrigger { ComboboxValue(placeholder: "Select a country") }
ComboboxContent do
ComboboxInput(placeholder: "Search", show_trigger: false)
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "br", selected: true) { "Brazil" }
ComboboxItem(value: "ar") { "Argentina" }
ComboboxItem(value: "cl") { "Chile" }
ComboboxItem(value: "pt") { "Portugal" }
ComboboxItem(value: "us") { "United States" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Multiple", description: "multiple: true picks several items, shown as chips. Backspace on the empty input removes the last one.", context: self) do
<<~RUBY
div(class: "w-80") do
Combobox(name: "frameworks[]", multiple: true) do
ComboboxChips do
ComboboxChipsInput(placeholder: "Add framework")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next", selected: true) { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Select all", description: "RubyUI extras: ComboboxToggleAll is an option that selects every enabled item, or clears them when all are selected; it hides while searching and also works in a popup (next example). ComboboxChips(max: 3) keeps the box small: past three items the chips collapse into one \"5 frameworks\" chip (term: from the root), whose remove button, like Backspace, clears the selection.", context: self) do
<<~RUBY
div(class: "w-80") do
Combobox(name: "frameworks_all[]", multiple: true, term: "frameworks") do
ComboboxChips(max: 3) do
ComboboxChipsInput(placeholder: "Add framework")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxToggleAll { "Select all" }
ComboboxSeparator()
ComboboxItem(value: "next") { "Next.js" }
ComboboxItem(value: "sveltekit") { "SvelteKit" }
ComboboxItem(value: "nuxt") { "Nuxt.js" }
ComboboxItem(value: "remix") { "Remix" }
ComboboxItem(value: "astro") { "Astro" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Multiple in a popup", description: "The same in a popup. term: shows \"2 fruits\" in the trigger instead of the list of names (RubyUI extra).", context: self) do
<<~RUBY
div(class: "w-64") do
Combobox(name: "fruits[]", multiple: true, term: "fruits") do
ComboboxTrigger { ComboboxValue(placeholder: "Pick fruits") }
ComboboxContent do
ComboboxInput(placeholder: "Search", show_trigger: false)
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxToggleAll { "Select all" }
ComboboxSeparator()
ComboboxItem(value: "apple") { "Apple" }
ComboboxItem(value: "banana") { "Banana" }
ComboboxItem(value: "blueberry") { "Blueberry" }
ComboboxItem(value: "grapes") { "Grapes" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Form", description: "required: makes the browser validate the selection: one radio for a single combobox, at least one checkbox for multiple: true. FormField shows the message and marks the visible input invalid.", context: self) do
<<~RUBY
form(class: "flex w-80 flex-col gap-4") do
FormField do
FormFieldLabel(for: "framework-form-input") { "Framework" }
Combobox(name: "framework_form", required: true) do
ComboboxInput(id: "framework-form-input", placeholder: "Select a framework")
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "next", input: {data: {value_missing: "Pick a framework"}}) { "Next.js" }
ComboboxItem(value: "remix", input: {data: {value_missing: "Pick a framework"}}) { "Remix" }
ComboboxItem(value: "astro", input: {data: {value_missing: "Pick a framework"}}) { "Astro" }
end
end
end
FormFieldError()
end
FormField do
FormFieldLabel(for: "stack-form-input") { "Stack" }
Combobox(name: "stack_form[]", multiple: true, required: true) do
ComboboxChips do
ComboboxChipsInput(id: "stack-form-input", placeholder: "Add a tool")
end
ComboboxContent do
ComboboxEmpty { "No items found." }
ComboboxList do
ComboboxItem(value: "rails", input: {data: {value_missing: "Pick at least one"}}) { "Rails" }
ComboboxItem(value: "hotwire", input: {data: {value_missing: "Pick at least one"}}) { "Hotwire" }
ComboboxItem(value: "phlex", input: {data: {value_missing: "Pick at least one"}}) { "Phlex" }
end
end
end
FormFieldError()
end
Button(type: "submit") { "Submit" }
end
RUBY
end
render Components::ComponentSetup::Tabs.new(component_name: component)
render Docs::ComponentsTable.new(component_files(component))
end
end
end
8
Add RubyUI::ComboboxEmpty to app/components/ruby_ui/combobox/combobox_empty.rb
# frozen_string_literal: true
module RubyUI
# Shown by CSS while the controller marks the content data-empty (no item
# matches the search).
class ComboboxEmpty < Base
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
role: "status",
aria: {live: "polite", atomic: "true"},
data: {slot: "combobox-empty"},
class: "hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex"
}
end
end
end
9
Add RubyUI::ComboboxGroup to app/components/ruby_ui/combobox/combobox_group.rb
# frozen_string_literal: true
require "securerandom"
module RubyUI
# A group of items, named by the ComboboxLabel inside it. The controller
# hides it while none of its items matches the search.
class ComboboxGroup < Base
def initialize(id: nil, **)
@id = id || "combobox-group-#{SecureRandom.hex(4)}"
super(id: @id, **)
end
# The children are captured first, so aria-labelledby only points at a
# ComboboxLabel that actually rendered (with its own id: when it has one).
def view_template(&block)
previous = context[:ruby_ui_combobox_group]
names = context[:ruby_ui_combobox_group] = {label_id: "#{@id}-label"}
body = block ? capture(&block) : ""
group_attrs = names[:labelledby] ? mix({aria: {labelledby: names[:labelledby]}}, attrs) : attrs
div(**group_attrs) { raw(safe(body)) }
ensure
context[:ruby_ui_combobox_group] = previous
end
private
def default_attrs
{
role: "group",
data: {slot: "combobox-group", ruby_ui__combobox_target: "group"}
}
end
end
end
10
Add RubyUI::ComboboxInput to app/components/ruby_ui/combobox/combobox_input.rb
# frozen_string_literal: true
module RubyUI
# The text input of a combobox, inside an input group (shadcn's ComboboxInput).
# Outside ComboboxContent it is the trigger: typing filters and opens the list,
# show_trigger: adds the chevron, show_clear: a button that clears the value.
# Inside ComboboxContent it is the search field of the popup; pass
# show_trigger: false there. Extra attributes go to the <input>.
class ComboboxInput < Base
include ComboboxContext
INPUT_GROUP = [
"group/input-group relative flex w-auto min-w-0 items-center outline-none",
"h-9 rounded-md border border-input shadow-xs transition-[color,box-shadow] dark:bg-input/30",
"has-[[data-slot=input-group-control]:focus-visible]:border-ring",
"has-[[data-slot=input-group-control]:focus-visible]:ring-3",
"has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50",
"has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3",
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20",
"dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
"in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0",
"has-[>[data-align=inline-end]]:[&>input]:pr-1.5",
"data-[disabled=true]:cursor-not-allowed"
].freeze
ADDON = "order-last flex h-auto cursor-text items-center justify-center gap-2 py-1.5 pr-2 " \
"text-sm font-medium text-muted-foreground select-none has-[>button]:-mr-1 " \
"group-data-[disabled=true]/input-group:opacity-50"
ADDON_BUTTON = "size-6 rounded-[calc(var(--radius)-5px)] p-0 shadow-none"
def initialize(placeholder: nil, show_trigger: true, show_clear: false, disabled: false, **)
@placeholder = placeholder
@show_trigger = show_trigger
@show_clear = show_clear
@disabled = disabled
super(**)
end
def view_template
@disabled ||= !!combobox[:disabled]
div(class: INPUT_GROUP, role: "group", data: {slot: "input-group", disabled: (@disabled ? "true" : nil)}) do
input(**with_combobox_defaults(disabled: @disabled, aria: {controls: combobox[:list_id], required: (combobox[:required] ? "true" : nil)}))
addon
end
end
private
def addon
div(class: ADDON, role: "group", data: {slot: "input-group-addon", align: "inline-end", action: "click->ruby-ui--combobox#focusInput"}) do
trigger_button if @show_trigger
clear_button if @show_clear
end
end
# Hidden while the clear button shows, as in shadcn.
def trigger_button
render Button.new(
variant: :ghost, size: :xs, icon: true, disabled: @disabled, tabindex: -1,
class: "#{ADDON_BUTTON} group-has-[[data-slot=combobox-clear]:not([hidden])]/input-group:hidden",
aria: {label: "Toggle list"},
data: {slot!: "input-group-button", action: "click->ruby-ui--combobox#toggle"}
) do
icon("m6 9 6 6 6-6")
end
end
# The controller shows it only while there is a value. It stays in the tab
# order: it is the keyboard way to clear a single value.
def clear_button
render Button.new(
variant: :ghost, size: :xs, icon: true, disabled: @disabled, hidden: true,
class: ADDON_BUTTON,
aria: {label: "Clear"},
data: {slot!: "combobox-clear", ruby_ui__combobox_target: "clear", action: "click->ruby-ui--combobox#clear"}
) do
icon("M18 6 6 18", "m6 6 12 12")
end
end
def icon(*paths)
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true",
class: "pointer-events-none size-4"
) { |s| paths.each { |d| s.path(d: d) } }
end
def default_attrs
{
type: "text",
role: "combobox",
placeholder: @placeholder,
autocomplete: "off",
autocorrect: "off",
spellcheck: "false",
autocapitalize: "none",
aria: {autocomplete: "list", expanded: "false", haspopup: "listbox"},
class: [
"h-full w-full min-w-0 flex-1 rounded-none border-0 bg-transparent px-2.5 py-1 text-base shadow-none",
"border-input outline-none ring-0 focus:ring-0 focus-visible:border-ring focus-visible:ring-0 focus-visible:ring-ring/50 md:text-sm dark:bg-transparent",
"placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
],
data: {
slot: "input-group-control",
ruby_ui__combobox_target: "input",
action: "input->ruby-ui--combobox#filter keydown->ruby-ui--combobox#inputKeydown " \
"click->ruby-ui--combobox#inputClick"
}
}
end
end
end
11
Add RubyUI::ComboboxItem to app/components/ruby_ui/combobox/combobox_item.rb
# frozen_string_literal: true
module RubyUI
# An option. Its value travels in a native radio (or checkbox, when the root
# is multiple:) named after the root's name:, kept visually hidden so forms,
# required and FormField work without JavaScript glue. input: adds attributes
# to that input (e.g. data: {value_missing: "..."}).
class ComboboxItem < Base
include ComboboxContext
ITEM = [
"group/combobox-item relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2",
"text-sm outline-hidden select-none",
"data-highlighted:bg-accent data-highlighted:text-accent-foreground",
"not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
].freeze
def initialize(value:, selected: false, disabled: false, text: nil, input: {}, **)
@value = value
@selected = selected
@disabled = disabled
@text = text
@input_attrs = input
super(**)
end
def view_template(&)
div(**attrs) do
native_input
yield if block_given?
indicator
end
end
private
def multiple? = !!combobox[:multiple]
def native_input
data = if multiple?
{
ruby_ui__checkbox_group_target: "checkbox",
action: "change->ruby-ui--checkbox-group#onChange change->ruby-ui--form-field#onInput invalid->ruby-ui--form-field#onInvalid"
}
else
{action: "change->ruby-ui--form-field#onInput invalid->ruby-ui--form-field#onInvalid"}
end
data[:ruby_ui__form_field_target] = "input"
input(**mix({
type: multiple? ? "checkbox" : "radio",
name: combobox[:name],
value: @value,
checked: @selected,
disabled: @disabled || combobox[:disabled],
required: !multiple? && combobox[:required],
tabindex: -1,
aria: {hidden: "true"},
class: "sr-only",
data: data
}, @input_attrs))
end
def indicator
span(class: "pointer-events-none absolute right-2 hidden size-4 items-center justify-center group-aria-selected/combobox-item:flex", aria: {hidden: "true"}) do
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true",
class: "pointer-events-none size-4"
) { |s| s.path(d: "M20 6 9 17l-5-5") }
end
end
def default_attrs
{
role: "option",
aria: {selected: @selected.to_s, disabled: (@disabled ? "true" : nil)},
data: {
slot: "combobox-item",
ruby_ui__combobox_target: "item",
value: @value,
text: @text,
disabled: (@disabled ? "" : nil),
action: "click->ruby-ui--combobox#select pointermove->ruby-ui--combobox#hover"
},
class: ITEM
}
end
end
end
12
Add RubyUI::ComboboxLabel to app/components/ruby_ui/combobox/combobox_label.rb
# frozen_string_literal: true
module RubyUI
class ComboboxLabel < Base
# Inside a ComboboxGroup, the first label names the group.
def view_template(&)
names = context[:ruby_ui_combobox_group]
return div(**attrs, &) if names.nil? || (!attrs[:id] && names[:labelledby])
id = attrs[:id] || names[:label_id]
names[:labelledby] ||= id
div(**attrs.merge(id: id), &)
end
private
def default_attrs
{
# The group is named through aria-labelledby; the text itself is hidden.
aria: {hidden: "true"},
data: {slot: "combobox-label"},
class: "px-2 py-1.5 text-xs text-muted-foreground"
}
end
end
end
13
Add RubyUI::ComboboxList to app/components/ruby_ui/combobox/combobox_list.rb
# frozen_string_literal: true
module RubyUI
class ComboboxList < Base
include ComboboxContext
def view_template(&)
div(**with_combobox_defaults(id: combobox[:list_id], aria: {multiselectable: (combobox[:multiple] ? "true" : nil)}), &)
end
private
def default_attrs
{
role: "listbox",
data: {
slot: "combobox-list",
ruby_ui__combobox_target: "list",
# Clicking an option must not take focus away from the input.
action: "mousedown->ruby-ui--combobox#keepFocus"
},
class: [
"max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height,100vh)---spacing(9)))]",
"scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
]
}
end
end
end
14
Add RubyUI::ComboboxSeparator to app/components/ruby_ui/combobox/combobox_separator.rb
# frozen_string_literal: true
module RubyUI
class ComboboxSeparator < Base
def view_template
div(**attrs)
end
private
def default_attrs
{
role: "separator",
aria: {orientation: "horizontal"},
data: {slot: "combobox-separator", ruby_ui__combobox_target: "separator"},
class: "-mx-1 my-1 h-px bg-border"
}
end
end
end
15
Add RubyUI::ComboboxToggleAll to app/components/ruby_ui/combobox/combobox_toggle_all.rb
# frozen_string_literal: true
module RubyUI
# RubyUI extra (no shadcn counterpart): an option that selects or clears
# every item of a multiple: combobox. Hidden while searching.
class ComboboxToggleAll < Base
def view_template(&)
div(**attrs) do
yield if block_given?
span(class: "pointer-events-none absolute right-2 hidden size-4 items-center justify-center group-aria-selected/combobox-item:flex", aria: {hidden: "true"}) do
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true",
class: "pointer-events-none size-4"
) { |s| s.path(d: "M20 6 9 17l-5-5") }
end
end
end
private
def default_attrs
{
role: "option",
aria: {selected: "false"},
data: {
slot: "combobox-item",
ruby_ui__combobox_target: "toggleAll",
action: "click->ruby-ui--combobox#select pointermove->ruby-ui--combobox#hover"
},
class: ComboboxItem::ITEM
}
end
end
end
16
Add RubyUI::ComboboxTrigger to app/components/ruby_ui/combobox/combobox_trigger.rb
# frozen_string_literal: true
module RubyUI
# The button that opens the popup, for the "Combobox in Popup" pattern: put a
# ComboboxValue inside it and a ComboboxInput inside ComboboxContent. It is a
# RubyUI Button (variant: :outline) with role=combobox, like Base UI's
# Combobox.Trigger rendered through shadcn's Button.
class ComboboxTrigger < Base
include ComboboxContext
def view_template(&block)
# The popup holds the search input, so it is a dialog (Base UI's role).
combobox[:popup] = :dialog
# aria-controls is set by the controller while the popup is open.
trigger_attrs = with_combobox_defaults(aria: {required: (combobox[:required] ? "true" : nil)})
render Button.new(variant: :outline, disabled: !!combobox[:disabled], **trigger_attrs) do
yield if block
chevron
end
end
private
def default_attrs
{
role: "combobox",
class: "w-full justify-between font-normal",
aria: {haspopup: "dialog", expanded: "false"},
data: {
ruby_ui__combobox_target: "trigger",
action: "click->ruby-ui--combobox#toggle keydown->ruby-ui--combobox#triggerKeydown"
}
}
end
def chevron
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true",
class: "pointer-events-none size-4 text-muted-foreground"
) { |s| s.path(d: "m6 9 6 6 6-6") }
end
end
end
17
Add RubyUI::ComboboxValue to app/components/ruby_ui/combobox/combobox_value.rb
# frozen_string_literal: true
module RubyUI
# Shows the selected item(s) inside ComboboxTrigger. The controller fills it:
# the placeholder when nothing is selected, the item text, the texts joined
# with ", " (multiple), or "<count> <term>" when the root has term:.
class ComboboxValue < Base
def initialize(placeholder: nil, **)
@placeholder = placeholder
super(**)
end
def view_template
span(**attrs) { @placeholder }
end
private
def default_attrs
{
class: "truncate data-placeholder:text-muted-foreground",
data: {
slot: "combobox-value",
ruby_ui__combobox_target: "value",
placeholder_text: @placeholder,
placeholder: ""
}
}
end
end
end
18
Add combobox_controller.js to app/javascript/controllers/ruby_ui/combobox_controller.js
import { Controller } from "@hotwired/stimulus";
import { computePosition, autoUpdate, offset, flip, shift, size } from "@floating-ui/dom";
// Connects to data-controller="ruby-ui--combobox"
//
// Follows the APG combobox pattern as Base UI does: focus stays in the text
// input, the active option is announced through aria-activedescendant and
// marked data-highlighted. Each option carries a native radio/checkbox, so the
// selection is whatever is checked and the form submits it as is.
export default class extends Controller {
static values = {
multiple: { type: Boolean, default: false },
term: String,
};
static targets = [
"trigger",
"value",
"input",
"clear",
"content",
"list",
"item",
"group",
"separator",
"toggleAll",
"chips",
"chipTemplate",
];
connect() {
this.cleanup = null;
this.highlighted = null;
this.focusReturn = null;
this.mirroredInvalid = false;
this.mirroredDescribedBy = false;
// A reconnect can bring back an option marked by a previous instance.
this.element.querySelectorAll("[data-highlighted]").forEach((option) => option.removeAttribute("data-highlighted"));
if (this.hasChipsTarget && this.hasContentTarget) this.contentTarget.dataset.chips = "true";
// FormField marks the hidden radios/checkboxes aria-invalid; mirror it on
// the control people see, so the error is announced and styled there.
this.invalidObserver = new MutationObserver(() => this.syncInvalid());
this.invalidObserver.observe(this.element, { subtree: true, attributes: true, attributeFilter: ["aria-invalid", "aria-describedby"] });
// The form's reset unchecks the inputs without firing change.
this.form = this.element.closest("form");
this.form?.addEventListener("reset", this.handleFormReset);
this.syncInvalid();
this.refresh();
}
disconnect() {
document.removeEventListener("pointerdown", this.handleOutsidePointerDown, true);
this.removeFocusReturn();
this.invalidObserver?.disconnect();
this.form?.removeEventListener("reset", this.handleFormReset);
clearTimeout(this.resetTimeout);
this.stopAutoUpdate();
if (this.hasContentTarget) this.settleExit(this.contentTarget);
}
// Re-reads the DOM (connect, Turbo morph): option ids, the popup state the
// server markup may have reset, and the checked inputs.
refresh() {
this.assignOptionIds();
if (this.hasListTarget && this.listTarget.id) {
this.inputTargets.forEach((input) => input.setAttribute("aria-controls", this.listTarget.id));
}
if (this.hasContentTarget) {
const content = this.contentTarget;
// A morph can restore data-closed while the native popover is still open
// (or the reverse): settle on closed, with the listeners released.
if (content.matches(":popover-open") !== content.hasAttribute("data-open") || this.isOpen) {
this.hide({ restoreFocus: false, animate: false });
}
}
this.syncSelection();
if (this.inputIsTrigger && !this.multipleValue) this.inputTarget.value = this.selectedText;
}
itemTargetConnected() {
this.assignOptionIds();
}
// reset fires before the form restores its controls; the next task sees the
// restored checked state.
handleFormReset = () => {
clearTimeout(this.resetTimeout);
this.resetTimeout = setTimeout(() => {
this.refresh();
// Lets CheckboxGroup (required multiple:) recompute its required flags.
const first = this.itemTargets.map((item) => this.inputOf(item)).find(Boolean);
if (first?.type === "checkbox") first.dispatchEvent(new Event("change", { bubbles: true }));
});
};
syncInvalid() {
const control = this.hasTriggerTarget ? this.triggerTarget : this.hasInputTarget ? this.inputTarget : null;
if (!control) return;
// FormField points its hint and error at the hidden inputs.
const describedBy = this.itemTargets.map((item) => this.inputOf(item)?.getAttribute("aria-describedby")).find(Boolean);
if (describedBy && (!control.hasAttribute("aria-describedby") || this.mirroredDescribedBy)) {
if (control.getAttribute("aria-describedby") !== describedBy) control.setAttribute("aria-describedby", describedBy);
this.mirroredDescribedBy = true;
}
const invalid = this.itemTargets.some((item) => this.inputOf(item)?.getAttribute("aria-invalid") === "true");
if (invalid) {
if (control.getAttribute("aria-invalid") === "true") return;
control.setAttribute("aria-invalid", "true");
this.mirroredInvalid = true;
} else if (this.mirroredInvalid) {
// Only undo what we set: an author's own aria-invalid stays.
control.removeAttribute("aria-invalid");
this.mirroredInvalid = false;
}
}
// --- Modes -----------------------------------------------------------------
get isOpen() {
return this.hasContentTarget && this.contentTarget.hasAttribute("data-open");
}
// The input sits outside the popup when it is the trigger (input or chips).
get inputIsTrigger() {
return this.hasInputTarget && !this.contentTarget.contains(this.inputTarget);
}
get anchor() {
if (this.hasChipsTarget) return this.chipsTarget;
if (this.hasTriggerTarget) return this.triggerTarget;
return this.inputTarget.closest("[data-slot=input-group]") || this.inputTarget;
}
get disabled() {
return this.element.dataset.disabled === "true";
}
// --- Opening and closing ----------------------------------------------------
toggle(event) {
event?.preventDefault();
this.isOpen ? this.hide({ restoreFocus: true }) : this.show();
}
triggerKeydown(event) {
if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
event.preventDefault();
if (!this.isOpen) this.show({ highlight: event.key === "ArrowDown" ? "first" : "last" });
}
inputClick() {
if (this.inputIsTrigger && !this.isOpen) this.show();
}
focusInput(event) {
if (event.target.closest("button")) return;
this.inputTarget.focus();
if (!this.isOpen) this.show();
}
show({ highlight = null } = {}) {
if (this.disabled || !this.hasContentTarget || this.isOpen) return;
const content = this.contentTarget;
content.removeAttribute("data-closed");
content.setAttribute("data-open", "");
if (!content.matches(":popover-open")) content.showPopover();
this.setExpanded(true);
this.applyFilter("");
this.position();
document.addEventListener("pointerdown", this.handleOutsidePointerDown, true);
if (!this.inputIsTrigger && this.hasInputTarget) {
this.inputTarget.value = "";
this.inputTarget.focus();
} else if (this.hasInputTarget && document.activeElement !== this.inputTarget) {
// Opened from the chevron: keys only reach the input.
this.inputTarget.focus();
}
const options = this.visibleOptions;
if (highlight === "first") this.highlight(options[0]);
else if (highlight === "last") this.highlight(options[options.length - 1]);
else this.highlight(options.find((option) => option.getAttribute("aria-selected") === "true"));
}
hide({ restoreFocus = false, animate = true } = {}) {
document.removeEventListener("pointerdown", this.handleOutsidePointerDown, true);
this.stopAutoUpdate();
this.setExpanded(false);
this.highlight(null);
if (!this.hasContentTarget) return;
const content = this.contentTarget;
content.removeAttribute("data-open");
content.setAttribute("data-closed", "");
animate ? this.hideAfterExitAnimation(content) : this.settleExit(content);
if (this.inputIsTrigger) {
// Typing doesn't change the value: the input goes back to the selection.
this.inputTarget.value = this.multipleValue ? "" : this.selectedText;
}
if (restoreFocus) (this.hasTriggerTarget ? this.triggerTarget : this.inputTarget)?.focus();
}
setExpanded(open) {
const value = open ? "true" : "false";
if (this.hasTriggerTarget) {
this.triggerTarget.setAttribute("aria-expanded", value);
// Like Base UI, the trigger points at the popup only while it is open.
if (open && this.hasContentTarget && this.contentTarget.id) {
this.triggerTarget.setAttribute("aria-controls", this.contentTarget.id);
} else {
this.triggerTarget.removeAttribute("aria-controls");
}
}
if (this.hasInputTarget) this.inputTarget.setAttribute("aria-expanded", value);
}
handleOutsidePointerDown = (event) => {
if (this.element.contains(event.target)) return;
const focusWasInside = this.element.contains(document.activeElement);
this.hide();
// Like Base UI, focus goes back to the trigger unless the click lands on
// something that takes focus itself.
this.removeFocusReturn();
if (focusWasInside && this.hasTriggerTarget) {
const trigger = this.triggerTarget;
this.focusReturn = () => {
this.focusReturn = null;
if (document.activeElement === document.body || !document.activeElement) trigger.focus();
};
document.addEventListener("click", this.focusReturn, { once: true, capture: true });
}
};
// A pointerdown with no click (a touch scroll) would otherwise leave it armed.
removeFocusReturn() {
if (!this.focusReturn) return;
document.removeEventListener("click", this.focusReturn, { capture: true });
this.focusReturn = null;
}
// Clicking an option must not move focus away from the input.
keepFocus(event) {
event.preventDefault();
}
// --- Keyboard -------------------------------------------------------------
inputKeydown(event) {
switch (event.key) {
case "ArrowDown":
event.preventDefault();
this.isOpen ? this.move(1) : this.show({ highlight: "first" });
break;
case "ArrowUp":
event.preventDefault();
this.isOpen ? this.move(-1) : this.show({ highlight: "last" });
break;
case "Home":
case "End": {
if (!this.isOpen) return;
// Like Base UI: jump to the first/last option. The caret still moves
// when there is text; on an empty input the browser would scroll the
// page instead, so that default is dropped.
if (this.inputTarget.value === "") event.preventDefault();
const options = this.visibleOptions;
this.highlight(event.key === "Home" ? options[0] : options[options.length - 1]);
break;
}
case "Enter":
if (!this.isOpen) return;
event.preventDefault();
if (this.highlighted) this.choose(this.highlighted);
break;
case "Escape":
if (!this.isOpen) return;
event.preventDefault();
event.stopPropagation();
this.hide({ restoreFocus: true });
break;
case "Tab":
if (this.isOpen) this.hide();
break;
case "Backspace":
if (this.hasChipsTarget && this.inputTarget.value === "") this.removeLastSelected();
break;
}
}
move(delta) {
const options = this.visibleOptions;
if (options.length === 0) return;
const index = options.indexOf(this.highlighted);
const next = index === -1 ? (delta > 0 ? 0 : options.length - 1) : (index + delta + options.length) % options.length;
this.highlight(options[next]);
}
hover(event) {
const option = event.currentTarget;
if (option !== this.highlighted && !this.isDisabled(option)) this.highlight(option, { scroll: false });
}
highlight(option, { scroll = true } = {}) {
this.highlighted?.removeAttribute("data-highlighted");
this.highlighted = option || null;
if (!this.hasInputTarget) return;
if (!option) {
this.inputTarget.removeAttribute("aria-activedescendant");
return;
}
option.setAttribute("data-highlighted", "");
this.inputTarget.setAttribute("aria-activedescendant", option.id);
if (scroll) option.scrollIntoView({ block: "nearest" });
}
// --- Filtering --------------------------------------------------------------
filter() {
if (!this.isOpen) this.show();
this.applyFilter(this.inputTarget.value);
this.highlight(null);
}
applyFilter(query) {
const term = query.trim().toLowerCase();
let visible = 0;
this.itemTargets.forEach((item) => {
const match = this.textOf(item).toLowerCase().includes(term);
item.hidden = !match;
if (match) visible++;
});
this.groupTargets.forEach((group) => {
group.hidden = !this.itemTargets.some((item) => !item.hidden && group.contains(item));
});
this.separatorTargets.forEach((separator) => (separator.hidden = term !== ""));
this.toggleAllTargets.forEach((toggleAll) => (toggleAll.hidden = term !== ""));
const empty = visible === 0;
for (const element of [this.hasContentTarget && this.contentTarget, this.hasListTarget && this.listTarget]) {
if (element) element.toggleAttribute("data-empty", empty);
}
}
// --- Selection --------------------------------------------------------------
select(event) {
this.choose(event.currentTarget);
}
choose(option) {
if (this.isDisabled(option)) return;
if (this.hasToggleAllTarget && option === this.toggleAllTarget) {
this.toggleAll();
return;
}
const input = this.inputOf(option);
if (!input) return;
if (this.multipleValue) {
input.checked = !input.checked;
} else {
this.itemTargets.forEach((item) => {
const other = this.inputOf(item);
if (other && other !== input) other.checked = false;
});
input.checked = true;
}
this.notify(input);
this.syncSelection();
if (this.multipleValue) {
if (this.hasChipsTarget) {
this.inputTarget.value = "";
this.applyFilter("");
}
} else {
this.hide({ restoreFocus: true });
}
}
toggleAll() {
const inputs = this.itemTargets.map((item) => this.inputOf(item)).filter((input) => input && !input.disabled);
const check = !inputs.every((input) => input.checked);
inputs.forEach((input) => {
if (input.checked === check) return;
input.checked = check;
this.notify(input);
});
this.syncSelection();
}
clear(event) {
event?.preventDefault();
this.clearSelection();
if (this.hasInputTarget) {
this.inputTarget.value = "";
this.inputTarget.focus();
}
if (this.isOpen) this.applyFilter("");
}
// Disabled items keep their selection: their chips can't be removed either.
clearSelection() {
this.itemTargets.forEach((item) => {
const input = this.inputOf(item);
if (!input?.checked || this.isDisabled(item) || input.disabled) return;
input.checked = false;
this.notify(input);
});
this.syncSelection();
}
removeChip(event) {
event.preventDefault();
event.stopPropagation();
const chip = event.currentTarget.closest("[data-slot=combobox-chip]");
if (chip?.hasAttribute("data-summary")) {
this.clearSelection();
if (this.hasInputTarget) this.inputTarget.focus();
return;
}
const value = chip?.dataset.value;
const item = this.itemTargets.find((candidate) => candidate.dataset.value === value);
const input = item && this.inputOf(item);
if (!input) return;
input.checked = false;
this.notify(input);
this.syncSelection();
// The clicked button left the DOM with its chip; keep typing in the input.
if (this.hasInputTarget) this.inputTarget.focus();
}
removeLastSelected() {
// The summary chip stands for the whole selection, so it goes as one.
if (this.chipsSummarized) {
this.clearSelection();
return;
}
const input = this.selectedItems.filter((item) => !this.isDisabled(item)).map((item) => this.inputOf(item)).at(-1);
if (!input || input.disabled) return;
input.checked = false;
this.notify(input);
this.syncSelection();
}
// Listeners on the native inputs (FormField, CheckboxGroup) see the change.
notify(input) {
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
syncSelection() {
const selected = this.selectedItems;
this.itemTargets.forEach((item) => {
item.setAttribute("aria-selected", selected.includes(item) ? "true" : "false");
});
if (this.hasToggleAllTarget) {
const enabled = this.itemTargets.filter((item) => !this.isDisabled(item));
const all = enabled.length > 0 && enabled.every((item) => selected.includes(item));
this.toggleAllTarget.setAttribute("aria-selected", all ? "true" : "false");
}
if (this.hasValueTarget) this.renderValue(selected);
if (this.hasClearTarget) this.clearTarget.hidden = selected.length === 0;
if (this.hasChipsTarget) this.renderChips(selected);
}
renderValue(selected) {
const value = this.valueTarget;
if (selected.length === 0) {
value.textContent = value.dataset.placeholderText || "";
value.setAttribute("data-placeholder", "");
return;
}
value.removeAttribute("data-placeholder");
value.textContent =
this.termValue && selected.length > 1
? `${selected.length} ${this.termValue}`
: selected.map((item) => this.textOf(item)).join(", ");
}
renderChips(selected) {
this.chipsTarget.querySelectorAll(":scope > [data-slot=combobox-chip]").forEach((chip) => chip.remove());
if (!this.hasChipTemplateTarget) return;
const before = this.hasInputTarget && this.chipsTarget.contains(this.inputTarget) ? this.inputTarget : null;
if (this.chipsSummarized) {
const chip = this.chipTemplateTarget.content.firstElementChild.cloneNode(true);
chip.setAttribute("data-summary", "");
const text = chip.querySelector("[data-text]") || chip;
text.textContent = `${selected.length} ${this.termValue || "selected"}`;
chip.querySelector("[data-slot=combobox-chip-remove]")?.setAttribute("aria-label", "Clear selection");
if (this.disabled) chip.querySelector("button")?.setAttribute("disabled", "");
this.chipsTarget.insertBefore(chip, before);
return;
}
selected.forEach((item) => {
const chip = this.chipTemplateTarget.content.firstElementChild.cloneNode(true);
chip.dataset.value = item.dataset.value;
const text = chip.querySelector("[data-text]") || chip;
text.textContent = this.textOf(item);
chip.querySelector("[data-slot=combobox-chip-remove]")?.setAttribute("aria-label", `Remove ${this.textOf(item)}`);
if (this.isDisabled(item) || this.disabled) chip.querySelector("button")?.setAttribute("disabled", "");
this.chipsTarget.insertBefore(chip, before);
});
}
// --- Helpers --------------------------------------------------------------
// ComboboxChips(max:): past the cap, one "<count> <term>" chip replaces them.
get chipsSummarized() {
if (!this.hasChipsTarget) return false;
const max = parseInt(this.chipsTarget.dataset.max, 10);
return Number.isInteger(max) && max >= 0 && this.selectedItems.length > max;
}
get visibleOptions() {
const options = [...(this.hasToggleAllTarget ? [this.toggleAllTarget] : []), ...this.itemTargets];
return options
.filter((option) => !option.hidden && !this.isDisabled(option))
.sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
}
get selectedItems() {
return this.itemTargets.filter((item) => this.inputOf(item)?.checked);
}
get selectedText() {
return this.selectedItems.map((item) => this.textOf(item)).join(", ");
}
inputOf(item) {
return item.querySelector("input[type=radio], input[type=checkbox]");
}
textOf(item) {
return item.dataset.text || item.textContent.trim();
}
isDisabled(option) {
return option.hasAttribute("data-disabled") || option.getAttribute("aria-disabled") === "true";
}
assignOptionIds() {
const prefix = (this.hasListTarget && this.listTarget.id) || this.element.id || "combobox";
const options = [...(this.hasToggleAllTarget ? [this.toggleAllTarget] : []), ...this.itemTargets];
let next = 0;
options.forEach((option) => {
if (option.id) return;
while (document.getElementById(`${prefix}-option-${next}`)) next++;
option.id = `${prefix}-option-${next}`;
});
}
// --- Positioning ----------------------------------------------------------
position() {
this.stopAutoUpdate();
const anchor = this.anchor;
const content = this.contentTarget;
const side = content.dataset.preferredSide || "bottom";
const align = content.dataset.align || "start";
const placement = align === "center" ? side : `${side}-${align}`;
const sideOffset = Number(content.dataset.sideOffset ?? 6);
const alignOffset = Number(content.dataset.alignOffset ?? 0);
this.cleanup = autoUpdate(anchor, content, () => {
if (!anchor.isConnected || !content.isConnected) return;
computePosition(anchor, content, {
strategy: "fixed",
placement,
middleware: [
offset({ mainAxis: sideOffset, crossAxis: alignOffset }),
flip(),
shift({ padding: 5 }),
size({
padding: 5,
apply({ availableWidth, availableHeight, rects }) {
content.style.setProperty("--anchor-width", `${rects.reference.width}px`);
content.style.setProperty("--available-width", `${availableWidth}px`);
content.style.setProperty("--available-height", `${availableHeight}px`);
},
}),
],
}).then(({ x, y, placement: resolved }) => {
if (!content.isConnected) return;
const [resolvedSide, resolvedAlign] = resolved.split("-");
Object.assign(content.style, { left: `${x}px`, top: `${y}px` });
content.dataset.side = resolvedSide;
content.style.setProperty("--transform-origin", this.transformOrigin(resolvedSide, resolvedAlign));
});
});
}
transformOrigin(side, align) {
const opposite = { top: "bottom", bottom: "top", left: "right", right: "left" }[side];
const cross = { start: side === "top" || side === "bottom" ? "left" : "top", end: side === "top" || side === "bottom" ? "right" : "bottom" }[align] || "center";
return side === "top" || side === "bottom" ? `${cross} ${opposite}` : `${opposite} ${cross}`;
}
stopAutoUpdate() {
this.cleanup?.();
this.cleanup = null;
}
// --- Exit animation (same block as the other overlay controllers) --------
exitAnimationNames = new WeakMap();
hideAfterExitAnimation(animated) {
const exitAnimations = animated.getAnimations().filter((animation) => animation instanceof CSSAnimation);
if (exitAnimations.length === 0) {
this.settleExit(animated);
return;
}
this.exitAnimationNames.set(animated, exitAnimations.map((animation) => animation.animationName));
animated.addEventListener("animationend", this.handleExitAnimationEnd);
animated.addEventListener("animationcancel", this.handleExitAnimationEnd);
}
handleExitAnimationEnd = (event) => {
if (event.target !== event.currentTarget) return;
if (!this.exitAnimationNames.get(event.currentTarget)?.includes(event.animationName)) return;
this.settleExit(event.currentTarget);
};
settleExit(animated) {
animated.removeEventListener("animationend", this.handleExitAnimationEnd);
animated.removeEventListener("animationcancel", this.handleExitAnimationEnd);
// Reopened mid-exit: leave it showing.
if (!animated.hasAttribute("data-closed")) return;
if (animated.matches(":popover-open")) animated.hidePopover();
}
}
19
Update the Stimulus controllers manifest file
rake stimulus:manifest:update20
Install @floating-ui/dom Javascript dependency
// with yarn
yarn add @floating-ui/dom
// with npm
npm install @floating-ui/dom
// with importmaps
bin/importmap pin @floating-ui/dom
21
Install required components
Component Combobox relies on the following RubyUI components. Refer to their individual installation guides for setup instructions:
Components
| Component | Built using | Source |
|---|---|---|
Combobox | Phlex | |
ComboboxChip | Phlex | |
ComboboxChips | Phlex | |
ComboboxChipsInput | Phlex | |
ComboboxContent | Phlex | |
ComboboxContext | Phlex | |
ComboboxDocs | Phlex | |
ComboboxEmpty | Phlex | |
ComboboxGroup | Phlex | |
ComboboxInput | Phlex | |
ComboboxItem | Phlex | |
ComboboxLabel | Phlex | |
ComboboxList | Phlex | |
ComboboxSeparator | Phlex | |
ComboboxToggleAll | Phlex | |
ComboboxTrigger | Phlex | |
ComboboxValue | Phlex | |
ComboboxController | Stimulus JS |