1
0
mirror of https://github.com/spacebarchat/client.git synced 2024-11-22 02:12:38 +01:00

re-spoiler when scrolled out of view

This commit is contained in:
Puyodead1 2023-09-23 17:04:42 -04:00
parent 3564c06047
commit 9d4b82a761
No known key found for this signature in database
GPG Key ID: A4FA4FEC0DD353FC

View File

@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
const Container = styled.span`
@ -16,17 +16,16 @@ const Container = styled.span`
&.visible {
background-color: hsl(var(--background-tertiary-hsl) / 0.3);
cursor: pointer;
// target child span
& > span {
opacity: 1;
}
}
`;
const Text = styled.span`
opacity: 0;
transition: opacity 0.1s ease;
.text {
opacity: 0;
transition: opacity 0.1s ease;
}
&.visible .text {
opacity: 1;
}
`;
interface Props {
@ -34,13 +33,35 @@ interface Props {
}
function Spoiler({ children }: Props) {
const [shown, setShown] = React.useState(false);
const [shown, setShown] = useState(false);
const containerRef = useRef<HTMLSpanElement | null>(null);
const show = () => setShown(true);
useEffect(() => {
const handleIntersection = (entries: IntersectionObserverEntry[]) => {
// when the element is not in the viewport, hide the spoiler
if (entries[0].intersectionRatio === 0 && shown) {
setShown(false);
}
};
const observer = new IntersectionObserver(handleIntersection);
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => {
if (containerRef.current) {
observer.unobserve(containerRef.current);
}
};
}, [shown]);
return (
<Container className={shown ? "visible" : undefined}>
<Text onClick={show}>{children}</Text>
<Container className={shown ? "visible" : ""} onClick={show} ref={containerRef}>
<span className="text">{children}</span>
</Container>
);
}