# Add Menu (/docs/agent-ui/components/add-menu)

Use an add menu in a [composer](./composer.mdx) when there are several kinds of things to add and each needs a word of explanation. It's an icon button that opens a menu of items with icons and descriptions, grouped under labels, where an item can open a submenu of its own.

<Example caption="Press Add, then choose Add context to mention a file, or open Plugins, GitHub and choose Link issue. Upload file opens the file picker and attaches what you choose.">
  <AddMenuExample />

  ```tsx tab="React"
  "use client";
  import type { ComposerDraft } from "@kind-ui/agent-ui/core";
  import { type ReactNode, useRef, useState } from "react";
  import { AddMenu } from "@/components/ui/add-menu";
  import { Composer, ComposerAttachments, ComposerInput, ComposerSubmit } from "@/components/ui/composer";

  function Icon({ children }: { children: ReactNode }) {
    return (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        {children}
      </svg>
    );
  }

  const items = [
    {
      id: "upload",
      label: "Upload file",
      description: "Attach files from your computer",
      icon: (
        <Icon>
          <path d="M12 3v12" />
          <path d="m17 8-5-5-5 5" />
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
        </Icon>
      ),
    },
    {
      id: "context",
      label: "Add context",
      description: "Mention the open file",
      icon: (
        <Icon>
          <circle cx="12" cy="12" r="4" />
          <path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8" />
        </Icon>
      ),
    },
    {
      id: "github",
      label: "GitHub",
      group: "Plugins",
      icon: (
        <Icon>
          <circle cx="18" cy="18" r="3" />
          <circle cx="6" cy="6" r="3" />
          <path d="M13 6h3a2 2 0 0 1 2 2v7" />
          <path d="M6 9v12" />
        </Icon>
      ),
      items: [
        { id: "github-issue", label: "Link issue", description: "#128 Retries never stop" },
        { id: "github-pr", label: "Review pull request", description: "#131 Add backoff" },
      ],
    },
    {
      id: "docs",
      label: "Docs",
      group: "Plugins",
      icon: (
        <Icon>
          <path d="M12 7v14" />
          <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
        </Icon>
      ),
      items: [{ id: "docs-retries", label: "Retries guide", description: "Mention the page" }],
    },
  ];

  const inserts: Record<string, string> = {
    context: "[@client.ts](mention:src/client.ts)",
    "github-issue": "Fixes #128",
    "github-pr": "Review #131",
    "docs-retries": "[@Retries guide](mention:docs/retries)",
  };

  export default function AddMenuExample() {
    const [draft, setDraft] = useState<ComposerDraft>({ text: "", tokens: [], attachments: [] });
    const files = useRef<HTMLInputElement>(null);

    return (
      <>
        <Composer
          aria-label="Message"
          value={draft}
          onValueChange={setDraft}
          onSubmit={() => new Promise<void>((resolve) => setTimeout(resolve, 1000))}
        >
          <ComposerAttachments />
          <ComposerInput aria-label="Prompt" placeholder="Ask anything" />
          <AddMenu
            style={{ gridArea: "attach" }}
            items={items}
            onAction={(id) => {
              if (id === "upload") files.current?.click();
              else
                setDraft((draft) => ({
                  ...draft,
                  text: `${draft.text.trimEnd()} ${inserts[id]} `.trimStart(),
                }));
            }}
          />
          <ComposerSubmit />
        </Composer>
        <input
          ref={files}
          type="file"
          multiple
          hidden
          onChange={(event) => {
            const chosen = Array.from(event.target.files ?? [], (file) => ({
              id: crypto.randomUUID(),
              file,
              name: file.name,
              size: file.size,
              mediaType: file.type,
            }));
            setDraft((draft) => ({ ...draft, attachments: [...draft.attachments, ...chosen] }));
            event.target.value = "";
          }}
        />
      </>
    );
  }
  ```

  ```vue tab="Vue"
  <script setup lang="ts">
  import type { ComposerDraft } from "@kind-ui/agent-ui/core";
  import { h, shallowRef, type VNode } from "vue";
  import { AddMenu } from "@/components/ui/vue/add-menu";
  import { Composer, ComposerAttachments, ComposerInput, ComposerSubmit } from "@/components/ui/vue/composer";

  const icon = (...children: VNode[]) =>
    h(
      "svg",
      {
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: "currentColor",
        "stroke-width": "2",
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
        "aria-hidden": "true",
      },
      children,
    );

  const items = [
    {
      id: "upload",
      label: "Upload file",
      description: "Attach files from your computer",
      icon: icon(
        h("path", { d: "M12 3v12" }),
        h("path", { d: "m17 8-5-5-5 5" }),
        h("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }),
      ),
    },
    {
      id: "context",
      label: "Add context",
      description: "Mention the open file",
      icon: icon(
        h("circle", { cx: "12", cy: "12", r: "4" }),
        h("path", { d: "M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8" }),
      ),
    },
    {
      id: "github",
      label: "GitHub",
      group: "Plugins",
      icon: icon(
        h("circle", { cx: "18", cy: "18", r: "3" }),
        h("circle", { cx: "6", cy: "6", r: "3" }),
        h("path", { d: "M13 6h3a2 2 0 0 1 2 2v7" }),
        h("path", { d: "M6 9v12" }),
      ),
      items: [
        { id: "github-issue", label: "Link issue", description: "#128 Retries never stop" },
        { id: "github-pr", label: "Review pull request", description: "#131 Add backoff" },
      ],
    },
    {
      id: "docs",
      label: "Docs",
      group: "Plugins",
      icon: icon(
        h("path", { d: "M12 7v14" }),
        h("path", {
          d: "M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",
        }),
      ),
      items: [{ id: "docs-retries", label: "Retries guide", description: "Mention the page" }],
    },
  ];

  const inserts: Record<string, string> = {
    context: "[@client.ts](mention:src/client.ts)",
    "github-issue": "Fixes #128",
    "github-pr": "Review #131",
    "docs-retries": "[@Retries guide](mention:docs/retries)",
  };

  const draft = shallowRef<ComposerDraft>({ text: "", tokens: [], attachments: [] });
  const files = shallowRef<HTMLInputElement>();
  const send = () => new Promise<void>((resolve) => setTimeout(resolve, 1000));

  function add(id: string) {
    if (id === "upload") files.value?.click();
    else draft.value = { ...draft.value, text: `${draft.value.text.trimEnd()} ${inserts[id]} `.trimStart() };
  }

  function attach(event: Event) {
    const input = event.target as HTMLInputElement;
    const chosen = Array.from(input.files ?? [], (file) => ({
      id: crypto.randomUUID(),
      file,
      name: file.name,
      size: file.size,
      mediaType: file.type,
    }));
    draft.value = { ...draft.value, attachments: [...draft.value.attachments, ...chosen] };
    input.value = "";
  }
  </script>

  <template>
    <Composer v-model:value="draft" aria-label="Message" :on-submit="send">
      <ComposerAttachments />
      <ComposerInput aria-label="Prompt" placeholder="Ask anything" />
      <AddMenu style="grid-area: attach" :items="items" :on-action="add" />
      <ComposerSubmit />
    </Composer>
    <input ref="files" type="file" multiple hidden @change="attach" />
  </template>
  ```

  ```svelte tab="Svelte"
  <script lang="ts">
    import type { ComposerDraft } from "@kind-ui/agent-ui/core";
    import { AddMenu, type AddMenuEntry } from "@/components/ui/svelte/add-menu/index.js";
    import {
      Composer,
      ComposerAttachments,
      ComposerInput,
      ComposerSubmit,
    } from "@/components/ui/svelte/composer/index.js";

    const items: AddMenuEntry[] = [
      { id: "upload", label: "Upload file", description: "Attach files from your computer", icon: upload },
      { id: "context", label: "Add context", description: "Mention the open file", icon: context },
      {
        id: "github",
        label: "GitHub",
        group: "Plugins",
        icon: github,
        items: [
          { id: "github-issue", label: "Link issue", description: "#128 Retries never stop" },
          { id: "github-pr", label: "Review pull request", description: "#131 Add backoff" },
        ],
      },
      {
        id: "docs",
        label: "Docs",
        group: "Plugins",
        icon: docs,
        items: [{ id: "docs-retries", label: "Retries guide", description: "Mention the page" }],
      },
    ];

    const inserts: Record<string, string> = {
      context: "[@client.ts](mention:src/client.ts)",
      "github-issue": "Fixes #128",
      "github-pr": "Review #131",
      "docs-retries": "[@Retries guide](mention:docs/retries)",
    };

    let draft: ComposerDraft = $state.raw({ text: "", tokens: [], attachments: [] });
    let files: HTMLInputElement;
  </script>

  {#snippet upload()}
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <path d="M12 3v12" />
      <path d="m17 8-5-5-5 5" />
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
    </svg>
  {/snippet}

  {#snippet context()}
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <circle cx="12" cy="12" r="4" />
      <path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8" />
    </svg>
  {/snippet}

  {#snippet github()}
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <circle cx="18" cy="18" r="3" />
      <circle cx="6" cy="6" r="3" />
      <path d="M13 6h3a2 2 0 0 1 2 2v7" />
      <path d="M6 9v12" />
    </svg>
  {/snippet}

  {#snippet docs()}
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
      <path d="M12 7v14" />
      <path
        d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
      />
    </svg>
  {/snippet}

  <Composer
    aria-label="Message"
    bind:value={draft}
    onSubmit={() => new Promise<void>((resolve) => setTimeout(resolve, 1000))}
  >
    <ComposerAttachments />
    <ComposerInput aria-label="Prompt" placeholder="Ask anything" />
    <AddMenu
      style="grid-area: attach"
      {items}
      onAction={(id: string) => {
        if (id === "upload") files.click();
        else draft = { ...draft, text: `${draft.text.trimEnd()} ${inserts[id]} `.trimStart() };
      }}
    />
    <ComposerSubmit />
  </Composer>
  <input
    bind:this={files}
    type="file"
    multiple
    hidden
    onchange={(event) => {
      const chosen = Array.from(event.currentTarget.files ?? [], (file) => ({
        id: crypto.randomUUID(),
        file,
        name: file.name,
        size: file.size,
        mediaType: file.type,
      }));
      draft = { ...draft, attachments: [...draft.attachments, ...chosen] };
      event.currentTarget.value = "";
    }}
  />
  ```

  ```tsx tab="Solid"
  import type { ComposerDraft } from "@kind-ui/agent-ui/core";
  import type { JSX } from "@solidjs/web";
  import { createSignal } from "solid-js";
  import { AddMenu } from "@/components/ui/solid/add-menu";
  import { Composer, ComposerAttachments, ComposerInput, ComposerSubmit } from "@/components/ui/solid/composer";

  function Icon(props: { children: JSX.Element }) {
    return (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        {props.children}
      </svg>
    );
  }

  const items = [
    {
      id: "upload",
      label: "Upload file",
      description: "Attach files from your computer",
      icon: (
        <Icon>
          <path d="M12 3v12" />
          <path d="m17 8-5-5-5 5" />
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
        </Icon>
      ),
    },
    {
      id: "context",
      label: "Add context",
      description: "Mention the open file",
      icon: (
        <Icon>
          <circle cx="12" cy="12" r="4" />
          <path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8" />
        </Icon>
      ),
    },
    {
      id: "github",
      label: "GitHub",
      group: "Plugins",
      icon: (
        <Icon>
          <circle cx="18" cy="18" r="3" />
          <circle cx="6" cy="6" r="3" />
          <path d="M13 6h3a2 2 0 0 1 2 2v7" />
          <path d="M6 9v12" />
        </Icon>
      ),
      items: [
        { id: "github-issue", label: "Link issue", description: "#128 Retries never stop" },
        { id: "github-pr", label: "Review pull request", description: "#131 Add backoff" },
      ],
    },
    {
      id: "docs",
      label: "Docs",
      group: "Plugins",
      icon: (
        <Icon>
          <path d="M12 7v14" />
          <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
        </Icon>
      ),
      items: [{ id: "docs-retries", label: "Retries guide", description: "Mention the page" }],
    },
  ];

  const inserts: Record<string, string> = {
    context: "[@client.ts](mention:src/client.ts)",
    "github-issue": "Fixes #128",
    "github-pr": "Review #131",
    "docs-retries": "[@Retries guide](mention:docs/retries)",
  };

  export default function AddMenuExample() {
    const [draft, setDraft] = createSignal<ComposerDraft>({ text: "", tokens: [], attachments: [] });
    let files: HTMLInputElement | undefined;

    return (
      <>
        <Composer
          aria-label="Message"
          value={draft()}
          onValueChange={(value) => setDraft(value)}
          onSubmit={() => new Promise<void>((resolve) => setTimeout(resolve, 1000))}
        >
          <ComposerAttachments />
          <ComposerInput aria-label="Prompt" placeholder="Ask anything" />
          <AddMenu
            style={{ "grid-area": "attach" }}
            items={items}
            onAction={(id) => {
              if (id === "upload") files?.click();
              else
                setDraft((draft) => ({
                  ...draft,
                  text: `${draft.text.trimEnd()} ${inserts[id]} `.trimStart(),
                }));
            }}
          />
          <ComposerSubmit />
        </Composer>
        <input
          ref={(el) => {
            files = el;
          }}
          type="file"
          multiple
          hidden
          onChange={(event) => {
            const input = event.currentTarget;
            const chosen = Array.from(input.files ?? [], (file) => ({
              id: crypto.randomUUID(),
              file,
              name: file.name,
              size: file.size,
              mediaType: file.type,
            }));
            setDraft((draft) => ({ ...draft, attachments: [...draft.attachments, ...chosen] }));
            input.value = "";
          }}
        />
      </>
    );
  }
  ```
