Files
monkey-ai-web/src/components/ui/controls.jsx
T
qiubaishen db3dba1e96 sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
2026-11-18 10:22:02 +08:00

630 lines
16 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 {
AutoComplete as AntAutoComplete,
Button as AntButton,
Cascader as AntCascader,
DatePicker as AntDatePicker,
Input as AntInput,
InputNumber as AntInputNumber,
Radio as AntRadio,
Select as AntSelect,
Switch as AntSwitch,
TimePicker as AntTimePicker,
Tag as AntTag,
TreeSelect as AntTreeSelect,
Upload as AntUpload,
message,
Space as AntSpace,
} from 'antd';
import dayjs from 'dayjs';
import { useConsoleControlSize } from '../console/ConsoleContext';
export const controlSize = (size) => (size === 'default' ? 'middle' : size);
export const placement = (position) =>
({
bottomLeft: 'bottomLeft',
bottomRight: 'bottomRight',
topLeft: 'topLeft',
topRight: 'topRight',
bottom: 'bottom',
top: 'top',
leftTop: 'leftTop',
rightTop: 'rightTop',
})[position] || position;
const statusOf = (status) =>
['error', 'warning'].includes(status) ? status : undefined;
// Existing screens consume values; DOM events stay inside this view boundary.
export const Input = forwardRef(function Input(
{
onChange,
onEnterPress,
showClear,
mode,
size,
validateStatus,
status,
readonly,
borderless,
...props
},
ref,
) {
const Component = mode === 'password' ? AntInput.Password : AntInput;
return (
<Component
{...props}
ref={ref}
size={useConsoleControlSize(size)}
readOnly={readonly ?? props.readOnly}
variant={borderless ? 'borderless' : undefined}
status={statusOf(validateStatus || status)}
allowClear={showClear ?? props.allowClear}
onPressEnter={onEnterPress}
onChange={(event) => onChange?.(event.target.value, event)}
/>
);
});
export const TextArea = forwardRef(function TextArea(
{ onChange, autosize, maxCount, showClear, validateStatus, ...props },
ref,
) {
return (
<AntInput.TextArea
{...props}
ref={ref}
autoSize={autosize}
maxLength={props.maxLength ?? maxCount}
allowClear={showClear}
status={statusOf(validateStatus)}
onChange={(event) => onChange?.(event.target.value, event)}
/>
);
});
Input.TextArea = TextArea;
Input.Password = AntInput.Password;
export const InputGroup = AntSpace.Compact;
export const Button = forwardRef(function Button(
{ theme, type, size, circle, iconPosition, ...props },
ref,
) {
const danger = props.danger || type === 'danger';
const buttonType =
theme === 'borderless'
? 'text'
: theme === 'solid'
? 'primary'
: theme === 'outline' || theme === 'light'
? 'default'
: type === 'primary'
? 'primary'
: ['link', 'text', 'dashed', 'default'].includes(type)
? type
: 'default';
return (
<AntButton
{...props}
ref={ref}
type={buttonType}
danger={danger}
size={useConsoleControlSize(size)}
shape={circle ? 'circle' : undefined}
iconPlacement={iconPosition === 'right' ? 'end' : 'start'}
/>
);
});
export const InputNumber = forwardRef(function InputNumber(
{
hideButtons,
innerButtons,
keepFocus,
suffix,
size,
validateStatus,
showClear,
onNumberChange,
onChange,
...props
},
ref,
) {
return (
<AntInputNumber
{...props}
ref={ref}
size={useConsoleControlSize(size)}
controls={!hideButtons}
suffix={suffix}
status={statusOf(validateStatus)}
onChange={(value) => {
onChange?.(value);
onNumberChange?.(value);
}}
/>
);
});
export function Select({
optionList,
options,
multiple,
filter,
searchable,
showClear,
allowCreate,
allowAdditions,
remote,
searchPosition,
search,
triggerRender,
renderOptionItem,
renderSelectedItem,
outerBottomSlot,
innerBottomSlot,
emptyContent,
onDropdownVisibleChange,
validateStatus,
selection,
size,
max,
additionLabel,
render,
prefix,
dropdownStyle,
dropdownClassName,
autoClearSearchValue,
onSearch,
searchValue,
filterSort,
...props
}) {
const canSearch =
remote || !!filter || searchable || search || allowCreate || allowAdditions;
return (
<AntSelect
{...props}
size={useConsoleControlSize(size)}
mode={
allowCreate || allowAdditions
? 'tags'
: multiple
? 'multiple'
: undefined
}
styles={{
...props.styles,
popup: {
...props.styles?.popup,
root: dropdownStyle ?? props.styles?.popup?.root,
},
}}
classNames={{
...props.classNames,
popup: {
...props.classNames?.popup,
root: dropdownClassName ?? props.classNames?.popup?.root,
},
}}
options={optionList || options}
allowClear={showClear ?? props.allowClear}
showSearch={{
enabled: canSearch,
filterOption: remote
? false
: typeof filter === 'function'
? filter
: filter === false
? false
: undefined,
optionFilterProp: 'label',
...(typeof props.showSearch === 'object' ? props.showSearch : {}),
...(autoClearSearchValue !== undefined ? { autoClearSearchValue } : {}),
...(onSearch !== undefined ? { onSearch } : {}),
...(searchValue !== undefined ? { searchValue } : {}),
...(filterSort !== undefined ? { filterSort } : {}),
}}
notFoundContent={emptyContent}
status={statusOf(validateStatus)}
onOpenChange={onDropdownVisibleChange ?? props.onOpenChange}
prefix={prefix}
popupRender={
outerBottomSlot || innerBottomSlot
? (menu) => (
<>
{menu}
{innerBottomSlot}
{outerBottomSlot}
</>
)
: undefined
}
optionRender={
renderOptionItem
? (option) =>
renderOptionItem({
...option.data,
label: option.label,
selected: multiple
? props.value?.includes(option.value)
: props.value === option.value,
onClick: () => {},
})
: undefined
}
labelRender={
renderSelectedItem && !multiple
? (item) => {
const result = renderSelectedItem(item, { onClose: () => {} });
return result?.content ?? result;
}
: undefined
}
tagRender={
renderSelectedItem && multiple
? ({ value, label, closable, onClose }) => {
const option = (optionList || options)?.find(
(item) => item.value === value,
) || { value, label };
const result = renderSelectedItem(option, { onClose });
if (result?.isRenderInTag === false) return result.content;
return (
<AntTag
closable={closable}
onClose={onClose}
onMouseDown={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
{result?.content ?? result}
</AntTag>
);
}
: undefined
}
/>
);
}
Select.Option = AntSelect.Option;
Select.OptGroup = AntSelect.OptGroup;
export const RadioGroup = forwardRef(function RadioGroup(
{ type, direction, size, buttonSize, children, ...props },
ref,
) {
const content =
type === 'button'
? React.Children.map(children, (child) =>
React.isValidElement(child) ? (
<AntRadio.Button {...child.props} />
) : (
child
),
)
: children;
return (
<AntRadio.Group
{...props}
ref={ref}
size={useConsoleControlSize(size || buttonSize)}
optionType={type === 'button' ? 'button' : 'default'}
className={[
props.className,
direction === 'vertical' ? 'ui-radio-vertical' : '',
]
.filter(Boolean)
.join(' ')}
>
{content}
</AntRadio.Group>
);
});
export const Radio = Object.assign(
function Radio({ extra, children, ...props }) {
return (
<AntRadio {...props}>
{children}
{extra && <div className='ui-field-help'>{extra}</div>}
</AntRadio>
);
},
{ Group: RadioGroup, Button: AntRadio.Button },
);
export function Switch({
checkedText,
uncheckedText,
size,
validateStatus,
...props
}) {
return (
<AntSwitch
{...props}
checkedChildren={checkedText}
unCheckedChildren={uncheckedText}
size={size === 'small' ? 'small' : 'medium'}
/>
);
}
const toDay = (value) => (value == null || value === '' ? null : dayjs(value));
const toDate = (value) =>
Array.isArray(value)
? value.map((v) => v?.toDate() ?? null)
: (value?.toDate() ?? null);
// Semi 契约:DatePicker / TimePicker 的 onChange 为 (Date | Date[], 文本 | 文本[])(onChangeWithDateFirst
// 默认 true),存量页面与 Form.DatePicker(取第一个参数为字段值)都按此编写;清空时 Date 为 null、文本为 ''。
// format 沿用 Semi 的 date-fns 记法(yyyy-MM-dd),在此转换为 dayjs 记法(YYYY-MM-DD)。
const toDayjsFormat = (format) =>
typeof format === 'string'
? format.replace(/y/g, 'Y').replace(/d/g, 'D')
: format;
export function DatePicker({
type,
value,
defaultValue,
onChange,
showClear,
disabledDate,
density,
presets,
size,
inputReadOnly,
dropdownClassName,
dropdownStyle,
format,
...props
}) {
const range = type?.toLowerCase().includes('range');
const Component = range ? AntDatePicker.RangePicker : AntDatePicker;
const convert = (v) => (range ? (v || []).map(toDay) : toDay(v));
return (
<Component
{...props}
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
classNames={{
...props.classNames,
popup: {
...props.classNames?.popup,
root: dropdownClassName ?? props.classNames?.popup?.root,
},
}}
styles={{
...props.styles,
popup: {
...props.styles?.popup,
root: dropdownStyle ?? props.styles?.popup?.root,
},
}}
{...(value !== undefined ? { value: convert(value) } : {})}
defaultValue={
defaultValue === undefined ? undefined : convert(defaultValue)
}
size={useConsoleControlSize(size)}
allowClear={showClear}
showTime={type?.toLowerCase().includes('time')}
inputReadOnly={inputReadOnly}
disabledDate={disabledDate ? (d) => disabledDate(d.toDate()) : undefined}
presets={presets?.map((p) => ({
label: p.label || p.text,
value: convert(p.value || (p.start && [p.start, p.end])),
}))}
onChange={(dates, strings) =>
onChange?.(dates ? toDate(dates) : null, dates ? strings : '')
}
/>
);
}
export function TimePicker({ value, onChange, format, ...props }) {
return (
<AntTimePicker
{...props}
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
value={toDay(value)}
onChange={(date, string) =>
onChange?.(date ? date.toDate() : null, date ? string : '')
}
/>
);
}
function treeNodes(nodes) {
return nodes?.map((n) => ({
...n,
title: n.label ?? n.title,
children: treeNodes(n.children),
}));
}
export function TreeSelect({
treeData,
showClear,
filterTreeNode,
expandAll,
showFilteredOnly,
...props
}) {
return (
<AntTreeSelect
{...props}
treeData={treeNodes(treeData)}
allowClear={showClear}
showSearch={{
enabled: !!filterTreeNode,
filterTreeNode:
typeof filterTreeNode === 'function' ? filterTreeNode : undefined,
treeNodeFilterProp: 'title',
...(typeof props.showSearch === 'object' ? props.showSearch : {}),
}}
treeDefaultExpandAll={expandAll}
/>
);
}
export function Cascader({
treeData,
showClear,
filterTreeNode,
searchPlaceholder,
displayProp,
leafOnly,
dropdownStyle,
...props
}) {
return (
<AntCascader
{...props}
styles={{ popup: { root: dropdownStyle } }}
options={treeData}
allowClear={showClear}
showSearch={!!filterTreeNode}
changeOnSelect={!leafOnly}
/>
);
}
export function AutoComplete({
data,
renderItem,
emptyContent,
onEnterPress,
onSearch,
showSearch,
size,
...props
}) {
return (
<AntAutoComplete
{...props}
showSearch={
onSearch
? { ...(typeof showSearch === 'object' ? showSearch : {}), onSearch }
: showSearch
}
options={data?.map((item) =>
typeof item === 'string' ? { value: item } : item,
)}
notFoundContent={emptyContent}
size={useConsoleControlSize(size)}
onKeyDown={(e) => {
if (e.key === 'Enter') onEnterPress?.(e);
}}
/>
);
}
export function TagInput({ addOnBlur, separator, showClear, ...props }) {
return (
<AntSelect
{...props}
mode='tags'
tokenSeparators={separator ? [separator].flat() : undefined}
allowClear={showClear}
/>
);
}
export function Upload({
draggable,
limit,
maxSize,
minSize,
dragMainText,
dragSubText,
dragIcon,
uploadTrigger,
customRequest,
beforeUpload,
onChange,
onSuccess,
onError,
onSizeError,
...props
}) {
const Component = draggable ? AntUpload.Dragger : AntUpload;
const fileForView = (f) => ({
...f,
name: f.name,
uid: f.uid,
fileInstance: f.originFileObj || f,
size: f.size,
});
return (
<Component
{...props}
maxCount={limit}
customRequest={
customRequest
? (request) =>
customRequest({
...request,
file: fileForView(request.file),
})
: undefined
}
beforeUpload={async (file, files) => {
if (
(maxSize != null && file.size > maxSize * 1024) ||
(minSize != null && file.size < minSize * 1024)
) {
if (onSizeError)
onSizeError(fileForView(file), files.map(fileForView));
else
message.error(
`${file.name}: ${maxSize != null ? `max ${maxSize} KB` : `min ${minSize} KB`}`,
);
return AntUpload.LIST_IGNORE;
}
const result = await beforeUpload?.({
file: fileForView(file),
fileList: files.map(fileForView),
});
if (result?.autoRemove || result?.shouldIgnore)
return AntUpload.LIST_IGNORE;
return uploadTrigger === 'custom' ||
result === false ||
result?.shouldUpload === false
? false
: result;
}}
onChange={(info) => {
const currentFile = fileForView(info.file);
const fileList = info.fileList.map(fileForView);
onChange?.({ ...info, currentFile, fileList });
if (info.file.status === 'done')
onSuccess?.(info.file.response, currentFile, fileList);
if (info.file.status === 'error')
onError?.(info.file.error, info.file.response, currentFile, fileList);
}}
>
{props.children ||
(draggable ? (
<>
<p>
{dragIcon}
{dragMainText}
</p>
<p className='ui-field-help'>{dragSubText}</p>
</>
) : null)}
</Component>
);
}