Skip to content
Shaken UI
Sign in

Morph Menu

Save

A round icon button that grows into its own menu panel, with its icon turning into a close mark and the items sliding in from the button's side.

Category
Overlays
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Morph Menu preview

Installation

npx @shakenui/cli add morph-menu

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add morph-menu --dry-run

Usage

morph-menu-example.tsx
"use client";

import { MorphMenu, MorphMenuItem, MorphMenuSeparator } from "@/components/shaken/ui/morph-menu";

function Icon({ d }: { d: string }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
      <path d={d} stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

export default function MorphMenuExample() {
  return (
    <div className="w-full max-w-md rounded-xl border border-zinc-950/10 bg-white p-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]">
      <label htmlFor="morph-menu-prompt" className="sr-only">
        Message
      </label>
      <textarea
        id="morph-menu-prompt"
        rows={2}
        placeholder="Ask the agent to change something"
        className="block w-full resize-none bg-transparent px-2 pt-1.5 text-sm text-zinc-950 outline-none placeholder:text-zinc-400 dark:text-white dark:placeholder:text-zinc-500"
      />
      <div className="flex items-center justify-between">
        <MorphMenu label="Add to message" side="top" align="start">
          <MorphMenuItem
            icon={<Icon d="M9.5 2.5H5A1.5 1.5 0 0 0 3.5 4v8A1.5 1.5 0 0 0 5 13.5h6a1.5 1.5 0 0 0 1.5-1.5V5.5l-3-3ZM9.5 2.5v3h3" />}
            shortcut="⌘U"
          >
            Upload a file
          </MorphMenuItem>
          <MorphMenuItem icon={<Icon d="M2.5 5.5v-2h2M11.5 3.5h2v2M13.5 10.5v2h-2M4.5 12.5h-2v-2M6 8h4" />} shortcut="⌘⇧S">
            Take a screenshot
          </MorphMenuItem>
          <MorphMenuItem
            icon={<Icon d="M5 3.5v9M5 12.5a1.5 1.5 0 1 0 0-3M11 6.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm0 0c0 2.5-2 3-6 3.5" />}
          >
            Reference a branch
          </MorphMenuItem>
          <MorphMenuSeparator />
          <MorphMenuItem icon={<Icon d="M3 4.5h10M3 8h10M3 11.5h6" />}>Start from a template</MorphMenuItem>
        </MorphMenu>
        <button
          type="button"
          aria-label="Send"
          className="inline-flex size-8 items-center justify-center rounded-full bg-zinc-950 text-white transition-colors duration-150 ease-out hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:bg-white dark:text-black dark:hover:bg-zinc-200"
        >
          <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
            <path d="M8 13V3M3.5 7.5 8 3l4.5 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
labelstring—Names the round trigger for screen readers, and appears as quiet text in the panel's corner row.
iconReactNodeplusTrigger icon. It turns 45 degrees as the panel opens, so the default plus becomes the close mark in the same spot.
side"top" | "bottom""top"Side the panel grows toward. Flips when there is not enough room.
align"start" | "end""start"Edge of the button the panel lines up with. Flips when there is not enough room.
open / defaultOpen / onOpenChangeBase UI Menu.Root—Open state, controlled or not.
className / triggerClassNamestring—Classes for the panel and for the round trigger.
icon / shortcut / destructiveReactNode / ReactNode / boolean—MorphMenuItem: a 16px icon, a shortcut hint, and the destructive style.

Accessibility

  • Built on Base UI Menu: the trigger has aria-haspopup and aria-expanded, the panel is role="menu", and items are menuitems.
  • Arrow keys move the highlight, typeahead jumps to items, Home and End go to the ends, Enter or Space activates, and Escape closes and returns focus to the trigger.
  • The turned icon in the panel's corner is aria-hidden and closes the menu on click, so clicking where the button was never activates an item; keyboard users close with Escape.
  • The highlight follows pointer and keys instantly; only opening and closing animate.
  • With reduced motion preferred, the panel appears and disappears without the morph, rotation, or item slide.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/morph-menu.tsxmorph-menu
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/morph-menu/0.1.0.json.

ui/morph-menu.tsxShow
ui/morph-menu.tsx
"use client";

import { Menu as BaseMenu } from "@base-ui/react/menu";
import { Children, type ComponentProps, type CSSProperties, type ReactNode, useRef } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

function PlusIcon() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
      <path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

// The trigger and the collapsed panel share one recipe, so the hand-off at either end is invisible.
const buttonSurface = cx(
  "border border-zinc-950/12 bg-white text-zinc-700 shadow-[0_1px_2px_rgb(0_0_0/0.06)]",
  "dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:shadow-none",
);

// Which corner of the panel sits on the trigger, read from the resolved side and alignment.
const corner = cx(
  "group-data-[side=top]/morph-menu:bottom-0 group-data-[side=bottom]/morph-menu:top-0",
  "group-data-[align=start]/morph-menu:left-0 group-data-[align=end]/morph-menu:right-0",
);

export interface MorphMenuProps extends Omit<BaseMenu.Root.Props, "children"> {
  /** Names the round trigger button for screen readers, for example "Create". */
  label: string;
  /**
   * Icon in the trigger. As the panel grows out of the button the icon turns 45 degrees and dims,
   * so the default plus becomes the panel's close mark in the same spot.
   */
  icon?: ReactNode;
  /** Side the panel grows toward. Flips when there is not enough room. */
  side?: "top" | "bottom";
  /** Edge of the trigger the panel lines up with. Flips when there is not enough room. */
  align?: "start" | "end";
  /** MorphMenuItem and MorphMenuSeparator elements. */
  children: ReactNode;
  /** Classes for the panel. */
  className?: string;
  /** Classes for the round trigger button. */
  triggerClassName?: string;
  /** Element to portal into. Defaults to `document.body`. */
  container?: BaseMenu.Portal.Props["container"];
}

/**
 * A round icon button that grows into its own menu. The button's shape stretches into the panel
 * with a slight overshoot, its icon turns and fades, and the items slide in with a short blur,
 * nearest the button first. Closing gathers the panel back into the button after a small
 * outward breath. Built on Base UI Menu: arrow keys, typeahead, Home and End, Escape, and focus
 * returning to the button all work as in any menu.
 */
export function MorphMenu({
  label,
  icon = <PlusIcon />,
  side = "top",
  align = "start",
  children,
  className,
  triggerClassName,
  container,
  actionsRef: actionsRefProp,
  ...props
}: MorphMenuProps) {
  const items = Children.toArray(children);
  const ownActions = useRef<BaseMenu.Root.Actions | null>(null);
  const actionsRef = actionsRefProp ?? ownActions;
  return (
    <BaseMenu.Root actionsRef={actionsRef} {...props}>
      <BaseMenu.Trigger
        aria-label={label}
        className={cx(
          "relative inline-flex size-10 shrink-0 cursor-default items-center justify-center rounded-full select-none",
          buttonSurface,
          "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-reduce:transition-none motion-safe:active:scale-[0.95]",
          "hover:border-zinc-950/20 hover:text-zinc-950 dark:hover:border-white/25 dark:hover:text-white",
          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
          triggerClassName,
        )}
      >
        {icon}
      </BaseMenu.Trigger>
      <BaseMenu.Portal container={container}>
        <BaseMenu.Positioner
          side={side}
          align={align}
          // Overlap the trigger exactly: the panel's corner is the button.
          sideOffset={({ anchor }) => -anchor.height}
          collisionAvoidance={{ side: "flip", align: "flip", fallbackAxisSide: "none" }}
          className="z-50 outline-none"
        >
          <BaseMenu.Popup
            className={withBase(
              cx(
                "group/morph-menu relative isolate min-w-56 p-1.5 text-sm text-zinc-950 outline-none dark:text-white",
                // The popup itself only fades in the last moment of closing, so Base UI waits for the whole morph.
                "transition-opacity duration-0 data-[ending-style]:opacity-0 data-[ending-style]:delay-220 data-[ending-style]:duration-60",
                "motion-reduce:data-[ending-style]:delay-0 motion-reduce:data-[ending-style]:duration-100",
              ),
              className,
            )}
          >
            {/* The surface grows from the trigger's 40px circle to the full panel. */}
            <span
              aria-hidden="true"
              className={cx(
                "absolute -z-10 size-full rounded-xl",
                corner,
                buttonSurface,
                "shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)] dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
                // Open: 380ms with a slight overshoot. Close: 260ms that first breathes out, then gathers in.
                "transition-[width,height,border-radius,box-shadow] duration-380 ease-[cubic-bezier(0.32,1.3,0.48,1)] motion-reduce:transition-none",
                "group-data-[starting-style]/morph-menu:size-10 group-data-[starting-style]/morph-menu:rounded-[20px] group-data-[starting-style]/morph-menu:shadow-[0_1px_2px_rgb(0_0_0/0.06)]",
                "group-data-[ending-style]/morph-menu:size-10 group-data-[ending-style]/morph-menu:rounded-[20px] group-data-[ending-style]/morph-menu:shadow-[0_1px_2px_rgb(0_0_0/0.06)]",
                "group-data-[ending-style]/morph-menu:duration-260 group-data-[ending-style]/morph-menu:ease-[cubic-bezier(0.5,-0.35,0.4,1)]",
                "dark:group-data-[starting-style]/morph-menu:shadow-none dark:group-data-[ending-style]/morph-menu:shadow-none",
              )}
            />
            {/* Items first, then a row that keeps the button's corner clear (reversed when the panel opens downward). */}
            <div className="flex flex-col group-data-[side=bottom]/morph-menu:flex-col-reverse">
              <div className="grid">
                {items.map((child, index) => (
                  <div
                    key={index}
                    className="contents"
                    // Items nearest the button arrive first.
                    style={{ "--morph-order": side === "top" ? items.length - 1 - index : index } as CSSProperties}
                  >
                    {child}
                  </div>
                ))}
              </div>
              <div
                aria-hidden="true"
                className={cx(
                  "flex h-[34px] items-center text-xs text-zinc-500 select-none",
                  "group-data-[align=start]/morph-menu:pl-[34px] group-data-[align=end]/morph-menu:justify-end group-data-[align=end]/morph-menu:pr-[34px]",
                  rowMotion,
                )}
              >
                <span className="px-2">{label}</span>
              </div>
            </div>
            {/* The trigger's icon, drawn on the panel where the button was. It turns 45 degrees and dims as the
                panel opens, and closes the menu when clicked (keyboard users close with Escape). */}
            <span
              aria-hidden="true"
              onClick={() => actionsRef.current?.close()}
              className={cx(
                "absolute flex size-10 items-center justify-center rounded-full text-zinc-500 dark:text-zinc-400",
                corner,
                "rotate-45 hover:text-zinc-950 dark:hover:text-white",
                "transition-[rotate,color] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                "group-data-[starting-style]/morph-menu:rotate-0 group-data-[starting-style]/morph-menu:text-zinc-700 dark:group-data-[starting-style]/morph-menu:text-zinc-300",
                "group-data-[ending-style]/morph-menu:rotate-0 group-data-[ending-style]/morph-menu:text-zinc-700 dark:group-data-[ending-style]/morph-menu:text-zinc-300",
                "group-data-[ending-style]/morph-menu:duration-220",
              )}
            >
              {icon}
            </span>
          </BaseMenu.Popup>
        </BaseMenu.Positioner>
      </BaseMenu.Portal>
    </BaseMenu.Root>
  );
}

// Each row slides a few pixels from the button's side with a short blur, staggered 28ms apart.
// Closing drops the stagger and fades them fast, before the surface gathers in.
const rowMotion = cx(
  "transition-[opacity,translate,filter] duration-280 ease-[cubic-bezier(0.23,1,0.32,1)] [transition-delay:calc(70ms+var(--morph-order,0)*28ms)] motion-reduce:transition-none",
  "group-data-[starting-style]/morph-menu:opacity-0 group-data-[starting-style]/morph-menu:blur-[3px]",
  "group-data-[side=top]/morph-menu:group-data-[starting-style]/morph-menu:translate-y-2",
  "group-data-[side=bottom]/morph-menu:group-data-[starting-style]/morph-menu:-translate-y-2",
  "group-data-[ending-style]/morph-menu:opacity-0 group-data-[ending-style]/morph-menu:blur-[2px] group-data-[ending-style]/morph-menu:duration-100 group-data-[ending-style]/morph-menu:[transition-delay:0ms]",
);

export interface MorphMenuItemProps extends BaseMenu.Item.Props {
  /** A 16px icon before the label. */
  icon?: ReactNode;
  /** A keyboard shortcut hint at the end of the row. */
  shortcut?: ReactNode;
  /** Styles the item for actions that delete or cannot be undone. */
  destructive?: boolean;
}

/** An action in the menu. Use `onClick` to handle it. The highlight follows pointer and keys instantly. */
export function MorphMenuItem({ icon, shortcut, destructive = false, className, children, ...props }: MorphMenuItemProps) {
  return (
    <BaseMenu.Item
      data-destructive={destructive || undefined}
      className={withBase(
        cx(
          "flex h-8 cursor-default items-center gap-2.5 rounded-md px-2 text-sm outline-none select-none",
          "[&_svg]:size-4 [&_svg]:shrink-0 data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
          rowMotion,
          destructive
            ? cx(
                "text-red-600 [&_svg]:text-red-600/80 data-[highlighted]:bg-red-500/[0.08] data-[highlighted]:text-red-700",
                "dark:text-red-400 dark:[&_svg]:text-red-400/80 dark:data-[highlighted]:bg-red-500/[0.12] dark:data-[highlighted]:text-red-300",
              )
            : cx(
                "text-zinc-700 [&_svg]:text-zinc-500 data-[highlighted]:bg-zinc-950/[0.05] data-[highlighted]:text-zinc-950 data-[highlighted]:[&_svg]:text-zinc-950",
                "dark:text-zinc-300 dark:[&_svg]:text-zinc-500 dark:data-[highlighted]:bg-white/[0.08] dark:data-[highlighted]:text-white dark:data-[highlighted]:[&_svg]:text-white",
              ),
        ),
        className,
      )}
      {...props}
    >
      {icon}
      <span className="min-w-0 flex-1 truncate">{children}</span>
      {shortcut ? <span className="ml-auto pl-6 font-mono text-xs text-zinc-400 tabular-nums dark:text-zinc-500">{shortcut}</span> : null}
    </BaseMenu.Item>
  );
}

/** A divider between groups of items. */
export function MorphMenuSeparator({ className, ...props }: ComponentProps<typeof BaseMenu.Separator>) {
  return (
    <BaseMenu.Separator
      className={withBase(cx("-mx-1.5 my-1.5 h-px bg-zinc-950/[0.07] dark:bg-white/[0.08]", rowMotion), className)}
      {...props}
    />
  );
}