From 7c323a22ce4091d44e0b4e3999395c0c3e6bc0bf Mon Sep 17 00:00:00 2001 From: Sahinur Date: Thu, 8 Oct 2026 17:58:12 +0600 Subject: [PATCH] fix: call the latest onReset when double-clicking a sash The sashreset listener is registered once in the mount effect and closed over the onReset prop from the first render. Keep onReset in a ref that is updated when the prop changes, like onChange/onDragStart/onDragEnd. Fixes #901 --- src/allotment.test.tsx | 59 ++++++++++++++++++++++++++++++++++++++++++ src/allotment.tsx | 9 +++++-- 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 src/allotment.test.tsx diff --git a/src/allotment.test.tsx b/src/allotment.test.tsx new file mode 100644 index 00000000..a2555c63 --- /dev/null +++ b/src/allotment.test.tsx @@ -0,0 +1,59 @@ +import React, { act } from "react"; +import { createRoot, Root } from "react-dom/client"; + +import { Allotment } from "./index"; + +class ResizeObserverMock { + observe() {} + unobserve() {} + disconnect() {} +} + +describe("Allotment", () => { + let container: HTMLDivElement; + let root: Root; + + beforeAll(() => { + (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; + (globalThis as any).ResizeObserver ??= ResizeObserverMock; + }); + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + }); + + test("double-clicking a sash calls the latest onReset", () => { + const firstOnReset = jest.fn(); + const secondOnReset = jest.fn(); + + const render = (onReset: () => void) => + act(() => { + root.render( + +
+
+ , + ); + }); + + render(firstOnReset); + render(secondOnReset); + + const sash = container.querySelector(".sash"); + expect(sash).not.toBeNull(); + + act(() => { + sash!.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + }); + + expect(firstOnReset).not.toHaveBeenCalled(); + expect(secondOnReset).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/allotment.tsx b/src/allotment.tsx index 77031a61..57221ae2 100644 --- a/src/allotment.tsx +++ b/src/allotment.tsx @@ -154,6 +154,7 @@ const Allotment = forwardRef( const splitViewViewRef = useRef(new Map()); const layoutService = useRef(new LayoutService()); const views = useRef([]); + const onResetRef = useRef(onReset); const [dimensionsInitialized, setDimensionsInitialized] = useState(false); @@ -287,8 +288,8 @@ const Allotment = forwardRef( }); splitViewRef.current.on("sashreset", (index: number) => { - if (onReset) { - onReset(); + if (onResetRef.current) { + onResetRef.current(); } else { if (resizeToPreferredSize(index)) { return; @@ -470,6 +471,10 @@ const Allotment = forwardRef( } }, [onDragEnd]); + useEffect(() => { + onResetRef.current = onReset; + }, [onReset]); + useResizeObserver({ ref: containerRef, onResize: ({ width, height }) => {