Files
monkey-ai-web/src/components/ui/index.jsx
T
2026-11-18 19:09:00 +08:00

958 lines
25 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { forwardRef } from 'react';
import * as Ant from 'antd';
import { controlSize, placement } from './controls';
import {
centerPaginationEvents,
centerPaginationOptions,
isCenterPaginationScope,
paginationEvents,
paginationShowTotal,
} from './pagination';
import { overlayMask } from './overlayPolicy';
import CenterTable from './CenterActionTable';
import './pagination.css';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useConsolePage } from '../console/ConsoleContext';
import { toConsoleTableChange } from '../console/consoleTableAdapter';
import {
ConsoleAlert,
ConsoleCard,
ConsoleDrawer,
ConsoleModal,
ConsoleTable,
ConsoleTabs,
} from '../console/ConsolePrimitives';
export * from './controls';
export { Form, withField } from './form';
export { Chat } from './chat';
export const { Checkbox, Col, Grid, List, Slider } = Ant;
export const Layout = Object.assign(
forwardRef(function Layout({ style, hasSider, ...props }, ref) {
return (
<Ant.Layout
{...props}
ref={ref}
style={style}
hasSider={style?.flexDirection === 'column' ? false : hasSider}
/>
);
}),
{
Header: Ant.Layout.Header,
Footer: Ant.Layout.Footer,
Sider: Ant.Layout.Sider,
Content: Ant.Layout.Content,
},
);
export const InputGroup = Ant.Space.Compact;
export const Row = ({ type, gutter, ...props }) => {
const isSettings = useConsolePage()?.page.key === 'setting';
return (
<Ant.Row
{...props}
gutter={isSettings ? [24, Array.isArray(gutter) ? gutter[1] : 0] : gutter}
/>
);
};
export const Icon = ({ svg, size, ...props }) => (
<span {...props} className={`anticon ${props.className || ''}`}>
{svg}
</span>
);
export const SplitButtonGroup = Ant.Space.Compact;
export const LocaleProvider = Ant.ConfigProvider;
const textType = (type) =>
['secondary', 'success', 'warning', 'danger'].includes(type)
? type
: ['tertiary', 'quaternary'].includes(type)
? 'secondary'
: undefined;
export const Typography = {
...Ant.Typography,
Text: ({ type, size, link, icon, children, ...props }) => {
const Component = link ? Ant.Typography.Link : Ant.Typography.Text;
return (
<Component {...props} type={textType(type)}>
{icon}
{children}
</Component>
);
},
Title: ({ heading = 4, ...props }) => (
<Ant.Typography.Title
{...props}
level={Math.min(5, Math.max(1, heading))}
/>
),
Paragraph: ({ type, ...props }) => (
<Ant.Typography.Paragraph {...props} type={textType(type)} />
),
};
export const Text = Typography.Text;
export const Card = forwardRef(function Card(
{
header,
headerExtraContent,
headerStyle,
bodyStyle,
footer,
shadows,
bordered,
size,
...props
},
ref,
) {
const Component = useConsolePage() ? ConsoleCard : Ant.Card;
return (
<Component
{...props}
ref={ref}
variant={
props.variant ?? (bordered === false ? 'borderless' : 'outlined')
}
size={size === 'small' ? 'small' : 'medium'}
title={
props.title ??
header?.title ??
(React.isValidElement(header) || typeof header === 'string'
? header
: undefined)
}
extra={headerExtraContent ?? header?.extra}
styles={{ header: headerStyle, body: bodyStyle, ...props.styles }}
>
{props.children}
{footer && <div className='ui-card-footer'>{footer}</div>}
</Component>
);
});
export const Space = ({ spacing, vertical, size, ...props }) => (
<Ant.Space
{...props}
orientation={vertical ? 'vertical' : 'horizontal'}
size={spacing === 'medium' ? 'middle' : (spacing ?? size)}
/>
);
export const Divider = ({ margin, align, layout, style, ...props }) => (
<Ant.Divider
{...props}
titlePlacement={align}
orientation={layout === 'vertical' ? 'vertical' : 'horizontal'}
style={{ margin, ...style }}
/>
);
export const Tag = forwardRef(function Tag(
{
size,
prefixIcon,
suffixIcon,
shape,
clickable,
type,
prefix,
children,
color,
bordered,
...props
},
ref,
) {
return (
<Ant.Tag
{...props}
ref={ref}
variant={props.variant ?? (bordered === false ? 'filled' : 'outlined')}
color={
['white', 'grey', 'light-blue', 'light-green'].includes(color)
? {
white: 'default',
grey: 'default',
'light-blue': 'blue',
'light-green': 'green',
}[color]
: color
}
icon={prefixIcon ?? props.icon}
>
{prefix}
{children}
{suffixIcon}
</Ant.Tag>
);
});
export const Avatar = Object.assign(
function Avatar({ color, size, shape, ...props }) {
const mapped = {
'extra-small': 20,
small: 24,
default: 32,
medium: 40,
large: 48,
'extra-large': 72,
};
return (
<Ant.Avatar
{...props}
size={mapped[size] || size}
shape={shape === 'square' ? 'square' : 'circle'}
/>
);
},
{ Group: Ant.Avatar.Group },
);
export const AvatarGroup = Ant.Avatar.Group;
export const Badge = ({ type, position, ...props }) => (
<Ant.Badge {...props} status={type === 'danger' ? 'error' : type} />
);
export const Spin = ({
size,
childStyle,
children,
style,
className,
'data-testid': testId,
tip,
wrapperClassName,
...props
}) =>
children ? (
<div
style={style}
className={`ui-spin-shell ${className || ''}`}
data-testid={testId}
>
<Ant.Spin
{...props}
description={tip ?? props.description}
classNames={{ root: wrapperClassName, ...props.classNames }}
size={size === 'default' ? 'medium' : size}
>
<div style={childStyle}>{children}</div>
</Ant.Spin>
</div>
) : (
<Ant.Spin
{...props}
size={size === 'default' ? 'medium' : size}
description={tip ?? props.description}
style={style}
className={className}
data-testid={testId}
/>
);
export const Empty = ({ title, darkModeImage, ...props }) => (
<Ant.Empty
{...props}
description={props.description ?? title}
image={props.image || Ant.Empty.PRESENTED_IMAGE_SIMPLE}
/>
);
export const Progress = ({ stroke, showText, type, size, ...props }) => (
<Ant.Progress
{...props}
type={type === 'circle' ? 'circle' : type}
strokeColor={stroke || props.strokeColor}
showInfo={showText ?? props.showInfo}
size={size === 'default' ? undefined : size}
/>
);
export function Table({
empty,
emptyText,
expandedRowRender,
rowExpandable,
expandedRowKeys,
onExpand,
expandRowByClick,
pagination,
size,
onChange,
...props
}) {
const consolePage = useConsolePage();
const BaseTable = consolePage ? ConsoleTable : CenterTable;
const unified = Boolean(pagination) && isCenterPaginationScope();
const Component = unified ? CenterPaginatedTable : BaseTable;
const expandable = expandedRowRender
? {
expandedRowRender,
rowExpandable,
expandedRowKeys,
onExpand,
expandRowByClick,
}
: undefined;
return (
<Component
{...props}
{...(unified
? { component: BaseTable, legacyPagination: pagination }
: {})}
size={controlSize(size)}
onChange={
consolePage && onChange
? (...args) => onChange(toConsoleTableChange(...args))
: onChange
}
locale={
empty !== undefined || emptyText !== undefined
? { emptyText: empty ?? emptyText }
: undefined
}
expandable={expandable}
pagination={
pagination === false
? false
: pagination
? {
...pagination,
current: pagination.currentPage ?? pagination.current,
pageSizeOptions:
pagination.pageSizeOpts ?? pagination.pageSizeOptions,
showTotal: paginationShowTotal(pagination.showTotal),
...paginationEvents(pagination),
}
: false
}
/>
);
}
function CenterPaginatedTable({
component: Component,
legacyPagination,
...props
}) {
const isMobile = useIsMobile();
const config = legacyPagination;
const local = config.total === undefined;
const [localPage, setLocalPage] = React.useState(config.currentPage ?? 1);
const [localSize, setLocalSize] = React.useState(config.pageSize ?? 10);
const pageSize =
local && !config.onPageSizeChange ? localSize : (config.pageSize ?? 10);
const total = config.total ?? props.dataSource?.length ?? 0;
const current = Math.min(
config.currentPage ?? config.current ?? localPage,
Math.max(1, Math.ceil(total / pageSize)),
);
const events = centerPaginationEvents({
...config,
pageSize,
...(local && !config.onPageSizeChange && !config.onShowSizeChange
? {
onPageSizeChange: (size) => {
config.onPageChange?.(1);
config.onChange?.(1, size);
},
}
: {}),
});
React.useEffect(() => {
const requested = config.currentPage ?? config.current;
if (!props.loading && requested !== undefined && requested > current) {
config.onPageChange?.(current);
config.onChange?.(current, pageSize);
}
}, [current, pageSize, props.loading, config]);
return (
<Component
{...props}
pagination={{
...centerPaginationOptions(config, isMobile),
showSizeChanger:
config.showSizeChanger ??
Boolean(
local ||
config.onPageSizeChange ||
config.onShowSizeChange ||
config.onChange,
),
current,
pageSize,
onShowSizeChange: undefined,
onChange: (page, size) => {
setLocalPage(size === pageSize ? page : 1);
setLocalSize(size);
events.onChange(page, size);
},
}}
/>
);
}
export function Pagination({
currentPage,
onPageChange,
pageSizeOpts,
onPageSizeChange,
preventPageChangeOnPageSizeChange,
size,
showTotal,
...props
}) {
const isMobile = useIsMobile();
const unified = isCenterPaginationScope();
const { onChange: onAntChange, pageSize: configuredSize = 10 } = props;
const config = {
...props,
currentPage,
onPageChange,
onPageSizeChange,
preventPageChangeOnPageSizeChange,
};
const requestedPage = currentPage ?? props.current;
const current =
unified && props.total !== undefined && requestedPage !== undefined
? Math.min(
requestedPage,
Math.max(1, Math.ceil(props.total / configuredSize)),
)
: requestedPage;
React.useEffect(() => {
if (unified && requestedPage !== undefined && requestedPage > current) {
onPageChange?.(current);
onAntChange?.(current, configuredSize);
}
}, [
unified,
requestedPage,
current,
onPageChange,
onAntChange,
configuredSize,
]);
return (
<Ant.Pagination
{...props}
current={current}
{...(unified ? centerPaginationEvents(config) : paginationEvents(config))}
pageSizeOptions={pageSizeOpts ?? props.pageSizeOptions}
size={size === 'small' ? 'small' : 'default'}
showTotal={paginationShowTotal(showTotal)}
{...(unified
? centerPaginationOptions({ className: props.className }, isMobile)
: {})}
/>
);
}
export const TabPane = ({ children }) => children;
export const Tabs = Object.assign(
function Tabs({
children,
tabList,
type,
size,
collapsible,
renderArrow,
lazyRender = false,
keepDOM = true,
...props
}) {
const Component = useConsolePage() ? ConsoleTabs : Ant.Tabs;
const items =
tabList?.map((tab) => ({ ...tab, key: tab.itemKey ?? tab.key })) ||
React.Children.toArray(children)
.filter(React.isValidElement)
.map((child) => ({
key: child.props.itemKey ?? child.key,
label: child.props.tab,
disabled: child.props.disabled,
children: child.props.children,
forceRender: lazyRender === false,
destroyOnHidden: keepDOM === false,
}));
return (
<Component
{...props}
size={controlSize(size)}
type={type === 'card' ? 'card' : 'line'}
items={items}
/>
);
},
{ TabPane },
);
export const Collapse = Object.assign(
function Collapse({ children, collapseIcon, items, ...props }) {
return (
<Ant.Collapse
{...props}
items={
items ||
React.Children.toArray(children)
.filter(React.isValidElement)
.map((child) => ({
key: child.props.itemKey ?? child.key,
label: child.props.header,
extra: child.props.extra,
children: child.props.children,
}))
}
/>
);
},
{ Panel: ({ children }) => children },
);
export const Collapsible = ({
isOpen,
keepDOM,
collapseHeight,
children,
style,
}) =>
!isOpen && !keepDOM ? null : (
<div
style={{ ...style, ...(!isOpen ? { display: 'none' } : {}) }}
aria-hidden={!isOpen}
>
{children}
</div>
);
export const Descriptions = Object.assign(
function Descriptions({ data, row, size, align, children, ...props }) {
const items =
data?.map((item, index) => ({
key: index,
label: item.key,
children: item.value,
})) ||
React.Children.toArray(children)
.filter(React.isValidElement)
.map((child, index) => ({
key: index,
label: child.props.itemKey,
children: child.props.children,
}));
return (
<Ant.Descriptions
{...props}
column={row ? undefined : 1}
layout={row ? 'vertical' : 'horizontal'}
size={controlSize(size)}
items={items}
/>
);
},
{ Item: ({ children }) => children },
);
export const Timeline = Object.assign(
function Timeline({ children, ...props }) {
return (
<Ant.Timeline
{...props}
items={React.Children.toArray(children)
.filter(React.isValidElement)
.map((child) => ({
color: child.props.type === 'ongoing' ? 'blue' : undefined,
title: child.props.time,
content: (
<>
{child.props.children}
{child.props.extra}
</>
),
}))}
/>
);
},
{ Item: ({ children }) => children },
);
export const Steps = Object.assign(
function Steps({ children, type, size, ...props }) {
return (
<Ant.Steps
{...props}
type={type === 'basic' ? 'default' : type}
size={controlSize(size)}
items={React.Children.toArray(children)
.filter(React.isValidElement)
.map((child) => child.props)}
/>
);
},
{ Step: ({ children }) => children },
);
export const Skeleton = Object.assign(
function Skeleton({ loading, active, placeholder, children, ...props }) {
return loading
? placeholder || <Ant.Skeleton {...props} active={active} />
: children;
},
{
...Ant.Skeleton,
Title: (props) => <Ant.Skeleton.Input {...props} active />,
Paragraph: ({ rows, ...props }) => (
<Ant.Skeleton {...props} paragraph={{ rows }} />
),
Image: Ant.Skeleton.Image,
Avatar: Ant.Skeleton.Avatar,
Button: Ant.Skeleton.Button,
},
);
export const Tooltip = ({ content, position, showArrow, ...props }) => (
<Ant.Tooltip
{...props}
title={content}
placement={placement(position)}
arrow={showArrow}
/>
);
export const Popover = ({ position, showArrow, ...props }) => (
<Ant.Popover {...props} placement={placement(position)} arrow={showArrow} />
);
export const Popconfirm = ({ content, position, okType, ...props }) => (
<Ant.Popconfirm
{...props}
description={content}
placement={placement(position)}
okButtonProps={{ danger: okType === 'danger' }}
/>
);
export const Banner = ({
type,
title,
fullMode,
bordered,
closeIcon,
children,
...props
}) => {
const Component = useConsolePage() ? ConsoleAlert : Ant.Alert;
return (
<Component
{...props}
title={title}
type={type === 'danger' ? 'error' : type}
showIcon
closable={!!closeIcon}
action={children}
/>
);
};
export const Alert = ({ message, ...props }) => {
const Component = useConsolePage() ? ConsoleAlert : Ant.Alert;
return <Component {...props} title={props.title ?? message} />;
};
function modalProps({
visible,
header,
closeOnEsc,
size,
keepDOM,
lazyRender,
motion,
okType,
type,
bodyStyle,
maskStyle,
mask,
maskClosable,
destroyOnClose,
...props
}) {
return {
...props,
mask: overlayMask(mask, maskClosable),
open: visible,
title: header === null ? null : (props.title ?? header),
keyboard: closeOnEsc,
forceRender: lazyRender === false,
destroyOnHidden:
keepDOM === false || destroyOnClose || props.destroyOnHidden,
width: size === 'full-width' ? '100%' : props.width,
okButtonProps: { danger: okType === 'danger', ...props.okButtonProps },
styles: { body: bodyStyle, mask: maskStyle, ...props.styles },
};
}
export const Modal = Object.assign(
function Modal(props) {
const Component = useConsolePage() ? ConsoleModal : Ant.Modal;
return <Component {...modalProps(props)} />;
},
{
destroyAll: Ant.Modal.destroyAll,
...Object.fromEntries(
['confirm', 'info', 'success', 'warning', 'error'].map((method) => [
method,
(config) => {
const { open, ...props } = modalProps(config);
return Ant.Modal[method](props);
},
]),
),
},
);
export const SideSheet = ({
visible,
onCancel,
closeOnEsc,
disableScroll,
bodyStyle,
headerStyle,
maskStyle,
destroyOnClose,
mask,
maskClosable,
width,
height,
...props
}) => {
const Component = useConsolePage() ? ConsoleDrawer : Ant.Drawer;
return (
<Component
{...props}
mask={overlayMask(mask, maskClosable)}
size={
props.size ??
(['top', 'bottom'].includes(props.placement) ? height : width)
}
open={visible}
onClose={onCancel}
keyboard={closeOnEsc}
destroyOnHidden={destroyOnClose ?? props.destroyOnHidden}
styles={{
body: bodyStyle,
header: headerStyle,
mask: maskStyle,
...props.styles,
}}
/>
);
};
export const Image = Ant.Image;
export const ImagePreview = ({
src,
visible,
onVisibleChange,
currentIndex,
onChange,
}) => (
<Ant.Image.PreviewGroup
items={Array.isArray(src) ? src : [src]}
preview={{
open: visible,
onOpenChange: onVisibleChange,
current: currentIndex,
onChange,
}}
/>
);
export const Toast = Object.fromEntries(
['success', 'info', 'warning', 'error', 'loading'].map((method) => [
method,
(content) =>
Ant.message[method](
typeof content === 'object' && !React.isValidElement(content)
? content
: { content },
),
]),
);
Toast.close = Ant.message.destroy;
Toast.destroyAll = Ant.message.destroy;
export const Notification = Object.fromEntries(
['success', 'info', 'warning', 'error', 'open'].map((method) => [
method,
({ title, message, content, description, btn, actions, ...config }) =>
Ant.notification[method]({
...config,
title: title ?? message,
description: content ?? description,
actions: actions ?? btn,
}),
]),
);
Notification.close = Ant.notification.destroy;
export function Highlight({ sourceString = '', searchWords = [], ...props }) {
const words = searchWords
.filter(Boolean)
.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
if (!words.length) return <span {...props}>{sourceString}</span>;
const re = new RegExp(`(${words.join('|')})`, 'gi');
return (
<span {...props}>
{sourceString
.split(re)
.map((part, index) =>
index % 2 ? <mark key={index}>{part}</mark> : part,
)}
</span>
);
}
function menuItems(children) {
return React.Children.toArray(children).flatMap((child, index) => {
if (!React.isValidElement(child)) return [];
if (child.type === DropdownDivider)
return [{ key: `divider-${index}`, type: 'divider' }];
if (child.type === DropdownItem)
return [
{
key: child.key || index,
label: child.props.children,
icon: child.props.icon,
disabled: child.props.disabled,
danger: child.props.type === 'danger',
className: child.props.className,
onClick: child.props.onClick,
},
];
if (child.type === React.Fragment || child.type === DropdownMenu)
return menuItems(child.props.children);
return [{ key: `content-${index}`, label: child, disabled: true }];
});
}
const DropdownItem = ({ children }) => children;
const DropdownMenu = ({ children }) => children;
const DropdownDivider = () => null;
export const Dropdown = Object.assign(
function Dropdown({
render,
position,
trigger,
visible,
onVisibleChange,
showTick,
clickToHide,
size,
onClickOutSide,
menu,
...props
}) {
return (
<Ant.Dropdown
{...props}
menu={
Array.isArray(menu)
? {
items: menu.map(({ node, name, type, ...item }, index) => ({
...item,
key: item.key ?? index,
label: item.label ?? name,
type: node === 'divider' ? 'divider' : undefined,
danger: item.danger ?? type === 'danger',
})),
}
: menu || { items: menuItems(render) }
}
placement={placement(position)}
trigger={[
trigger ||
(typeof window !== 'undefined' &&
window.matchMedia?.('(hover: none)').matches
? 'click'
: 'hover'),
]}
open={visible}
onOpenChange={onVisibleChange}
/>
);
},
{ Menu: DropdownMenu, Item: DropdownItem, Divider: DropdownDivider },
);
const NavItem = ({ children }) => children;
const NavSub = ({ children }) => children;
const NavGroup = ({ children }) => children;
export const Nav = Object.assign(
function Nav({
children,
isCollapsed,
defaultIsCollapsed,
onCollapseChange,
selectedKeys,
renderWrapper,
onSelect,
openKeys,
onOpenChange,
itemStyle,
hoverStyle,
selectedStyle,
...props
}) {
function items(nodes, prefix = '') {
return React.Children.toArray(nodes).flatMap((child, index) => {
if (!React.isValidElement(child)) return [];
const p = child.props;
if (child.type === NavGroup) {
const children = items(p.children, `${prefix}${p.itemKey}-`);
if (children.length === 0) return [];
// Collapsed menus keep their icon tooltips without group headings.
if (isCollapsed) return children;
return [
{
type: 'group',
key: p.itemKey,
label: p.text,
className: p.className,
children: p.folded ? [] : children,
},
];
}
if (child.type === NavItem || child.type === NavSub) {
const label = renderWrapper
? renderWrapper({ itemElement: <span>{p.text}</span>, props: p })
: p.text;
return [
{
key: p.itemKey,
label,
icon: p.icon,
className: p.className,
children:
child.type === NavSub
? items(p.children, `${prefix}${p.itemKey}-`)
: undefined,
},
];
}
if (child.type === Divider)
return [{ type: 'divider', key: `${prefix}divider-${index}` }];
return p.children ? items(p.children, `${prefix}${index}-`) : [];
});
}
return (
<Ant.Menu
{...props}
mode='inline'
inlineCollapsed={isCollapsed}
selectedKeys={selectedKeys}
openKeys={openKeys}
onOpenChange={(keys) => onOpenChange?.({ openKeys: keys })}
onSelect={(info) => onSelect?.({ ...info, itemKey: info.key })}
items={items(children)}
/>
);
},
{ Item: NavItem, Sub: NavSub, Group: NavGroup },
);