{"$schema":"https:\/\/ui.shadcn.com\/schema\/registry-item.json","name":"message-bubble","type":"registry:component","title":"Message Bubble","description":"A focused conversational surface with visual tones, independent alignment, grouped messages, expandable content, and interactive link or button support.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"docs":"Message Bubble: usage, props and types at https:\/\/beui.dev\/components\/agents\/message-bubble.md","files":[{"path":"components\/agents\/message-bubble.tsx","type":"registry:component","target":"@components\/agents\/message-bubble.tsx","content":"\"use client\";\n\/\/ beui.dev\/components\/agents\/message-bubble\n\nimport { ChevronDown } from \"lucide-react\";\nimport {\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion\/react\";\nimport {\n  type ComponentPropsWithRef,\n  cloneElement,\n  createContext,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { MessageSideContext } from \"@\/components\/agents\/message-context\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@\/lib\/ease\";\nimport { useMessages } from \"@\/lib\/i18n\";\nimport { mergeRefs } from \"@\/lib\/merge-refs\";\nimport { cn } from \"@\/lib\/utils\";\n\nexport type MessageBubbleVariant =\n  | \"solid\"\n  | \"soft\"\n  | \"tint\"\n  | \"outline\"\n  | \"ghost\"\n  | \"danger\";\nexport type MessageBubbleAlign = \"start\" | \"end\";\n\n\/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. *\/\nexport const messageBubbleMessages = {\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n};\n\nexport type MessageBubbleMessages = typeof messageBubbleMessages;\n\ninterface MessageBubbleContextValue {\n  align?: MessageBubbleAlign;\n  animateIn: boolean;\n  variant: MessageBubbleVariant;\n  labels?: Partial<MessageBubbleMessages>;\n}\n\nconst MessageBubbleContext = createContext<MessageBubbleContextValue>({\n  animateIn: true,\n  variant: \"soft\",\n});\n\nexport interface MessageBubbleProps\n  extends Omit<HTMLMotionProps<\"div\">, \"children\"> {\n  \/** Fill and border style of the bubble. Default: \"soft\" *\/\n  variant?: MessageBubbleVariant;\n  \/** Defaults to the surrounding Message alignment when omitted. *\/\n  align?: MessageBubbleAlign;\n  \/** Plays the bubble entrance once when this component mounts. *\/\n  animateIn?: boolean;\n  \/** Override any built-in string. *\/\n  labels?: Partial<MessageBubbleMessages>;\n  children?: ReactNode;\n}\n\nexport interface MessageBubbleContentProps\n  extends ComponentPropsWithRef<\"div\"> {\n  \/** Replaces the content element while preserving bubble styling. *\/\n  render?: ReactElement;\n}\n\nexport interface MessageBubbleGroupProps extends ComponentPropsWithRef<\"div\"> {\n  \/** Gap between bubbles. Default: \"compact\" *\/\n  spacing?: \"compact\" | \"default\";\n}\n\nexport interface MessageBubbleCollapsibleProps\n  extends ComponentPropsWithRef<\"div\"> {\n  \/** Whether the full text shows, for controlled use. *\/\n  open?: boolean;\n  \/** Whether the full text shows at first when uncontrolled. Default: false *\/\n  defaultOpen?: boolean;\n  \/** Called with the new state when the text expands or collapses. *\/\n  onOpenChange?: (open: boolean) => void;\n  \/** Lines shown while collapsed. Default: 4 *\/\n  collapsedLines?: 2 | 3 | 4 | 5 | 6;\n  \/** Text of the expand button. Default: \"Show more\" *\/\n  moreLabel?: ReactNode;\n  \/** Text of the collapse button. Default: \"Show less\" *\/\n  lessLabel?: ReactNode;\n  \/** Classes merged onto the clamped text wrapper. *\/\n  contentClassName?: string;\n  \/** Classes merged onto the show more button. *\/\n  triggerClassName?: string;\n  children?: ReactNode;\n}\n\nconst BUBBLE_CONTENT_REVEAL = {\n  duration: 0.12,\n  ease: EASE_OUT,\n  delay: 0.04,\n} as const;\n\n\/\/ Expanded text wipes in top to bottom, quick enough to read straight on.\nconst REVEAL = { duration: 0.32, ease: EASE_OUT } as const;\n\/\/ Clamped text stays solid to here (%), then fades out by the bottom.\nconst CLAMP_SOLID = 68;\n\/\/ How soft the moving edge of the wipe is, in % of the text's height.\nconst WIPE_EDGE = 12;\n\n\/\/ Sent bubbles should pop into place quickly with one restrained overshoot.\nconst BUBBLE_POP = {\n  type: \"spring\",\n  stiffness: 520,\n  damping: 27,\n  mass: 0.52,\n} as const;\n\nexport function MessageBubble({\n  variant = \"soft\",\n  align,\n  animateIn = false,\n  labels,\n  className,\n  children,\n  initial,\n  animate,\n  exit,\n  transition,\n  layout,\n  ...props\n}: MessageBubbleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const messageSide = useContext(MessageSideContext);\n  const resolvedAlign = align ?? messageSide ?? \"start\";\n\n  return (\n    <MessageBubbleContext.Provider\n      value={{ align: resolvedAlign, animateIn, variant, labels }}\n    >\n      <motion.div\n        data-slot=\"message-bubble\"\n        data-align={resolvedAlign}\n        data-variant={variant}\n        layout={layout}\n        initial={initial ?? false}\n        animate={animate}\n        exit={\n          exit ??\n          (reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.99 })\n        }\n        transition={transition ?? (reduce ? { duration: 0.12 } : SPRING_LAYOUT)}\n        className={cn(\n          \"group\/bubble flex w-full flex-col\",\n          resolvedAlign === \"end\" ? \"items-end\" : \"items-start\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      <\/motion.div>\n    <\/MessageBubbleContext.Provider>\n  );\n}\n\nfunction bubbleContentClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n  interactive: boolean,\n) {\n  return cn(\n    \"relative z-0 min-w-9 max-w-[82%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 text-foreground\",\n    \/\/ The corner by the speaker is tighter, so a bubble points at who said it.\n    align === \"end\" ? \"rounded-ee-md\" : \"rounded-es-md\",\n    \"[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-background\/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-background\/60 [&_pre]:p-3 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5\",\n    variant === \"solid\" &&\n      \"text-primary-foreground [&_code]:bg-primary-foreground\/15 [&_pre]:bg-primary-foreground\/15\",\n    variant === \"ghost\" && \"w-full max-w-none rounded-none px-0 py-0\",\n    variant === \"danger\" && \"text-destructive\",\n    interactive &&\n      \"cursor-pointer text-left outline-none transition-[background-color,color,transform] duration-150 hover:brightness-[0.98] focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.99]\",\n  );\n}\n\nfunction bubbleSurfaceClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n) {\n  return cn(\n    \"pointer-events-none absolute inset-0 -z-10 rounded-[inherit]\",\n    align === \"end\" ? \"origin-bottom-right\" : \"origin-bottom-left\",\n    variant === \"solid\" && \"bg-primary\",\n    variant === \"soft\" && \"bg-muted\",\n    variant === \"tint\" && \"bg-muted\",\n    variant === \"outline\" && \"border border-border\/70 bg-background\",\n    variant === \"danger\" && \"bg-destructive\/10\",\n  );\n}\n\nexport function MessageBubbleContent({\n  render,\n  className,\n  children,\n  ref,\n  ...props\n}: MessageBubbleContentProps) {\n  const reduce = useReducedMotion() ?? false;\n  const { align = \"start\", animateIn, variant } =\n    useContext(MessageBubbleContext);\n  const interactive =\n    render?.type === \"button\" || render?.type === \"a\";\n  const classes = cn(\n    bubbleContentClass(variant, align, interactive),\n    className,\n  );\n  const composedChildren = (\n    <>\n      {\/* The surface pops in once, then always matches its text: a surface\n          that springs after its content leaves streamed lines and expanded\n          text hanging outside the bubble. *\/}\n      {variant !== \"ghost\" ? (\n        <motion.span\n          aria-hidden=\"true\"\n          initial={\n            animateIn && !reduce\n              ? {\n                  opacity: 0,\n                  scale: 0.92,\n                }\n              : false\n          }\n          animate={{ opacity: 1, scale: 1 }}\n          transition={\n            reduce\n              ? { duration: 0 }\n              : {\n                  opacity: { duration: 0.12, ease: EASE_OUT },\n                  scale: BUBBLE_POP,\n                }\n          }\n          className={bubbleSurfaceClass(variant, align)}\n        \/>\n      ) : null}\n      <motion.div\n        initial={animateIn ? { opacity: 0 } : false}\n        animate={{ opacity: 1 }}\n        transition={\n          reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL\n        }\n        className=\"relative\"\n      >\n        {children}\n      <\/motion.div>\n    <\/>\n  );\n\n  if (render) {\n    const child = render as ReactElement<\n      Record<string, unknown> & { className?: string; ref?: Ref<HTMLElement> }\n    >;\n\n    return cloneElement(child, {\n      ...props,\n      ref: mergeRefs(child.props.ref, ref as Ref<HTMLElement> | undefined),\n      className: cn(classes, child.props.className),\n      children: composedChildren,\n      \"data-slot\": \"message-bubble-content\",\n    });\n  }\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"message-bubble-content\"\n      className={classes}\n      {...props}\n    >\n      {composedChildren}\n    <\/div>\n  );\n}\n\nexport function MessageBubbleGroup({\n  spacing = \"compact\",\n  className,\n  ...props\n}: MessageBubbleGroupProps) {\n  return (\n    <div\n      data-slot=\"message-bubble-group\"\n      className={cn(\n        \"flex w-full flex-col\",\n        spacing === \"compact\" ? \"gap-1.5\" : \"gap-3\",\n        \/\/ A bubble that follows one from the same speaker tightens its top\n        \/\/ corner on that side too, so the run reads as one turn.\n        \"[&>[data-align=end]+[data-align=end]_[data-slot=message-bubble-content]]:rounded-se-md\",\n        \"[&>[data-align=start]+[data-align=start]_[data-slot=message-bubble-content]]:rounded-ss-md\",\n        className,\n      )}\n      {...props}\n    \/>\n  );\n}\n\nconst LINE_CLAMP_CLASS = {\n  2: \"line-clamp-2\",\n  3: \"line-clamp-3\",\n  4: \"line-clamp-4\",\n  5: \"line-clamp-5\",\n  6: \"line-clamp-6\",\n} as const;\n\nexport function MessageBubbleCollapsible({\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  collapsedLines = 4,\n  moreLabel,\n  lessLabel,\n  contentClassName,\n  triggerClassName,\n  className,\n  children,\n  ...props\n}: MessageBubbleCollapsibleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const contentId = useId();\n  const t = useMessages(\n    \"messageBubble\",\n    messageBubbleMessages,\n    useContext(MessageBubbleContext).labels,\n  );\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const contentRef = useRef<HTMLDivElement>(null);\n  \/\/ Where the clamped text ended, as a share of the full text: the reveal\n  \/\/ starts there, so the lines already on screen never blink.\n  const clampedHeight = useRef(0);\n  \/\/ The fade mask, from solid (`solid`%) to clear (`clear`%). Clamped, it\n  \/\/ softens the last lines; open, it wipes down until the text is all solid.\n  const solid = useMotionValue(currentOpen ? 100 : CLAMP_SOLID);\n  const clear = useMotionValue(currentOpen ? 100 + WIPE_EDGE : 100);\n  const mask = useMotionTemplate`linear-gradient(to bottom, #000 ${solid}%, transparent ${clear}%)`;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next) clampedHeight.current = contentRef.current?.offsetHeight ?? 0;\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  \/\/ Opening shows the whole text at once (no height animation) and wipes the\n  \/\/ new lines in from the top; closing clamps straight back.\n  useLayoutEffect(() => {\n    if (!currentOpen) {\n      solid.set(CLAMP_SOLID);\n      clear.set(100);\n      return;\n    }\n    const full = contentRef.current?.offsetHeight ?? 0;\n    const start =\n      reduce || !full || !clampedHeight.current\n        ? 100\n        : Math.min(100, (clampedHeight.current \/ full) * 100 - WIPE_EDGE);\n    solid.set(start);\n    clear.set(start + WIPE_EDGE);\n    if (start >= 100) return;\n    const toSolid = animate(solid, 100, REVEAL);\n    const toClear = animate(clear, 100 + WIPE_EDGE, REVEAL);\n    return () => {\n      toSolid.stop();\n      toClear.stop();\n    };\n  }, [currentOpen, reduce, solid, clear]);\n\n  return (\n    <div\n      data-slot=\"message-bubble-collapsible\"\n      data-state={currentOpen ? \"open\" : \"closed\"}\n      className={cn(\"w-full\", className)}\n      {...props}\n    >\n      <motion.div\n        ref={contentRef}\n        id={contentId}\n        style={{ maskImage: mask, WebkitMaskImage: mask }}\n        className={cn(\n          !currentOpen && LINE_CLAMP_CLASS[collapsedLines],\n          contentClassName,\n        )}\n      >\n        {children}\n      <\/motion.div>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className={cn(\n          \"mt-2 inline-flex h-7 items-center gap-1 rounded-full px-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n          triggerClassName,\n        )}\n      >\n        <span>{currentOpen\n            ? (lessLabel ?? t(\"showLess\"))\n            : (moreLabel ?? t(\"showMore\"))}<\/span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n        >\n          <ChevronDown className=\"size-3.5\" \/>\n        <\/motion.span>\n      <\/button>\n    <\/div>\n  );\n}\n"},{"path":"components\/agents\/message-context.tsx","type":"registry:component","target":"@components\/agents\/message-context.tsx","content":"\"use client\";\n\nimport { createContext } from \"react\";\n\nexport type MessageSide = \"start\" | \"end\";\n\nexport const MessageSideContext = createContext<MessageSide | undefined>(\n  undefined,\n);\n"},{"path":"lib\/ease.ts","type":"registry:lib","target":"@lib\/ease.ts","content":"\/\/ Shared motion tokens. Easing curves mirror the CSS custom properties in\n\/\/ globals.css; springs are the canonical physics used across components.\n\/\/ Strong custom variants - defaults like `ease-in`\/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n\/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. *\/\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n\/** CSS string form of EASE_OUT for inline style transitions. *\/\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n\/** Press feedback on buttons and other tappable surfaces. *\/\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n\/** Content swaps - label\/icon slots trading places inside a control. *\/\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n\/** Overlay panel entrances - modals and sheets summoned by pointer. *\/\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n\/** Shared-layout glides - pills, indicators and panels morphing between positions. *\/\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n\/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). *\/\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n\/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. *\/\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n\/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. *\/\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib\/i18n.tsx","type":"registry:lib","target":"@lib\/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n\/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n *\/\nexport type Messages = Record<string, string>;\n\n\/** A language file: component namespace \u2192 any subset of that component's messages. *\/\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n\/** Without a locale, digits stay plain so server and client render the same text. *\/\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  \/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. *\/\n  locale: string;\n  \/**\n   * Component namespace \u2192 translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   *\/\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}<\/LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n\/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n *\/\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  \/\/ Inline `labels={{ \u2026 }}` is a new object every render. Keying it by content\n  \/\/ keeps `t` one identity until a label changes, so effects and memos that\n  \/\/ depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(\/\\{(\\w+)\\}\/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib\/merge-refs.ts","type":"registry:lib","target":"@lib\/merge-refs.ts","content":"import type { Ref } from \"react\";\n\n\/** Points a callback or object ref at `value`. *\/\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n\/** One callback ref that sets every ref it is given. *\/\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"lib\/utils.ts","type":"registry:lib","target":"@lib\/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}