Compare commits

...
Author SHA1 Message Date
Julius Marminge 61a8ca2c31 refactor: remove redundant workLogCount stick-to-bottom effect
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.

Made-with: Cursor
2026-03-02 10:10:15 -08:00
Julius Marminge 8294392062 fix: align handoff preview URLs with image attachment index
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.

Made-with: Cursor
2026-03-02 09:53:08 -08:00
Julius Marminge b58b8fd0fd Stabilize chat scroll restoration across thread switches
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
2026-03-02 00:46:01 -08:00
+257 -31
View File
@@ -24,7 +24,11 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStat
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer"; import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router"; import { useNavigate, useSearch } from "@tanstack/react-router";
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual"; import {
measureElement as measureVirtualElement,
type VirtualItem,
useVirtualizer,
} from "@tanstack/react-virtual";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery"; import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery"; import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
@@ -47,7 +51,7 @@ import {
formatElapsed, formatElapsed,
formatTimestamp, formatTimestamp,
} from "../session-logic"; } from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll"; import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store"; import { useStore } from "../store";
import { truncateTitle } from "../truncateTitle"; import { truncateTitle } from "../truncateTitle";
import { import {
@@ -130,6 +134,8 @@ function formatMessageMeta(createdAt: string, duration: string | null): string {
const LAST_EDITOR_KEY = "t3code:last-editor"; const LAST_EDITOR_KEY = "t3code:last-editor";
const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
const IMAGE_ONLY_BOOTSTRAP_PROMPT = const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -251,6 +257,19 @@ function revokeUserMessagePreviewUrls(message: ChatMessage): void {
} }
} }
function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
if (message.role !== "user" || !message.attachments) {
return [];
}
const previewUrls: string[] = [];
for (const attachment of message.attachments) {
if (attachment.type !== "image") continue;
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
previewUrls.push(attachment.previewUrl);
}
return previewUrls;
}
type ComposerCommandItem = type ComposerCommandItem =
| { | {
id: string; id: string;
@@ -485,14 +504,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [nowTick, setNowTick] = useState(() => Date.now()); const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0); const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null); const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState< const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
Record<string, string> Record<string, string>
>(() => readLastInvokedScriptByProjectFromStorage()); >(() => readLastInvokedScriptByProjectFromStorage());
const messagesScrollRef = useRef<HTMLDivElement>(null); const messagesScrollRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true); const shouldAutoScrollRef = useRef(true);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerCommandInputRef = useRef<HTMLInputElement>(null); const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]); const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef<Record<string, number>>({});
const sendInFlightRef = useRef(false); const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0); const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({}); const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -614,18 +641,105 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => derivePendingApprovals(threadActivities), () => derivePendingApprovals(threadActivities),
[threadActivities], [threadActivities],
); );
useEffect(() => {
attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
}, [attachmentPreviewHandoffByMessageId]);
const clearAttachmentPreviewHandoffs = useCallback(() => {
for (const timeoutId of Object.values(attachmentPreviewHandoffTimeoutByMessageIdRef.current)) {
window.clearTimeout(timeoutId);
}
attachmentPreviewHandoffTimeoutByMessageIdRef.current = {};
for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
for (const previewUrl of previewUrls) {
revokeBlobPreviewUrl(previewUrl);
}
}
attachmentPreviewHandoffByMessageIdRef.current = {};
setAttachmentPreviewHandoffByMessageId({});
}, []);
const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
if (previewUrls.length === 0) return;
const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
for (const previewUrl of previousPreviewUrls) {
if (!previewUrls.includes(previewUrl)) {
revokeBlobPreviewUrl(previewUrl);
}
}
setAttachmentPreviewHandoffByMessageId((existing) => {
const next = {
...existing,
[messageId]: previewUrls,
};
attachmentPreviewHandoffByMessageIdRef.current = next;
return next;
});
const existingTimeout = attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
if (typeof existingTimeout === "number") {
window.clearTimeout(existingTimeout);
}
attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId] = window.setTimeout(() => {
const currentPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId];
if (currentPreviewUrls) {
for (const previewUrl of currentPreviewUrls) {
revokeBlobPreviewUrl(previewUrl);
}
}
setAttachmentPreviewHandoffByMessageId((existing) => {
if (!(messageId in existing)) return existing;
const { [messageId]: _removed, ...rest } = existing;
attachmentPreviewHandoffByMessageIdRef.current = rest;
return rest;
});
delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
}, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
}, []);
const timelineMessages = useMemo(() => { const timelineMessages = useMemo(() => {
const serverMessages = activeThread?.messages ?? []; const serverMessages = activeThread?.messages ?? [];
const serverMessagesWithPreviewHandoff =
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
? serverMessages
: serverMessages.map((message) => {
if (message.role !== "user" || !message.attachments || message.attachments.length === 0) {
return message;
}
const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id];
if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) {
return message;
}
let changed = false;
let imageIndex = 0;
const attachments = message.attachments.map((attachment) => {
if (attachment.type !== "image") {
return attachment;
}
const handoffPreviewUrl = handoffPreviewUrls[imageIndex];
imageIndex += 1;
if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) {
return attachment;
}
changed = true;
return {
...attachment,
previewUrl: handoffPreviewUrl,
};
});
return changed ? { ...message, attachments } : message;
});
if (optimisticUserMessages.length === 0) { if (optimisticUserMessages.length === 0) {
return serverMessages; return serverMessagesWithPreviewHandoff;
} }
const serverIds = new Set(serverMessages.map((message) => message.id)); const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id));
const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id)); const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id));
if (pendingMessages.length === 0) { if (pendingMessages.length === 0) {
return serverMessages; return serverMessagesWithPreviewHandoff;
} }
return [...serverMessages, ...pendingMessages]; return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
}, [activeThread?.messages, optimisticUserMessages]); }, [activeThread?.messages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
const timelineEntries = useMemo( const timelineEntries = useMemo(
() => deriveTimelineEntries(timelineMessages, workLogEntries), () => deriveTimelineEntries(timelineMessages, workLogEntries),
[timelineMessages, workLogEntries], [timelineMessages, workLogEntries],
@@ -1170,31 +1284,80 @@ export default function ChatView({ threadId }: ChatViewProps) {
// Auto-scroll on new messages // Auto-scroll on new messages
const messageCount = timelineMessages.length; const messageCount = timelineMessages.length;
const workLogCount = workLogEntries.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => { const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current; const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return; if (!scrollContainer) return;
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior }); scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
shouldAutoScrollRef.current = true; shouldAutoScrollRef.current = true;
}, []); }, []);
const scheduleStickToBottom = useCallback(() => {
if (pendingAutoScrollFrameRef.current !== null) return;
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
pendingAutoScrollFrameRef.current = null;
scrollMessagesToBottom();
});
}, [scrollMessagesToBottom]);
const onMessagesScroll = useCallback(() => { const onMessagesScroll = useCallback(() => {
const scrollContainer = messagesScrollRef.current; const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return; if (!scrollContainer) return;
shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer); shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer);
}, []); }, []);
useEffect(() => {
return () => {
const frame = pendingAutoScrollFrameRef.current;
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
};
}, []);
useLayoutEffect(() => { useLayoutEffect(() => {
if (!activeThread?.id) return; if (!activeThread?.id) return;
scrollMessagesToBottom(); shouldAutoScrollRef.current = true;
}, [activeThread?.id, scrollMessagesToBottom]); scheduleStickToBottom();
const timeout = window.setTimeout(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
if (isScrollContainerNearBottom(scrollContainer)) return;
scheduleStickToBottom();
}, 96);
return () => {
window.clearTimeout(timeout);
};
}, [activeThread?.id, scheduleStickToBottom]);
useLayoutEffect(() => {
const composerForm = composerFormRef.current;
if (!composerForm) return;
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver((entries) => {
const [entry] = entries;
if (!entry) return;
const nextHeight = entry.contentRect.height;
const previousHeight = composerFormHeightRef.current;
composerFormHeightRef.current = nextHeight;
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
});
observer.observe(composerForm);
return () => {
observer.disconnect();
};
}, [activeThread?.id, scheduleStickToBottom]);
useEffect(() => { useEffect(() => {
if (!shouldAutoScrollRef.current) return; if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth"); scheduleStickToBottom();
}, [messageCount, scrollMessagesToBottom]); }, [messageCount, scheduleStickToBottom]);
useEffect(() => { useEffect(() => {
if (phase !== "running") return; if (phase !== "running") return;
if (!shouldAutoScrollRef.current) return; if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth"); scheduleStickToBottom();
}, [phase, workLogCount, scrollMessagesToBottom]); }, [phase, scheduleStickToBottom, timelineEntries]);
useEffect(() => { useEffect(() => {
setExpandedWorkGroups({}); setExpandedWorkGroups({});
@@ -1230,6 +1393,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => { useEffect(() => {
if (!activeThread?.id) { if (!activeThread?.id) {
clearAttachmentPreviewHandoffs();
setOptimisticUserMessages((existing) => { setOptimisticUserMessages((existing) => {
for (const message of existing) { for (const message of existing) {
revokeUserMessagePreviewUrls(message); revokeUserMessagePreviewUrls(message);
@@ -1242,21 +1406,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
return; return;
} }
const serverIds = new Set(activeThread.messages.map((message) => message.id)); const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => { const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id));
const removed = existing.filter((message) => serverIds.has(message.id)); if (removedMessages.length === 0) {
for (const message of removed) { return;
revokeUserMessagePreviewUrls(message); }
setOptimisticUserMessages((existing) => existing.filter((message) => !serverIds.has(message.id)));
for (const removedMessage of removedMessages) {
const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
if (previewUrls.length > 0) {
handoffAttachmentPreviews(removedMessage.id, previewUrls);
continue;
} }
const next = existing.filter((message) => !serverIds.has(message.id)); revokeUserMessagePreviewUrls(removedMessage);
return next.length === existing.length ? existing : next; }
}); }, [
}, [activeThread?.id, activeThread?.messages]); activeThread?.id,
activeThread?.messages,
clearAttachmentPreviewHandoffs,
handoffAttachmentPreviews,
optimisticUserMessages,
]);
useEffect(() => { useEffect(() => {
promptRef.current = prompt; promptRef.current = prompt;
}, [prompt]); }, [prompt]);
useEffect(() => { useEffect(() => {
clearAttachmentPreviewHandoffs();
setOptimisticUserMessages((existing) => { setOptimisticUserMessages((existing) => {
for (const message of existing) { for (const message of existing) {
revokeUserMessagePreviewUrls(message); revokeUserMessagePreviewUrls(message);
@@ -1268,7 +1444,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
dragDepthRef.current = 0; dragDepthRef.current = 0;
setIsDragOverComposer(false); setIsDragOverComposer(false);
setExpandedImage(null); setExpandedImage(null);
}, [threadId]); }, [clearAttachmentPreviewHandoffs, threadId]);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
@@ -1760,6 +1936,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
streaming: false, streaming: false,
}, },
]); ]);
// Sending a message should always bring the latest user turn into view.
shouldAutoScrollRef.current = true;
scheduleStickToBottom();
setThreadError(threadIdForSend, null); setThreadError(threadIdForSend, null);
promptRef.current = ""; promptRef.current = "";
@@ -2185,6 +2364,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onScroll={onMessagesScroll} onScroll={onMessagesScroll}
> >
<MessagesTimeline <MessagesTimeline
key={activeThread.id}
hasMessages={timelineMessages.length > 0} hasMessages={timelineMessages.length > 0}
isWorking={isWorking} isWorking={isWorking}
activeTurnInProgress={!latestTurnSettled} activeTurnInProgress={!latestTurnSettled}
@@ -2209,6 +2389,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Input bar */} {/* Input bar */}
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}> <div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
<form <form
ref={composerFormRef}
onSubmit={onSend} onSubmit={onSend}
className="mx-auto w-full min-w-fit max-w-3xl" className="mx-auto w-full min-w-fit max-w-3xl"
data-chat-composer-form="true" data-chat-composer-form="true"
@@ -2804,6 +2985,20 @@ type TimelineRow =
} }
| { kind: "working"; id: string; createdAt: string | null }; | { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineMessageHeight(message: TimelineMessage): number {
const textLength = message.text.length;
if (message.role === "assistant") {
const estimatedLines = Math.max(1, Math.ceil(textLength / 72));
return 78 + Math.min(estimatedLines * 22, 820);
}
const estimatedLines = Math.max(1, Math.ceil(textLength / 56));
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / 2);
const attachmentHeight = attachmentRows * 124;
return 96 + Math.min(estimatedLines * 22, 620) + attachmentHeight;
}
const MessagesTimeline = memo(function MessagesTimeline({ const MessagesTimeline = memo(function MessagesTimeline({
hasMessages, hasMessages,
isWorking, isWorking,
@@ -2875,7 +3070,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]); }, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
const firstUnvirtualizedRowIndex = useMemo(() => { const firstUnvirtualizedRowIndex = useMemo(() => {
if (!activeTurnInProgress) return rows.length; const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
if (!activeTurnInProgress) return firstTailRowIndex;
const turnStartedAtMs = const turnStartedAtMs =
typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN; typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
@@ -2895,22 +3091,20 @@ const MessagesTimeline = memo(function MessagesTimeline({
); );
} }
if (firstCurrentTurnRowIndex < 0) { if (firstCurrentTurnRowIndex < 0) return firstTailRowIndex;
return rows.length;
}
for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) { for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
const previousRow = rows[index]; const previousRow = rows[index];
if (!previousRow || previousRow.kind !== "message") continue; if (!previousRow || previousRow.kind !== "message") continue;
if (previousRow.message.role === "user") { if (previousRow.message.role === "user") {
return index; return Math.min(index, firstTailRowIndex);
} }
if (previousRow.message.role === "assistant" && !previousRow.message.streaming) { if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
break; break;
} }
} }
return firstCurrentTurnRowIndex; return Math.min(firstCurrentTurnRowIndex, firstTailRowIndex);
}, [activeTurnInProgress, activeTurnStartedAt, rows]); }, [activeTurnInProgress, activeTurnStartedAt, rows]);
const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, { const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
@@ -2921,16 +3115,46 @@ const MessagesTimeline = memo(function MessagesTimeline({
const rowVirtualizer = useVirtualizer({ const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount, count: virtualizedRowCount,
getScrollElement: () => scrollContainerRef.current, getScrollElement: () => scrollContainerRef.current,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
estimateSize: (index: number) => { estimateSize: (index: number) => {
const row = rows[index]; const row = rows[index];
if (!row) return 96; if (!row) return 96;
if (row.kind === "work") return 112; if (row.kind === "work") return 112;
if (row.kind === "working") return 40; if (row.kind === "working") return 40;
return row.message.role === "assistant" ? 220 : 170; return estimateTimelineMessageHeight(row.message);
}, },
measureElement: (element: HTMLElement) => element.getBoundingClientRect().height, measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
overscan: 8, overscan: 8,
}); });
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
return () => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
};
}, [rowVirtualizer]);
const pendingMeasureFrameRef = useRef<number | null>(null);
const onTimelineImageLoad = useCallback(() => {
if (pendingMeasureFrameRef.current !== null) return;
pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
pendingMeasureFrameRef.current = null;
rowVirtualizer.measure();
});
}, [rowVirtualizer]);
useEffect(() => {
return () => {
const frame = pendingMeasureFrameRef.current;
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
};
}, []);
const virtualRows = rowVirtualizer.getVirtualItems(); const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount); const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -3022,6 +3246,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
src={image.previewUrl} src={image.previewUrl}
alt={image.name} alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover" className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
onClick={() => { onClick={() => {
const preview = buildExpandedImagePreview(userImages, image.id); const preview = buildExpandedImagePreview(userImages, image.id);
if (!preview) return; if (!preview) return;