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

useComposerRestingTransition.ts

526 lines22.1 KB

1import { observeResize } from "~/lib/observeResize";
2import { shouldAnimateComposerRestingTransition } from "../composerFooterLayout";
3import { useEffect, useLayoutEffect, useRef } from "react";
4​
5const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50;
6const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
7const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4;
8​
9export function useComposerRestingTransition(
10 isCollapsed: boolean,
11 isResting: boolean,
12 restingControlsRef: React.RefObject<HTMLDivElement | null>,
13 onOverlayHeightChange: (height: number) => void,
14 animationsActive: boolean,
15 animationDurationMs: number,
16) {
17 const elementRef = useRef<HTMLDivElement>(null);
18 const isCollapsedRef = useRef(isCollapsed);
19 const previousCollapsedRef = useRef(isCollapsed);
20 const previousRestingRef = useRef(isResting);
21 const previousHeightRef = useRef<number | null>(null);
22 const previousModelStripHeightRef = useRef<number | null>(null);
23 const previousContentOffsetsRef = useRef<{
24 promptFromTop: number | null;
25 promptHeight: number | null;
26 actionFromBottom: number | null;
27 controlsFromBottom: number | null;
28 controlsFromLeft: number | null;
29 surfaceBottomInset: number | null;
30 }>({
31 promptFromTop: null,
32 promptHeight: null,
33 actionFromBottom: null,
34 controlsFromBottom: null,
35 controlsFromLeft: null,
36 surfaceBottomInset: null,
37 });
38 const animationRef = useRef<Animation | null>(null);
39 const animationTargetHeightRef = useRef<number | null>(null);
40 const contentAnimationsRef = useRef<Animation[]>([]);
41 const stateChangeAnimationsRef = useRef<Animation[]>([]);
42 const pinnedOverlayRef = useRef<HTMLElement | null>(null);
43 const transitionCleanupTimeoutRef = useRef<number | null>(null);
44 const transitionLayoutRequestRef = useRef(0);
45 const hasCompletedInitialLayoutRef = useRef(false);
46​
47 const clearOverlayPin = () => {
48 // The overlay belongs to the chat view and outlives this composer, so it
49 // is remembered from pin time rather than re-resolved through a ref that
50 // React may already have detached during unmount.
51 const overlay = pinnedOverlayRef.current;
52 pinnedOverlayRef.current = null;
53 overlay?.style.removeProperty("height");
54 overlay?.style.removeProperty("display");
55 overlay?.style.removeProperty("flex-direction");
56 overlay?.style.removeProperty("justify-content");
57 };
58​
59 const clearTransitionStyles = () => {
60 const element = elementRef.current;
61 const footer = element?.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
62 element?.style.removeProperty("overflow");
63 element?.style.removeProperty("clip-path");
64 element?.style.removeProperty("overflow-clip-margin");
65 element
66 ?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]')
67 ?.style.removeProperty("height");
68 footer?.style.removeProperty("position");
69 footer?.style.removeProperty("top");
70 footer?.style.removeProperty("bottom");
71 footer?.style.removeProperty("left");
72 footer?.style.removeProperty("right");
73 footer?.style.removeProperty("height");
74 const shell = element?.closest<HTMLElement>('[data-slot="composer-shell"]');
75 shell?.removeAttribute("data-model-strip-transition");
76 const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
77 for (const property of [
78 "position",
79 "top",
80 "visibility",
81 "height",
82 "min-height",
83 "padding-top",
84 "align-items",
85 "z-index",
86 "pointer-events",
87 ]) {
88 modelStrip?.style.removeProperty(property);
89 }
90 clearOverlayPin();
91 };
92​
93 useLayoutEffect(() => {
94 isCollapsedRef.current = isCollapsed;
95 });
96​
97 const transitionToCurrentGeometry = (stateChanged: boolean) => {
98 const element = elementRef.current;
99 const surface = element?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]');
100 if (!element || !surface) return;
101​
102 const nextIsCollapsed = isCollapsedRef.current;
103​
104 const visibleTransitionElement = (selector: string) =>
105 Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
106 (candidate) => candidate.getClientRects().length > 0,
107 ) ?? null;
108 const prompt = visibleTransitionElement(
109 '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
110 );
111 const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]');
112 const footer = element.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
113 const continuousControls =
114 element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true";
115 const controls = nextIsCollapsed
116 ? restingControlsRef.current
117 : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
118​
119 const shell = element.closest<HTMLElement>('[data-slot="composer-shell"]');
120 const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
121 const interruptedStripHeight =
122 animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null;
123 const interruptedAnimation = animationRef.current;
124 const interruptedPromptTop = interruptedAnimation
125 ? (prompt?.getBoundingClientRect().top ?? null)
126 : null;
127 const interruptedActionTop = interruptedAnimation
128 ? (action?.getBoundingClientRect().top ?? null)
129 : null;
130 const interruptedControlsLeft = interruptedAnimation
131 ? (controls?.getBoundingClientRect().left ?? null)
132 : null;
133 const interruptedControlsTop = interruptedAnimation
134 ? (controls?.getBoundingClientRect().top ?? null)
135 : null;
136 const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null;
137 const interruptedTargetHeight = animationTargetHeightRef.current;
138 const interruptedCurrentTime =
139 typeof interruptedAnimation?.currentTime === "number"
140 ? interruptedAnimation.currentTime
141 : null;
142 const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration;
143 if (transitionCleanupTimeoutRef.current !== null) {
144 window.clearTimeout(transitionCleanupTimeoutRef.current);
145 transitionCleanupTimeoutRef.current = null;
146 }
147 interruptedAnimation?.cancel();
148 animationRef.current = null;
149 for (const animation of contentAnimationsRef.current) animation.cancel();
150 contentAnimationsRef.current = [];
151 if (stateChanged) {
152 for (const animation of stateChangeAnimationsRef.current) animation.cancel();
153 stateChangeAnimationsRef.current = [];
154 }
155 clearTransitionStyles();
156​
157 const nextRect = element.getBoundingClientRect();
158 const nextHeight = nextRect.height;
159 const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null;
160 // The chat view resize-observes the overlay to place the timeline
161 // inset, the scroll-to-end pill, and the mini player. Publishing the
162 // destination height here turns that feedback into one update instead
163 // of a ChatView re-render on every animation frame.
164 const overlay = element.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
165 const overlayRect = overlay?.getBoundingClientRect();
166 const overlayHeight = overlayRect?.height ?? null;
167 if (overlayHeight !== null) {
168 onOverlayHeightChange(overlayHeight);
169 }
170 const nextPromptRect = prompt?.getBoundingClientRect() ?? null;
171 const nextPromptTop = nextPromptRect?.top ?? null;
172 const nextActionTop = action?.getBoundingClientRect().top ?? null;
173 const nextControlsRect = controls?.getBoundingClientRect() ?? null;
174 const nextControlsTop = nextControlsRect?.top ?? null;
175 const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1;
176 const previousHeight = interruptedHeight ?? previousHeightRef.current;
177 const targetChanged =
178 interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5;
179 const shouldAnimate = shouldAnimateComposerRestingTransition({
180 hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current,
181 stateChanged,
182 hasInterruptedAnimation: interruptedHeight !== null,
183 });
184​
185 if (
186 shouldAnimate &&
187 animationsActive &&
188 previousHeight !== null &&
189 Math.abs(previousHeight - nextHeight) >= 0.5
190 ) {
191 const remainingDuration =
192 typeof interruptedDuration === "number" && interruptedCurrentTime !== null
193 ? Math.max(1, interruptedDuration - interruptedCurrentTime)
194 : animationDurationMs;
195 const duration =
196 interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs;
197 element.style.overflow = "clip";
198 if (modelStrip) {
199 const controlsClearance = Math.max(
200 nextModelStripHeight ?? 0,
201 previousModelStripHeightRef.current ?? 0,
202 );
203 element.style.overflowClipMargin = `${controlsClearance}px`;
204 element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`;
205 }
206 surface.style.height = "100%";
207​
208 if (overlay && overlayHeight !== null) {
209 overlay.style.height = `${String(overlayHeight)}px`;
210 overlay.style.display = "flex";
211 overlay.style.flexDirection = "column";
212 overlay.style.justifyContent = "flex-end";
213 pinnedOverlayRef.current = overlay;
214 }
215​
216 if (footer) {
217 footer.style.position = "absolute";
218 footer.style.top = "auto";
219 footer.style.bottom = `${String(footerBottom)}px`;
220 footer.style.height = "3rem";
221 if (nextIsCollapsed) {
222 footer.style.left = "auto";
223 footer.style.right = "1px";
224 } else {
225 footer.style.left = "1px";
226 footer.style.right = "1px";
227 }
228 }
229​
230 let stripAnimation: Animation | null = null;
231 if (modelStrip) {
232 const stripHeight = modelStrip.getBoundingClientRect().height;
233 const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop);
234 const fromHeight =
235 interruptedStripHeight ??
236 (previousCollapsedRef.current
237 ? (previousModelStripHeightRef.current ?? stripHeight)
238 : stripOverlap);
239 const toHeight = nextIsCollapsed ? stripHeight : stripOverlap;
240 modelStrip.style.position = "relative";
241 modelStrip.style.top = "auto";
242 modelStrip.style.visibility = "visible";
243 modelStrip.style.minHeight = "0";
244 modelStrip.style.paddingTop = "0";
245 modelStrip.style.alignItems = "flex-end";
246 modelStrip.style.pointerEvents = "none";
247 modelStrip.style.zIndex = "20";
248 shell?.setAttribute("data-model-strip-transition", "true");
249 stripAnimation = modelStrip.animate(
250 [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }],
251 { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" },
252 );
253 }
254​
255 const animation = element.animate(
256 [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
257 {
258 duration,
259 easing: COMPOSER_RESTING_TRANSITION_EASING,
260 fill: "both",
261 },
262 );
263 animationRef.current = animation;
264 animationTargetHeightRef.current = nextHeight;
265​
266 const animatedRect = element.getBoundingClientRect();
267 const previousBottom =
268 overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null
269 ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset
270 : animatedRect.bottom;
271 const bottomShift = previousBottom - animatedRect.bottom;
272 const previousPromptTop =
273 interruptedPromptTop ??
274 (previousContentOffsetsRef.current.promptFromTop === null
275 ? null
276 : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop);
277 const previousActionTop =
278 interruptedActionTop ??
279 (previousContentOffsetsRef.current.actionFromBottom === null
280 ? null
281 : previousBottom - previousContentOffsetsRef.current.actionFromBottom);
282 const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : [];
283 const animateContentPosition = (
284 content: HTMLElement | null,
285 previousTop: number | null,
286 previousLeft: number | null = null,
287 ) => {
288 if (!content || previousTop === null) return;
289 const rect = content.getBoundingClientRect();
290 const offset = previousTop - rect.top;
291 const offsetX = previousLeft === null ? 0 : previousLeft - rect.left;
292 if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return;
293 contentAnimations.push(
294 content.animate(
295 [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }],
296 {
297 duration,
298 easing: COMPOSER_RESTING_TRANSITION_EASING,
299 },
300 ),
301 );
302 };
303 animateContentPosition(prompt, previousPromptTop);
304 animateContentPosition(action, previousActionTop);
305 if (continuousControls) {
306 const previousControlsTop =
307 interruptedControlsTop ??
308 (previousContentOffsetsRef.current.controlsFromBottom === null
309 ? null
310 : previousBottom - previousContentOffsetsRef.current.controlsFromBottom);
311 const previousControlsLeft =
312 interruptedControlsLeft ??
313 (previousContentOffsetsRef.current.controlsFromLeft === null
314 ? null
315 : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft);
316 animateContentPosition(controls, previousControlsTop, previousControlsLeft);
317 }
318 contentAnimationsRef.current = contentAnimations;
319​
320 if (stateChanged) {
321 const stateChangeAnimations: Animation[] = [];
322​
323 const previousPromptHeight = previousContentOffsetsRef.current.promptHeight;
324 if (
325 !nextIsCollapsed &&
326 prompt &&
327 nextPromptRect &&
328 previousPromptHeight !== null &&
329 nextPromptRect.height - previousPromptHeight >= 0.5
330 ) {
331 const hiddenHeight = nextPromptRect.height - previousPromptHeight;
332 stateChangeAnimations.push(
333 prompt.animate(
334 [
335 { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` },
336 { clipPath: "inset(0 0 0 0)" },
337 ],
338 {
339 duration,
340 easing: COMPOSER_RESTING_TRANSITION_EASING,
341 },
342 ),
343 );
344 }
345​
346 const arrivingControls = nextIsCollapsed
347 ? restingControlsRef.current
348 : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
349 if (arrivingControls && !continuousControls) {
350 const drift = nextIsCollapsed
351 ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX
352 : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX;
353 stateChangeAnimations.push(
354 arrivingControls.animate(
355 [
356 { opacity: 0, transform: `translateY(${String(drift)}px)` },
357 { opacity: 1, transform: "none" },
358 ],
359 {
360 duration: nextIsCollapsed ? duration : duration / 2,
361 delay: nextIsCollapsed ? 0 : duration / 2,
362 fill: "backwards",
363 easing: COMPOSER_RESTING_TRANSITION_EASING,
364 },
365 ),
366 );
367 }
368​
369 const arrivingImagePreviews = nextIsCollapsed
370 ? Array.from(
371 element.querySelectorAll<HTMLElement>('[data-chat-composer-resting-images="true"]'),
372 )
373 : Array.from(
374 element.querySelectorAll<HTMLElement>('[data-chat-composer-expanded-image="true"]'),
375 );
376 for (const imagePreview of arrivingImagePreviews) {
377 stateChangeAnimations.push(
378 imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], {
379 duration: nextIsCollapsed ? duration : duration / 2,
380 delay: nextIsCollapsed ? 0 : duration / 2,
381 fill: "backwards",
382 easing: COMPOSER_RESTING_TRANSITION_EASING,
383 }),
384 );
385 }
386 stateChangeAnimationsRef.current = stateChangeAnimations;
387 }
388​
389 const finishTransition = (cancelAnimations: boolean) => {
390 if (animationRef.current !== animation) return;
391 if (transitionCleanupTimeoutRef.current !== null) {
392 window.clearTimeout(transitionCleanupTimeoutRef.current);
393 transitionCleanupTimeoutRef.current = null;
394 }
395 if (cancelAnimations) {
396 animation.cancel();
397 for (const contentAnimation of contentAnimationsRef.current) {
398 contentAnimation.cancel();
399 }
400 for (const stateChangeAnimation of stateChangeAnimationsRef.current) {
401 stateChangeAnimation.cancel();
402 }
403 }
404 animationRef.current = null;
405 animationTargetHeightRef.current = null;
406 contentAnimationsRef.current = [];
407 stateChangeAnimationsRef.current = [];
408 animation.cancel();
409 stripAnimation?.cancel();
410 clearTransitionStyles();
411 };
412 void animation.finished.catch(() => undefined).then(() => finishTransition(false));
413 // A suspended document timeline can leave `finished` pending while
414 // these measurement styles remain active. Wall-clock cleanup makes
415 // the natural layout the eventual source of truth in that case.
416 transitionCleanupTimeoutRef.current = window.setTimeout(
417 () => finishTransition(true),
418 duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS,
419 );
420 } else {
421 animationTargetHeightRef.current = null;
422 }
423​
424 previousCollapsedRef.current = nextIsCollapsed;
425 previousHeightRef.current = nextHeight;
426 previousModelStripHeightRef.current = nextModelStripHeight;
427 previousContentOffsetsRef.current = {
428 promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top,
429 promptHeight: nextPromptRect?.height ?? null,
430 actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop,
431 controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop,
432 controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left,
433 surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null,
434 };
435 };
436​
437 useLayoutEffect(() => {
438 const requestId = transitionLayoutRequestRef.current + 1;
439 transitionLayoutRequestRef.current = requestId;
440 const stateChanged = previousCollapsedRef.current !== isCollapsed;
441 // A non-Git context strip enters or leaves flow through ChatView state in
442 // an earlier layout effect. Let React flush that parent update before the
443 // FLIP reads its destination geometry, while still running before paint.
444 queueMicrotask(() => {
445 if (transitionLayoutRequestRef.current !== requestId) return;
446 transitionToCurrentGeometry(stateChanged);
447 });
448 return () => {
449 if (transitionLayoutRequestRef.current === requestId) {
450 transitionLayoutRequestRef.current += 1;
451 }
452 };
453 }, [isCollapsed, transitionToCurrentGeometry]);
454​
455 useLayoutEffect(() => {
456 if (previousRestingRef.current === isResting) return;
457 previousRestingRef.current = isResting;
458 if (animationRef.current) return;
459 const overlay = elementRef.current?.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
460 if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height);
461 }, [isResting, onOverlayHeightChange]);
462​
463 useLayoutEffect(() => {
464 const element = elementRef.current;
465 if (!element) return;
466​
467 const body = element.querySelector<HTMLElement>('[data-chat-composer-body="true"]');
468 return observeResize(body ? [element, body] : element, (entries) => {
469 if (animationRef.current) {
470 if (body && entries.some((entry) => entry.target === body)) {
471 transitionToCurrentGeometry(false);
472 }
473 return;
474 }
475 const elementRect = element.getBoundingClientRect();
476 const visibleTransitionElement = (selector: string) =>
477 Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
478 (candidate) => candidate.getClientRects().length > 0,
479 ) ?? null;
480 const promptRect = visibleTransitionElement(
481 '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
482 )?.getBoundingClientRect();
483 const actionTop = visibleTransitionElement(
484 '[data-chat-composer-transition-actions="true"]',
485 )?.getBoundingClientRect().top;
486 const controlsRect = (
487 isCollapsedRef.current
488 ? restingControlsRef.current
489 : visibleTransitionElement('[data-chat-composer-controls="left"]')
490 )?.getBoundingClientRect();
491 previousHeightRef.current = elementRect.height;
492 previousContentOffsetsRef.current = {
493 promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top,
494 promptHeight: promptRect?.height ?? null,
495 actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop,
496 controlsFromBottom:
497 controlsRect === undefined ? null : elementRect.bottom - controlsRect.top,
498 controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left,
499 surfaceBottomInset:
500 (element
501 .closest<HTMLElement>('[data-chat-composer-overlay="true"]')
502 ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom,
503 };
504 });
505 }, [restingControlsRef, transitionToCurrentGeometry]);
506​
507 useEffect(() => {
508 hasCompletedInitialLayoutRef.current = true;
509 return () => {
510 if (transitionCleanupTimeoutRef.current !== null) {
511 window.clearTimeout(transitionCleanupTimeoutRef.current);
512 transitionCleanupTimeoutRef.current = null;
513 }
514 animationRef.current?.cancel();
515 animationRef.current = null;
516 animationTargetHeightRef.current = null;
517 for (const animation of contentAnimationsRef.current) animation.cancel();
518 contentAnimationsRef.current = [];
519 for (const animation of stateChangeAnimationsRef.current) animation.cancel();
520 stateChangeAnimationsRef.current = [];
521 clearTransitionStyles();
522 };
523 }, [clearTransitionStyles]);
524​
525 return elementRef;