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 all commits
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
3 changes: 2 additions & 1 deletion packages/menu/src/MenuContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ MenuContainer.propTypes = {
triggerRef: PropTypes.any.isRequired,
menuRef: PropTypes.any.isRequired,
idPrefix: PropTypes.string,
environment: PropTypes.any,
document: PropTypes.any,
window: PropTypes.any,
onChange: PropTypes.func,
isExpanded: PropTypes.bool,
defaultExpanded: PropTypes.bool,
Expand Down
10 changes: 8 additions & 2 deletions packages/menu/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,14 @@ export interface IUseMenuProps<T = HTMLButtonElement, M = HTMLElement> {
focusedValue?: string | null;
selectedItems?: ISelectedItem[];
}) => void;
/** Sets the environment where the menu is rendered */
environment?: Window;
/**
* 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
73 changes: 50 additions & 23 deletions packages/menu/src/useMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,26 +38,46 @@ import {
ISelectedItem
} from './types';

/**
* Returns the document object from the window or document prop. To maintain SSR compatibility, use within useEffect hooks to reference correct document object.
*
* @param win
* @param doc
* @returns Document
*/
function getDocument(win?: IUseMenuProps['window'], doc?: IUseMenuProps['document']) {
let _document: IUseMenuProps['document'];

if (doc) {
_document = doc;
} else {
_document = win ? win.document : window.document;
}
return _document;
}

export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLElement = HTMLElement>({
items: rawItems,
defaultExpanded = false,
defaultFocusedValue,
document: documentProp,
focusedValue,
idPrefix,
environment,
menuRef,
triggerRef,
rtl = false,
onChange = () => undefined,
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 menuItems = useMemo(
() =>
rawItems.reduce((items, item: MenuItem) => {
Expand Down Expand Up @@ -398,11 +418,10 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
*/
const handleBlur = useCallback(
(event: React.FocusEvent) => {
const win = environment || window;

setTimeout(() => {
const _document = getDocument(windowProp, documentProp);
// 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 +439,15 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
}
});
},
[closeMenu, controlledIsExpanded, environment, menuRef, returnFocusToTrigger, triggerRef]
[
closeMenu,
controlledIsExpanded,
documentProp,
menuRef,
returnFocusToTrigger,
triggerRef,
windowProp
]
);

const handleMenuMouseLeave = useCallback(() => {
Expand Down Expand Up @@ -515,7 +542,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, windowProp || window);
}

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

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

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

return () => {
win.document.removeEventListener('keydown', handleMenuKeyDown, true);
(_document as Document).removeEventListener('keydown', handleMenuKeyDown, true);
Comment on lines +665 to +674
Copy link
Member

Choose a reason for hiding this comment

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

Is it worth coercing the getDocument return value to Document so you don't need to repeatedly coerce throughout?

};
}, [controlledIsExpanded, handleMenuKeyDown, environment]);
}, [controlledIsExpanded, documentProp, handleMenuKeyDown, windowProp]);

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