Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailsCard.tsx

176 lines7.2 KB

1import { useLayoutEffect, useState, type ReactNode, type RefObject } from "react";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { ScrollArea } from "../ui/scroll-area";
4import { cn } from "../../lib/utils";
5import { Popover, PopoverPopup, PopoverCreateHandle } from "../ui/popover";
6import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore";
7import { useChatCanvas } from "./ChatCanvasContext";
8import {
9 THREAD_DETAILS_CARD_GAP,
10 resolveThreadDetailsCardDensity,
11} from "./threadDetailsCardLayout";
12import { observeResize } from "../../lib/observeResize";
13​
14export function ThreadDetailsCard({
15 threadRef,
16 anchor,
17 handle,
18 children,
19}: {
20 threadRef: ScopedThreadRef;
21 anchor: RefObject<Element | null>;
22 handle: ReturnType<typeof PopoverCreateHandle>;
23 children: (density: "full" | "compact" | "essential") => ReactNode;
24}) {
25 const canvas = useChatCanvas();
26 const preferredPlacement = canvas?.preferredDetailsCard ?? null;
27 const placement = canvas?.detailsCardPlacement ?? null;
28 const mode = placement ? "inline" : "popover";
29 const topInset = canvas?.detailsCardTopInset ?? 0;
30 const inlineOpen = useRightPanelStore((state) =>
31 selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"),
32 );
33 const popoverOpen = useRightPanelStore((state) =>
34 selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"),
35 );
36 const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}`;
37 const [measurements, setMeasurements] = useState({
38 key: measurementKey,
39 heights: { full: 0, compact: 0 },
40 });
41 const contentHeights =
42 measurements.key === measurementKey ? measurements.heights : { full: 0, compact: 0 };
43 const height = placement?.height ?? Math.max(0, (canvas?.container.height ?? 0) - 52);
44 const density = resolveThreadDetailsCardDensity(height, contentHeights);
45 const measureDetailsCard = canvas?.measureDetailsCard;
46 const cardWidth = preferredPlacement?.width;
47 // The mode derives from canvas measurements, the preview frame and the
48 // inline flag, which live in three stores, so no single write site sees the
49 // card leave popover mode. A flag left set would reopen the popover unasked
50 // when the card returns to popover mode.
51 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the popover flag in the right panel store when the derived mode turns inline
52 useLayoutEffect(() => {
53 if (mode === "inline" && popoverOpen)
54 useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", false);
55 }, [mode, popoverOpen, threadRef]);
56 const [contentElement, setContentElement] = useState<HTMLDivElement | null>(null);
57 const { environmentId, threadId } = threadRef;
58 // Re-measures when the density or measurement key changes, so each density's
59 // height is measured once it renders.
60 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the card's DOM height via ResizeObserver and reports it to the canvas
61 useLayoutEffect(() => {
62 const element = contentElement;
63 if (!element || density === "essential") return;
64 const measure = () => {
65 const frame = element.closest<HTMLElement>("[data-thread-details-card]");
66 const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0);
67 // PR lists and lineage scroll as they expand. Counting them toward density would hide
68 // the section and workspace controls when the user asks to see more rows.
69 const lists = element.querySelectorAll<HTMLElement>(
70 "[data-thread-relationships-panel], [data-thread-details-pr-list]",
71 );
72 const fittingHeight =
73 next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0);
74 setMeasurements((current) => {
75 const heights = current.key === measurementKey ? current.heights : { full: 0, compact: 0 };
76 return current.key === measurementKey && heights[density] === fittingHeight
77 ? current
78 : { key: measurementKey, heights: { ...heights, [density]: fittingHeight } };
79 });
80 // Only the laid-out DOM knows the full card height, and the canvas keeps preview
81 // frames clear of it, so it is reported from this measure effect.
82 if (density === "full" && cardWidth !== undefined) {
83 measureDetailsCard?.({
84 threadRef: { environmentId, threadId },
85 width: cardWidth,
86 fullContentHeight: next,
87 });
88 }
89 };
90 measure();
91 return observeResize(element, measure);
92 }, [
93 contentElement,
94 density,
95 measurementKey,
96 cardWidth,
97 measureDetailsCard,
98 environmentId,
99 threadId,
100 ]);
101 const card = (
102 <div
103 className={cn(
104 "dropdown-glass isolate contain-paint grid max-h-full grid-rows-[minmax(0,1fr)] overflow-hidden rounded-2xl",
105 mode === "popover" &&
106 "max-h-[min(calc(100dvh-6.5rem),calc(var(--available-height,100dvh)-1rem))]",
107 )}
108 style={placement ? { maxHeight: height } : undefined}
109 data-thread-details-card
110 >
111 <ScrollArea scrollFade className="min-h-0">
112 <div ref={setContentElement}>{children(density)}</div>
113 </ScrollArea>
114 </div>
115 );
116 return (
117 <Popover
118 handle={handle}
119 open={mode === "popover" && popoverOpen}
120 onOpenChange={(open, details) => {
121 const target =
122 details.reason === "focus-out"
123 ? (details.event as FocusEvent).relatedTarget
124 : details.reason === "outside-press"
125 ? details.event.target
126 : null;
127 if (!open && target instanceof Element && target.closest("[data-thread-find-bar]")) {
128 details.cancel();
129 return;
130 }
131 useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open);
132 }}
133 >
134 {placement && inlineOpen ? (
135 <aside
136 aria-label="Thread details"
137 // Skip the return transition to avoid overlapping the rising preview.
138 className={cn(
139 "absolute z-20",
140 topInset > 0 && "transition-[top] duration-150 ease-out motion-reduce:transition-none",
141 )}
142 style={{
143 right: placement.right,
144 top: placement.y,
145 width: placement.width,
146 maxHeight: height,
147 }}
148 data-density={density}
149 data-thread-details-panel="inline"
150 >
151 {card}
152 </aside>
153 ) : null}
154 {/* Rendered in both modes: base-ui keeps a popup that unmounts mid-open
155 mounted, because its exit animation never finishes. Staying in the tree
156 lets it close cleanly when the card switches inline. */}
157 <PopoverPopup
158 anchor={anchor}
159 align="end"
160 // Account for the find panel's 8px card padding.
161 alignOffset={THREAD_DETAILS_CARD_GAP - 8}
162 collisionAvoidance={{ side: "shift", align: "shift", fallbackAxisSide: "none" }}
163 side="bottom"
164 sideOffset={topInset}
165 variant="panel"
166 padding="none"
167 >
168 {mode === "popover" ? (
169 <div data-density={density} data-thread-details-panel="popover">
170 {card}
171 </div>
172 ) : null}
173 </PopoverPopup>
174 </Popover>
175 );