# Morph select

> A native form select enhanced into an anchored, searchable choice panel with a moving selected label.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/morph-select`
- File: `src/components/haze/ui/morph-select.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/morph-select

## Use when
- Named choices benefit from short descriptions and filtering
- A real select value must submit while the interface uses a richer choice panel

## Avoid when
- Use select for a short list that needs only native platform UI
- Use multi-select when more than one value may be chosen

## Alternatives
- [select](https://hazeui.com/ui/select.md)
- [combobox](https://hazeui.com/ui/combobox.md)
- [multi-select](https://hazeui.com/ui/multi-select.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied prefix for this component and its related elements. |
| name | `string` | id | no | Form submission name. |
| label | `string` | "Workspace" | no | Visible name of the selection. |
| options | `{ value: string; label: string; description?: string; disabled?: boolean }[]` | Studio, Platform and Support | no | Single-selection options with optional helper copy. |
| value | `string` |  | no | Initial selected value; otherwise the first enabled option. |
| searchable | `boolean` | true | no | Shows a filter field within the enhanced panel. |
| required | `boolean` |  | no | Enables native selection validation. |
| disabled | `boolean` |  | no | Disables the native control and its enhancement. |
| class | `string` |  | no | Additional classes for the component root. |
| ...attributes | `native control attributes` |  | no | Other attributes are forwarded to the real form control. |

## Accessibility
- A native select remains responsible for form values, disabled state, reset and validation; it is visible without enhancement.
- The enhanced panel uses a named listbox with selected states and disabled native option buttons.
- Native popover provides Escape and light dismissal; choosing a value returns focus to the trigger.
- Key Enter, Space, ArrowDown on trigger: Open the choices.
- Key ArrowUp, ArrowDown, Home, End: Move through available choices in the open panel.
- Key Enter, Escape: Choose a focused option or dismiss the panel.

## Agent prompts

### Install and use

Install the Haze UI component "Morph select" with `npx shadcn@latest add @haze/morph-select`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import MorphSelect from "@/components/haze/ui/morph-select.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/morph-select.md

### Customize with real content

Adapt the Haze morph-select ui for our product. Replace the demo values of these props with our real content: id, name, label, options, value, searchable, required, disabled, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: A native select remains responsible for form values, disabled state, reset and validation; it is visible without enhancement. The enhanced panel uses a named listbox with selected states and disabled native option buttons. Native popover provides Escape and light dismissal; choosing a value returns focus to the trigger. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using morph-select, check it fits: use it when named choices benefit from short descriptions and filtering; a real select value must submit while the interface uses a richer choice panel. Avoid it when use select for a short list that needs only native platform ui; use multi-select when more than one value may be chosen. Alternatives: @haze/select, @haze/combobox, @haze/multi-select.

## Example requests that should lead here
- Add a searchable workspace select with option descriptions and an animated selection label.

## Source

```astro
---
import { Check, ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Option { value: string; label: string; description?: string; disabled?: boolean }
interface Props {
  id: string;
  name?: string;
  label?: string;
  options?: Option[];
  value?: string;
  searchable?: boolean;
  required?: boolean;
  disabled?: boolean;
  class?: string;
  [key: string]: unknown;
}
const { id, name = id, label = "Workspace", options = [{ value: "studio", label: "Studio", description: "Design and exploration" }, { value: "platform", label: "Platform", description: "Engineering and releases" }, { value: "support", label: "Support", description: "Customer conversations" }], value, searchable = true, required, disabled, class: className, ...rest } = Astro.props;
const selected = options.find(option => option.value === value) ?? options.find(option => !option.disabled);
const field = "h-10 w-full min-w-0 rounded-lg border border-frame-input bg-field px-3 text-sm tracking-[-0.01em] text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden aria-invalid:border-destructive! aria-invalid:focus-visible:ring-destructive/24 disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50";
---

<div data-haze-morph-select class={cn("grid min-w-0 gap-2", className)}>
  <label id={`${id}-label`} for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
  <select {...rest} id={id} name={name} required={required} disabled={disabled} data-morph-native class={cn(field, "border-frame hover:border-frame-strong hover:bg-accent [&>option]:bg-popover [&>option]:text-popover-foreground")}>
    {options.map(option => <option value={option.value} disabled={option.disabled} selected={selected?.value === option.value}>{option.label}</option>)}
  </select>
  <button data-morph-trigger type="button" disabled={disabled} hidden popovertarget={`${id}-panel`} aria-haspopup="listbox" aria-expanded="false" aria-labelledby={`${id}-label ${id}-value`} style={`anchor-name: --${id}-select`} class={cn(field, "flex cursor-pointer border-frame hover:border-frame-strong hover:bg-accent items-center justify-between gap-2 text-start active:scale-[0.97] active:duration-75 [&[hidden]]:hidden")}><span id={`${id}-value`} data-morph-label class="truncate">{selected?.label ?? "Choose an option"}</span><ChevronDown aria-hidden="true" class="size-4 shrink-0 text-muted-foreground" /></button>
  <div id={`${id}-panel`} data-morph-panel popover style={`position-anchor: --${id}-select`} class="m-auto max-h-[min(24rem,calc(100dvh-2rem))] w-72 max-w-[calc(100vw-1rem)] supports-[position-area:block-end]:w-[anchor-size(width)] overflow-y-auto rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-float backdrop:bg-background/60 scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:mx-0 supports-[position-area:block-end]:my-1 supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]">
    {searchable && <input data-morph-search type="search" aria-label={`Filter ${label.toLowerCase()} options`} placeholder="Find an option…" class="-mx-1 -mt-1 mb-1 block h-10 w-[calc(100%+0.5rem)] min-w-0 border-0 border-b border-border bg-transparent px-4 text-[0.8125rem] text-foreground outline-hidden placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:hidden" />}
    <div id={`${id}-options`} role="listbox" aria-labelledby={`${id}-label`} class="grid gap-0.5">
      {options.map((option, index) => <button id={`${id}-option-${index}`} type="button" role="option" aria-selected={option.value === selected?.value ? "true" : "false"} disabled={option.disabled} data-morph-option data-value={option.value} data-label={option.label} class="flex min-h-10 min-w-0 cursor-pointer items-center gap-2 rounded-sm px-3 py-2 text-start transition-colors duration-75 hover:bg-accent focus:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-selected:bg-accent disabled:cursor-not-allowed disabled:opacity-50 [&[hidden]]:hidden"><span class="grid min-w-0 flex-1 gap-0.5"><span class="text-[0.8125rem]/5 font-medium wrap-anywhere">{option.label}</span>{option.description && <span class="text-[0.8125rem]/5 wrap-anywhere text-muted-foreground">{option.description}</span>}</span><Check aria-hidden="true" class="size-4 shrink-0 opacity-0 [[aria-selected=true]_&]:opacity-100" /></button>)}
    </div>
    <p data-morph-empty hidden class="p-3 text-[0.8125rem]/5 text-muted-foreground [&[hidden]]:hidden">No matching options.</p>
    <span data-morph-status role="status" class="sr-only"></span>
  </div>
</div>

<script>
  function initMorphSelects() {
    document.querySelectorAll<HTMLElement>("[data-haze-morph-select]").forEach(root => {
      if (root.hasAttribute("data-enhanced")) return;
      const select = root.querySelector<HTMLSelectElement>("[data-morph-native]");
      const trigger = root.querySelector<HTMLButtonElement>("[data-morph-trigger]");
      const label = root.querySelector<HTMLElement>("[data-morph-label]");
      const panel = root.querySelector<HTMLElement>("[data-morph-panel]");
      const search = root.querySelector<HTMLInputElement>("[data-morph-search]");
      const status = root.querySelector<HTMLElement>("[data-morph-status]");
      const empty = root.querySelector<HTMLElement>("[data-morph-empty]");
      const options = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-morph-option]"));
      if (!select || !trigger || !label || !panel || typeof panel.showPopover !== "function") return;
      const sync = () => { label.textContent = select.selectedOptions[0]?.label ?? "Choose an option"; options.forEach(option => option.setAttribute("aria-selected", String(option.dataset.value === select.value))); trigger.disabled = select.disabled; };
      const visible = () => options.filter(option => !option.hidden && !option.disabled);
      const filter = () => { const query = search?.value.toLocaleLowerCase().trim() ?? ""; options.forEach(option => { option.hidden = !(option.textContent ?? "").toLocaleLowerCase().includes(query); }); if (empty) empty.hidden = options.some(option => !option.hidden); if (status) status.textContent = `${visible().length} options available.`; };
      options.forEach(option => option.addEventListener("click", () => {
        select.value = option.dataset.value ?? "";
        select.dispatchEvent(new Event("input", { bubbles: true }));
        select.dispatchEvent(new Event("change", { bubbles: true }));
        sync();
        panel.hidePopover();
        trigger.focus();
        if (!matchMedia("(prefers-reduced-motion: reduce)").matches) label.animate([{ opacity: .4, translate: "0 3px" }, { opacity: 1, translate: "0 0" }], { duration: 200 });
      }));
      panel.addEventListener("toggle", event => {
        const open = (event as ToggleEvent).newState === "open";
        trigger.setAttribute("aria-expanded", String(open));
        if (open) { if (search) { search.value = ""; filter(); search.focus(); } else (options.find(option => option.dataset.value === select.value && !option.disabled) ?? visible()[0])?.focus(); }
      });
      search?.addEventListener("input", filter);
      panel.addEventListener("keydown", event => {
        const items = visible();
        const index = items.indexOf(document.activeElement as HTMLButtonElement);
        const next = event.key === "ArrowDown" ? (index + 1) % items.length : event.key === "ArrowUp" ? (index <= 0 ? items.length - 1 : index - 1) : event.key === "Home" && document.activeElement !== search ? 0 : event.key === "End" && document.activeElement !== search ? items.length - 1 : -1;
        if (next >= 0) { event.preventDefault(); items[next]?.focus(); }
        if (event.key === "Escape") { panel.hidePopover(); trigger.focus(); }
        if (event.key === "Tab") panel.hidePopover();
      });
      trigger.addEventListener("keydown", event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); panel.showPopover(); } });
      select.addEventListener("change", sync);
      select.addEventListener("invalid", event => { event.preventDefault(); trigger.focus(); trigger.setAttribute("aria-invalid", "true"); });
      select.form?.addEventListener("reset", () => queueMicrotask(sync));
      new MutationObserver(sync).observe(select, { attributes: true, attributeFilter: ["disabled"] });
      select.hidden = true;
      trigger.hidden = false;
      root.querySelector<HTMLLabelElement>("label")?.setAttribute("for", `${select.id}-trigger`);
      trigger.id = `${select.id}-trigger`;
      root.setAttribute("data-enhanced", "");
      sync();
    });
  }
  initMorphSelects();
  if (!document.documentElement.hasAttribute("data-haze-morph-select-listener")) {
    document.documentElement.setAttribute("data-haze-morph-select-listener", "");
    document.addEventListener("astro:page-load", initMorphSelects);
  }
</script>
```
