// EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。 // // 设计要点(计划 T2.4 + §0.5 P5 + 评审收口): // - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。 // - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。 // - 🔴 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, parseCandidateExpression, type CandidateVariant, 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'; // ── bpmn-js 服务契约(最小) ─────────────────────────────────────────────────── interface Modeling { updateProperties(element: BpmnElement, props: Record): void; } interface Moddle { create(type: string, props?: Record): Record; } export interface PanelModeler extends SelectionModeler { get(service: string): unknown; } // ── 办理人 type 取值(§0 实测 10 种)+ 中文标签 ──────────────────────────────── const CANDIDATE_TYPES: Array<{ value: string; label: string }> = [ { value: 'user', label: '指定人员' }, { value: 'depart', label: '指定部门' }, { value: 'position', label: '指定岗位' }, { value: 'formSpecifiedDimension', label: '表单指定维度' }, { value: 'initiator', label: '流程发起人' }, { value: 'sameToTask', label: '同某任务办理人' }, { value: 'beforeTaskLeader', label: '上一办理人领导' }, { value: 'beforeTaskDepartManager', label: '上一办理人部门经理' }, { value: 'scriptUser', label: '脚本/表达式' }, { value: 'projectRoleType', label: '项目角色' }, ]; const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all']; // 有专用控件的属性,禁止再从「扩展属性」兜底编辑器写入(去重、防冲突)。 const RESERVED_EXT_LOCALNAMES = new Set(['candidateUsers', 'formKey', 'collection', 'elementVariable']); // ── 会签完成条件预设 ───────────────────────────────────────────────────────── type CompletionType = 'all' | 'majority' | 'count' | 'custom'; const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}'; const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}'; 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; } // 精确匹配预设串(不用子串,否则 >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) 与直读属性) ────────────────────────────────── function mget(obj: unknown, name: string): unknown { if (!obj || typeof obj !== 'object') return undefined; const o = obj as Record & { get?: (n: string) => unknown }; if (typeof o.get === 'function') return o.get(name); 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; } // formKey 下拉展示名:网关无名称时 name 回落为 id(uuid),未命名项显示「…(未命名)」。 function wfTemplateLabel(t: WfTemplateOption): string { if (t.name && t.name !== t.id) return t.name; return (t.id.length > 8 ? t.id.slice(0, 8) : t.id) + '…(未命名)'; } function newCandidateItem(): UserPropertyItem { return { type: 'user', content: '', isCandidate: true, isSendMail: false, isSendPhone: false, isSendMessage: false, }; } interface ListenerRow { event: string; mode: 'class' | 'delegateExpression'; value: string; /** 原监听器的 field 子元素数组(编辑时原样保留,引用不动)。 */ fields?: unknown[]; } 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, items, onChange, }: { idPrefix: string; items: UserPropertyItem[]; onChange: (next: UserPropertyItem[]) => void; }) { const patch = (i: number, p: Partial) => onChange(items.map((it, idx) => (idx === i ? { ...it, ...p } : it))); const remove = (i: number) => onChange(items.filter((_, idx) => idx !== i)); const add = () => onChange([...items, newCandidateItem()]); return (
{items.map((it, i) => (
patch(i, { content: e.target.value })} style={{ flex: 1, minWidth: 0 }} />
))}
); } function Section({ title, children }: { title: string; children: React.ReactNode }) { return (
{title}
{children}
); } export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) { const element = useSelectedElement(modeler); const modeling = modeler ? (modeler.get('modeling') as Modeling | undefined) : undefined; const moddle = modeler ? (modeler.get('moddle') as Moddle | undefined) : undefined; const isUserTask = element?.type === 'bpmn:UserTask'; // ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ───────── const [candidateItems, setCandidateItems] = useState([]); 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([]); const [templatesDegraded, setTemplatesDegraded] = useState(false); const [formKeyFilter, setFormKeyFilter] = useState(''); // undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。 const [syncTick, setSyncTick] = useState(0); // 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。 const otherExtRef = useRef([]); // 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。 const selfWriteRef = useRef(false); // formKey 数据源加载一次(透传 degraded;1016 项靠过滤输入,不裸滚动)。 useEffect(() => { let alive = true; Promise.resolve(fetchWfTemplates()) .then((r) => { if (!alive) return; setTemplates(Array.isArray(r?.templates) ? r.templates : []); setTemplatesDegraded(!!r?.degraded); }) .catch(() => { if (!alive) return; setTemplates([]); setTemplatesDegraded(true); }); return () => { alive = false; }; }, []); // 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([]); setCandidateMeta({}); setCandidateNonStandard(false); setCosign(FRESH_COSIGN); setCosignMeta({}); setFormKey(''); setExtAttrs([]); setNewAttr({ key: '', value: '' }); setListeners([]); otherExtRef.current = []; return; } const bo = element.businessObject; // 办理人 const rawCand = bo.get('activiti:candidateUsers') as string | undefined; const cand = parseCandidateExpression(rawCand); setCandidateItems(cand?.items ?? []); 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, ); 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, }); setCosignMeta(parsed?.meta ?? {}); } else { setCosign(FRESH_COSIGN); setCosignMeta({}); } // formKey setFormKey((bo.get('activiti:formKey') as string) ?? ''); // 扩展属性(长尾 $attrs,只留 activiti:/flowable: 前缀) const attrs = bo.$attrs ?? {}; setExtAttrs( Object.entries(attrs) .filter(([k]) => k.startsWith('activiti:') || k.startsWith('flowable:')) .map(([key, value]) => ({ key, value: String(value) })), ); setNewAttr({ key: '', value: '' }); // 任务监听器 const extEl = bo.get('extensionElements') as { values?: unknown[] } | undefined; const values = (extEl?.values ?? []) as unknown[]; // moddle 类型名遵循 activiti/camunda 惯例=PascalCase(xml.tagAlias:lowerCase 令 XML 元素名仍小写 // ),故按 $type 'activiti:TaskListener' 识别;小写名会致扩展类型 $pkg 串味、 // 断部署(见 moddle/serialization.test.ts)。 otherExtRef.current = values.filter((v) => (v as { $type?: string }).$type !== 'activiti:TaskListener'); setListeners( values .filter((v) => (v as { $type?: string }).$type === 'activiti:TaskListener') .map((v) => { const cls = mget(v, 'class') as string | undefined; const del = mget(v, 'delegateExpression') as string | undefined; const fields = ((v as { fields?: unknown[] }).fields ?? mget(v, 'fields')) as unknown[] | undefined; return { event: (mget(v, 'event') as string) ?? 'create', mode: cls ? 'class' : del ? 'delegateExpression' : 'class', value: cls ?? del ?? '', fields: fields && fields.length ? fields : undefined, } as ListenerRow; }), ); }, [element, syncTick]); function update(props: Record) { if (element && modeling) { selfWriteRef.current = true; modeling.updateProperties(element, props); } } // ── 办理人写回 ───────────────────────────────────────────────────────────── function writeCandidate(items: UserPropertyItem[]) { 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; } setCandidateItems(items); update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) }); } // ── 会签写回 ─────────────────────────────────────────────────────────────── function writeCosign(next: CosignState) { setCosign(next); if (!next.enabled) { update({ loopCharacteristics: undefined }); return; } if (!moddle) return; const collection = buildCandidateExpression( next.items, 'multiInstance' as CandidateVariant, cosignMeta, ); const props: Record = { isSequential: next.isSequential, 'activiti:collection': collection, }; // 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 }); } // ── formKey 写回 ─────────────────────────────────────────────────────────── function writeFormKey(value: string) { setFormKey(value); update({ 'activiti:formKey': value === '' ? undefined : value }); } // ── 扩展属性写回 ─────────────────────────────────────────────────────────── 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 }]; }); update({ [key]: newAttr.value }); setNewAttr({ key: '', value: '' }); } function editExtAttr(key: string, value: string) { setExtAttrs((prev) => prev.map((a) => (a.key === key ? { ...a, value } : a))); update({ [key]: value }); } function removeExtAttr(key: string) { setExtAttrs((prev) => prev.filter((a) => a.key !== key)); update({ [key]: undefined }); } // ── 任务监听器写回 ───────────────────────────────────────────────────────── function writeListeners(next: ListenerRow[]) { setListeners(next); if (!moddle) return; const listenerEls = next.map((l) => { const props: Record = { event: l.event }; props[l.mode] = l.value; if (l.fields && l.fields.length) props.fields = l.fields; return moddle.create('activiti:TaskListener', props); }); const all = [...otherExtRef.current, ...listenerEls]; const extEl = all.length ? moddle.create('bpmn:ExtensionElements', { values: all }) : undefined; update({ extensionElements: extEl }); } function addListener() { writeListeners([...listeners, { event: 'create', mode: 'class', value: '' }]); } function patchListener(i: number, p: Partial) { writeListeners(listeners.map((l, idx) => (idx === i ? { ...l, ...p } : l))); } function removeListener(i: number) { writeListeners(listeners.filter((_, idx) => idx !== i)); } // ── 渲染 ─────────────────────────────────────────────────────────────────── if (!element) { return (
请选择一个用户任务节点以编辑 EIP4 属性。
); } if (!isUserTask) { return (
选中的不是用户任务节点。EIP4 定制控件仅对用户任务(办理人 / 会签 / formKey)可用。
); } const candidateBadges = notableMeta(candidateMeta); const formKeyQuery = formKeyFilter.trim().toLowerCase(); const filteredTemplates = formKeyQuery ? templates.filter( (t) => t.name.toLowerCase().includes(formKeyQuery) || t.id.toLowerCase().includes(formKeyQuery), ) : templates; return (
EIP4 引擎以本控件为准,下方标准面板原生字段仅供高级调试。
{candidateBadges.length > 0 ? (
含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除)
) : null} {candidateNonStandard ? (
当前为非标准办理人表达式,编辑将覆盖原表达式。
) : null}
{cosign.enabled ? (
writeCosign({ ...cosign, items })} />
完成条件 {cosign.completionType === 'count' ? ( writeCosign({ ...cosign, completionN: Number(e.target.value) || 1 }) } style={{ width: 64 }} /> ) : null} {cosign.completionType === 'custom' ? ( 当前条件:{cosign.completionCustomBody || '(无)'} ) : null}
) : null}
{templatesDegraded ? (
模板列表暂不可用(数据源异常);可保留当前值或稍后重试。
) : null} setFormKeyFilter(e.target.value)} style={{ width: '100%', marginBottom: 6 }} />
{extAttrs.map((a, i) => (
editExtAttr(a.key, e.target.value)} style={{ flex: 1, minWidth: 0 }} />
))}
setNewAttr((s) => ({ ...s, key: e.target.value }))} style={{ flex: '0 0 130px', minWidth: 0 }} /> setNewAttr((s) => ({ ...s, value: e.target.value }))} style={{ flex: 1, minWidth: 0 }} />
{listeners.map((l, i) => (
patchListener(i, { value: e.target.value })} /> {l.fields && l.fields.length ? ( 含 field 配置({l.fields.length})· 编辑时原样保留 ) : null}
))}
); } const hintStyle: React.CSSProperties = { padding: 12, color: 'var(--text-3)', fontSize: 12, borderBottom: '1px solid var(--line)', };