Merge branch '2.0' into feat/actions-2.0

# Conflicts:
#	packages/core/client/src/flow/models/TableColumnModel.tsx
#	packages/core/client/src/flow/models/actions/BulkDeleteActionModel.tsx
#	packages/core/client/src/flow/models/actions/DeleteActionModel.tsx
#	packages/core/client/src/flow/models/actions/LinkActionModel.tsx
#	packages/core/client/src/flow/models/actions/ViewActionModel.tsx
#	packages/core/client/src/flow/models/base/ActionModel.tsx
#	packages/core/client/src/flow/models/index.ts
This commit is contained in:
chenos 2025-06-19 23:37:58 +08:00
commit 1f794f3a5f
52 changed files with 1198 additions and 902 deletions

View File

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

View File

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

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { FlowPageComponent } from '../FlowPage'; import { FlowPage } from '../FlowPage';
export const openModeAction = { export const openModeAction = {
title: '打开方式', title: '打开方式',
@ -39,7 +39,7 @@ export const openModeAction = {
function DrawerContent() { function DrawerContent() {
return ( return (
<div> <div>
<FlowPageComponent <FlowPage
parentId={ctx.model.uid} parentId={ctx.model.uid}
sharedContext={{ sharedContext={{
...ctx.extra, ...ctx.extra,

View File

@ -19,4 +19,4 @@ export const refreshOnCompleteAction = {
ctx.globals.message.success('Data refreshed successfully.'); ctx.globals.message.success('Data refreshed successfully.');
} }
}, },
} };

View File

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

View File

@ -1,106 +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 { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel';
export class DeleteActionModel extends ActionModel {
defaultProps: ButtonProps = {
type: 'link',
title: 'Delete',
};
}
DeleteActionModel.registerFlow({
key: 'handleClick',
title: '点击事件',
on: {
eventName: 'click',
},
steps: {
secondaryConfirmation: {
title: '二次确认',
uiSchema: {
enable: {
type: 'boolean',
title: 'Enable secondary confirmation',
default: true,
'x-decorator': 'FormItem',
'x-component': 'Checkbox',
},
title: {
type: 'string',
title: 'Title',
default: 'Delete record',
'x-decorator': 'FormItem',
'x-component': 'Input.TextArea',
},
content: {
type: 'string',
title: 'Content',
default: 'Are you sure you want to delete it?',
'x-decorator': 'FormItem',
'x-component': 'Input.TextArea',
},
},
defaultParams(ctx) {
return {
enable: true,
title: 'Delete record',
content: 'Are you sure you want to delete it?',
};
},
async handler(ctx, params) {
if (params.enable) {
const confirmed = await ctx.globals.modal.confirm({
title: params.title,
content: params.content,
});
if (!confirmed) {
ctx.exit();
}
}
},
},
delete: {
async handler(ctx, params) {
if (!ctx.extra.currentResource || !ctx.extra.currentRecord) {
ctx.globals.message.error('No resource or record selected for deletion.');
return;
}
await ctx.extra.currentResource.destroy(ctx.extra.currentRecord);
ctx.globals.message.success('Record deleted successfully.');
await ctx.extra.currentResource.refresh();
},
},
refresh: {
title: '执行后刷新数据',
uiSchema: {
enable: {
type: 'boolean',
title: 'Enable refresh',
'x-decorator': 'FormItem',
'x-component': 'Checkbox',
},
},
defaultParams(ctx) {
return {
enable: true,
};
},
async handler(ctx, params) {
if (params.enable) {
await ctx.extra.currentResource.refresh();
ctx.globals.message.success('Data refreshed successfully.');
}
},
},
},
});

View File

@ -1,112 +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 { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel';
import Variable from '../../schema-component/antd/variable/Variable';
import { css } from '@emotion/css';
export class LinkActionModel extends ActionModel {
defaultProps: ButtonProps = {
type: 'link',
title: 'Link',
};
}
LinkActionModel.registerFlow({
key: 'handleClick',
title: '点击事件',
on: {
eventName: 'click',
},
steps: {
navigate: {
title: '编辑链接',
uiSchema: {
url: {
title: 'URL',
'x-decorator': 'FormItem',
'x-component': Variable.TextArea,
description: 'Do not concatenate search params in the URL',
},
params: {
type: 'array',
'x-component': 'ArrayItems',
'x-decorator': 'FormItem',
title: `Search parameters`,
items: {
type: 'object',
properties: {
space: {
type: 'void',
'x-component': 'Space',
'x-component-props': {
style: {
flexWrap: 'nowrap',
maxWidth: '100%',
},
className: css`
& > .ant-space-item:first-child,
& > .ant-space-item:last-child {
flex-shrink: 0;
}
`,
},
properties: {
name: {
type: 'string',
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-component-props': {
placeholder: `{{t("Name")}}`,
},
},
value: {
type: 'string',
'x-decorator': 'FormItem',
'x-component': Variable.TextArea,
'x-component-props': {
placeholder: `{{t("Value")}}`,
useTypedConstant: true,
changeOnSelect: true,
},
},
remove: {
type: 'void',
'x-decorator': 'FormItem',
'x-component': 'ArrayItems.Remove',
},
},
},
},
},
properties: {
add: {
type: 'void',
title: 'Add parameter',
'x-component': 'ArrayItems.Addition',
},
},
},
openInNewWindow: {
type: 'boolean',
'x-content': 'Open in new window',
'x-decorator': 'FormItem',
'x-component': 'Checkbox',
},
},
handler(ctx, params) {
ctx.globals.modal.confirm({
title: `${ctx.extra.currentRecord?.id}`,
content: JSON.stringify(params, null, 2),
});
},
},
},
});

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,225 +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 } 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 {
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(),
};
}
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 {
// 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',
},
},
{
key: 'popup',
label: 'Popup',
createModelOptions: {
use: 'PopupActionModel',
},
},
{
key: 'edit',
label: 'Edit',
createModelOptions: {
use: 'EditActionModel',
},
},
{
key: 'edit',
label: 'Duplicate',
createModelOptions: {
use: 'DuplicateActionModel',
},
},
{
key: 'edit',
label: 'Custom Request',
createModelOptions: {
use: 'CustomRequestActionModel',
},
},
{
key: 'edit',
label: 'Update record',
createModelOptions: {
use: 'UpdateRecordActionModel',
},
},
]}
>
<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,
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('title', field.title);
ctx.model.setProps('dataIndex', field.name);
},
},
},
});

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

