From 52944464072c521b961de39895bc9285cbf1540b Mon Sep 17 00:00:00 2001 From: Yuyao Huang Date: Sat, 9 May 2026 16:04:08 +0800 Subject: [PATCH] fix: use requestAnimationFrame to defer in-focus and handler binding requestAnimationFrame waits until after the browser has rendered the current frame, which includes processing the async scroll event queued by scrollToTask. This ensures in-focus is set after the scroll event fires, not overwritten by it. --- static/js/tasks.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/static/js/tasks.js b/static/js/tasks.js index b910252..8150f84 100644 --- a/static/js/tasks.js +++ b/static/js/tasks.js @@ -69,16 +69,18 @@ async function loadTasks() { } } - // Directly set in-focus on the scrolled task instead of recalculating - if (focusTaskId) { - document.querySelectorAll(".task-item.in-focus").forEach(el => el.classList.remove("in-focus")); - const focusEl = document.querySelector(`[data-task-id="${focusTaskId}"]`); - if (focusEl) { - focusEl.classList.add("in-focus"); + // Wait one frame so the async scroll event from scrollToTask fires first, + // then set in-focus and bind handlers after it has been consumed. + requestAnimationFrame(() => { + if (focusTaskId) { + document.querySelectorAll(".task-item.in-focus").forEach(el => el.classList.remove("in-focus")); + const focusEl = document.querySelector(`[data-task-id="${focusTaskId}"]`); + if (focusEl) { + focusEl.classList.add("in-focus"); + } } - } - - initScrollFocus(); + initScrollFocus(); + }); } catch (error) { console.error("Failed to load tasks:", error); } @@ -170,12 +172,8 @@ function initScrollFocus() { scrollView.removeEventListener("scroll", handleScrollFocus); scrollView.removeEventListener("scroll", handleScrollSave); - - // Delay binding to skip the async scroll event queued by scrollToTask - setTimeout(() => { - scrollView.addEventListener("scroll", handleScrollFocus); - scrollView.addEventListener("scroll", handleScrollSave); - }, 0); + scrollView.addEventListener("scroll", handleScrollFocus); + scrollView.addEventListener("scroll", handleScrollSave); } function handleScrollFocus() {