Skip to content
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

Create context menu component #110

Merged
merged 17 commits into from
Jan 5, 2024
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"vitest": "^0.34.4"
},
"dependencies": {
"@radix-ui/react-context-menu": "^2.1.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-form": "^0.0.3",
"@radix-ui/react-separator": "^1.0.3",
Expand Down
80 changes: 80 additions & 0 deletions src/components/Menu/ContextMenu.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
Copyright 2023 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from "react";
import { Meta, StoryFn } from "@storybook/react";
import UserProfileIcon from "@vector-im/compound-design-tokens/icons/user-profile.svg";
import NotificationsIcon from "@vector-im/compound-design-tokens/icons/notifications.svg";
import ChatProblemIcon from "@vector-im/compound-design-tokens/icons/chat-problem.svg";
import LeaveIcon from "@vector-im/compound-design-tokens/icons/leave.svg";

import { ContextMenu as ContextMenuComponent } from "./ContextMenu";
import { MenuItem } from "./MenuItem";
import { Separator } from "../Separator/Separator";

export default {
title: "Menu/ContextMenu",
component: ContextMenuComponent,
tags: ["autodocs"],
argTypes: {},
args: {},
} as Meta<typeof ContextMenuComponent>;

const Template: StoryFn<typeof ContextMenuComponent> = (args) => {
return (
<ContextMenuComponent
{...args}
title="Settings"
trigger={
<div
style={{
borderRadius: 24,
background: "var(--cpd-color-bg-subtle-secondary)",
inlineSize: 300,
blockSize: 200,
textAlign: "center",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 32,
boxSizing: "border-box",
}}
>
Right click or long press to open menu
</div>
}
hasAccessibleAlternative={false}
>
<MenuItem Icon={UserProfileIcon} label="Profile" onSelect={() => {}} />
<MenuItem
Icon={NotificationsIcon}
label="Notifications"
onSelect={() => {}}
/>
<MenuItem Icon={ChatProblemIcon} label="Feedback" onSelect={() => {}} />
<Separator />
<MenuItem
kind="critical"
Icon={LeaveIcon}
label="Sign out"
onSelect={() => {}}
/>
</ContextMenuComponent>
);
};

export const ContextMenu = Template.bind({});
ContextMenu.args = {};
50 changes: 50 additions & 0 deletions src/components/Menu/ContextMenu.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2023 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import React from "react";
import UserProfileIcon from "@vector-im/compound-design-tokens/icons/user-profile.svg";

import { ContextMenu } from "./ContextMenu";
import { MenuItem } from "./MenuItem";
import userEvent from "@testing-library/user-event";

describe("ContextMenu", () => {
it("opens by right-clicking", async () => {
const onOpenChange = vi.fn();
render(
<ContextMenu
title="Settings"
onOpenChange={onOpenChange}
trigger={<div>Open menu</div>}
hasAccessibleAlternative
>
<MenuItem Icon={UserProfileIcon} label="Profile" onSelect={() => {}} />
</ContextMenu>,
);

expect(screen.queryByRole("menu")).toBe(null);
// Right-click the trigger area
const trigger = screen.getByText("Open menu");
await userEvent.pointer([{ target: trigger }, { keys: "[MouseRight]" }]);
expect(onOpenChange).toHaveBeenLastCalledWith(true);
});

// Here it would be nice to also test opening by long-pressing, but that
// requires fake timers, and user-event appears to stall out when using fake
// timers :(
});
142 changes: 142 additions & 0 deletions src/components/Menu/ContextMenu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
Copyright 2023 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React, { FC, ReactNode, useCallback, useMemo, useState } from "react";
import {
Root,
Trigger,
Portal,
Content,
ContextMenuItem,
} from "@radix-ui/react-context-menu";
import { FloatingMenu } from "./FloatingMenu";
import { Drawer } from "vaul";
import classnames from "classnames";
import drawerStyles from "./DrawerMenu.module.css";
import { MenuContext, MenuData, MenuItemWrapperProps } from "./MenuContext";
import { DrawerMenu } from "./DrawerMenu";
import { getPlatform } from "../../utils/platform";

interface Props {
/**
* The menu title.
*/
title: string;
/**
* Event handler called when the open state of the menu changes.
*/
onOpenChange?: (open: boolean) => void;
/**
* The trigger that can be right-clicked or long-pressed to open the menu.
* This must be a component that accepts a ref and spreads props.
* https://www.radix-ui.com/primitives/docs/guides/composition
*/
trigger: ReactNode;
/**
* Whether the functionality of this menu is available through some other
* keyboard-accessible means. Preferably this should be true, because context
* menus are potentially difficult to discover, but if false the trigger will
* become focusable so that it can be opened via keyboard navigation.
*/
hasAccessibleAlternative: boolean;
/**
* The menu contents.
*/
children: ReactNode;
}

const ContextMenuItemWrapper: FC<MenuItemWrapperProps> = ({
onSelect,
children,
}) => (
<ContextMenuItem onSelect={onSelect ?? undefined} asChild>
{children}
</ContextMenuItem>
);

/**
* A menu opened by right-clicking or long-pressing another UI element.
*/
export const ContextMenu: FC<Props> = ({
title,
onOpenChange: onOpenChangeProp,
trigger: triggerProp,
hasAccessibleAlternative,
children: childrenProp,
}) => {
const [open, setOpen] = useState(false);
robintown marked this conversation as resolved.
Show resolved Hide resolved
const onOpenChange = useCallback(
(value: boolean) => {
setOpen(value);
onOpenChangeProp?.(value);
},
[setOpen, onOpenChangeProp],
);

// Normally, the menu takes the form of a floating box. But on Android and
// iOS, the menu should morph into a drawer
const platform = getPlatform();
const drawer = platform === "android" || platform === "ios";
const context: MenuData = useMemo(
() => ({
MenuItemWrapper: drawer ? null : ContextMenuItemWrapper,
onOpenChange,
}),
[onOpenChange],
);
const children = (
<MenuContext.Provider value={context}>{childrenProp}</MenuContext.Provider>
);

const trigger = (
<Trigger
aria-haspopup="menu"
tabIndex={hasAccessibleAlternative ? undefined : 0}
asChild
>
{triggerProp}
</Trigger>
);

// This is a small hack: Vaul drawers only support buttons as triggers, so
// we end up mounting an empty Radix context menu tree alongside the
// drawer tree, purely so we can use its Trigger component (which supports
// touch for free). The resulting behavior and DOM tree looks exactly the
// same as if Vaul provided a long-press trigger of its own, so I think
// this is fine.
return drawer ? (
<>
<Root onOpenChange={onOpenChange}>{trigger}</Root>
<Drawer.Root open={open} onOpenChange={onOpenChange}>
<Drawer.Portal>
<Drawer.Overlay className={classnames(drawerStyles.bg)} />
<Drawer.Content asChild>
<DrawerMenu title={title}>{children}</DrawerMenu>
</Drawer.Content>
</Drawer.Portal>
</Drawer.Root>
</>
) : (
<Root onOpenChange={onOpenChange}>
{trigger}
<Portal>
<Content asChild>
<FloatingMenu title={title}>{children}</FloatingMenu>
</Content>
</Portal>
</Root>
);
};
2 changes: 1 addition & 1 deletion src/components/Menu/ToggleMenuItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Props = Pick<
ComponentProps<typeof MenuItem>,
"className" | "Icon" | "label" | "onSelect"
> &
Omit<ComponentProps<typeof ToggleInput>, "id" | "children">;
Omit<ComponentProps<typeof ToggleInput>, "id" | "children" | "onSelect">;

/**
* A menu item with a toggle control. Clicking anywhere on the surface will
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export { Badge } from "./components/Badge/Badge";
export { Button, IconButton } from "./components/Button";
export { Body } from "./components/Typography/Body";
export { Text } from "./components/Typography/Text";
export { ContextMenu } from "./components/Menu/ContextMenu";
export { Glass } from "./components/Glass/Glass";
export {
Heading,
Expand Down
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default defineConfig({
"classnames",
"graphemer",
"vaul",
"@radix-ui/react-context-menu",
"@radix-ui/react-dropdown-menu",
"@radix-ui/react-form",
"@radix-ui/react-tooltip",
Expand Down
13 changes: 13 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1747,6 +1747,19 @@
dependencies:
"@babel/runtime" "^7.13.10"

"@radix-ui/react-context-menu@^2.1.5":
version "2.1.5"
resolved "https://registry.yarnpkg.com/@radix-ui/react-context-menu/-/react-context-menu-2.1.5.tgz#1bdbd72761439f9166f75dc4598f276265785c83"
integrity sha512-R5XaDj06Xul1KGb+WP8qiOh7tKJNz2durpLBXAGZjSVtctcRFCuEvy2gtMwRJGePwQQE5nV77gs4FwRi8T+r2g==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/primitive" "1.0.1"
"@radix-ui/react-context" "1.0.1"
"@radix-ui/react-menu" "2.0.6"
"@radix-ui/react-primitive" "1.0.3"
"@radix-ui/react-use-callback-ref" "1.0.1"
"@radix-ui/react-use-controllable-state" "1.0.1"

"@radix-ui/[email protected]":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/react-context/-/react-context-1.0.1.tgz#fe46e67c96b240de59187dcb7a1a50ce3e2ec00c"
Expand Down