From db683451edc91f45b5d03f01b142475e72a61b86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ricles=20Emanuel?= Date: Sun, 7 Jan 2024 10:32:21 -0300 Subject: [PATCH] fix: highlight all paragraphs on textlines component --- islands/NRF/TextLines.tsx | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/islands/NRF/TextLines.tsx b/islands/NRF/TextLines.tsx index 5815c206..c3da2306 100644 --- a/islands/NRF/TextLines.tsx +++ b/islands/NRF/TextLines.tsx @@ -1,5 +1,5 @@ import { useEffect } from "preact/hooks"; -import { animate, AnimationControls, scroll } from "motion"; +import { animate, scroll } from "motion"; export interface Props { lines: string[]; @@ -11,25 +11,27 @@ function TextLines({ lines, animateOnScroll }: Props) { if (animateOnScroll) { const section = document.querySelector("#section")!; const paragraphs = document.querySelectorAll("#section p"); - let selectedParagraphIndex: number | null = null; + let lastHighlighted = 0; - scroll( - ({ y }: { y: { progress: number } }) => { - const index = Math.floor(y.progress * paragraphs.length); - if (index !== selectedParagraphIndex && y.progress !== 0) { - animate(paragraphs[selectedParagraphIndex!], { color: "#131313" }); - animate(paragraphs[index], { color: "white" }); - selectedParagraphIndex = index; - } else if (y.progress === 0) { - animate(paragraphs[selectedParagraphIndex!], { color: "#131313" }); - selectedParagraphIndex = null; - } - }, - { - target: section, - offset: ["0 0", "end end"], + const handleScroll = ({ y }: { y: { progress: number } }) => { + const currHighlighted = Math.floor( + y.progress * (paragraphs.length + 1) + ); + const direction = currHighlighted > lastHighlighted ? 1 : -1; + const color = direction === 1 ? "white" : "#131313"; + + for ( + let i = lastHighlighted; + direction === 1 ? i < currHighlighted : i >= currHighlighted; + i += direction + ) { + animate(paragraphs[i], { color }); } - ); + + lastHighlighted = currHighlighted; + }; + + scroll(handleScroll, { target: section, offset: ["0 0", "end end"] }); } }, []);