689 lines
18 KiB
React
689 lines
18 KiB
React
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 { useTranslation } from 'react-i18next';
|
||
import { DATE_RANGE_PRESETS } from '../../constants/console.constants';
|
||
import '../common/table/table-filter-range.css';
|
||
import {
|
||
useConsoleControlSize,
|
||
useConsolePage,
|
||
} 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;
|
||
|
||
function useSettingsInputId(id) {
|
||
const generatedId = React.useId();
|
||
const isSettings = useConsolePage()?.page.key === 'setting';
|
||
return id ?? (isSettings ? generatedId : 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 isSettings = useConsolePage()?.page.key === 'setting';
|
||
const Component = mode === 'password' ? AntInput.Password : AntInput;
|
||
return (
|
||
<Component
|
||
{...props}
|
||
id={useSettingsInputId(props.id)}
|
||
autoComplete={
|
||
props.autoComplete ??
|
||
(isSettings
|
||
? mode === 'password' || props.type === 'password'
|
||
? 'new-password'
|
||
: 'off'
|
||
: undefined)
|
||
}
|
||
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}
|
||
id={useSettingsInputId(props.id)}
|
||
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}
|
||
id={useSettingsInputId(props.id)}
|
||
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,
|
||
tableFilter = false,
|
||
size,
|
||
inputReadOnly,
|
||
dropdownClassName,
|
||
dropdownStyle,
|
||
format,
|
||
...props
|
||
}) {
|
||
const { t } = useTranslation();
|
||
const range = type?.toLowerCase().includes('range');
|
||
const Component = range ? AntDatePicker.RangePicker : AntDatePicker;
|
||
const convert = (v) => (range ? (v || []).map(toDay) : toDay(v));
|
||
const withTime = type?.toLowerCase().includes('time');
|
||
const selected = tableFilter && range ? convert(value ?? defaultValue) : [];
|
||
const tablePresets =
|
||
tableFilter && range
|
||
? DATE_RANGE_PRESETS.map(({ text, start, end }) => {
|
||
const bounds = [start, end];
|
||
const active = bounds.every((get, index) =>
|
||
selected[index]?.isSame(dayjs(get()), withTime ? 'second' : 'day'),
|
||
);
|
||
return {
|
||
label: (
|
||
<span
|
||
className={active ? 'table-filter-period-active' : undefined}
|
||
>
|
||
{t(text)}
|
||
</span>
|
||
),
|
||
value: () => bounds.map((get) => dayjs(get())),
|
||
};
|
||
})
|
||
: undefined;
|
||
return (
|
||
<Component
|
||
{...props}
|
||
{...(tableFilter
|
||
? {
|
||
className: [props.className, 'table-filter-range']
|
||
.filter(Boolean)
|
||
.join(' '),
|
||
placeholder: [t('开始时间'), t('结束时间')],
|
||
popupAlign: {
|
||
offset: [0, 0],
|
||
...props.popupAlign,
|
||
overflow: {
|
||
adjustX: 1,
|
||
adjustY: 1,
|
||
shiftX: true,
|
||
shiftY: true,
|
||
...props.popupAlign?.overflow,
|
||
},
|
||
},
|
||
}
|
||
: {})}
|
||
{...(tableFilter
|
||
? { format: withTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD' }
|
||
: {})}
|
||
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
|
||
classNames={{
|
||
...props.classNames,
|
||
popup: {
|
||
...props.classNames?.popup,
|
||
root:
|
||
[
|
||
dropdownClassName ?? props.classNames?.popup?.root,
|
||
tableFilter && 'table-filter-range-popup',
|
||
]
|
||
.filter(Boolean)
|
||
.join(' ') || undefined,
|
||
},
|
||
}}
|
||
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(tableFilter ? 'middle' : size)}
|
||
allowClear={tableFilter || showClear}
|
||
showTime={withTime}
|
||
inputReadOnly={inputReadOnly}
|
||
disabledDate={disabledDate ? (d) => disabledDate(d.toDate()) : undefined}
|
||
presets={
|
||
tablePresets ??
|
||
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>
|
||
);
|
||
}
|