Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
70 changes: 54 additions & 16 deletions docs/Menu.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,34 @@ export const MyMenu = () => (
);
```

| Prop | Required | Type | Default | Description |
| ------------- | -------- | -------------------- | ------- | ---------------------------------------- |
| `to` | Required | `string | location` | - | The menu item's target. It is passed to a React Router [NavLink](https://reacttraining.com/react-router/web/api/NavLink) component. |
| `primaryText` | Required | `ReactNode` | - | The menu content, displayed when the menu isn't minimized. |
| `leftIcon` | Optional | `ReactNode` | - | The menu icon |
| Prop | Required | Type | Default | Description |
| ------------------ | -------- | -------------------- | ------- | ---------------------------------------- |
| `to` | Required | `string | location` | - | The menu item's target. It is passed to a React Router [NavLink](https://reacttraining.com/react-router/web/api/NavLink) component. |
| `primaryText` | Required | `ReactNode` | - | The menu content, displayed when the menu isn't minimized. |
| `keyboardShortcut` | Optional | `string | string[]` | - | The keyboard shortcut(s) to activate this menu item |
| `leftIcon` | Optional | `ReactNode` | - | The menu icon |
| `sx` | Optional | `SxProp` | - | Style overrides, powered by MUI System |

Additional props are passed down to [the underling Material UI `<MenuItem>` component](https://mui.com/material-ui/api/menu-item/).

### `to`

The `primaryText` prop accepts a string, that react-admin passes through the [translation utility](./Translation.md). Alternately, you can set the menu item content using the `children`, e.g. to display a badge on top of the menu item:
The menu item's target. It is passed to a React Router [NavLink](https://reacttraining.com/react-router/web/api/NavLink) component.

```tsx
// in src/MyMenu.js
import { Menu } from 'react-admin';

