Skip to content

Commit d9cffd3

Browse files
committed
option to scroll to the most recent chat content
1 parent 109a177 commit d9cffd3

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

src/components/Chat/ChatArea.tsx

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,15 @@ export interface ChatAreaProps
2323
*/
2424
contentWidth?: "small" | "medium" | "large" | "full";
2525
/**
26-
* Put in chat content in a list and add spacings automatically.
27-
* Works best if each child represents one chat content item.
26+
* Put chat content in a list and add spacings automatically.
27+
* Works best if each `ChatArea` child represents one chat content item.
2828
*/
2929
autoSpacingSize?: SpacingProps["size"];
30+
/**
31+
* Scrolls content to the first or last child automatically.
32+
* The correct value depends on the place where you insert the most recent chat item.
33+
*/
34+
autoScrollTo?: "first" | "last";
3035
}
3136

3237
/**
@@ -40,8 +45,23 @@ export const ChatArea = ({
4045
contentWidth = "medium",
4146
autoSpacingSize,
4247
gapSize = "medium",
48+
autoScrollTo,
4349
...otherFlexibleLayoutContainerProps
4450
}: ChatAreaProps) => {
51+
const chatcontents = React.useRef<HTMLDivElement>(null);
52+
53+
React.useEffect(() => {
54+
if (chatcontents.current && children && autoScrollTo) {
55+
const chatitems = chatcontents.current.getElementsByClassName(`${eccgui}-chat__content`);
56+
if (chatitems.length > 0) {
57+
chatitems[autoScrollTo === "first" ? 0 : chatitems.length - 1].scrollIntoView({
58+
behavior: "instant",
59+
block: autoScrollTo === "first" ? "start" : "end",
60+
});
61+
}
62+
}
63+
}, [chatcontents, children, autoScrollTo]);
64+
4565
return (
4666
<FlexibleLayoutContainer
4767
className={
@@ -72,7 +92,7 @@ export const ChatArea = ({
7292
: undefined
7393
}
7494
>
75-
<div className={`${eccgui}-chat__area-contentwidth`}>
95+
<div className={`${eccgui}-chat__area-contentwidth`} ref={chatcontents}>
7696
{autoSpacingSize && children ? (
7797
<ul>
7898
{React.Children.toArray(children).map((child) => (

0 commit comments

Comments
 (0)