</Example>

## Installation [#installation]

```bash tab="React"
npx shadcn@latest add @kind-ui/add-menu
```

```bash tab="Web Components"
npx shadcn@latest add @kind-ui/add-menu-web
```

```bash tab="Vue"
npx shadcn@latest add @kind-ui/add-menu-vue
```

```bash tab="Svelte"
npx shadcn@latest add @kind-ui/add-menu-svelte
```

```bash tab="Solid"
npx shadcn@latest add @kind-ui/add-menu-solid
```

## Composition [#composition]

```text
AddMenu
├── AddMenuTrigger
└── AddMenuContent
    └── AddMenuRows
```

`AddMenu` is a group named by its `label`, around UI SDK's Menu. `AddMenuTrigger` is UI SDK's `MenuTrigger`, an icon button named by the `label` that shows a plus unless you pass children. `AddMenuContent` is UI SDK's `MenuContent`, and `AddMenuRows` draws one level of rows inside it: each group under its label, separated from the others, and a submenu for each item with `items`. `AddMenu` renders the trigger and content when you pass no children.

## Usage [#usage]

### Items [#items]

Pass `items`, each with an `id` and a `label`, and optionally a `description` (a second line under the label), an `icon`, a `group` and `disabled`. Items gather by `group`, in the order each group first appears, each under its label and separated from the next. Items without a `group` gather the same way, with no label. A disabled item stays in the menu, dimmed, and can't run. Every `id` must be unique, across submenus too.

