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

ThreadDetailsCard.tsx

187 lines7.7 KB

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