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

ChatCanvas.tsx

212 lines8.4 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 [timelineElement, registerTimeline] = useState<HTMLElement | null>(null);
73 const measurements = useStore(store, (state) => selectCanvasMeasurements(state, rightPanelOpen));
74 const detailsCardMeasurement = useStore(store, (state) => state.detailsCardMeasurement);
75 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes canvas, find bar and timeline resizes and writes the measurements to the canvas store
76 useLayoutEffect(() => {
77 const element = elementRef.current;
78 const probe = widthProbeRef.current;
79 const htmlPreviewProbe = htmlPreviewWidthProbeRef.current;
80 if (!element || !probe || !htmlPreviewProbe) return;
81 const findBar =
82 detailsCardTopInset > 0 ? element.querySelector<HTMLElement>("[data-thread-find-bar]") : null;
83 let disposed = false;
84 // Seeking forces layout, so it runs once when a transition starts, not every frame.
85 let transitionWidths: ReturnType<typeof measureTransitionWidths> = null;
86 const measure = () => {
87 const width = element.clientWidth;
88 const transitions = panelWidthTransitions(element);
89 if (
90 transitions.length !== (transitionWidths?.transitions.length ?? 0) ||
91 transitions.some((animation, index) => animation !== transitionWidths?.transitions[index])
92 ) {
93 const settling = measureTransitionWidths(element, transitions);
94 if (settling && transitionWidths) {
95 settling.narrowestWidth = Math.min(
96 settling.narrowestWidth,
97 transitionWidths.narrowestWidth,
98 );
99 }
100 transitionWidths = settling;
101 // The last resize can arrive while the transitions still count as running.
102 if (settling) {
103 void Promise.allSettled(settling.transitions.map((animation) => animation.finished)).then(
104 () => {
105 if (disposed || transitionWidths !== settling) return;
106 measure();
107 },
108 );
109 }
110 }
111 const canvasBounds = element.getBoundingClientRect();
112 const findBarBounds = findBar?.getBoundingClientRect();
113 const styles = getComputedStyle(probe);
114 store.getState().setMeasurements(
115 {
116 findBar:
117 detailsCardTopInset > 0
118 ? {
119 left: findBarBounds ? findBarBounds.left - canvasBounds.left : 0,
120 right: findBarBounds ? findBarBounds.right - canvasBounds.left : 0,
121 bottom: findBarBounds ? findBarBounds.bottom - canvasBounds.top : 0,
122 }
123 : null,
124 width,
125 narrowestWidth: transitionWidths?.narrowestWidth ?? width,
126 height: element.clientHeight,
127 padding: Number.parseFloat(styles.paddingLeft),
128 maxChatWidth: Number.parseFloat(styles.width),
129 maxHtmlPreviewWidth: Number.parseFloat(getComputedStyle(htmlPreviewProbe).width),
130 minChatWidth: Number.parseFloat(styles.minWidth),
131 composerHeight: composerOverlayElement?.getBoundingClientRect().height ?? 0,
132 timelineGutter: timelineElement
133 ? (timelineElement.offsetWidth - timelineElement.clientWidth) / 2
134 : 0,
135 },
136 rightPanelOpen,
137 );
138 };
139 measure();
140 const observed: Element[] = [element, probe, htmlPreviewProbe];
141 if (findBar) observed.push(findBar);
142 if (composerOverlayElement) observed.push(composerOverlayElement);
143 if (timelineElement) observed.push(timelineElement);
144 const stopObserving = observeResize(observed, measure);
145 return () => {
146 disposed = true;
147 stopObserving();
148 };
149 }, [store, composerOverlayElement, timelineElement, detailsCardTopInset, rightPanelOpen]);
150 const detailsCardInlineOpen = useRightPanelStore((state) =>
151 threadRef === null
152 ? false
153 : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"),
154 );
155 const model = resolveChatCanvasModel({
156 measurements,
157 detailsCardMeasurement,
158 threadRef,
159 preview,
160 detailsCardInlineOpen,
161 });
162 const context = {
163 container: model.container,
164 lane: model.lane,
165 layout: model.layout,
166 previewKey: preview?.key ?? null,
167 registerTimeline,
168 measureDetailsCard: store.getState().measureDetailsCard,
169 detailsCardTopInset: model.detailsCardTopInset,
170 preferredDetailsCard: model.preferredDetailsCard,
171 detailsCardPlacement: model.detailsCardPlacement,
172 };
173 const { layout } = context;
174 const htmlPreviewLane =
175 layout.htmlPreview.width > layout.chat.width
176 ? {
177 "--html-preview-lane-offset": `${layout.htmlPreview.left - layout.chat.left}px`,
178 "--html-preview-lane-width": `${layout.htmlPreview.width}px`,
179 }
180 : null;
181 return (
182 <ChatCanvasContext value={context}>
183 <div
184 {...props}
185 ref={elementRef}
186 data-chat-canvas
187 data-preview-overlaps-chat={layout.overlapsChat || undefined}
188 className="relative flex min-h-0 min-w-0 flex-1 flex-col"
189 style={
190 {
191 "--chat-timeline-gutter": `${measurements.timelineGutter}px`,
192 "--chat-lane-inset-start": `${layout.chat.insetStart}px`,
193 "--chat-lane-inset-end": `${layout.chat.insetEnd}px`,
194 ...htmlPreviewLane,
195 } as CSSProperties
196 }
197 >
198 <div
199 ref={widthProbeRef}
200 aria-hidden
201 className="pointer-events-none invisible absolute h-0 w-(--chat-content-max-width) min-w-[40rem] box-content ps-3 sm:ps-12"
202 />
203 <div
204 ref={htmlPreviewWidthProbeRef}
205 aria-hidden
206 className="pointer-events-none invisible absolute h-0 w-(--html-preview-max-width)"
207 />
208 {children}
209 </div>
210 </ChatCanvasContext>
211 );