{"$schema":"https://ui.shadcn.com/schema/registry.json","author":"Kaiyu Hsu <uicapsule@kyh.io>","categories":["controls","minimal"],"dependencies":["lucide-react","motion"],"description":"Material 3 Expressive split button — the trailing half rounds into a circle and flips its chevron as a native popover menu unfurls from its anchor.","devDependencies":[],"files":[{"content":"\"use client\";\n\nimport { SplitButton } from \"./split-button\";\n\nconst Preview = () => (\n  <main className=\"flex h-dvh items-start justify-center overflow-hidden bg-[radial-gradient(ellipse_60%_55%_at_50%_40%,#1d2433_0%,#131314_70%)] pt-[38vh]\">\n    <SplitButton />\n  </main>\n);\n\nexport default Preview;\n","path":"/preview.tsx","target":"uicapsule/split-button/preview.tsx","type":"registry:file"},{"content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ToggleEvent } from \"react\";\nimport { Check, ChevronDown, Copy, Pencil, Save, Upload } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\n\ntype ActionId = \"save\" | \"save-as\" | \"copy\" | \"export\";\n\nconst MENU_ITEMS = [\n  { icon: Pencil, id: \"save-as\", label: \"Save as\" },\n  { icon: Copy, id: \"copy\", label: \"Save a copy\" },\n  { icon: Upload, id: \"export\", label: \"Export\" },\n] as const satisfies readonly { id: ActionId; label: string; icon: typeof Save }[];\n\nconst DONE_LABEL: Record<ActionId, string> = {\n  copy: \"Copied\",\n  export: \"Exported\",\n  save: \"Saved\",\n  \"save-as\": \"Saved as\",\n};\n\nconst CONFIRM_MS = 1600;\n\nconst LEADING_WIDTH = 144;\nconst SEAM = 2;\nconst TRAILING_SIZE = 56;\nconst TRAILING_RADIUS = TRAILING_SIZE / 2;\n\nconst MORPH_SPRING = { bounce: 0.35, visualDuration: 0.3 };\nconst PRESS_SCALE = 0.9;\nconst PRESS_DOWN = { duration: 0.08, ease: \"easeOut\" } as const;\nconst PRESS_RELEASE = { bounce: 0.55, type: \"spring\", visualDuration: 0.35 } as const;\n\nconst roundnessOf = (morph: number) => Math.min(Math.max(morph, 0), 1);\n\ninterface Confirmation {\n  id: ActionId;\n  seq: number;\n}\n\nexport const SplitButton = () => {\n  const domId = useId().replaceAll(/[^\\w-]/gu, \"\");\n  const anchorName = `--split-${domId}`;\n  const menuId = `split-menu-${domId}`;\n\n  const menuRef = useRef<HTMLDivElement>(null);\n  const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);\n  const confirmSeq = useRef(0);\n\n  const [open, setOpen] = useState(false);\n  const [activeIndex, setActiveIndex] = useState<number | null>(null);\n  const [confirmation, setConfirmation] = useState<Confirmation | null>(null);\n\n  const morph = useSpring(0, MORPH_SPRING);\n  const scale = useMotionValue(1);\n  const cornerRadius = useTransform(morph, (m) => roundnessOf(m) * TRAILING_RADIUS);\n  const chevronRotate = useTransform(morph, [0, 1], [0, 180]);\n  const chevronShift = useTransform(morph, (m) => (roundnessOf(m) - 1) * 2);\n  const seamX = useTransform(() => LEADING_WIDTH + TRAILING_RADIUS * (1 - scale.get()));\n  const filletRadius = useTransform(() => cornerRadius.get() * scale.get() + SEAM);\n  const filletTop = useTransform(() => TRAILING_RADIUS * (1 - scale.get()) - SEAM);\n\n  const filletBottom = useTransform(\n    () => TRAILING_RADIUS * (1 + scale.get()) + SEAM - filletRadius.get(),\n  );\n\n  const notchMask = {\n    maskImage: useMotionTemplate`linear-gradient(#000, #000), radial-gradient(circle ${filletRadius}px at 100% 100%, transparent ${filletRadius}px, #000 calc(${filletRadius}px + 0.5px)), radial-gradient(circle ${filletRadius}px at 100% 0, transparent ${filletRadius}px, #000 calc(${filletRadius}px + 0.5px))`,\n    maskPosition: useMotionTemplate`0 0, calc(${seamX}px - 1px) ${filletTop}px, calc(${seamX}px - 1px) ${filletBottom}px`,\n    maskRepeat: \"no-repeat\",\n    maskSize: useMotionTemplate`${seamX}px 100%, calc(${filletRadius}px + 1px) ${filletRadius}px, calc(${filletRadius}px + 1px) ${filletRadius}px`,\n  };\n\n  const confirm = (id: ActionId) => {\n    confirmSeq.current += 1;\n    setConfirmation({ id, seq: confirmSeq.current });\n  };\n\n  const choose = (id: ActionId) => {\n    menuRef.current?.hidePopover();\n    confirm(id);\n  };\n\n  useEffect(() => {\n    if (!confirmation) {\n      return;\n    }\n\n    const timer = window.setTimeout(() => setConfirmation(null), CONFIRM_MS);\n\n    return () => window.clearTimeout(timer);\n  }, [confirmation]);\n\n  const press = async () => {\n    await animate(scale, PRESS_SCALE, PRESS_DOWN);\n    await animate(scale, 1, PRESS_RELEASE);\n  };\n\n  const onToggle = (event: ToggleEvent<HTMLDivElement>) => {\n    const isOpen = event.newState === \"open\";\n    setOpen(isOpen);\n    morph.set(isOpen ? 1 : 0);\n    void press();\n\n    if (!isOpen) {\n      setActiveIndex(null);\n    }\n  };\n\n  const focusItem = (index: number) => {\n    const count = MENU_ITEMS.length;\n    const next = (index + count) % count;\n    setActiveIndex(next);\n    itemRefs.current[next]?.focus();\n  };\n\n  const onMenuKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const target = new Map([\n      [\"ArrowDown\", (activeIndex ?? -1) + 1],\n      [\"ArrowUp\", (activeIndex ?? MENU_ITEMS.length) - 1],\n      [\"End\", MENU_ITEMS.length - 1],\n      [\"Home\", 0],\n    ]).get(event.key);\n\n    if (target !== undefined) {\n      event.preventDefault();\n      focusItem(target);\n    }\n  };\n\n  const onTrailingKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {\n    if (event.key === \"ArrowDown\") {\n      event.preventDefault();\n      menuRef.current?.showPopover();\n      focusItem(0);\n    }\n  };\n\n  const confirmedLabel = confirmation ? DONE_LABEL[confirmation.id] : null;\n\n  return (\n    <>\n      <div\n        className=\"group/split inline-flex h-14 gap-0.5 select-none\"\n        data-open={open}\n        style={{ anchorName }}\n      >\n        <button\n          type=\"button\"\n          aria-label={confirmedLabel ?? \"Save\"}\n          onClick={() => confirm(\"save\")}\n          className=\"group/leading relative isolate flex cursor-pointer items-center justify-center gap-2 rounded-l-full text-[17px] font-medium text-[#062e6f] outline-none focus-visible:ring-2 focus-visible:ring-[#d3e3fd] focus-visible:ring-offset-2 focus-visible:ring-offset-[#131314]\"\n          style={{ width: LEADING_WIDTH }}\n        >\n          <motion.span\n            aria-hidden\n            className=\"pointer-events-none absolute inset-y-0 left-0 -z-10 rounded-l-full bg-[#a8c7fa] transition-colors duration-200 group-hover/leading:bg-[#b6d0fb] group-active/leading:bg-[#c2d7fc]\"\n            style={{ ...notchMask, width: LEADING_WIDTH + SEAM + TRAILING_RADIUS }}\n          />\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            <motion.span\n              key={confirmedLabel ?? \"idle\"}\n              className=\"flex items-center gap-2\"\n              initial={{ filter: \"blur(4px)\", opacity: 0, y: 10 }}\n              animate={{ filter: \"blur(0px)\", opacity: 1, y: 0 }}\n              exit={{ filter: \"blur(4px)\", opacity: 0, y: -10 }}\n              transition={{ bounce: 0.25, duration: 0.35, type: \"spring\" }}\n            >\n              {confirmedLabel ? (\n                <Check className=\"size-5\" strokeWidth={2.5} />\n              ) : (\n                <Save className=\"size-5\" strokeWidth={2.25} />\n              )}\n              {confirmedLabel ?? \"Save\"}\n            </motion.span>\n          </AnimatePresence>\n        </button>\n        <motion.button\n          type=\"button\"\n          popoverTarget={menuId}\n          aria-label=\"More save options\"\n          aria-haspopup=\"menu\"\n          aria-expanded={open}\n          onKeyDown={onTrailingKeyDown}\n          className=\"relative z-10 grid cursor-pointer place-items-center rounded-r-[28px] bg-[#a8c7fa] text-[#062e6f] transition-colors duration-300 outline-none group-data-[open=true]/split:bg-[#d3e3fd] hover:bg-[#b6d0fb] focus-visible:ring-2 focus-visible:ring-[#d3e3fd] focus-visible:ring-offset-2 focus-visible:ring-offset-[#131314] active:bg-[#c2d7fc]\"\n          style={{\n            borderBottomLeftRadius: cornerRadius,\n            borderTopLeftRadius: cornerRadius,\n            height: TRAILING_SIZE,\n            scale,\n            width: TRAILING_SIZE,\n          }}\n        >\n          <motion.span className=\"grid\" style={{ rotate: chevronRotate, x: chevronShift }}>\n            <ChevronDown className=\"size-6\" strokeWidth={2.5} />\n          </motion.span>\n        </motion.button>\n      </div>\n      <div\n        ref={menuRef}\n        id={menuId}\n        popover=\"auto\"\n        role=\"menu\"\n        tabIndex={-1}\n        aria-label=\"Save options\"\n        onToggle={onToggle}\n        onKeyDown={onMenuKeyDown}\n        style={{ left: \"anchor(left)\", positionAnchor: anchorName, top: \"anchor(bottom)\" }}\n        className=\"m-0 mt-1.5 w-56 origin-top-left -translate-y-1 scale-[0.9] rounded-[6px_6px_24px_24px] border-0 bg-[#2b2c30] p-1.5 text-[#e3e3e3] opacity-0 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.6)] transition-[opacity,scale,translate,display,overlay] transition-discrete duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] [inset:auto] open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1 starting:open:scale-[0.9] starting:open:opacity-0\"\n      >\n        {MENU_ITEMS.map((item, index) => (\n          <button\n            key={item.id}\n            ref={(node) => {\n              itemRefs.current[index] = node;\n            }}\n            type=\"button\"\n            role=\"menuitem\"\n            tabIndex={-1}\n            data-active={activeIndex === index}\n            onPointerEnter={() => focusItem(index)}\n            onFocus={() => setActiveIndex(index)}\n            onClick={() => choose(item.id)}\n            className=\"flex h-12 w-full cursor-pointer items-center gap-3 rounded-[4px] px-3 text-left text-[15px] transition-[background-color,color,border-radius] duration-200 outline-none first:rounded-t-[4px] last:rounded-b-[20px] data-[active=true]:rounded-[16px] data-[active=true]:bg-[#004a77] data-[active=true]:text-[#c2e7ff]\"\n          >\n            <item.icon className=\"size-5\" strokeWidth={2} />\n            {item.label}\n          </button>\n        ))}\n      </div>\n    </>\n  );\n};\n","path":"/split-button.tsx","target":"uicapsule/split-button/split-button.tsx","type":"registry:file"}],"homepage":"https://www.uicapsule.com/ui/split-button","name":"split-button","registryDependencies":[],"title":"Split Button","type":"registry:block"}