defmodule Corex.Combobox do @moduledoc ~S''' Phoenix implementation of [Zag.js Combobox](https://zagjs.com/components/react/combobox). Pass options with `Corex.List.new/1`. With `redirect`, use per-item `:to`, `:redirect` (`:href` | `:patch` | `:navigate` | `false`), and `:new_tab`; Zag runs single-select when `redirect` is true. ### Minimal ```heex <.combobox class="combobox" translation={%Corex.Combobox.Translation{placeholder: "Select a country", empty: "No results"}} items={Corex.List.new([ %{label: "France", id: "fra", disabled: true}, %{label: "Belgium", id: "bel"}, %{label: "Germany", id: "deu"}, %{label: "Netherlands", id: "nld"}, %{label: "Switzerland", id: "che"}, %{label: "Austria", id: "aut"} ])} > <:trigger> <.heroicon name="hero-chevron-down" /> ``` ### Grouped ```heex <.combobox class="combobox" translation={%Corex.Combobox.Translation{placeholder: "Select a country", empty: "No results"}} items={Corex.List.new([ %{label: "France", id: "fra", group: "Europe"}, %{label: "Belgium", id: "bel", group: "Europe"}, %{label: "Germany", id: "deu", group: "Europe"}, %{label: "Netherlands", id: "nld", group: "Europe"}, %{label: "Switzerland", id: "che", group: "Europe"}, %{label: "Austria", id: "aut", group: "Europe"}, %{label: "Japan", id: "jpn", group: "Asia"}, %{label: "China", id: "chn", group: "Asia"}, %{label: "South Korea", id: "kor", group: "Asia"}, %{label: "Thailand", id: "tha", group: "Asia"}, %{label: "USA", id: "usa", group: "North America"}, %{label: "Canada", id: "can", group: "North America"}, %{label: "Mexico", id: "mex", group: "North America"} ])} > <:trigger> <.heroicon name="hero-chevron-down" /> ``` ### Extended This example requires the installation of [Flagpack](https://hex.pm/packages/flagpack) to display the use of custom item rendering. ```heex <.combobox class="combobox" translation={%Corex.Combobox.Translation{placeholder: "Select a country", empty: "No results"}} items={Corex.List.new([ %{label: "France", id: "fra"}, %{label: "Belgium", id: "bel"}, %{label: "Germany", id: "deu"}, %{label: "Netherlands", id: "nld"}, %{label: "Switzerland", id: "che"}, %{label: "Austria", id: "aut"} ])} > <:item :let={item}> {item.label} <:trigger> <.heroicon name="hero-chevron-down" /> <:clear_trigger> <.heroicon name="hero-backspace" /> <:item_indicator> <.heroicon name="hero-check" /> ``` ### Extended Grouped This example requires the installation of [Flagpack](https://hex.pm/packages/flagpack) to display the use of custom item rendering. ```heex <.combobox class="combobox" translation={%Corex.Combobox.Translation{placeholder: "Select a country", empty: "No results"}} items={Corex.List.new([ %{label: "France", id: "fra", group: "Europe"}, %{label: "Belgium", id: "bel", group: "Europe"}, %{label: "Germany", id: "deu", group: "Europe"}, %{label: "Japan", id: "jpn", group: "Asia"}, %{label: "China", id: "chn", group: "Asia"}, %{label: "South Korea", id: "kor", group: "Asia"} ])} > <:item :let={item}> {item.label} <:trigger> <.heroicon name="hero-chevron-down" /> <:clear_trigger> <.heroicon name="hero-backspace" /> <:item_indicator> <.heroicon name="hero-check" /> ``` ## Phoenix Form Integration Use `field={f[:key]}` or `field={@form[:key]}` with a form built from an Ecto changeset. Set the form `id` in `to_form/2` and use `id={@form.id}` on `<.form>`. Build the form in the controller with `Schema.changeset(%Schema{}, %{}) |> Phoenix.Component.to_form(as: :form_name, id: "form-id")`. The combobox stays uncontrolled in the browser; merge hook-driven updates into changeset params when validating (see Angle Slider form docs). See the Select or NumberInput component docs for full controller and LiveView examples. ### Server-side Filtering Disable client filtering with `disabled={false}` and use `on_input_value_change` to filter on the server. This example uses a local list; replace with a database query for real apps. ```heex defmodule MyAppWeb.CountryCombobox do use MyAppWeb, :live_view @items [ %{id: "fra", label: "France"}, %{id: "bel", label: "Belgium"}, %{id: "deu", label: "Germany"}, %{id: "usa", label: "USA"}, %{id: "jpn", label: "Japan"} ] def mount(_params, _session, socket) do {:ok, assign(socket, items: [])} end def handle_event("search", %{"value" => value, "reason" => "input-change"}, socket) do filtered = if byte_size(value) < 1 do [] else term = String.downcase(value) Enum.filter(@items, fn item -> String.contains?(String.downcase(item.label), term) end) end {:noreply, assign(socket, items: filtered)} end def render(assigns) do ~H""" <.combobox id="country-combobox" items={@items} filter={false} on_input_value_change="search" > <:trigger><.heroicon name="hero-chevron-down" /> """ end end ``` ## Styling Use data attributes to target elements: ```css [data-scope="combobox"][data-part="root"] {} [data-scope="combobox"][data-part="control"] {} [data-scope="combobox"][data-part="input"] {} [data-scope="combobox"][data-part="trigger"] {} [data-scope="combobox"][data-part="clear-trigger"] {} [data-scope="combobox"][data-part="content"] {} [data-scope="combobox"][data-part="empty"] {} [data-scope="combobox"][data-part="item-group"] {} [data-scope="combobox"][data-part="item-group-label"] {} [data-scope="combobox"][data-part="item"] {} [data-scope="combobox"][data-part="item-text"] {} [data-scope="combobox"][data-part="item-indicator"] {} ``` If you wish to use the default Corex styling, you can use the class `combobox` on the component. This requires to install `Mix.Tasks.Corex.Design` first and import the component css file. ```css @import "../corex/main.css"; @import "../corex/tokens/themes/neo/light.css"; @import "../corex/components/combobox.css"; ``` You can then use modifiers ```heex <.combobox class="combobox combobox--accent combobox--lg" items={Corex.List.new([])}> <:empty>No results <:trigger> <.heroicon name="hero-chevron-down" /> ``` ''' defmodule Translation do @moduledoc """ Translation struct for Combobox component strings. Without gettext: `translation={%Combobox.Translation{ placeholder: "Select...", empty: "No results" }}` With gettext: `translation={%Combobox.Translation{ placeholder: gettext("Select..."), empty: gettext("No results") }}` """ defstruct [:placeholder, :empty] end @doc type: :component use Phoenix.Component import Corex.Gettext, only: [gettext: 1] import Corex.Helpers, only: [ validate_value!: 1, normalize_items: 1, has_groups?: 1, normalize_groups: 1, entry_value: 1 ] alias Phoenix.LiveView alias Phoenix.LiveView.JS alias Corex.Combobox.Anatomy.{ ClearTrigger, Content, Control, Empty, Input, Item, ItemGroup, ItemGroupLabel, ItemIndicator, ItemText, Label, List, Positioner, Props, Root, Trigger } alias Corex.Combobox.Connect @doc """ Renders a combobox component. """ attr(:id, :string, required: false, doc: "The id of the combobox, useful for API to identify the combobox" ) attr(:items, :list, default: [], doc: "Items from `Corex.List.new/1` (or maps with :id and :label)" ) attr(:value, :any, default: nil, doc: "Initial selected item ids (list of strings or a single string); not updated by LiveView after mount" ) attr(:controlled, :boolean, default: false, doc: "When true (e.g. LiveView playground), selection is driven from the server via `data-value` and the hook passes Zag `value` on updates. When false, only `data-default-value` is used for SSR and hook updates omit selection so client filter/typing stay stable." ) attr(:on_open_change, :string, default: nil, doc: "The server event name to trigger on open change" ) attr(:on_open_change_client, :string, default: nil, doc: "The client event name to trigger on open change" ) attr(:disabled, :boolean, default: false, doc: "Whether the combobox is disabled") attr(:translation, Corex.Combobox.Translation, default: nil, doc: "Override translatable strings" ) attr(:placeholder, :string, default: nil, doc: "Input placeholder; when nil, uses translation.placeholder" ) attr(:always_submit_on_enter, :boolean, default: false, doc: "Whether to always submit on enter" ) attr(:auto_focus, :boolean, default: false, doc: "Whether to auto focus the combobox") attr(:close_on_select, :boolean, default: true, doc: "Whether to close the combobox on select") attr(:dir, :string, default: nil, doc: "The direction of the combobox. When nil, derived from document (html lang + config :rtl_locales)" ) attr(:orientation, :string, default: "vertical", values: ["horizontal", "vertical"], doc: "Layout orientation for the combobox" ) attr(:input_behavior, :string, default: "autohighlight", doc: "The input behavior of the combobox" ) attr(:loop_focus, :boolean, default: false, doc: "Whether to loop focus the combobox") attr(:multiple, :boolean, default: false, doc: "Whether to allow multiple selection") attr(:invalid, :boolean, default: false, doc: "Whether the combobox is invalid") attr(:name, :string, doc: "The name of the combobox") attr(:form, :string, doc: "The id of the form of the combobox") attr(:read_only, :boolean, default: false, doc: "Whether the combobox is read only") attr(:required, :boolean, default: false, doc: "Whether the combobox is required") attr(:filter, :boolean, default: true, doc: "When true, filter options client-side by input value. Set to false when using on_input_value_change for server-side filtering" ) attr(:on_input_value_change, :string, default: nil, doc: "The server event name to trigger on input value change" ) attr(:on_value_change, :string, default: nil, doc: "The server event name to trigger on value change" ) attr(:on_value_change_client, :string, default: nil, doc: "The client event name to trigger on value change" ) attr(:redirect, :boolean, default: false, doc: """ When true, selecting a value triggers redirect-on-select. Each item picks the navigation kind via `:redirect` (`:href` (default) | `:patch` | `:navigate` | `false`). Items may also set `:to` (overrides the destination) and `:new_tab` (opens in a new tab). When true, the client runs single-select in Zag even if `multiple` is set on this component. """ ) attr(:positioning, :map, default: %Corex.Positioning{same_width: true}, doc: "The positioning of the combobox" ) attr(:trigger_aria_label, :string, default: nil, doc: "Accessible name for the open/close trigger button. Defaults to gettext(\"Open options\")." ) attr(:clear_trigger_aria_label, :string, default: nil, doc: "Accessible name for the clear trigger button. Defaults to gettext(\"Clear selection\")." ) attr(:rest, :global) slot :label, required: false, doc: "The label content" do attr(:class, :string, required: false) end slot :empty, required: false, doc: "Content when there are no results. When omitted, translation.empty is used" do attr(:class, :string, required: false) end slot :trigger, required: true, doc: "The trigger button content" do attr(:class, :string, required: false) end slot :clear_trigger, required: false, doc: "The clear button content" do attr(:class, :string, required: false) end slot :item_indicator, required: false, doc: "Optional indicator for selected items" do attr(:class, :string, required: false) end slot :error, required: false do attr(:class, :string, required: false) end slot :item, required: false, doc: "Custom content for each item. Receives the item as :let binding" do attr(:class, :string, required: false) end attr(:field, Phoenix.HTML.FormField, doc: "A form field struct retrieved from the form, for example: @form[:country]. Automatically sets id, name, value, and errors from the form field" ) attr(:errors, :list, default: [], doc: "List of error messages to display" ) def combobox(%{field: %Phoenix.HTML.FormField{} = field} = assigns) do errors = if Phoenix.Component.used_input?(field), do: field.errors, else: [] items = normalize_items(assigns.items) raw_value = get_value(field.value) value = normalize_value_to_ids(items, raw_value) selected_label = get_selected_label(items, value) assigns |> assign(:items, items) |> assign(field: nil) |> assign(:errors, Enum.map(errors, &Corex.Gettext.translate_error(&1))) |> assign_new(:id, fn -> field.id end) |> assign_new(:form, fn -> field.form.id end) |> assign_new(:name, fn -> field.name end) |> assign_new(:controlled, fn -> true end) |> assign(:value, value) |> assign(:selected_label, selected_label) |> combobox() end def combobox(assigns) do default_translation = %Translation{ placeholder: gettext("Select"), empty: gettext("No results") } translation = assigns[:translation] || default_translation placeholder = assigns[:placeholder] || translation.placeholder empty_text = translation.empty assigns = assigns |> assign_new(:id, fn -> "combobox-#{System.unique_integer([:positive])}" end) |> assign_new(:name, fn -> "name-#{System.unique_integer([:positive])}" end) |> assign_new(:form, fn -> nil end) |> assign_new(:dir, fn -> "ltr" end) |> assign_new(:controlled, fn -> false end) |> assign(:translation, translation) |> assign(:placeholder, placeholder) |> assign(:empty_text, empty_text) items = normalize_items(assigns.items) raw_initial = Map.get(assigns, :value) value_list = normalize_value_to_ids(items, get_value(raw_initial)) has_groups = has_groups?(items) groups = normalize_groups(items) selected_label = get_selected_label(items, value_list) assigns = assigns |> assign(:items, items) |> assign(:has_groups, has_groups) |> assign(:groups, groups) |> assign(:value, value_list) |> assign(:selected_label, selected_label) |> assign(:value_for_hidden_input, value_for_hidden_input(value_list, assigns.multiple)) ~H"""
{render_slot(@label)}
  • {if Enum.empty?(@empty), do: @empty_text, else: render_slot(@empty)}
  • {group_id}
    • {entry.label} {render_slot(@item, entry)} {render_slot(@item_indicator)}
  • {entry.label} {render_slot(@item, entry)} {render_slot(@item_indicator)}
{render_slot(@error, msg)}
  • {if Enum.empty?(@empty), do: @empty_text, else: render_slot(@empty)}
  • {group_id}
    • {entry.label} {render_slot(@item, entry)} {render_slot(@item_indicator)}
  • {entry.label} {render_slot(@item, entry)} {render_slot(@item_indicator)}
  • """ end defp item_attrs(id, entry, dir, orientation) do base = Connect.item(%Item{ id: id, item: entry, value: entry_value(entry), dir: dir, orientation: orientation, to: Map.get(entry, :to), redirect: Map.get(entry, :redirect), new_tab: Map.get(entry, :new_tab, false) }) if Map.get(entry, :disabled) do base |> Map.put("data-disabled", "") |> Map.put("aria-disabled", "true") else base end end defp item_attrs_template(id, entry, dir, orientation) do base = Connect.item_template(%Item{ id: id, item: entry, value: entry_value(entry), dir: dir, orientation: orientation, to: Map.get(entry, :to), redirect: Map.get(entry, :redirect), new_tab: Map.get(entry, :new_tab, false) }) if Map.get(entry, :disabled) do base |> Map.put("data-disabled", "") |> Map.put("aria-disabled", "true") else base end end defp get_value(field_value) do case field_value do nil -> [] [] -> [] value when is_list(value) -> Enum.map(value, &to_string/1) value -> [to_string(value)] end end defp normalize_value_to_ids(items, value_list) do Enum.map(value_list, &resolve_value_id(items, &1)) end defp resolve_value_id(items, val) do by_id = Enum.find(items, &(&1.id == val)) by_label = Enum.find(items, &(&1.label == val)) cond do by_id != nil -> val by_label != nil -> by_label.id true -> val end end defp get_selected_label(items, value) do case value do [] -> nil _ -> value |> Enum.map(fn val -> items |> Enum.find(&(&1.id == val)) end) |> Enum.filter(& &1) |> Enum.map(& &1.label) |> case do [] -> nil labels -> Enum.join(labels, ", ") end end end defp value_for_hidden_input(value_list, _multiple) when value_list == [], do: "" defp value_for_hidden_input(value_list, false), do: Elixir.List.first(value_list) defp value_for_hidden_input(value_list, true), do: Enum.join(value_list, ",") @doc type: :api @doc """ Sets combobox selection from the client. Dispatches `corex:combobox:set-value` on the hook root. """ def set_value(combobox_id, value) when is_binary(combobox_id) do JS.dispatch("corex:combobox:set-value", to: "##{combobox_id}", detail: %{value: normalize_combobox_set_value!(value)}, bubbles: false ) end @doc type: :api @doc """ Sets combobox selection from the server via `push_event` (`combobox_set_value`). """ def set_value(socket, combobox_id, value) when is_struct(socket, Phoenix.LiveView.Socket) and is_binary(combobox_id) do LiveView.push_event(socket, "combobox_set_value", %{ id: combobox_id, value: normalize_combobox_set_value!(value) }) end defp normalize_combobox_set_value!(value) when is_list(value), do: validate_value!(value) defp normalize_combobox_set_value!(value) when is_binary(value) do case String.trim(value) do "" -> [] trimmed -> trimmed |> String.split(",", trim: true) |> validate_value!() end end defp normalize_combobox_set_value!(value), do: validate_value!(Elixir.List.wrap(value)) end