"use client"; import { useCallback, useEffect, useId, useRef, useState, type Dispatch, type MouseEvent, type ReactNode, type RefObject, type SetStateAction, } from "react"; import { createPortal } from "react-dom"; import { useShallow } from "zustand/react/shallow"; import { IconMessage, IconPlus, IconPlayerPlay, IconTrash } from "@tabler/icons-react"; import { Button } from "@kandev/ui/button"; import { Textarea } from "@kandev/ui/textarea"; import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, } from "@kandev/ui/drawer"; import { useTouchDrawer } from "@/hooks/use-compact-task-chrome"; import { PlanSelectionPopover } from "@/components/task/plan-selection-popover"; import { floatingBounds, placeFloatingRect } from "@/components/task/floating-selection-position"; import { useCommentsStore } from "@/lib/state/slices/comments"; import type { AgentMessageComment } from "@/lib/state/slices/comments"; import { useRunComment } from "@/hooks/domains/comments/use-run-comment"; import { agentMessageCommentHighlightName, createMessageTextAnchor, getMessageSelection, isSelectableAgentMessage, resolveMessageTextAnchor, type MessageSelection, } from "@/lib/chat/agent-message-comments"; import type { Message } from "@/lib/types/http"; import { cn, generateUUID } from "@/lib/utils"; import { messageCommentDecorationAtPoint, supportsCustomHighlights, useMessageCommentDecorations, useMessageCommentShortcut, } from "./use-message-comment-dom"; import { MessageCommentDecorationOverlay, MessageCustomHighlightStyle, } from "./message-comment-decorations"; import { useTranslation } from "react-i18next"; type MessageCommentSurfaceProps = { message: Message; sessionId?: string | null; isTurnActive: boolean; children: ReactNode; }; type CommentTarget = { selection: MessageSelection; anchor: AgentMessageComment["anchor"]; position: { x: number; y: number }; editingCommentId?: string; editingText?: string; }; const EMPTY_COMMENT_IDS: string[] = []; const INTERACTIVE_MESSAGE_TARGETS = 'a, button, input, textarea, select, summary, [role="button"], [role="link"], [contenteditable="true"]'; function isInteractiveMessageTarget(target: EventTarget | null) { return target instanceof Element && Boolean(target.closest(INTERACTIVE_MESSAGE_TARGETS)); } function useDecorationClickHandler( decorations: ReturnType, openExistingComment: (commentId: string, position: { x: number; y: number }) => void, ) { return useCallback( (event: MouseEvent) => { if (isInteractiveMessageTarget(event.target)) return; const selection = window.getSelection(); if (selection && !selection.isCollapsed) return; const decoration = messageCommentDecorationAtPoint(decorations, event.clientX, event.clientY); if (!decoration) return; event.preventDefault(); openExistingComment(decoration.comment.id, { x: event.clientX, y: event.clientY }); }, [decorations, openExistingComment], ); } function commentFromTarget( message: Message, sessionId: string, target: CommentTarget, renderedText: string, feedback: string, ): AgentMessageComment | null { const resolved = resolveMessageTextAnchor(target.anchor, renderedText); if (!resolved) return null; const anchor = createMessageTextAnchor(message.id, renderedText, resolved.start, resolved.end); return { id: generateUUID(), sessionId, source: "agent-message", messageId: message.id, selectedText: anchor.selectedText, text: feedback.trim(), createdAt: new Date().toISOString(), status: "pending", anchor, }; } function SelectionCommentTrigger({ selection, isTouch, onOpen, portalContainer, }: { selection: MessageSelection; isTouch: boolean; onOpen: () => void; portalContainer?: HTMLElement | null; }) { const { t } = useTranslation(); const size = isTouch ? 44 : 28; const portalRect = portalContainer?.getBoundingClientRect(); const outerSize = size + 8; const position = placeFloatingRect({ left: selection.rect.right - outerSize, topCandidates: [selection.rect.top - outerSize - 8, selection.rect.bottom + 8], width: outerSize, height: outerSize, bounds: floatingBounds(portalRect), }); return createPortal(
, portalContainer ?? document.body, ); } function DrawerCommentActions({ isEditing, disabled, onAdd, onRun, onDelete, }: { isEditing: boolean; disabled: boolean; onAdd: () => void; onRun?: () => void; onDelete?: () => void; }) { const { t } = useTranslation(); return (
{isEditing && onDelete ? ( ) : ( )}
{onRun && !isEditing ? ( ) : null}
); } function MessageCommentDrawer({ target, open, onClose, onAdd, onRun, onDelete, errorMessage, }: { target: CommentTarget | null; open: boolean; onClose: () => void; onAdd: (feedback: string) => boolean | void; onRun: (feedback: string) => boolean | void; onDelete: (() => void) | undefined; errorMessage?: string | null; }) { const { t } = useTranslation(); const [feedback, setFeedback] = useState(target?.editingText ?? ""); const targetKey = `${target?.editingCommentId ?? "new"}:${target?.selection.start ?? 0}:${target?.selection.end ?? 0}`; useEffect(() => { setFeedback(target?.editingText ?? ""); }, [targetKey, target?.editingText]); if (!target) return null; const isEditing = target.editingCommentId !== undefined; const submit = () => { if (feedback.trim() && onAdd(feedback.trim()) !== false) onClose(); }; const run = () => { if (feedback.trim() && onRun(feedback.trim()) !== false) onClose(); }; return ( !next && onClose()}> {isEditing ? t("task:editComment") : t("task:comment")} “{target.selection.selectedText}”