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
This commit is contained in:
yhua1998 2023-09-13 13:57:30 +08:00 committed by GitHub
parent b589f48aa9
commit 368701610f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
import { useEffect, useRef } from "react"; import { useEffect, useRef, useCallback } from "react";
import styles from "./home.module.scss"; import styles from "./home.module.scss";
@ -53,7 +53,7 @@ function useHotKey() {
} }
function useDragSideBar() { 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 config = useAppConfig();
const startX = useRef(0); const startX = useRef(0);
@ -71,14 +71,16 @@ function useDragSideBar() {
}); });
const handleMouseUp = useRef(() => { 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("mousemove", handleMouseMove.current);
window.removeEventListener("mouseup", handleMouseUp.current); window.removeEventListener("mouseup", handleMouseUp.current);
}); });
const onDragMouseDown = (e: MouseEvent) => { const onDragMouseDown = (e: MouseEvent) => {
startX.current = e.clientX; 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("mousemove", handleMouseMove.current);
window.addEventListener("mouseup", handleMouseUp.current); window.addEventListener("mouseup", handleMouseUp.current);
}; };