The best way to control Claude Code, Codex and more from any computer or phone

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