Skip to content

Commit

Permalink
[fix] Fix Context Menu selection lost on Safari
Browse files Browse the repository at this point in the history
  • Loading branch information
NooBat committed Dec 30, 2024
1 parent 85422cf commit 238cdef
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/mui-material/src/Menu/Menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import composeClasses from '@mui/utils/composeClasses';
import HTMLElementType from '@mui/utils/HTMLElementType';
import { useRtl } from '@mui/system/RtlProvider';
import useSlotProps from '@mui/utils/useSlotProps';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import MenuList from '../MenuList';
import Popover, { PopoverPaper } from '../Popover';
import rootShouldForwardProp from '../styles/rootShouldForwardProp';
Expand Down Expand Up @@ -106,6 +107,21 @@ const Menu = React.forwardRef(function Menu(inProps, ref) {

const menuListActionsRef = React.useRef(null);

useEnhancedEffect(() => {
if (open) {
const selection = document.getSelection();

if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);

setTimeout(() => {
// Restore the selection before focusing, to not affect the text selection on Safari and Firefox.
selection.addRange(range);
});
}
}
}, [open]);

const handleEntering = (element, isAppearing) => {
if (menuListActionsRef.current) {
menuListActionsRef.current.adjustStyleForScrollbar(element, {
Expand Down
10 changes: 10 additions & 0 deletions packages/mui-material/src/MenuList/MenuList.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ function moveFocus(
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
const selection = document.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);

setTimeout(() => {
// Restore the selection before focusing, to not affect the text selection on Safari and Firefox.
selection.addRange(range);
});
}

nextFocus.focus();
return true;
}
Expand Down

0 comments on commit 238cdef

Please sign in to comment.