Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/issue-316-script-reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@coding-flow/flow-design": minor
---

新增脚本引用 Provider:设计器不再直接耦合脚本 key 存储,支持通过上下文配置切换 key / inline 两种脚本引用形态(后端 issue #316)。
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,11 @@ pnpm run test:flow-mobile-form
pnpm run test:flow-mobile-approval
```


## 脚本引用模式

设计器通过 `ScriptReferenceProvider` 读写流程定义中的脚本引用,支持 `key`(默认,兼容既有数据)与 `inline`(正文直存)两种形态,由应用侧通过上下文配置注入。详见 [docs/integration/script-reference.md](./docs/integration/script-reference.md)。

## 许可证

本项目为 Flow Engine 的前端部分,遵循主项目的 [LICENSE](./LICENSE)。
53 changes: 53 additions & 0 deletions docs/integration/script-reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# 脚本引用模式(flow-design)

流程定义的 `script` 字段是一个**不透明的脚本引用**:可以是后端脚本 key,也可以直接是脚本正文。设计器组件不解释它,全部通过 `ScriptReferenceProvider` 读写。

## 两种模式

| 模式 | 引用形态 | 设计器行为 | 后端配置 |
|---|---|---|---|
| `key`(默认) | 后端脚本 key | 加载时 `GET /api/groovy-script/getScript` 取正文;保存时 `POST /api/groovy-script/save`,引用不变 | `flow.script.ref-mode=key` 或留空 |
| `inline` | 脚本正文 | 加载时直接把引用作为正文;保存时把正文写回流程定义,不发起任何脚本存储请求 | `flow.script.ref-mode=inline` |

前后端模式需由接入方保持一致:后端通过 `flow.script.ref-mode` 选择 Gateway 实现,前端通过上下文注入配置,**引擎不做自动探测**。

## 注入方式

```tsx
import {
configureScriptReference,
ScriptReferenceScope,
ScriptReferenceProvider,
} from '@coding-flow/flow-design';

// 1. 应用初始化时全局配置
configureScriptReference({ mode: 'inline' });

// 2. 局部作用域(同一应用内不同设计器实例可用不同模式)
<ScriptReferenceScope config={{ mode: 'key' }}>
<DesignPanel />
</ScriptReferenceScope>

// 3. 完全自定义实现
const custom: ScriptReferenceProvider = { /* resolve / persist / compile / metadata */ };
configureScriptReference({ provider: custom });
```

`useScriptReference()` 返回当前 Provider,组件优先读 React Context,其次读全局配置,默认 `KeyModeProvider`。测试可用 `resetScriptReference()` 复位。

## 端口方法

| 方法 | 语义 |
|---|---|
| `resolve(ref)` | 引用 -> 可编辑的脚本正文 |
| `persist(ref, content)` | 保存正文,返回写回流程定义的引用(key 模式返回原 key,inline 模式返回正文) |
| `compile(content)` | 语法编译校验(与存储无关,两种模式都可用) |
| `metadata(ref)` | 脚本元数据(key 模式读 `/getMetadata`,inline 模式返回空对象) |

## 组件改造

`GroovyScriptLoader` 不再直接引用 `@/api/script`,改由 Provider 完成加载与保存;`GroovyCodeEditor` 的编译按钮走 `provider.compile`。其余视图组件沿用 `scriptKey` prop 名,值已是不透明引用。节点视图 JS(`/api/cmd/node-view/*`)仍保持 key 模式。

## 兼容性

默认 `key` 模式行为与既有设计器完全一致,无需修改任何接入代码、流程定义或数据。inline 模式是新能力,切换时需要重新保存流程定义以写入正文引用;两种模式不得混用于同一流程定义。
1 change: 1 addition & 0 deletions packages/flow-design/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from '@/components/design-panel';
export * from '@/components/design-import';
export * from '@/plugins';
export * from '@/script-components/provider';
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import React from "react";
import { GroovyScriptContent } from "@/script-components/components/groovy-script-modal";
import { GroovyCodeEditor } from '@/components/groovy-code';
import { compile } from "@/api/script";
import { useScriptReference } from '@/script-components/provider';
import { message } from "antd";
import { FlowMessageKey, FlowMessageRegistry } from "@coding-flow/flow-core";

export const AdvancedScriptEditor: React.FC<GroovyScriptContent> = (props) => {


const { script, onChange, readonly } = props;
const provider = useScriptReference();

const handleChange = (value: string) => {
if (!readonly) {
Expand All @@ -26,7 +27,7 @@ export const AdvancedScriptEditor: React.FC<GroovyScriptContent> = (props) => {
placeholder={"请输入脚本..."}
onCompile={(code) => {
console.log('编译脚本:', code);
compile({ script: code }).then((res: any) => {
provider.compile(code).then((res) => {
if (res.success) {
message.success(
FlowMessageRegistry.getInstance().get(FlowMessageKey.DESIGN_SCRIPT_COMPILE_SUCCESS)
Expand All @@ -35,7 +36,7 @@ export const AdvancedScriptEditor: React.FC<GroovyScriptContent> = (props) => {
message.error(
FlowMessageRegistry.getInstance().get(
FlowMessageKey.DESIGN_SCRIPT_COMPILE_FAILED,
{ message: res.message }
{ message: res.message ?? '' }
)
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,98 +1,85 @@
import { getScript, save } from '@/api/script';
import React from 'react';
import {EventBus} from "@coding-flow/flow-core";
import {useScriptReference} from '@/script-components/provider';

/**
* 脚本内容更新事件
* 当某 scriptKey 对应的脚本内容被编辑保存后广播,通知所有订阅该 key 的实例(如画布与侧边栏)
* 立即用最新内容刷新,避免因 key 不变而无法感知内容变化。
* 回调签名:(key: string, content: string) => void
* 脚本内容更新事件。
* 某个脚本引用对应的内容被编辑保存后广播,通知所有订阅该引用的实例(如画布与侧边栏)
* 立即用最新内容刷新。回调签名:(ref: string, content: string) => void
*/
const SCRIPT_UPDATED_EVENT = 'groovy-script-updated';

export interface GroovyScriptLoaderProps {
// script key
/** 流程定义中的脚本引用(key 或正文,由 Provider 解释) */
value?: string;
// onChange
onChange?: (value: string) => void;
content: React.ComponentType<GroovyScriptLoaderContent>;
}


export interface GroovyScriptLoaderContent {
// script key
/** 脚本引用(保留 scriptKey 名称以兼容既有视图组件) */
scriptKey: string;
// script
/** 脚本正文 */
value?: string;
// script on change
onChange?: (value: string) => void;
}


export const GroovyScriptLoader: React.FC<GroovyScriptLoaderProps> = (props) => {

const scriptKey = props.value || '';
const provider = useScriptReference();
const scriptRef = props.value || '';

const [script, setScript] = React.useState('');

const ScriptContent = props.content;

const handlerSaveScript = (script: string) => {
save({
key: scriptKey,
script: script
}).then((res: any) => {

});
}


const handleScriptChange = (currentScript: string) => {
const handleScriptChange = async (currentScript: string) => {
if (script === currentScript) {
return;
}
console.log('script changed', currentScript);
handlerSaveScript(currentScript);
// 广播脚本内容更新,让画布等其他订阅该 key 的实例同步刷新
EventBus.getInstance().emit(SCRIPT_UPDATED_EVENT, scriptKey, currentScript);
// 由 Provider 决定写回流程定义的是 key 还是正文
const nextRef = await provider.persist(scriptRef, currentScript);
EventBus.getInstance().emit(SCRIPT_UPDATED_EVENT, nextRef, currentScript);
setScript(currentScript);

props.onChange?.(scriptKey);
}
props.onChange?.(nextRef);
};

React.useEffect(() => {
if (scriptKey) {
getScript(scriptKey).then((res: any) => {
setScript(res.data);
});
if (!scriptRef) {
setScript('');
return;
}
}, [scriptKey]);
let active = true;
provider.resolve(scriptRef)
.then((content) => {
if (active) setScript(content ?? '');
})
.catch(() => {
if (active) setScript('');
});
return () => {
active = false;
};
}, [scriptRef, provider]);

// 订阅脚本内容更新:当同一 scriptKey 的内容在其他实例被编辑保存时,立即同步最新内容
React.useEffect(() => {
if (!scriptKey) {
if (!scriptRef) {
return;
}
const handler = (key: string, content: string) => {
if (key === scriptKey) {
const handler = (ref: string, content: string) => {
if (ref === scriptRef) {
setScript(content);
}
};
EventBus.getInstance().on(SCRIPT_UPDATED_EVENT, handler);
return () => {
EventBus.getInstance().off(SCRIPT_UPDATED_EVENT, handler);
};
}, [scriptKey]);

React.useEffect(() => {
return () => {
setScript('');
};
}, []);
}, [scriptRef]);

return (
<ScriptContent
scriptKey={scriptKey}
scriptKey={scriptRef}
value={script}
onChange={handleScriptChange}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as scriptApi from '@/api/script';
import type {ScriptApi, ScriptCompileResult, ScriptReferenceProvider} from './types';

const compileOnlyApi: ScriptApi = {
getScript: async () => ({data: ''}),
save: async () => ({}),
compile: (body) => scriptApi.compile(body),
getMetadata: async () => ({data: {}}),
};

/**
* 正文模式:流程定义直接保存脚本正文。
* 不发起任何脚本存储请求;编译接口与存储无关,仍走后端编译能力。
*/
export class InlineModeProvider implements ScriptReferenceProvider {
readonly mode = 'inline' as const;

private readonly api: ScriptApi;

constructor(api: ScriptApi = compileOnlyApi) {
this.api = api;
}

async resolve(ref: string): Promise<string> {
return ref ?? '';
}

async persist(ref: string, content: string): Promise<string> {
return content;
}

async compile(content: string): Promise<ScriptCompileResult> {
const response = await this.api.compile({script: content});
return {success: !!response?.success, message: response?.message};
}

async metadata(ref: string): Promise<Record<string, unknown>> {
return {};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import * as scriptApi from '@/api/script';
import type {ScriptApi, ScriptCompileResult, ScriptReferenceProvider} from './types';

const defaultApi: ScriptApi = {
getScript: (key) => scriptApi.getScript(key),
save: (body) => scriptApi.save(body),
compile: (body) => scriptApi.compile(body),
getMetadata: (key) => scriptApi.getMetadata(key),
};

/** 默认实现:流程定义保存脚本 key,行为与既有设计器一致。 */
export class KeyModeProvider implements ScriptReferenceProvider {
readonly mode = 'key' as const;

private readonly api: ScriptApi;

constructor(api: ScriptApi = defaultApi) {
this.api = api;
}

async resolve(ref: string): Promise<string> {
if (!ref) return '';
const response = await this.api.getScript(ref);
return response?.data ?? '';
}

async persist(ref: string, content: string): Promise<string> {
await this.api.save({key: ref, script: content});
return ref;
}

async compile(content: string): Promise<ScriptCompileResult> {
const response = await this.api.compile({script: content});
return {success: !!response?.success, message: response?.message};
}

async metadata(ref: string): Promise<Record<string, unknown>> {
if (!ref) return {};
const response = await this.api.getMetadata(ref);
return response?.data ?? {};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React, {createContext, useContext, useMemo} from 'react';
import {KeyModeProvider} from './KeyModeProvider';
import {InlineModeProvider} from './InlineModeProvider';
import type {ScriptReferenceMode, ScriptReferenceProvider} from './types';

export interface ScriptReferenceConfig {
/** key(默认)或 inline */
mode?: ScriptReferenceMode;
/** 接入方自定义实现,优先于 mode */
provider?: ScriptReferenceProvider;
}

const ScriptReferenceScopeContext = createContext<ScriptReferenceProvider | null>(null);
const defaultKeyProvider = new KeyModeProvider();
let configuredProvider: ScriptReferenceProvider | null = null;

/**
* 应用构建/初始化时注入脚本引用配置(全局默认)。
* 后端通过 flow.script.ref-mode 选择对应实现,前后端由接入方保持一致。
*/
export function configureScriptReference(config: ScriptReferenceConfig = {}): ScriptReferenceProvider {
configuredProvider = createProvider(config);
return configuredProvider;
}

/** 重置为默认 key 模式,主要供测试使用。 */
export function resetScriptReference(): void {
configuredProvider = null;
}

export function getScriptReferenceProvider(): ScriptReferenceProvider {
return configuredProvider ?? defaultKeyProvider;
}

export function useScriptReference(): ScriptReferenceProvider {
return useContext(ScriptReferenceScopeContext) ?? getScriptReferenceProvider();
}

/** 局部作用域配置,允许同一应用内不同设计器实例使用不同形态。 */
export const ScriptReferenceScope: React.FC<React.PropsWithChildren<{
config?: ScriptReferenceConfig;
}>> = ({config, children}) => {
const provider = useMemo(
() => config ? createProvider(config) : getScriptReferenceProvider(),
[config?.mode, config?.provider],
);
return <ScriptReferenceScopeContext.Provider value={provider}>{children}</ScriptReferenceScopeContext.Provider>;
};

function createProvider(config: ScriptReferenceConfig): ScriptReferenceProvider {
if (config.provider) return config.provider;
return config.mode === 'inline' ? new InlineModeProvider() : new KeyModeProvider();
}
4 changes: 4 additions & 0 deletions packages/flow-design/src/script-components/provider/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './types';
export * from './KeyModeProvider';
export * from './InlineModeProvider';
export * from './ScriptReferenceContext';
Loading
Loading