From a9a304ab3da47012c4fde72b73c56531d5e49ccc Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 2 Jul 2026 12:01:26 +0800 Subject: [PATCH] =?UTF-8?q?fix(modeler):=20=E4=BE=A7=E6=9D=BF=E8=AF=84?= =?UTF-8?q?=E5=AE=A1=E6=94=B6=E5=8F=A3=E2=80=94=E2=80=94=E4=BC=9A=E7=AD=BE?= =?UTF-8?q?=E4=BF=9D=E7=9C=9F=E8=AF=BB=E5=9B=9E/=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E5=9B=9E=E5=BD=92=E6=B5=8B=E8=AF=95/meta?= =?UTF-8?q?=E5=8F=AF=E8=A7=81=E6=80=A7+=E6=B8=85=E9=99=A4=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/modeler/Eip4Panel.test.tsx | 225 ++++++++++++++++++++++++++++-- src/modeler/Eip4Panel.tsx | 242 +++++++++++++++++++++++++-------- 2 files changed, 406 insertions(+), 61 deletions(-) diff --git a/src/modeler/Eip4Panel.test.tsx b/src/modeler/Eip4Panel.test.tsx index 2e9a8df..c5592f7 100644 --- a/src/modeler/Eip4Panel.test.tsx +++ b/src/modeler/Eip4Panel.test.tsx @@ -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 { 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 值。 vi.mock('../api/processModeler', () => ({ @@ -28,7 +32,8 @@ const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); // type=position // ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ──────────────────── 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 created: Array> = []; const moddle = { @@ -40,7 +45,8 @@ function makeModeler() { }; const modeling = { updateProperties }; 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 get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {}); @@ -49,11 +55,38 @@ function makeModeler() { // 避免「update not wrapped in act」告警。 const select = (element: unknown) => act(async () => { - handler?.({ newSelection: element ? [element] : [] }); + selHandler?.({ newSelection: element ? [element] : [] }); 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; +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=原始扩展属性袋。 */ @@ -138,13 +171,51 @@ describe('Eip4Panel — 办理人(candidateUsers)', () => { expect(parsed.items[0].content).toBe('changed'); }); - it('清空最后一行:写回 undefined(清除属性)', async () => { + it('清空最后一行(meta 为空):无 confirm,直接写回 undefined', async () => { const { modeler, updateProperties, select } = makeModeler(); render(); + 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(); await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE })); 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('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true); + }); + + it('I-3 清空含非空业务 meta:confirm=取消 → 不写回、行仍在', async () => { + const { modeler, updateProperties, select } = makeModeler(); + confirmSpy.mockReturnValue(false); + render(); + 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(); + 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(); + await select(userTask({ 'activiti:candidateUsers': '${someOtherExpr(execution)}' })); + expect(screen.getByTestId('eip4-candidate-nonstandard')).toBeInTheDocument(); }); it('增行:改 type 下拉写回对应 type', async () => { @@ -243,6 +314,69 @@ describe('Eip4Panel — 会签(multiInstance)', () => { '${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(); + 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; + expect(loop.isSequential).toBe(true); + }); + + it('I-1 elementVariable=assign 往返保 assign(不被强写 assignee)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + 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; + expect(loop['activiti:elementVariable']).toBe('assign'); + }); + + it('I-1 非预设完成条件 >0.6 不被归一为全票(自定义态保留原 body)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + 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; + 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(); + await select(userTask({ loopCharacteristics: loop })); + fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } }); + const written = lastPayload(updateProperties).loopCharacteristics as Record; + expect('activiti:elementVariable' in written).toBe(false); // 缺省态不写 + expect('completionCondition' in written).toBe(false); // 原本无完成条件不发出 + }); }); describe('Eip4Panel — formKey', () => { @@ -300,6 +434,28 @@ describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => { expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom'); expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument(); }); + + it('顺手:无 activiti:/flowable: 前缀的新键被拒(不写回)', async () => { + const { modeler, updateProperties, select } = makeModeler(); + render(); + 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(); + 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)', () => { @@ -366,3 +522,56 @@ describe('Eip4Panel — 任务监听器(taskListener)', () => { 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(); + 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 = { + 'activiti:candidateUsers': buildCandidateExpression([item('X')], 'candidate', {}), + }; + const el = { + id: 't1', + type: 'bpmn:UserTask', + businessObject: { $type: 'bpmn:UserTask', get: (n: string) => map[n] }, + }; + render(); + 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'); + }); +}); diff --git a/src/modeler/Eip4Panel.tsx b/src/modeler/Eip4Panel.tsx index 5312200..d046d1f 100644 --- a/src/modeler/Eip4Panel.tsx +++ b/src/modeler/Eip4Panel.tsx @@ -1,13 +1,18 @@ // EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。 // -// 设计要点(计划 T2.4 + §0.5 P5): -// - 全部写操作经 bpmn-js `modeling.updateProperties(element, {...})`,undo/redo 天然生效。 +// 设计要点(计划 T2.4 + §0.5 P5 + 评审收口): +// - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。 // - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。 -// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 ref, -// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。 -// - 扩展属性只列长尾 $attrs(已声明属性如 formKey/candidateUsers 不进 $attrs,故不重复)。 +// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 state, +// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。顶部只读徽标显示, +// 删光 items 时 confirm 确认才写 undefined(评审 I-3)。 +// - 🔴 会签保真(评审 I-1):isSequential/elementVariable/completionCondition 原始值读进 state、 +// 写回用读到的值(真实库有 isSequential=true / elementVariable=assign / 完成条件 >0.6 等 +// 非预设形态,强写会静默改坏派任);完成条件 body 不匹配预设时置「自定义(保留)」态, +// 仅用户主动选预设才改写。 +// - 扩展属性只列长尾 $attrs;新增强制 activiti:/flowable: 前缀并拉黑有专用控件的键。 // - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。 -// - 原生标准属性面板照旧显示于本侧板下方,本控件顶部灰字提示以本控件为准。 +// - undo/redo:订阅 commandStack.changed,非自身写入时对当前选中重灌本地态。 import { useEffect, useRef, useState } from 'react'; import { buildCandidateExpression, @@ -16,6 +21,7 @@ import { type UserPropertyItem, } from './candidateExpression'; import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler'; +import { toast } from '../components/ui'; import type { BpmnElement, SelectionModeler } 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 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_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}'; -function completionBody(type: CompletionType, n: number): string { - if (type === 'majority') return COMPLETION_MAJORITY; - if (type === 'count') return '${nrOfCompletedInstances>=' + n + '}'; +function completionBodyFor(s: CosignState): string { + if (s.completionType === 'majority') return COMPLETION_MAJORITY; + if (s.completionType === 'count') return '${nrOfCompletedInstances>=' + s.completionN + '}'; + if (s.completionType === 'custom') return s.completionCustomBody; return COMPLETION_ALL; } -function parseCompletion(body: string | undefined): { type: CompletionType; n: number } { - if (!body) return { type: 'all', n: 2 }; - if (body.indexOf('>0.5') >= 0) return { type: 'majority', n: 2 }; - const m = body.match(/nrOfCompletedInstances>=(\d+)/); - if (m) return { type: 'count', n: Number(m[1]) }; - return { type: 'all', n: 2 }; +// 精确匹配预设串(不用子串,否则 >0.55 会误判为过半);非预设/无 body → 自定义(保留)。 +function parseCompletion(body: string | undefined): { + type: CompletionType; + n: number; + custom: string; +} { + 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) 与直读属性) ────────────────────────────────── @@ -72,6 +87,18 @@ function mget(obj: unknown, name: string): unknown { return o[name]; } +// 非空业务 meta → 只读徽标/确认文案(用于「删光办理人会一并移除 X」)。 +function notableMeta(meta: Record): 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 { return { type: 'user', @@ -94,10 +121,26 @@ interface ListenerRow { interface CosignState { enabled: boolean; items: UserPropertyItem[]; + /** 保真:串行/并行,读回原值(真实库有 isSequential=true)。 */ + isSequential: boolean; + /** 保真:循环变量名,读回原值(真实库有 assign/loop_assign/缺省);为空则写回时省略该属性。 */ + elementVariable: string; completionType: CompletionType; 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 编辑器(办理人 / 会签人员复用) ────────────────────────────────────── function ItemsEditor({ idPrefix, @@ -219,25 +262,24 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { const isUserTask = element?.type === 'bpmn:UserTask'; - // ── 本地编辑态(选中变更时从 businessObject 重新初始化) ────────────────────── + // ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ───────── const [candidateItems, setCandidateItems] = useState([]); - const [cosign, setCosign] = useState({ - enabled: false, - items: [], - completionType: 'all', - completionN: 2, - }); + const [candidateMeta, setCandidateMeta] = useState>({}); + const [candidateNonStandard, setCandidateNonStandard] = useState(false); + const [cosign, setCosign] = useState(FRESH_COSIGN); + const [cosignMeta, setCosignMeta] = useState>({}); const [formKey, setFormKey] = useState(''); const [extAttrs, setExtAttrs] = useState>([]); const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' }); const [listeners, setListeners] = useState([]); const [templates, setTemplates] = useState([]); + // undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。 + const [syncTick, setSyncTick] = useState(0); - // meta 透传:codec parse 出的外层业务字段,写回时原样带回(不进 UI 渲染,只存 ref)。 - const candidateMetaRef = useRef>({}); - const cosignMetaRef = useRef>({}); // 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。 const otherExtRef = useRef([]); + // 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。 + const selfWriteRef = useRef(false); // formKey 数据源加载一次。 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(() => { if (!element || element.type !== 'bpmn:UserTask') { setCandidateItems([]); - setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); + setCandidateMeta({}); + setCandidateNonStandard(false); + setCosign(FRESH_COSIGN); + setCosignMeta({}); setFormKey(''); setExtAttrs([]); setNewAttr({ key: '', value: '' }); setListeners([]); - candidateMetaRef.current = {}; - cosignMetaRef.current = {}; otherExtRef.current = []; return; } 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 ?? []); - candidateMetaRef.current = cand?.meta ?? {}; + setCandidateMeta(cand?.meta ?? {}); + setCandidateNonStandard(!!rawCand && !cand); // 非空但解析失败=非标准表达式 - // 会签 + // 会签(保真读回 isSequential/elementVariable/completionCondition 原值) const loop = bo.get('loopCharacteristics'); if (loop) { 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({ enabled: true, items: parsed?.items ?? [], + isSequential: Boolean(mget(loop, 'isSequential')), + elementVariable: (mget(loop, 'activiti:elementVariable') as string) ?? '', completionType: cc.type, completionN: cc.n, + completionCustomBody: cc.custom, }); - cosignMetaRef.current = parsed?.meta ?? {}; + setCosignMeta(parsed?.meta ?? {}); } else { - setCosign({ enabled: false, items: [], completionType: 'all', completionN: 2 }); - cosignMetaRef.current = {}; + setCosign(FRESH_COSIGN); + setCosignMeta({}); } // formKey @@ -319,22 +385,33 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { } as ListenerRow; }), ); - }, [element]); + }, [element, syncTick]); function update(props: Record) { - if (element && modeling) modeling.updateProperties(element, props); + if (element && modeling) { + selfWriteRef.current = true; + modeling.updateProperties(element, props); + } } // ── 办理人写回 ───────────────────────────────────────────────────────────── function writeCandidate(items: UserPropertyItem[]) { - setCandidateItems(items); 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 }); return; } - update({ - 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMetaRef.current), - }); + setCandidateItems(items); + update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) }); } // ── 会签写回 ─────────────────────────────────────────────────────────────── @@ -348,17 +425,18 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { const collection = buildCandidateExpression( next.items, 'multiInstance' as CandidateVariant, - cosignMetaRef.current, + cosignMeta, ); - const completionCondition = moddle.create('bpmn:FormalExpression', { - body: completionBody(next.completionType, next.completionN), - }); - const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', { - isSequential: false, + const props: Record = { + isSequential: next.isSequential, '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 }); } @@ -372,6 +450,15 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { function addExtAttr() { const key = newAttr.key.trim(); 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) => { const rest = prev.filter((a) => a.key !== key); return [...rest, { key, value: newAttr.value }]; @@ -428,6 +515,8 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { ); } + const candidateBadges = notableMeta(candidateMeta); + return (
+ {candidateBadges.length > 0 ? ( +
+ 含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除) +
+ ) : null} + {candidateNonStandard ? ( +
+ 当前为非标准办理人表达式,编辑将覆盖原表达式。 +
+ ) : null}
@@ -453,12 +558,31 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { {cosign.enabled ? (
+ + writeCosign({ ...cosign, items })} /> -
+
完成条件