Skip to content

feat: make search component chat scroll better #3851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 4 additions & 107 deletions clients/search-component/src/TrieveModal/Chat/ChatMode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,111 +11,27 @@ import { InlineChatHeader } from "./InlineChatHeader";
import { ChatInput } from "./ChatInput";

export const ChatMode = () => {
const { props, modalRef, minHeight, resetHeight, addHeight } =
useModalState();
const { props, modalRef } = useModalState();
const { messages } = useChatState();

const actualChatRef = useRef<HTMLDivElement>(null);
const rulerRef = useRef<HTMLDivElement>(null);

const [ref, { entry }] = useIntersectionObserver();
const isOnScreen = entry && entry.isIntersecting;

const onMessageSend = () => {
setTimeout(() => {
if (!actualChatRef.current || !modalRef.current) {
return;
}

const userMessages = actualChatRef.current.querySelectorAll(
".user-message-container",
);
if (userMessages.length === 0) {
return;
}

const lastUserMessage = userMessages[userMessages.length - 1];

const messageRect = lastUserMessage.getBoundingClientRect();
const containerRect = modalRef.current.getBoundingClientRect();

const bufferSpace = 20;

const scrollTo =
messageRect.top -
containerRect.top +
modalRef.current.scrollTop -
bufferSpace;

handleHeightAddition();

setTimeout(() => {
if (!modalRef.current) {
return;
}
modalRef.current.scrollTo({
top: scrollTo,
behavior: "smooth",
});
}, 30); // 30 used for consistency with react-dom updates
}, 100);
};

const calculateHeightToAdd = () => {
if (!modalRef.current || !actualChatRef.current) {
return 0;
}
if (!rulerRef.current) {
return 0;
}

const userMessages = actualChatRef.current.querySelectorAll(
".user-message-container",
);
if (userMessages.length === 0) {
return 0;
}

const lastUserMessage = userMessages[userMessages.length - 1];

const messageRect = lastUserMessage.getBoundingClientRect();

const scrollContainerVisibleHeight = modalRef.current.clientHeight;
const messageRectYDistance =
messageRect.top +
modalRef.current.scrollTop +
lastUserMessage.scrollHeight;

const redLead = rulerRef.current.scrollHeight - messageRectYDistance;

const targetGap =
scrollContainerVisibleHeight - lastUserMessage.scrollHeight;

const heightToAdd = targetGap - redLead;
return heightToAdd - 80;
};

const handleHeightAddition = () => {
const height = calculateHeightToAdd();
addHeight(height);
};

return (
<Suspense>
{props.previewTopicId == undefined && (
<InlineChatHeader resetHeight={resetHeight} />
)}
{props.previewTopicId == undefined && <InlineChatHeader />}
<div
ref={modalRef}
className="chat-modal-wrapper tv-justify-items-stretch tv-flex-grow tv-pt-3 tv-pb-2 tv-px-2 tv-relative tv-overflow-y-auto tv-flex tv-overflow-x-hidden"
>
<ChatRuler rulerRef={rulerRef} minHeight={minHeight} />
<div
className="tv-flex-col tv-h-full tv-grow tv-flex tv-gap-4 tv-max-w-full"
ref={actualChatRef}
>
{/* Only shows with zero messages */}
<SuggestedQuestions onMessageSend={onMessageSend} />{" "}
<SuggestedQuestions onMessageSend={() => {}} />{" "}
{messages.map((message, i) => {
if (message.type === "user") {
return <UserMessage key={i} message={message} idx={i} />;
Expand All @@ -130,28 +46,9 @@ export const ChatMode = () => {
></div>
</div>
</div>
<ChatInput onMessageSend={onMessageSend} showShadow={!isOnScreen} />
<ChatInput onMessageSend={() => {}} showShadow={!isOnScreen} />
</Suspense>
);
};

// sits on the left side of chat in a flexbox to enforce the minimum height and control scroll
const ChatRuler = ({
minHeight,
rulerRef,
}: {
minHeight: number;
rulerRef: React.RefObject<HTMLDivElement>;
}) => {
return (
<div
ref={rulerRef}
className="tv-min-w-[1px]"
style={{
minHeight,
}}
></div>
);
};

export default ChatMode;
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ import React from "react";
import { useChatState } from "../../utils/hooks/chat-context";
import { useModalState } from "../../utils/hooks/modal-context";

export const InlineChatHeader = ({
resetHeight,
}: {
resetHeight: () => void;
}) => {
export const InlineChatHeader = () => {
const { props } = useModalState();
const { messages, clearConversation, isDoneReading, stopGeneratingMessage } =
useChatState();
Expand All @@ -23,7 +19,6 @@ export const InlineChatHeader = ({
className={`tv-text-xs tv-rounded-md !tv-bg-transparent tv-flex !hover:bg-tv-zinc-200 tv-px-2 tv-justify-end tv-items-center tv-p-2 tv-gap-0.5 tv-cursor-pointer ${props.type}`}
onClick={() => {
if (isDoneReading) {
resetHeight();
clearConversation();
} else {
stopGeneratingMessage();
Expand Down
45 changes: 0 additions & 45 deletions clients/search-component/src/utils/hooks/modal-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,6 @@ const ModalContext = createContext<{
setSelectedSidebarFilters: React.Dispatch<
React.SetStateAction<Record<string, string[]>>
>;
minHeight: number;
resetHeight: () => void;
addHeight: (height: number) => void;
}>({
props: defaultProps,
trieveSDK: (() => {}) as unknown as TrieveSDK,
Expand Down Expand Up @@ -320,10 +317,7 @@ const ModalContext = createContext<{
// sidebar filter specific state
selectedSidebarFilters: {},
setSelectedSidebarFilters: () => {},
minHeight: 0,
resetHeight: () => {},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
addHeight: (height: number) => {},
});

const ModalProvider = ({
Expand Down Expand Up @@ -360,9 +354,6 @@ const ModalProvider = ({
const [selectedSidebarFilters, setSelectedSidebarFilters] = useState<
Record<string, string[]>
>({});
const [minHeight, setMinHeight] = useState(0);
const [chatHeight, setChatHeight] = useState(0);
const [enabled, setEnabled] = useState(true);

const trieve = new TrieveSDK({
baseUrl: props.baseUrl,
Expand Down Expand Up @@ -587,39 +578,6 @@ const ModalProvider = ({
};
}, [query, imageUrl, audioBase64, selectedTags, mode]);

useEffect(() => {
if (!modalRef || !modalRef.current) {
return;
}
const ref = modalRef.current;
const observer = new ResizeObserver((entries) => {
setChatHeight(entries[0].contentRect.height);
});

observer.observe(ref);
return () => {
observer.disconnect();
};
}, [modalRef]);

useEffect(() => {
if (chatHeight > minHeight && enabled) {
setMinHeight(chatHeight);
}
}, [chatHeight, minHeight, enabled]);

const resetHeight = useCallback(() => {
setMinHeight(0);
setEnabled(false);
setTimeout(() => {
setEnabled(true);
}, 200);
}, []);

const addHeight = useCallback((height: number) => {
setMinHeight((prev) => prev + height);
}, []);

return (
<ModalContext.Provider
value={{
Expand Down Expand Up @@ -660,9 +618,6 @@ const ModalProvider = ({
setSelectedSidebarFilters,
fingerprint,
setFingerprint,
minHeight,
resetHeight,
addHeight,
}}
>
{children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,6 @@ export const AllRecommendationsTable = () => {
page={page}
setPage={setPage}
label="Recommendations"
tooltipContent="View and filter all your recommendations."
tableHeadings={[
{
heading: "Positive Tracking IDs",
Expand All @@ -374,7 +373,6 @@ export const AllRecommendationsTable = () => {
{ heading: "Results", tooltip: "The number of results returned" },
]}
hasNext={data?.queries.length == 10}
tabs={tabs}
filters={shopifyFilters}
query={query}
setQuery={setQuery}
Expand Down
Loading