fix(modeler): 侧板评审收口——会签保真读回/切换节点回归测试/meta可见性+清除确认

I-1 会签保真:isSequential/elementVariable/completionCondition 原值读进 CosignState、
写回用读到的值(真实库 isSequential=true×2 / elementVariable=assign|loop_assign / 完成条件
>0.6×7 原强写会静默改坏派任);完成条件 body 不匹配预设→「自定义(保留)」态,仅主动选预设才
改写;elementVariable 缺省态与原本无 completionCondition 写回时省略,不凭空写空。parseCompletion
改精确匹配预设串(修 >0.55 误判过半的子串 bug)。新增串行开关+循环变量输入。

I-2 双节点回归:A(meta X)→B(meta Y)→编辑 B→写回 meta===Y≠X,防串台。

I-3 meta 可见性:顶部只读徽标显示非空业务 meta(如任务后置服务 PM_XXX);删光 items 且含非空
业务 meta 时 window.confirm 确认才写 undefined(取消则本地态与引擎均不变)。

顺手:扩展属性强制 activiti:/flowable: 前缀 + 拉黑有专用控件的键(candidateUsers/formKey/
collection/elementVariable);非标准办理人表达式(parse→null)显示「编辑将覆盖」警示;订阅
commandStack.changed,非自身写入时对当前选中重灌本地态(undo/redo 脱同步防线)。

测试 Eip4Panel 21→33;全量 vitest 186 绿 / tsc -b 干净 / npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-02 12:01:26 +08:00
parent 6fceff784d
commit a9a304ab3d
2 changed files with 406 additions and 61 deletions

View File

