import React, { useState, useEffect, useRef, useCallback } from 'react'; import { createPortal } from 'react-dom'; import type { ImageAttachment } from '../types'; import { AttachmentsButton } from './AttachmentsButton'; import { submitHint } from '../utils/platform'; import { useDraggable } from '../hooks/useDraggable'; interface CommentPopoverProps { /** Element to anchor the popover near (re-reads position on scroll) */ anchorEl?: HTMLElement; /** Static viewport rect to anchor near when no stable DOM element exists */ anchorRect?: DOMRect; /** Truncated selected text shown in header, or empty for global */ contextText: string; /** Whether this is a global comment */ isGlobal: boolean; /** Pre-filled text (for type-to-comment) */ initialText?: string; /** Called on submit with comment text and optional images */ onSubmit: (text: string, images?: ImageAttachment[]) => void; /** Called when popover is closed/cancelled */ onClose: () => void; /** Opt-in: persist text + images across close/reopen, keyed by this string. Cleared on submit. */ draftKey?: string; } const MAX_POPOVER_WIDTH = 384; const GAP = 8; // Module-level draft store: survives popover unmount so reopening the same key restores in-progress text. const draftStore = new Map(); /** Mirrors the latest text + images into `draftStore[draftKey]` so they outlive popover unmount. No-op without a key. */ function useCommentDraftSync(draftKey: string | undefined, text: string, images: ImageAttachment[]) { useEffect(() => { if (!draftKey) return; if (text.trim() || images.length > 0) { draftStore.set(draftKey, { text, images }); } else { draftStore.delete(draftKey); } }, [draftKey, text, images]); } function computePosition(anchorRect: DOMRect): { top: number; left: number; flipAbove: boolean; width: number } { const spaceBelow = window.innerHeight - anchorRect.bottom; const flipAbove = spaceBelow < 280; const width = Math.min(MAX_POPOVER_WIDTH, window.innerWidth - 32); const top = flipAbove ? anchorRect.top - GAP : anchorRect.bottom + GAP; let left = anchorRect.left + anchorRect.width / 2 - width / 2; left = Math.max(16, Math.min(left, window.innerWidth - width - 16)); return { top, left, flipAbove, width }; } export const CommentPopover: React.FC = ({ anchorEl, anchorRect, contextText, isGlobal, initialText = '', onSubmit, onClose, draftKey, }) => { const [mode, setMode] = useState<'popover' | 'dialog'>('popover'); const initialDraft = draftKey ? draftStore.get(draftKey) : undefined; const [text, setText] = useState(initialDraft?.text ?? initialText); const [images, setImages] = useState(initialDraft?.images ?? []); const [position, setPosition] = useState<{ top: number; left: number; flipAbove: boolean; width: number } | null>(null); const textareaRef = useRef(null); const popoverRef = useRef(null); const { dragPosition, dragHandleProps, wasDragged, reset: resetDrag } = useDraggable(popoverRef); useCommentDraftSync(draftKey, text, images); // Reset drag when anchor changes (new annotation) or mode switches useEffect(() => { resetDrag(); }, [anchorEl, anchorRect, resetDrag]); useEffect(() => { if (mode === 'popover') resetDrag(); }, [mode, resetDrag]); // Track anchor position on scroll/resize (popover mode only, not after user drag) useEffect(() => { if (mode !== 'popover' || wasDragged) return; const update = () => { const rect = anchorEl?.getBoundingClientRect() ?? anchorRect; if (rect) setPosition(computePosition(rect)); }; update(); window.addEventListener('scroll', update, true); window.addEventListener('resize', update); return () => { window.removeEventListener('scroll', update, true); window.removeEventListener('resize', update); }; }, [anchorEl, anchorRect, mode, wasDragged]); // Focus textarea on mount and mode changes useEffect(() => { const id = setTimeout(() => { const el = textareaRef.current; if (el) { el.focus(); el.selectionStart = el.selectionEnd = el.value.length; } }, 0); return () => clearTimeout(id); }, [mode]); // Click-outside for popover mode useEffect(() => { if (mode !== 'popover') return; const handlePointerDown = (e: PointerEvent) => { const target = e.target as Node | null; if (!target) return; if (popoverRef.current?.contains(target)) return; // Don't close if clicking inside a child portal (AttachmentsButton, ImageAnnotator, etc.) const el = target as HTMLElement; if (el.closest?.('[data-popover-layer]')) return; onClose(); }; document.addEventListener('pointerdown', handlePointerDown, true); return () => document.removeEventListener('pointerdown', handlePointerDown, true); }, [mode, onClose]); const handleSubmit = useCallback(() => { if (text.trim() || images.length > 0) { if (draftKey) draftStore.delete(draftKey); onSubmit(text, images.length > 0 ? images : undefined); } }, [text, images, onSubmit, draftKey]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); if (mode === 'dialog') { setMode('popover'); } else { onClose(); } return; } if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && !e.nativeEvent.isComposing) { e.preventDefault(); handleSubmit(); } }; const headerLabel = isGlobal ? 'Global Comment' : contextText ? `"${contextText.length > 50 ? contextText.slice(0, 50) + '...' : contextText}"` : 'Comment'; const canSubmit = text.trim().length > 0 || images.length > 0; if (mode === 'dialog') { return createPortal(
{/* Backdrop */}
{/* Dialog card */}
e.stopPropagation()} > {/* Header */}
{headerLabel}
{/* Textarea */}