"use client"; /** * The Little Tutor entry point under a message. * * A thread records the message it was opened from in * ``preferences.tutor_source_message_id``. This renders one quiet line there — * ``Little Tutor ×2`` — and opens a popover listing those threads: each row * focuses the existing tab, and deleting one closes it for good. * * Bare side chats and threads created before the attribution existed have no * source message, so they never reach this component; the viewer's own * launcher still lists them. */ import { useCallback, useEffect, useRef, useState, } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; import { MessagesSquare, Trash2, Unlink } from "lucide-react"; import type { SessionSummary } from "@/lib/session-api"; import { placeMenu } from "@/lib/floating-menu"; import { formatRelativeTime } from "@/lib/relative-time"; import { displaySessionTitle } from "@/lib/session-title"; const POPOVER_WIDTH = 304; interface PopoverPosition { left: number; top?: number; bottom?: number; maxHeight: number; } export interface MessageThreadMarkerProps { threads: SessionSummary[]; /** User bubbles align right; assistant bubbles align left. */ align?: "left" | "right"; onOpen: (thread: SessionSummary) => void; onDelete: (thread: SessionSummary) => Promise; /** Remove the thread from this message without deleting the conversation. */ onDetach?: (thread: SessionSummary) => Promise; } export default function MessageThreadMarker({ threads, align = "left", onOpen, onDelete, onDetach, }: MessageThreadMarkerProps) { const { t, i18n } = useTranslation(); const [open, setOpen] = useState(false); const [position, setPosition] = useState(null); const [confirming, setConfirming] = useState(null); const [deleting, setDeleting] = useState(null); const [detaching, setDetaching] = useState(null); const triggerRef = useRef(null); const popoverRef = useRef(null); const close = useCallback((restoreFocus = false) => { setOpen(false); setPosition(null); setConfirming(null); if (restoreFocus) triggerRef.current?.focus(); }, []); const toggle = useCallback(() => { if (open) { close(); return; } const trigger = triggerRef.current; if (!trigger) return; const rect = trigger.getBoundingClientRect(); const placement = placeMenu(rect, POPOVER_WIDTH); setPosition({ left: placement.left, // ``placeMenu`` reports the anchored edge; above the button we must hang // the popover from its bottom instead of starting it at the anchor top. ...(placement.openUpward ? { bottom: window.innerHeight - rect.top + 8 } : { top: rect.bottom + 8 }), maxHeight: placement.maxHeight, }); setOpen(true); }, [close, open]); // A popover that outlives its threads (the last one was deleted) has nothing // left to say. useEffect(() => { if (open && threads.length === 0) close(); }, [close, open, threads.length]); useEffect(() => { if (!open) return; const onPointer = (event: MouseEvent) => { const target = event.target; if (!(target instanceof Node)) return; if (popoverRef.current?.contains(target) || triggerRef.current?.contains(target)) { return; } close(); }; const onKey = (event: KeyboardEvent) => { if (event.key !== "Escape") return; event.stopPropagation(); close(true); }; const onScroll = (event: Event) => { if (event.target instanceof Node && popoverRef.current?.contains(event.target)) { return; } close(); }; const onResize = () => close(); document.addEventListener("mousedown", onPointer); document.addEventListener("keydown", onKey, true); window.addEventListener("resize", onResize); window.addEventListener("scroll", onScroll, true); return () => { document.removeEventListener("mousedown", onPointer); document.removeEventListener("keydown", onKey, true); window.removeEventListener("resize", onResize); window.removeEventListener("scroll", onScroll, true); }; }, [close, open]); if (threads.length === 0) return null; const openThread = (thread: SessionSummary) => { close(); onOpen(thread); }; const deleteThread = async (thread: SessionSummary) => { if (deleting) return; setDeleting(thread.session_id); try { await onDelete(thread); setConfirming(null); } catch { // The page that owns the deletion says what went wrong; return the row // to its normal state so the learner can try again. setConfirming(null); } finally { setDeleting(null); } }; const detachThread = async (thread: SessionSummary) => { if (!onDetach || detaching) return; setDetaching(thread.session_id); try { await onDetach(thread); } catch { // The page that owns the detach explains the failure; the row stays. } finally { setDetaching(null); } }; return (
{open && position ? createPortal(

{t("Tutor threads on this message")}

{threads.map((thread) => ( openThread(thread)} onDetach={() => void detachThread(thread)} onAskDelete={() => setConfirming(thread.session_id)} onCancelDelete={() => setConfirming(null)} onConfirmDelete={() => void deleteThread(thread)} /> ))}
, document.body, ) : null}
); } function ThreadRow({ thread, timeLabel, confirming, deleting, detaching, deleteDisabled, canDetach, onOpen, onDetach, onAskDelete, onCancelDelete, onConfirmDelete, }: { thread: SessionSummary; timeLabel: string; confirming: boolean; deleting: boolean; detaching: boolean; deleteDisabled: boolean; canDetach: boolean; onOpen: () => void; onDetach: () => void; onAskDelete: () => void; onCancelDelete: () => void; onConfirmDelete: () => void; }) { const { t } = useTranslation(); const title = displaySessionTitle(thread.title, t("Side chat")); return (
{confirming ? ( ) : ( {canDetach ? ( ) : null} )}
); }