@@ -1,7 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'; import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn'; import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn';
import { parseCandidateExpression } from './candidateExpression'; import {
parseCandidateExpression,
buildCandidateExpression,
type UserPropertyItem,
} from './candidateExpression';
// formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值。 // formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值。
vi.mock('../api/processModeler', () => ({ vi.mock('../api/processModeler', () => ({
@@ -28,7 +32,8 @@ const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); // type=position
// ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ──────────────────── // ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ────────────────────
function makeModeler() { function makeModeler() {
let handler: ((e: unknown) => void) | null = null; let selHandler: ((e: unknown) => void) | null = null;
let cmdHandler: (() => void) | null = null;
const updateProperties = vi.fn(); const updateProperties = vi.fn();
const created: Array<Record<string, unknown>> = []; const created: Array<Record<string, unknown>> = [];
const moddle = { const moddle = {
@@ -40,7 +45,8 @@ function makeModeler() {
}; };
const modeling = { updateProperties }; const modeling = { updateProperties };
const on = vi.fn((ev: string, cb: (e: unknown) => void) => { const on = vi.fn((ev: string, cb: (e: unknown) => void) => {
if (ev === 'selection.changed') handler = cb; if (ev === 'selection.changed') selHandler = cb;
if (ev === 'commandStack.changed') cmdHandler = cb as () => void;
}); });
const off = vi.fn(); const off = vi.fn();
const get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {}); const get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {});
@@ -49,11 +55,38 @@ function makeModeler() {
// 避免「update not wrapped in act」告警。 // 避免「update not wrapped in act」告警。
const select = (element: unknown) => const select = (element: unknown) =>
act(async () => { act(async () => {
handler?.({ newSelection: element ? [element] : [] }); selHandler?.({ newSelection: element ? [element] : [] });
await Promise.resolve(); await Promise.resolve();
await Promise.resolve(); await Promise.resolve();
}); });
return { modeler, updateProperties, moddle, created, select }; // 模拟外部 undo/redo:commandStack.changed。
const fireCommandStack = () =>
act(async () => {
cmdHandler?.();
await Promise.resolve();
});
return { modeler, updateProperties, moddle, created, select, fireCommandStack };
}
/** 全项目 window.confirm 默认放行(具体测试可再 spy 覆盖);afterEach 复原。 */
let confirmSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
});
afterEach(() => {
confirmSpy.mockRestore();
});
/** 一个内容非空、meta 为空的合法办理人表达式(清空时不触发 confirm)。 */
function candidateNoMeta(content = 'u1'): string {
const item: UserPropertyItem = {
type: 'user',
content,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
};
return buildCandidateExpression([item], 'candidate', {});
} }
/** 造一个 userTask element:map=businessObject.get(name) 源,$attrs=原始扩展属性袋。 */ /** 造一个 userTask element:map=businessObject.get(name) 源,$attrs=原始扩展属性袋。 */
@@ -138,13 +171,51 @@ describe('Eip4Panel — 办理人(candidateUsers)', () => {
expect(parsed.items[0].content).toBe('changed'); expect(parsed.items[0].content).toBe('changed');
}); });
it('清空最后一行:写回 undefined(清除属性)', async () => { it('清空最后一行(meta 为空):无 confirm,直接写回 undefined', async () => {
const { modeler, updateProperties, select } = makeModeler(); const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />); render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': candidateNoMeta() }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).not.toHaveBeenCalled();
expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined();
expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true);
});
it('I-3 清空含非空业务 meta:confirm=确认 → 写回 undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
confirmSpy.mockReturnValue(true);
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0')); fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(String(confirmSpy.mock.calls[0][0])).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined(); expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined();
expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true); });
it('I-3 清空含非空业务 meta:confirm=取消 → 不写回、行仍在', async () => {
const { modeler, updateProperties, select } = makeModeler();
confirmSpy.mockReturnValue(false);
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(updateProperties).not.toHaveBeenCalled(); // 引擎未变
expect(screen.getByTestId('eip4-candidate-content-0')).toBeInTheDocument(); // 行未删
});
it('I-3 非空业务 meta 顶部只读徽标显示任务后置服务', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
const badge = screen.getByTestId('eip4-candidate-meta-badge');
expect(badge.textContent).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
});
it('顺手:非标准办理人表达式显示「编辑将覆盖」警示', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': '${someOtherExpr(execution)}' }));
expect(screen.getByTestId('eip4-candidate-nonstandard')).toBeInTheDocument();
}); });
it('增行:改 type 下拉写回对应 type', async () => { it('增行:改 type 下拉写回对应 type', async () => {
@@ -243,6 +314,69 @@ describe('Eip4Panel — 会签(multiInstance)', () => {
'${nrOfCompletedInstances/nrOfInstances>0.5}', '${nrOfCompletedInstances/nrOfInstances>0.5}',
); );
}); });
// ── I-1 会签保真:读回并原样保留 isSequential / elementVariable / 非预设完成条件 ──────
// 真实库存在 isSequential=true、elementVariable=assign、完成条件 >0.6 等形态;强写会静默改坏。
function cosignLoop() {
return moddleEl('bpmn:MultiInstanceLoopCharacteristics', {
isSequential: true,
'activiti:collection': extractAttr('activiti:collection'),
'activiti:elementVariable': 'assign',
completionCondition: { body: '${nrOfCompletedInstances/nrOfInstances>0.6}' },
});
}
it('I-1 串行会签往返保 isSequential=true(不被强写 false)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
expect((screen.getByTestId('eip4-cosign-sequential') as HTMLInputElement).checked).toBe(true);
// 触发一次写(编辑会签人员 content),断言 isSequential 保留 true
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect(loop.isSequential).toBe(true);
});
it('I-1 elementVariable=assign 往返保 assign(不被强写 assignee)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
expect((screen.getByTestId('eip4-cosign-element-variable') as HTMLInputElement).value).toBe('assign');
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect(loop['activiti:elementVariable']).toBe('assign');
});
it('I-1 非预设完成条件 >0.6 不被归一为全票(自定义态保留原 body)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
// 下拉显「自定义(保留)」+ 原 body 展示
expect(screen.getByText(/自定义(保留)/)).toBeInTheDocument();
expect(screen.getByTestId('eip4-cosign-completion-custom').textContent).toContain(
'${nrOfCompletedInstances/nrOfInstances>0.6}',
);
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect((loop.completionCondition as { body: string }).body).toBe(
'${nrOfCompletedInstances/nrOfInstances>0.6}',
);
});
it('I-1 缺 elementVariable 的会签:写回省略该属性(不凭空写空)', async () => {
const { modeler, updateProperties, select } = makeModeler();
const loop = moddleEl('bpmn:MultiInstanceLoopCharacteristics', {
isSequential: false,
'activiti:collection': extractAttr('activiti:collection'),
// 无 activiti:elementVariable、无 completionCondition
});
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: loop }));
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const written = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect('activiti:elementVariable' in written).toBe(false); // 缺省态不写
expect('completionCondition' in written).toBe(false); // 原本无完成条件不发出
});
}); });
describe('Eip4Panel — formKey', () => { describe('Eip4Panel — formKey', () => {
@@ -300,6 +434,28 @@ describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => {
expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom'); expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom');
expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument(); expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument();
}); });
it('顺手:无 activiti:/flowable: 前缀的新键被拒(不写回)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), { target: { value: 'foo' } });
fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'v' } });
fireEvent.click(screen.getByTestId('eip4-extattr-add'));
expect(updateProperties).not.toHaveBeenCalled();
});
it('顺手:拉黑有专用控件的键(activiti:formKey)不允许从扩展属性写', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), {
target: { value: 'activiti:formKey' },
});
fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'x' } });
fireEvent.click(screen.getByTestId('eip4-extattr-add'));
expect(updateProperties).not.toHaveBeenCalled();
});
}); });
describe('Eip4Panel — 任务监听器(taskListener)', () => { describe('Eip4Panel — 任务监听器(taskListener)', () => {
@@ -366,3 +522,56 @@ describe('Eip4Panel — 任务监听器(taskListener)', () => {
expect('class' in listener).toBe(false); expect('class' in listener).toBe(false);
}); });
}); });
describe('Eip4Panel — 切换节点 / undo-redo 重灌(评审 I-2 + 顺手)', () => {
it('I-2 A(meta X)→B(meta Y)→编辑 B→写回 meta===Y 且 ≠X', async () => {
const { modeler, updateProperties, select } = makeModeler();
const item = (c: string): UserPropertyItem => ({
type: 'user',
content: c,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
const exprA = buildCandidateExpression([item('a')], 'candidate', { taskSuccessService: 'SVC_X' });
const exprB = buildCandidateExpression([item('b')], 'candidate', { taskSuccessService: 'SVC_Y' });
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ __id: 'A', 'activiti:candidateUsers': exprA }));
await select(userTask({ __id: 'B', 'activiti:candidateUsers': exprB }));
// 编辑 B 的 content
fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { target: { value: 'b2' } });
const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string;
const meta = parseCandidateExpression(written)!.meta;
expect(meta.taskSuccessService).toBe('SVC_Y'); // 用 B 的 meta
expect(meta.taskSuccessService).not.toBe('SVC_X'); // 不串到 A 的 meta
});
it('顺手:commandStack.changed(外部 undo)对当前选中重灌本地态', async () => {
const { modeler, select, fireCommandStack } = makeModeler();
const item = (c: string): UserPropertyItem => ({
type: 'user',
content: c,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
// 可变 map:模拟外部 undo 改写 businessObject。
const map: Record<string, unknown> = {
'activiti:candidateUsers': buildCandidateExpression([item('X')], 'candidate', {}),
};
const el = {
id: 't1',
type: 'bpmn:UserTask',
businessObject: { $type: 'bpmn:UserTask', get: (n: string) => map[n] },
};
render(<Eip4Panel modeler={modeler} />);
await select(el);
expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('X');
// 外部 undo 改了 businessObject → commandStack.changed → 重灌
map['activiti:candidateUsers'] = buildCandidateExpression([item('Y')], 'candidate', {});
await fireCommandStack();
expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('Y');
});
});

