From b3644704ecfb9f68b8f7c561c661f0457d6d1097 Mon Sep 17 00:00:00 2001 From: Xinyuan Wang Date: Mon, 19 Jun 2023 08:23:12 -0400 Subject: [PATCH] Fix dropdown menu position in playground when scroll (#4496) --- .../lexical-playground/src/ui/DropDown.tsx | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/lexical-playground/src/ui/DropDown.tsx b/packages/lexical-playground/src/ui/DropDown.tsx index aa2508bfc67..ba5ef5f8bb9 100644 --- a/packages/lexical-playground/src/ui/DropDown.tsx +++ b/packages/lexical-playground/src/ui/DropDown.tsx @@ -6,6 +6,7 @@ * */ +import * as React from 'react'; import { ReactNode, useCallback, @@ -14,7 +15,6 @@ import { useRef, useState, } from 'react'; -import * as React from 'react'; import {createPortal} from 'react-dom'; type DropDownContextType = { @@ -23,6 +23,8 @@ type DropDownContextType = { const DropDownContext = React.createContext(null); +const dropDownPadding = 4; + export function DropDownItem({ children, className, @@ -167,7 +169,7 @@ export default function DropDown({ if (showDropDown && button !== null && dropDown !== null) { const {top, left} = button.getBoundingClientRect(); - dropDown.style.top = `${top + 40}px`; + dropDown.style.top = `${top + button.offsetHeight + dropDownPadding}px`; dropDown.style.left = `${Math.min( left, window.innerWidth - dropDown.offsetWidth - 20, @@ -200,6 +202,28 @@ export default function DropDown({ } }, [dropDownRef, buttonRef, showDropDown, stopCloseOnClickSelf]); + useEffect(() => { + const handleButtonPositionUpdate = () => { + if (showDropDown) { + const button = buttonRef.current; + const dropDown = dropDownRef.current; + if (button !== null && dropDown !== null) { + const {top} = button.getBoundingClientRect(); + const newPosition = top + button.offsetHeight + dropDownPadding; + if (newPosition !== dropDown.getBoundingClientRect().top) { + dropDown.style.top = `${newPosition}px`; + } + } + } + }; + + document.addEventListener('scroll', handleButtonPositionUpdate); + + return () => { + document.removeEventListener('scroll', handleButtonPositionUpdate); + }; + }, [buttonRef, dropDownRef, showDropDown]); + return ( <>