Merge branch 'fields-flow-modal' of github.com:nocobase/nocobase into fields-flow-modal

This commit is contained in:
katherinehhh 2025-06-19 23:28:53 +08:00
commit 9fd9b00057
85 changed files with 1719 additions and 1182 deletions

View File

@ -111,6 +111,7 @@ console.log(apiResource.getData());
- `setSourceId(sourceId) / getSourceId()`: 设置/获取源对象 ID。
- `setDataSourceKey(dataSourceKey) / getDataSourceKey()`: 设置/获取数据源标识(通过 header
- `setFilter(filter) / getFilter()`: 设置/获取过滤条件。
- `addFilterGroup(key, filter) / removeFilterGroup(key)`: 设置/移除条件组。
- `setAppends(appends) / getAppends()`: 设置/获取附加字段。
- `addAppends(appends) / removeAppends(appends)`: 添加/移除附加字段。
- `setFilterByTk(filterByTk) / getFilterByTk()`: 设置/获取主键过滤条件。

View File

@ -18,26 +18,26 @@ function InternalFlowPage({ uid, sharedContext }) {
return <FlowModelRenderer model={model} sharedContext={sharedContext} showFlowSettings hideRemoveInSettings />;
}
export const FlowPage = () => {
export const FlowRoute = () => {
const params = useParams();
return <FlowPageComponent uid={params.name} />;
return <FlowPage uid={params.name} />;
};
export const FlowPageComponent = (props) => {
export const FlowPage = (props) => {
const { uid, parentId, sharedContext } = props;
const flowEngine = useFlowEngine();
const { loading, data } = useRequest(
async () => {
const options = {
uid,
use: 'PageFlowModel',
use: 'PageModel',
subModels: {
tabs: [
{
use: 'PageTabFlowModel',
use: 'PageTabModel',
subModels: {
grid: {
use: 'BlockGridFlowModel',
use: 'BlockGridModel',
},
},
},

View File

@ -12,13 +12,13 @@ import _ from 'lodash';
import { Plugin } from '../application/Plugin';
import { FlowEngineRunner } from './FlowEngineRunner';
import { MockFlowModelRepository } from './FlowModelRepository';
import { FlowPage } from './FlowPage';
import { FlowRoute } from './FlowPage';
import * as models from './models';
import { DateTimeFormat } from './flowSetting/DateTimeFormat';
export class PluginFlowEngine extends Plugin {
async load() {
this.app.addComponents({ FlowPage });
this.app.addComponents({ FlowRoute });
this.app.flowEngine.setModelRepository(new MockFlowModelRepository());
const filteredModels = Object.fromEntries(
Object.entries(models).filter(

View File

@ -1,46 +0,0 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import type { ButtonType } from 'antd/es/button';
import React from 'react';
import { FlowPageComponent } from '../FlowPage';
import { ActionModel } from './ActionModel';
export class AddNewActionModel extends ActionModel {
title = 'Add new';
}
AddNewActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
handler(ctx, params) {
// eslint-disable-next-line prefer-const
let currentDrawer: any;
function DrawerContent() {
return (
<div>
<FlowPageComponent parentId={ctx.model.uid} sharedContext={{ ...ctx.extra, currentDrawer }} />
</div>
);
}
currentDrawer = ctx.globals.drawer.open({
title: '命令式 Drawer',
width: 800,
content: <DrawerContent />,
});
},
},
},
});

View File

@ -1,42 +0,0 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Submit } from '@formily/antd-v5';
import React from 'react';
import { ActionModel } from './ActionModel';
export class SubmitActionModel extends ActionModel {
render() {
return <Submit {...this.props}>{this.props.title || 'Submit'}</Submit>;
}
}
SubmitActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
async handler(ctx, params) {
if (ctx.extra.currentModel) {
await ctx.extra.currentModel.form.submit();
const values = ctx.extra.currentModel.form.values;
await ctx.extra.currentModel.resource.save(values);
}
if (ctx.shared.currentDrawer) {
ctx.shared.currentDrawer.destroy();
}
if (ctx.shared.currentResource) {
ctx.shared.currentResource.refresh();
}
},
},
},
});

View File

@ -1,301 +0,0 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { EditOutlined, SettingOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { css } from '@emotion/css';
import { observer } from '@formily/reactive-react';
import { AddActionModel, CollectionField, FlowModelRenderer, FlowsFloatContextMenu } from '@nocobase/flow-engine';
import { Space, TableColumnProps, Tooltip } from 'antd';
import React from 'react';
import { ActionModel } from './ActionModel';
import { FieldFlowModel, SupportedFieldInterfaces } from './FieldFlowModel';
import { QuickEditForm } from './QuickEditForm';
export class TableColumnModel extends FieldFlowModel {
static readonly supportedFieldInterfaces: SupportedFieldInterfaces = '*';
getColumnProps(): TableColumnProps {
const titleContent = (
<FlowsFloatContextMenu
model={this}
containerStyle={{ display: 'block', padding: '11px 8px', margin: '-11px -8px' }}
>
{this.props.title}
</FlowsFloatContextMenu>
);
return {
...this.props,
title: this.props.tooltip ? (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
{titleContent}
<Tooltip title={this.props.tooltip}>
<QuestionCircleOutlined style={{ cursor: 'pointer' }} />
</Tooltip>
</span>
) : (
titleContent
),
ellipsis: true,
onCell: (record) => ({
className: css`
.edit-icon {
position: absolute;
display: none;
color: #1890ff;
margin-left: 8px;
cursor: pointer;
top: 50%;
right: 8px;
transform: translateY(-50%);
}
&:hover {
background: rgba(24, 144, 255, 0.1) !important;
}
&:hover .edit-icon {
display: inline-flex;
}
`,
}),
render: this.render(),
width: this.props.width || 200,
onHeaderCell: () => ({
className: css`
.ant-table-cell-content {
display: inline !important;
}
`,
}),
};
}
setComponentProps(props) {
this.setProps('componentProps', { ...(this.props.componentProps || {}), ...props });
}
getComponentProps() {
return this.props.componentProps;
}
setDataSource(dataSource) {
this.setProps('componentProps', { ...(this.props.componentProps || {}), dataSource });
}
getDataSource() {
return this.props.componentProps.dataSource || [];
}
renderQuickEditButton(record) {
return (
<Tooltip title="快速编辑">
<EditOutlined
className="edit-icon"
onClick={async (e) => {
e.stopPropagation();
await QuickEditForm.open({
flowEngine: this.flowEngine,
collectionField: this.field as CollectionField,
filterByTk: record.id,
});
await this.parent.resource.refresh();
}}
/>
</Tooltip>
);
}
render() {
return (value, record, index) => (
<>
{value}
{this.renderQuickEditButton(record)}
</>
);
}
}
TableColumnModel.define({
title: 'Table Column',
icon: 'TableColumn',
defaultOptions: {
use: 'TableColumnModel',
},
sort: 0,
});
const Columns = observer<any>(({ record, model, index }) => {
return (
<Space>
{model.mapSubModels('actions', (action: ActionModel) => {
const fork = action.createFork({}, `${index}`);
return (
<FlowModelRenderer
showFlowSettings
key={fork.uid}
model={fork}
extraContext={{ currentResource: model.parent.resource, currentRecord: record }}
/>
);
})}
</Space>
);
});
export class TableActionsColumnModel extends TableColumnModel {
static readonly supportedFieldInterfaces: SupportedFieldInterfaces = null;
getColumnProps() {
return {
...this.props,
title: (
<FlowsFloatContextMenu
model={this}
containerStyle={{ display: 'block', padding: '11px 8px', margin: '-11px -8px' }}
>
<Space>
{this.props.title || 'Actions'}
<AddActionModel
model={this}
subModelKey={'actions'}
items={() => [
{
key: 'view',
label: 'View',
createModelOptions: {
use: 'ViewActionModel',
},
},
{
key: 'link',
label: 'Link',
createModelOptions: {
use: 'LinkActionModel',
},
},
{
key: 'delete',
label: 'Delete',
createModelOptions: {
use: 'DeleteActionModel',
},
},
]}
>
<SettingOutlined />
</AddActionModel>
</Space>
</FlowsFloatContextMenu>
),
render: this.render(),
};
}
render() {
return (value, record, index) => <Columns record={record} model={this} index={index} />;
}
}
TableColumnModel.registerFlow({
key: 'default',
auto: true,
title: 'Basic',
steps: {
step1: {
handler(ctx, params) {
if (!params.fieldPath) {
return;
}
if (ctx.model.field) {
return;
}
const field = ctx.globals.dataSourceManager.getCollectionField(params.fieldPath);
ctx.model.field = field;
ctx.model.fieldPath = params.fieldPath;
ctx.model.setProps('dataIndex', field.name);
ctx.model.setComponentProps(field.getComponentProps());
if (field.enum.length) {
ctx.model.setDataSource(field.enum);
}
},
},
editColumTitle: {
title: 'Column title',
uiSchema: {
title: {
'x-component': 'Input',
'x-decorator': 'FormItem',
'x-component-props': {
placeholder: 'Column title',
},
},
},
defaultParams: (ctx) => {
return {
title: ctx.model.field?.title,
};
},
handler(ctx, params) {
ctx.model.setProps('title', params.title || ctx.model.field?.title);
},
},
editTooltip: {
title: 'Edit tooltip',
uiSchema: {
tooltip: {
'x-component': 'Input.TextArea',
'x-decorator': 'FormItem',
'x-component-props': {
placeholder: 'Edit tooltip',
},
},
},
handler(ctx, params) {
ctx.model.setProps('tooltip', params.tooltip);
},
},
editColumnWidth: {
title: 'Column width',
uiSchema: {
width: {
'x-component': 'NumberPicker',
'x-decorator': 'FormItem',
},
},
defaultParams: {
width: '200',
},
handler(ctx, params) {
ctx.model.setProps('width', params.width);
},
},
fixed: {
title: 'Fixed',
uiSchema: {
fixed: {
'x-component': 'Select',
'x-decorator': 'FormItem',
enum: [
{
value: 'none',
label: 'Not fixed',
},
{
value: 'left',
label: 'Left fixed',
},
{
value: 'right',
label: 'Right fixed',
},
],
},
},
defaultParams: {
fixed: 'none',
},
handler(ctx, params) {
ctx.model.setProps('fixed', params.fixed);
},
},
},
});

View File

@ -0,0 +1,70 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { ButtonProps } from 'antd';
import React from 'react';
import { FlowPage } from '../../FlowPage';
import { ActionModel } from '../base/ActionModel';
export class AddNewActionModel extends ActionModel {
defaultProps: ButtonProps = {
type: 'primary',
children: 'Add new',
};
}
AddNewActionModel.registerFlow({
sort: 200,
title: '事件',
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
title: '弹窗配置',
uiSchema: {
width: {
type: 'number',
title: '宽度',
'x-decorator': 'FormItem',
'x-component': 'NumberPicker',
'x-component-props': {
placeholder: '请输入宽度',
},
},
},
defaultParams: {
width: 800,
},
handler(ctx, params) {
// eslint-disable-next-line prefer-const
let currentDrawer: any;
function DrawerContent() {
return (
<div>
<FlowPage
parentId={ctx.model.uid}
sharedContext={{ parentBlockModel: ctx.shared.currentBlockModel, currentDrawer }}
/>
</div>
);
}
currentDrawer = ctx.globals.drawer.open({
// title: '命令式 Drawer',
header: null,
width: params.width,
content: <DrawerContent />,
});
},
},
},
});

View File

@ -8,11 +8,13 @@
*/
import { MultiRecordResource } from '@nocobase/flow-engine';
import React from 'react';
import { ActionModel } from './ActionModel';
import { ButtonProps } from 'antd';
import { ActionModel } from '../base/ActionModel';
export class BulkDeleteActionModel extends ActionModel {
title = 'Delete';
defaultProps: ButtonProps = {
children: 'Delete',
};
}
BulkDeleteActionModel.registerFlow({
@ -23,11 +25,11 @@ BulkDeleteActionModel.registerFlow({
steps: {
step1: {
async handler(ctx, params) {
if (!ctx.extra.currentResource) {
if (!ctx.shared?.currentBlockModel?.resource) {
ctx.globals.message.error('No resource selected for deletion.');
return;
}
const resource = ctx.extra.currentResource as MultiRecordResource;
const resource = ctx.shared.currentBlockModel.resource as MultiRecordResource;
if (resource.getSelectedRows().length === 0) {
ctx.globals.message.warning('No records selected for deletion.');
return;

View File

@ -7,13 +7,15 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import type { ButtonType } from 'antd/es/button';
import React from 'react';
import { ActionModel } from './ActionModel';
import { MultiRecordResource } from '@nocobase/flow-engine';
import type { ButtonProps } from 'antd';
import { ActionModel } from '../base/ActionModel';
export class DeleteActionModel extends ActionModel {
title = 'Delete';
type: ButtonType = 'link';
defaultProps: ButtonProps = {
children: 'Delete',
type: 'link',
};
}
DeleteActionModel.registerFlow({
@ -54,11 +56,16 @@ DeleteActionModel.registerFlow({
},
step1: {
async handler(ctx, params) {
if (!ctx.extra.currentResource || !ctx.extra.currentRecord) {
if (!ctx.shared?.currentBlockModel?.resource) {
ctx.globals.message.error('No resource selected for deletion.');
return;
}
if (!ctx.extra.currentRecord) {
ctx.globals.message.error('No resource or record selected for deletion.');
return;
}
await ctx.extra.currentResource.destroy(ctx.extra.currentRecord);
const resource = ctx.shared.currentBlockModel.resource as MultiRecordResource;
await resource.destroy(ctx.extra.currentRecord);
ctx.globals.message.success('Record deleted successfully.');
},
},

View File

@ -0,0 +1,53 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { MultiRecordResource } from '@nocobase/flow-engine';
import { Button, ButtonProps, Input, Popover } from 'antd';
import _ from 'lodash';
import React from 'react';
import { ActionModel } from '../base/ActionModel';
export class FilterActionModel extends ActionModel {
defaultProps: ButtonProps = {
type: 'default',
children: 'Filter',
};
render() {
return (
<Popover
content={
<div>
<Input
placeholder="Nickname, email, phone, etc."
onChange={_.debounce((e) => {
const resource = this.ctx.shared?.currentBlockModel?.resource as MultiRecordResource;
if (!resource) {
return;
}
resource.addFilterGroup(this.uid, {
$or: [
{ ['nickname.$includes']: e.target.value },
{ ['email.$includes']: e.target.value },
{ ['phone.$includes']: e.target.value },
],
});
resource.refresh();
}, 500)}
/>
</div>
}
trigger="click"
placement="bottom"
>
<Button {...this.defaultProps} {...this.props} />
</Popover>
);
}
}

View File

@ -7,13 +7,14 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import type { ButtonType } from 'antd/es/button';
import React from 'react';
import { ActionModel } from './ActionModel';
import type { ButtonProps } from 'antd';
import { ActionModel } from '../base/ActionModel';
export class LinkActionModel extends ActionModel {
title = 'Link';
type: ButtonType = 'link';
defaultProps: ButtonProps = {
type: 'link',
children: 'Link',
};
}
LinkActionModel.registerFlow({
@ -23,12 +24,7 @@ LinkActionModel.registerFlow({
},
steps: {
step1: {
handler(ctx, params) {
ctx.globals.modal.confirm({
title: `${ctx.extra.currentRecord?.id}`,
content: 'Are you sure you want to perform this action?',
});
},
handler(ctx, params) {},
},
},
});

View File

@ -0,0 +1,36 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { ButtonProps } from 'antd';
import { ActionModel } from '../base/ActionModel';
export class RefreshActionModel extends ActionModel {
defaultProps: ButtonProps = {
children: 'Refresh',
};
}
RefreshActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
async handler(ctx, params) {
if (!ctx.shared?.currentBlockModel?.resource) {
ctx.globals.message.error('No resource selected for refresh.');
return;
}
const currentBlockModel = ctx.shared.currentBlockModel;
await currentBlockModel.resource.refresh();
},
},
},
});

View File

@ -7,14 +7,16 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import type { ButtonType } from 'antd/es/button';
import { ButtonProps } from 'antd';
import React from 'react';
import { FlowPageComponent } from '../FlowPage';
import { ActionModel } from './ActionModel';
import { FlowPage } from '../../FlowPage';
import { ActionModel } from '../base/ActionModel';
export class ViewActionModel extends ActionModel {
title = 'View';
type: ButtonType = 'link';
defaultProps: ButtonProps = {
children: 'View',
type: 'link',
};
}
ViewActionModel.registerFlow({
@ -31,13 +33,20 @@ ViewActionModel.registerFlow({
function DrawerContent() {
return (
<div>
<FlowPageComponent parentId={ctx.model.uid} sharedContext={{ ...ctx.extra, currentDrawer }} />
<FlowPage
parentId={ctx.model.uid}
sharedContext={{
currentDrawer,
parentRecord: ctx.extra.currentRecord,
parentBlockModel: ctx.shared.currentBlockModel,
}}
/>
</div>
);
}
currentDrawer = ctx.globals.drawer.open({
title: '命令式 Drawer',
// title: '命令式 Drawer',
width: 800,
content: <DrawerContent />,
});

View File

@ -9,23 +9,23 @@
import { FlowModel } from '@nocobase/flow-engine';
import { Button } from 'antd';
import type { ButtonType } from 'antd/es/button';
import type { ButtonProps } from 'antd/es/button';
import React from 'react';
export class ActionModel extends FlowModel {
set onClick(fn) {
this.setProps('onClick', fn);
}
title = 'Action';
type: ButtonType = 'default';
defaultProps: ButtonProps = {
type: 'default',
children: 'Action',
};
render() {
return (
<Button type={this.type} {...this.props}>
{this.props.children || this.title}
</Button>
<Button
{...this.defaultProps}
{...this.props}
onClick={(event) => {
this.dispatchEvent('click', { event });
}}
/>
);
}
}
@ -33,10 +33,13 @@ export class ActionModel extends FlowModel {
ActionModel.registerFlow({
key: 'default',
auto: true,
title: '基础',
sort: 100,
steps: {
step1: {
title: '编辑按钮',
uiSchema: {
title: {
children: {
type: 'string',
title: '标题',
'x-decorator': 'FormItem',
@ -48,17 +51,12 @@ ActionModel.registerFlow({
},
defaultParams(ctx) {
return {
title: ctx.model.title,
type: 'default',
...ctx.model.defaultProps,
};
},
handler(ctx, params) {
ctx.model.setProps('children', params.title);
ctx.model.onClick = (e) => {
ctx.model.dispatchEvent('click', {
...ctx.extra,
event: e,
});
};
ctx.model.setProps('children', params.children);
},
},
},

View File

@ -0,0 +1,19 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Collection, DefaultStructure, FlowModel, FlowResource } from '@nocobase/flow-engine';
export class BlockModel<T = DefaultStructure> extends FlowModel<T> {}
export class DataBlockModel<T = DefaultStructure> extends BlockModel<T> {
resource: FlowResource;
collection: Collection;
}
export class FilterBlockModel<T = DefaultStructure> extends BlockModel<T> {}

View File

@ -12,8 +12,8 @@ import { CollectionField, FlowModel } from '@nocobase/flow-engine';
// null 表示不支持任何字段接口,* 表示支持所有字段接口
export type SupportedFieldInterfaces = string[] | '*' | null;
export class FieldFlowModel extends FlowModel {
field: CollectionField;
export class FieldModel extends FlowModel {
collectionField: CollectionField;
fieldPath: string;
public static readonly supportedFieldInterfaces: SupportedFieldInterfaces = null;
}

View File

@ -11,7 +11,7 @@ import { AddBlockButton, FlowModel, FlowModelRenderer } from '@nocobase/flow-eng
import { Button, Card, Dropdown } from 'antd';
import _ from 'lodash';
import React from 'react';
import { BlockFlowModel } from './BlockFlowModel';
import { BlockModel } from './BlockModel';
function Grid({ items }) {
return (
@ -27,35 +27,24 @@ function Grid({ items }) {
);
}
// function AddBlockButton({ model }) {
// return (
// <Dropdown
// menu={{
// onClick: (info) => {
// const BlockModel = model.flowEngine.getModelClass(info.key);
// model.addItem(_.cloneDeep(BlockModel.meta.defaultOptions));
// },
// items: model.getBlockModels(),
// }}
// >
// <Button>Add block</Button>
// </Dropdown>
// );
// }
type BlockGridFlowModelStructure = {
type GridModelStructure = {
subModels: {
items: BlockFlowModel[];
items: BlockModel[];
};
};
export class BlockGridFlowModel extends FlowModel<BlockGridFlowModelStructure> {
export class GridModel extends FlowModel<GridModelStructure> {
subModelBaseClass = 'BlockModel';
render() {
return (
<div style={{ padding: 16 }}>
<Grid items={this.subModels.items?.slice() || []} />
<AddBlockButton model={this} subModelKey="items" />
<AddBlockButton model={this} subModelKey="items" subModelBaseClass={this.subModelBaseClass} />
</div>
);
}
}
export class BlockGridModel extends GridModel {
subModelBaseClass = 'BlockModel';
}

View File

@ -13,13 +13,13 @@ import { Button, Tabs } from 'antd';
import _ from 'lodash';
import React from 'react';
type PageFlowModelStructure = {
type PageModelStructure = {
subModels: {
tabs: FlowModel[];
};
};
export class PageFlowModel extends FlowModel<PageFlowModelStructure> {
export class PageModel extends FlowModel<PageModelStructure> {
addTab(tab: any) {
const model = this.addSubModel('tabs', tab);
model.save();
@ -48,11 +48,11 @@ export class PageFlowModel extends FlowModel<PageFlowModelStructure> {
<Button
onClick={() =>
this.addTab({
use: 'PageTabFlowModel',
use: 'PageTabModel',
props: { key: uid(), label: `Tab - ${uid()}` },
subModels: {
grid: {
use: 'BlockGridFlowModel',
use: 'BlockGridModel',
},
},
})
@ -70,7 +70,7 @@ export class PageFlowModel extends FlowModel<PageFlowModelStructure> {
}
}
PageFlowModel.registerFlow({
PageModel.registerFlow({
key: 'default',
auto: true,
steps: {
@ -94,7 +94,7 @@ PageFlowModel.registerFlow({
},
async handler(ctx, params) {
ctx.model.setProps('enableTabs', params.enableTabs || false);
console.log('PageFlowModel step1 handler', ctx.model.props.enableTabs);
console.log('PageModel step1 handler', ctx.model.props.enableTabs);
},
},
},

View File

@ -9,11 +9,11 @@
import { FlowModel, FlowModelRenderer } from '@nocobase/flow-engine';
import React from 'react';
import { BlockGridFlowModel } from './BlockGridFlowModel';
import { BlockGridModel } from './GridModel';
export class PageTabFlowModel extends FlowModel<{
export class PageTabModel extends FlowModel<{
subModels: {
grid: BlockGridFlowModel;
grid: BlockGridModel;
};
}> {
render() {
@ -26,7 +26,7 @@ export class PageTabFlowModel extends FlowModel<{
}
}
PageTabFlowModel.registerFlow({
PageTabModel.registerFlow({
key: 'default',
auto: true,
steps: {

View File

@ -7,22 +7,19 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Application, Plugin } from '@nocobase/client';
import { Collection, FlowModel, MultiRecordResource } from '@nocobase/flow-engine';
import { Collection, MultiRecordResource } from '@nocobase/flow-engine';
import { Card, Modal } from 'antd';
import moment from 'moment';
import dataSource from 'packages/core/client/docs/zh-CN/core/flow-models/demos/data-source';
import { createdAt } from 'packages/plugins/@nocobase/plugin-mock-collections/src/server/field-interfaces';
import React from 'react';
import { Calendar, momentLocalizer } from 'react-big-calendar';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import { BlockFlowModel } from './BlockFlowModel';
import { DataBlockModel } from '../../base/BlockModel';
const localizer = momentLocalizer(moment);
export class CalendarBlockFlowModel extends BlockFlowModel {
collection: Collection;
resource: MultiRecordResource;
export class CalendarBlockModel extends DataBlockModel {
declare resource: MultiRecordResource;
render() {
const data = this.resource.getData();
return (
@ -49,7 +46,15 @@ export class CalendarBlockFlowModel extends BlockFlowModel {
}
}
CalendarBlockFlowModel.registerFlow({
CalendarBlockModel.define({
title: 'Calendar',
group: 'Content',
defaultOptions: {
use: 'CalendarBlockModel',
},
});
CalendarBlockModel.registerFlow({
key: 'key2',
on: {
eventName: 'onSelectEvent',
@ -73,7 +78,7 @@ CalendarBlockFlowModel.registerFlow({
},
});
CalendarBlockFlowModel.registerFlow({
CalendarBlockModel.registerFlow({
key: 'key3',
on: {
eventName: 'onDoubleClickEvent',
@ -97,7 +102,7 @@ CalendarBlockFlowModel.registerFlow({
},
});
CalendarBlockFlowModel.registerFlow({
CalendarBlockModel.registerFlow({
key: 'default',
auto: true,
steps: {
@ -170,7 +175,7 @@ CalendarBlockFlowModel.registerFlow({
},
},
handler: async (ctx, params) => {
console.log('CalendarBlockFlowModel step2 params:', params);
console.log('CalendarBlockModel step2 params:', params);
ctx.model.setProps('titleAccessor', params.titleAccessor);
ctx.model.setProps('startAccessor', params.startAccessor);
ctx.model.setProps('endAccessor', params.endAccessor);
@ -178,11 +183,3 @@ CalendarBlockFlowModel.registerFlow({
},
},
});
CalendarBlockFlowModel.define({
title: 'Calendar',
group: 'Content',
defaultOptions: {
use: 'CalendarBlockFlowModel',
},
});

View File

@ -0,0 +1,49 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { ButtonProps } from 'antd';
import { ActionModel } from '../../base/ActionModel';
export class FormActionModel extends ActionModel {}
export class FormSubmitActionModel extends FormActionModel {
defaultProps: ButtonProps = {
children: 'Submit',
type: 'primary',
htmlType: 'submit',
};
}
FormSubmitActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
async handler(ctx, params) {
if (!ctx.shared?.currentBlockModel?.resource) {
ctx.globals.message.error('No resource selected for submission.');
return;
}
const currentBlockModel = ctx.shared.currentBlockModel;
const currentResource = ctx.shared.currentBlockModel.resource;
await currentBlockModel.form.submit();
const values = currentBlockModel.form.values;
await currentBlockModel.resource.save(values);
await currentBlockModel.form.reset();
// currentResource.refresh();
ctx.shared.parentBlockModel?.resource?.refresh();
if (ctx.shared.currentDrawer) {
ctx.shared.currentDrawer.destroy();
}
},
},
},
});

View File

@ -10,22 +10,16 @@
import { FormButtonGroup, FormLayout } from '@formily/antd-v5';
import { createForm, Form } from '@formily/core';
import { FormProvider } from '@formily/react';
import {
AddActionButton,
AddFieldButton,
Collection,
FlowModelRenderer,
SingleRecordResource,
} from '@nocobase/flow-engine';
import { AddActionButton, AddFieldButton, FlowModelRenderer, SingleRecordResource } from '@nocobase/flow-engine';
import { Card } from 'antd';
import React from 'react';
import { BlockFlowModel } from './BlockFlowModel';
import { FormFieldModel } from './FormFieldModel';
import { DataBlockModel } from '../../base/BlockModel';
import { FormFieldModel } from './fields/FormFieldModel';
export class FormModel extends BlockFlowModel {
export class FormModel extends DataBlockModel {
form: Form;
resource: SingleRecordResource;
collection: Collection;
declare resource: SingleRecordResource;
// collection: Collection;
render() {
return (
@ -33,7 +27,7 @@ export class FormModel extends BlockFlowModel {
<FormProvider form={this.form}>
<FormLayout layout={'vertical'}>
{this.mapSubModels('fields', (field) => (
<FlowModelRenderer model={field} showFlowSettings />
<FlowModelRenderer model={field} showFlowSettings sharedContext={{ currentBlockModel: this }} />
))}
</FormLayout>
<AddFieldButton
@ -65,9 +59,9 @@ export class FormModel extends BlockFlowModel {
/>
<FormButtonGroup>
{this.mapSubModels('actions', (action) => (
<FlowModelRenderer model={action} showFlowSettings extraContext={{ currentModel: this }} />
<FlowModelRenderer model={action} showFlowSettings sharedContext={{ currentBlockModel: this }} />
))}
<AddActionButton model={this} subModelBaseClass="ActionModel" />
<AddActionButton model={this} subModelBaseClass="FormActionModel" />
</FormButtonGroup>
</FormProvider>
</Card>
@ -118,9 +112,8 @@ FormModel.registerFlow({
resource.setAPIClient(ctx.globals.api);
ctx.model.resource = resource;
}
console.log('FormModel flow context', ctx.shared, ctx.model.getSharedContext());
if (ctx.shared.currentRecord) {
ctx.model.resource.setFilterByTk(ctx.shared.currentRecord.id);
if (ctx.shared.parentRecord) {
ctx.model.resource.setFilterByTk(ctx.shared.parentRecord.id);
await ctx.model.resource.refresh();
ctx.model.form.setInitialValues(ctx.model.resource.getData());
}

View File

@ -15,17 +15,16 @@ import {
CollectionField,
FlowEngine,
FlowEngineProvider,
FlowModel,
FlowModelRenderer,
SingleRecordResource,
} from '@nocobase/flow-engine';
import dataSource from 'packages/core/client/docs/zh-CN/core/flow-models/demos/data-source';
import React from 'react';
import { BlockFlowModel } from './BlockFlowModel';
export class QuickEditForm extends BlockFlowModel {
export class QuickEditForm extends FlowModel {
form: Form;
resource: SingleRecordResource;
collection: Collection;
declare resource: SingleRecordResource;
declare collection: Collection;
static async open(options: { flowEngine: FlowEngine; collectionField: CollectionField; filterByTk: string }) {
const model = options.flowEngine.createModel({

View File

@ -0,0 +1,257 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { connect, mapProps, mapReadPretty } from '@formily/react';
import { isValid, toArr } from '@formily/shared';
import { Select } from 'antd';
import React, { useMemo } from 'react';
import { FormFieldModel } from '../FormFieldModel';
function toValue(record: any | any[], fieldNames, multiple = false) {
if (!record) return multiple ? [] : undefined;
const { label: labelKey, value: valueKey } = fieldNames;
const convert = (item: any) => {
if (typeof item !== 'object' || item === null) return undefined;
return {
label: item[labelKey],
value: item[valueKey],
};
};
if (multiple) {
if (!Array.isArray(record)) return [];
return record.map(convert).filter(Boolean);
}
return convert(record);
}
function LazySelect(props) {
const { fieldNames, value, multiple } = props;
return (
<Select
showSearch
labelInValue
{...props}
value={toValue(value, fieldNames, multiple)}
mode={multiple && 'multiple'}
onChange={(value, option) => {
props.onChange(option);
}}
/>
);
}
export const AssociationSelect = connect(
(props: any) => {
return <LazySelect {...props} />;
},
mapProps(
{
dataSource: 'options',
},
(props, field) => {
return {
...props,
};
},
),
mapReadPretty((props) => {
return props.value;
}),
);
export class AssociationSelectFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['m2m', 'm2o', 'o2o', 'o2m', 'oho', 'obo', 'updatedBy', 'createdBy'];
dataSource;
fieldNames: { label: string; value: string; color?: string; icon?: any };
set onPopupScroll(fn) {
this.field.setComponentProps({ onPopupScroll: fn });
}
set onDropdownVisibleChange(fn) {
this.field.setComponentProps({ onDropdownVisibleChange: fn });
}
set onSearch(fn) {
this.field.setComponentProps({ onSearch: fn });
}
setDataSource(dataSource) {
this.field.dataSource = dataSource;
}
getDataSource() {
return this.field.dataSource;
}
setFieldNames(fieldNames) {
this.fieldNames = fieldNames;
}
get component() {
return [AssociationSelect, {}];
}
}
AssociationSelectFieldModel.registerFlow({
key: 'init',
auto: true,
sort: 100,
steps: {
step1: {
handler(ctx, params) {
let initialized = false;
ctx.model.onDropdownVisibleChange = (open) => {
if (open && !initialized) {
initialized = true;
ctx.model.dispatchEvent('dropdownOpen', {
apiClient: ctx.app.apiClient,
field: ctx.model.field,
form: ctx.model.form,
});
}
};
ctx.model.onPopupScroll = (e) => {
ctx.model.dispatchEvent('popupScroll', {
event: e,
apiClient: ctx.app.apiClient,
field: ctx.model.field,
});
};
ctx.model.onSearch = (searchText) => {
ctx.model.dispatchEvent('search', {
searchText,
apiClient: ctx.app.apiClient,
field: ctx.model.field,
});
};
},
},
},
});
AssociationSelectFieldModel.registerFlow({
key: 'event1',
on: {
eventName: 'dropdownOpen',
},
steps: {
step1: {
async handler(ctx, params) {
const { target } = ctx.model.collectionField.options;
const apiClient = ctx.app.apiClient;
const response = await apiClient.request({
url: `/${target}:list`,
params: {
pageSize: 20,
},
});
const { data } = response.data;
ctx.model.setDataSource(data);
},
},
},
});
const paginationState = {
page: 1,
pageSize: 20,
loading: false,
hasMore: true,
};
AssociationSelectFieldModel.registerFlow({
key: 'event2',
on: {
eventName: 'popupScroll',
},
steps: {
step1: {
async handler(ctx, params) {
if (paginationState.loading || !paginationState.hasMore) {
return;
}
paginationState.loading = true;
try {
const { target } = ctx.model.collectionField.options;
const apiClient = ctx.app.apiClient;
const response = await apiClient.request({
url: `/${target}:list`,
params: {
page: paginationState.page,
pageSize: paginationState.pageSize,
},
});
const { data } = response.data;
const currentDataSource = ctx.model.getDataSource() || [];
ctx.model.setDataSource([...currentDataSource, ...data]);
if (data.length < paginationState.pageSize) {
paginationState.hasMore = false;
} else {
paginationState.page++;
}
} catch (error) {
console.error('滚动分页请求失败:', error);
} finally {
paginationState.loading = false;
}
},
},
},
});
AssociationSelectFieldModel.registerFlow({
key: 'event3',
on: {
eventName: 'search',
},
steps: {
step1: {
async handler(ctx, params) {
try {
const collectionField = ctx.model.collectionField;
const collectionManager = collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(collectionField.options.target);
const labelFieldName = ctx.model.field.componentProps.fieldNames.label;
const targetLabelField = targetCollection.getField(labelFieldName);
const targetInterface = ctx.app.dataSourceManager.collectionFieldInterfaceManager.getFieldInterface(
targetLabelField.options.interface,
);
const operator = targetInterface?.filterable?.operators?.[0]?.value || '$includes';
const searchText = ctx.extra.searchText?.trim();
const apiClient = ctx.app.apiClient;
const response = await apiClient.request({
url: `/${collectionField.options.target}:list`,
params: {
filter: {
[labelFieldName]: {
[operator]: searchText,
},
},
},
});
const { data } = response.data;
ctx.model.setDataSource(data);
} catch (error) {
console.error('AssociationSelectField search flow error:', error);
// 出错时也可以选择清空数据源或者显示错误提示
ctx.model.setDataSource([]);
}
},
},
},
});

View File

@ -7,8 +7,8 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../FormFieldModel';
import { Checkbox } from 'antd';
import { Checkbox } from '@formily/antd-v5';
import { FormFieldModel } from './FormFieldModel';
export class CheckboxFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['checkbox'];

View File

@ -7,8 +7,8 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../FormFieldModel';
import { Checkbox } from '@formily/antd-v5';
import { FormFieldModel } from './FormFieldModel';
export class CheckboxGroupField extends FormFieldModel {
static supportedFieldInterfaces = ['checkboxGroup'];

View File

@ -7,9 +7,9 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { ColorPicker as AntdColorPicker } from 'antd';
import { connect, mapProps } from '@formily/react';
import { FormFieldModel } from '../../FormFieldModel';
import { ColorPicker as AntdColorPicker } from 'antd';
import { FormFieldModel } from './FormFieldModel';
const ColorPicker = connect(
AntdColorPicker,

View File

@ -0,0 +1,204 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { css } from '@emotion/css';
import { DatePicker } from '@formily/antd-v5';
import { getPickerFormat } from '@nocobase/utils/client';
import { DateFormatCom, ExpiresRadio } from '../../../../../components';
import { FormFieldModel } from '../FormFieldModel';
export class DateTimeFieldModel extends FormFieldModel {
setComponentProps(componentProps) {
let { dateFormat, timeFormat } = componentProps || {};
if (!componentProps.format && (dateFormat || timeFormat)) {
if (!dateFormat) {
dateFormat = this.field.componentProps?.dateFormat || 'YYYY-MM-DD';
}
if (!timeFormat) {
timeFormat = this.field.componentProps?.timeFormat || 'HH:mm:ss';
}
componentProps.format = componentProps?.showTime ? `${dateFormat} ${timeFormat}` : dateFormat;
}
super.setComponentProps({
...componentProps,
});
}
get component() {
return [DatePicker, {}];
}
}
DateTimeFieldModel.registerFlow({
key: 'key3',
auto: true,
sort: 1000,
title: 'Specific properties',
steps: {
dateFormat: {
title: 'Date display format',
uiSchema: {
picker: {
type: 'string',
title: '{{t("Picker")}}',
'x-decorator': 'FormItem',
'x-component': 'Radio.Group',
description: '{{ t("Switching the picker, the value and default value will be cleared") }}',
enum: [
{
label: '{{t("Date")}}',
value: 'date',
},
{
label: '{{t("Month")}}',
value: 'month',
},
{
label: '{{t("Quarter")}}',
value: 'quarter',
},
{
label: '{{t("Year")}}',
value: 'year',
},
],
},
dateFormat: {
type: 'string',
title: '{{t("Date format")}}',
'x-component': ExpiresRadio,
'x-decorator': 'FormItem',
'x-decorator-props': {},
'x-component-props': {
className: css`
.ant-radio-wrapper {
display: flex;
margin: 5px 0px;
}
`,
defaultValue: 'dddd',
formats: ['MMMM Do YYYY', 'YYYY-MM-DD', 'MM/DD/YY', 'YYYY/MM/DD', 'DD/MM/YYYY'],
},
// default: dateFormatDefaultValue,
enum: [
{
label: DateFormatCom({ format: 'MMMM Do YYYY' }),
value: 'MMMM Do YYYY',
},
{
label: DateFormatCom({ format: 'YYYY-MM-DD' }),
value: 'YYYY-MM-DD',
},
{
label: DateFormatCom({ format: 'MM/DD/YY' }),
value: 'MM/DD/YY',
},
{
label: DateFormatCom({ format: 'YYYY/MM/DD' }),
value: 'YYYY/MM/DD',
},
{
label: DateFormatCom({ format: 'DD/MM/YYYY' }),
value: 'DD/MM/YYYY',
},
{
label: 'custom',
value: 'custom',
},
],
'x-reactions': {
dependencies: ['picker'],
fulfill: {
state: {
value: `{{ getPickerFormat($deps[0])}}`,
componentProps: { picker: `{{$deps[0]}}` },
},
},
},
},
showTime: {
type: 'boolean',
'x-decorator': 'FormItem',
'x-component': 'Checkbox',
'x-content': '{{t("Show time")}}',
'x-reactions': [
{
dependencies: ['picker'],
fulfill: {
state: {
hidden: `{{ $form.values.picker !== 'date' || collectionField.type!== 'date' }}`,
},
},
},
],
},
timeFormat: {
type: 'string',
title: '{{t("Time format")}}',
'x-component': ExpiresRadio,
'x-decorator': 'FormItem',
'x-decorator-props': {
className: css`
margin-bottom: 0px;
`,
},
'x-component-props': {
className: css`
color: red;
.ant-radio-wrapper {
display: flex;
margin: 5px 0px;
}
`,
defaultValue: 'h:mm a',
formats: ['hh:mm:ss a', 'HH:mm:ss'],
timeFormat: true,
},
'x-reactions': [
(field) => {
const { showTime } = field.form.values || {};
field.hidden = !showTime;
},
],
enum: [
{
label: DateFormatCom({ format: 'hh:mm:ss a' }),
value: 'hh:mm:ss a',
},
{
label: DateFormatCom({ format: 'HH:mm:ss' }),
value: 'HH:mm:ss',
},
{
label: 'custom',
value: 'custom',
},
],
},
},
handler(ctx, params) {
ctx.model.flowEngine.flowSettings.registerScopes({
getPickerFormat,
collectionField: ctx.model.collectionField,
});
ctx.model.setComponentProps({ ...params });
},
defaultParams: (ctx) => {
const { showTime, dateFormat, timeFormat, picker } = ctx.model.field.componentProps;
return {
picker: picker || 'date',
dateFormat: dateFormat || 'YYYY-MM-DD',
timeFormat: timeFormat,
showTime,
};
},
},
},
});

View File

@ -0,0 +1,13 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { DateTimeFieldModel } from './DateTimeFieldModel';
export class UnixTimestampFieldModel extends DateTimeFieldModel {
static supportedFieldInterfaces = ['unixTimestamp'];
}

View File

@ -8,12 +8,12 @@
*/
import { FormItem, Input } from '@formily/antd-v5';
import type { FieldPatternTypes, FieldValidator } from '@formily/core';
import { Field, Form } from '@formily/core';
import { FieldContext } from '@formily/react';
import type { FieldValidator, FieldPatternTypes } from '@formily/core';
import { CollectionField, FlowModel } from '@nocobase/flow-engine';
import React from 'react';
import { ReactiveField } from '../Formily/ReactiveField';
import { ReactiveField } from '../../../../formily/ReactiveField';
type FieldComponentTuple = [component: React.ElementType, props: Record<string, any>] | any[];
@ -248,7 +248,3 @@ FormFieldModel.registerFlow({
},
},
});
export class CommonFormItemFlowModel extends FormFieldModel {
public static readonly supportedFieldInterfaces = '*';
}

View File

@ -7,15 +7,15 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../FormFieldModel';
import { CloseOutlined } from '@ant-design/icons';
import { useFormLayout } from '@formily/antd-v5';
import { Button, Empty, Input, Space, theme, Radio, Flex, Popover } from 'antd';
import { connect, mapProps } from '@formily/react';
import { Button, Empty, Flex, Input, Popover, Radio, Space, theme } from 'antd';
import { debounce, groupBy } from 'lodash';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { connect, mapProps } from '@formily/react';
import { Icon, hasIcon, icons } from '../../../../icon';
import { Icon, hasIcon, icons } from '../../../../../icon';
import { FormFieldModel } from './FormFieldModel';
const { Search } = Input;
interface IconPickerProps {

View File

@ -7,12 +7,12 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../FormFieldModel';
import { connect, mapReadPretty } from '@formily/react';
import { InputNumber as AntdInputNumber, InputNumberProps as AntdInputNumberProps } from 'antd';
import React from 'react';
import BigNumber from 'bignumber.js';
import { omit } from 'lodash';
import React from 'react';
import { FormFieldModel } from './FormFieldModel';
type ComposedInputNumber = React.ForwardRefExoticComponent<
Pick<Partial<any>, string | number | symbol> & React.RefAttributes<unknown>

View File

@ -10,7 +10,7 @@
import { css, cx } from '@emotion/css';
import { Input } from 'antd';
import JSON5 from 'json5';
import { FormFieldModel } from '../../FormFieldModel';
import { FormFieldModel } from './FormFieldModel';
const jsonCss = css`
font-size: 80%;

View File

@ -8,14 +8,14 @@
*/
import { Input } from '@formily/antd-v5';
import React, { useMemo } from 'react';
import { connect, mapProps, mapReadPretty } from '@formily/react';
import { FormFieldModel } from '../../../FormFieldModel';
import { useMarkdownStyles } from './style';
import { useParseMarkdown, convertToText } from './util';
import { useGlobalTheme } from '../../../../../global-theme';
import { Spin } from 'antd';
import { EllipsisWithTooltip } from '../../../../components';
import React, { useMemo } from 'react';
import { useGlobalTheme } from '../../../../../../global-theme';
import { EllipsisWithTooltip } from '../../../../../components';
import { FormFieldModel } from '../FormFieldModel';
import { useMarkdownStyles } from './style';
import { convertToText, useParseMarkdown } from './util';
const MarkdownReadPretty = (props) => {
const { ellipsis } = props;

View File

@ -8,8 +8,8 @@
*/
import { Input } from '@formily/antd-v5';
import { FormFieldModel } from '../../FormFieldModel';
import { customAlphabet as Alphabet } from 'nanoid';
import { FormFieldModel } from './FormFieldModel';
export class NanoIDFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['nanoID'];

View File

@ -8,7 +8,7 @@
*/
import { Password } from '@formily/antd-v5';
import { FormFieldModel } from '../../FormFieldModel';
import { FormFieldModel } from './FormFieldModel';
export class PasswordFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['password'];

View File

@ -8,11 +8,11 @@
*/
import { connect, mapProps } from '@formily/react';
import { FormFieldModel } from '../../FormFieldModel';
import { useMemo } from 'react';
import { isNum } from '@formily/shared';
import { InputNumber } from 'antd';
import * as math from 'mathjs';
import { useMemo } from 'react';
import { FormFieldModel } from './FormFieldModel';
const isNumberLike = (index: any): index is number => isNum(index) || /^-?\d+(\.\d+)?$/.test(index);

View File

@ -7,8 +7,8 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../FormFieldModel';
import { Radio } from '@formily/antd-v5';
import { FormFieldModel } from './FormFieldModel';
export class RadioGroupFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['radioGroup'];

View File

@ -7,10 +7,10 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { connect, mapProps } from '@formily/react';
import { FormFieldModel } from '../../../FormFieldModel';
import { lazy } from '../../../../../lazy-helper';
import React from 'react';
import { lazy } from '../../../../../../lazy-helper';
import { FormFieldModel } from '../FormFieldModel';
import { useRichTextStyles } from './style';
const ReactQuill = lazy(() => import('react-quill'));

View File

@ -8,7 +8,7 @@
*/
import { Select } from '@formily/antd-v5';
import { FormFieldModel } from '../../FormFieldModel';
import { FormFieldModel } from './FormFieldModel';
export class SelectFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['select', 'multipleSelect'];

View File

@ -0,0 +1,14 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from './FormFieldModel';
export class SingleTextFieldModel extends FormFieldModel {
static supportedFieldInterfaces = '*';
}

View File

@ -8,7 +8,7 @@
*/
import { Input } from '@formily/antd-v5';
import { FormFieldModel } from '../../FormFieldModel';
import { FormFieldModel } from './FormFieldModel';
export class TextareaFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['textarea'];

View File

@ -8,7 +8,7 @@
*/
import { TimePicker } from '@formily/antd-v5';
import { FormFieldModel } from '../../FormFieldModel';
import { FormFieldModel } from './FormFieldModel';
export class TimeFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['time'];

View File

@ -0,0 +1,31 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
export * from './AssociationSelectFieldModel';
export * from './CheckboxFieldModel';
export * from './CheckboxGroupField';
export * from './ColorFieldModel';
export * from './DateTimeFieldModel/DateTimeFieldModel';
export * from './DateTimeFieldModel/DateTimeWithTzFieldModel';
export * from './DateTimeFieldModel/UnixTimestampFieldModel';
export * from './FormFieldModel';
export * from './IconFieldModel';
export * from './InputNumberFieldModel';
export * from './JsonFieldModel';
export * from './MarkdownFieldModel';
export * from './NanoIDFieldModel';
export * from './PasswordFieldModel';
export * from './PercentFieldModel';
export * from './RadioGroupFieldModel';
export * from './RichTextFieldModel';
export * from './SelectFieldModel';
export * from './SingleTextFieldModel';
export * from './TextareaFieldModel';
export * from './TimeFieldModel';
//

View File

@ -0,0 +1,85 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { SettingOutlined } from '@ant-design/icons';
import { observer } from '@formily/reactive-react';
import { AddActionModel, FlowModelRenderer, FlowsFloatContextMenu } from '@nocobase/flow-engine';
import { Space } from 'antd';
import React from 'react';
import { ActionModel } from '../../base/ActionModel';
import { SupportedFieldInterfaces } from '../../base/FieldModel';
import { TableColumnModel } from './TableColumnModel';
const Columns = observer<any>(({ record, model, index }) => {
return (
<Space>
{model.mapSubModels('actions', (action: ActionModel) => {
const fork = action.createFork({}, `${index}`);
return (
<FlowModelRenderer showFlowSettings key={fork.uid} model={fork} extraContext={{ currentRecord: record }} />
);
})}
</Space>
);
});
export class TableActionsColumnModel extends TableColumnModel {
static readonly supportedFieldInterfaces: SupportedFieldInterfaces = null;
getColumnProps() {
return {
// title: 'Actions',
...this.props,
title: (
<FlowsFloatContextMenu
model={this}
containerStyle={{ display: 'block', padding: '11px 8px', margin: '-11px -8px' }}
>
<Space>
{this.props.title || 'Actions'}
<AddActionModel
model={this}
subModelKey={'actions'}
items={() => [
{
key: 'view',
label: 'View',
createModelOptions: {
use: 'ViewActionModel',
},
},
{
key: 'link',
label: 'Link',
createModelOptions: {
use: 'LinkActionModel',
},
},
{
key: 'delete',
label: 'Delete',
createModelOptions: {
use: 'DeleteActionModel',
},
},
]}
>
<SettingOutlined />
</AddActionModel>
</Space>
</FlowsFloatContextMenu>
),
render: this.render(),
};
}
render() {
return (value, record, index) => <Columns record={record} model={this} index={index} />;
}
}

View File

@ -0,0 +1,128 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { EditOutlined } from '@ant-design/icons';
import { css } from '@emotion/css';
import { CollectionField, FlowsFloatContextMenu } from '@nocobase/flow-engine';
import { TableColumnProps, Tooltip } from 'antd';
import React from 'react';
import { FieldModel, SupportedFieldInterfaces } from '../../base/FieldModel';
import { QuickEditForm } from '../form/QuickEditForm';
export class TableColumnModel extends FieldModel {
static readonly supportedFieldInterfaces: SupportedFieldInterfaces = '*';
getColumnProps(): TableColumnProps {
return {
...this.props,
title: (
<FlowsFloatContextMenu
model={this}
containerStyle={{ display: 'block', padding: '11px 8px', margin: '-11px -8px' }}
>
{this.props.title}
</FlowsFloatContextMenu>
),
ellipsis: true,
onCell: (record) => ({
className: css`
.edit-icon {
position: absolute;
display: none;
color: #1890ff;
margin-left: 8px;
cursor: pointer;
top: 50%;
right: 8px;
transform: translateY(-50%);
}
&:hover {
background: rgba(24, 144, 255, 0.1) !important;
}
&:hover .edit-icon {
display: inline-flex;
}
`,
}),
render: this.render(),
};
}
setComponentProps(props) {
this.setProps('componentProps', { ...(this.props.componentProps || {}), ...props });
}
getComponentProps() {
return this.props.componentProps;
}
setDataSource(dataSource) {
this.setProps('componentProps', { ...(this.props.componentProps || {}), dataSource });
}
getDataSource() {
return this.props.componentProps.dataSource || [];
}
renderQuickEditButton(record) {
return (
<Tooltip title="快速编辑">
<EditOutlined
className="edit-icon"
onClick={async (e) => {
e.stopPropagation();
await QuickEditForm.open({
flowEngine: this.flowEngine,
collectionField: this.collectionField as CollectionField,
filterByTk: record.id,
});
await this.parent.resource.refresh();
}}
/>
</Tooltip>
);
}
render() {
return (value, record, index) => (
<>
{value}
{this.renderQuickEditButton(record)}
</>
);
}
}
TableColumnModel.define({
title: 'Table Column',
icon: 'TableColumn',
defaultOptions: {
use: 'TableColumnModel',
},
sort: 0,
});
TableColumnModel.registerFlow({
key: 'default',
auto: true,
steps: {
step1: {
handler(ctx, params) {
if (!params.fieldPath) {
return;
}
if (ctx.model.collectionField) {
return;
}
const field = ctx.globals.dataSourceManager.getCollectionField(params.fieldPath);
ctx.model.collectionField = field;
ctx.model.fieldPath = params.fieldPath;
ctx.model.setProps('title', field.title);
ctx.model.setProps('dataIndex', field.name);
},
},
},
});

View File

@ -19,8 +19,8 @@ import {
} from '@nocobase/flow-engine';
import { Button, Card, Space, Table } from 'antd';
import React from 'react';
import { ActionModel } from './ActionModel';
import { BlockFlowModel } from './BlockFlowModel';
import { ActionModel } from '../../base/ActionModel';
import { DataBlockModel } from '../../base/BlockModel';
import { TableColumnModel } from './TableColumnModel';
type S = {
@ -30,37 +30,15 @@ type S = {
};
};
function adjustColumnOrder(columns) {
const leftFixedColumns = [];
const normalColumns = [];
const rightFixedColumns = [];
columns.forEach((column) => {
if (column.fixed === 'left') {
leftFixedColumns.push(column);
} else if (column.fixed === 'right') {
rightFixedColumns.push(column);
} else {
normalColumns.push(column);
}
});
return [...leftFixedColumns, ...normalColumns, ...rightFixedColumns];
}
export class TableModel extends BlockFlowModel<S> {
collection: Collection;
resource: MultiRecordResource;
export class TableModel extends DataBlockModel<S> {
declare resource: MultiRecordResource;
getColumns() {
const columns = this.mapSubModels('columns', (column) => {
return this.mapSubModels('columns', (column) => {
return column.getColumnProps();
});
const addColumn = {
}).concat({
key: 'addColumn',
fixed: 'right',
width: 180,
title: (
<AddFieldButton
collection={this.collection}
@ -91,11 +69,7 @@ export class TableModel extends BlockFlowModel<S> {
}}
/>
),
};
// 加入后再排序
const allColumns = [...columns, addColumn];
return adjustColumnOrder(allColumns);
} as any);
}
render() {
@ -103,11 +77,7 @@ export class TableModel extends BlockFlowModel<S> {
<Card>
<Space style={{ marginBottom: 16 }}>
{this.mapSubModels('actions', (action) => (
<FlowModelRenderer
model={action}
showFlowSettings
extraContext={{ currentModel: this, currentResource: this.resource }}
/>
<FlowModelRenderer model={action} showFlowSettings sharedContext={{ currentBlockModel: this }} />
))}
<AddActionButton model={this} subModelBaseClass="ActionModel">
<Button icon={<SettingOutlined />}>Configure actions</Button>
@ -161,9 +131,6 @@ export class TableModel extends BlockFlowModel<S> {
this.resource.setPageSize(pagination.pageSize);
this.resource.refresh();
}}
scroll={{
x: 'max-content',
}}
/>
</Card>
);
@ -209,7 +176,7 @@ TableModel.registerFlow({
resource.setAPIClient(ctx.globals.api);
ctx.model.resource = resource;
await resource.refresh();
await ctx.model.applySubModelsAutoFlows('columns');
await ctx.model.applySubModelsAutoFlows('columns', null, { currentBlockModel: ctx.model });
},
},
},
@ -224,13 +191,6 @@ TableModel.define({
columns: [
{
use: 'TableActionsColumnModel',
subModels: {
actions: [
{
use: 'ActionModel',
},
],
},
},
],
},

View File

@ -6,14 +6,14 @@
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { toArr, isArr } from '@formily/shared';
import { isArr, toArr } from '@formily/shared';
import { getDefaultFormat, str2moment } from '@nocobase/utils/client';
import { Tag } from 'antd';
import { useCompile } from '../../../../../schema-component/hooks';
import { TableColumnModel } from '../../../TableColumnModel';
import { loadTitleFieldOptions } from '../../../common/utils';
import { getUniqueKeyFromCollection } from '../../../../../collection-manager/interfaces/utils';
import React from 'react';
import { getUniqueKeyFromCollection } from '../../../../../../collection-manager/interfaces/utils';
import { useCompile } from '../../../../../../schema-component/hooks';
import { loadTitleFieldOptions } from '../../../../common/utils';
import { TableColumnModel } from '../../TableColumnModel';
export function transformNestedData(inputData) {
const resultArray = [];
@ -125,9 +125,9 @@ export class AssociationSelectColumnFieldModel extends TableColumnModel {
{
<AssociationSelectReadPretty
{...this.getComponentProps()}
collectionField={this.field.options}
collectionField={this.collectionField.options}
value={value}
cm={this.field.collection.dataSource.collectionManager}
cm={this.collectionField.collection.dataSource.collectionManager}
/>
}
{this.renderQuickEditButton(record)}
@ -171,20 +171,20 @@ AssociationSelectColumnFieldModel.registerFlow({
},
},
defaultParams: (ctx) => {
const { target } = ctx.model.field.options;
const collectionManager = ctx.model.field.collection.collectionManager;
const { target } = ctx.model.collectionField.options;
const collectionManager = ctx.model.collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(target);
return {
label: ctx.model.getComponentProps().fieldNames?.label || targetCollection.options.titleField,
};
},
handler(ctx, params) {
const { target } = ctx.model.field.options;
const collectionManager = ctx.model.field.collection.collectionManager;
const { target } = ctx.model.collectionField.options;
const collectionManager = ctx.model.collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(target);
ctx.model.flowEngine.flowSettings.registerScopes({
loadTitleFieldOptions,
collectionField: ctx.model.field,
collectionField: ctx.model.collectionField,
dataSourceManager: ctx.app.dataSourceManager,
});
const filterKey = getUniqueKeyFromCollection(targetCollection.options as any);

View File

@ -7,10 +7,10 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React, { FC } from 'react';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Checkbox } from 'antd';
import { TableColumnModel } from '../../TableColumnModel';
import React, { FC } from 'react';
import { TableColumnModel } from '../TableColumnModel';
interface CheckboxReadPrettyProps {
showUnchecked?: boolean;

View File

@ -7,13 +7,13 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { TableColumnModel } from '../../TableColumnModel';
import { usePrefixCls } from '@formily/antd-v5/esm/__builtins__';
import { isArr } from '@formily/shared';
import { getDefaultFormat, str2moment } from '@nocobase/utils/client';
import cls from 'classnames';
import dayjs from 'dayjs';
import React from 'react';
import { TableColumnModel } from '../TableColumnModel';
const ReadPretty = (props: any) => {
const { value, picker = 'date' } = props;

View File

@ -7,11 +7,11 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { useForm } from '@formily/react';
import { Select } from 'antd';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { TableColumnModel } from '../../TableColumnModel';
import { TableColumnModel } from '../TableColumnModel';
import { InputNumberReadPretty } from '../components/InputNumberReadPretty';
export class NumberColumnFieldModel extends TableColumnModel {
@ -136,8 +136,8 @@ NumberColumnFieldModel.registerFlow({
},
defaultParams: (ctx) => {
const { formatStyle, unitConversion, unitConversionType, separator, step, addonBefore, addonAfter } =
ctx.model.getComponentProps();
const { step: prescition } = ctx.model.field?.getComponentProps() || {};
ctx.model.getProps().componentProps;
const { step: prescition } = ctx.model.collectionField?.getComponentProps() || {};
return {
formatStyle: formatStyle || 'normal',
unitConversion,
@ -150,7 +150,7 @@ NumberColumnFieldModel.registerFlow({
},
handler(ctx, params) {
const { formatStyle, unitConversion, unitConversionType, separator, step, addonBefore, addonAfter } = params;
const { step: prescition } = ctx.model.field?.getComponentProps() || {};
const { step: prescition } = ctx.model.collectionField?.getComponentProps() || {};
ctx.model.setComponentProps({
formatStyle: formatStyle || 'normal',
unitConversion,

View File

@ -7,10 +7,10 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { isNum } from '@formily/shared';
import * as math from 'mathjs';
import { TableColumnModel } from '../../TableColumnModel';
import React from 'react';
import { TableColumnModel } from '../TableColumnModel';
import { InputNumberReadPretty } from '../components/InputNumberReadPretty';
const isNumberLike = (index: any): index is number => isNum(index) || /^-?\d+(\.\d+)?$/.test(index);

View File

@ -0,0 +1,46 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Tag } from 'antd';
import React, { FC } from 'react';
import { TableColumnModel } from '../TableColumnModel';
const ReadPretty: FC<any> = (props) => {
const { value, dataSource } = props;
if (!value) {
return;
}
return (
<div>
{dataSource
.filter((option) => option.value == value)
.map((option, key) => (
<Tag key={key} color={option.color} icon={option.icon}>
{option.label}
</Tag>
))}
</div>
);
};
export class RadioGroupReadPrettyFieldModel extends TableColumnModel {
public static readonly supportedFieldInterfaces = ['radioGroup'];
render() {
return (value, record, index) => {
return (
<>
{<ReadPretty value={value} {...this.getComponentProps()} />}
{this.renderQuickEditButton(record)}
</>
);
};
}
}

View File

@ -7,9 +7,9 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { Tag } from 'antd';
import { TableColumnModel } from '../../TableColumnModel';
import React from 'react';
import { TableColumnModel } from '../TableColumnModel';
import { getCurrentOptions } from '../utils/utils';
const fieldNames = {

View File

@ -7,6 +7,6 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { DefaultStructure, FlowModel } from '@nocobase/flow-engine';
import { ActionModel } from '../../base/ActionModel';
export class BlockFlowModel<T = DefaultStructure> extends FlowModel<T> {}
export class FilterFormActionModel extends ActionModel {}

View File

@ -0,0 +1,15 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormFieldModel } from '../../data-blocks/form/fields/FormFieldModel';
// null 表示不支持任何字段接口,* 表示支持所有字段接口
export type SupportedFieldInterfaces = string[] | '*' | null;
export class FilterFormFieldModel extends FormFieldModel {}

View File

@ -0,0 +1,112 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FormButtonGroup, FormLayout } from '@formily/antd-v5';
import { createForm, Form } from '@formily/core';
import { FormProvider } from '@formily/react';
import { AddActionButton, AddFieldButton, Collection, FlowModelRenderer } from '@nocobase/flow-engine';
import { Card } from 'antd';
import React from 'react';
import { FilterBlockModel } from '../../base/BlockModel';
import { FilterFormFieldModel } from './FilterFormFieldModel';
export class FilterFormModel extends FilterBlockModel {
form: Form;
collection: Collection;
render() {
return (
<Card>
<FormProvider form={this.form}>
<FormLayout layout={'vertical'}>
{this.mapSubModels('fields', (field) => (
<FlowModelRenderer model={field} showFlowSettings sharedContext={{ currentBlockModel: this }} />
))}
</FormLayout>
<AddFieldButton
buildCreateModelOptions={(field, fieldClass) => ({
use: fieldClass.name,
stepParams: {
default: {
step1: {
fieldPath: `${field.collection.dataSource.name}.${field.collection.name}.${field.name}`,
},
},
},
})}
onModelAdded={async (fieldModel: FilterFormFieldModel) => {
const fieldInfo = fieldModel.stepParams?.field;
if (fieldInfo && typeof fieldInfo.name === 'string') {
// 如果需要设置 collectionField可以从 collection 中获取
const fields = this.collection.getFields();
const field = fields.find((f) => f.name === fieldInfo.name);
if (field) {
fieldModel.collectionField = field;
}
}
}}
subModelKey="fields"
model={this}
collection={this.collection}
subModelBaseClass="FilterFormFieldModel"
/>
<FormButtonGroup>
{this.mapSubModels('actions', (action) => (
<FlowModelRenderer model={action} showFlowSettings sharedContext={{ currentBlockModel: this }} />
))}
<AddActionButton model={this} subModelBaseClass="FilterFormActionModel" />
</FormButtonGroup>
</FormProvider>
</Card>
);
}
}
FilterFormModel.registerFlow({
key: 'default',
auto: true,
steps: {
step1: {
paramsRequired: true,
hideInSettings: true,
uiSchema: {
dataSourceKey: {
type: 'string',
title: 'Data Source Key',
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-component-props': {
placeholder: 'Enter data source key',
},
},
collectionName: {
type: 'string',
title: 'Collection Name',
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-component-props': {
placeholder: 'Enter collection name',
},
},
},
defaultParams: {
dataSourceKey: 'main',
},
async handler(ctx, params) {
ctx.model.form = ctx.extra.form || createForm();
if (!ctx.model.collection) {
ctx.model.collection = ctx.globals.dataSourceManager.getCollection(
params.dataSourceKey,
params.collectionName,
);
}
},
},
},
});

View File

@ -0,0 +1,45 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FlowEngine, MultiRecordResource } from '@nocobase/flow-engine';
import { ButtonProps } from 'antd';
import { DataBlockModel } from '../../base/BlockModel';
import { FilterFormActionModel } from './FilterFormActionModel';
export class FilterFormResetActionModel extends FilterFormActionModel {
defaultProps: ButtonProps = {
children: 'Reset',
};
}
FilterFormResetActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
async handler(ctx, params) {
if (!ctx.shared?.currentBlockModel?.form) {
ctx.globals.message.error('No form available for reset.');
return;
}
const currentBlockModel = ctx.shared.currentBlockModel;
await currentBlockModel.form.reset();
const flowEngine = ctx.globals.flowEngine as FlowEngine;
flowEngine.forEachModel((model: DataBlockModel) => {
if (model.resource && model?.collection?.name === currentBlockModel.collection.name) {
(model.resource as MultiRecordResource).removeFilterGroup(currentBlockModel.uid);
(model.resource as MultiRecordResource).refresh();
}
});
},
},
},
});

View File

@ -0,0 +1,48 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { FlowEngine, MultiRecordResource } from '@nocobase/flow-engine';
import type { ButtonProps, ButtonType } from 'antd/es/button';
import { ActionModel } from '../../base/ActionModel';
import { DataBlockModel } from '../../base/BlockModel';
import { FilterFormActionModel } from './FilterFormActionModel';
export class FilterFormSubmitActionModel extends FilterFormActionModel {
defaultProps: ButtonProps = {
children: 'Filter',
type: 'primary',
};
}
FilterFormSubmitActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
step1: {
async handler(ctx, params) {
if (!ctx.shared?.currentBlockModel?.form) {
ctx.globals.message.error('No form available for submission.');
return;
}
const currentBlockModel = ctx.shared.currentBlockModel;
await currentBlockModel.form.submit();
const values = currentBlockModel.form.values;
const flowEngine = ctx.globals.flowEngine as FlowEngine;
flowEngine.forEachModel((model: DataBlockModel) => {
if (model.resource && model?.collection?.name === currentBlockModel.collection.name) {
(model.resource as MultiRecordResource).addFilterGroup(currentBlockModel.uid, values);
(model.resource as MultiRecordResource).refresh();
}
});
},
},
},
});

View File

@ -1,280 +0,0 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import React from 'react';
import { Select } from 'antd';
import { connect, mapReadPretty, mapProps } from '@formily/react';
import { FormFieldModel } from '../../../FormFieldModel';
import { loadTitleFieldOptions } from '../../../common/utils';
import { getUniqueKeyFromCollection } from '../../../../../collection-manager/interfaces/utils';
function toValue(record: any | any[], fieldNames, multiple = false) {
if (!record) return multiple ? [] : undefined;
const { label: labelKey, value: valueKey } = fieldNames;
const convert = (item: any) => {
if (typeof item !== 'object' || item === null) return undefined;
return {
label: item[labelKey],
value: item[valueKey],
};
};
if (multiple) {
if (!Array.isArray(record)) return [];
return record.map(convert).filter(Boolean);
}
return convert(record);
}
function LazySelect(props) {
const { fieldNames, value, multiple } = props;
return (
<Select
showSearch
labelInValue
{...props}
value={toValue(value, fieldNames, multiple)}
mode={multiple && 'multiple'}
onChange={(value, option) => {
props.onChange(option);
}}
/>
);
}
export const AssociationSelect = connect(
(props: any) => <LazySelect {...props} />,
mapProps({ dataSource: 'options' }),
mapReadPretty((props) => props.value),
);
export class AssociationSelectFieldModel extends FormFieldModel {
static supportedFieldInterfaces = ['m2m', 'm2o', 'o2o', 'o2m', 'oho', 'obo', 'updatedBy', 'createdBy'];
dataSource;
fieldNames: { label: string; value: string; color?: string; icon?: any };
optionsLoadState?: {
page: number;
pageSize: number;
loading: boolean;
hasMore: boolean;
searchText?: string;
};
set onPopupScroll(fn) {
this.field.setComponentProps({ onPopupScroll: fn });
}
set onDropdownVisibleChange(fn) {
this.field.setComponentProps({ onDropdownVisibleChange: fn });
}
set onSearch(fn) {
this.field.setComponentProps({ onSearch: fn });
}
setDataSource(dataSource) {
this.field.dataSource = dataSource;
}
getDataSource() {
return this.field.dataSource;
}
get component() {
return [AssociationSelect, {}];
}
}
export const DEFAULT_ASSOCIATION_PAGE_SIZE = 40;
async function fetchAssociationItems({ ctx, page = 1, searchText = '' }) {
const { target } = ctx.model.collectionField.options;
const fieldNames = ctx.model.field.componentProps.fieldNames;
const labelField = fieldNames?.label || 'id';
const apiClient = ctx.app.apiClient;
const collectionManager = ctx.model.collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(target);
const targetLabelField = targetCollection.getField(labelField);
const targetInterface = ctx.app.dataSourceManager.collectionFieldInterfaceManager.getFieldInterface(
targetLabelField.options.interface,
);
const operator = targetInterface?.filterable?.operators?.[0]?.value || '$includes';
const filter = searchText
? {
[labelField]: {
[operator]: searchText,
},
}
: undefined;
const response = await apiClient.request({
url: `/${target}:list`,
params: {
page,
pageSize: DEFAULT_ASSOCIATION_PAGE_SIZE,
filter,
},
});
return response.data?.data || [];
}
//初始化
AssociationSelectFieldModel.registerFlow({
key: 'init',
auto: true,
sort: 100,
steps: {
step1: {
handler(ctx) {
ctx.model.onDropdownVisibleChange = (open) => {
ctx.model.dispatchEvent('dropdownOpen', {
apiClient: ctx.app.apiClient,
field: ctx.model.field,
form: ctx.model.form,
});
};
ctx.model.onPopupScroll = (e) => {
ctx.model.dispatchEvent('popupScroll', {
event: e,
apiClient: ctx.app.apiClient,
field: ctx.model.field,
});
};
ctx.model.onSearch = (searchText) => {
ctx.model.dispatchEvent('search', {
searchText,
apiClient: ctx.app.apiClient,
field: ctx.model.field,
});
};
},
},
},
});
// 下拉打开加载第一页数据
AssociationSelectFieldModel.registerFlow({
key: 'dropdownOpen',
on: { eventName: 'dropdownOpen' },
steps: {
step1: {
async handler(ctx) {
ctx.model.optionsLoadState = {
page: 1,
pageSize: DEFAULT_ASSOCIATION_PAGE_SIZE,
hasMore: true,
loading: false,
};
const data = await fetchAssociationItems({ ctx, page: 1 });
ctx.model.setDataSource(data);
},
},
},
});
// 滚动分页追加
AssociationSelectFieldModel.registerFlow({
key: 'popupScroll',
on: { eventName: 'popupScroll' },
steps: {
step1: {
async handler(ctx) {
const event = ctx.extra?.event;
if (!event?.target) return;
const { scrollTop, scrollHeight, clientHeight } = event.target;
// 只在接近底部时才触发加载
if (scrollTop + clientHeight < scrollHeight - 20) {
return;
}
const state = (ctx.model.optionsLoadState ||= {
page: 1,
pageSize: DEFAULT_ASSOCIATION_PAGE_SIZE,
hasMore: true,
loading: false,
});
if (state.loading || !state.hasMore) return;
state.loading = true;
try {
const nextPage = state.page + 1;
const data = await fetchAssociationItems({ ctx, page: nextPage, searchText: state.searchText || '' });
ctx.model.setDataSource([...ctx.model.getDataSource(), ...data]);
state.hasMore = data.length === state.pageSize;
if (state.hasMore) state.page = nextPage;
} finally {
state.loading = false;
}
},
},
},
});
//搜索数据
AssociationSelectFieldModel.registerFlow({
key: 'search',
on: { eventName: 'search' },
steps: {
step1: {
async handler(ctx) {
const searchText = ctx.extra.searchText?.trim();
ctx.model.optionsLoadState = {
page: 1,
pageSize: DEFAULT_ASSOCIATION_PAGE_SIZE,
hasMore: true,
loading: false,
searchText,
};
const data = await fetchAssociationItems({ ctx, page: 1, searchText });
ctx.model.setDataSource(data);
},
},
},
});
// 标题字段设置
AssociationSelectFieldModel.registerFlow({
key: 'fieldNames',
auto: true,
sort: 200,
steps: {
fieldNames: {
title: 'Title field',
uiSchema: {
label: {
'x-component': 'Select',
'x-decorator': 'FormItem',
'x-reactions': ['{{loadTitleFieldOptions(collectionField, dataSourceManager)}}'],
},
},
defaultParams: (ctx) => {
const { target } = ctx.model.collectionField.options;
const collectionManager = ctx.model.collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(target);
return {
label: ctx.model.field.componentProps.fieldNames?.label || targetCollection.options.titleField,
};
},
handler(ctx, params) {
ctx.model.flowEngine.flowSettings.registerScopes({
loadTitleFieldOptions,
collectionField: ctx.model.collectionField,
dataSourceManager: ctx.app.dataSourceManager,
});
const { target } = ctx.model.collectionField.options;
const collectionManager = ctx.model.collectionField.collection.collectionManager;
const targetCollection = collectionManager.getCollection(target);
const newFieldNames = {
...ctx.model.field.componentProps.fieldNames,
value: getUniqueKeyFromCollection(targetCollection.options as any),
label: params.label || targetCollection.options.titleField,
};
ctx.model.field.setComponentProps({ fieldNames: newFieldNames });
},
},
},
});

View File

@ -1,44 +0,0 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { DatePicker } from '@formily/antd-v5';
import { FormFieldModel } from '../../../FormFieldModel';
export class DateTimeFieldModel extends FormFieldModel {
setComponentProps(componentProps) {
let { dateFormat, timeFormat } = componentProps || {};
if (!componentProps.format && (dateFormat || timeFormat)) {
if (!dateFormat) {
dateFormat = this.field.componentProps?.dateFormat || 'YYYY-MM-DD';
}
if (!timeFormat) {
timeFormat = this.field.componentProps?.timeFormat || 'HH:mm:ss';
}
componentProps.format = componentProps?.showTime ? `${dateFormat} ${timeFormat}` : dateFormat;
}
super.setComponentProps({
...componentProps,
});
}
get component() {
return [DatePicker, {}];
}
}
DateTimeFieldModel.registerFlow({
key: 'key3',
auto: true,
sort: 1000,
title: 'Specific properties',
steps: {
dateFormat: {
use: 'dateDisplayFormat',
title: 'Date display format',
},
},
});

View File

@ -7,23 +7,31 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
export * from './ActionModel';
export * from './AddNewActionModel';
export * from './BlockFlowModel';
export * from './BlockGridFlowModel';
export * from './BulkDeleteActionModel';
export * from './CalendarBlockFlowModel';
export * from './DeleteActionModel';
export * from './FormFieldModel';
export * from './FormModel';
export * from './HtmlBlockFlowModel';
export * from './LinkActionModel';
export * from './PageFlowModel';
export * from './PageTabFlowModel';
export * from './QuickEditForm';
export * from './SubmitActionModel';
export * from './TableColumnModel';
export * from './TableModel';
export * from './ViewActionModel';
export * from './form/fields';
export * from './table/fields';
export * from './actions/AddNewActionModel';
export * from './actions/BulkDeleteActionModel';
export * from './actions/DeleteActionModel';
export * from './actions/FilterActionModel';
export * from './actions/LinkActionModel';
export * from './actions/RefreshActionModel';
export * from './actions/ViewActionModel';
export * from './base/ActionModel';
export * from './base/BlockModel';
export * from './base/GridModel';
export * from './base/PageModel';
export * from './base/PageTabModel';
export * from './data-blocks/calendar/CalendarBlockModel';
export * from './data-blocks/form/fields';
export * from './data-blocks/form/FormActionModel';
export * from './data-blocks/form/FormModel';
export * from './data-blocks/form/QuickEditForm';
export * from './data-blocks/table/fields';
export * from './data-blocks/table/TableActionsColumnModel';
export * from './data-blocks/table/TableColumnModel';
export * from './data-blocks/table/TableModel';
export * from './filter-blocks/form/FilterFormActionModel';
export * from './filter-blocks/form/FilterFormFieldModel';
export * from './filter-blocks/form/FilterFormModel';
export * from './filter-blocks/form/FilterFormResetActionModel';
export * from './filter-blocks/form/FilterFormSubmitActionModel';
export * from './other-blocks/html/HtmlBlockModel';
//

View File

@ -9,7 +9,7 @@
import { Card } from 'antd';
import React, { createRef } from 'react';
import { BlockFlowModel } from './BlockFlowModel';
import { BlockModel } from '../../base/BlockModel';
function waitForRefCallback<T extends HTMLElement>(ref: React.RefObject<T>, cb: (el: T) => void, timeout = 3000) {
const start = Date.now();
@ -21,7 +21,7 @@ function waitForRefCallback<T extends HTMLElement>(ref: React.RefObject<T>, cb:
check();
}
export class HtmlBlockFlowModel extends BlockFlowModel {
export class HtmlBlockModel extends BlockModel {
ref = createRef<HTMLDivElement>();
render() {
return (
@ -33,11 +33,11 @@ export class HtmlBlockFlowModel extends BlockFlowModel {
}
}
HtmlBlockFlowModel.define({
HtmlBlockModel.define({
title: 'HTML',
group: 'Content',
defaultOptions: {
use: 'HtmlBlockFlowModel',
use: 'HtmlBlockModel',
stepParams: {
default: {
step1: {
@ -49,7 +49,7 @@ HtmlBlockFlowModel.define({
},
});
HtmlBlockFlowModel.registerFlow({
HtmlBlockModel.registerFlow({
key: 'default',
auto: true,
steps: {

View File

@ -115,7 +115,7 @@ export const FlowPageMenuItem = () => {
export function getFlowPageMenuSchema({ pageSchemaUid, tabSchemaUid, tabSchemaName }) {
return {
type: 'void',
'x-component': 'FlowPage',
'x-component': 'FlowRoute',
'x-uid': pageSchemaUid,
};
}

View File

@ -10,7 +10,7 @@
export enum NocoBaseDesktopRouteType {
group = 'group',
page = 'page',
flowPage = 'flowPage',
flowRoute = 'flowRoute',
link = 'link',
tabs = 'tabs',
}

View File

@ -7,11 +7,11 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Button } from 'antd';
import React, { useMemo } from 'react';
import { AddSubModelButton, SubModelItemsType, mergeSubModelItems } from './AddSubModelButton';
import { FlowModel } from '../../models/flowModel';
import { ModelConstructor } from '../../types';
import { Button } from 'antd';
import { AddSubModelButton, SubModelItemsType, mergeSubModelItems } from './AddSubModelButton';
import { createBlockItems } from './blockItems';
interface AddBlockButtonProps {
@ -75,7 +75,7 @@ interface AddBlockButtonProps {
*/
export const AddBlockButton: React.FC<AddBlockButtonProps> = ({
model,
subModelBaseClass = 'BlockFlowModel',
subModelBaseClass = 'BlockModel',
subModelKey = 'blocks',
children = <Button>Add block</Button>,
subModelType = 'array',

View File

@ -184,6 +184,10 @@ export class FlowEngine {
return this.modelInstances.get(uid) as T | undefined;
}
forEachModel<T extends FlowModel = FlowModel>(callback: (model: T) => void): void {
this.modelInstances.forEach(callback);
}
/**
*
* @param {string} uid Model

View File

@ -58,7 +58,10 @@ export class FlowModel<Structure extends { parent?: any; subModels?: any } = Def
* key fork fork
*/
private forkCache: Map<string, ForkFlowModel<any>> = new Map();
// model 树的共享运行上下文
/**
* model
*/
private _sharedContext: Record<string, any> = {};
constructor(options: FlowModelOptions<Structure>) {
@ -95,6 +98,10 @@ export class FlowModel<Structure extends { parent?: any; subModels?: any } = Def
onInit(options): void {}
get async() {
return this._options.async || false;
}
static get meta() {
return modelMetas.get(this);
}
@ -625,9 +632,14 @@ export class FlowModel<Structure extends { parent?: any; subModels?: any } = Def
return this.flowEngine.createModel(options);
}
async applySubModelsAutoFlows<K extends keyof Structure['subModels'], R>(subKey: K, extra?: Record<string, any>) {
async applySubModelsAutoFlows<K extends keyof Structure['subModels'], R>(
subKey: K,
extra?: Record<string, any>,
shared?: Record<string, any>,
) {
await Promise.all(
this.mapSubModels(subKey, async (column) => {
column.setSharedContext(shared);
await column.applyAutoFlows(extra);
}),
);
@ -726,11 +738,21 @@ export class FlowModel<Structure extends { parent?: any; subModels?: any } = Def
});
}
get ctx() {
return {
globals: this.flowEngine.getContext(),
shared: this.getSharedContext(),
};
}
public setSharedContext(ctx: Record<string, any>) {
this._sharedContext = ctx;
}
public getSharedContext() {
if (this.async || !this.parent) {
return this._sharedContext;
}
return {
...this.parent?.getSharedContext(),
...this._sharedContext, // 当前实例的 context 优先级最高

View File

@ -7,191 +7,216 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { action, define, observable } from '@formily/reactive';
import type { IModelComponentProps } from '../types';
import { FlowModel } from './flowModel';
/**
* ForkFlowModel FlowModel
* - master FlowModel
* - props (localProps) master
* - this fork master
* - 使 Object.create this.constructor
* - setter this fork
* - FlowEngine.modelInstances uid master
*/
export class ForkFlowModel<TMaster extends FlowModel = FlowModel> {
/** 与 master 相同的 UID用于日志调试 */
public readonly uid: string;
/** 调试标识,便于在日志或断言中快速识别 */
public readonly isFork = true;
/** 本地覆盖的 propsfork 层面的 UI/状态 */
public localProps: IModelComponentProps;
/** master 引用 */
private master: TMaster;
/** 是否已被释放 */
private disposed = false;
/** fork 在 master.forks 中的索引 */
public readonly forkId: number;
constructor(master: TMaster, initialProps: IModelComponentProps = {}, forkId = 0) {
this.master = master;
this.uid = master.uid;
this.localProps = { ...initialProps };
this.forkId = forkId;
define(this, {
localProps: observable,
setProps: action,
});
// 返回代理对象,实现自动透传
return new Proxy(this, {
get: (target: any, prop: PropertyKey, receiver: any) => {
// disposed check
if (prop === 'disposed') return target.disposed;
// 特殊处理 constructor应该返回 master 的 constructor
if (prop === 'constructor') {
return target.master.constructor;
}
if (prop === 'props') {
// 对 props 做合并返回
return { ...target.master.getProps(), ...target.localProps };
}
// fork 自身属性 / 方法优先
if (prop in target) {
return Reflect.get(target, prop, receiver);
}
// 默认取 master 上的值
const value = (target.master as any)[prop];
// 如果是函数,需要绑定到 fork 实例,让 this 指向 fork
// 使用闭包捕获正确的 constructor避免异步方法中的竞态条件
if (typeof value === 'function') {
const masterConstructor = target.master.constructor;
return function (this: any, ...args: any[]) {
// 创建一个临时的 this 对象,包含正确的 constructor
const contextThis = Object.create(this);
Object.defineProperty(contextThis, 'constructor', {
value: masterConstructor,
configurable: true,
enumerable: false,
writable: false,
});
return value.apply(contextThis, args);
}.bind(receiver);
}
return value;
},
set: (target: any, prop: PropertyKey, value: any, receiver: any) => {
if (prop === 'props') {
return true;
}
// 如果 fork 自带字段,则写到自身(例如 localProps
if (prop in target) {
return Reflect.set(target, prop, value, receiver);
}
// 其余写入 master但需要确保 setter 中的 this 指向 fork
// 检查 master 上是否有对应的 setter
const descriptor = this.getPropertyDescriptor(target.master, prop);
if (descriptor && descriptor.set) {
// 如果有 setter直接用 receiverfork 实例)作为 this 调用
// 这样 setter 中的 this 就指向 fork可以正确调用 fork 的方法
descriptor.set.call(receiver, value);
return true;
} else {
// 没有 setter直接赋值到 master
(target.master as any)[prop] = value;
return true;
}
},
});
}
/**
*
*/
private getPropertyDescriptor(obj: any, prop: PropertyKey): PropertyDescriptor | undefined {
let current = obj;
while (current) {
const descriptor = Object.getOwnPropertyDescriptor(current, prop);
if (descriptor) {
return descriptor;
}
current = Object.getPrototypeOf(current);
}
return undefined;
}
/**
* props fork
*/
setProps(key: string | IModelComponentProps, value?: any): void {
if (this.disposed) return;
if (typeof key === 'string') {
this.localProps[key] = value;
} else {
this.localProps = { ...this.localProps, ...key };
}
}
/**
* render 使 master props
*/
render() {
if (this.disposed) return null;
// 将 master.render 以 fork 作为 this 调用,使其读取到合并后的 props
const mergedProps = { ...this.master.getProps(), ...this.localProps };
// 临时替换 this.props
const originalProps = (this as any).props;
(this as any).props = mergedProps;
try {
return (this.master.render as any).call(this);
} finally {
(this as any).props = originalProps;
}
}
/**
* fork master.forks
*/
dispose() {
if (this.disposed) return;
this.disposed = true;
if (this.master && (this.master as any).forks) {
(this.master as any).forks.delete(this as any);
}
// 从 master 的 forkCache 中移除自己
if (this.master && (this.master as any).forkCache) {
const forkCache = (this.master as any).forkCache;
for (const [key, fork] of forkCache.entries()) {
if (fork === this) {
forkCache.delete(key);
break;
}
}
}
// @ts-ignore
this.master = null;
}
/**
* propsmaster + localPropslocal
*/
getProps(): IModelComponentProps {
return { ...this.master.getProps(), ...this.localProps };
}
}
// 类型断言:让 ForkFlowModel 可以被当作 FlowModel 使用
export interface ForkFlowModel<TMaster extends FlowModel = FlowModel> extends FlowModel {}
import { action, define, observable } from '@formily/reactive';
import type { IModelComponentProps } from '../types';
import { FlowModel } from './flowModel';
/**
* ForkFlowModel FlowModel
* - master FlowModel
* - props (localProps) master
* - this fork master
* - 使 Object.create this.constructor
* - setter this fork
* - FlowEngine.modelInstances uid master
*/
export class ForkFlowModel<TMaster extends FlowModel = FlowModel> {
/** 与 master 相同的 UID用于日志调试 */
public readonly uid: string;
/** 调试标识,便于在日志或断言中快速识别 */
public readonly isFork = true;
/** 本地覆盖的 propsfork 层面的 UI/状态 */
public localProps: IModelComponentProps;
/** master 引用 */
private master: TMaster;
/** 是否已被释放 */
private disposed = false;
/** fork 在 master.forks 中的索引 */
public readonly forkId: number;
/** 用于共享上下文的对象,存储跨 fork 的共享数据 */
// private _sharedContext: Record<string, any> = {};
constructor(master: TMaster, initialProps: IModelComponentProps = {}, forkId = 0) {
this.master = master;
this.uid = master.uid;
this.localProps = { ...initialProps };
this.forkId = forkId;
define(this, {
localProps: observable,
setProps: action,
});
// 返回代理对象,实现自动透传
return new Proxy(this, {
get: (target: any, prop: PropertyKey, receiver: any) => {
// disposed check
if (prop === 'disposed') return target.disposed;
// 特殊处理 constructor应该返回 master 的 constructor
if (prop === 'constructor') {
return target.master.constructor;
}
if (prop === 'props') {
// 对 props 做合并返回
return { ...target.master.getProps(), ...target.localProps };
}
// fork 自身属性 / 方法优先
if (prop in target) {
return Reflect.get(target, prop, receiver);
}
// 默认取 master 上的值
const value = (target.master as any)[prop];
// 如果是函数,需要绑定到 fork 实例,让 this 指向 fork
// 使用闭包捕获正确的 constructor避免异步方法中的竞态条件
if (typeof value === 'function') {
const masterConstructor = target.master.constructor;
return function (this: any, ...args: any[]) {
// 创建一个临时的 this 对象,包含正确的 constructor
const contextThis = Object.create(this);
Object.defineProperty(contextThis, 'constructor', {
value: masterConstructor,
configurable: true,
enumerable: false,
writable: false,
});
return value.apply(contextThis, args);
}.bind(receiver);
}
return value;
},
set: (target: any, prop: PropertyKey, value: any, receiver: any) => {
if (prop === 'props') {
return true;
}
// 如果 fork 自带字段,则写到自身(例如 localProps
if (prop in target) {
return Reflect.set(target, prop, value, receiver);
}
// 其余写入 master但需要确保 setter 中的 this 指向 fork
// 检查 master 上是否有对应的 setter
const descriptor = this.getPropertyDescriptor(target.master, prop);
if (descriptor && descriptor.set) {
// 如果有 setter直接用 receiverfork 实例)作为 this 调用
// 这样 setter 中的 this 就指向 fork可以正确调用 fork 的方法
descriptor.set.call(receiver, value);
return true;
} else {
// 没有 setter直接赋值到 master
(target.master as any)[prop] = value;
return true;
}
},
});
}
public setSharedContext(ctx: Record<string, any>) {
this['_sharedContext'] = ctx;
}
public getSharedContext() {
if (this.async || !this.parent) {
return this['_sharedContext'] || {};
}
return {
...this.parent?.getSharedContext(),
...this['_sharedContext'], // 当前实例的 context 优先级最高
};
}
get ctx() {
return {
globals: this.flowEngine.getContext(),
shared: this.getSharedContext(),
};
}
/**
*
*/
private getPropertyDescriptor(obj: any, prop: PropertyKey): PropertyDescriptor | undefined {
let current = obj;
while (current) {
const descriptor = Object.getOwnPropertyDescriptor(current, prop);
if (descriptor) {
return descriptor;
}
current = Object.getPrototypeOf(current);
}
return undefined;
}
/**
* props fork
*/
setProps(key: string | IModelComponentProps, value?: any): void {
if (this.disposed) return;
if (typeof key === 'string') {
this.localProps[key] = value;
} else {
this.localProps = { ...this.localProps, ...key };
}
}
/**
* render 使 master props
*/
render() {
if (this.disposed) return null;
// 将 master.render 以 fork 作为 this 调用,使其读取到合并后的 props
const mergedProps = { ...this.master.getProps(), ...this.localProps };
// 临时替换 this.props
const originalProps = (this as any).props;
(this as any).props = mergedProps;
try {
return (this.master.render as any).call(this);
} finally {
(this as any).props = originalProps;
}
}
/**
* fork master.forks
*/
dispose() {
if (this.disposed) return;
this.disposed = true;
if (this.master && (this.master as any).forks) {
(this.master as any).forks.delete(this as any);
}
// 从 master 的 forkCache 中移除自己
if (this.master && (this.master as any).forkCache) {
const forkCache = (this.master as any).forkCache;
for (const [key, fork] of forkCache.entries()) {
if (fork === this) {
forkCache.delete(key);
break;
}
}
}
// @ts-ignore
this.master = null;
}
/**
* propsmaster + localPropslocal
*/
getProps(): IModelComponentProps {
return { ...this.master.getProps(), ...this.localProps };
}
}
// 类型断言:让 ForkFlowModel 可以被当作 FlowModel 使用
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ForkFlowModel<TMaster extends FlowModel = FlowModel> extends FlowModel {}

View File

@ -31,6 +31,8 @@ export abstract class BaseRecordResource<TData = any> extends APIResource<TData>
headers: {} as Record<string, any>,
};
protected filterGroups = new Map<string, any>();
protected splitValue(value: string | string[]): string[] {
if (typeof value === 'string') {
return value.split(',').map((item) => item.trim());
@ -100,11 +102,27 @@ export abstract class BaseRecordResource<TData = any> extends APIResource<TData>
}
setFilter(filter: Record<string, any>) {
return this.addRequestParameter('filter', filter);
return this.addRequestParameter('filter', JSON.stringify(filter));
}
getFilter(): Record<string, any> {
return this.request.params.filter;
return {
$and: [...this.filterGroups.values()].filter(Boolean),
};
}
resetFilter() {
this.setFilter(this.getFilter());
}
addFilterGroup(key: string, filter) {
this.filterGroups.set(key, filter);
this.resetFilter();
}
removeFilterGroup(key: string) {
this.filterGroups.delete(key);
this.resetFilter();
}
setAppends(appends: string[]) {

View File

@ -285,6 +285,7 @@ export interface DefaultStructure {
*/
export interface FlowModelOptions<Structure extends { parent?: any; subModels?: any } = DefaultStructure> {
uid: string;
async?: boolean; // 是否异步加载模型
props?: IModelComponentProps;
stepParams?: Record<string, any>;
subModels?: Structure['subModels'];