Skip to content

feat: New Actions #768

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 2 commits into
base: feature
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
59 changes: 59 additions & 0 deletions components/actions/ActionMenu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { EllipsisOutlined } from '@ant-design/icons';
import { Dropdown, MenuProps } from 'antd';
import React from 'react';
import { ActionsProps } from '.';
import { useXProviderContext } from '../x-provider';
import { ActionItemType, ItemType } from './interface';

export const findItem = (keyPath: string[], items: ActionItemType[]): ActionItemType | null => {
const keyToFind = keyPath[0]; // Get the first key from the keyPath

for (const item of items) {
if (item.key === keyToFind) {
// If the item is found and this is the last key in the path
if (keyPath.length === 1) return item;

// If it is a SubItemType, recurse to find in its children
if ('children' in item) {
return findItem(keyPath.slice(1), item.children!);
}
}
}

return null;
};

const ActionMenu = (props: { item: ItemType } & Pick<ActionsProps, 'prefixCls' | 'onClick'>) => {
const { onClick: onMenuClick, item } = props;
const { children = [], triggerSubMenuAction = 'hover' } = item;
const { getPrefixCls } = useXProviderContext();
const prefixCls = getPrefixCls('actions', props.prefixCls);
const icon = item?.icon ?? <EllipsisOutlined />;

const menuProps: MenuProps = {
items: children,
onClick: ({ key, keyPath, domEvent }) => {
onMenuClick?.({

Check warning on line 36 in components/actions/ActionMenu.tsx

View check run for this annotation

Codecov / codecov/patch

components/actions/ActionMenu.tsx#L35-L36

Added lines #L35 - L36 were not covered by tests
key,
keyPath: [...keyPath, item.key],
domEvent,
item: findItem(keyPath, children)!,

Choose a reason for hiding this comment

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

The findItem function assumes that children is always defined when it exists in an item. Consider adding a check to ensure children is not undefined before accessing it to prevent potential runtime errors.

});
},
};

return (
<Dropdown
menu={menuProps}
overlayClassName={`${prefixCls}-sub-item`}
arrow
trigger={[triggerSubMenuAction]}
>
<div className={`${prefixCls}-list-item`}>
<div className={`${prefixCls}-list-item-icon`}>{icon}</div>
</div>
</Dropdown>
);
};

export default ActionMenu;
42 changes: 42 additions & 0 deletions components/actions/__tests__/actionMenu.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { findItem } from '../ActionMenu';
import { ItemType } from '../interface';

describe('findItem function', () => {
const items: ItemType[] = [
{ key: '1', label: 'Action 1' },
{
key: '2',
label: 'Action 2',
children: [
{ key: '2-1', label: 'Sub Action 1' },
{ key: '2-2', label: 'Sub Action 2' },
],
},
{ key: '3', label: 'Action 3' },
];

it('should return the item if it exists at the root level', () => {
const result = findItem(['1'], items);
expect(result).toEqual(items[0]);
});

it('should return the item if it exists at a deeper level', () => {
const result = findItem(['2', '2-1'], items);
expect(result).toEqual(items[1].children![0]);
});

it('should return null if the item does not exist', () => {
const result = findItem(['4'], items);
expect(result).toBeNull();
});

it('should return null when searching a non-existent sub-item', () => {
const result = findItem(['2', '2-3'], items);
expect(result).toBeNull();
});

it('should handle an empty keyPath gracefully', () => {
const result = findItem([], items);
expect(result).toBeNull();
});
});
55 changes: 55 additions & 0 deletions components/actions/__tests__/actions.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import React from 'react';
import Actions, { ActionsProps } from '../index'; // Adjust the import according to your file structure

describe('Actions Component', () => {
const consoleSpy = jest.spyOn(console, 'log'); // 监视 console.log
const mockOnClick = jest.fn();
const items = [
{ key: '1', label: 'Action 1', icon: <span>icon1</span> },
{
key: '2',
label: 'Action 2',
icon: <span>icon2</span>,
onClick: () => console.log('Action 2 clicked'),
},
{
key: 'sub',
children: [{ key: 'sub-1', label: 'Sub Action 1', icon: <span>⚙️</span> }],
},
];

it('renders correctly', () => {
const { getByText } = render(<Actions items={items} onClick={mockOnClick} />);

expect(getByText('icon1')).toBeInTheDocument();
expect(getByText('icon2')).toBeInTheDocument();
});

it('calls onClick when an action item is clicked', () => {
const onClick: ActionsProps['onClick'] = ({ keyPath }) => {
console.log(`You clicked ${keyPath.join(',')}`);
};
const { getByText } = render(<Actions items={items} onClick={onClick} />);

fireEvent.click(getByText('icon1'));
expect(consoleSpy).toHaveBeenCalledWith('You clicked 1');
});

it('calls individual item onClick if provided', () => {
const consoleSpy = jest.spyOn(console, 'log');
const { getByText } = render(<Actions items={items} onClick={mockOnClick} />);

fireEvent.click(getByText('icon2'));
expect(consoleSpy).toHaveBeenCalledWith('Action 2 clicked');
consoleSpy.mockRestore();
});

it('renders sub-menu items', async () => {
const { getByText, container } = render(<Actions items={items} onClick={mockOnClick} />);

fireEvent.mouseOver(container.querySelector('.ant-dropdown-trigger')!); // Assuming the dropdown opens on hover

await waitFor(() => expect(getByText('Sub Action 1')).toBeInTheDocument());
});
});
7 changes: 7 additions & 0 deletions components/actions/demo/basic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## zh-CN

