fix: scroll behavior, browser back navigation, and weather widget sizing (#1336)

This commit is contained in:
josh 2025-11-30 03:48:27 +00:00 committed by GitHub
parent e90a6ee209
commit b3a155d2a4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 157 additions and 121 deletions

View file

@ -2,7 +2,7 @@
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { useSearchParams } from "next/navigation";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { unstable_serialize } from "swr/infinite";
@ -50,12 +50,25 @@ export function Chat({
autoResume: boolean;
initialLastContext?: AppUsage;
}) {
const router = useRouter();
const { visibilityType } = useChatVisibility({
chatId: id,
initialVisibilityType,
});
const { mutate } = useSWRConfig();
// Handle browser back/forward navigation
useEffect(() => {
const handlePopState = () => {
// When user navigates back/forward, refresh to sync with URL
router.refresh();
};
window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
}, [router]);
const { setDataStream } = useDataStream();
const [input, setInput] = useState<string>("");

View file

@ -44,51 +44,57 @@ function PureMessages({
useDataStream();
return (
<div
className="relative flex-1 touch-pan-y overflow-y-auto"
ref={messagesContainerRef}
>
<div className="mx-auto flex min-w-0 max-w-4xl flex-col gap-4 px-2 py-4 md:gap-6 md:px-4">
{messages.length === 0 && <Greeting />}
<div className="relative flex-1">
<div
className="absolute inset-0 touch-pan-y overflow-y-auto"
ref={messagesContainerRef}
>
<div className="mx-auto flex min-w-0 max-w-4xl flex-col gap-4 px-2 py-4 md:gap-6 md:px-4">
{messages.length === 0 && <Greeting />}
{messages.map((message, index) => (
<PreviewMessage
chatId={chatId}
isLoading={status === "streaming" && messages.length - 1 === index}
isReadonly={isReadonly}
key={message.id}
message={message}
regenerate={regenerate}
requiresScrollPadding={
hasSentMessage && index === messages.length - 1
}
setMessages={setMessages}
vote={
votes
? votes.find((vote) => vote.messageId === message.id)
: undefined
}
{messages.map((message, index) => (
<PreviewMessage
chatId={chatId}
isLoading={
status === "streaming" && messages.length - 1 === index
}
isReadonly={isReadonly}
key={message.id}
message={message}
regenerate={regenerate}
requiresScrollPadding={
hasSentMessage && index === messages.length - 1
}
setMessages={setMessages}
vote={
votes
? votes.find((vote) => vote.messageId === message.id)
: undefined
}
/>
))}
{status === "submitted" && <ThinkingMessage />}
<div
className="min-h-[24px] min-w-[24px] shrink-0"
ref={messagesEndRef}
/>
))}
{status === "submitted" && <ThinkingMessage />}
<div
className="min-h-[24px] min-w-[24px] shrink-0"
ref={messagesEndRef}
/>
</div>
</div>
{!isAtBottom && (
<button
aria-label="Scroll to bottom"
className="-translate-x-1/2 absolute bottom-40 left-1/2 z-10 rounded-full border bg-background p-2 shadow-lg transition-colors hover:bg-muted"
onClick={() => scrollToBottom("smooth")}
type="button"
>
<ArrowDownIcon className="size-4" />
</button>
)}
<button
aria-label="Scroll to bottom"
className={`-translate-x-1/2 absolute bottom-4 left-1/2 z-10 rounded-full border bg-background p-2 shadow-lg transition-all hover:bg-muted ${
isAtBottom
? "pointer-events-none scale-0 opacity-0"
: "pointer-events-auto scale-100 opacity-100"
}`}
onClick={() => scrollToBottom("smooth")}
type="button"
>
<ArrowDownIcon className="size-4" />
</button>
</div>
);
}

View file

@ -37,7 +37,7 @@ function PureSuggestedActions({ chatId, sendMessage }: SuggestedActionsProps) {
<Suggestion
className="h-auto w-full whitespace-normal p-3 text-left"
onClick={(suggestion) => {
window.history.replaceState({}, "", `/chat/${chatId}`);
window.history.pushState({}, "", `/chat/${chatId}`);
sendMessage({
role: "user",
parts: [{ type: "text", text: suggestion }],

View file

@ -330,7 +330,7 @@ export function Weather({
return (
<div
className={cx(
"relative flex w-full flex-col gap-6 overflow-hidden rounded-3xl p-6 shadow-lg backdrop-blur-sm",
"relative flex w-full flex-col gap-3 overflow-hidden rounded-2xl p-4 shadow-lg backdrop-blur-sm",
{
"bg-gradient-to-br from-sky-400 via-blue-500 to-blue-600": isDay,
},
@ -343,44 +343,44 @@ export function Weather({
<div className="absolute inset-0 bg-white/10 backdrop-blur-sm" />
<div className="relative z-10">
<div className="mb-4 flex items-center justify-between">
<div className="font-medium text-sm text-white/80">{location}</div>
<div className="mb-2 flex items-center justify-between">
<div className="font-medium text-white/80 text-xs">{location}</div>
<div className="text-white/60 text-xs">
{format(new Date(weatherAtLocation.current.time), "MMM d, h:mm a")}
</div>
</div>
<div className="mb-6 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={cx("text-white/90", {
"text-yellow-200": isDay,
"text-blue-200": !isDay,
})}
>
{isDay ? <SunIcon size={48} /> : <MoonIcon size={48} />}
{isDay ? <SunIcon size={32} /> : <MoonIcon size={32} />}
</div>
<div className="font-light text-5xl text-white">
<div className="font-light text-3xl text-white">
{n(weatherAtLocation.current.temperature_2m)}
<span className="text-2xl text-white/80">
<span className="text-lg text-white/80">
{weatherAtLocation.current_units.temperature_2m}
</span>
</div>
</div>
<div className="text-right">
<div className="font-medium text-sm text-white/90">
<div className="font-medium text-white/90 text-xs">
H: {n(currentHigh)}°
</div>
<div className="text-sm text-white/70">L: {n(currentLow)}°</div>
<div className="text-white/70 text-xs">L: {n(currentLow)}°</div>
</div>
</div>
<div className="rounded-2xl bg-white/10 p-4 backdrop-blur-sm">
<div className="mb-3 font-medium text-sm text-white/80">
<div className="rounded-xl bg-white/10 p-3 backdrop-blur-sm">
<div className="mb-2 font-medium text-white/80 text-xs">
Hourly Forecast
</div>
<div className="flex justify-between gap-2">
<div className="flex justify-between gap-1">
{displayTimes.map((time, index) => {
const hourTime = new Date(time);
const isCurrentHour =
@ -389,7 +389,7 @@ export function Weather({
return (
<div
className={cx(
"flex min-w-0 flex-1 flex-col items-center gap-2 rounded-lg px-1 py-2",
"flex min-w-0 flex-1 flex-col items-center gap-1 rounded-md px-1 py-1.5",
{
"bg-white/20": isCurrentHour,
}
@ -406,10 +406,10 @@ export function Weather({
"text-blue-200": !isDay,
})}
>
<CloudIcon size={20} />
<CloudIcon size={16} />
</div>
<div className="font-medium text-sm text-white">
<div className="font-medium text-white text-xs">
{n(displayTemperatures[index])}°
</div>
</div>
@ -418,7 +418,7 @@ export function Weather({
</div>
</div>
<div className="mt-4 flex justify-between text-white/60 text-xs">
<div className="mt-2 flex justify-between text-white/60 text-xs">
<div>
Sunrise:{" "}
{format(new Date(weatherAtLocation.daily.sunrise[0]), "h:mm a")}

View file

@ -1,102 +1,119 @@
import { useCallback, useEffect, useRef, useState } from "react";
import useSWR from "swr";
type ScrollFlag = ScrollBehavior | false;
export function useScrollToBottom() {
const containerRef = useRef<HTMLDivElement>(null);
const endRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const isAtBottomRef = useRef(true);
const isUserScrollingRef = useRef(false);
const { data: scrollBehavior = false, mutate: setScrollBehavior } =
useSWR<ScrollFlag>("messages:should-scroll", null, { fallbackData: false });
// Keep ref in sync with state
useEffect(() => {
isAtBottomRef.current = isAtBottom;
}, [isAtBottom]);
const handleScroll = useCallback(() => {
const checkIfAtBottom = useCallback(() => {
if (!containerRef.current) {
return;
return true;
}
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
// Check if we are within 100px of the bottom (like v0 does)
setIsAtBottom(scrollTop + clientHeight >= scrollHeight - 100);
return scrollTop + clientHeight >= scrollHeight - 100;
}, []);
useEffect(() => {
const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {
if (!containerRef.current) {
return;
}
const container = containerRef.current;
const resizeObserver = new ResizeObserver(() => {
requestAnimationFrame(() => {
handleScroll();
});
containerRef.current.scrollTo({
top: containerRef.current.scrollHeight,
behavior,
});
}, []);
const mutationObserver = new MutationObserver(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
handleScroll();
});
});
});
resizeObserver.observe(container);
mutationObserver.observe(container, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["style", "class", "data-state"],
});
handleScroll();
return () => {
resizeObserver.disconnect();
mutationObserver.disconnect();
};
}, [handleScroll]);
// Handle user scroll events
useEffect(() => {
const container = containerRef.current;
if (!container) {
return;
}
container.addEventListener("scroll", handleScroll);
handleScroll(); // Check initial state
let scrollTimeout: ReturnType<typeof setTimeout>;
const handleScroll = () => {
// Mark as user scrolling
isUserScrollingRef.current = true;
clearTimeout(scrollTimeout);
// Update isAtBottom state
const atBottom = checkIfAtBottom();
setIsAtBottom(atBottom);
isAtBottomRef.current = atBottom;
// Reset user scrolling flag after scroll ends
scrollTimeout = setTimeout(() => {
isUserScrollingRef.current = false;
}, 150);
};
container.addEventListener("scroll", handleScroll, { passive: true });
return () => {
container.removeEventListener("scroll", handleScroll);
clearTimeout(scrollTimeout);
};
}, [handleScroll]);
}, [checkIfAtBottom]);
// Auto-scroll when content changes
useEffect(() => {
if (scrollBehavior && containerRef.current) {
const container = containerRef.current;
const scrollOptions: ScrollToOptions = {
top: container.scrollHeight,
behavior: scrollBehavior,
};
container.scrollTo(scrollOptions);
setScrollBehavior(false);
const container = containerRef.current;
if (!container) {
return;
}
}, [scrollBehavior, setScrollBehavior]);
const scrollToBottom = useCallback(
(currentScrollBehavior: ScrollBehavior = "smooth") => {
setScrollBehavior(currentScrollBehavior);
},
[setScrollBehavior]
);
const scrollIfNeeded = () => {
// Only auto-scroll if user was at bottom and isn't actively scrolling
if (isAtBottomRef.current && !isUserScrollingRef.current) {
requestAnimationFrame(() => {
container.scrollTo({
top: container.scrollHeight,
behavior: "instant",
});
setIsAtBottom(true);
isAtBottomRef.current = true;
});
}
};
// Watch for DOM changes
const mutationObserver = new MutationObserver(scrollIfNeeded);
mutationObserver.observe(container, {
childList: true,
subtree: true,
characterData: true,
});
// Watch for size changes
const resizeObserver = new ResizeObserver(scrollIfNeeded);
resizeObserver.observe(container);
// Also observe children for size changes
for (const child of container.children) {
resizeObserver.observe(child);
}
return () => {
mutationObserver.disconnect();
resizeObserver.disconnect();
};
}, []);
function onViewportEnter() {
setIsAtBottom(true);
isAtBottomRef.current = true;
}
function onViewportLeave() {
setIsAtBottom(false);
isAtBottomRef.current = false;
}
return {

View file

@ -11,7 +11,7 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{