export const MyMenu = () => (
<Menu>
<Menu.Item to="/custom-route" primaryText="Miscellaneous" />
</Menu>
);
```

### `primaryText`

The menu content, displayed when the menu isn't minimized. It accepts a string, that react-admin passes through the [translation utility](./Translation.md). Alternately, you can set the menu item content using the `children`, e.g. to display a badge on top of the menu item:

```jsx
import Badge from '@mui/material/Badge';
Expand All @@ -212,6 +230,26 @@ export const MyMenu = () => (

Note that if you use the `children` prop, you'll have to translate the menu item content yourself using [`useTranslate`](./useTranslate.md). You'll also need to provide a `primaryText` either way, because it will be rendered in the tooltip when the side menu is collapsed.

### `keyboardShortcut`

The keyboard shortcut(s) to activate this menu item. Pass a string or an array of string that defines the supported keyboard shortcuts:
Comment thread
Madeorsk marked this conversation as resolved.

```tsx
export const MyMenu = () => (
<Menu>
<Menu.Item
to="/sales"
primaryText="Sales"
keyboardShortcut="ctrl+alt+S"
/>
</Menu>
);
```

This leverages the [react-hotkeys-hook](https://github.com/JohannesKlauss/react-hotkeys-hook) library, checkout [their documentation](https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/) for more examples.
Comment thread
slax57 marked this conversation as resolved.
Outdated

### `leftIcon`

The `letfIcon` prop allows setting the menu left icon.

```jsx
Expand All @@ -231,7 +269,16 @@ export const MyMenu = () => (
);
```

Additional props are passed down to [the underling Material UI `<MenuItem>` component](https://mui.com/material-ui/api/menu-item/).
### `sx`

You can use the `sx` prop to customize the style of the component.

| Rule name | Description |
|-----------------------------|---------------------------------------------------------------------|
| `&.RaMenuItemLink-active` | Applied to the underlying `MuiMenuItem`'s `activeClassName` prop |
| `& .RaMenuItemLink-icon` | Applied to the `ListItemIcon` component when `leftIcon` prop is set |

To override the style of all instances of `<MenuItemLink>` using the [application-wide style overrides](./AppTheme.md#theming-individual-components), use the `RaMenuItemLink` key.

**Tip**: The `<Menu.Item>` component makes use of the React Router [NavLink](https://reactrouter.com/docs/en/v6/components/nav-link) component, hence allowing to customize the active menu style. For instance, here is how to use a custom theme to show a left border for the active menu:

Expand Down Expand Up @@ -260,15 +307,6 @@ export const theme = {
};
```

You can use the `sx` prop to customize the style of the component.

| Rule name | Description |
|-----------------------------|---------------------------------------------------------------------|
| `&.RaMenuItemLink-active` | Applied to the underlying `MuiMenuItem`'s `activeClassName` prop |
| `& .RaMenuItemLink-icon` | Applied to the `ListItemIcon` component when `leftIcon` prop is set |

To override the style of all instances of `<MenuItemLink>` using the [application-wide style overrides](./AppTheme.md#theming-individual-components), use the `RaMenuItemLink` key.

## `<Menu.DashboardItem>`

The `<Menu.DashboardItem>` component displays a menu item for the dashboard.
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ module.exports = {
'/packages/create-react-admin/templates',
],
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\](?!(@hookform)/).+\\.(js|jsx|mjs|ts|tsx)$',
'[/\\\\]node_modules[/\\\\](?!(@hookform|react-hotkeys-hook)/).+\\.(js|jsx|mjs|ts|tsx)$',
],
transform: {
// '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
Expand Down
1 change: 1 addition & 0 deletions packages/ra-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"lodash": "^4.17.21",
"query-string": "^7.1.3",
"react-error-boundary": "^4.0.13",
"react-hotkeys-hook": "^5.1.0",
"react-is": "^18.2.0 || ^19.0.0"
},
"gitHead": "587df4c27bfcec4a756df4f95e5fc14728dfc0d7"
Expand Down
19 changes: 19 additions & 0 deletions packages/ra-core/src/util/KeyboardShortcut.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
type HotkeyCallback,
type Keys,
type Options,
useHotkeys,
} from 'react-hotkeys-hook';

export const KeyboardShortcut = (props: KeyboardShortcutProps) => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

please add jsDoc to explain why we need that (to add a keyboard shortcut conditionally? I so, why don't we use the "enabled" option?)

const { callback, dependencies, keys, options } = props;
useHotkeys(keys, callback, options, dependencies);
return null;
};

export interface KeyboardShortcutProps {
keys: Keys;
callback: HotkeyCallback;
options?: Options;
dependencies?: readonly unknown[];
}
10 changes: 10 additions & 0 deletions packages/ra-core/src/util/getKeyboardShortcutLabel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Keys } from 'react-hotkeys-hook';

export const getKeyboardShortcutLabel = (keyboardShortcut: Keys) => {
if (typeof keyboardShortcut === 'string') {
return keyboardShortcut.split('+').join(' + ');
}
return keyboardShortcut
.map(shortcut => getKeyboardShortcutLabel(shortcut))
.join(', ');
};
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a bit short, we'd need to be smarter than that and show icons for key modifiers dependent on the platform (e.g. command / windows)

2 changes: 2 additions & 0 deletions packages/ra-core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ export * from './asyncDebounce';
export * from './hooks';
export * from './shallowEqual';
export * from './useCheckForApplicationUpdate';
export * from './getKeyboardShortcutLabel';
export * from './KeyboardShortcut';
6 changes: 3 additions & 3 deletions packages/ra-ui-materialui/src/layout/DashboardMenuItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react';
import DashboardIcon from '@mui/icons-material/Dashboard';
import { To } from 'react-router';
import { useBasename } from 'ra-core';

import { MenuItemLink, MenuItemLinkProps } from './MenuItemLink';
Expand All @@ -24,8 +23,9 @@ export const DashboardMenuItem = (props: DashboardMenuItemProps) => {
);
};

export interface DashboardMenuItemProps extends Omit<MenuItemLinkProps, 'to'> {
to?: To;
export interface DashboardMenuItemProps
extends Omit<MenuItemLinkProps, 'to'>,
Partial<Pick<MenuItemLinkProps, 'to'>> {
/**
* @deprecated
*/
Expand Down
59 changes: 59 additions & 0 deletions packages/ra-ui-materialui/src/layout/Menu.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { Default, WithDashboard, WithKeyboardShortcuts } from './Menu.stories';

describe('<Menu>', () => {
it('should render a default menu with items for all registered resources', async () => {
render(<Default />);
await screen.findByText('Posts', { selector: '[role="menuitem"]' });
await screen.findByText('Comments', { selector: '[role="menuitem"]' });
await screen.findByText('Tags', { selector: '[role="menuitem"]' });
await screen.findByText('Users', { selector: '[role="menuitem"]' });
await screen.findByText('Orders', { selector: '[role="menuitem"]' });
await screen.findByText('Reviews', { selector: '[role="menuitem"]' });
});

it('should render a default menu with items for all registered resources and the dashboard', async () => {
render(<WithDashboard />);
await screen.findByText('Dashboard', { selector: '[role="menuitem"]' });
await screen.findByText('Posts', { selector: '[role="menuitem"]' });
await screen.findByText('Comments', { selector: '[role="menuitem"]' });
await screen.findByText('Tags', { selector: '[role="menuitem"]' });
await screen.findByText('Users', { selector: '[role="menuitem"]' });
await screen.findByText('Orders', { selector: '[role="menuitem"]' });
await screen.findByText('Reviews', { selector: '[role="menuitem"]' });
});

it('should support keyboard shortcuts', async () => {
render(<WithKeyboardShortcuts />);
await screen.findByText('Dashboard', { selector: '[role="menuitem"]' });
fireEvent.keyDown(global.document, {
key: 'c',
code: 'KeyC',
ctrlKey: true,
altKey: true,
});
expect(await screen.findAllByText('Customers')).toHaveLength(2);
fireEvent.keyDown(global.document, {
key: 's',
code: 'KeyS',
ctrlKey: true,
altKey: true,
});
expect(await screen.findAllByText('Sales')).toHaveLength(2);
fireEvent.keyDown(global.document, {
key: 'p',
code: 'KeyP',
ctrlKey: true,
altKey: true,
});
expect(await screen.findAllByText('Products')).toHaveLength(2);
fireEvent.keyDown(global.document, {
key: 'd',
code: 'KeyD',
ctrlKey: true,
altKey: true,
});
expect(await screen.findAllByText('Dashboard')).toHaveLength(2);
});
});
73 changes: 73 additions & 0 deletions packages/ra-ui-materialui/src/layout/Menu.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ export const Default = () => {
);
};

export const WithDashboard = () => {
const MenuDefault = () => <Menu hasDashboard={true} dense={false} />;
const DefaultLayout = ({ children }) => (
<Layout menu={MenuDefault}>{children}</Layout>
);
const Dashboard = () => <Page title="Dashboard" />;

return (
<Admin
store={memoryStore()}
dataProvider={testDataProvider()}
layout={DefaultLayout}
dashboard={Dashboard}
>
{resources.map((resource, index) => (
<Resource
name={resource}
key={`resource_${index}`}
list={<DemoList name={resource} />}
/>
))}
</Admin>
);
};

export const Dense = () => {
const MenuDense = () => <Menu hasDashboard={true} dense={true} />;
const LayoutDense = ({ children }) => (
Expand Down Expand Up @@ -135,6 +160,54 @@ export const Custom = () => {
);
};

export const WithKeyboardShortcuts = () => {
const CustomMenu = () => (
<Menu>
<Menu.DashboardItem keyboardShortcut="ctrl+alt+D" />
<Menu.Item
to="/sales"
leftIcon={<PieChartOutlined />}
primaryText="Sales"
keyboardShortcut="ctrl+alt+S"
/>
<Menu.Item
to="/customers"
leftIcon={<PeopleOutlined />}
primaryText="Customers"
keyboardShortcut="ctrl+alt+C"
/>
<Menu.ResourceItem
name="products"
leftIcon={<Inventory />}
keyboardShortcut="ctrl+alt+P"
/>
</Menu>
);
const CustomLayout = ({ children }) => (
<Layout menu={CustomMenu}>{children}</Layout>
);

const Dashboard = () => <Page title="Dashboard" />;
return (
<TestMemoryRouter initialEntries={['/']}>
<Admin
dataProvider={testDataProvider()}
layout={CustomLayout}
dashboard={Dashboard}
>
<Resource name="products" list={<Page title="Products" />} />
<CustomRoutes>
<Route path="/sales" element={<Page title="Sales" />} />
<Route
path="/customers"
element={<Page title="Customers" />}
/>
</CustomRoutes>
</Admin>
</TestMemoryRouter>
);
};

const Page = ({ title }) => (
<>
<Typography variant="h5" mt={2}>
Expand Down
7 changes: 6 additions & 1 deletion packages/ra-ui-materialui/src/layout/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ export const Menu = (inProps: MenuProps) => {
props: inProps,
name: PREFIX,
});
const { children, className, ...rest } = props;
const {
children,
className,
hasDashboard: hasDashboardProp,
...rest
} = props;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If you just want to discard hasDashboard, what about using _ instead of hasDashboardProp?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's how we usually do it

const hasDashboard = useHasDashboard();
const [open] = useSidebarState();

Expand Down
Loading
Loading