In React, `icon` is an image URL or an element, like an inline `<svg>`. Icons are hidden from assistive technology, so the label names the row.

### Running Items [#running-items]

Pressing an item calls `onAction` with its `id` and closes the menu, with the reason `item-press` and `details.source` saying how it was pressed. Cancel it with `details.cancel()` to keep the menu open. Without `onAction`, every item is disabled.

```tsx
<AddMenu
  items={[{ id: "upload", label: "Upload file" }]}
  onAction={(id) => fileInput.current?.click()}
/>
```

The Add Menu doesn't attach anything itself. In the example above, the composer's draft is controlled with `value` and `onValueChange`, so **Upload file** adds the files a hidden file input picked to its attachments, and the other items add text to it.

### Submenus [#submenus]

Give an item `items` to make it open a submenu of them, marked with a chevron, like a plugin and its commands. Its `items` group the same way. An item with `items` opens its submenu and never calls `onAction`.

### Opening [#opening]

Pass `open` and `onOpenChange` to control whether the menu is open, or `defaultOpen` to start open. `onOpenChange` gets UI SDK Menu's reason, like `trigger-press` or `escape-key`. Set `disabled` to keep the button from opening the menu; it also closes an open one.

### Keyboard [#keyboard]

The button is one Tab stop. Enter, Space or Down Arrow opens the menu with focus on the first item, and the arrow keys move between items, skipping separators. Typing a letter moves to the next item whose label starts with it. Right Arrow opens a submenu, and Left Arrow or Escape closes only the submenu. Enter or Space runs an item, and Escape closes the menu, with focus back on the button.

