adds scrolltobottom button, still handling initial state when scrollbar is present

This commit is contained in:
Danny Avila 2023-02-13 16:31:18 -05:00
parent 583fd56ca5
commit 92b2109dc3
3 changed files with 53 additions and 10 deletions

View file

@ -1,8 +1,9 @@
import React, { useEffect, useRef } from 'react';
import React, { useEffect, useState, useRef } from 'react';
import { useSelector } from 'react-redux';
import useDocumentTitle from '~/hooks/useDocumentTitle';
import useDidMountEffect from '~/hooks/useDidMountEffect';
import Message from './Message';
import ScrollToBottom from './ScrollToBottom';
import Landing from './Landing';
export default function Messages({ title, messages }) {
@ -11,23 +12,33 @@ export default function Messages({ title, messages }) {
}
useDocumentTitle(title);
const messagesEndRef = useRef(null);
const [showScrollButton, setShowScrollButton] = useState(false);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// this useEffect triggers the following warning:
// Warning: Internal React error: Expected static flag was missing.
// useEffect(() => {
// scrollToBottom();
// }, [messages]);
if (document.body.clientHeight > window.innerHeight) {
setShowScrollButton(true);
}
useDidMountEffect(() => scrollToBottom(), [messages]);
const handleScroll = (e) => {
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
setShowScrollButton(false);
} else {
setShowScrollButton(true);
}
}
const scrollHandler = (e) => {
e.preventDefault();
scrollToBottom();
};
return (
<div className="flex-1 overflow-y-auto ">
<div className="flex-1 overflow-y-auto " onScroll={handleScroll}>
{/* <div className="flex-1 overflow-hidden"> */}
<div className="h-full dark:bg-gray-800">
<div className="flex h-full flex-col items-center text-sm dark:bg-gray-800">
@ -40,6 +51,7 @@ export default function Messages({ title, messages }) {
error={!!message.error ? true : false}
/>
))}
{showScrollButton && <ScrollToBottom scrollHandler={scrollHandler} />}
<div
className="group h-32 w-full flex-shrink-0 dark:border-gray-900/50 dark:bg-gray-800 md:h-48"
ref={messagesEndRef}

View file

@ -0,0 +1,31 @@
import React from 'react';
export default function ScrollToBottom({ scrollHandler }) {
return (
<button
onClick={scrollHandler}
className="absolute right-6 bottom-[124px] z-10 cursor-pointer rounded-full border border-gray-200 bg-gray-50 text-gray-600 dark:border-white/10 dark:bg-white/10 dark:text-gray-200 md:bottom-[120px]"
>
<svg
stroke="currentColor"
fill="none"
strokeWidth="2"
viewBox="0 0 24 24"
strokeLinecap="round"
strokeLinejoin="round"
className="m-1 h-4 w-4"
height="1em"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<line
x1="12"
y1="5"
x2="12"
y2="19"
/>
<polyline points="19 12 12 19 5 12" />
</svg>
</button>
);
}