{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "comments",
  "title": "Comments",
  "description": "Primitives for comments: threads with one level of replies joined by a line, a composer that suggests people after @ and submits with ⌘ Enter, highlighted mentions, reaction toggles with an emoji picker, an edit and delete menu, and resolved threads that collapse to a summary.",
  "registryDependencies": [
    "avatar",
    "button",
    "dropdown-menu",
    "input-group",
    "https://www.dashboardblocks.com/r/radix/activity-feed.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/comments.tsx",
      "content": "'use client'\n\nimport {\n  ActivityIcon,\n  ActivityTime,\n  activityToneClasses,\n} from '@/registry/components/dashboardblocks/activity-feed'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  type FormEvent,\n  Fragment,\n  type KeyboardEvent,\n  type ReactNode,\n  startTransition,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'\nimport { Button } from '@/components/ui/button'\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu'\nimport {\n  InputGroup,\n  InputGroupAddon,\n  InputGroupTextarea,\n} from '@/components/ui/input-group'\n\nimport { cn } from '@/lib/utils'\n\ninterface CommentAuthor {\n  avatar?: string\n  name: string\n}\n\ninterface CommentReaction {\n  count: number\n  emoji: string\n  reacted: boolean\n}\n\ninterface ThreadComment {\n  at: Date\n  author: CommentAuthor\n  body: string\n  edited?: boolean\n  id: string\n  reactions?: CommentReaction[]\n  replies?: ThreadComment[]\n  resolved?: boolean\n}\n\ninterface ReactionChoice {\n  emoji: string\n  label: string\n}\n\nconst defaultReactions: ReactionChoice[] = [\n  { emoji: '👍', label: 'Thumbs up' },\n  { emoji: '❤️', label: 'Heart' },\n  { emoji: '🎉', label: 'Hooray' },\n  { emoji: '😄', label: 'Laugh' },\n  { emoji: '👀', label: 'Eyes' },\n  { emoji: '🚀', label: 'Rocket' },\n]\n\nfunction toggleReaction(reactions: CommentReaction[] = [], emoji: string) {\n  if (!reactions.some((reaction) => reaction.emoji === emoji)) {\n    return [...reactions, { count: 1, emoji, reacted: true }]\n  }\n  return reactions\n    .map((reaction) =>\n      reaction.emoji === emoji\n        ? {\n            ...reaction,\n            count: reaction.count + (reaction.reacted ? -1 : 1),\n            reacted: !reaction.reacted,\n          }\n        : reaction,\n    )\n    .filter((reaction) => reaction.count > 0)\n}\n\nfunction updateComment<T extends ThreadComment>(\n  comments: T[],\n  id: string,\n  update: (comment: ThreadComment) => ThreadComment | null,\n): T[] {\n  return comments.flatMap((comment) => {\n    if (comment.id === id) {\n      const next = update(comment)\n      return next ? [next as T] : []\n    }\n    if (!comment.replies) return [comment]\n    return [{ ...comment, replies: updateComment(comment.replies, id, update) }]\n  })\n}\n\ninterface MentionSegment {\n  mention?: string\n  text: string\n}\n\nfunction escapeRegExp(value: string) {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction parseMentions(text: string, names?: string[]) {\n  const name = names?.length\n    ? [...names]\n        .sort((a, b) => b.length - a.length)\n        .map(escapeRegExp)\n        .join('|')\n    : '[\\\\p{L}\\\\p{N}_]+'\n  const pattern = new RegExp(`(?<![\\\\p{L}\\\\p{N}_@.])@(${name})(?![\\\\p{L}\\\\p{N}_])`, 'gu')\n  const segments: MentionSegment[] = []\n  let last = 0\n  for (const match of text.matchAll(pattern)) {\n    if (match.index > last) segments.push({ text: text.slice(last, match.index) })\n    segments.push({ mention: match[1], text: match[0] })\n    last = match.index + match[0].length\n  }\n  if (last < text.length) segments.push({ text: text.slice(last) })\n  return segments\n}\n\nfunction getMentions(text: string, names?: string[]) {\n  return [\n    ...new Set(\n      parseMentions(text, names).flatMap((segment) =>\n        segment.mention ? [segment.mention] : [],\n      ),\n    ),\n  ]\n}\n\nfunction initials(name: string) {\n  return name\n    .split(/\\s+/)\n    .filter(Boolean)\n    .slice(0, 2)\n    .map((part) => part[0]?.toUpperCase())\n    .join('')\n}\n\nfunction CommentAvatar({\n  author,\n  className,\n  size = 'default',\n}: {\n  author: CommentAuthor\n  className?: string\n  size?: 'default' | 'sm'\n}) {\n  return (\n    <Avatar aria-hidden size={size} className={className}>\n      {author.avatar && <AvatarImage src={author.avatar} alt='' />}\n      <AvatarFallback>{initials(author.name)}</AvatarFallback>\n    </Avatar>\n  )\n}\n\nfunction CommentBody({\n  body,\n  className,\n  people,\n}: {\n  body: string\n  className?: string\n  people?: CommentAuthor[]\n}) {\n  return (\n    <p className={cn('text-sm break-words whitespace-pre-wrap', className)}>\n      {parseMentions(\n        body,\n        people?.map((person) => person.name),\n      ).map((segment, index) =>\n        segment.mention ? (\n          <span\n            key={index}\n            className={cn('rounded-sm px-0.5 font-medium', activityToneClasses.info)}\n          >\n            {segment.text}\n          </span>\n        ) : (\n          <Fragment key={index}>{segment.text}</Fragment>\n        ),\n      )}\n    </p>\n  )\n}\n\ninterface ReactionBarProps {\n  choices?: ReactionChoice[]\n  className?: string\n  onToggle?: (emoji: string) => void\n  reactions: CommentReaction[]\n}\n\nfunction ReactionBar({\n  choices = defaultReactions,\n  className,\n  onToggle,\n  reactions,\n}: ReactionBarProps) {\n  const id = useId()\n  const [picking, setPicking] = useState(false)\n  const triggerRef = useRef<HTMLButtonElement>(null)\n  const pickerRef = useRef<HTMLDivElement>(null)\n  const labelOf = (emoji: string) =>\n    choices.find((choice) => choice.emoji === emoji)?.label ?? emoji\n\n  useEffect(() => {\n    if (picking) pickerRef.current?.querySelector('button')?.focus()\n  }, [picking])\n\n  function close() {\n    setPicking(false)\n    triggerRef.current?.focus()\n  }\n\n  function onPickerKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const buttons = [...(pickerRef.current?.querySelectorAll('button') ?? [])]\n    const index = buttons.indexOf(document.activeElement as HTMLButtonElement)\n    if (event.key === 'Escape') {\n      event.preventDefault()\n      close()\n    } else if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {\n      event.preventDefault()\n      const step = event.key === 'ArrowRight' ? 1 : -1\n      buttons[(index + step + buttons.length) % buttons.length]?.focus()\n    }\n  }\n\n  if (!onToggle && reactions.length === 0) return null\n\n  return (\n    <div className={cn('flex flex-wrap items-center gap-1', className)}>\n      {reactions.map((reaction) =>\n        onToggle ? (\n          <Button\n            key={reaction.emoji}\n            type='button'\n            variant='outline'\n            size='xs'\n            aria-pressed={reaction.reacted}\n            aria-label={`${labelOf(reaction.emoji)}: ${reaction.count}`}\n            className='tabular-nums aria-pressed:border-sky-500/40 aria-pressed:bg-sky-500/10'\n            onClick={() => onToggle(reaction.emoji)}\n          >\n            <span aria-hidden>{reaction.emoji}</span>\n            <span aria-hidden>{reaction.count}</span>\n          </Button>\n        ) : (\n          <span\n            key={reaction.emoji}\n            role='img'\n            aria-label={`${labelOf(reaction.emoji)}: ${reaction.count}`}\n            className='bg-muted flex h-6 items-center gap-1 rounded-full px-2 text-xs tabular-nums'\n          >\n            <span aria-hidden>{reaction.emoji}</span>\n            <span aria-hidden>{reaction.count}</span>\n          </span>\n        ),\n      )}\n      {onToggle && (\n        <div\n          className='flex items-center gap-1'\n          onBlur={(event) => {\n            if (!event.currentTarget.contains(event.relatedTarget as Node | null))\n              setPicking(false)\n          }}\n        >\n          <Button\n            ref={triggerRef}\n            type='button'\n            variant='ghost'\n            size='icon-xs'\n            aria-label='Add reaction'\n            aria-expanded={picking}\n            aria-controls={picking ? `${id}-picker` : undefined}\n            onClick={() => setPicking(!picking)}\n          >\n            <IconPlaceholder\n              lucide='SmilePlusIcon'\n              tabler='IconMoodPlus'\n              hugeicons='SmilePlusIcon'\n              phosphor='SmileyIcon'\n              remixicon='RiEmotionLine'\n            />\n          </Button>\n          {picking && (\n            <div\n              ref={pickerRef}\n              id={`${id}-picker`}\n              role='toolbar'\n              tabIndex={-1}\n              aria-label='Reactions'\n              className='bg-popover text-popover-foreground ring-foreground/10 flex items-center gap-0.5 rounded-md p-0.5 shadow-xs ring-1'\n              onKeyDown={onPickerKeyDown}\n              // Safari doesn't focus a button on click, so pressing one would blur the picker and close it before the click lands.\n              onMouseDown={(event) => event.preventDefault()}\n            >\n              {choices.map((choice) => (\n                <Button\n                  key={choice.emoji}\n                  type='button'\n                  variant='ghost'\n                  size='icon-xs'\n                  aria-label={choice.label}\n                  aria-pressed={\n                    reactions.find((reaction) => reaction.emoji === choice.emoji)\n                      ?.reacted ?? false\n                  }\n                  className='text-sm aria-pressed:bg-sky-500/10'\n                  onClick={() => {\n                    onToggle(choice.emoji)\n                    close()\n                  }}\n                >\n                  {choice.emoji}\n                </Button>\n              ))}\n            </div>\n          )}\n        </div>\n      )}\n    </div>\n  )\n}\n\ninterface CommentMenuItem {\n  icon?: ReactNode\n  label: string\n  onSelect: () => void\n  variant?: 'default' | 'destructive'\n}\n\nfunction CommentMenu({\n  items,\n  label = 'More actions',\n}: {\n  items: CommentMenuItem[]\n  label?: string\n}) {\n  const firstDestructive = items.findIndex((item) => item.variant === 'destructive')\n  return (\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <Button variant='ghost' size='icon-xs' aria-label={label}>\n          <IconPlaceholder\n            lucide='EllipsisIcon'\n            tabler='IconDots'\n            hugeicons='MoreHorizontalCircle01Icon'\n            phosphor='DotsThreeIcon'\n            remixicon='RiMoreLine'\n          />\n        </Button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align='end' className='w-auto min-w-36'>\n        {items.map((item, index) => (\n          <Fragment key={item.label}>\n            {index === firstDestructive && index > 0 && <DropdownMenuSeparator />}\n            <DropdownMenuItem variant={item.variant} onClick={item.onSelect}>\n              {item.icon}\n              {item.label}\n            </DropdownMenuItem>\n          </Fragment>\n        ))}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  )\n}\n\ninterface CommentItemProps {\n  actions?: ReactNode\n  badge?: ReactNode\n  className?: string\n  comment: ThreadComment\n  editor?: ReactNode\n  menu?: ReactNode\n  /** Pass a fixed date, so times render the same on the server and in the browser. */\n  now: Date\n  onReact?: (emoji: string) => void\n  people?: CommentAuthor[]\n  size?: 'default' | 'sm'\n  /** @default 'UTC' */\n  timeZone?: string\n}\n\nfunction CommentItem({\n  actions,\n  badge,\n  className,\n  comment,\n  editor,\n  menu,\n  now,\n  onReact,\n  people,\n  size = 'default',\n  timeZone = 'UTC',\n}: CommentItemProps) {\n  const id = useId()\n  const reactions = comment.reactions ?? []\n  return (\n    <article\n      aria-labelledby={`${id}-author ${id}-time`}\n      data-comment-id={comment.id}\n      className={cn('flex gap-3', className)}\n    >\n      <CommentAvatar author={comment.author} size={size} />\n      <div className='flex min-w-0 flex-1 flex-col gap-1'>\n        <div\n          className={cn('flex items-center gap-2', size === 'sm' ? 'min-h-6' : 'min-h-8')}\n        >\n          <div className='flex min-w-0 flex-1 flex-wrap items-center gap-x-2'>\n            <span\n              id={`${id}-author`}\n              title={comment.author.name}\n              className='truncate text-sm font-medium'\n            >\n              {comment.author.name}\n            </span>\n            {badge}\n            <span id={`${id}-time`} className='flex items-center gap-1'>\n              <ActivityTime date={comment.at} now={now} timeZone={timeZone} />\n              {comment.edited && (\n                <span className='text-muted-foreground text-xs'>(edited)</span>\n              )}\n            </span>\n          </div>\n          {menu}\n        </div>\n        {editor || (\n          <>\n            <CommentBody body={comment.body} people={people} />\n            {(reactions.length > 0 || onReact || actions) && (\n              <div className='mt-1 flex flex-wrap items-center gap-1'>\n                <ReactionBar reactions={reactions} onToggle={onReact} />\n                {actions}\n              </div>\n            )}\n          </>\n        )}\n      </div>\n    </article>\n  )\n}\n\nfunction findMentionQuery(text: string, caret: number) {\n  const match = /(?:^|[\\s(])@([\\p{L}\\p{M}'’.-]*(?: [\\p{L}\\p{M}'’.-]*)?)$/u.exec(\n    text.slice(0, caret),\n  )\n  if (!match) return null\n  return { query: match[1], start: caret - match[1].length - 1 }\n}\n\ninterface CommentComposerProps {\n  focusOnMount?: boolean\n  className?: string\n  defaultValue?: string\n  disabled?: boolean\n  /** Shown when someone submits nothing. @default 'Write something first.' */\n  emptyMessage?: string\n  footer?: ReactNode\n  label?: string\n  /** Shows a Cancel button, and Escape cancels too. */\n  onCancel?: () => void\n  /** Resolve to a message to show it as an error and keep what was typed. */\n  onSubmit: (body: string) => void | string | Promise<void | string>\n  onValueChange?: (value: string) => void\n  pendingLabel?: string\n  people?: CommentAuthor[]\n  /** @default 'Leave a comment' */\n  placeholder?: string\n  /** @default 'Comment' */\n  submitLabel?: string\n  value?: string\n}\n\nfunction CommentComposer({\n  className,\n  defaultValue = '',\n  disabled = false,\n  emptyMessage = 'Write something first.',\n  focusOnMount = false,\n  footer,\n  label = 'Comment',\n  onCancel,\n  onSubmit,\n  onValueChange,\n  pendingLabel = 'Posting',\n  people = [],\n  placeholder = 'Leave a comment',\n  submitLabel = 'Comment',\n  value,\n}: CommentComposerProps) {\n  const id = useId()\n  const textareaRef = useRef<HTMLTextAreaElement>(null)\n  const pendingCaret = useRef<number | null>(null)\n  const [uncontrolled, setUncontrolled] = useState(defaultValue)\n  const [caret, setCaret] = useState(0)\n  const [active, setActive] = useState(0)\n  const [dismissed, setDismissed] = useState<number | null>(null)\n  const [isSubmitting, setIsSubmitting] = useState(false)\n  const [error, setError] = useState<string>()\n  const text = value ?? uncontrolled\n\n  const match = findMentionQuery(text, caret)\n  const query = match?.query.toLowerCase() ?? ''\n  const suggestions =\n    match && match.start !== dismissed\n      ? people\n          .filter((person) => {\n            const name = person.name.toLowerCase()\n            return (\n              name.startsWith(query) ||\n              name.split(/\\s+/).some((part) => part.startsWith(query))\n            )\n          })\n          .slice(0, 6)\n      : []\n  const open = suggestions.length > 0\n  const activeIndex = Math.min(active, suggestions.length - 1)\n\n  useEffect(() => {\n    const textarea = textareaRef.current\n    if (!focusOnMount || !textarea) return\n    textarea.focus()\n    textarea.setSelectionRange(textarea.value.length, textarea.value.length)\n    setCaret(textarea.value.length)\n  }, [focusOnMount])\n\n  useLayoutEffect(() => {\n    if (pendingCaret.current === null) return\n    textareaRef.current?.setSelectionRange(pendingCaret.current, pendingCaret.current)\n    pendingCaret.current = null\n  }, [text])\n\n  function change(next: string) {\n    if (value === undefined) setUncontrolled(next)\n    onValueChange?.(next)\n    setError(undefined)\n  }\n\n  function insert(person: CommentAuthor) {\n    if (!match) return\n    const mention = `@${person.name} `\n    const end = match.start + mention.length\n    change(text.slice(0, match.start) + mention + text.slice(caret).replace(/^ /, ''))\n    pendingCaret.current = end\n    setCaret(end)\n  }\n\n  async function submit(event?: FormEvent<HTMLFormElement>) {\n    event?.preventDefault()\n    const body = text.trim()\n    if (isSubmitting || disabled) return\n    if (!body) {\n      setError(emptyMessage)\n      return textareaRef.current?.focus()\n    }\n    setIsSubmitting(true)\n    try {\n      const refused = await onSubmit(body)\n      startTransition(() => {\n        if (typeof refused === 'string') return setError(refused)\n        change('')\n        setCaret(0)\n      })\n    } catch {\n      startTransition(() => setError('Something went wrong. Try again.'))\n    } finally {\n      startTransition(() => setIsSubmitting(false))\n    }\n  }\n\n  function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {\n    if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n      event.preventDefault()\n      void submit()\n    } else if (open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {\n      event.preventDefault()\n      const step = event.key === 'ArrowDown' ? 1 : -1\n      setActive((activeIndex + step + suggestions.length) % suggestions.length)\n    } else if (open && (event.key === 'Enter' || event.key === 'Tab')) {\n      event.preventDefault()\n      insert(suggestions[activeIndex])\n    } else if (open && event.key === 'Escape') {\n      event.preventDefault()\n      setDismissed(match?.start ?? null)\n    } else if (event.key === 'Escape' && onCancel) {\n      event.preventDefault()\n      onCancel()\n    }\n  }\n\n  return (\n    <form\n      method='post'\n      onSubmit={(event) => void submit(event)}\n      className={cn('flex flex-col gap-1.5', className)}\n    >\n      <InputGroup>\n        <InputGroupTextarea\n          ref={textareaRef}\n          aria-label={label}\n          aria-describedby={error ? `${id}-hint ${id}-error` : `${id}-hint`}\n          aria-autocomplete={people.length > 0 ? 'list' : undefined}\n          aria-controls={open ? `${id}-people` : undefined}\n          aria-activedescendant={open ? `${id}-person-${activeIndex}` : undefined}\n          aria-invalid={error ? true : undefined}\n          placeholder={placeholder}\n          value={text}\n          disabled={disabled}\n          readOnly={isSubmitting}\n          onChange={(event) => {\n            change(event.target.value)\n            setCaret(event.target.selectionStart)\n            setActive(0)\n          }}\n          onSelect={(event) => setCaret(event.currentTarget.selectionStart)}\n          onKeyDown={onKeyDown}\n        />\n        {open && (\n          <div\n            id={`${id}-people`}\n            role='listbox'\n            aria-label='People'\n            className='w-full border-t p-1'\n          >\n            {suggestions.map((person, index) => (\n              // oxlint-disable-next-line jsx-a11y/click-events-have-key-events -- the textarea's keydown handler picks options, as the APG combobox pattern does\n              <div\n                key={person.name}\n                id={`${id}-person-${index}`}\n                role='option'\n                tabIndex={-1}\n                aria-selected={index === activeIndex}\n                className='aria-selected:bg-accent aria-selected:text-accent-foreground flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm'\n                onMouseDown={(event) => event.preventDefault()}\n                onMouseMove={() => setActive(index)}\n                onClick={() => insert(person)}\n              >\n                <CommentAvatar author={person} size='sm' />\n                <span className='truncate'>{person.name}</span>\n              </div>\n            ))}\n          </div>\n        )}\n        <InputGroupAddon align='block-end'>\n          <div className='min-w-0 flex-1 text-xs font-normal'>{footer}</div>\n          {onCancel && (\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              disabled={isSubmitting}\n              onClick={onCancel}\n            >\n              Cancel\n            </Button>\n          )}\n          <Button type='submit' size='sm' disabled={disabled || isSubmitting}>\n            {isSubmitting ? pendingLabel : submitLabel}\n          </Button>\n        </InputGroupAddon>\n      </InputGroup>\n      <p id={`${id}-hint`} className='sr-only'>\n        {people.length > 0 && 'Type @ to mention someone. '}\n        Press Command or Control and Enter to submit.\n      </p>\n      <p aria-live='polite' className='sr-only'>\n        {open &&\n          `${suggestions.length} ${suggestions.length === 1 ? 'person' : 'people'} found`}\n      </p>\n      {error && (\n        <p id={`${id}-error`} role='alert' className='text-destructive text-sm'>\n          {error}\n        </p>\n      )}\n    </form>\n  )\n}\n\ninterface CommentThreadProps {\n  className?: string\n  comment: ThreadComment\n  currentUser: CommentAuthor\n  header?: ReactNode\n  /** Pass a fixed date, so times render the same on the server and in the browser. */\n  now: Date\n  onDelete?: (commentId: string) => void\n  onEdit?: (commentId: string, body: string) => Promise<void> | void\n  onReact?: (commentId: string, emoji: string) => void\n  onReply?: (body: string) => Promise<void> | void\n  onResolve?: (resolved: boolean) => void\n  people?: CommentAuthor[]\n  renderBadge?: (comment: ThreadComment) => ReactNode\n  /** @default 'UTC' */\n  timeZone?: string\n}\n\nfunction CommentThread({\n  className,\n  comment,\n  currentUser,\n  header,\n  now,\n  onDelete,\n  onEdit,\n  onReact,\n  onReply,\n  onResolve,\n  people,\n  renderBadge,\n  timeZone = 'UTC',\n}: CommentThreadProps) {\n  const id = useId()\n  const [replying, setReplying] = useState(false)\n  const [draft, setDraft] = useState('')\n  const [editingId, setEditingId] = useState<string | null>(null)\n  const [expanded, setExpanded] = useState(false)\n  const [status, setStatus] = useState('')\n  const pendingFocus = useRef<'reopen' | 'resolve' | null>(null)\n  const [focusTarget, setFocusTarget] = useState<{ selector: string } | null>(null)\n  const focusedTarget = useRef<typeof focusTarget>(null)\n  const rootRef = useRef<HTMLDivElement>(null)\n  const replies = comment.replies ?? []\n  const resolved = Boolean(comment.resolved)\n  const canReply = Boolean(onReply) && !resolved\n\n  useEffect(() => {\n    const target = pendingFocus.current\n    if (target && resolved === (target === 'reopen')) {\n      document.getElementById(`${id}-${target}`)?.focus()\n      pendingFocus.current = null\n    }\n  }, [id, resolved])\n\n  useEffect(() => {\n    if (!focusTarget || focusTarget === focusedTarget.current) return\n    focusedTarget.current = focusTarget\n    rootRef.current?.querySelector<HTMLElement>(focusTarget.selector)?.focus()\n  }, [focusTarget])\n\n  function focusReply() {\n    requestAnimationFrame(() => document.getElementById(`${id}-reply`)?.focus())\n  }\n\n  function startReply(to?: CommentAuthor) {\n    const mention = to && to.name !== currentUser.name ? `@${to.name} ` : ''\n    setDraft((current) =>\n      mention && !current.includes(mention.trim())\n        ? `${current}${current && !/\\s$/.test(current) ? ' ' : ''}${mention}`\n        : current,\n    )\n    if (!replying) return setReplying(true)\n    requestAnimationFrame(() => {\n      const textarea = document\n        .getElementById(`${id}-composer`)\n        ?.querySelector('textarea')\n      textarea?.focus()\n      textarea?.setSelectionRange(textarea.value.length, textarea.value.length)\n    })\n  }\n\n  function stopReply() {\n    setReplying(false)\n    setDraft('')\n    setFocusTarget({ selector: `#${CSS.escape(`${id}-reply`)}` })\n  }\n\n  function stopEditing(commentId: string) {\n    setEditingId(null)\n    setFocusTarget({\n      selector: `[data-comment-id=\"${CSS.escape(commentId)}\"] [aria-label^=\"More actions\"]`,\n    })\n  }\n\n  function resolve(next: boolean) {\n    pendingFocus.current = next ? 'reopen' : 'resolve'\n    setStatus(next ? 'Thread resolved' : 'Thread reopened')\n    setExpanded(false)\n    onResolve?.(next)\n  }\n\n  function renderComment(item: ThreadComment, isReply: boolean) {\n    const own = item.author.name === currentUser.name\n    const editing = editingId === item.id\n    const menuItems: CommentMenuItem[] = []\n    if (own && onEdit) {\n      menuItems.push({\n        icon: (\n          <IconPlaceholder\n            lucide='PencilIcon'\n            tabler='IconPencil'\n            hugeicons='PencilEdit02Icon'\n            phosphor='PencilSimpleIcon'\n            remixicon='RiPencilLine'\n          />\n        ),\n        label: 'Edit',\n        onSelect: () => setEditingId(item.id),\n      })\n    }\n    if (own && onDelete) {\n      menuItems.push({\n        icon: (\n          <IconPlaceholder\n            lucide='Trash2Icon'\n            tabler='IconTrash'\n            hugeicons='Delete02Icon'\n            phosphor='TrashIcon'\n            remixicon='RiDeleteBinLine'\n          />\n        ),\n        label: 'Delete',\n        onSelect: () => {\n          onDelete(item.id)\n          setStatus('Comment deleted')\n          if (isReply) focusReply()\n        },\n        variant: 'destructive',\n      })\n    }\n    return (\n      <CommentItem\n        comment={item}\n        now={now}\n        timeZone={timeZone}\n        people={people}\n        size={isReply ? 'sm' : 'default'}\n        badge={renderBadge?.(item)}\n        menu={\n          menuItems.length > 0 &&\n          !editing && (\n            <CommentMenu\n              items={menuItems}\n              label={`More actions for comment by ${item.author.name}`}\n            />\n          )\n        }\n        onReact={onReact && ((emoji) => onReact(item.id, emoji))}\n        editor={\n          editing &&\n          onEdit && (\n            <CommentComposer\n              focusOnMount\n              className='mt-1'\n              defaultValue={item.body}\n              label='Edit comment'\n              people={people}\n              submitLabel='Save'\n              pendingLabel='Saving'\n              onCancel={() => stopEditing(item.id)}\n              onSubmit={async (body) => {\n                await onEdit(item.id, body)\n                startTransition(() => {\n                  stopEditing(item.id)\n                  setStatus('Comment saved')\n                })\n              }}\n            />\n          )\n        }\n        actions={\n          <>\n            {canReply && (\n              <Button\n                id={isReply ? undefined : `${id}-reply`}\n                type='button'\n                variant='ghost'\n                size='xs'\n                aria-label={isReply ? `Reply to ${item.author.name}` : undefined}\n                onClick={() => startReply(isReply ? item.author : undefined)}\n              >\n                <IconPlaceholder\n                  lucide='ReplyIcon'\n                  tabler='IconCornerUpLeft'\n                  hugeicons='ArrowTurnBackwardIcon'\n                  phosphor='ArrowBendUpLeftIcon'\n                  remixicon='RiReplyLine'\n                />\n                Reply\n              </Button>\n            )}\n            {!isReply && !resolved && onResolve && (\n              <Button\n                id={`${id}-resolve`}\n                type='button'\n                variant='ghost'\n                size='xs'\n                onClick={() => resolve(true)}\n              >\n                <IconPlaceholder\n                  lucide='CircleCheckIcon'\n                  tabler='IconCircleCheck'\n                  hugeicons='CheckmarkCircle02Icon'\n                  phosphor='CheckCircleIcon'\n                  remixicon='RiCheckboxCircleLine'\n                />\n                Resolve\n              </Button>\n            )}\n          </>\n        }\n      />\n    )\n  }\n\n  const showComposer = replying && canReply\n  const connected = replies.length > 0 || showComposer\n\n  function connector(isLast: boolean) {\n    return (\n      <>\n        <span\n          aria-hidden\n          className='border-border absolute top-0 left-[calc(1rem-0.5px)] h-7 w-6 rounded-bl-[0.625rem] border-b border-l'\n        />\n        {!isLast && (\n          <span\n            aria-hidden\n            className='bg-border absolute top-[1.125rem] bottom-0 left-[calc(1rem-0.5px)] w-px'\n          />\n        )}\n      </>\n    )\n  }\n\n  return (\n    <div ref={rootRef} className={cn('flex flex-col gap-3', className)}>\n      {resolved && (\n        <div className='bg-muted/50 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg px-3 py-2'>\n          <p className='flex min-w-0 flex-1 basis-48 items-center gap-2 text-sm'>\n            <ActivityIcon\n              tone='success'\n              className='ring-0 [--activity-marker:1.25rem] [&_svg]:size-3'\n              icon={\n                <IconPlaceholder\n                  lucide='CheckIcon'\n                  tabler='IconCheck'\n                  hugeicons='Tick02Icon'\n                  phosphor='CheckIcon'\n                  remixicon='RiCheckLine'\n                />\n              }\n            />\n            <span className='font-medium'>Resolved</span>\n            <span className='text-muted-foreground min-w-0 truncate'>\n              {comment.author.name}: {comment.body}\n            </span>\n          </p>\n          <div className='ml-auto flex items-center gap-1'>\n            <Button\n              type='button'\n              variant='ghost'\n              size='xs'\n              aria-expanded={expanded}\n              aria-controls={expanded ? `${id}-thread` : undefined}\n              onClick={() => setExpanded(!expanded)}\n            >\n              {expanded\n                ? 'Hide'\n                : replies.length > 0\n                  ? `Show ${replies.length + 1} comments`\n                  : 'Show'}\n            </Button>\n            {onResolve && (\n              <Button\n                id={`${id}-reopen`}\n                type='button'\n                variant='outline'\n                size='xs'\n                onClick={() => resolve(false)}\n              >\n                Reopen\n              </Button>\n            )}\n          </div>\n        </div>\n      )}\n      {(!resolved || expanded) && (\n        <div id={`${id}-thread`} className='flex flex-col gap-3'>\n          {header}\n          <div>\n            <div className='relative'>\n              {connected && (\n                <span\n                  aria-hidden\n                  className='bg-border absolute top-10 bottom-0 left-[calc(1rem-0.5px)] w-px'\n                />\n              )}\n              {renderComment(comment, false)}\n            </div>\n            {replies.length > 0 && (\n              <ul aria-label={`Replies to ${comment.author.name}`}>\n                {replies.map((reply, index) => (\n                  <li key={reply.id} className='relative pt-4 pl-11'>\n                    {connector(index === replies.length - 1 && !showComposer)}\n                    {renderComment(reply, true)}\n                  </li>\n                ))}\n              </ul>\n            )}\n            {showComposer && (\n              <div id={`${id}-composer`} className='relative flex gap-3 pt-4 pl-11'>\n                {connector(true)}\n                <CommentAvatar author={currentUser} size='sm' />\n                <CommentComposer\n                  focusOnMount\n                  className='min-w-0 flex-1'\n                  label={`Reply to ${comment.author.name}`}\n                  placeholder='Reply'\n                  submitLabel='Reply'\n                  people={people}\n                  value={draft}\n                  onValueChange={setDraft}\n                  onCancel={stopReply}\n                  onSubmit={async (body) => {\n                    await onReply?.(body)\n                    startTransition(() => {\n                      setStatus('Reply posted')\n                      stopReply()\n                    })\n                  }}\n                />\n              </div>\n            )}\n          </div>\n        </div>\n      )}\n      <p aria-live='polite' className='sr-only'>\n        {status}\n      </p>\n    </div>\n  )\n}\n\nexport {\n  CommentAvatar,\n  CommentBody,\n  CommentComposer,\n  CommentItem,\n  CommentMenu,\n  CommentThread,\n  ReactionBar,\n  defaultReactions,\n  getMentions,\n  parseMentions,\n  toggleReaction,\n  updateComment,\n}\n\nexport type {\n  CommentAuthor,\n  CommentComposerProps,\n  CommentItemProps,\n  CommentMenuItem,\n  CommentReaction,\n  CommentThreadProps,\n  MentionSegment,\n  ReactionBarProps,\n  ReactionChoice,\n  ThreadComment,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/comments.tsx"
    }
  ],
  "type": "registry:component"
}
