Skip to content

feat(menu)!: allow users to specify both window and document env #694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/menu/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,19 @@ export interface IUseMenuProps<T = HTMLButtonElement, M = HTMLElement> {
focusedValue?: string | null;
selectedItems?: ISelectedItem[];
}) => void;
/** Sets the environment where the menu is rendered */
/**
* Sets the environment where the menu is rendered
* @deprecated use `window` prop instead.
* */
environment?: Window;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not deprecate; prefer the immediate feat(menu)!: ... breaking change in react-containers

/**
* Sets the window where the menu is rendered
* */
window?: Window;
/**
* Sets the document where the menu is rendered
* */
document?: Document | ShadowRoot;
}

export interface IUseMenuReturnValue {
Expand Down
60 changes: 35 additions & 25 deletions packages/menu/src/useMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,32 @@ import {
} from './types';

export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLElement = HTMLElement>({
items: rawItems,
idPrefix,
defaultExpanded = false,
defaultFocusedValue,
document: documentProp,
environment,
menuRef,
triggerRef,
rtl = false,
onChange = () => undefined,
focusedValue,
idPrefix,
isExpanded,
defaultExpanded = false,
items: rawItems,
menuRef,
restoreFocus = true,
rtl = false,
selectedItems,
focusedValue,
defaultFocusedValue
triggerRef,
window: windowProp,
onChange = () => undefined
}: IUseMenuProps<T, M>): IUseMenuReturnValue => {
const prefix = `${useId(idPrefix)}-`;
const triggerId = `${prefix}menu-trigger`;
const isExpandedControlled = isExpanded !== undefined;
const isSelectedItemsControlled = selectedItems !== undefined;
const isFocusedValueControlled = focusedValue !== undefined;

const _window = windowProp || environment;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recall there being problems with initializing this outside of the handlers because it potentially references globals in a way that breaks SSR. The logic should be restored throughout to get the window and/or document as needed – probably via a utility function.

let _document: Document | ShadowRoot = _window ? _window.document : window.document;
_document = documentProp ? documentProp : _document;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let _document: Document | ShadowRoot = _window ? _window.document : window.document;
_document = documentProp ? documentProp : _document;
let _document: IUseMenuProps['document'];
if (documentProp) {
_document = documentProp
} else {
_document = _window ? _window.document : window.document;
}

...for improved readability and type reuse. Repeated ternaries are difficult to read and usually a signal for refactor.


const menuItems = useMemo(
() =>
rawItems.reduce((items, item: MenuItem) => {
Expand Down Expand Up @@ -398,11 +405,9 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
*/
const handleBlur = useCallback(
(event: React.FocusEvent) => {
const win = environment || window;

setTimeout(() => {
// Timeout is required to ensure blur is handled after focus
const activeElement = win.document.activeElement;
const activeElement = _document.activeElement;
const isMenuOrTriggerFocused =
menuRef.current?.contains(activeElement) || triggerRef.current?.contains(activeElement);

Expand All @@ -420,7 +425,14 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
}
});
},
[closeMenu, controlledIsExpanded, environment, menuRef, returnFocusToTrigger, triggerRef]
[
_document.activeElement,
closeMenu,
controlledIsExpanded,
menuRef,
returnFocusToTrigger,
triggerRef
]
);

const handleMenuMouseLeave = useCallback(() => {
Expand Down Expand Up @@ -515,7 +527,7 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
event.preventDefault();

if (item.href) {
triggerLink(event.target as HTMLAnchorElement, environment || window);
triggerLink(event.target as HTMLAnchorElement, _window || window);
}

returnFocusToTrigger(isTransitionItem);
Expand Down Expand Up @@ -587,16 +599,16 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
}
},
[
_window,
getNextFocusedValue,
getSelectedItems,
isExpandedControlled,
isFocusedValueControlled,
isSelectedItemsControlled,
onChange,
returnFocusToTrigger,
environment,
rtl,
getNextFocusedValue,
isFocusedValueControlled,
state.nestedPathIds,
onChange
state.nestedPathIds
]
);

Expand Down Expand Up @@ -635,18 +647,16 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
* Respond to clicks outside the open menu
*/
useEffect(() => {
const win = environment || window;

if (controlledIsExpanded) {
win.document.addEventListener('keydown', handleMenuKeyDown, true);
(_document as Document).addEventListener('keydown', handleMenuKeyDown, true);
} else if (!controlledIsExpanded) {
win.document.removeEventListener('keydown', handleMenuKeyDown, true);
(_document as Document).removeEventListener('keydown', handleMenuKeyDown, true);
}

return () => {
win.document.removeEventListener('keydown', handleMenuKeyDown, true);
(_document as Document).removeEventListener('keydown', handleMenuKeyDown, true);
};
}, [controlledIsExpanded, handleMenuKeyDown, environment]);
}, [controlledIsExpanded, _document, handleMenuKeyDown]);

/**
* When the menu is opened, this effect sets focus on the current menu item using `focusedValue`
Expand Down