Skip to content

revert using portal for render menu and add exenv package for checkin… #167

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 1 commit 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
12 changes: 12 additions & 0 deletions cypress/integration/context-menu.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ describe('Context menu', () => {
cy.getByDataTest(DATA_TEST.CONTEXT_MENU).should('be.visible');
});

it('Can mount on specified dom node', () => {
cy.getByDataTest(DATA_TEST.CONTEXT_MENU_TRIGGER).rightclick();
cy.getByDataTest(DATA_TEST.CONTEXT_MENU).should('be.visible');

cy.getByDataTest(DATA_TEST.MOUNT_NODE).then(el => {
expect(el.children().length).to.eq(0);
});

cy.getByDataTest(DATA_TEST.TOGGLE_MOUNT_NODE).check();
cy.getByDataTest(DATA_TEST.CONTEXT_MENU_TRIGGER).rightclick();
});

it('Close on Escape', () => {
cy.getByDataTest(DATA_TEST.CONTEXT_MENU_TRIGGER).rightclick();
cy.getByDataTest(DATA_TEST.CONTEXT_MENU).should('be.visible');
Expand Down
17 changes: 17 additions & 0 deletions example/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ interface SelectorState {
animation: string | false;
event: string;
hideItems: boolean;
customMountNode: boolean;
customPosition: boolean;
disableEnterAnimation: boolean;
disableExitAnimation: boolean;
Expand Down Expand Up @@ -68,6 +69,7 @@ export function App() {
animation: false,
event: selector.events[0],
hideItems: false,
customMountNode: false,
customPosition: false,
disableEnterAnimation: false,
disableExitAnimation: false,
Expand All @@ -81,6 +83,9 @@ export function App() {
const { show } = useContextMenu({
id: MENU_ID,
});
const customMountNode = document.querySelector(
`[data-test="${DATA_TEST.MOUNT_NODE}"]`
);

function handleSelector({
target: { name, value },
Expand Down Expand Up @@ -153,6 +158,17 @@ export function App() {
/>
</li>
))}
<li>
<label htmlFor="customMountNode">Use custom mount node</label>
<input
type="checkbox"
id="customMountNode"
name="customMountNode"
checked={state.customMountNode}
onChange={handleCheckboxes}
data-test={DATA_TEST.TOGGLE_MOUNT_NODE}
/>
</li>
<li>
<label htmlFor="customPosition">Use custom position</label>
<input
Expand Down Expand Up @@ -224,6 +240,7 @@ export function App() {
theme={state.theme}
animation={getAnimation()}
data-test={DATA_TEST.CONTEXT_MENU}
mountNode={state.customMountNode ? customMountNode : null}
>
<Item
onClick={handleItemClick}
Expand Down
1 change: 1 addition & 0 deletions example/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const MENU_ID = '🦄';

export const enum DATA_TEST {
MOUNT_NODE = 'mount-node',
TOGGLE_MOUNT_NODE = 'toggle-mount-node',
TOGGLE_CUSTOM_POSITION = 'toggle-custom-position',
CONTEXT_MENU_TRIGGER = 'trigger',
CONTEXT_MENU = 'context-menu',
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
],
"module": "dist/react-contexify.esm.js",
"devDependencies": {
"@types/exenv": "^1.2.0",
"@types/react": "^16.9.56",
"@types/react-dom": "^16.9.9",
"cssnano": "^4.1.10",
Expand All @@ -76,6 +77,7 @@
"typescript": "^4.0.3"
},
"dependencies": {
"clsx": "^1.1.1"
"clsx": "^1.1.1",
"exenv": "^1.2.2"
}
}
41 changes: 23 additions & 18 deletions src/components/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import React, {
} from 'react';
import cx from 'clsx';

import { Portal, PortalProps } from './Portal';
import { RefTrackerProvider } from './RefTrackerProvider';

import { eventManager } from '../core/eventManager';
Expand All @@ -29,7 +30,8 @@ import {
} from './utils';

export interface MenuProps
extends Omit<React.HTMLAttributes<HTMLElement>, 'id'> {
extends PortalProps,
Omit<React.HTMLAttributes<HTMLElement>, 'id'> {
/**
* Unique id to identify the menu. Use to Trigger the corresponding menu
*/
Expand Down Expand Up @@ -99,6 +101,7 @@ export const Menu: React.FC<MenuProps> = ({
style,
className,
children,
mountNode,
animation = 'scale',
onHidden = NOOP,
onShown = NOOP,
Expand Down Expand Up @@ -310,22 +313,24 @@ export const Menu: React.FC<MenuProps> = ({
};

return (
<RefTrackerProvider refTracker={refTracker}>
{visible && (
<div
{...rest}
className={cssClasses}
onAnimationEnd={handleAnimationEnd}
style={menuStyle}
ref={nodeRef}
role="menu"
>
{cloneItems(children, {
propsFromTrigger,
triggerEvent,
})}
</div>
)}
</RefTrackerProvider>
<Portal mountNode={mountNode}>
<RefTrackerProvider refTracker={refTracker}>
{visible && (
<div
{...rest}
className={cssClasses}
onAnimationEnd={handleAnimationEnd}
style={menuStyle}
ref={nodeRef}
role="menu"
>
{cloneItems(children, {
propsFromTrigger,
triggerEvent,
})}
</div>
)}
</RefTrackerProvider>
</Portal>
);
};
50 changes: 50 additions & 0 deletions src/components/Portal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';

import { canUseDOM, isFn } from './utils';

export interface PortalProps {
/**
* HTML node where to mount the context menu.
*
* In SSR mode, prefer the callback form to be sure that document is only
* accessed on the client. `e.g. () => document.querySelector('#element')`
*
* `default: document.body`
*/
mountNode?: Element | (() => Element);
}

export const Portal: React.FC<PortalProps> = ({ children, mountNode }) => {
const [canRender, setCanRender] = useState(false);
const node = useRef<HTMLDivElement>();

useEffect(() => {
let parentNode: Element;
if (canUseDOM) {
parentNode = document.body;
node.current = document.createElement('div');

if (isFn(mountNode)) {
parentNode = mountNode();
} else if (mountNode instanceof Element) {
parentNode = mountNode;
}

parentNode.appendChild(node.current);

setCanRender(true);
}
return () => {
if (canUseDOM) {
parentNode.removeChild(node.current!);
}
};
}, [mountNode]);

if (!canUseDOM) {
return null;
}

return canRender ? createPortal(children, node.current!) : null;
};
3 changes: 3 additions & 0 deletions src/components/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Children, cloneElement, ReactNode, ReactElement } from 'react';
import ExecutionEnvironment from 'exenv';

import {
BooleanPredicate,
Expand Down Expand Up @@ -64,3 +65,5 @@ export function hasExitAnimation(animation: MenuAnimation) {
(isStr(animation) || ('exit' in animation && animation.exit))
);
}

export const canUseDOM = ExecutionEnvironment.canUseDOM;
10 changes: 10 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1241,6 +1241,11 @@
resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f"
integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==

"@types/exenv@^1.2.0":
version "1.2.0"
resolved "https://registry.yarnpkg.com/@types/exenv/-/exenv-1.2.0.tgz#84ff936feeafc917c3c66f80b43e917f56eed00b"
integrity sha512-kSyh9q6bvrOGEnJ9X9Io5gjXaakcSRQTax/Nj2ZKJHuOZ7bH4uvUgLyXA9uV2QBCP7+T8KS0JHbPfP1/79ckKw==

"@types/graceful-fs@^4.1.2":
version "4.1.4"
resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.4.tgz#4ff9f641a7c6d1a3508ff88bc3141b152772e753"
Expand Down Expand Up @@ -3338,6 +3343,11 @@ executable@^4.1.1:
dependencies:
pify "^2.2.0"

exenv@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/exenv/-/exenv-1.2.2.tgz#2ae78e85d9894158670b03d47bec1f03bd91bb9d"
integrity sha1-KueOhdmJQVhnCwPUe+wfA72Ru50=

exit-hook@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8"
Expand Down