View File

@@ -1,13 +1,18 @@
// EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。 // EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。
// //
// 设计要点(计划 T2.4 + §0.5 P5): // 设计要点(计划 T2.4 + §0.5 P5 + 评审收口):
// - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。 // - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。
// - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。 // - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。
// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 ref, // - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 state,
// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。 // 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。顶部只读徽标显示,
// - 扩展属性只列长尾 $attrs(已声明属性如 formKey/candidateUsers 不进 $attrs,故不重复)。 // 删光 items 时 confirm 确认才写 undefined(评审 I-3)。
// - 🔴 会签保真(评审 I-1):isSequential/elementVariable/completionCondition 原始值读进 state、
// 写回用读到的值(真实库有 isSequential=true / elementVariable=assign / 完成条件 >0.6 等
// 非预设形态,强写会静默改坏派任);完成条件 body 不匹配预设时置「自定义(保留)」态,
// 仅用户主动选预设才改写。
// - 扩展属性只列长尾 $attrs;新增强制 activiti:/flowable: 前缀并拉黑有专用控件的键。
// - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。 // - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。
// - 原生标准属性面板照旧显示于本侧板下方,本控件顶部灰字提示以本控件为准。 // - undo/redo:订阅 commandStack.changed,非自身写入时对当前选中重灌本地态。
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { import {
buildCandidateExpression, buildCandidateExpression,
@@ -16,6 +21,7 @@ import {
type UserPropertyItem, type UserPropertyItem,
} from './candidateExpression'; } from './candidateExpression';
import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler'; import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler';
import { toast } from '../components/ui';
import type { BpmnElement, SelectionModeler } from './useSelectedElement'; import type { BpmnElement, SelectionModeler } from './useSelectedElement';
import { useSelectedElement } from './useSelectedElement'; import { useSelectedElement } from './useSelectedElement';
@@ -46,22 +52,31 @@ const CANDIDATE_TYPES: Array<{ value: string; label: string }> = [
const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all']; const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all'];
// 有专用控件的属性,禁止再从「扩展属性」兜底编辑器写入(去重、防冲突)。
const RESERVED_EXT_LOCALNAMES = new Set(['candidateUsers', 'formKey', 'collection', 'elementVariable']);
// ── 会签完成条件预设 ───────────────────────────────────────────────────────── // ── 会签完成条件预设 ─────────────────────────────────────────────────────────
type CompletionType = 'all' | 'majority' | 'count'; type CompletionType = 'all' | 'majority' | 'count' | 'custom';
const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}'; const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}';
const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}'; const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}';
function completionBody(type: CompletionType, n: number): string { function completionBodyFor(s: CosignState): string {
if (type === 'majority') return COMPLETION_MAJORITY; if (s.completionType === 'majority') return COMPLETION_MAJORITY;
if (type === 'count') return '${nrOfCompletedInstances>=' + n + '}'; if (s.completionType === 'count') return '${nrOfCompletedInstances>=' + s.completionN + '}';
if (s.completionType === 'custom') return s.completionCustomBody;
return COMPLETION_ALL; return COMPLETION_ALL;
} }
function parseCompletion(body: string | undefined): { type: CompletionType; n: number } { // 精确匹配预设串(不用子串,否则 >0.55 会误判为过半);非预设/无 body → 自定义(保留)。
if (!body) return { type: 'all', n: 2 }; function parseCompletion(body: string | undefined): {
if (body.indexOf('>0.5') >= 0) return { type: 'majority', n: 2 }; type: CompletionType;
const m = body.match(/nrOfCompletedInstances>=(\d+)/); n: number;
if (m) return { type: 'count', n: Number(m[1]) }; custom: string;
return { type: 'all', n: 2 }; } {
if (body === COMPLETION_ALL) return { type: 'all', n: 2, custom: '' };
if (body === COMPLETION_MAJORITY) return { type: 'majority', n: 2, custom: '' };
const m = body ? body.match(/^\$\{nrOfCompletedInstances>=(\d+)\}$/) : null;
if (m) return { type: 'count', n: Number(m[1]), custom: '' };
return { type: 'custom', n: 2, custom: body ?? '' };
} }
// ── moddle 读值(兼容 .get(name) 与直读属性) ────────────────────────────────── // ── moddle 读值(兼容 .get(name) 与直读属性) ──────────────────────────────────
@@ -72,6 +87,18 @@ function mget(obj: unknown, name: string): unknown {
return o[name]; return o[name];
} }
// 非空业务 meta → 只读徽标/确认文案(用于「删光办理人会一并移除 X」)。
function notableMeta(meta: Record<string, unknown>): string[] {
const out: string[] = [];
if (typeof meta.taskSuccessService === 'string' && meta.taskSuccessService)
out.push('任务后置服务:' + meta.taskSuccessService);
if (typeof meta.messageTemplate === 'string' && meta.messageTemplate) out.push('消息模板');
if (meta.isSkipInitiator === true) out.push('跳过发起人');
if (meta.isNoUserSkip === true) out.push('无办理人自动跳过');
if (meta.isSkipBeforeTask === true) out.push('跳过前置任务办理人');
return out;
}
function newCandidateItem(): UserPropertyItem { function newCandidateItem(): UserPropertyItem {
return { return {
type: 'user', type: 'user',
@@ -94,10 +121,26 @@ interface ListenerRow {
interface CosignState { interface CosignState {
enabled: boolean; enabled: boolean;
items: UserPropertyItem[]; items: UserPropertyItem[];
/** 保真:串行/并行,读回原值(真实库有 isSequential=true)。 */
isSequential: boolean;
/** 保真:循环变量名,读回原值(真实库有 assign/loop_assign/缺省);为空则写回时省略该属性。 */
elementVariable: string;
completionType: CompletionType; completionType: CompletionType;
completionN: number; completionN: number;
/** completionType==='custom' 时保留的原始 body;'' 表示原本无 completionCondition。 */
completionCustomBody: string;
} }
const FRESH_COSIGN: CosignState = {
enabled: false,
items: [],
isSequential: false,
elementVariable: 'assignee',
completionType: 'all',
completionN: 2,
completionCustomBody: '',
};
// ── items 编辑器(办理人 / 会签人员复用) ────────────────────────────────────── // ── items 编辑器(办理人 / 会签人员复用) ──────────────────────────────────────
function ItemsEditor({ function ItemsEditor({
idPrefix, idPrefix,
@@ -219,25 +262,24 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
const isUserTask = element?.type === 'bpmn:UserTask'; const isUserTask = element?.type === 'bpmn:UserTask';
// ── 本地编辑态(选中变更时从 businessObject 重新初始化) ────────────────────── // ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ─────────
const [candidateItems, setCandidateItems] = useState<UserPropertyItem[]>([]); const [candidateItems, setCandidateItems] = useState<UserPropertyItem[]>([]);
const [cosign, setCosign] = useState<CosignState>({ const [candidateMeta, setCandidateMeta] = useState<Record<string, unknown>>({});
enabled: false, const [candidateNonStandard, setCandidateNonStandard] = useState(false);
items: [], const [cosign, setCosign] = useState<CosignState>(FRESH_COSIGN);
completionType: 'all', const [cosignMeta, setCosignMeta] = useState<Record<string, unknown>>({});
completionN: 2,
});
const [formKey, setFormKey] = useState(''); const [formKey, setFormKey] = useState('');
const [extAttrs, setExtAttrs] = useState<Array<{ key: string; value: string }>>([]); const [extAttrs, setExtAttrs] = useState<Array<{ key: string; value: string }>>([]);
const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' }); const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' });
const [listeners, setListeners] = useState<ListenerRow[]>([]); const [listeners, setListeners] = useState<ListenerRow[]>([]);
const [templates, setTemplates] = useState<WfTemplateOption[]>([]); const [templates, setTemplates] = useState<WfTemplateOption[]>([]);
// undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。
const [syncTick, setSyncTick] = useState(0);
// meta 透传:codec parse 出的外层业务字段,写回时原样带回(不进 UI 渲染,只存 ref)。
const candidateMetaRef = useRef<Record<string, unknown>>({});
const cosignMetaRef = useRef<Record<string, unknown>>({});
// 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。 // 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。
const otherExtRef = useRef<unknown[]>([]); const otherExtRef = useRef<unknown[]>([]);
// 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。
const selfWriteRef = useRef(false);
// formKey 数据源加载一次。 // formKey 数据源加载一次。
useEffect(() => { useEffect(() => {
@@ -250,42 +292,66 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
}; };
}, []); }, []);
// 选中变更 → 从 businessObject 重新初始化本地态。 // undo/redo 脱同步防线:非自身写入的 commandStack 变更 → 对当前选中重灌本地态。
useEffect(() => {
if (!modeler) return;
const handler = () => {
if (selfWriteRef.current) {
selfWriteRef.current = false; // 自身 updateProperties 触发,不重灌(避免规范化闪烁)
return;
}
setSyncTick((t) => t + 1);
};
modeler.on('commandStack.changed', handler);
return () => {
modeler.off?.('commandStack.changed', handler);
};
}, [modeler]);
// 选中变更 / 外部命令 → 从 businessObject 重新初始化本地态。
useEffect(() => { useEffect(() => {
if (!element || element.type !== 'bpmn:UserTask') { if (!element || element.type !== 'bpmn:UserTask') {
setCandidateItems([]); setCandidateItems([]);
setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); setCandidateMeta({});
setCandidateNonStandard(false);
setCosign(FRESH_COSIGN);
setCosignMeta({});
setFormKey(''); setFormKey('');
setExtAttrs([]); setExtAttrs([]);
setNewAttr({ key: '', value: '' }); setNewAttr({ key: '', value: '' });
setListeners([]); setListeners([]);
candidateMetaRef.current = {};
cosignMetaRef.current = {};
otherExtRef.current = []; otherExtRef.current = [];
return; return;
} }
const bo = element.businessObject; const bo = element.businessObject;
// 办理人 // 办理人
const cand = parseCandidateExpression(bo.get('activiti:candidateUsers') as string | undefined); const rawCand = bo.get('activiti:candidateUsers') as string | undefined;
const cand = parseCandidateExpression(rawCand);
setCandidateItems(cand?.items ?? []); setCandidateItems(cand?.items ?? []);
candidateMetaRef.current = cand?.meta ?? {}; setCandidateMeta(cand?.meta ?? {});
setCandidateNonStandard(!!rawCand && !cand); // 非空但解析失败=非标准表达式
// 会签 // 会签(保真读回 isSequential/elementVariable/completionCondition 原值)
const loop = bo.get('loopCharacteristics'); const loop = bo.get('loopCharacteristics');
if (loop) { if (loop) {
const parsed = parseCandidateExpression(mget(loop, 'activiti:collection') as string | undefined); const parsed = parseCandidateExpression(mget(loop, 'activiti:collection') as string | undefined);
const cc = parseCompletion((mget(loop, 'completionCondition') as { body?: string } | undefined)?.body); const cc = parseCompletion(
(mget(loop, 'completionCondition') as { body?: string } | undefined)?.body,
);
setCosign({ setCosign({
enabled: true, enabled: true,
items: parsed?.items ?? [], items: parsed?.items ?? [],
isSequential: Boolean(mget(loop, 'isSequential')),
elementVariable: (mget(loop, 'activiti:elementVariable') as string) ?? '',
completionType: cc.type, completionType: cc.type,
completionN: cc.n, completionN: cc.n,
completionCustomBody: cc.custom,
}); });
cosignMetaRef.current = parsed?.meta ?? {}; setCosignMeta(parsed?.meta ?? {});
} else { } else {
setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); setCosign(FRESH_COSIGN);
cosignMetaRef.current = {}; setCosignMeta({});
} }
// formKey // formKey
@@ -319,22 +385,33 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
} as ListenerRow; } as ListenerRow;
}), }),
); );
}, [element]); }, [element, syncTick]);
function update(props: Record<string, unknown>) { function update(props: Record<string, unknown>) {
if (element && modeling) modeling.updateProperties(element, props); if (element && modeling) {
selfWriteRef.current = true;
modeling.updateProperties(element, props);
}
} }
// ── 办理人写回 ───────────────────────────────────────────────────────────── // ── 办理人写回 ─────────────────────────────────────────────────────────────
function writeCandidate(items: UserPropertyItem[]) { function writeCandidate(items: UserPropertyItem[]) {
setCandidateItems(items);
if (items.length === 0) { if (items.length === 0) {
// 删光 items:若外层含非空业务 meta,confirm 确认才写 undefined(否则连带清除业务字段)。
const notable = notableMeta(candidateMeta);
if (
notable.length > 0 &&
typeof window !== 'undefined' &&
!window.confirm('清空办理人将一并移除:' + notable.join('、') + '。确认清空?')
) {
return; // 取消:本地态与引擎均不变
}
setCandidateItems([]);
update({ 'activiti:candidateUsers': undefined }); update({ 'activiti:candidateUsers': undefined });
return; return;
} }
update({ setCandidateItems(items);
'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMetaRef.current), update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) });
});
} }
// ── 会签写回 ─────────────────────────────────────────────────────────────── // ── 会签写回 ───────────────────────────────────────────────────────────────
@@ -348,17 +425,18 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
const collection = buildCandidateExpression( const collection = buildCandidateExpression(
next.items, next.items,
'multiInstance' as CandidateVariant, 'multiInstance' as CandidateVariant,
cosignMetaRef.current, cosignMeta,
); );
const completionCondition = moddle.create('bpmn:FormalExpression', { const props: Record<string, unknown> = {
body: completionBody(next.completionType, next.completionN), isSequential: next.isSequential,
});
const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', {
isSequential: false,
'activiti:collection': collection, 'activiti:collection': collection,
'activiti:elementVariable': 'assignee', };
completionCondition, // elementVariable 为空(真实库缺省态)则省略,不凭空写空属性。
}); if (next.elementVariable) props['activiti:elementVariable'] = next.elementVariable;
const body = completionBodyFor(next);
// body 为空(原本无 completionCondition)则不发出该子元素,保真。
if (body) props.completionCondition = moddle.create('bpmn:FormalExpression', { body });
const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', props);
update({ loopCharacteristics: loop }); update({ loopCharacteristics: loop });
} }
@@ -372,6 +450,15 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
function addExtAttr() { function addExtAttr() {
const key = newAttr.key.trim(); const key = newAttr.key.trim();
if (!key) return; if (!key) return;
if (!key.startsWith('activiti:') && !key.startsWith('flowable:')) {
toast('扩展属性键必须以 activiti: 或 flowable: 开头', 'warn');
return;
}
const local = key.slice(key.indexOf(':') + 1);
if (RESERVED_EXT_LOCALNAMES.has(local)) {
toast('该属性有专用控件,请用上方对应控件编辑', 'warn');
return;
}
setExtAttrs((prev) => { setExtAttrs((prev) => {
const rest = prev.filter((a) => a.key !== key); const rest = prev.filter((a) => a.key !== key);
return [...rest, { key, value: newAttr.value }]; return [...rest, { key, value: newAttr.value }];
@@ -428,6 +515,8 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
); );
} }
const candidateBadges = notableMeta(candidateMeta);
return ( return (
<div <div
data-testid="process-modeler-eip4-panel" data-testid="process-modeler-eip4-panel"
@@ -438,6 +527,22 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
</div> </div>
<Section title="办理人"> <Section title="办理人">
{candidateBadges.length > 0 ? (
<div
data-testid="eip4-candidate-meta-badge"
style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8, lineHeight: 1.6 }}
>
含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除)
</div>
) : null}
{candidateNonStandard ? (
<div
data-testid="eip4-candidate-nonstandard"
style={{ fontSize: 12, color: 'var(--warn, #d48806)', marginBottom: 8 }}
>
当前为非标准办理人表达式,编辑将覆盖原表达式。
</div>
) : null}
<ItemsEditor idPrefix="eip4-candidate" items={candidateItems} onChange={writeCandidate} /> <ItemsEditor idPrefix="eip4-candidate" items={candidateItems} onChange={writeCandidate} />
</Section> </Section>
@@ -453,12 +558,31 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
</label> </label>
{cosign.enabled ? ( {cosign.enabled ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
data-testid="eip4-cosign-sequential"
checked={cosign.isSequential}
onChange={(e) => writeCosign({ ...cosign, isSequential: e.target.checked })}
/>
串行(顺序会签)
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<span style={{ flex: '0 0 auto' }}>循环变量</span>
<input
data-testid="eip4-cosign-element-variable"
value={cosign.elementVariable}
placeholder="assignee"
onChange={(e) => writeCosign({ ...cosign, elementVariable: e.target.value })}
style={{ flex: 1, minWidth: 0 }}
/>
</label>
<ItemsEditor <ItemsEditor
idPrefix="eip4-cosign" idPrefix="eip4-cosign"
items={cosign.items} items={cosign.items}
onChange={(items) => writeCosign({ ...cosign, items })} onChange={(items) => writeCosign({ ...cosign, items })}
/> />
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, flexWrap: 'wrap' }}>
<span>完成条件</span> <span>完成条件</span>
<select <select
data-testid="eip4-cosign-completion-type" data-testid="eip4-cosign-completion-type"
@@ -467,6 +591,10 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
writeCosign({ ...cosign, completionType: e.target.value as CompletionType }) writeCosign({ ...cosign, completionType: e.target.value as CompletionType })
} }
> >
{/* 自定义(保留)仅在当前为自定义态时可选中——presets 不提供切到自定义,防误清 */}
{cosign.completionType === 'custom' ? (
<option value="custom">自定义(保留)</option>
) : null}
<option value="all">全票通过</option> <option value="all">全票通过</option>
<option value="majority">过半通过</option> <option value="majority">过半通过</option>
<option value="count">指定数</option> <option value="count">指定数</option>
@@ -483,6 +611,14 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
style={{ width: 64 }} style={{ width: 64 }}
/> />
) : null} ) : null}
{cosign.completionType === 'custom' ? (
<span
data-testid="eip4-cosign-completion-custom"
style={{ fontSize: 12, color: 'var(--text-3)' }}
>
当前条件:<code>{cosign.completionCustomBody || '(无)'}</code>
</span>
) : null}
</div> </div>
</div> </div>
) : null} ) : null}