View File

@ -8,12 +8,12 @@
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel'; import { useGlobalVariable } from '../../../application/hooks/useGlobalVariable';
import { secondaryConfirmationAction } from '../actions/secondaryConfirmationAction'; import { BlocksSelector } from '../../../schema-component/antd/action/Action.Designer';
import { refreshOnCompleteAction } from '../actions/refreshOnCompleteAction'; import { useAfterSuccessOptions } from '../../../schema-component/antd/action/hooks/useGetAfterSuccessVariablesOptions';
import { useAfterSuccessOptions } from '../../schema-component/antd/action/hooks/useGetAfterSuccessVariablesOptions'; import { refreshOnCompleteAction } from '../../actions/refreshOnCompleteAction';
import { useGlobalVariable } from '../../application/hooks/useGlobalVariable'; import { secondaryConfirmationAction } from '../../actions/secondaryConfirmationAction';
import { BlocksSelector } from '../../schema-component/antd/action/Action.Designer'; import { ActionModel } from '../base/ActionModel';
export class CustomRequestActionModel extends ActionModel { export class CustomRequestActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {
@ -51,7 +51,8 @@ CustomRequestActionModel.registerFlow({
required: true, required: true,
title: 'HTTP method', title: 'HTTP method',
'x-decorator-props': { 'x-decorator-props': {
tooltip: 'When the HTTP method is Post, Put or Patch, and this custom request inside the form, the request body will be automatically filled in with the form data', tooltip:
'When the HTTP method is Post, Put or Patch, and this custom request inside the form, the request body will be automatically filled in with the form data',
}, },
'x-decorator': 'FormItem', 'x-decorator': 'FormItem',
'x-component': 'Select', 'x-component': 'Select',

View File

@ -0,0 +1,73 @@
/**
* 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 type { ButtonProps } from 'antd';
import { ActionModel } from '../base/ActionModel';
export class DeleteActionModel extends ActionModel {
defaultProps: ButtonProps = {
children: 'Delete',
type: 'link',
};
}
DeleteActionModel.registerFlow({
key: 'event1',
on: {
eventName: 'click',
},
steps: {
confirm: {
uiSchema: {
title: {
type: 'string',
title: 'Confirm title',
'x-decorator': 'FormItem',
'x-component': 'Input',
},
content: {
type: 'string',
title: 'Confirm content',
'x-decorator': 'FormItem',
'x-component': 'Input.TextArea',
},
},
defaultParams: {
title: 'Confirm Deletion',
content: 'Are you sure you want to delete this record?',
},
async handler(ctx, params) {
const confirmed = await ctx.globals.modal.confirm({
title: params.title,
content: params.content,
});
if (!confirmed) {
ctx.globals.message.info('Deletion cancelled.');
return ctx.exit();
}
},
},
step1: {
async handler(ctx, params) {
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;
}
const resource = ctx.shared.currentBlockModel.resource as MultiRecordResource;
await resource.destroy(ctx.extra.currentRecord);
ctx.globals.message.success('Record deleted successfully.');
},
},
},
});

View File

@ -8,11 +8,8 @@
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel'; import { openModeAction } from '../../actions/openModeAction';
import { openModeAction } from '../actions/openModeAction'; import { ActionModel } from '../base/ActionModel';
import { findFormBlock } from '../../block-provider/FormBlockProvider';
import { useMemo } from 'react';
import { useSyncFromForm } from '../../schema-settings/DataTemplates/utils';
export class DuplicateActionModel extends ActionModel { export class DuplicateActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {

View File

@ -8,8 +8,8 @@
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel'; import { openModeAction } from '../../actions/openModeAction';
import { openModeAction } from '../actions/openModeAction'; import { ActionModel } from '../base/ActionModel';
export class EditActionModel extends ActionModel { export class EditActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {

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,24 +7,24 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd';
import { ActionModel } from './ActionModel'; import { ActionModel } from '../base/ActionModel';
import { openModeAction } from '../actions/openModeAction';
export class ViewActionModel extends ActionModel { export class LinkActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {
type: 'link', type: 'link',
title: 'View', children: 'Link',
}; };
} }
ViewActionModel.registerFlow({ LinkActionModel.registerFlow({
key: 'handleClick', key: 'event1',
title: '点击事件',
on: { on: {
eventName: 'click', eventName: 'click',
}, },
steps: { steps: {
open: openModeAction, step1: {
handler(ctx, params) {},
},
}, },
}); });

View File

@ -8,8 +8,8 @@
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd/es/button';
import { ActionModel } from './ActionModel'; import { openModeAction } from '../../actions/openModeAction';
import { openModeAction } from '../actions/openModeAction'; import { ActionModel } from '../base/ActionModel';
export class PopupActionModel extends ActionModel { export class PopupActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {

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,11 +7,11 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd';
import { ActionModel } from './ActionModel'; import { afterSuccessAction } from '../../actions/afterSuccessAction';
import { secondaryConfirmationAction } from '../actions/secondaryConfirmationAction'; import { refreshOnCompleteAction } from '../../actions/refreshOnCompleteAction';
import { refreshOnCompleteAction } from '../actions/refreshOnCompleteAction'; import { secondaryConfirmationAction } from '../../actions/secondaryConfirmationAction';
import { afterSuccessAction } from '../actions/afterSuccessAction'; import { ActionModel } from '../base/ActionModel';
export class UpdateRecordActionModel extends ActionModel { export class UpdateRecordActionModel extends ActionModel {
defaultProps: ButtonProps = { defaultProps: ButtonProps = {

View File

@ -7,16 +7,19 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * 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 React from 'react';
import { FlowPageComponent } from '../FlowPage'; import { FlowPage } from '../../FlowPage';
import { ActionModel } from './ActionModel'; import { ActionModel } from '../base/ActionModel';
export class AddNewActionModel extends ActionModel { export class ViewActionModel extends ActionModel {
title = 'Add new'; defaultProps: ButtonProps = {
children: 'View',
type: 'link',
};
} }
AddNewActionModel.registerFlow({ ViewActionModel.registerFlow({
key: 'event1', key: 'event1',
on: { on: {
eventName: 'click', eventName: 'click',
@ -30,13 +33,20 @@ AddNewActionModel.registerFlow({
function DrawerContent() { function DrawerContent() {
return ( return (
<div> <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> </div>
); );
} }
currentDrawer = ctx.globals.drawer.open({ currentDrawer = ctx.globals.drawer.open({
title: '命令式 Drawer', // title: '命令式 Drawer',
width: 800, width: 800,
content: <DrawerContent />, content: <DrawerContent />,
}); });

View File

@ -11,62 +11,52 @@ import { FlowModel } from '@nocobase/flow-engine';
import { Button } from 'antd'; import { Button } from 'antd';
import type { ButtonProps } from 'antd/es/button'; import type { ButtonProps } from 'antd/es/button';
import React from 'react'; import React from 'react';
import IconPicker from '../../schema-component/antd/icon-picker/IconPicker';
import { Icon } from '../../icon/Icon';
export class ActionModel extends FlowModel { export class ActionModel extends FlowModel {
declare props: ButtonProps;
defaultProps: ButtonProps = { defaultProps: ButtonProps = {
type: 'default', type: 'default',
title: 'Action', children: 'Action',
}; };
render() { render() {
const props = { ...this.defaultProps, ...this.props };
const icon = <Icon type={props.icon as any} />;
return ( return (
<Button {...props} icon={icon}> <Button
{props.children || props.title} {...this.defaultProps}
</Button> {...this.props}
onClick={(event) => {
this.dispatchEvent('click', { event });
}}
/>
); );
} }
} }
ActionModel.registerFlow({ ActionModel.registerFlow({
key: 'default', key: 'default',
title: '通用配置',
auto: true, auto: true,
title: '基础',
sort: 100,
steps: { steps: {
buttonProps: { step1: {
title: '编辑按钮', title: '编辑按钮',
uiSchema: { uiSchema: {
title: { children: {
type: 'string',
title: '标题',
'x-decorator': 'FormItem', 'x-decorator': 'FormItem',
'x-component': 'Input', 'x-component': 'Input',
title: 'Button title', 'x-component-props': {
}, placeholder: '请输入标题',
icon: { },
'x-decorator': 'FormItem',
'x-component': IconPicker,
title: 'Button icon',
}, },
}, },
defaultParams(ctx) { defaultParams(ctx) {
return { return {
title: ctx.model.defaultProps.title, type: 'default',
icon: ctx.model.defaultProps.icon, ...ctx.model.defaultProps,
}; };
}, },
handler(ctx, params) { handler(ctx, params) {
ctx.model.setProps(params); ctx.model.setProps('children', params.children);
ctx.model.setProps('onClick', (event) => {
ctx.model.dispatchEvent('click', {
...ctx.extra,
event,
});
});
}, },
}, },
}, },

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 表示不支持任何字段接口,* 表示支持所有字段接口 // null 表示不支持任何字段接口,* 表示支持所有字段接口
export type SupportedFieldInterfaces = string[] | '*' | null; export type SupportedFieldInterfaces = string[] | '*' | null;
export class FieldFlowModel extends FlowModel { export class FieldModel extends FlowModel {
field: CollectionField; collectionField: CollectionField;
fieldPath: string; fieldPath: string;
public static readonly supportedFieldInterfaces: SupportedFieldInterfaces = null; 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 { Button, Card, Dropdown } from 'antd';
import _ from 'lodash'; import _ from 'lodash';
import React from 'react'; import React from 'react';
import { BlockFlowModel } from './BlockFlowModel'; import { BlockModel } from './BlockModel';
function Grid({ items }) { function Grid({ items }) {
return ( return (
@ -27,35 +27,24 @@ function Grid({ items }) {
); );
} }
// function AddBlockButton({ model }) { type GridModelStructure = {
// 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 = {
subModels: { subModels: {
items: BlockFlowModel[]; items: BlockModel[];
}; };
}; };
export class BlockGridFlowModel extends FlowModel<BlockGridFlowModelStructure> { export class GridModel extends FlowModel<GridModelStructure> {
subModelBaseClass = 'BlockModel';
render() { render() {
return ( return (
<div style={{ padding: 16 }}> <div style={{ padding: 16 }}>
<Grid items={this.subModels.items?.slice() || []} /> <Grid items={this.subModels.items?.slice() || []} />
<AddBlockButton model={this} subModelKey="items" /> <AddBlockButton model={this} subModelKey="items" subModelBaseClass={this.subModelBaseClass} />
</div> </div>
); );
} }
} }
export class BlockGridModel extends GridModel {
subModelBaseClass = 'BlockModel';
}

View File

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

View File

@ -7,22 +7,19 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
import { Application, Plugin } from '@nocobase/client'; import { Collection, MultiRecordResource } from '@nocobase/flow-engine';
import { Collection, FlowModel, MultiRecordResource } from '@nocobase/flow-engine';
import { Card, Modal } from 'antd'; import { Card, Modal } from 'antd';
import moment from 'moment'; 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 React from 'react';
import { Calendar, momentLocalizer } from 'react-big-calendar'; import { Calendar, momentLocalizer } from 'react-big-calendar';
import 'react-big-calendar/lib/css/react-big-calendar.css'; import 'react-big-calendar/lib/css/react-big-calendar.css';
import { BlockFlowModel } from './BlockFlowModel'; import { DataBlockModel } from '../../base/BlockModel';
const localizer = momentLocalizer(moment); const localizer = momentLocalizer(moment);
export class CalendarBlockFlowModel extends BlockFlowModel { export class CalendarBlockModel extends DataBlockModel {
collection: Collection; declare resource: MultiRecordResource;
resource: MultiRecordResource;
render() { render() {
const data = this.resource.getData(); const data = this.resource.getData();
return ( 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', key: 'key2',
on: { on: {
eventName: 'onSelectEvent', eventName: 'onSelectEvent',
@ -73,7 +78,7 @@ CalendarBlockFlowModel.registerFlow({
}, },
}); });
CalendarBlockFlowModel.registerFlow({ CalendarBlockModel.registerFlow({
key: 'key3', key: 'key3',
on: { on: {
eventName: 'onDoubleClickEvent', eventName: 'onDoubleClickEvent',
@ -97,7 +102,7 @@ CalendarBlockFlowModel.registerFlow({
}, },
}); });
CalendarBlockFlowModel.registerFlow({ CalendarBlockModel.registerFlow({
key: 'default', key: 'default',
auto: true, auto: true,
steps: { steps: {
@ -170,7 +175,7 @@ CalendarBlockFlowModel.registerFlow({
}, },
}, },
handler: async (ctx, params) => { 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('titleAccessor', params.titleAccessor);
ctx.model.setProps('startAccessor', params.startAccessor); ctx.model.setProps('startAccessor', params.startAccessor);
ctx.model.setProps('endAccessor', params.endAccessor); 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

@ -12,7 +12,7 @@ import { Field, Form } from '@formily/core';
import { FieldContext } from '@formily/react'; import { FieldContext } from '@formily/react';
import { CollectionField, FlowModel } from '@nocobase/flow-engine'; import { CollectionField, FlowModel } from '@nocobase/flow-engine';
import React from 'react'; import React from 'react';
import { ReactiveField } from '../Formily/ReactiveField'; import { ReactiveField } from '../../../formily/ReactiveField';
export class FormFieldModel extends FlowModel { export class FormFieldModel extends FlowModel {
collectionField: CollectionField; collectionField: CollectionField;

View File

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

View File

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

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,115 @@
/**
* 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(),
};
}
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

@ -10,6 +10,7 @@
import { SettingOutlined } from '@ant-design/icons'; import { SettingOutlined } from '@ant-design/icons';
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import { import {
AddActionButton,
AddActionModel, AddActionModel,
AddFieldButton, AddFieldButton,
Collection, Collection,
@ -18,8 +19,8 @@ import {
} from '@nocobase/flow-engine'; } from '@nocobase/flow-engine';
import { Button, Card, Space, Table } from 'antd'; import { Button, Card, Space, Table } from 'antd';
import React from 'react'; import React from 'react';
import { ActionModel } from './ActionModel'; import { ActionModel } from '../../base/ActionModel';
import { BlockFlowModel } from './BlockFlowModel'; import { DataBlockModel } from '../../base/BlockModel';
import { TableColumnModel } from './TableColumnModel'; import { TableColumnModel } from './TableColumnModel';
type S = { type S = {
@ -29,9 +30,8 @@ type S = {
}; };
}; };
export class TableModel extends BlockFlowModel<S> { export class TableModel extends DataBlockModel<S> {
collection: Collection; declare resource: MultiRecordResource;
resource: MultiRecordResource;
getColumns() { getColumns() {
return this.mapSubModels('columns', (column) => { return this.mapSubModels('columns', (column) => {
@ -77,13 +77,12 @@ export class TableModel extends BlockFlowModel<S> {
<Card> <Card>
<Space style={{ marginBottom: 16 }}> <Space style={{ marginBottom: 16 }}>
{this.mapSubModels('actions', (action) => ( {this.mapSubModels('actions', (action) => (
<FlowModelRenderer <FlowModelRenderer model={action} showFlowSettings sharedContext={{ currentBlockModel: this }} />
model={action}
showFlowSettings
extraContext={{ currentModel: this, currentResource: this.resource }}
/>
))} ))}
<AddActionModel <AddActionButton model={this} subModelBaseClass="ActionModel">
<Button icon={<SettingOutlined />}>Configure actions</Button>
</AddActionButton>
{/* <AddActionModel
model={this} model={this}
subModelKey={'actions'} subModelKey={'actions'}
items={() => [ items={() => [
@ -104,7 +103,7 @@ export class TableModel extends BlockFlowModel<S> {
]} ]}
> >
<Button icon={<SettingOutlined />}>Configure actions</Button> <Button icon={<SettingOutlined />}>Configure actions</Button>
</AddActionModel> </AddActionModel> */}
</Space> </Space>
<Table <Table
className={css` className={css`
@ -177,7 +176,7 @@ TableModel.registerFlow({
resource.setAPIClient(ctx.globals.api); resource.setAPIClient(ctx.globals.api);
ctx.model.resource = resource; ctx.model.resource = resource;
await resource.refresh(); await resource.refresh();
await ctx.model.applySubModelsAutoFlows('columns'); await ctx.model.applySubModelsAutoFlows('columns', null, { currentBlockModel: ctx.model });
}, },
}, },
}, },
@ -192,13 +191,6 @@ TableModel.define({
columns: [ columns: [
{ {
use: 'TableActionsColumnModel', use: 'TableActionsColumnModel',
subModels: {
actions: [
{
use: 'ActionModel',
},
],
},
}, },
], ],
}, },

