@nocobase/flow-engine
Version:
A standalone flow engine for NocoBase, managing workflows, models, and actions.
851 lines (843 loc) • 33.7 kB
JavaScript
/**
* 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.
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var flowSettings_exports = {};
__export(flowSettings_exports, {
FlowSettings: () => FlowSettings
});
module.exports = __toCommonJS(flowSettings_exports);
var import_core = require("@formily/core");
var import_react = require("@formily/react");
var import_reactive = require("@formily/reactive");
var import_antd = require("antd");
var import_lodash = __toESM(require("lodash"));
var import_react2 = __toESM(require("react"));
var import_DefaultSettingsIcon = require("./components/settings/wrappers/contextual/DefaultSettingsIcon");
var import_StepSettingsDialog = require("./components/settings/wrappers/contextual/StepSettingsDialog");
var import_emitter = require("./emitter");
var import_flowContext = require("./flowContext");
var import__ = require(".");
var import_useFlowSettingsContext = require("./hooks/useFlowSettingsContext");
var import_utils = require("./utils");
var import_useFlowStep = require("./hooks/useFlowStep");
var _forceEnabled, _emitter;
const Panel = import_antd.Collapse.Panel;
const _FlowSettings = class _FlowSettings {
constructor(engine) {
__publicField(this, "components", {});
__publicField(this, "scopes", {});
__publicField(this, "antdComponentsLoaded", false);
__publicField(this, "enabled");
__privateAdd(this, _forceEnabled, false);
// 强制启用状态,主要用于设计模式下的强制启用
__publicField(this, "toolbarItems", []);
__privateAdd(this, _emitter, new import_emitter.Emitter());
this.enabled = false;
engine.context.defineProperty("flowSettingsEnabled", {
get: /* @__PURE__ */ __name(() => this.enabled, "get"),
cache: false
});
this.addDefaultToolbarItems();
(0, import_reactive.define)(this, {
enabled: import_reactive.observable
});
}
on(event, callback) {
__privateGet(this, _emitter).on(event, callback);
}
off(event, callback) {
__privateGet(this, _emitter).off(event, callback);
}
/**
* 添加默认的工具栏项目
* @private
*/
addDefaultToolbarItems() {
this.toolbarItems.push({
key: "settings-menu",
component: import_DefaultSettingsIcon.DefaultSettingsIcon,
sort: 0
// 默认为0,作为第一个添加的项目
});
}
/**
* 加载 FlowSettings 所需的资源。
* @returns {Promise<void>}
* @example
* await flowSettings.load();
*/
async load() {
if (this.antdComponentsLoaded) {
console.log("FlowSettings: Antd components already loaded, skipping...");
return;
}
try {
const {
ArrayBase,
ArrayCards,
ArrayCollapse,
ArrayItems,
ArrayTable,
ArrayTabs,
Cascader,
Checkbox,
DatePicker,
Editable,
Form,
FormDialog,
FormDrawer,
FormButtonGroup,
FormCollapse,
FormGrid,
FormItem,
FormLayout,
FormStep,
FormTab,
Input,
NumberPicker,
Password,
PreviewText,
Radio,
Reset,
Select,
SelectTable,
Space: Space2,
Submit,
Switch,
TimePicker,
Transfer,
TreeSelect,
Upload
} = await import("@formily/antd-v5");
const { Button: Button2 } = await import("antd");
this.components.Form = Form;
this.components.FormDialog = FormDialog;
this.components.FormDrawer = FormDrawer;
this.components.FormItem = FormItem;
this.components.FormLayout = FormLayout;
this.components.FormGrid = FormGrid;
this.components.FormStep = FormStep;
this.components.FormTab = FormTab;
this.components.FormCollapse = FormCollapse;
this.components.FormButtonGroup = FormButtonGroup;
this.components.Input = Input;
this.components.NumberPicker = NumberPicker;
this.components.Password = Password;
this.components.Select = Select;
this.components.SelectTable = SelectTable;
this.components.Cascader = Cascader;
this.components.TreeSelect = TreeSelect;
this.components.Transfer = Transfer;
this.components.DatePicker = DatePicker;
this.components.TimePicker = TimePicker;
this.components.Checkbox = Checkbox;
this.components.Radio = Radio;
this.components.Switch = Switch;
this.components.ArrayBase = ArrayBase;
this.components.ArrayCards = ArrayCards;
this.components.ArrayCollapse = ArrayCollapse;
this.components.ArrayItems = ArrayItems;
this.components.ArrayTable = ArrayTable;
this.components.ArrayTabs = ArrayTabs;
this.components.Upload = Upload;
this.components.Space = Space2;
this.components.Editable = Editable;
this.components.PreviewText = PreviewText;
this.components.Button = Button2;
this.components.Submit = Submit;
this.components.Reset = Reset;
this.antdComponentsLoaded = true;
console.log("FlowSettings: Antd components loaded successfully");
} catch (error) {
console.error("FlowSettings: Failed to load Antd components:", error);
throw error;
}
}
/**
* 添加组件到 FlowSettings 的组件注册表中。
* 这些组件可以在 flow step 的 uiSchema 中使用。
* @param {Record<string, any>} components 要添加的组件对象
* @returns {void}
* @example
* flowSettings.registerComponents({ MyComponent, AnotherComponent });
*/
registerComponents(components) {
Object.keys(components).forEach((name) => {
if (this.components[name]) {
console.warn(`FlowSettings: Component with name '${name}' is already registered and will be overwritten.`);
}
this.components[name] = components[name];
});
}
/**
* 添加作用域到 FlowSettings 的作用域注册表中。
* 这些作用域可以在 flow step 的 uiSchema 中使用。
* @param {Record<string, any>} scopes 要添加的作用域对象
* @returns {void}
* @example
* flowSettings.registerScopes({ useMyHook, myVariable, myFunction });
*/
registerScopes(scopes) {
Object.keys(scopes).forEach((name) => {
if (this.scopes[name]) {
console.warn(`FlowSettings: Scope with name '${name}' is already registered and will be overwritten.`);
}
this.scopes[name] = scopes[name];
});
}
/**
* 启用流程设置组件的显示
* @example
* flowSettings.enable();
*/
enable() {
this.enabled = true;
}
forceEnable() {
__privateSet(this, _forceEnabled, true);
this.enabled = true;
}
/**
* 禁用流程设置组件的显示
* @example
* flowSettings.disable();
*/
disable() {
if (__privateGet(this, _forceEnabled)) {
return;
}
this.enabled = false;
}
forceDisable() {
__privateSet(this, _forceEnabled, false);
this.enabled = false;
}
/**
* 添加扩展工具栏项目
* @param {ToolbarItemConfig} config 项目配置
* @example
* // 添加一个复制图标组件
* const CopyIcon = ({ model }) => {
* const handleCopy = () => {
* navigator.clipboard.writeText(model.uid);
* };
* return (
* <Tooltip title="复制">
* <CopyOutlined onClick={handleCopy} style={{ cursor: 'pointer', fontSize: 12 }} />
* </Tooltip>
* );
* };
*
* flowSettings.addToolbarItem({
* key: 'copy',
* component: CopyIcon,
* sort: 10 // 数字越小越靠右
* });
*
* // 添加下拉菜单项目组件
* const MoreActionsIcon = ({ model }) => {
* const menuItems = [
* { key: 'action1', label: '操作1', onClick: () => console.log('操作1', model) },
* { key: 'action2', label: '操作2', onClick: () => console.log('操作2', model) }
* ];
* return (
* <Dropdown menu={{ items: menuItems }} trigger={['hover']}>
* <MoreOutlined style={{ cursor: 'pointer', fontSize: 12 }} />
* </Dropdown>
* );
* };
*
* flowSettings.addToolbarItem({
* key: 'more-actions',
* component: MoreActionsIcon,
* visible: (model) => model.someCondition,
* sort: 20 // 数字越大越靠左
* });
*/
addToolbarItem(config) {
const existingIndex = this.toolbarItems.findIndex((item) => item.key === config.key);
if (existingIndex !== -1) {
console.warn(`FlowSettings: Toolbar item with key '${config.key}' already exists and will be replaced.`);
this.toolbarItems[existingIndex] = config;
} else {
this.toolbarItems.push(config);
}
this.toolbarItems.sort((a, b) => (b.sort || 0) - (a.sort || 0));
}
/**
* 批量添加工具栏项目
* @param {ToolbarItemConfig[]} configs 项目配置数组
* @example
* flowSettings.addToolbarItems([
* { key: 'copy', component: CopyIcon, sort: 10 },
* { key: 'edit', component: EditIcon, sort: 20 }
* ]);
*/
addToolbarItems(configs) {
configs.forEach((config) => this.addToolbarItem(config));
}
/**
* 移除工具栏项目
* @param {string} key 项目的唯一标识
* @example
* flowSettings.removeToolbarItem('copy');
*/
removeToolbarItem(key) {
const index = this.toolbarItems.findIndex((item) => item.key === key);
if (index !== -1) {
this.toolbarItems.splice(index, 1);
}
}
/**
* 获取所有工具栏项目配置
* @returns {ToolbarItemConfig[]} 所有项目配置
*/
getToolbarItems() {
return [...this.toolbarItems];
}
/**
* 清空所有工具栏项目
* @example
* flowSettings.clearToolbarItems();
*/
clearToolbarItems() {
this.toolbarItems = [];
}
/**
* 显示单个步骤的配置界面
* @param {StepSettingsDialogProps} props 步骤设置对话框的属性
* @returns {Promise<any>} 返回表单提交的值
* @example
* const result = await flowSettings.openStepSettingsDialog({
* model: myModel,
* flowKey: 'myFlow',
* stepKey: 'myStep',
* dialogWidth: 800,
* dialogTitle: '自定义标题'
* });
*/
async openStepSettingsDialog(props) {
return await (0, import_StepSettingsDialog.openStepSettingsDialog)(props);
}
/**
* 渲染单个步骤的表单
* @private
* @param {any} uiSchema 步骤的 UI Schema
* @param {any} initialValues 表单初始值(在此方法中不直接使用,而是通过 form 实例获取)
* @param {any} flowEngine 流引擎实例,用于获取 scopes 和 components
* @param {any} form 表单实例(从外部传入以便统一管理)
* @returns {React.ReactElement} 渲染的表单元素
*/
renderStepForm({
uiSchema,
initialValues,
flowEngine,
form,
onFormValuesChange: onFormValuesChange2
}) {
var _a, _b;
const scopes = {
// 为 schema 表达式提供上下文能力(可在表达式中使用 useFlowSettingsContext 等)
useFlowSettingsContext: import_useFlowSettingsContext.useFlowSettingsContext,
...((_a = flowEngine == null ? void 0 : flowEngine.flowSettings) == null ? void 0 : _a.scopes) || {}
};
const formSchema = {
type: "object",
properties: {
layout: {
type: "void",
"x-component": "FormLayout",
"x-component-props": { layout: "vertical" },
properties: uiSchema
}
}
};
const compiledSchema = (0, import_utils.compileUiSchema)(scopes, formSchema);
const SchemaField = (0, import_react.createSchemaField)();
return import_react2.default.createElement(
FormProviderWithForm,
{ form, initialValues, onFormValuesChange: onFormValuesChange2 },
import_react2.default.createElement(SchemaField, {
schema: compiledSchema,
components: ((_b = flowEngine == null ? void 0 : flowEngine.flowSettings) == null ? void 0 : _b.components) || {},
scope: scopes
})
);
}
/**
* 打开流程设置入口(聚合渲染多个 flow 的可配置步骤)
*
* 行为约定:
* - 必须提供 model 实例;用于解析 flow 定义、上下文与保存参数。
* - 当同时提供 flowKey 与 flowKeys 时,以 flowKey 为准(只处理单个 flow)。
* - 当提供 stepKey 时,应与某个 flowKey 组合使用;仅渲染该 flow 下命中的步骤。
* - 当外部明确指定了 flowKey + stepKey 且仅匹配到一个步骤时,采用“单步直出”表单(不使用折叠面板)。
* - 当未提供 stepKey,但最终仅匹配到一个步骤时,仍保持折叠面板的外观,以区别于上述“单步直出”样式。
* - uiMode 控制展示容器:'dialog' 或 'drawer',由 model.context.viewer 提供具体实现。
*
* 副作用:
* - 打开对应的视图容器;提交时逐步校验与保存每个 step 的参数,调用 before/after hooks,并最终触发 model.save()。
* - 通过 model.context.message 提示保存成功或错误信息。
*
* 参数:
* - options.model: FlowModel 实例(必填)。
* - options.preset?: 当为 true 时,仅渲染 flow 中标记了 preset=true 的步骤。
* - options.flowKey?: 目标 flow 的 key。
* - options.flowKeys?: 多个目标 flow 的 key 列表(当同时提供 flowKey 时被忽略)。
* - options.stepKey?: 目标步骤的 key(通常与 flowKey 搭配使用)。
* - options.uiMode?: 默认 'dialog'。
* - options.onCancel?: 取消按钮点击后触发的回调(无参数)。
* - options.onSaved?: 配置保存成功后触发的回调(无参数)。
*
* @param {FlowSettingsOpenOptions} options 打开选项
* @returns {Promise<boolean>} 是否成功打开弹窗
*/
async open(options) {
var _a, _b, _c, _d, _e, _f;
__privateGet(this, _emitter).emit("beforeOpen", options);
const { model, flowKey, flowKeys, stepKey, uiMode = "dialog", preset, onCancel, onSaved } = options;
if (!model) {
throw new Error("FlowSettings.open: model is required");
}
const t = (0, import_utils.getT)(model);
const message = (_a = model.context) == null ? void 0 : _a.message;
const allFlowsMap = model.getFlows();
const targetFlowKeys = (() => {
if (flowKey) return [flowKey];
if (Array.isArray(flowKeys) && flowKeys.length) return flowKeys;
return Array.from(allFlowsMap.keys());
})();
const entries = [];
await this.load();
for (const fk of targetFlowKeys) {
const flow = model.getFlow(fk);
if (!flow) {
console.warn(`FlowSettings.open: Flow with key '${fk}' not found`);
continue;
}
for (const sk of Object.keys(flow.steps || {})) {
if (stepKey && sk !== stepKey) continue;
const step = flow.steps[sk];
if (!preset && (!step || step.hideInSettings)) continue;
if (preset && !step.preset) continue;
const mergedUiSchema = await (0, import_utils.resolveStepUiSchema)(model, flow, step);
if (!mergedUiSchema || Object.keys(mergedUiSchema).length === 0) continue;
let stepTitle = step.title;
let beforeParamsSave = step.beforeParamsSave;
let afterParamsSave = step.afterParamsSave;
let actionDefaultParams = {};
let uiMode2;
if (step.use) {
const action = (_c = (_b = model.flowEngine) == null ? void 0 : _b.getAction) == null ? void 0 : _c.call(_b, step.use);
if (action) {
actionDefaultParams = action.defaultParams || {};
stepTitle = stepTitle || action.title;
beforeParamsSave = beforeParamsSave || action.beforeParamsSave;
afterParamsSave = afterParamsSave || action.afterParamsSave;
uiMode2 = action.uiMode;
}
}
const flowRuntimeContext = new import_flowContext.FlowRuntimeContext(model, fk, "settings");
(0, import_utils.setupRuntimeContextSteps)(flowRuntimeContext, flow.steps, model, fk);
flowRuntimeContext.defineProperty("currentStep", { value: step });
const modelStepParams = model.getStepParams(fk, sk) || {};
const resolvedDefaultParams = await (0, import_utils.resolveDefaultParams)(step.defaultParams, flowRuntimeContext);
const resolvedActionDefaults = await (0, import_utils.resolveDefaultParams)(actionDefaultParams, flowRuntimeContext);
const initialValues = {
...resolvedActionDefaults || {},
...resolvedDefaultParams || {},
...modelStepParams
};
entries.push({
flowKey: fk,
flowTitle: t(flow.title) || fk,
stepKey: sk,
stepTitle: t(stepTitle) || sk,
initialValues,
previousParams: { ...modelStepParams || {} },
mergedUiSchema,
// 存储合并后的 UI Schema,在 renderStepForm 中进行包装
beforeParamsSave,
afterParamsSave,
ctx: flowRuntimeContext,
uiMode: step.uiMode || uiMode2
});
}
}
if (entries.length === 0) {
if (!preset) {
(_d = message == null ? void 0 : message.info) == null ? void 0 : _d.call(message, t("This model has no configurable flow settings"));
}
return false;
}
const viewer = model.context.viewer;
const resolvedUiMode = entries.length === 1 ? await (0, import_utils.resolveUiMode)(entries[0].uiMode || uiMode, entries[0].ctx) : uiMode;
const modeType = typeof resolvedUiMode === "string" ? resolvedUiMode : resolvedUiMode.type || "dialog";
const openView = viewer[modeType || "dialog"].bind(viewer);
const flowEngine = model.flowEngine;
const scopes = {
// 为 schema 表达式提供上下文能力(可在表达式中使用 useFlowSettingsContext 等)
useFlowSettingsContext: import_useFlowSettingsContext.useFlowSettingsContext,
...((_e = flowEngine == null ? void 0 : flowEngine.flowSettings) == null ? void 0 : _e.scopes) || {}
};
let modeProps = typeof resolvedUiMode === "object" && resolvedUiMode ? resolvedUiMode.props || {} : {};
if (modeType === "embed") {
const target = document.querySelector("#nocobase-embed-container");
const onOpen = modeProps.onOpen;
const onClose = modeProps.onClose;
if (target) {
target.innerHTML = "";
}
modeProps = {
target,
styles: {
body: {
padding: (_f = flowEngine.context.themeToken) == null ? void 0 : _f.padding
}
},
...modeProps,
onOpen() {
target.style.width = modeProps.width || "33.3%";
target.style.maxWidth = modeProps.maxWidth || "800px";
target.style.minWidth = modeProps.minWidth || "0px";
onOpen == null ? void 0 : onOpen();
},
onClose() {
target.style.width = "auto";
target.style.maxWidth = "none";
target.style.minWidth = "auto";
onClose == null ? void 0 : onClose();
}
};
}
const grouped = {};
entries.forEach((e) => {
if (!grouped[e.flowKey]) grouped[e.flowKey] = { title: e.flowTitle, steps: [] };
grouped[e.flowKey].steps.push(e);
});
const forms = /* @__PURE__ */ new Map();
const keyOf = /* @__PURE__ */ __name((e) => `${e.flowKey}::${e.stepKey}`, "keyOf");
entries.forEach((e) => {
const form = (0, import_core.createForm)({ initialValues: (0, import_utils.compileUiSchema)(scopes, e.initialValues) });
forms.set(keyOf(e), form);
});
const flowKeysOrdered = Object.keys(grouped);
const multipleFlows = flowKeysOrdered.length > 1;
const getTitle = /* @__PURE__ */ __name(() => {
if (flowKey && stepKey && entries.length === 1) {
return entries[0].stepTitle;
}
if (!multipleFlows && entries.length > 0) {
return entries[0].stepTitle;
}
return "";
}, "getTitle");
const dispose = { value: /* @__PURE__ */ __name(() => {
}, "value") };
const autoUpdateViewProps = /* @__PURE__ */ __name((step, currentDialog) => {
dispose.value = (0, import_reactive.reaction)(
() => {
return (0, import_utils.resolveUiMode)(step.uiMode || uiMode, step.ctx);
},
(newValue) => {
newValue.then((newUiMode) => {
if (import_lodash.default.isPlainObject(newUiMode == null ? void 0 : newUiMode.props)) {
currentDialog.update(newUiMode.props);
}
}).catch((error) => {
console.warn("Error resolving uiMode:", error);
});
}
);
}, "autoUpdateViewProps");
openView({
// 默认标题与宽度可被传入的 props 覆盖
title: modeProps.title || getTitle(),
width: modeProps.width ?? 600,
destroyOnClose: true,
onClose: /* @__PURE__ */ __name(() => dispose.value(), "onClose"),
zIndex: 5e3,
// 允许透传其它 props(如 maskClosable、footer 等),但确保 content 由我们接管
...modeProps,
content: /* @__PURE__ */ __name((currentView, viewCtx) => {
viewCtx == null ? void 0 : viewCtx.defineMethod("getStepFormValues", (flowKey2, stepKey2) => {
var _a2;
return (_a2 = forms.get(keyOf({ flowKey: flowKey2, stepKey: stepKey2 }))) == null ? void 0 : _a2.values;
});
const renderStepForm = /* @__PURE__ */ __name((entry) => {
const form = forms.get(keyOf(entry));
if (!form) return null;
entry.ctx.view = currentView;
return import_react2.default.createElement(
import_useFlowSettingsContext.FlowSettingsContextProvider,
{ value: entry.ctx },
import_react2.default.createElement(
import_useFlowStep.FlowStepContext.Provider,
{
value: {
params: (0, import__.untracked)(() => ({ ...entry.initialValues, ...form.values })),
path: `${model.uid}_${entry.flowKey}_${entry.stepKey}`
}
},
this.renderStepForm({
uiSchema: entry.mergedUiSchema,
initialValues: entry.initialValues,
flowEngine,
form
})
)
);
}, "renderStepForm");
const renderStepPanels = /* @__PURE__ */ __name((steps) => steps.map((s) => import_react2.default.createElement(Panel, { header: s.stepTitle, key: keyOf(s) }, renderStepForm(s))), "renderStepPanels");
const toFlowTabItem = /* @__PURE__ */ __name((fk) => {
const group = grouped[fk];
return {
key: fk,
label: t(group.title) || fk,
children: group.steps.length > 1 ? import_react2.default.createElement(
import_antd.Collapse,
{ defaultActiveKey: group.steps.map((s) => keyOf(s)) },
...renderStepPanels(group.steps)
) : renderStepForm(group.steps[0])
};
}, "toFlowTabItem");
const renderStepsContainer = /* @__PURE__ */ __name(() => {
if (flowKey && stepKey && entries.length === 1) {
const step = entries[0];
autoUpdateViewProps(step, currentView);
return renderStepForm(step);
}
if (!multipleFlows) {
const step = entries[0];
autoUpdateViewProps(step, currentView);
return renderStepForm(entries[0]);
}
const items = flowKeysOrdered.map((fk) => toFlowTabItem(fk));
const defaultActiveKey = flowKey && grouped[flowKey] ? flowKey : flowKeysOrdered[0];
return import_react2.default.createElement(import_antd.Tabs, { items, defaultActiveKey });
}, "renderStepsContainer");
const onSaveAll = /* @__PURE__ */ __name(async () => {
var _a2, _b2;
try {
for (const e of entries) {
const form = forms.get(keyOf(e));
if (!form) continue;
await form.submit();
const currentValues = form.values;
model.setStepParams(e.flowKey, e.stepKey, currentValues);
if (typeof e.beforeParamsSave === "function") {
await e.beforeParamsSave(e.ctx, currentValues, e.previousParams);
}
}
await model.saveStepParams();
(_a2 = message == null ? void 0 : message.success) == null ? void 0 : _a2.call(message, t("Configuration saved"));
for (const e of entries) {
const form = forms.get(keyOf(e));
if (!form) continue;
const currentValues = form.values;
if (typeof e.afterParamsSave === "function") {
await e.afterParamsSave(e.ctx, currentValues, e.previousParams);
}
}
currentView.close();
try {
await (onSaved == null ? void 0 : onSaved());
} catch (cbErr) {
console.error("FlowSettings.open: onSaved callback error", cbErr);
}
} catch (err) {
if (err instanceof import_utils.FlowExitException) {
currentView.close();
return;
}
console.error("FlowSettings.open: save error", err);
(_b2 = message == null ? void 0 : message.error) == null ? void 0 : _b2.call(message, t("Error saving configuration, please check console"));
}
}, "onSaveAll");
currentView.submit = onSaveAll;
const stepsEl = renderStepsContainer();
const Cancel = /* @__PURE__ */ __name((props) => {
return import_react2.default.createElement(
import_antd.Button,
{
onClick: /* @__PURE__ */ __name(async () => {
currentView.close();
try {
await (onCancel == null ? void 0 : onCancel());
} catch (cbErr) {
console.error("FlowSettings.open: onCancel callback error", cbErr);
}
}, "onClick")
},
props.title || t("Cancel")
);
}, "Cancel");
const Save = /* @__PURE__ */ __name((props) => {
return import_react2.default.createElement(import_antd.Button, { type: "primary", onClick: onSaveAll }, props.title || t("Save"));
}, "Save");
let footerButtons = import_react2.default.createElement(
import_antd.Space,
{ align: "end" },
import_react2.default.createElement(Cancel),
import_react2.default.createElement(Save)
);
if (modeProps.footer) {
footerButtons = import_lodash.default.isFunction(modeProps.footer) ? modeProps.footer(footerButtons, {
OkBtn: Save,
CancelBtn: Cancel
}) : modeProps.footer;
}
if (modeProps.footer === null) {
footerButtons = null;
}
let footerEl;
if (currentView.Footer) {
footerEl = import_react2.default.createElement(currentView.Footer, null, footerButtons);
}
return import_react2.default.createElement(import_react2.default.Fragment, null, stepsEl, footerEl);
}, "content")
});
return true;
}
// =============================
// Dynamic flows editor (disabled)
// Kept as comments to preserve context
// =============================
/*
public async openDynamicFlowsEditor(
options: Pick<FlowSettingsOpenOptions, 'model' | 'uiMode' | 'onCancel'> & {
onSaved?: (flows: FlowDefinition[]) => void | Promise<void>;
},
) {
const { model, uiMode = 'dialog', onCancel, onSaved } = options;
const t = getT(model);
const message = model.context?.message;
// 构造响应式 value(深度可变)
const base = model.getDynamicFlows() || [];
const reactiveFlows = observable(JSON.parse(JSON.stringify(base)));
// 打开视图
const viewer = (model as any).context.viewer;
const modeType: 'dialog' | 'drawer' = typeof uiMode === 'string' ? uiMode : uiMode.type;
const modeProps: Record<string, any> = typeof uiMode === 'object' && uiMode ? uiMode.props || {} : {};
const openView = viewer[modeType].bind(viewer);
openView({
title: modeProps.title,
width: modeProps.width ?? 800,
destroyOnClose: true,
...modeProps,
content: (currentDialog) => {
const editorEl = React.createElement(DynamicFlowsEditor as any, { value: reactiveFlows, model });
const onSubmit = async () => {
try {
const plain = JSON.parse(JSON.stringify(reactiveFlows));
(model as any).setDynamicFlows(plain as FlowDefinition[]);
await (model as any).saveDynamicFlows();
message?.success?.(t('Configuration saved'));
currentDialog.close();
try {
await onSaved?.(plain);
} catch (cbErr) {
console.error('FlowSettings.openDynamicFlowsEditor: onSaved callback error', cbErr);
}
} catch (err) {
console.error('FlowSettings.openDynamicFlowsEditor: save error', err);
message?.error?.(t('Error saving configuration, please check console'));
}
};
const footer = React.createElement(
currentDialog.Footer,
null,
React.createElement(
Space,
{ align: 'end' },
React.createElement(
Button,
{
onClick: async () => {
currentDialog.close();
try {
await onCancel?.();
} catch (cbErr) {
console.error('FlowSettings.openDynamicFlowsEditor: onCancel callback error', cbErr);
}
},
},
t('Cancel'),
),
React.createElement(Button, { type: 'primary', onClick: onSubmit }, t('OK')),
),
);
return React.createElement(React.Fragment, null, editorEl, footer);
},
});
}
*/
};
_forceEnabled = new WeakMap();
_emitter = new WeakMap();
__name(_FlowSettings, "FlowSettings");
let FlowSettings = _FlowSettings;
function FormProviderWithForm({
children,
form,
initialValues,
onFormValuesChange: _onFormValuesChange
}) {
const formInstanceRef = import_react2.default.useRef(form);
if (!formInstanceRef.current) {
formInstanceRef.current = (0, import_core.createForm)({
initialValues,
effects() {
(0, import_core.onFormValuesChange)(_onFormValuesChange);
}
});
}
return import_react2.default.createElement(import_react.FormProvider, { form: formInstanceRef.current }, children);
}
__name(FormProviderWithForm, "FormProviderWithForm");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FlowSettings
});