### Presentation and Motion [#presentation-and-motion]

The menu opens as a popover below the button. With `presentation="auto"`, the default, it's a bottom sheet on small touch screens instead, where a submenu replaces the level and Left Arrow or Escape goes back; pass `"popover"` or `"sheet"` to choose one. The popover rises and fades in. Under `prefers-reduced-motion`, or with `motion="reduced"`, it only fades, over 120 ms, and with `motion="none"` it opens at once. The sheet slides up whatever the motion settings.

## API Reference [#api-reference]

### AddMenuOptions

| Prop            | Type                                                                                   | Description                                                                                                                                                                                                                                                                               |
| --------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label?`        | `string \| undefined`                                                                  | Names the trigger. Each menu has its own default. Names the trigger, an icon button. Default: `"Add"`                                                                                                                                                                                     |
| `open?`         | `boolean \| undefined`                                                                 | Whether the menu is open. Passing it controls it: change it in `onOpenChange`.                                                                                                                                                                                                            |
| `defaultOpen?`  | `boolean \| undefined`                                                                 | Whether the menu is open at first, when `open` isn't passed. Default: `false`                                                                                                                                                                                                             |
| `onOpenChange?` | `((open: boolean, details: ChangeDetails<MenuOpenChangeReason>) => void) \| undefined` | Called when the menu opens or closes, with UI SDK Menu's reason.                                                                                                                                                                                                                          |
| `presentation?` | `"auto" \| "popover" \| "sheet"`                                                       | How the menu presents. `"auto"` is a bottom sheet on small touch screens and a popover elsewhere. Default: `"auto"`                                                                                                                                                                       |
| `disabled?`     | `boolean \| undefined`                                                                 | Whether the trigger can't open the menu. Default: `false`                                                                                                                                                                                                                                 |
| `motion?`       | `"auto" \| "none" \| "reduced"`                                                        | How the menu opens and closes. `"auto"` follows `prefers-reduced-motion`. Default: `"auto"`                                                                                                                                                                                               |
| `items?`        | `MenuEntry<unknown>[] \| undefined`                                                    | What the menu offers, grouped by their `group` in the order groups first appear, each group under its label. An entry with `items` opens a submenu of them. Every `id` is unique across all levels. The primitive passes each `icon` through to the render layer untouched. Default: `[]` |
| `onAction?`     | `((id: string, details: ChangeDetails<AddMenuActionReason>) => void) \| undefined`     | Called when a person or `run` runs an item, by its `id`. Cancel it to keep the menu open. Without it, every item is disabled.                                                                                                                                                             |

Vue, Svelte and Solid take the same props. Controlled props and callbacks are spelled as each framework expects:

| React                  | Vue                            | Svelte                      | Solid                  |
| ---------------------- | ------------------------------ | --------------------------- | ---------------------- |
| `open`, `onOpenChange` | `v-model:open`, `@open-change` | `bind:open`, `onOpenChange` | `open`, `onOpenChange` |
| `onAction`             | `@action`                      | `onAction`                  | `onAction`             |

### Agent [#agent]

An agent connected with `createAgent` finds the add menu by its label and reads `open`. It lists every item it could run, in submenus too, by `id` and label. `run` takes an item's `id` and refuses an unknown or disabled one, or one that opens a submenu. It's offered only while `onAction` is set and the menu is enabled, and it leaves the menu open or closed as it was. `open` is offered while the menu is closed and enabled, and `close` while it's open. None needs a person to confirm.

### AddMenuAgentActions

| Prop    | Type                                     | Description                                                                                                                                                                                                            |
| ------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`  | `(() => boolean) \| undefined`           | Opens the menu. Offered only while it's closed and enabled. Returns whether the change was accepted.                                                                                                                   |
| `close` | `(() => boolean) \| undefined`           | Closes the menu. Offered only while it's open. Returns whether the change was accepted.                                                                                                                                |
| `run`   | `((id: string) => boolean) \| undefined` | Runs an item by its `id`, leaving the menu as it is. Offered only while `onAction` is set and the menu is enabled. Returns whether it ran: `false` for an unknown, disabled or submenu id, or one the owner cancelled. |

<Caption>
  Runs in React, Vue, Svelte, Solid and Web Components. On `<kind-add-menu label="Add" can-run>`, set `items` and `open` as properties, and listen for `addaction`, with the item's `id` as `event.detail.value`, and `openchange`. An item's `icon` is an image URL or an Element, which the element copies into its row. The element fills in its button and menu when it has no children.
</Caption>
