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

ChatCanvas.tsx

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