"use client"; import { useLayoutEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction, type ReactNode, type RefObject, } from "react"; import { IconColumns } from "@tabler/icons-react"; import type { ActiveThread } from "@/lib/threads/active-threads"; import { useTranslation } from "react-i18next"; import { ThreadColumn } from "./thread-column"; import { useThreadColumnActivation } from "./use-thread-column-activation"; import { useThreadFocusRequest } from "./use-thread-focus-request"; import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint"; import { MobileThreadPicker } from "./mobile-thread-picker"; import { ThreadTaskActionsProvider } from "./thread-task-actions"; import { useThreadSelectionRecovery } from "./use-thread-selection-recovery"; import { resolveThreadLayout, type ThreadLayoutResult } from "./thread-layout"; import type { ThreadLayout } from "@/lib/state/slices/ui/thread-view-types"; import { cn } from "@/lib/utils"; type ThreadsBoardProps = { threads: ActiveThread[]; isLoading?: boolean; layout?: ThreadLayout; autoHideComposer?: boolean; /** Column a deep link asked for; scrolled into view and ringed on arrival. */ focusedTaskId?: string | null; /** * URL-driven callers must pass a stable request identity across target absence. * Omission keys dismissal to the resolved task ID for legacy callers, so a * temporary null target resets dismissal rather than retaining URL semantics. */ focusRequestKey?: string | null; /** Session a task-detail link asked the target column to select. */ focusedSessionId?: string | null; /** Removes a target session query after the target column proves it invalid. */ onInvalidRequestedSession?: (taskId: string, sessionId: string) => void; onOpenTask: (taskId: string) => void; /** Composes the page header with the viewport's active phone thread. */ renderHeader?: (activeMobileTaskId: string | null, gridHeightFallback: boolean) => ReactNode; }; function ThreadsPlaceholder({ testId, children }: { testId: string; children: React.ReactNode }) { return (
{children}
); } function ThreadsEmptyState() { const { t } = useTranslation(); return ( ); } function ThreadsLoadingState() { const { t } = useTranslation(); return (

{t("threads:loading")}

); } function focusThreadPicker(event: Event, column: Element | undefined) { const trigger = column?.querySelector('[data-testid="thread-picker-trigger"]'); if (!trigger) return; event.preventDefault(); trigger.focus({ preventScroll: true }); } type BoardSize = { height: number; width: number } | null; function useBoardContentSize( boardRef: RefObject, isEmpty: boolean, setSize: Dispatch>, ) { useLayoutEffect(() => { const board = boardRef.current; if (!board) setSize(null); if (!board || typeof ResizeObserver === "undefined") return; let disposed = false; const observer = new ResizeObserver((entries) => { if (disposed) return; const entry = entries[0]; if (entry) { const { height, width } = entry.contentRect; setSize((previous) => previous?.height === height && previous.width === width ? previous : { height, width }, ); } }); observer.observe(board); return () => { disposed = true; observer.disconnect(); }; }, [boardRef, isEmpty, setSize]); } function useThreadBoardLayout( orderedIds: readonly string[], layout: ThreadLayout, isMobile: boolean, focusedTaskId: string | null, ) { const [size, setSize] = useState(null); const composition = resolveThreadLayout({ layout, isMobile, taskCount: orderedIds.length, contentHeight: size?.height ?? null, }); const layoutKey = `${composition.layout}:${composition.rows}:${isMobile}:${size?.width}`; const activation = useThreadColumnActivation(orderedIds, focusedTaskId, layoutKey); useBoardContentSize(activation.boardRef, orderedIds.length === 0, setSize); const rememberThread = useThreadSelectionRecovery( orderedIds, activation.boardRef, isMobile, layoutKey, ); return { ...activation, composition, layoutKey, rememberThread }; } function boardLayoutStyle(composition: ThreadLayoutResult) { if (composition.layout !== "grid") return undefined; return { gridAutoFlow: "column", gridTemplateRows: `repeat(${composition.rows}, minmax(0, 1fr))`, gridTemplateColumns: `repeat(${composition.columns}, minmax(360px, 1fr))`, }; } function useThreadPicker( boardRef: RefObject, isMobile: boolean, mobileTaskId: string | null, firstId: string | null, ) { const [open, setOpen] = useState(false); if (!isMobile && open) setOpen(false); const returnFocusTaskId = useRef(null); const taskColumn = (taskId: string | null) => Array.from(boardRef.current?.children ?? []).find( (element) => element.getAttribute("data-thread-column-id") === taskId, ); function choose(taskId: string) { returnFocusTaskId.current = taskId; setOpen(true); } function select(taskId: string) { returnFocusTaskId.current = taskId; taskColumn(taskId)?.scrollIntoView({ inline: "start", block: "nearest", behavior: "instant" }); setOpen(false); } function restoreFocus(event: Event) { focusThreadPicker( event, taskColumn(returnFocusTaskId.current) ?? taskColumn(mobileTaskId) ?? taskColumn(firstId), ); } return { open, setOpen, choose, select, restoreFocus }; } /** * The deck: every live agent conversation as its own column, scrolled * horizontally. Columns keep the order the selector gave them, so a thread the * reader is following does not jump while they read it. */ export function ThreadsBoard({ threads, isLoading = false, layout = "columns", autoHideComposer = false, focusedTaskId = null, focusRequestKey = focusedTaskId, focusedSessionId = null, onInvalidRequestedSession, onOpenTask, renderHeader, }: ThreadsBoardProps) { const { markedTaskId, activationTaskId, retire } = useThreadFocusRequest( focusedTaskId, focusRequestKey, ); const { isMobile, isFinePointer } = useResponsiveBreakpoint(); const orderedIds = useMemo(() => threads.map((thread) => thread.taskId), [threads]); const { boardRef, registerColumn, preloadTaskIds, detailTaskIds, mobileTaskId, composition, layoutKey, rememberThread, } = useThreadBoardLayout(orderedIds, layout, isMobile, activationTaskId); const picker = useThreadPicker(boardRef, isMobile, mobileTaskId, orderedIds[0] ?? null); return (
{renderHeader?.(mobileTaskId, composition.heightFallback)} {threads.length === 0 ? (
{isLoading ? : }
) : (
{ retire(); rememberThread(event); }} // Capture phase: a column's own handlers must not be able to swallow the // interaction that retires the mark. onPointerDownCapture={(event) => { retire(); rememberThread(event); }} onFocusCapture={(event) => { retire(); rememberThread(event); }} className={cn( "min-h-0 min-w-0 w-full flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain md:gap-3 md:p-3 md:snap-none", composition.layout === "grid" ? "grid" : "flex", )} style={boardLayoutStyle(composition)} > {threads.map((thread) => ( picker.choose(thread.taskId), } : undefined } isFocused={thread.taskId === markedTaskId} layoutKey={layoutKey} requestedSessionId={thread.taskId === focusedTaskId ? focusedSessionId : null} isPreloaded={preloadTaskIds.has(thread.taskId)} isDetailActive={detailTaskIds.has(thread.taskId)} onInvalidRequestedSession={onInvalidRequestedSession} onColumnRef={registerColumn} onOpenTask={onOpenTask} /> ))}
)} {isMobile && threads.length > 0 && ( )}
); }