"use client"; import React, { useState, useCallback, useRef, useEffect } from "react"; import { createPortal } from "react-dom"; import { IconPlus, IconTrash, IconGripHorizontal, IconPlayerPlay } from "@tabler/icons-react"; import { Button } from "@kandev/ui/button"; import { Textarea } from "@kandev/ui/textarea"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip"; import { cn } from "@/lib/utils"; import { floatingBounds, placeFloatingRect } from "@/components/task/floating-selection-position"; import { useTranslation } from "react-i18next"; import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, } from "@kandev/ui/drawer"; import { useTouchDrawer } from "@/hooks/use-compact-task-chrome"; type SelectionPosition = { x: number; y: number; }; type PlanSelectionPopoverProps = { selectedText: string; position: SelectionPosition; onAdd: (comment: string, selectedText: string) => boolean | void | Promise; onAddAndRun?: (comment: string, selectedText: string) => boolean | void | Promise; onClose: () => void; editingComment?: string; onDelete?: () => boolean | void | Promise; testId?: string; inputTestId?: string; addButtonTestId?: string; runButtonTestId?: string; portalContainer?: HTMLElement | null; errorMessage?: string | null; runDisabledReason?: string | null; }; const POPOVER_WIDTH = 340; const POPOVER_HEIGHT = 180; const MARGIN = 8; /** Drag support for the popover. */ function useDrag() { const [offset, setOffset] = useState({ dx: 0, dy: 0 }); const dragging = useRef(false); const startPos = useRef({ x: 0, y: 0 }); const startOffset = useRef({ dx: 0, dy: 0 }); const onMouseDown = useCallback( (e: React.MouseEvent) => { e.preventDefault(); dragging.current = true; startPos.current = { x: e.clientX, y: e.clientY }; startOffset.current = { ...offset }; const onMouseMove = (ev: MouseEvent) => { if (!dragging.current) return; setOffset({ dx: startOffset.current.dx + ev.clientX - startPos.current.x, dy: startOffset.current.dy + ev.clientY - startPos.current.y, }); }; const onMouseUp = () => { dragging.current = false; document.removeEventListener("mousemove", onMouseMove); document.removeEventListener("mouseup", onMouseUp); }; document.addEventListener("mousemove", onMouseMove); document.addEventListener("mouseup", onMouseUp); }, [offset], ); return { offset, onMouseDown }; } function usePopoverDismiss( onClose: () => void, popoverRef: React.RefObject, disabled: boolean, ) { useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if (!disabled && popoverRef.current && !popoverRef.current.contains(e.target as Node)) { onClose(); } }; const timer = setTimeout(() => { document.addEventListener("mousedown", handleClickOutside); }, 100); return () => { clearTimeout(timer); document.removeEventListener("mousedown", handleClickOutside); }; }, [disabled, onClose, popoverRef]); useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape" && !disabled) onClose(); }; document.addEventListener("keydown", handleKeyDown); return () => document.removeEventListener("keydown", handleKeyDown); }, [disabled, onClose]); } function usePopoverComposer( comment: string, selectedText: string, onAdd: (comment: string, selectedText: string) => boolean | void | Promise, onClose: () => void, onAddAndRun?: (comment: string, selectedText: string) => boolean | void | Promise, ) { const [isSubmitting, setIsSubmitting] = useState(false); const handleSubmit = useCallback(async () => { if (!comment.trim()) return; setIsSubmitting(true); try { if ((await onAdd(comment.trim(), selectedText)) !== false) onClose(); } finally { setIsSubmitting(false); } }, [comment, onAdd, selectedText, onClose]); const handleSubmitAndRun = useCallback(async () => { if (!comment.trim() || !onAddAndRun) return; setIsSubmitting(true); try { if ((await onAddAndRun(comment.trim(), selectedText)) !== false) onClose(); } finally { setIsSubmitting(false); } }, [comment, onAddAndRun, selectedText, onClose]); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.repeat) return; if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); if (e.shiftKey && onAddAndRun) { void handleSubmitAndRun(); } else { void handleSubmit(); } } }, [handleSubmit, handleSubmitAndRun, onAddAndRun], ); return { handleSubmit, handleSubmitAndRun, handleKeyDown, isDisabled: !comment.trim() || isSubmitting, isSubmitting, previewText: selectedText.length > 80 ? selectedText.slice(0, 80).trim() + "\u2026" : selectedText, }; } function useCommentDelete(onDelete: PlanSelectionPopoverProps["onDelete"], onClose: () => void) { const [isDeleting, setIsDeleting] = useState(false); const deleteComment = useCallback(async () => { if (!onDelete) return; setIsDeleting(true); try { if ((await onDelete()) !== false) onClose(); } finally { setIsDeleting(false); } }, [onClose, onDelete]); return { isDeleting, deleteComment: onDelete ? deleteComment : undefined }; } function CommentMutationMessages({ errorMessage, runDisabledReason, canRun, className, }: { errorMessage?: string | null; runDisabledReason?: string | null; canRun: boolean; className: string; }) { return ( <> {errorMessage ? (

{errorMessage}

) : null} {runDisabledReason && canRun ? (

{runDisabledReason}

) : null} ); } function PlanCommentDrawerHeader({ editingComment, selectedText, }: { editingComment?: string; selectedText: string; }) { const { t } = useTranslation(); return ( {editingComment ? t("task:editComment") : t("task:comment")} “{selectedText}” ); } function DeleteCommentButton({ onDelete, disabled }: { onDelete?: () => void; disabled: boolean }) { const { t } = useTranslation(); if (!onDelete) return null; return ( ); } function RunCommentButton({ onSubmitAndRun, isDisabled, runButtonTestId, runDisabledReason, }: { onSubmitAndRun?: () => void; isDisabled: boolean; runButtonTestId?: string; runDisabledReason?: string | null; }) { const { t } = useTranslation(); if (!onSubmitAndRun) return null; return (

{runDisabledReason || t("task:saveAndSendToAgent")}

); } function PopoverActions({ isEditing, isDisabled, onSubmit, onSubmitAndRun, onDelete, addButtonTestId, runButtonTestId, runDisabledReason, mutationPending, }: { isEditing: boolean; isDisabled: boolean; onSubmit: () => void; onSubmitAndRun?: () => void; onDelete?: () => void; addButtonTestId?: string; runButtonTestId?: string; runDisabledReason?: string | null; mutationPending: boolean; }) { const { t } = useTranslation(); const splitAction = Boolean(onSubmitAndRun && !isEditing); return (
{isEditing ? t("task:cmdEnterToUpdate") : t("task:cmdEnterToAdd")} {onSubmitAndRun && !isEditing ? t("task:shiftEnterToRun") : ""}

{isEditing ? t("task:updateComment") : t("task:saveCommentForReview")}

); } function isCommentMutationPending(isSubmitting: boolean, isDeleting: boolean): boolean { return isSubmitting || isDeleting; } function useMutationProtectedClose(onClose: () => void, mutationPending: boolean) { return useCallback(() => { if (!mutationPending) onClose(); }, [mutationPending, onClose]); } function DesktopPlanSelectionPopover({ selectedText, position, onAdd, onAddAndRun, onClose, editingComment, onDelete, testId, inputTestId, addButtonTestId, runButtonTestId, portalContainer, errorMessage, runDisabledReason, }: PlanSelectionPopoverProps) { const { t } = useTranslation(); const [comment, setComment] = useState(editingComment || ""); const textareaRef = useRef(null); const popoverRef = useRef(null); const { offset, onMouseDown } = useDrag(); const { isDeleting, deleteComment } = useCommentDelete(onDelete, onClose); useEffect(() => { textareaRef.current?.focus(); }, []); const effectiveOnAddAndRun = editingComment ? undefined : onAddAndRun; const { handleSubmit, handleSubmitAndRun, handleKeyDown, isDisabled, isSubmitting, previewText } = usePopoverComposer(comment, selectedText, onAdd, onClose, effectiveOnAddAndRun); const mutationPending = isCommentMutationPending(isSubmitting, isDeleting); usePopoverDismiss(onClose, popoverRef, mutationPending); const portalRect = portalContainer?.getBoundingClientRect(); const { left, top } = placeFloatingRect({ left: position.x, topCandidates: [position.y + 4, position.y - POPOVER_HEIGHT - 4], width: POPOVER_WIDTH, height: POPOVER_HEIGHT, bounds: floatingBounds(portalRect), margin: MARGIN, }); return createPortal(

“{previewText}”