{
  "name": "entity-select",
  "type": "registry:ui",
  "framework": "react",
  "title": "Entity Select",
  "description": "The picker for a server's own members, roles and channels, with chips when more than one may be chosen.",
  "dependencies": [
    "radix-ui"
  ],
  "files": [
    {
      "path": "ui/entity-select.tsx",
      "content": "\"use client\"\n\nimport { Popover as PopoverPrimitive } from \"radix-ui\"\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/*\n * The picker for things the server already knows about: its members, its\n * roles, its channels, or all of them at once.\n *\n * It is a separate control from the string select rather than a mode of it,\n * because the rows are not strings. A member arrives with a face, a role with\n * a colour and a headcount, a channel with the glyph that says what kind of\n * channel it is — and when more than one can be chosen, the choices come back\n * out of the list and sit in the control as chips, which a string select\n * never does.\n */\n\n/** What the list is drawn from. Mentionable mixes members and roles. */\nexport type EntityKind = \"user\" | \"role\" | \"channel\" | \"mentionable\"\n\nexport interface EntityOption {\n  value: string\n  label: string\n  /** A member's avatar, or the glyph a role or channel is known by. */\n  icon?: React.ReactNode\n  /** Members carrying this role — shown beside the name, as the client does. */\n  count?: number\n  /** A short tag after the name. An app is the one that always has one. */\n  badge?: string\n  /** A role's colour, which its name takes in the list and in its chip. */\n  color?: string\n  disabled?: boolean\n}\n\n/**\n * What one of these may carry. The platform takes at most this many either\n * way — as the list it offers, and as the selection it accepts back.\n */\nexport const ENTITY_SELECT_MAX = 25\n\nexport interface EntitySelectProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"onSelect\" | \"defaultValue\"\n> {\n  options: readonly EntityOption[]\n  /** Which of the four this is. Only the empty-list wording depends on it. */\n  kind?: EntityKind\n  /** Controlled selection. Leave undefined to let the control own it. */\n  value?: readonly string[]\n  defaultValue?: readonly string[]\n  onValueChange?: (value: readonly string[]) => void\n  /** How many may be chosen. More than one turns the control into chips. */\n  max?: number\n  placeholder?: string\n  disabled?: boolean\n  /** Accessible name of the trigger and the listbox. */\n  label?: string\n  /** Shown when the list is empty. Defaults to a line for each `kind`. */\n  emptyLabel?: string\n  /**\n   * The element the panel is portalled into. Defaults to `document.body`;\n   * pass the enclosing native `<dialog>` or a themed wrapper to keep it there.\n   */\n  container?: React.ComponentProps<typeof PopoverPrimitive.Portal>[\"container\"]\n}\n\nconst EMPTY = {\n  user: \"No members to show\",\n  role: \"No roles to show\",\n  channel: \"No channels to show\",\n  mentionable: \"Nothing to show\",\n} as const satisfies Record<EntityKind, string>\n\n/** The headcount beside a role, which is a number and the glyph for people. */\nfunction Headcount({ count }: { readonly count: number }) {\n  return (\n    <span className=\"flex shrink-0 items-center gap-1 text-xs tabular-nums text-newt-text-muted\">\n      <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" className=\"h-3.5 w-3.5\">\n        <path\n          fill=\"currentColor\"\n          d=\"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.9 0-7 2-7 4.5V20h14v-1.5c0-2.5-3.1-4.5-7-4.5Z\"\n        />\n      </svg>\n      {count}\n    </span>\n  )\n}\n\n/*\n * Radix Popover owns the panel: outside press, Escape, collision-aware\n * placement and the portal. The listbox inside it stays hand-written, because\n * Radix has no listbox that takes more than one value: focus never leaves the\n * control, and `aria-activedescendant` names the row the keyboard is on.\n */\nconst EntitySelect = React.forwardRef<HTMLDivElement, EntitySelectProps>(\n  (\n    {\n      className,\n      options: given,\n      kind = \"user\",\n      value,\n      defaultValue = [],\n      onValueChange,\n      max = 1,\n      placeholder = \"Make a selection\",\n      disabled = false,\n      label = \"Select an option\",\n      emptyLabel,\n      container,\n      ...props\n    },\n    ref\n  ) => {\n    /* The cap is applied here: the keyboard and the option ids count rows, and\n     * a row the platform would reject should not be one of them. */\n    const options = React.useMemo(\n      () => given.slice(0, ENTITY_SELECT_MAX),\n      [given]\n    )\n    const limit = Math.min(max, ENTITY_SELECT_MAX)\n    const multiple = limit > 1\n\n    const id = React.useId()\n    const listboxId = `${id}-listbox`\n    const optionId = (index: number) => `${id}-option-${index}`\n\n    const triggerRef = React.useRef<HTMLButtonElement>(null)\n    const listRef = React.useRef<HTMLUListElement>(null)\n\n    const [open, setOpen] = React.useState(false)\n    const [active, setActive] = React.useState(-1)\n    const [uncontrolled, setUncontrolled] =\n      React.useState<readonly string[]>(defaultValue)\n    const selected = value ?? uncontrolled\n\n    const chosen = React.useMemo(\n      () => options.filter((option) => selected.includes(option.value)),\n      [options, selected]\n    )\n\n    const commit = React.useCallback(\n      (next: readonly string[]) => {\n        if (value === undefined) setUncontrolled(next)\n        onValueChange?.(next)\n      },\n      [value, onValueChange]\n    )\n\n    const selectable = React.useCallback(\n      (index: number) => Boolean(options[index]) && !options[index].disabled,\n      [options]\n    )\n\n    const firstSelectable = React.useCallback(\n      () => options.findIndex((option) => !option.disabled),\n      [options]\n    )\n\n    const lastSelectable = React.useCallback(() => {\n      for (let i = options.length - 1; i >= 0; i--) {\n        if (!options[i].disabled) return i\n      }\n      return -1\n    }, [options])\n\n    const step = React.useCallback(\n      (from: number, direction: 1 | -1) => {\n        const count = options.length\n        for (let i = 1; i <= count; i++) {\n          const index = (from + direction * i + count * i) % count\n          if (selectable(index)) return index\n        }\n        return from\n      },\n      [options.length, selectable]\n    )\n\n    const scrollToActive = (index: number) => {\n      listRef.current\n        ?.querySelector(`#${CSS.escape(optionId(index))}`)\n        ?.scrollIntoView({ block: \"nearest\" })\n    }\n\n    React.useEffect(() => {\n      if (active < 0) return\n      scrollToActive(active)\n      // eslint-disable-next-line react-hooks/exhaustive-deps -- optionId is derived from a stable id\n    }, [active])\n\n    const openMenu = () => {\n      if (disabled || open) return\n      setOpen(true)\n      const current = options.findIndex((option) =>\n        selected.includes(option.value)\n      )\n      setActive(\n        current >= 0 && selectable(current) ? current : firstSelectable()\n      )\n    }\n\n    const closeMenu = () => {\n      setOpen(false)\n      setActive(-1)\n    }\n\n    const toggle = (index: number) => {\n      const option = options[index]\n      if (!option || option.disabled) return\n      if (!multiple) {\n        commit([option.value])\n        closeMenu()\n        triggerRef.current?.focus()\n        return\n      }\n      /*\n       * At the limit the list stays open and stops taking more, rather than\n       * silently dropping the oldest choice: the reader picked those, and a\n       * control that quietly un-picks one is a control that lies.\n       */\n      const already = selected.includes(option.value)\n      if (!already && selected.length >= limit) return\n      commit(\n        already\n          ? selected.filter((each) => each !== option.value)\n          : [...selected, option.value]\n      )\n    }\n\n    const remove = (entity: string) => {\n      commit(selected.filter((each) => each !== entity))\n    }\n\n    const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {\n      switch (event.key) {\n        case \"ArrowDown\":\n        case \"ArrowUp\": {\n          event.preventDefault()\n          if (!open) {\n            openMenu()\n            return\n          }\n          setActive((current) =>\n            step(current, event.key === \"ArrowDown\" ? 1 : -1)\n          )\n          return\n        }\n        case \"Home\":\n          if (!open) return\n          event.preventDefault()\n          setActive(firstSelectable())\n          return\n        case \"End\":\n          if (!open) return\n          event.preventDefault()\n          setActive(lastSelectable())\n          return\n        case \"Enter\":\n        case \" \": {\n          event.preventDefault()\n          if (!open) {\n            openMenu()\n            return\n          }\n          if (active >= 0) toggle(active)\n          return\n        }\n        case \"Backspace\": {\n          /* The chip nearest the caret goes first, which is the last one. */\n          if (!multiple || open || chosen.length === 0) return\n          event.preventDefault()\n          const last = chosen[chosen.length - 1]\n          if (last) remove(last.value)\n          return\n        }\n        default:\n      }\n    }\n\n    return (\n      <PopoverPrimitive.Root\n        open={open}\n        onOpenChange={(next) => (next ? openMenu() : closeMenu())}\n      >\n        <div\n          ref={ref}\n          className={cn(\"w-full max-w-[420px]\", className)}\n          {...props}\n        >\n          {/*\n           * An anchor rather than a trigger: a popover trigger announces a\n           * dialog, and this control is a combobox that opens a listbox.\n           */}\n          <PopoverPrimitive.Anchor asChild>\n            <button\n              ref={triggerRef}\n              type=\"button\"\n              role=\"combobox\"\n              aria-haspopup=\"listbox\"\n              aria-expanded={open}\n              aria-controls={open ? listboxId : undefined}\n              aria-activedescendant={\n                open && active >= 0 ? optionId(active) : undefined\n              }\n              aria-label={label}\n              disabled={disabled}\n              onClick={() => (open ? closeMenu() : openMenu())}\n              onKeyDown={onKeyDown}\n              className={cn(\n                \"flex w-full items-center gap-2 rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-base px-3 py-2 text-start text-sm text-newt-text-secondary\",\n                \"transition-colors duration-fast ease-newt hover:border-newt-text-muted\",\n                \"focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-newt-text-link\",\n                open && \"border-newt-text-link\",\n                disabled && \"cursor-not-allowed opacity-50\"\n              )}\n            >\n              <span className=\"flex min-w-0 flex-1 flex-wrap items-center gap-1.5\">\n                {chosen.length === 0 ? (\n                  <span className=\"text-newt-text-muted\">{placeholder}</span>\n                ) : multiple ? (\n                  chosen.map((option) => (\n                    /*\n                     * A chip is not a button: it sits inside one, and nesting\n                     * two would be markup a keyboard cannot untangle. Its\n                     * cross is decorative, and Backspace is the way in from\n                     * the keyboard.\n                     */\n                    <span\n                      key={option.value}\n                      onMouseDown={(event) => {\n                        event.preventDefault()\n                        event.stopPropagation()\n                        remove(option.value)\n                      }}\n                      className=\"flex items-center gap-1.5 rounded-[var(--newt-radius-sm)] bg-newt-bg-elevated px-1.5 py-1 text-xs text-newt-text-primary\"\n                    >\n                      {option.icon ? (\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"flex h-4 w-4 shrink-0\"\n                        >\n                          {option.icon}\n                        </span>\n                      ) : null}\n                      <span\n                        style={\n                          option.color ? { color: option.color } : undefined\n                        }\n                      >\n                        {option.label}\n                      </span>\n                      <svg\n                        viewBox=\"0 0 24 24\"\n                        aria-hidden=\"true\"\n                        className=\"h-3 w-3\"\n                      >\n                        <path\n                          fill=\"currentColor\"\n                          d=\"M7.05 5.64a1 1 0 0 1 1.41 0L12 9.17l3.54-3.53a1 1 0 1 1 1.41 1.41L13.41 10.6l3.54 3.53a1 1 0 0 1-1.41 1.42L12 12.01l-3.54 3.54a1 1 0 0 1-1.41-1.42l3.53-3.53-3.53-3.54a1 1 0 0 1 0-1.42Z\"\n                        />\n                      </svg>\n                    </span>\n                  ))\n                ) : (\n                  <span className=\"flex min-w-0 items-center gap-2\">\n                    {chosen[0]?.icon ? (\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"flex h-5 w-5 shrink-0\"\n                      >\n                        {chosen[0].icon}\n                      </span>\n                    ) : null}\n                    <span\n                      className=\"truncate text-newt-text-primary\"\n                      style={\n                        chosen[0]?.color\n                          ? { color: chosen[0].color }\n                          : undefined\n                      }\n                    >\n                      {chosen[0]?.label}\n                    </span>\n                  </span>\n                )}\n              </span>\n\n              <svg\n                viewBox=\"0 0 24 24\"\n                aria-hidden=\"true\"\n                className={cn(\n                  \"h-[18px] w-[18px] shrink-0\",\n                  open && \"rotate-180\"\n                )}\n              >\n                <path\n                  fill=\"currentColor\"\n                  d=\"M5.3 9.3a1 1 0 0 1 1.4 0l5.3 5.29 5.3-5.3a1 1 0 1 1 1.4 1.42l-6 6a1 1 0 0 1-1.4 0l-6-6a1 1 0 0 1 0-1.42Z\"\n                />\n              </svg>\n            </button>\n          </PopoverPrimitive.Anchor>\n        </div>\n\n        <PopoverPrimitive.Portal container={container}>\n          <PopoverPrimitive.Content\n            /*\n             * Not the dialog Radix makes of a popover: the control names the\n             * listbox inside with `aria-controls`, and this is only its frame.\n             */\n            role=\"presentation\"\n            align=\"start\"\n            sideOffset={4}\n            /*\n             * Focus stays on the control: aria-activedescendant drives the\n             * list, so the panel must never take it. The row in force is\n             * brought into view here, once the list exists.\n             */\n            onOpenAutoFocus={(event) => {\n              event.preventDefault()\n              if (active >= 0) scrollToActive(active)\n            }}\n            /*\n             * A press on the control is not a press outside: its own click\n             * handler closes the list, and dismissing here as well would let\n             * that click open it again.\n             */\n            onInteractOutside={(event) => {\n              const target = event.target\n              if (\n                target instanceof Node &&\n                triggerRef.current?.contains(target)\n              ) {\n                event.preventDefault()\n              }\n            }}\n            onMouseDown={(event) => event.preventDefault()}\n            className=\"z-[110] w-[var(--radix-popover-trigger-width)] rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-floating p-1.5 shadow-elevation-high outline-none\"\n          >\n            <ul\n              ref={listRef}\n              id={listboxId}\n              role=\"listbox\"\n              aria-label={label}\n              aria-multiselectable={multiple || undefined}\n              /*\n               * The scrollbar shows rather than hiding until the pointer\n               * moves: the list is capped at 25, so the bar is what says\n               * there is more of it below the fold.\n               */\n              className={cn(\n                \"m-0 max-h-[300px] list-none overflow-y-auto p-0\",\n                \"[scrollbar-width:thin] [scrollbar-color:var(--newt-bg-active)_transparent]\",\n                \"[&::-webkit-scrollbar]:w-2\",\n                \"[&::-webkit-scrollbar-track]:bg-transparent\",\n                \"[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-newt-bg-active [&::-webkit-scrollbar-thumb]:bg-clip-padding\",\n                \"[&::-webkit-scrollbar-thumb:hover]:bg-newt-text-muted [&::-webkit-scrollbar-thumb:hover]:bg-clip-padding\"\n              )}\n            >\n              {options.length === 0 ? (\n                <li className=\"px-2.5 py-2 text-sm text-newt-text-muted\">\n                  {emptyLabel ?? EMPTY[kind]}\n                </li>\n              ) : (\n                options.map((option, index) => {\n                  const picked = selected.includes(option.value)\n                  const highlighted = index === active && !option.disabled\n                  return (\n                    <li\n                      key={option.value}\n                      id={optionId(index)}\n                      role=\"option\"\n                      aria-selected={picked}\n                      aria-disabled={option.disabled || undefined}\n                      onMouseEnter={() => {\n                        if (!option.disabled) setActive(index)\n                      }}\n                      onClick={() => toggle(index)}\n                      className={cn(\n                        \"flex cursor-pointer items-center gap-2.5 rounded-[var(--newt-radius-sm)] px-2.5 py-2 text-sm text-newt-text-secondary\",\n                        highlighted && \"bg-newt-bg-elevated\",\n                        picked && \"text-newt-text-primary\",\n                        option.disabled &&\n                          \"cursor-not-allowed bg-transparent text-newt-text-muted opacity-50\"\n                      )}\n                    >\n                      {option.icon ? (\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"flex h-6 w-6 shrink-0 items-center justify-center\"\n                        >\n                          {option.icon}\n                        </span>\n                      ) : null}\n\n                      <span\n                        className=\"min-w-0 flex-1 truncate font-medium\"\n                        style={\n                          option.color ? { color: option.color } : undefined\n                        }\n                      >\n                        {option.label}\n                      </span>\n\n                      {option.count === undefined ? null : (\n                        <Headcount count={option.count} />\n                      )}\n\n                      {option.badge === undefined ? null : (\n                        <span className=\"shrink-0 rounded-[var(--newt-radius-sm)] bg-newt-brand px-1 py-0.5 text-[10px] font-bold uppercase leading-none text-newt-on-accent\">\n                          {option.badge}\n                        </span>\n                      )}\n\n                      {/*\n                       * A box rather than a tick, and only when more than one\n                       * may be chosen: the shape says whether picking this one\n                       * un-picks the last.\n                       */}\n                      {multiple ? (\n                        <span\n                          aria-hidden=\"true\"\n                          data-checked={picked || undefined}\n                          className={cn(\n                            \"flex h-5 w-5 shrink-0 items-center justify-center rounded-[var(--newt-radius-sm)] border-2 border-newt-text-muted\",\n                            \"data-[checked]:border-newt-brand data-[checked]:bg-newt-brand\"\n                          )}\n                        >\n                          {picked ? (\n                            <svg viewBox=\"0 0 16 16\" className=\"h-3.5 w-3.5\">\n                              <path\n                                fill=\"#fff\"\n                                d=\"M6.2 11.6 3.1 8.5a1 1 0 0 1 1.4-1.4l1.7 1.7 4.3-4.3a1 1 0 1 1 1.4 1.4l-5 5a1 1 0 0 1-1.4 0Z\"\n                              />\n                            </svg>\n                          ) : null}\n                        </span>\n                      ) : null}\n                    </li>\n                  )\n                })\n              )}\n            </ul>\n          </PopoverPrimitive.Content>\n        </PopoverPrimitive.Portal>\n      </PopoverPrimitive.Root>\n    )\n  }\n)\nEntitySelect.displayName = \"EntitySelect\"\n\nexport { EntitySelect }\n",
      "type": "registry:ui"
    }
  ]
}