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

ChatCanvas.tsx

220 lines8.8 KB

1import { useLayoutEffect, useRef, useState, type ComponentProps, type CSSProperties } from "react";
2import { useStore } from "zustand";
3import { ChatCanvasContext } from "./ChatCanvasContext";
4import type { ChatCanvasPreview } from "./chatCanvasLayout";
5import {
6 resolveChatCanvasModel,
7 selectCanvasMeasurements,
8 type ChatCanvasStore,
9} from "./canvasStore";
10import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore";
11import { observeResize } from "../../lib/observeResize";
12import type { ScopedThreadRef } from "@t3tools/contracts";
13​
14function panelWidthTransitions(element: HTMLElement) {
15 const panels = element
16 .closest("[data-panel-animations]")
17 ?.querySelectorAll('[data-slot="sidebar-gap"], [data-preview-panel-mode="inline"]');
18 return Array.from(panels ?? []).flatMap((panel) =>
19 panel
20 .getAnimations()
21 .filter(
22 (animation): animation is CSSTransition =>
23 animation instanceof CSSTransition &&
24 animation.transitionProperty === "width" &&
25 animation.playState === "running",
26 ),
27 );
29​
30// Sample only the layout panels; seeking unrelated transitions can change their lifecycle.
31function measureTransitionWidths(element: HTMLElement, transitions: CSSTransition[]) {
32 if (transitions.length === 0) return null;
33 const times = transitions.map((animation) => animation.currentTime);
34 // Opposite panel transitions can reach their widest points at different times.
35 for (const animation of transitions) {
36 const end = Number(animation.effect?.getComputedTiming().endTime ?? 0);
37 animation.currentTime = 0;
38 const startWidth = element.clientWidth;
39 animation.currentTime = end;
40 if (startWidth < element.clientWidth) animation.currentTime = 0;
41 }
42 const narrowestWidth = element.clientWidth;
43 transitions.forEach((animation, index) => {
44 animation.currentTime = times[index] ?? null;
45 });
46 return { transitions, narrowestWidth };
48​
49export function ChatCanvas({
50 store,
51 threadRef,
52 preview,
53 composerOverlayElement,
54 detailsCardTopInset = 0,
55 rightPanelOpen,
56 children,
57 ...props
58}: Omit<ComponentProps<"div">, "className" | "style" | "ref"> & {
59 store: ChatCanvasStore;
60 /** Beside the canvas, so it decides which remembered width the first layout uses. */
61 rightPanelOpen: boolean;
62 /** The thread whose details card sits on the canvas; other threads' measurements are stale. */
63 threadRef: ScopedThreadRef | null;
64 /** The thread's mini player while it renders on this canvas. */
65 preview: ChatCanvasPreview | null;
66 composerOverlayElement: HTMLElement | null;
67 detailsCardTopInset?: number;
68}) {
69 const elementRef = useRef<HTMLDivElement | null>(null);
70 const widthProbeRef = useRef<HTMLDivElement | null>(null);
71 const htmlPreviewWidthProbeRef = useRef<HTMLDivElement | null>(null);
72 const detailsCardWidthProbeRef = useRef<HTMLDivElement | null>(null);
73 const [timelineElement, registerTimeline] = useState<HTMLElement | null>(null);
74 const measurements = useStore(store, (state) => selectCanvasMeasurements(state, rightPanelOpen));
75 const detailsCardMeasurement = useStore(store, (state) => state.detailsCardMeasurement);
76 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes canvas, find bar and timeline resizes and writes the measurements to the canvas store
77 useLayoutEffect(() => {
78 const element = elementRef.current;
79 const probe = widthProbeRef.current;
80 const htmlPreviewProbe = htmlPreviewWidthProbeRef.current;
81 const detailsCardProbe = detailsCardWidthProbeRef.current;
82 if (!element || !probe || !htmlPreviewProbe || !detailsCardProbe) return;
83 const findBar =
84 detailsCardTopInset > 0 ? element.querySelector<HTMLElement>("[data-thread-find-bar]") : null;
85 let disposed = false;
86 // Seeking forces layout, so it runs once when a transition starts, not every frame.
87 let transitionWidths: ReturnType<typeof measureTransitionWidths> = null;
88 const measure = () => {
89 const width = element.clientWidth;
90 const transitions = panelWidthTransitions(element);
91 if (
92 transitions.length !== (transitionWidths?.transitions.length ?? 0) ||
93 transitions.some((animation, index) => animation !== transitionWidths?.transitions[index])
94 ) {
95 const settling = measureTransitionWidths(element, transitions);
96 if (settling && transitionWidths) {
97 settling.narrowestWidth = Math.min(
98 settling.narrowestWidth,
99 transitionWidths.narrowestWidth,
100 );
101 }
102 transitionWidths = settling;
103 // The last resize can arrive while the transitions still count as running.
104 if (settling) {
105 void Promise.allSettled(settling.transitions.map((animation) => animation.finished)).then(
106 () => {
107 if (disposed || transitionWidths !== settling) return;
108 measure();
109 },
110 );
111 }
112 }
113 const canvasBounds = element.getBoundingClientRect();
114 const findBarBounds = findBar?.getBoundingClientRect();
115 const styles = getComputedStyle(probe);
116 store.getState().setMeasurements(
117 {
118 findBar:
119 detailsCardTopInset > 0
120 ? {
121 left: findBarBounds ? findBarBounds.left - canvasBounds.left : 0,
122 right: findBarBounds ? findBarBounds.right - canvasBounds.left : 0,
123 bottom: findBarBounds ? findBarBounds.bottom - canvasBounds.top : 0,
124 }
125 : null,
126 width,
127 narrowestWidth: transitionWidths?.narrowestWidth ?? width,
128 height: element.clientHeight,
129 padding: Number.parseFloat(styles.paddingLeft),
130 maxChatWidth: Number.parseFloat(styles.width),
131 maxHtmlPreviewWidth: Number.parseFloat(getComputedStyle(htmlPreviewProbe).width),
132 minChatWidth: Number.parseFloat(styles.minWidth),
133 detailsCardWidth: Number.parseFloat(getComputedStyle(detailsCardProbe).width),
134 composerHeight: composerOverlayElement?.getBoundingClientRect().height ?? 0,
135 timelineGutter: timelineElement
136 ? (timelineElement.offsetWidth - timelineElement.clientWidth) / 2
137 : 0,
138 },
139 rightPanelOpen,
140 );
141 };
142 measure();
143 const observed: Element[] = [element, probe, htmlPreviewProbe, detailsCardProbe];
144 if (findBar) observed.push(findBar);
145 if (composerOverlayElement) observed.push(composerOverlayElement);
146 if (timelineElement) observed.push(timelineElement);
147 const stopObserving = observeResize(observed, measure);
148 return () => {
149 disposed = true;
150 stopObserving();
151 };
152 }, [store, composerOverlayElement, timelineElement, detailsCardTopInset, rightPanelOpen]);
153 const detailsCardInlineOpen = useRightPanelStore((state) =>
154 threadRef === null
155 ? false
156 : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"),
157 );
158 const model = resolveChatCanvasModel({
159 measurements,
160 detailsCardMeasurement,
161 threadRef,
162 preview,
163 detailsCardInlineOpen,
164 });
165 const context = {
166 container: model.container,
167 lane: model.lane,
168 layout: model.layout,
169 previewKey: preview?.key ?? null,
170 registerTimeline,
171 measureDetailsCard: store.getState().measureDetailsCard,
172 detailsCardTopInset: model.detailsCardTopInset,
173 preferredDetailsCard: model.preferredDetailsCard,
174 detailsCardPlacement: model.detailsCardPlacement,
175 };
176 const { layout } = context;
177 const htmlPreviewLane =
178 layout.htmlPreview.width > layout.chat.width
179 ? {
180 "--html-preview-lane-offset": `${layout.htmlPreview.left - layout.chat.left}px`,
181 "--html-preview-lane-width": `${layout.htmlPreview.width}px`,
182 }
183 : null;
184 return (
185 <ChatCanvasContext value={context}>
186 <div
187 {...props}
188 ref={elementRef}
189 data-chat-canvas
190 data-preview-overlaps-chat={layout.overlapsChat || undefined}
191 className="relative flex min-h-0 min-w-0 flex-1 flex-col"
192 style={
193 {
194 "--chat-timeline-gutter": `${measurements.timelineGutter}px`,
195 "--chat-lane-inset-start": `${layout.chat.insetStart}px`,
196 "--chat-lane-inset-end": `${layout.chat.insetEnd}px`,
197 ...htmlPreviewLane,
198 } as CSSProperties
199 }
200 >
201 <div
202 ref={widthProbeRef}
203 aria-hidden
204 className="pointer-events-none invisible absolute h-0 w-(--chat-content-max-width) min-w-[40rem] box-content ps-3 sm:ps-12"
205 />
206 <div
207 ref={htmlPreviewWidthProbeRef}
208 aria-hidden
209 className="pointer-events-none invisible absolute h-0 w-(--html-preview-max-width)"
210 />
211 <div
212 ref={detailsCardWidthProbeRef}
213 aria-hidden
214 className="pointer-events-none invisible absolute h-0 w-(--thread-details-panel-width)"
215 />
216 {children}
217 </div>
218 </ChatCanvasContext>
219 );