View File

@ -7,6 +7,6 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * 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/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

@ -7,26 +7,30 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
export * from './ActionModel'; export * from './actions/AddNewActionModel';
export * from './AddNewActionModel'; export * from './actions/BulkDeleteActionModel';
export * from './BlockFlowModel'; export * from './actions/DeleteActionModel';
export * from './BlockGridFlowModel'; export * from './actions/FilterActionModel';
export * from './BulkDeleteActionModel'; export * from './actions/LinkActionModel';
export * from './CalendarBlockFlowModel'; export * from './actions/RefreshActionModel';
export * from './DeleteActionModel'; export * from './actions/ViewActionModel';
export * from './FormFieldModel'; export * from './base/ActionModel';
export * from './FormModel'; export * from './base/BlockModel';
export * from './HtmlBlockFlowModel'; export * from './base/GridModel';
export * from './LinkActionModel'; export * from './base/PageModel';
export * from './PageFlowModel'; export * from './base/PageTabModel';
export * from './PageTabFlowModel'; export * from './data-blocks/calendar/CalendarBlockModel';
export * from './QuickEditForm'; export * from './data-blocks/form/FormActionModel';
export * from './SubmitActionModel'; export * from './data-blocks/form/FormFieldModel';
export * from './TableColumnModel'; export * from './data-blocks/form/FormModel';
export * from './TableModel'; export * from './data-blocks/form/QuickEditForm';
export * from './ViewActionModel'; export * from './data-blocks/table/TableActionsColumnModel';
export * from './PopupActionModel'; export * from './data-blocks/table/TableColumnModel';
export * from './EditActionModel'; export * from './data-blocks/table/TableModel';
export * from './DuplicateActionModel'; export * from './filter-blocks/form/FilterFormActionModel';
export * from './CustomRequestActionModel'; export * from './filter-blocks/form/FilterFormFieldModel';
export * from './UpdateRecordActionModel'; 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 { Card } from 'antd';
import React, { createRef } from 'react'; 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) { function waitForRefCallback<T extends HTMLElement>(ref: React.RefObject<T>, cb: (el: T) => void, timeout = 3000) {
const start = Date.now(); const start = Date.now();
@ -21,7 +21,7 @@ function waitForRefCallback<T extends HTMLElement>(ref: React.RefObject<T>, cb:
check(); check();
} }
export class HtmlBlockFlowModel extends BlockFlowModel { export class HtmlBlockModel extends BlockModel {
ref = createRef<HTMLDivElement>(); ref = createRef<HTMLDivElement>();
render() { render() {
return ( return (
@ -33,11 +33,11 @@ export class HtmlBlockFlowModel extends BlockFlowModel {
} }
} }
HtmlBlockFlowModel.define({ HtmlBlockModel.define({
title: 'HTML', title: 'HTML',
group: 'Content', group: 'Content',
defaultOptions: { defaultOptions: {
use: 'HtmlBlockFlowModel', use: 'HtmlBlockModel',
stepParams: { stepParams: {
default: { default: {
step1: { step1: {
@ -49,7 +49,7 @@ HtmlBlockFlowModel.define({
}, },
}); });
HtmlBlockFlowModel.registerFlow({ HtmlBlockModel.registerFlow({
key: 'default', key: 'default',
auto: true, auto: true,
steps: { steps: {

View File

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

View File

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

View File

@ -8,7 +8,7 @@
*/ */
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { AddSubModelButton } from './AddSubModelButton'; import { AddSubModelButton, SubModelItemsType } from './AddSubModelButton';
import { FlowModel } from '../../models/flowModel'; import { FlowModel } from '../../models/flowModel';
import { ModelConstructor } from '../../types'; import { ModelConstructor } from '../../types';
import { Button } from 'antd'; import { Button } from 'antd';
@ -32,6 +32,14 @@ interface AddActionButtonProps {
* *
*/ */
children?: React.ReactNode; children?: React.ReactNode;
/**
* Model菜单的函数
*/
filter?: (blockClass: ModelConstructor, className: string) => boolean;
/**
* itemsaction菜单
*/
items?: SubModelItemsType;
} }
/** /**
@ -51,12 +59,17 @@ export const AddActionButton: React.FC<AddActionButtonProps> = ({
subModelKey = 'actions', subModelKey = 'actions',
children = <Button>Configure actions</Button>, children = <Button>Configure actions</Button>,
subModelType = 'array', subModelType = 'array',
items,
filter,
onModelAdded, onModelAdded,
}) => { }) => {
const items = useMemo(() => { const allActionsItems = useMemo(() => {
const blockClasses = model.flowEngine.filterModelClassByParent(subModelBaseClass); const actionClasses = model.flowEngine.filterModelClassByParent(subModelBaseClass);
const registeredBlocks = []; const registeredBlocks = [];
for (const [className, ModelClass] of blockClasses) { for (const [className, ModelClass] of actionClasses) {
if (filter && !filter(ModelClass, className)) {
continue;
}
const item = { const item = {
key: className, key: className,
label: ModelClass.meta?.title || className, label: ModelClass.meta?.title || className,
@ -76,7 +89,7 @@ export const AddActionButton: React.FC<AddActionButtonProps> = ({
model={model} model={model}
subModelKey={subModelKey} subModelKey={subModelKey}
subModelType={subModelType} subModelType={subModelType}
items={items} items={items ?? allActionsItems}
onModelAdded={onModelAdded} onModelAdded={onModelAdded}
> >
{children} {children}

View File

@ -7,11 +7,11 @@
* For more information, please refer to: https://www.nocobase.com/agreement. * For more information, please refer to: https://www.nocobase.com/agreement.
*/ */
import { Button } from 'antd';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { AddSubModelButton, SubModelItemsType, mergeSubModelItems } from './AddSubModelButton';
import { FlowModel } from '../../models/flowModel'; import { FlowModel } from '../../models/flowModel';
import { ModelConstructor } from '../../types'; import { ModelConstructor } from '../../types';
import { Button } from 'antd'; import { AddSubModelButton, SubModelItemsType, mergeSubModelItems } from './AddSubModelButton';
import { createBlockItems } from './blockItems'; import { createBlockItems } from './blockItems';
interface AddBlockButtonProps { interface AddBlockButtonProps {
@ -34,13 +34,13 @@ interface AddBlockButtonProps {
*/ */
children?: React.ReactNode; children?: React.ReactNode;
/** /**
* items * items
*/ */
items?: SubModelItemsType; items?: SubModelItemsType;
/** /**
* * Model菜单的函
*/ */
filterBlocks?: (blockClass: ModelConstructor, className: string) => boolean; filter?: (blockClass: ModelConstructor, className: string) => boolean;
/** /**
* *
*/ */
@ -75,12 +75,12 @@ interface AddBlockButtonProps {
*/ */
export const AddBlockButton: React.FC<AddBlockButtonProps> = ({ export const AddBlockButton: React.FC<AddBlockButtonProps> = ({
model, model,
subModelBaseClass = 'BlockFlowModel', subModelBaseClass = 'BlockModel',
subModelKey = 'blocks', subModelKey = 'blocks',
children = <Button>Add block</Button>, children = <Button>Add block</Button>,
subModelType = 'array', subModelType = 'array',
items, items,
filterBlocks, filter: filterBlocks,
appendItems, appendItems,
onModelAdded, onModelAdded,
}) => { }) => {

View File

@ -42,6 +42,10 @@ export interface AddFieldButtonProps {
* UI组件 * UI组件
*/ */
children?: React.ReactNode; children?: React.ReactNode;
/**
* items
*/
items?: SubModelItemsType;
} }
/** /**
@ -63,6 +67,7 @@ export const AddFieldButton: React.FC<AddFieldButtonProps> = ({
subModelType = 'array', subModelType = 'array',
collection, collection,
buildCreateModelOptions, buildCreateModelOptions,
items,
appendItems, appendItems,
onModelAdded, onModelAdded,
}) => { }) => {
@ -117,7 +122,7 @@ export const AddFieldButton: React.FC<AddFieldButtonProps> = ({
}; };
}, [model, subModelBaseClass, fields, buildCreateModelOptions]); }, [model, subModelBaseClass, fields, buildCreateModelOptions]);
const items = useMemo(() => { const fieldItems = useMemo(() => {
return mergeSubModelItems([buildFieldItems, appendItems], { addDividers: true }); return mergeSubModelItems([buildFieldItems, appendItems], { addDividers: true });
}, [buildFieldItems, appendItems]); }, [buildFieldItems, appendItems]);
@ -126,7 +131,7 @@ export const AddFieldButton: React.FC<AddFieldButtonProps> = ({
model={model} model={model}
subModelKey={subModelKey} subModelKey={subModelKey}
subModelType={subModelType} subModelType={subModelType}
items={items} items={items ?? fieldItems}
onModelAdded={onModelAdded} onModelAdded={onModelAdded}
> >
{children} {children}

View File

@ -184,6 +184,10 @@ export class FlowEngine {
return this.modelInstances.get(uid) as T | undefined; 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 * @param {string} uid Model

View File

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

View File

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

View File

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