From 368701610f039241eeb0fda27db28803b607527e Mon Sep 17 00:00:00 2001 From: yhua1998 <101091026+yhua1998@users.noreply.github.com> Date: Wed, 13 Sep 2023 13:57:30 +0800 Subject: [PATCH] fix: Width changes abruptly when dragging the sidebar (jumps) In useRef is non-responsive, we can't get the modified config.sidebarWidth dynamic modification value in handleMouseUp --- app/components/sidebar.tsx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/components/sidebar.tsx b/app/components/sidebar.tsx index 634639f1..c42138ef 100644 --- a/app/components/sidebar.tsx +++ b/app/components/sidebar.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useCallback } from "react"; import styles from "./home.module.scss"; @@ -53,7 +53,7 @@ function useHotKey() { } function useDragSideBar() { - const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x); + const limit = useCallback((x: number) => Math.min(MAX_SIDEBAR_WIDTH, x)); const config = useAppConfig(); const startX = useRef(0); @@ -71,14 +71,16 @@ function useDragSideBar() { }); const handleMouseUp = useRef(() => { - startDragWidth.current = config.sidebarWidth ?? 300; + // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth + // startDragWidth.current = config.sidebarWidth ?? 300; window.removeEventListener("mousemove", handleMouseMove.current); window.removeEventListener("mouseup", handleMouseUp.current); }); const onDragMouseDown = (e: MouseEvent) => { startX.current = e.clientX; - + // Remembers the initial width each time the mouse is pressed + startDragWidth.current = config.sidebarWidth window.addEventListener("mousemove", handleMouseMove.current); window.addEventListener("mouseup", handleMouseUp.current); };