feat: 参考原型图 ui优化提交 个人端-用户中心 相关的页面

This commit is contained in:
zhanjunhao
2026-11-04 19:59:06 +08:00
parent 472e534fe1
commit e6c41e7587
576 changed files with 18075 additions and 18912 deletions
+258
View File
@@ -0,0 +1,258 @@
/*
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, { useEffect, useLayoutEffect, useMemo, useState } from 'react';
import { App, ConfigProvider, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import zhTW from 'antd/locale/zh_TW';
import enGB from 'antd/locale/en_GB';
import jaJP from 'antd/locale/ja_JP';
import koKR from 'antd/locale/ko_KR';
import viVN from 'antd/locale/vi_VN';
import thTH from 'antd/locale/th_TH';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/zh-tw';
import 'dayjs/locale/en-gb';
import 'dayjs/locale/ja';
import 'dayjs/locale/ko';
import 'dayjs/locale/vi';
import 'dayjs/locale/th';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { useActualTheme } from '../../context/Theme';
import { normalizeLanguage } from '../../i18n/language';
import { colord } from 'colord';
// 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。
const DAYJS_LOCALES = {
zh: 'zh-cn',
'zh-TW': 'zh-tw',
en: 'en-gb',
ja: 'ja',
ko: 'ko',
vi: 'vi',
th: 'th',
};
// 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、
// 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary,
// 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。
const PROTOTYPE_DARK_PRIMARY = '#d1963a';
const PROTOTYPE_DARK_SEED = '#f2ad41';
export const prototypeTheme = (dark) => ({
algorithm: (seed, map) => {
const derive =
dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
? {
...seed,
colorPrimary: PROTOTYPE_DARK_SEED,
colorInfo: PROTOTYPE_DARK_SEED,
}
: seed;
return {
...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map),
colorPrimary: seed.colorPrimary,
colorInfo: seed.colorInfo,
};
},
token: {
colorPrimary: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorBgLayout: dark ? '#11151c' : '#f4f6f9',
colorBgContainer: dark ? '#1b212b' : '#ffffff',
colorText: dark ? '#e6ebf3' : '#263247',
colorTextSecondary: dark ? '#8e9aaa' : '#7e8998',
colorBorderSecondary: dark ? '#2b333f' : '#e9edf2',
borderRadius: 8,
fontFamily: '"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif',
controlHeight: 34,
},
components: {
Layout: {
headerBg: dark ? '#1b212b' : '#ffffff',
siderBg: dark ? '#1b212b' : '#ffffff',
},
Menu: {
itemHeight: 42,
itemSelectedBg: dark ? '#382b1b' : '#fff3df',
itemSelectedColor: dark ? '#f2ad41' : '#a95d07',
},
Card: { headerFontSize: 15 },
Modal: { borderRadiusLG: 12 },
},
});
function TokenBridge() {
const { token } = theme.useToken();
useLayoutEffect(() => {
const values = {
'ui-color-white': '#fff',
'ui-color-black': '#000',
...Object.fromEntries(
[0, 1, 2, 3, 4].map((i) => [
`ui-color-bg-${i}`,
i === 0 ? token.colorBgLayout : token.colorBgContainer,
]),
),
...Object.fromEntries(
[
token.colorText,
token.colorTextSecondary,
token.colorTextTertiary,
token.colorTextQuaternary,
].map((v, i) => [`ui-color-text-${i}`, v]),
),
...Object.fromEntries(
[
token.colorFillQuaternary,
token.colorFillTertiary,
token.colorFillSecondary,
].map((v, i) => [`ui-color-fill-${i}`, v]),
),
'ui-color-border': token.colorBorder,
'ui-color-disabled-bg': token.colorBgContainerDisabled,
'ui-color-disabled-text': token.colorTextDisabled,
'ui-color-shadow': token.boxShadow,
'ui-color-link': token.colorLink,
'ui-color-link-hover': token.colorLinkHover,
'ui-color-focus-border': token.colorPrimary,
'ui-color-highlight-bg': token.colorPrimaryBg,
'ui-color-highlight': token.colorPrimaryText,
'ui-color-text': token.colorText,
'ui-color-border-light': token.colorBorderSecondary,
'ui-color-disabled-border': token.colorBorder,
'ui-color-tertiary': token.colorTextTertiary,
'ui-border-radius-small': `${token.borderRadiusSM}px`,
'ui-border-radius-medium': `${token.borderRadius}px`,
'ui-font-family-mono': token.fontFamilyCode,
};
const rgb = (color) => {
const { r, g, b } = colord(color).toRgb();
return `${r}, ${g}, ${b}`;
};
values['ui-color-primary-rgb'] = rgb(token.colorPrimary);
for (const name of [
'blue',
'green',
'purple',
'violet',
'grey',
'primary',
]) {
const color =
name === 'grey'
? token.colorTextSecondary
: name === 'primary'
? token.colorPrimary
: token[`${name === 'violet' ? 'purple' : name}6`];
values[`ui-${name}-5`] = rgb(color);
values[`ui-${name}-0`] = rgb(
name === 'grey' ? token.colorFillQuaternary : token.colorPrimaryBg,
);
values[`ui-${name}-1`] = rgb(
name === 'grey' ? token.colorFillTertiary : token.colorPrimaryBgHover,
);
}
for (const name of ['primary', 'info', 'success', 'warning', 'danger']) {
const antName =
name === 'danger' ? 'Error' : name[0].toUpperCase() + name.slice(1);
for (const [suffix, antSuffix] of Object.entries({
'': '',
'-hover': 'Hover',
'-active': 'Active',
'-disabled': 'Border',
'-light-default': 'Bg',
'-light-hover': 'BgHover',
'-light-active': 'Border',
}))
values[`ui-color-${name}${suffix}`] =
token[`color${antName}${antSuffix}`];
}
for (const [name, value] of Object.entries(values))
if (value != null) document.body.style.setProperty(`--${name}`, value);
}, [token]);
return null;
}
export default function UiThemeProvider({ children }) {
const dark = useActualTheme() === 'dark';
const { i18n } = useTranslation();
const { pathname } = useLocation();
const [revision, setRevision] = useState(0);
useEffect(() => {
const frame = requestAnimationFrame(() =>
setRevision((value) => value + 1),
);
return () => cancelAnimationFrame(frame);
}, [dark]);
useEffect(() => {
const update = () => setRevision((value) => value + 1);
window.addEventListener('theme-tokens-applied', update);
return () => window.removeEventListener('theme-tokens-applied', update);
}, []);
// Re-read the computed brand when the existing CSS theme is applied.
const config = useMemo(() => {
const result = prototypeTheme(dark);
// Keep existing configured brand previews and persistence in helpers/theme.js.
const brand = getComputedStyle(document.body)
.getPropertyValue('--brand-primary')
.trim();
if (brand) result.token.colorPrimary = brand;
return result;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dark, revision]);
const language = normalizeLanguage(i18n.language);
const locale =
{
zh: zhCN,
'zh-TW': zhTW,
en: enGB,
ja: jaJP,
ko: koKR,
vi: viVN,
th: thTH,
}[language] || zhCN;
// 日期面板的星期、月份名称来自 dayjs 全局语言,需与 Ant Design locale 保持一致。
dayjs.locale(DAYJS_LOCALES[language] || 'zh-cn');
useLayoutEffect(() => {
document.body.dataset.uiScope =
pathname.startsWith('/weyai/') || pathname.startsWith('/client/authorize')
? 'external'
: 'admin';
}, [pathname]);
useEffect(() => {
ConfigProvider.config({
holderRender: (nodes) => (
<ConfigProvider theme={config} locale={locale}>
{nodes}
</ConfigProvider>
),
});
}, [config, locale]);
return (
<ConfigProvider theme={config} locale={locale}>
<App>
<TokenBridge />
{children}
</App>
</ConfigProvider>
);
}
+36
View File
@@ -0,0 +1,36 @@
/*
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 { ThemeManager } from '@visactor/vchart';
let observer;
export function initVChartTheme({ isWatchingThemeSwitch = true } = {}) {
const update = () =>
ThemeManager.setCurrentTheme(
document.documentElement.classList.contains('dark') ? 'dark' : 'light',
);
update();
if (isWatchingThemeSwitch && !observer) {
observer = new MutationObserver(update);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
}
}
+153
View File
@@ -0,0 +1,153 @@
/*
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,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { Avatar, Button, Input, List } from 'antd';
import { Send, Square, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
// Only message presentation and the composer live here; the page owns all chat actions.
export const Chat = forwardRef(function Chat(
{
chats = [],
roleConfig = {},
chatBoxRenderConfig = {},
renderInputArea,
onMessageSend,
onClear,
onStopGenerator,
showClearContext,
showStopGenerate,
placeholder,
className = '',
style,
},
ref,
) {
const { t } = useTranslation();
const [value, setValue] = useState('');
const input = useRef(null);
const list = useRef(null);
useImperativeHandle(
ref,
() => ({
scrollToBottom: () =>
list.current?.lastElementChild?.scrollIntoView({ block: 'end' }),
focus: () => input.current?.focus(),
}),
[],
);
const generating = ['loading', 'incomplete'].includes(chats.at(-1)?.status);
const send = () => {
if (value.length === 0 || (showStopGenerate && generating)) return;
onMessageSend?.(value, []);
setValue('');
};
const nodes = {
inputNode: (
<Input.TextArea
ref={input}
value={value}
placeholder={placeholder}
autoSize={{ minRows: 1, maxRows: 8 }}
onChange={(e) => setValue(e.target.value)}
onPressEnter={(e) => {
if (!e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
send();
}
}}
/>
),
sendNode: (
<Button
type='primary'
aria-label={t('发送')}
disabled={value.length === 0 || (showStopGenerate && generating)}
icon={<Send size={16} />}
onClick={send}
/>
),
clearContextNode: showClearContext ? (
<Button
aria-label={t('清空对话')}
icon={<Trash2 size={16} />}
onClick={onClear}
/>
) : null,
stopGenerateNode:
showStopGenerate && generating ? (
<Button
aria-label={t('停止生成')}
icon={<Square size={16} />}
onClick={onStopGenerator}
/>
) : null,
};
return (
<div className={`ui-chat ${className}`} style={style}>
<div className='ui-chat-list' ref={list}>
<List
dataSource={chats}
split={false}
renderItem={(message) => (
<List.Item
key={message.id}
className={`ui-chat-message ui-chat-message-${message.role}`}
>
<Avatar src={roleConfig[message.role]?.avatar}>
{roleConfig[message.role]?.name?.slice?.(0, 1)}
</Avatar>
<div className='ui-chat-message-body'>
{chatBoxRenderConfig.renderChatBoxTitle?.({ message })}
{chatBoxRenderConfig.renderChatBoxContent?.({
message,
className: 'ui-chat-content',
}) ?? message.content}
{chatBoxRenderConfig.renderChatBoxAction?.({ message })}
</div>
</List.Item>
)}
/>
</div>
{nodes.stopGenerateNode && (
<div className='ui-chat-stop'>{nodes.stopGenerateNode}</div>
)}
<div className='ui-chat-input'>
{renderInputArea ? (
renderInputArea({
detailProps: { ...nodes, onClick: () => input.current?.focus() },
})
) : (
<>
{nodes.inputNode}
{nodes.clearContextNode}
{nodes.sendNode}
</>
)}
</div>
</div>
);
});
+576
View File
@@ -0,0 +1,576 @@
/*
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';
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={controlSize(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={controlSize(size)}
shape={circle ? 'circle' : undefined}
iconPosition={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={controlSize(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,
...props
}) {
const canSearch =
remote || !!filter || searchable || search || allowCreate || allowAdditions;
return (
<AntSelect
{...props}
size={controlSize(size)}
mode={
allowCreate || allowAdditions
? 'tags'
: multiple
? 'multiple'
: undefined
}
styles={{
...props.styles,
popup: { ...props.styles?.popup, root: dropdownStyle },
}}
classNames={{
...props.classNames,
popup: { ...props.classNames?.popup, root: dropdownClassName },
}}
options={optionList || options}
allowClear={showClear ?? props.allowClear}
showSearch={canSearch}
filterOption={
remote
? false
: typeof filter === 'function'
? filter
: filter === false
? false
: undefined
}
optionFilterProp='label'
notFoundContent={emptyContent}
status={statusOf(validateStatus)}
onOpenChange={onDropdownVisibleChange}
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={controlSize(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' : 'default'}
/>
);
}
const toDay = (value) => (value == null || value === '' ? null : dayjs(value));
const toDate = (value) =>
Array.isArray(value)
? value.map((v) => v?.toDate() ?? null)
: (value?.toDate() ?? null);
export function DatePicker({
type,
value,
defaultValue,
onChange,
showClear,
disabledDate,
density,
presets,
size,
inputReadOnly,
...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}
{...(value !== undefined ? { value: convert(value) } : {})}
defaultValue={
defaultValue === undefined ? undefined : convert(defaultValue)
}
size={controlSize(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 ? (range ? strings : strings) : '', toDate(dates))
}
/>
);
}
export function TimePicker({ value, onChange, ...props }) {
return (
<AntTimePicker
{...props}
value={toDay(value)}
onChange={(date, string) => onChange?.(string, date?.toDate())}
/>
);
}
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={!!filterTreeNode}
treeNodeFilterProp='title'
filterTreeNode={
typeof filterTreeNode === 'function' ? filterTreeNode : undefined
}
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,
size,
...props
}) {
return (
<AntAutoComplete
{...props}
options={data?.map((item) =>
typeof item === 'string' ? { value: item } : item,
)}
notFoundContent={emptyContent}
size={controlSize(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>
);
}
+321
View File
@@ -0,0 +1,321 @@
/*
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, {
createContext,
forwardRef,
useContext,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useReducer,
} from 'react';
import { Checkbox, Form as AntForm } from 'antd';
import * as Controls from './controls';
const FormContext = createContext(null);
const fieldPath = (field) =>
typeof field === 'string'
? field.replace(/\[(\d+)\]/g, '.$1').split('.')
: field;
export const Form = forwardRef(function Form(
{
initValues,
values,
onSubmit,
onSubmitFail,
onValueChange,
getFormApi,
children,
labelPosition,
labelWidth,
labelAlign,
layout,
allowEmpty,
trigger,
stopValidateWithError,
...props
},
ref,
) {
const [form] = AntForm.useForm();
const [, renderValues] = useReducer((value) => value + 1, 0);
const callbacks = useRef({ getFormApi, onValueChange });
callbacks.current = { getFormApi, onValueChange };
const api = useMemo(
() => ({
getValues: () => form.getFieldsValue(true),
getValue: (field) => form.getFieldValue(fieldPath(field)),
setValue: (field, value) => {
form.setFieldValue(fieldPath(field), value);
callbacks.current.onValueChange?.(form.getFieldsValue(true), {
[field]: value,
});
renderValues();
},
setValues: (next) => {
form.setFieldsValue(next);
callbacks.current.onValueChange?.(form.getFieldsValue(true), next);
renderValues();
},
reset: (fields) => {
form.resetFields(fields?.map?.(fieldPath));
callbacks.current.onValueChange?.(form.getFieldsValue(true));
renderValues();
},
validate: (fields) => form.validateFields(fields?.map?.(fieldPath)),
submitForm: () => form.submit(),
getFieldExist: (field) =>
form.getFieldInstance(fieldPath(field)) !== undefined,
}),
[form],
);
useImperativeHandle(ref, () => ({ formApi: api, ...api }), [api]);
useEffect(() => {
callbacks.current.getFormApi?.(api);
renderValues();
}, [api]);
useEffect(() => {
if (values) form.setFieldsValue(values);
}, [form, values]);
return (
<FormContext.Provider value={form}>
<AntForm
{...props}
form={form}
initialValues={initValues}
layout={
layout === 'horizontal' || labelPosition === 'left'
? 'horizontal'
: layout === 'inline'
? 'inline'
: 'vertical'
}
labelCol={labelWidth ? { flex: labelWidth } : undefined}
labelAlign={labelAlign}
onFinish={onSubmit}
onFinishFailed={onSubmitFail}
onValuesChange={(_, all) => {
callbacks.current.onValueChange?.(all);
renderValues();
}}
>
{typeof children === 'function'
? children({
formState: { values: form.getFieldsValue(true) },
formApi: api,
values: form.getFieldsValue(true),
})
: children}
</AntForm>
</FormContext.Provider>
);
});
function labelProps(label) {
return label &&
typeof label === 'object' &&
!React.isValidElement(label) &&
'text' in label
? { label: label.text, required: label.required, htmlFor: label.name }
: { label };
}
// Legacy Form.RadioGroup reports the selected value; standalone RadioGroup reports an event.
const FieldRadioGroup = forwardRef(function FieldRadioGroup(
{ onChange, ...props },
ref,
) {
return (
<Controls.RadioGroup
{...props}
ref={ref}
onChange={(event) => onChange?.(event.target.value, event)}
/>
);
});
export function withField(
Component,
{ valueKey = 'value', onKeyChangeFnName = 'onChange' } = {},
) {
const Field = forwardRef(function Field(
{
field,
label,
noLabel,
initValue,
rules,
validate,
required,
extraText,
helpText,
pure,
trigger,
stopValidateWithError,
validateStatus,
className,
style,
...props
},
ref,
) {
const form = useContext(FormContext);
const normalizedRules =
rules?.map((rule) => {
if (!rule.validator) return rule;
return {
...rule,
validator: (_, value) =>
new Promise((resolve, reject) => {
let settled = false;
const callback = (error) => {
if (settled) return;
settled = true;
error ? reject(new Error(error.message || error)) : resolve();
};
try {
const result = rule.validator(
rule,
value,
callback,
form?.getFieldsValue(true),
);
if (result?.then) result.then(() => callback(), callback);
else if (result === true) callback();
else if (
result === false ||
typeof result === 'string' ||
result instanceof Error
)
callback(result || rule.message || 'Invalid value');
} catch (error) {
callback(error);
}
}),
};
}) || [];
if (validate)
normalizedRules.push({
validator: async (_, value) => {
const error = await validate(value, form?.getFieldsValue(true));
if (error) throw new Error(String(error));
},
});
const control =
field === undefined && props.children && Component === Controls.Input ? (
props.children
) : (
<Component {...props} ref={ref} style={style} />
);
// Unnamed slots remain controlled by the page; named fields use Ant Form's store.
return (
<AntForm.Item
{...(noLabel ? {} : labelProps(label))}
name={field === undefined ? undefined : fieldPath(field)}
initialValue={initValue}
rules={normalizedRules}
required={required || labelProps(label).required}
valuePropName={valueKey}
trigger={onKeyChangeFnName}
validateTrigger={trigger === 'blur' ? 'onBlur' : 'onChange'}
getValueFromEvent={(...args) =>
valueKey === 'checked'
? (args[0]?.target?.checked ?? args[0])
: valueKey === 'fileList'
? args[0]?.fileList
: args[0]
}
extra={extraText}
help={helpText}
validateStatus={
validateStatus === 'default' ? undefined : validateStatus
}
className={className}
noStyle={pure}
>
{control}
</AntForm.Item>
);
});
Field.Option = Component.Option;
Field.OptGroup = Component.OptGroup;
return Field;
}
for (const name of [
'Input',
'TextArea',
'InputNumber',
'Select',
'DatePicker',
'TimePicker',
'RadioGroup',
'CheckboxGroup',
'TagInput',
'TreeSelect',
'AutoComplete',
'Upload',
]) {
const Component =
name === 'CheckboxGroup'
? Checkbox.Group
: name === 'RadioGroup'
? FieldRadioGroup
: Controls[name];
Form[name] = withField(Component);
}
Form.Switch = withField(Controls.Switch, { valueKey: 'checked' });
Form.Checkbox = withField(Checkbox, { valueKey: 'checked' });
Form.Upload = withField(Controls.Upload, { valueKey: 'fileList' });
Form.Slot = function Slot({ label, error, children, ...props }) {
return (
<AntForm.Item
{...props}
{...labelProps(label)}
validateStatus={error?.error ? 'error' : undefined}
help={
error?.error ? (
<span id={error.errorMessageId}>{error.error}</span>
) : undefined
}
>
{children}
</AntForm.Item>
);
};
Form.Section = function Section({ text, extraText, children, ...props }) {
return (
<section {...props}>
<h3 className='ui-form-section'>{text}</h3>
{extraText && <p className='ui-field-help'>{extraText}</p>}
{children}
</section>
);
};
Form.Label = function Label({ required, children, ...props }) {
return (
<label {...props}>
{required && <span className='ui-required'>*</span>}
{children}
</label>
);
};
+542
View File
@@ -0,0 +1,542 @@
/*
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 from 'react';
import * as Icons from 'lucide-react';
export const IconSearch = ({ size = 16, ...props }) => (
<Icons.Search
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconPlus = ({ size = 16, ...props }) => (
<Icons.Plus
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconRefresh = ({ size = 16, ...props }) => (
<Icons.RefreshCw
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconDelete = ({ size = 16, ...props }) => (
<Icons.Trash2
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconClose = ({ size = 16, ...props }) => (
<Icons.X
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconMail = ({ size = 16, ...props }) => (
<Icons.Mail
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconKey = ({ size = 16, ...props }) => (
<Icons.KeyRound
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconEdit = ({ size = 16, ...props }) => (
<Icons.Pencil
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconSave = ({ size = 16, ...props }) => (
<Icons.Save
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconLock = ({ size = 16, ...props }) => (
<Icons.LockKeyhole
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconCopy = ({ size = 16, ...props }) => (
<Icons.Copy
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconLink = ({ size = 16, ...props }) => (
<Icons.Link
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconUser = ({ size = 16, ...props }) => (
<Icons.User
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconChevronDown = ({ size = 16, ...props }) => (
<Icons.ChevronDown
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconAlertTriangle = ({ size = 16, ...props }) => (
<Icons.TriangleAlert
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconGithubLogo = ({ size = 16, ...props }) => (
<Icons.Github
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconEyeOpened = ({ size = 16, ...props }) => (
<Icons.Eye
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconChevronUp = ({ size = 16, ...props }) => (
<Icons.ChevronUp
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconCreditCard = ({ size = 16, ...props }) => (
<Icons.CreditCard
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconMore = ({ size = 16, ...props }) => (
<Icons.Ellipsis
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconFile = ({ size = 16, ...props }) => (
<Icons.File
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconShield = ({ size = 16, ...props }) => (
<Icons.Shield
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconCode = ({ size = 16, ...props }) => (
<Icons.Code
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconBolt = ({ size = 16, ...props }) => (
<Icons.Zap
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconFilter = ({ size = 16, ...props }) => (
<Icons.Filter
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconHelpCircle = ({ size = 16, ...props }) => (
<Icons.CircleHelp
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconGift = ({ size = 16, ...props }) => (
<Icons.Gift
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconEyeClosed = ({ size = 16, ...props }) => (
<Icons.EyeOff
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconPlayCircle = ({ size = 16, ...props }) => (
<Icons.CirclePlay
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconCheckCircleStroked = ({ size = 16, ...props }) => (
<Icons.CircleCheck
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconTreeTriangleDown = ({ size = 16, ...props }) => (
<Icons.ChevronDown
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconSetting = ({ size = 16, ...props }) => (
<Icons.Settings
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconLayers = ({ size = 16, ...props }) => (
<Icons.Layers
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconUserAdd = ({ size = 16, ...props }) => (
<Icons.UserPlus
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconPulse = ({ size = 16, ...props }) => (
<Icons.Activity
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconSend = ({ size = 16, ...props }) => (
<Icons.Send
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconVideo = ({ size = 16, ...props }) => (
<Icons.Video
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconActivity = ({ size = 16, ...props }) => (
<Icons.Activity
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconDownload = ({ size = 16, ...props }) => (
<Icons.Download
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconShieldStroked = ({ size = 16, ...props }) => (
<Icons.Shield
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconMinus = ({ size = 16, ...props }) => (
<Icons.Minus
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconMenu = ({ size = 16, ...props }) => (
<Icons.Menu
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconBell = ({ size = 16, ...props }) => (
<Icons.Bell
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconUpload = ({ size = 16, ...props }) => (
<Icons.Upload
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconHistory = ({ size = 16, ...props }) => (
<Icons.History
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconServer = ({ size = 16, ...props }) => (
<Icons.Server
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconGlobe = ({ size = 16, ...props }) => (
<Icons.Globe
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconBookmark = ({ size = 16, ...props }) => (
<Icons.Bookmark
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconInfoCircle = ({ size = 16, ...props }) => (
<Icons.Info
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconExternalOpen = ({ size = 16, ...props }) => (
<Icons.ExternalLink
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconUserGroup = ({ size = 16, ...props }) => (
<Icons.Users
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconMoneyExchangeStroked = ({ size = 16, ...props }) => (
<Icons.ArrowRightLeft
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconHistogram = ({ size = 16, ...props }) => (
<Icons.ChartColumn
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconStopwatchStroked = ({ size = 16, ...props }) => (
<Icons.Timer
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconTypograph = ({ size = 16, ...props }) => (
<Icons.Type
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconTickCircle = ({ size = 16, ...props }) => (
<Icons.CircleCheck
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconImage = ({ size = 16, ...props }) => (
<Icons.Image
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconAlertCircle = ({ size = 16, ...props }) => (
<Icons.CircleAlert
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconLineChart = ({ size = 16, ...props }) => (
<Icons.ChartLine
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconSaveStroked = ({ size = 16, ...props }) => (
<Icons.Save
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const Iconbolt = ({ size = 16, ...props }) => (
<Icons.Zap
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconClock = ({ size = 16, ...props }) => (
<Icons.Clock
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconTick = ({ size = 16, ...props }) => (
<Icons.Check
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconArrowRight = ({ size = 16, ...props }) => (
<Icons.ArrowRight
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
export const IconArticle = ({ size = 16, ...props }) => (
<Icons.FileText
{...props}
size={
{ small: 14, default: 16, large: 20, 'extra-large': 24 }[size] || size
}
/>
);
+740
View File
@@ -0,0 +1,740 @@
/*
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 { paginationEvents } from './pagination';
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, ...props }) => <Ant.Row {...props} />;
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,
) {
return (
<Ant.Card
{...props}
ref={ref}
variant={
props.variant ?? (bordered === false ? 'borderless' : 'outlined')
}
size={size === 'small' ? 'small' : 'default'}
title={
props.title ??
header?.title ??
(React.isValidElement(header) || typeof header === 'string'
? header
: undefined)
}
extra={headerExtraContent ?? header?.extra}
styles={{ header: headerStyle, body: bodyStyle }}
>
{props.children}
{footer && <div className='ui-card-footer'>{footer}</div>}
</Ant.Card>
);
});
export const Space = ({ spacing, vertical, size, ...props }) => (
<Ant.Space
{...props}
direction={vertical ? 'vertical' : 'horizontal'}
size={spacing ?? size}
/>
);
export const Divider = ({ margin, align, layout, style, ...props }) => (
<Ant.Divider
{...props}
orientation={align}
type={layout === 'vertical' ? 'vertical' : 'horizontal'}
style={{ margin, ...style }}
/>
);
export const Tag = ({
size,
prefixIcon,
suffixIcon,
shape,
clickable,
type,
prefix,
children,
color,
...props
}) => (
<Ant.Tag
{...props}
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,
...props
}) =>
children ? (
<div
style={style}
className={`ui-spin-shell ${className || ''}`}
data-testid={testId}
>
<Ant.Spin {...props} size={controlSize(size)}>
<div style={childStyle}>{children}</div>
</Ant.Spin>
</div>
) : (
<Ant.Spin
{...props}
size={controlSize(size)}
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,
...props
}) {
const expandable = expandedRowRender
? {
expandedRowRender,
rowExpandable,
expandedRowKeys,
onExpand,
expandRowByClick,
}
: undefined;
return (
<Ant.Table
{...props}
size={controlSize(size)}
locale={{ emptyText: empty ?? emptyText }}
expandable={expandable}
pagination={
pagination === false
? false
: pagination
? {
...pagination,
current: pagination.currentPage ?? pagination.current,
pageSizeOptions:
pagination.pageSizeOpts ?? pagination.pageSizeOptions,
...paginationEvents(pagination),
}
: false
}
/>
);
}
export function Pagination({
currentPage,
onPageChange,
pageSizeOpts,
onPageSizeChange,
preventPageChangeOnPageSizeChange,
size,
showTotal,
...props
}) {
return (
<Ant.Pagination
{...props}
current={currentPage ?? props.current}
{...paginationEvents({
...props,
currentPage,
onPageChange,
onPageSizeChange,
preventPageChangeOnPageSizeChange,
})}
pageSizeOptions={pageSizeOpts ?? props.pageSizeOptions}
size={size === 'small' ? 'small' : 'default'}
showTotal={showTotal === true ? (total) => `${total}` : showTotal}
/>
);
}
export const TabPane = ({ children }) => children;
export const Tabs = Object.assign(
function Tabs({
children,
tabList,
type,
size,
collapsible,
renderArrow,
lazyRender = false,
keepDOM = true,
...props
}) {
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 (
<Ant.Tabs
{...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,
label: child.props.time,
children: (
<>
{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
}) => (
<Ant.Alert
{...props}
message={title}
type={type === 'danger' ? 'error' : type}
showIcon
closable={!!closeIcon}
action={children}
/>
);
export const Alert = Ant.Alert;
function modalProps({
visible,
header,
closeOnEsc,
size,
keepDOM,
lazyRender,
motion,
okType,
type,
bodyStyle,
maskStyle,
destroyOnClose,
...props
}) {
return {
...props,
open: visible,
title: header === null ? null : (props.title ?? header),
keyboard: closeOnEsc,
forceRender: lazyRender === false,
destroyOnHidden: keepDOM === false || destroyOnClose,
width: size === 'full-width' ? '100%' : props.width,
okButtonProps: { danger: okType === 'danger', ...props.okButtonProps },
styles: { body: bodyStyle, mask: maskStyle },
};
}
export const Modal = Object.assign(
function Modal(props) {
return <Ant.Modal {...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,
...props
}) => (
<Ant.Drawer
{...props}
open={visible}
onClose={onCancel}
keyboard={closeOnEsc}
destroyOnHidden={destroyOnClose}
styles={{ body: bodyStyle, header: headerStyle, mask: maskStyle }}
/>
);
export const Image = Ant.Image;
export const ImagePreview = ({
src,
visible,
onVisibleChange,
currentIndex,
onChange,
}) => (
<Ant.Image.PreviewGroup
items={Array.isArray(src) ? src : [src]}
preview={{ visible, 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,
(config) =>
Ant.notification[method]({
...config,
message: config.title ?? config.message,
description: config.content ?? config.description,
}),
]),
);
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={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;
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 === 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 },
);
+48
View File
@@ -0,0 +1,48 @@
/*
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
*/
// Preserve the existing callback sequence while Ant Design owns presentation.
export function paginationEvents({
currentPage,
current,
pageSize = 10,
onPageChange,
onChange,
onPageSizeChange,
onShowSizeChange,
preventPageChangeOnPageSizeChange = false,
}) {
const page = currentPage ?? current ?? 1;
return {
onChange(nextPage, nextSize) {
if (nextSize !== pageSize) return;
if (nextPage !== page) onPageChange?.(nextPage);
onChange?.(nextPage, nextSize);
},
onShowSizeChange(nextPage, nextSize) {
onPageSizeChange?.(nextSize);
onShowSizeChange?.(nextPage, nextSize);
const next = preventPageChangeOnPageSizeChange
? page
: Math.floor(((page - 1) * pageSize) / nextSize) + 1;
if (next !== page) onPageChange?.(next);
onChange?.(next, nextSize);
},
};
}