From 423ebb403f889734a2d74f5fa2639d5f940a5f48 Mon Sep 17 00:00:00 2001 From: Gigi Date: Tue, 14 Oct 2025 11:24:35 +0200 Subject: [PATCH] fix: add retry mechanism for scroll-to-highlight in article content - Replace single 100ms delay with retry mechanism - Try up to 20 times (2 seconds total) to find highlight mark element - Fixes timing issue when content is still loading from explore page - Mark elements need time to be rendered after article loads - Retry every 100ms until element is found or max attempts reached - Improves reliability of highlight scrolling from external navigation --- src/hooks/useHighlightInteractions.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/hooks/useHighlightInteractions.ts b/src/hooks/useHighlightInteractions.ts index baf9d90f..024db59a 100644 --- a/src/hooks/useHighlightInteractions.ts +++ b/src/hooks/useHighlightInteractions.ts @@ -58,12 +58,15 @@ export const useHighlightInteractions = ({ } }, [onHighlightClick, contentVersion]) - // Scroll to selected highlight + // Scroll to selected highlight with retry mechanism useEffect(() => { if (!selectedHighlightId || !contentRef.current) return - // Use a small delay to ensure DOM is updated - const timeoutId = setTimeout(() => { + let attempts = 0 + const maxAttempts = 20 // Try for up to 2 seconds + const retryDelay = 100 + + const tryScroll = () => { if (!contentRef.current) return const markElement = contentRef.current.querySelector(`mark[data-highlight-id="${selectedHighlightId}"]`) @@ -76,10 +79,16 @@ export const useHighlightInteractions = ({ htmlElement.classList.add('highlight-pulse') setTimeout(() => htmlElement.classList.remove('highlight-pulse'), 1500) }, 500) + } else if (attempts < maxAttempts) { + attempts++ + setTimeout(tryScroll, retryDelay) } else { - console.warn('Could not find mark element for highlight:', selectedHighlightId) + console.warn('Could not find mark element for highlight after', maxAttempts, 'attempts:', selectedHighlightId) } - }, 100) + } + + // Start trying after a small initial delay + const timeoutId = setTimeout(tryScroll, 100) return () => clearTimeout(timeoutId) }, [selectedHighlightId, contentVersion])