基础用法。

## en-US

Basic usage.
27 changes: 27 additions & 0 deletions components/actions/demo/basic.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CopyOutlined, RedoOutlined } from '@ant-design/icons';
import { Actions, ActionsProps } from '@ant-design/x';
import { message } from 'antd';
import React from 'react';

const actionItems = [
{
key: 'retry',
icon: <RedoOutlined />,
label: 'Retry',
},
{
key: 'copy',
icon: <CopyOutlined />,
label: 'Copy',
},
];

const Demo = () => {
const onClick: ActionsProps['onClick'] = ({ keyPath }) => {
// Logic for handling click events
message.success(`you clicked ${keyPath.join(',')}`);
};
return <Actions items={actionItems} onClick={onClick} />;
};

export default Demo;
7 changes: 7 additions & 0 deletions components/actions/demo/sub.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## zh-CN

更多菜单项。

## en-US

More menu items.
65 changes: 65 additions & 0 deletions components/actions/demo/sub.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { CopyOutlined, DeleteOutlined, RedoOutlined, ShareAltOutlined } from '@ant-design/icons';
import { Actions, ActionsProps } from '@ant-design/x';
import { Modal, message } from 'antd';
import React from 'react';

const actionItems: ActionsProps['items'] = [
{
key: 'retry',
label: 'Retry',
icon: <RedoOutlined />,
},
{
key: 'copy',
label: 'Copy',
icon: <CopyOutlined />,
},
{
key: 'more',
children: [
{
key: 'share',
label: 'Share',
icon: <ShareAltOutlined />,
children: [
{ key: 'qq', label: 'QQ' },
{ key: 'wechat', label: 'WeChat' },
],
},
{ key: 'import', label: 'Import' },
{
key: 'delete',
label: 'Delete',
icon: <DeleteOutlined />,
onClick: () => {
Modal.confirm({
title: 'Are you sure want to delete?',
content: 'Some descriptions',
onOk() {
message.success('Delete successfully');
},
onCancel() {
message.info('Cancel');
},
});
},
danger: true,
},
],
},
{
key: 'clear',
label: 'Clear',
icon: <DeleteOutlined />,
},
];

const Demo: React.FC = () => {
const onClick: ActionsProps['onClick'] = ({ keyPath }) => {
// Logic for handling click events
message.success(`you clicked ${keyPath.join(',')}`);
};
return <Actions items={actionItems} onClick={onClick} />;
};

export default Demo;
7 changes: 7 additions & 0 deletions components/actions/demo/variant.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## zh-CN

使用`variant`切换变体。

## en-US

Use `variant` to switch variants.
27 changes: 27 additions & 0 deletions components/actions/demo/variant.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CopyOutlined, RedoOutlined } from '@ant-design/icons';
import { Actions, ActionsProps } from '@ant-design/x';
import { message } from 'antd';
import React from 'react';

const actionItems = [
{
key: 'retry',
icon: <RedoOutlined />,
label: 'Retry',
},
{
key: 'copy',
icon: <CopyOutlined />,
label: 'Copy',
},
];

const Demo: React.FC = () => {
const onClick: ActionsProps['onClick'] = ({ keyPath }) => {
// Logic for handling click events
message.success(`you clicked ${keyPath.join(',')}`);
};
return <Actions items={actionItems} onClick={onClick} variant="border" />;
};

export default Demo;
63 changes: 63 additions & 0 deletions components/actions/index.en-US.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
category: Components
group:
title: Common
order: 0
title: Actions
description: Used for quickly configuring required action buttons or features in some AI scenarios.
cover: https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*1ysXSqEnAckAAAAAAAAAAAAADgCCAQ/original
coverDark: https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*EkYUTotf-eYAAAAAAAAAAAAADgCCAQ/original
demo:
cols: 1
---

## When to Use

The Actions component is used for quickly configuring required action buttons or features in some AI scenarios.

## Examples

<!-- prettier-ignore -->
<code src="./demo/basic.tsx">Basic</code>
<code src="./demo/sub.tsx">More Menu Items</code>
<code src="./demo/variant.tsx">Using Variants</code>

## API

Common props ref:[Common props](/docs/react/common-props)

### Actions

| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| items | A list containing multiple action items | ActionItemType[] | - | - |
| rootClassName | Style class for the root node | string | - | - |
| onClick | Callback function when an action item is clicked | `function({ item, key, keyPath, selectedKeys, domEvent })` | - | - |
| style | Style for the root node | React.CSSProperties | - | - |
| variant | Variant | `'borderless' \| 'border'` | 'borderless' | - |
| prefixCls | Prefix for style class names | string | - | - |

### ItemType

| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| key | The unique identifier for the custom action | string | - | - |
| label | The display label for the custom action | string | - | - |
| icon | The icon for the custom action | ReactNode | - | - |
| children | Sub action items | ActionItemType[] | - | - |
| triggerSubMenuAction | Action to trigger the sub-menu | `hover \| click` | - | - |
| onClick | Callback function when the custom action button is clicked | () => void | - | - |

### SubItemType

| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| label | The display label for the custom action | string | - | - |
| key | The unique identifier for the custom action | string | - | - |
| icon | The icon for the custom action | ReactNode | - | - |
| onClick | Callback function when the custom action button is clicked | () => void | - | - |
| danger | Syntax sugar, set dangerous icon | boolean | false | - |

### ActionItemType

> type `ActionItemType` = `ItemType` | `SubItemType`
Loading