@bpmn-nova/studio 0.3.7-preview → 0.3.8-preview

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ BPMN Nova 的 Vanilla JavaScript / TypeScript 完整入口,提供流程设计
4
4
 
5
5
  > **English summary:** The complete framework-neutral BPMN Nova package for process design, viewing, approval traces, themes, properties, and pure SVG export.
6
6
 
7
- > 当前版本为 `0.3.7-preview`。请使用 `@preview` 安装,并在生产接入前验证目标 BPMN XML 与引擎扩展。
7
+ > 当前版本为 `0.3.8-preview`。请使用 `@preview` 安装,并在生产接入前验证目标 BPMN XML 与引擎扩展。
8
8
 
9
9
  ![BPMN Nova 流程设计器](https://raw.githubusercontent.com/daxiangme/bpmn-nova/dev/docs/assets/bpmn-nova-designer.jpg)
10
10
 
package/dist/canvas.js CHANGED
@@ -2,14 +2,16 @@ import {
2
2
  applyContainmentOperation,
3
3
  clearConnectedWaypoints,
4
4
  CONTAINMENT_LIMITS,
5
+ edgeWaypoints,
5
6
  elementScopeId,
7
+ getEdge,
6
8
  getNode,
7
9
  isEmbeddedSubProcess,
8
10
  NODE_DEFINITIONS,
9
11
  resolveContainment,
10
12
  snapNodePosition,
11
13
  } from './modules/core/index.js';
12
- import { DiagramRenderer } from './modules/renderer-svg/index.js';
14
+ import { DiagramRenderer, ZOOM_LIMITS } from './modules/renderer-svg/index.js';
13
15
  import { hydrateIcons } from './modules/icons/index.js';
14
16
  import { canCreateSequenceFlow } from './controller.js';
15
17
  import { createDefaultContextMenuRegistry } from './context-menu.js';
@@ -34,6 +36,31 @@ function toolbarIcon(id) {
34
36
  return icon;
35
37
  }
36
38
 
39
+ // Fit-to-bounds keeps a narrower range than the renderer's own zoom limits so
40
+ // a single small element does not blow up to 200%. fitSelection() and
41
+ // revealElement({ zoom: 'fit' }) share these two helpers, so the acceptance
42
+ // requirement "fit equals fitSelection" holds by construction.
43
+ const FIT_ZOOM_LIMITS = Object.freeze({ min: 0.5, max: 2 });
44
+
45
+ function fitZoomForBounds(bounds, viewportRect, padding) {
46
+ const availableWidth = Math.max(1, viewportRect.width - padding * 2);
47
+ const availableHeight = Math.max(1, viewportRect.height - padding * 2);
48
+ return Math.max(FIT_ZOOM_LIMITS.min, Math.min(FIT_ZOOM_LIMITS.max, Math.min(
49
+ availableWidth / Math.max(bounds.width, 1),
50
+ availableHeight / Math.max(bounds.height, 1),
51
+ )));
52
+ }
53
+
54
+ function viewportStateCenteredOn(bounds, viewportRect, zoom) {
55
+ return {
56
+ zoom,
57
+ pan: {
58
+ x: viewportRect.width / 2 - (bounds.x + bounds.width / 2) * zoom,
59
+ y: viewportRect.height / 2 - (bounds.y + bounds.height / 2) * zoom,
60
+ },
61
+ };
62
+ }
63
+
37
64
  export class BpmnCanvas {
38
65
  constructor({ container, studio, rendererOptions = {}, nodeSubtitleResolver = rendererOptions.nodeSubtitleResolver, interactions = null, selectionToolbar = null, contextMenu = null, contextMenuRegistry = createDefaultContextMenuRegistry(), pointerMode = 'select', themeController = null, theme = null, onThemeChange = null } = {}) {
39
66
  if (!container) throw new Error('BpmnCanvas requires a container.');
@@ -81,7 +108,7 @@ export class BpmnCanvas {
81
108
  },
82
109
  onStartConnect: (node) => studio.startConnect(node.id),
83
110
  canConnect: (source, target) => canCreateSequenceFlow(studio.model, source.id, target.id),
84
- canCreateNodeType: (nodeType) => studio.allowsNodeType(nodeType),
111
+ canCreateNodeType: (nodeType) => studio.canAddNode(nodeType),
85
112
  onQuickAdd: (source, type, preset) => studio.commands.quickAdd(source.id, type, preset),
86
113
  onDeleteNode: (node) => studio.commands.remove({ kind: 'node', id: node.id }),
87
114
  onUngroup: (node) => studio.commands.ungroup(node.id),
@@ -913,21 +940,58 @@ export class BpmnCanvas {
913
940
  const bounds = this.studio.getSelectionBounds();
914
941
  if (!bounds) return false;
915
942
  const rect = this.renderer.viewport.getBoundingClientRect();
916
- const availableWidth = Math.max(1, rect.width - padding * 2);
917
- const availableHeight = Math.max(1, rect.height - padding * 2);
918
- const zoom = Math.max(0.5, Math.min(2, Math.min(availableWidth / Math.max(bounds.width, 1), availableHeight / Math.max(bounds.height, 1))));
919
- this.renderer.setViewportState({
920
- zoom,
921
- pan: {
922
- x: rect.width / 2 - (bounds.x + bounds.width / 2) * zoom,
923
- y: rect.height / 2 - (bounds.y + bounds.height / 2) * zoom,
924
- },
925
- });
943
+ const zoom = fitZoomForBounds(bounds, rect, padding);
944
+ this.renderer.setViewportState(viewportStateCenteredOn(bounds, rect, zoom));
945
+ return true;
946
+ }
947
+ // Locate a single node or edge without changing getSelectionBounds() or
948
+ // fitSelection() semantics. Edges use their routed waypoints, so auto-routed
949
+ // connections (empty waypoints) work as well.
950
+ revealElement(id, options = {}) {
951
+ const studio = this.studio;
952
+ const model = studio.model;
953
+ const requestedKind = options.kind === 'node' || options.kind === 'edge' ? options.kind : null;
954
+ const node = requestedKind === 'edge' ? null : getNode(model, id);
955
+ const edge = node || requestedKind === 'node' ? null : getEdge(model, id);
956
+ if (!node && !edge) return false;
957
+ const element = node || edge;
958
+ const kind = node ? 'node' : 'edge';
959
+ const padding = Number.isFinite(options.padding) && options.padding >= 0 ? options.padding : 72;
960
+ let bounds;
961
+ if (node) {
962
+ bounds = { x: element.x, y: element.y, width: element.width, height: element.height };
963
+ } else {
964
+ const points = edgeWaypoints(model, element);
965
+ if (!points.length) return false;
966
+ const xs = points.map((point) => point.x);
967
+ const ys = points.map((point) => point.y);
968
+ const minX = Math.min(...xs);
969
+ const minY = Math.min(...ys);
970
+ bounds = { x: minX, y: minY, width: Math.max(...xs) - minX, height: Math.max(...ys) - minY };
971
+ }
972
+ // A straight horizontal/vertical edge has a zero-width/height box; expand
973
+ // it by padding so fit zoom stays finite and the line keeps breathing room.
974
+ if (!bounds.width) bounds = { ...bounds, x: bounds.x - padding, width: padding * 2 };
975
+ if (!bounds.height) bounds = { ...bounds, y: bounds.y - padding, height: padding * 2 };
976
+ const scopeId = elementScopeId(model, element);
977
+ if (scopeId !== studio.activeScopeId) studio.navigateToScope(scopeId);
978
+ const rect = this.renderer.viewport.getBoundingClientRect();
979
+ let zoom;
980
+ if (options.zoom === 'fit') {
981
+ zoom = fitZoomForBounds(bounds, rect, padding);
982
+ } else if (typeof options.zoom === 'number' && Number.isFinite(options.zoom)) {
983
+ zoom = Math.max(ZOOM_LIMITS.min, Math.min(ZOOM_LIMITS.max, options.zoom));
984
+ } else {
985
+ zoom = this.renderer.zoom;
986
+ }
987
+ this.renderer.setViewportState(viewportStateCenteredOn(bounds, rect, zoom));
988
+ if (options.select !== false) studio.select({ kind, id: element.id });
926
989
  return true;
927
990
  }
928
991
  zoomBy(factor) { this.renderer.zoomBy(factor); }
929
992
  actualSize(padding) { this.renderer.actualSize(padding); }
930
993
  getViewportState() { return this.renderer.getViewportState(); }
994
+ setViewportState(state) { return this.renderer.setViewportState(state); }
931
995
  setTheme(theme) { return this.renderer.setTheme(theme); }
932
996
  setThemeMode(mode) { return this.renderer.setThemeMode(mode); }
933
997
  getThemeState() { return this.renderer.getThemeState(); }
package/dist/config.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { NODE_DEFINITIONS } from './modules/core/index.js';
2
+
1
3
  const CONTROL_SIZE_PRESETS = Object.freeze({
2
4
  small: 28,
3
5
  medium: 32,
@@ -58,6 +60,22 @@ function optionalTypeList(value, path) {
58
60
  return Object.freeze(entries);
59
61
  }
60
62
 
63
+ function normalizeNodeLimits(value) {
64
+ if (value === undefined || value === null) return undefined;
65
+ assertObject(value, 'config.modeling.nodeLimits');
66
+ const normalized = {};
67
+ for (const [nodeType, limit] of Object.entries(value)) {
68
+ if (!NODE_DEFINITIONS[nodeType] || nodeType === 'generic') {
69
+ throw new TypeError(`config.modeling.nodeLimits contains unknown BPMN node type: ${nodeType}`);
70
+ }
71
+ if (!isObject(limit) || !Number.isInteger(limit.max) || limit.max < 0) {
72
+ throw new TypeError(`config.modeling.nodeLimits.${nodeType}.max must be a non-negative integer.`);
73
+ }
74
+ normalized[nodeType] = Object.freeze({ max: limit.max });
75
+ }
76
+ return Object.freeze(normalized);
77
+ }
78
+
61
79
  function normalizePropertiesProfile(value) {
62
80
  if (value === undefined) return 'business';
63
81
  if (value !== 'business' && value !== 'developer') {
@@ -216,6 +234,7 @@ export function normalizeStudioConfig(config, { fallback = null, legacy = null }
216
234
  const controlSize = normalizeStudioControlSize(uiInput.controlSize);
217
235
  const allowedNodeTypes = optionalTypeList(modelingInput.allowedNodeTypes, 'config.modeling.allowedNodeTypes');
218
236
  const allowedEdgeTypes = optionalTypeList(modelingInput.allowedEdgeTypes, 'config.modeling.allowedEdgeTypes');
237
+ const nodeLimits = normalizeNodeLimits(modelingInput.nodeLimits);
219
238
  const responsive = viewerInput.responsive === undefined ? false : viewerInput.responsive;
220
239
  if (typeof responsive !== 'boolean') throw new TypeError('config.viewer.responsive must be a boolean.');
221
240
 
@@ -223,6 +242,7 @@ export function normalizeStudioConfig(config, { fallback = null, legacy = null }
223
242
  propertiesProfile: normalizePropertiesProfile(modelingInput.propertiesProfile),
224
243
  ...(allowedNodeTypes ? { allowedNodeTypes } : {}),
225
244
  ...(allowedEdgeTypes ? { allowedEdgeTypes } : {}),
245
+ ...(nodeLimits ? { nodeLimits } : {}),
226
246
  };
227
247
  const ui = {
228
248
  controlSize,
@@ -105,6 +105,7 @@ export class BpmnStudioController {
105
105
  const normalizedConfig = normalizeStudioConfig(config, { legacy });
106
106
  this._allowedNodeTypes = normalizeAllowedNodeTypes(normalizedConfig.modeling.allowedNodeTypes);
107
107
  this._allowedEdgeTypes = normalizeAllowedEdgeTypes(normalizedConfig.modeling.allowedEdgeTypes);
108
+ this._nodeLimits = normalizedConfig.modeling.nodeLimits || null;
108
109
  this._assertAllowedModel(model);
109
110
  this._model = model;
110
111
  this.history = new HistoryStack(historyLimit);
@@ -164,6 +165,35 @@ export class BpmnStudioController {
164
165
  && (!this._allowedEdgeTypes || this._allowedEdgeTypes.has(edgeType));
165
166
  }
166
167
 
168
+ _countNodesOfType(nodeType) {
169
+ let count = 0;
170
+ for (const node of this._model.nodes) if (node.type === nodeType) count += 1;
171
+ return count;
172
+ }
173
+
174
+ // Node limits count the whole model, including every subprocess scope, and
175
+ // like allowedNodeTypes are fixed when the controller is constructed.
176
+ canAddNode(nodeType, count = 1) {
177
+ if (!this.allowsNodeType(nodeType)) return false;
178
+ const limit = this._nodeLimits?.[nodeType];
179
+ if (!limit) return true;
180
+ return this._countNodesOfType(nodeType) + count <= limit.max;
181
+ }
182
+
183
+ canChangeNodeType(id, type) {
184
+ if (!this.allowsNodeType(type)) return false;
185
+ const node = getNode(this._model, id);
186
+ if (!node) return false;
187
+ if (node.type === type) return true;
188
+ return this.canAddNode(type, 1);
189
+ }
190
+
191
+ nodeLimitReason(nodeType, count = 1) {
192
+ const limit = this._nodeLimits?.[nodeType];
193
+ if (!limit || this._countNodesOfType(nodeType) + count <= limit.max) return null;
194
+ return `最多 ${limit.max} 个${NODE_DEFINITIONS[nodeType]?.label || nodeType}`;
195
+ }
196
+
167
197
  _assertAllowedModel(model) {
168
198
  if (this._allowedNodeTypes) {
169
199
  const unsupportedNode = model?.nodes?.find((node) => !this._allowedNodeTypes.has(node.type));
@@ -177,6 +207,16 @@ export class BpmnStudioController {
177
207
  throw new Error(`BPMN edge type is not allowed: ${unsupportedEdge.type || 'sequenceFlow'} (${unsupportedEdge.id})`);
178
208
  }
179
209
  }
210
+ if (this._nodeLimits) {
211
+ const counts = new Map();
212
+ for (const node of model?.nodes || []) counts.set(node.type, (counts.get(node.type) || 0) + 1);
213
+ for (const [nodeType, count] of counts) {
214
+ const limit = this._nodeLimits[nodeType];
215
+ if (limit && count > limit.max) {
216
+ throw new Error(`BPMN node limit exceeded: ${nodeType} (max ${limit.max}, found ${count})`);
217
+ }
218
+ }
219
+ }
180
220
  }
181
221
 
182
222
  getState() {
@@ -191,6 +231,9 @@ export class BpmnStudioController {
191
231
  propertiesProfile: this.propertiesProfile,
192
232
  allowedNodeTypes: this._allowedNodeTypes ? [...this._allowedNodeTypes] : null,
193
233
  allowedEdgeTypes: this._allowedEdgeTypes ? [...this._allowedEdgeTypes] : null,
234
+ nodeLimits: this._nodeLimits
235
+ ? Object.fromEntries(Object.entries(this._nodeLimits).map(([nodeType, limit]) => [nodeType, { ...limit }]))
236
+ : null,
194
237
  activeScopeId: this.activeScopeId,
195
238
  scopePath: getScopePath(this._model, this.activeScopeId),
196
239
  };
@@ -379,6 +422,7 @@ export class BpmnStudioController {
379
422
  const def = NODE_DEFINITIONS[nodeType];
380
423
  if (!def) throw new Error(`Unknown BPMN node type: ${nodeType}`);
381
424
  if (!this.allowsNodeType(nodeType)) throw new Error(`BPMN node type is not allowed: ${nodeType}`);
425
+ if (!this.canAddNode(nodeType)) throw new Error(`BPMN node limit reached: ${nodeType} (max ${this._nodeLimits[nodeType].max})`);
382
426
  const position = point || { x: 100, y: 100 };
383
427
  let node;
384
428
  this._commit('create-node', () => {
@@ -404,11 +448,18 @@ export class BpmnStudioController {
404
448
  const nodeSpecs = template.nodes || [];
405
449
  if (!nodeSpecs.length) throw new Error('A template must contain at least one node.');
406
450
  const keys = new Set();
451
+ const typeCounts = new Map();
407
452
  for (const spec of nodeSpecs) {
408
453
  if (!spec.key || keys.has(spec.key)) throw new Error('Template node keys must be unique.');
409
454
  if (!NODE_DEFINITIONS[spec.nodeType]) throw new Error(`Unknown BPMN node type: ${spec.nodeType}`);
410
455
  if (!this.allowsNodeType(spec.nodeType)) throw new Error(`BPMN node type is not allowed: ${spec.nodeType}`);
411
456
  keys.add(spec.key);
457
+ typeCounts.set(spec.nodeType, (typeCounts.get(spec.nodeType) || 0) + 1);
458
+ }
459
+ // Limits apply to the template's combined per-type counts, checked before
460
+ // any commit so a rejected template leaves model and history untouched.
461
+ for (const [nodeType, count] of typeCounts) {
462
+ if (!this.canAddNode(nodeType, count)) throw new Error(`BPMN node limit reached: ${nodeType} (max ${this._nodeLimits[nodeType].max})`);
412
463
  }
413
464
  for (const edge of template.edges || []) {
414
465
  if (!keys.has(edge.source) || !keys.has(edge.target)) throw new Error('Template edge references an unknown node key.');
@@ -592,7 +643,7 @@ export class BpmnStudioController {
592
643
  changeNodeType(id, type) {
593
644
  const node = getNode(this._model, id);
594
645
  const def = NODE_DEFINITIONS[type];
595
- if (!node || !def || !this.allowsNodeType(type) || node.type === type) return false;
646
+ if (!node || !def || !this.canChangeNodeType(id, type) || node.type === type) return false;
596
647
  if (isEmbeddedSubProcess(node) && !isEmbeddedSubProcess(type) && hasScopeChildren(this._model, id)) return false;
597
648
  this._commit('change-node-type', () => {
598
649
  const next = createNode(type, node.x, node.y, { id: node.id, name: node.name });
@@ -609,7 +660,7 @@ export class BpmnStudioController {
609
660
  if (!this.allowsEdgeType('sequenceFlow')) return null;
610
661
  const source = getNode(this._model, sourceId);
611
662
  const def = NODE_DEFINITIONS[type];
612
- if (!source || elementScopeId(this._model, source) !== this.activeScopeId || !def || !this.allowsNodeType(type)) return null;
663
+ if (!source || elementScopeId(this._model, source) !== this.activeScopeId || !def || !this.canAddNode(type)) return null;
613
664
  const direction = this._model.settings?.direction || 'horizontal';
614
665
  const spacing = LAYOUT_DENSITIES[this._model.settings?.layoutDensity || 'balanced'] || LAYOUT_DENSITIES.balanced;
615
666
  const outgoingCount = this._model.edges.filter((edge) => edge.source === sourceId).length;
package/dist/index.d.ts CHANGED
@@ -209,6 +209,7 @@ export interface StudioState {
209
209
  propertiesProfile: 'business' | 'developer'
210
210
  allowedNodeTypes: NodeType[] | null
211
211
  allowedEdgeTypes: EdgeType[] | null
212
+ nodeLimits: StudioNodeLimits | null
212
213
  activeScopeId: string
213
214
  scopePath: Array<{ id: string; name: string; kind: 'process' | 'subProcess' }>
214
215
  }
@@ -232,10 +233,14 @@ export interface StudioExtension {
232
233
  setup(context: { studio: BpmnStudioController }): void | (() => void)
233
234
  }
234
235
  export type StudioControlSize = 'small' | 'medium' | 'large' | `${number}px`
236
+ /** Per-type node caps counted across the whole model (all subprocess scopes). Fixed at controller construction. */
237
+ export type StudioNodeLimits = Partial<Record<NodeType, { max: number }>>
235
238
  export interface StudioModelingConfig {
236
239
  propertiesProfile?: 'business' | 'developer'
237
240
  allowedNodeTypes?: readonly NodeType[]
238
241
  allowedEdgeTypes?: readonly EdgeType[]
242
+ /** For example `{ startEvent: { max: 1 } }`. `max` must be a non-negative integer; unknown node types throw TypeError. */
243
+ nodeLimits?: StudioNodeLimits
239
244
  }
240
245
  export interface StudioSidebarConfig {
241
246
  /** Defaults to true. Disabling collapse keeps an available sidebar expanded. */
@@ -358,6 +363,12 @@ export class BpmnStudioController {
358
363
  setPropertiesProfile(profile: 'business' | 'developer'): void
359
364
  allowsNodeType(nodeType: NodeType): boolean
360
365
  allowsEdgeType(edgeType: EdgeType): boolean
366
+ /** Type is allowed and adding `count` nodes (default 1) stays within config.modeling.nodeLimits, counted across the whole model. */
367
+ canAddNode(nodeType: NodeType, count?: number): boolean
368
+ /** Type is allowed and converting node `id` to it stays within node limits; a node already of that type does not count again. */
369
+ canChangeNodeType(id: string, type: NodeType): boolean
370
+ /** Human-readable limit reason (for example `最多 1 个开始事件`) when adding `count` nodes (default 1) would exceed the cap, otherwise null. */
371
+ nodeLimitReason(nodeType: NodeType, count?: number): string | null
361
372
  startConnect(sourceId: string): boolean
362
373
  cancelConnect(): void
363
374
  createNode(input: Parameters<StudioCommands['createNode']>[0]): BpmnNode
@@ -407,6 +418,10 @@ export class InteractionController {
407
418
  beginCreate(intent: CreateIntent): { intent: CreateIntent; startedAt: number }
408
419
  serialize(session: unknown): string
409
420
  deserialize(value: string): unknown
421
+ /** Readable reason when this create intent would exceed config.modeling.nodeLimits, otherwise null. Templates are judged by their combined per-type counts. */
422
+ createBlockedReason(intent: CreateIntent, point?: Point | null): string | null
423
+ /** Readable reason when a template definition would exceed node limits, otherwise null. */
424
+ templateLimitReason(definition: TemplateDefinition | null | undefined): string | null
410
425
  drop(session: unknown, pointer: { clientX: number; clientY: number }, canvas: { clientToWorld(x: number, y: number): Point }): unknown
411
426
  }
412
427
  export function createTemplateRegistry(templates?: TemplateRegistration[]): TemplateRegistry
@@ -480,6 +495,16 @@ export interface BpmnCanvasOptions {
480
495
  theme?: NovaThemeInput
481
496
  onThemeChange?: (state: NovaThemeState) => void
482
497
  }
498
+ export interface CanvasRevealElementOptions {
499
+ /** Restrict the lookup to nodes or edges; by id alone nodes are searched first. */
500
+ kind?: 'node' | 'edge'
501
+ /** Select the element after revealing it. Defaults to true. */
502
+ select?: boolean
503
+ /** 'keep' (default) only pans; 'fit' reuses fitSelection's zoom computation; a number targets that zoom, clamped to the renderer's 0.25–2.25 limits. */
504
+ zoom?: 'keep' | 'fit' | number
505
+ /** Padding around the element for fit zoom and zero-size edge boxes. Defaults to 72. */
506
+ padding?: number
507
+ }
483
508
  export class BpmnCanvas {
484
509
  constructor(options: BpmnCanvasOptions)
485
510
  clientToWorld(clientX: number, clientY: number): Point
@@ -487,6 +512,10 @@ export class BpmnCanvas {
487
512
  fitView(padding?: number, options?: Record<string, unknown>): void
488
513
  refreshPresentation(): void
489
514
  fitSelection(padding?: number): boolean
515
+ /** Center the viewport on a node or edge (auto-routed edges included), switching scope when needed. Returns false when the id is unknown, leaving viewport and selection untouched. */
516
+ revealElement(id: string, options?: CanvasRevealElementOptions): boolean
517
+ /** Delegate to the renderer viewport: apply zoom and pan in one step. */
518
+ setViewportState(state: { zoom: number; pan: Point }): boolean
490
519
  setPointerMode(mode: 'select' | 'marquee' | 'pan'): boolean
491
520
  getPointerMode(): 'select' | 'marquee' | 'pan'
492
521
  zoomBy(factor: number): void
@@ -32,11 +32,59 @@ export class InteractionController {
32
32
  }
33
33
  deserialize(value) { return this.beginCreate(JSON.parse(value)); }
34
34
 
35
+ /**
36
+ * Node-limit gate shared by drop() and palette availability. Returns a
37
+ * readable reason when creating this intent would exceed
38
+ * config.modeling.nodeLimits, otherwise null. Templates are judged by their
39
+ * combined per-type counts, matching createTemplate().
40
+ */
41
+ createBlockedReason(intent, point = null) {
42
+ if (!intent || typeof this.studio?.canAddNode !== 'function') return null;
43
+ if (intent.kind === 'node') {
44
+ return this.studio.canAddNode(intent.nodeType) ? null : this._nodeLimitReason(intent.nodeType);
45
+ }
46
+ if (intent.kind !== 'template') return null;
47
+ const template = this.templates.resolve(intent.templateId);
48
+ if (!template) return null;
49
+ let definition;
50
+ try {
51
+ definition = template.create({ studio: this.studio, point: point || { x: 0, y: 0 }, intent });
52
+ } catch {
53
+ // A host template that cannot be built without a real drop point keeps
54
+ // its current behaviour instead of being silently disabled.
55
+ return null;
56
+ }
57
+ return this.templateLimitReason(definition);
58
+ }
59
+
60
+ /** Readable reason when a template definition would exceed node limits. */
61
+ templateLimitReason(definition) {
62
+ if (typeof this.studio?.canAddNode !== 'function') return null;
63
+ const counts = new Map();
64
+ for (const spec of definition?.nodes || []) {
65
+ if (!spec?.nodeType) continue;
66
+ counts.set(spec.nodeType, (counts.get(spec.nodeType) || 0) + 1);
67
+ }
68
+ for (const [nodeType, count] of counts) {
69
+ if (!this.studio.canAddNode(nodeType, count)) return this._nodeLimitReason(nodeType, count);
70
+ }
71
+ return null;
72
+ }
73
+
74
+ _nodeLimitReason(nodeType, count = 1) {
75
+ const reason = this.studio.nodeLimitReason?.(nodeType, count);
76
+ if (reason) return reason;
77
+ return `已达${NODE_DEFINITIONS[nodeType]?.label || nodeType}数量上限`;
78
+ }
79
+
35
80
  drop(session, pointer, canvas) {
36
81
  if (!session?.intent || !canvas?.clientToWorld) throw new Error('Drop requires a create session and canvas coordinate adapter.');
37
82
  const point = canvas.clientToWorld(pointer.clientX, pointer.clientY);
38
83
  const intent = session.intent;
39
84
  if (intent.kind === 'node') {
85
+ // UI drops must not throw into DOM event callbacks when the type is
86
+ // disallowed or its node limit is already reached.
87
+ if (this.createBlockedReason(intent)) return null;
40
88
  const definition = NODE_DEFINITIONS[intent.nodeType];
41
89
  const centered = definition ? { x: point.x - definition.width / 2, y: point.y - definition.height / 2 } : point;
42
90
  return this.studio.commands.createNode({ nodeType: intent.nodeType, point: centered, preset: intent.preset });
@@ -44,7 +92,11 @@ export class InteractionController {
44
92
  if (intent.kind === 'template') {
45
93
  const template = this.templates.resolve(intent.templateId);
46
94
  if (!template) throw new Error(`Unknown template: ${intent.templateId}`);
47
- return this.studio.commands.createTemplate(template.create({ studio: this.studio, point, intent }), point);
95
+ const definition = template.create({ studio: this.studio, point, intent });
96
+ // Same guard as nodes: a template that would exceed a node limit returns
97
+ // null instead of throwing into the drop event, and commits nothing.
98
+ if (this.templateLimitReason(definition)) return null;
99
+ return this.studio.commands.createTemplate(definition, point);
48
100
  }
49
101
  return intent.run?.({ studio: this.studio, point }) || null;
50
102
  }
@@ -54,8 +54,20 @@ export type PaletteSectionRenderer = (context: {
54
54
  export interface PalettePanelOptions {
55
55
  container: HTMLElement
56
56
  registry: PaletteRegistry
57
- studio: { getState(): unknown }
58
- interactions: { beginCreate(intent: PaletteCreateIntent): unknown; serialize(session: unknown): string }
57
+ studio: {
58
+ getState(): unknown
59
+ model?: unknown
60
+ /** When present, the panel refreshes item availability on modelChanged. */
61
+ subscribe?(listener: (event: { type: string }) => void): () => void
62
+ canAddNode?(nodeType: NodeType, count?: number): boolean
63
+ nodeLimitReason?(nodeType: NodeType, count?: number): string | null
64
+ }
65
+ interactions: {
66
+ beginCreate(intent: PaletteCreateIntent): unknown
67
+ serialize(session: unknown): string
68
+ /** When present, template items are greyed out while a node limit blocks them. */
69
+ createBlockedReason?(intent: PaletteCreateIntent, point?: unknown): string | null
70
+ }
59
71
  canvas?: unknown
60
72
  iconRegistry?: IconRegistry
61
73
  renderItem?: PaletteItemRenderer | null
@@ -19,11 +19,18 @@ export class PalettePanel {
19
19
  this.themeController = themeController || new ThemeController({ root: container, theme, onChange: onThemeChange });
20
20
  this._ownsThemeController = !themeController;
21
21
  this._cleanups = [];
22
+ this._itemButtons = [];
23
+ // Node-limit availability changes with the model. Refresh item state in
24
+ // place instead of re-rendering so section expansion and focus survive.
25
+ this._offStudio = typeof studio.subscribe === 'function'
26
+ ? studio.subscribe((event) => { if (event.type === 'modelChanged') this._refreshAvailability(); })
27
+ : null;
22
28
  this.render();
23
29
  }
24
30
 
25
31
  render() {
26
32
  this._cleanups.splice(0).forEach((cleanup) => cleanup?.());
33
+ this._itemButtons = [];
27
34
  this.container.innerHTML = '';
28
35
  this.container.classList.add('nova-palette');
29
36
  const sections = this.registry.resolve({ studio: this.studio, model: this.studio.model });
@@ -62,8 +69,9 @@ export class PalettePanel {
62
69
  }
63
70
  const button = element('button', 'nova-palette-item');
64
71
  button.type = 'button';
65
- button.draggable = Boolean(item.create && item.create.kind !== 'action');
66
- button.title = item.description || item.label;
72
+ const record = { item, button };
73
+ this._itemButtons.push(record);
74
+ this._applyItemAvailability(record);
67
75
  const iconHost = element('span', 'nova-palette-item-icon');
68
76
  const icon = createIconElement(this.iconRegistry.resolve(item.iconId), { title: item.label });
69
77
  if (icon) iconHost.appendChild(icon);
@@ -86,8 +94,41 @@ export class PalettePanel {
86
94
  return host;
87
95
  }
88
96
 
97
+ // Applies to default and custom provider items alike; custom renderers
98
+ // (renderItem) own their DOM and can query studio.canAddNode themselves.
99
+ _itemDisabledReason(item) {
100
+ const create = item.create;
101
+ if (create?.kind === 'node') {
102
+ if (this.studio.canAddNode?.(create.nodeType) !== false) return null;
103
+ return this.studio.nodeLimitReason?.(create.nodeType) || '该节点类型当前不可用';
104
+ }
105
+ if (create?.kind === 'template') {
106
+ // Templates are judged by their combined per-type counts; the interaction
107
+ // controller owns that check so palette and drop stay in sync.
108
+ return this.interactions?.createBlockedReason?.(create) || null;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ _applyItemAvailability(record) {
114
+ const { item, button } = record;
115
+ const reason = this._itemDisabledReason(item);
116
+ button.disabled = Boolean(reason);
117
+ button.draggable = Boolean(item.create && item.create.kind !== 'action') && !reason;
118
+ button.title = reason || item.description || item.label;
119
+ if (reason) button.setAttribute('aria-disabled', 'true');
120
+ else button.removeAttribute('aria-disabled');
121
+ }
122
+
123
+ _refreshAvailability() {
124
+ for (const record of this._itemButtons) this._applyItemAvailability(record);
125
+ }
126
+
89
127
  destroy() {
128
+ this._offStudio?.();
129
+ this._offStudio = null;
90
130
  this._cleanups.splice(0).forEach((cleanup) => cleanup?.());
131
+ this._itemButtons = [];
91
132
  this.container.innerHTML = '';
92
133
  this.container.classList.remove('nova-palette');
93
134
  if (this._ownsThemeController) this.themeController.destroy();
@@ -19,7 +19,7 @@ function nodeTypeOptions(context) {
19
19
  return Object.entries(NODE_DEFINITIONS)
20
20
  .filter(([type, def]) => type !== 'generic'
21
21
  && compatible.includes(def.kind)
22
- && context.studio?.allowsNodeType?.(type) !== false)
22
+ && context.studio?.canChangeNodeType?.(context.element?.id, type) !== false)
23
23
  .map(([value, def]) => ({ value, label: def.label }));
24
24
  }
25
25
 
@@ -5,6 +5,9 @@ import type { NovaThemeInput, NovaThemeMode, NovaThemeState, RuntimeAppearanceRe
5
5
  import type { SvgExportArtifact, SvgExportOptions, SvgExportPreviewController, SvgNodeRenderer } from '../export-svg/index.js'
6
6
  import type { NodeSubtitleResolver } from '../node-presentation/index.js'
7
7
 
8
+ /** Viewport zoom range shared by the renderer and callers that clamp a requested zoom. */
9
+ export const ZOOM_LIMITS: { readonly min: number; readonly max: number }
10
+
8
11
  export interface SceneBounds {
9
12
  left: number
10
13
  top: number
@@ -9,12 +9,19 @@ import { exportDiagramSvg, openSvgExportPreview } from '../export-svg/index.js';
9
9
  const SVG_NS = 'http://www.w3.org/2000/svg';
10
10
  const XHTML_NS = 'http://www.w3.org/1999/xhtml';
11
11
 
12
+ /**
13
+ * Single source of truth for the viewport zoom range. Callers that need to
14
+ * clamp a requested zoom (for example BpmnCanvas.revealElement) read these
15
+ * limits instead of duplicating the numbers.
16
+ */
17
+ export const ZOOM_LIMITS = Object.freeze({ min: 0.25, max: 2.25 });
18
+
12
19
  function clamp(value, min, max) {
13
20
  return Math.max(min, Math.min(max, value));
14
21
  }
15
22
 
16
23
  function quantizeZoom(value, step = 0.05) {
17
- const clamped = clamp(value, 0.25, 2.25);
24
+ const clamped = clamp(value, ZOOM_LIMITS.min, ZOOM_LIMITS.max);
18
25
  return Math.round(Math.round(clamped / step) * step * 1000) / 1000;
19
26
  }
20
27
 
@@ -739,7 +746,7 @@ export class DiagramRenderer {
739
746
  const rect = this.viewport.getBoundingClientRect();
740
747
  if (rect.width < 1 || rect.height < 1) return;
741
748
  const maxZoom = options.maxZoom ?? 1.15;
742
- const minZoom = options.minZoom ?? 0.25;
749
+ const minZoom = options.minZoom ?? ZOOM_LIMITS.min;
743
750
  const rawZoom = Math.min((rect.width - padding * 2) / boundsW, (rect.height - padding * 2) / boundsH, maxZoom);
744
751
  let nextZoom = clamp(rawZoom, minZoom, maxZoom);
745
752
  if (options.snapZoom !== false) nextZoom = quantizeZoom(nextZoom, options.zoomStep ?? 0.05);
package/llms-full.txt CHANGED
@@ -323,7 +323,7 @@ Before changing Nova package versions, publishing, or recovering a partial relea
323
323
  - **流程展示**:只读 BPMN、实际审批路径、移动时间线和完整 BPMN 运行态。
324
324
  - **嵌入与扩展**:宿主布局、业务属性、节点内容、主题、审批详情及纯 SVG 导出。
325
325
 
326
- 当前版本为 **`0.3.7-preview`**,使用 `@preview` 安装。组件负责建模、展示和交互;流程执行、审批提交及权限由宿主业务系统负责。完整能力与 Preview 边界见[项目介绍](https://github.com/daxiangme/bpmn-nova/blob/dev/docs/src/guide/overview.md)。
326
+ 当前版本为 **`0.3.8-preview`**,使用 `@preview` 安装。组件负责建模、展示和交互;流程执行、审批提交及权限由宿主业务系统负责。完整能力与 Preview 边界见[项目介绍](https://github.com/daxiangme/bpmn-nova/blob/dev/docs/src/guide/overview.md)。
327
327
 
328
328
  ## 安装
329
329
 
@@ -412,7 +412,7 @@ npm run docs:ai:check
412
412
  BPMN Nova 提供可嵌入的流程设计器、只读 Viewer、运行态审批轨迹、实例级主题、纯 SVG 导出,以及 React / Vue 适配。项目使用独立的 DOM / SVG 渲染实现,不依赖 `bpmn-js`,并为 Flowable 与 Activiti 提供 XML Profile 和属性扩展。
413
413
 
414
414
  > [!IMPORTANT]
415
- > 当前版本为 `0.3.7-preview`。它适合 SDK 评估、产品集成验证和企业审批原型;公开 Interface、BPMN XML round-trip 与引擎兼容能力仍在持续稳定中,建议使用 `@preview` 安装并在生产接入前完成目标流程验证。
415
+ > 当前版本为 `0.3.8-preview`。它适合 SDK 评估、产品集成验证和企业审批原型;公开 Interface、BPMN XML round-trip 与引擎兼容能力仍在持续稳定中,建议使用 `@preview` 安装并在生产接入前完成目标流程验证。
416
416
 
417
417
  AI 或代码生成工具接入必须从 [`llms.txt`](https://github.com/daxiangme/bpmn-nova/blob/dev/llms.txt) 的完整安装流程开始;需要全部接口与定制上下文时再读取 [`llms-full.txt`](https://github.com/daxiangme/bpmn-nova/blob/dev/llms-full.txt)。这两份文件也会随三个公开 npm 包发布。
418
418
 
@@ -1842,7 +1842,7 @@ export function createAssetResolver(resolveAssetUrl: ResolveAssetUrl): RuntimeAs
1842
1842
 
1843
1843
  # BPMN Nova 快速开始
1844
1844
 
1845
- 本文面向通过 NPM 集成 BPMN Nova 的应用开发者。版本 `0.3.7-preview` 要求现代浏览器;Node.js 18+ 用于构建、SSR 和开发工具。
1845
+ 本文面向通过 NPM 集成 BPMN Nova 的应用开发者。版本 `0.3.8-preview` 要求现代浏览器;Node.js 18+ 用于构建、SSR 和开发工具。
1846
1846
 
1847
1847
  ## 1. 按语言与框架选择入口
1848
1848
 
@@ -2318,7 +2318,7 @@ BPMN Nova 的 Vanilla JavaScript / TypeScript 完整入口,提供流程设计
2318
2318
 
2319
2319
  > **English summary:** The complete framework-neutral BPMN Nova package for process design, viewing, approval traces, themes, properties, and pure SVG export.
2320
2320
 
2321
- > 当前版本为 `0.3.7-preview`。请使用 `@preview` 安装,并在生产接入前验证目标 BPMN XML 与引擎扩展。
2321
+ > 当前版本为 `0.3.8-preview`。请使用 `@preview` 安装,并在生产接入前验证目标 BPMN XML 与引擎扩展。
2322
2322
 
2323
2323
  ![BPMN Nova 流程设计器](../../assets/bpmn-nova-designer.jpg)
2324
2324
 
@@ -2391,6 +2391,22 @@ studio.destroy()
2391
2391
 
2392
2392
  `allowedNodeTypes` 与 `allowedEdgeTypes` 同时约束 XML 导入、Palette、连接、快捷新增、模板和节点类型转换;不传时开放 Nova 当前支持的全部图元。`allowedModes` 控制默认工作台显示和允许切换的模式。不传 Runtime 时实例模式保持空运行事实,不会注入演示审批数据。
2393
2393
 
2394
+ `config.modeling.nodeLimits`(自 0.3.8-preview 起)在白名单之外再限制每种类型的数量,只在创建 Controller 时生效:
2395
+
2396
+ ```js
2397
+ const studio = createStudioController({
2398
+ model,
2399
+ config: { modeling: { nodeLimits: { startEvent: { max: 1 } } } },
2400
+ })
2401
+
2402
+ studio.canAddNode('startEvent') // 已有一个开始事件时为 false
2403
+ studio.nodeLimitReason('startEvent') // '最多 1 个开始事件'
2404
+ studio.canChangeNodeType('EndEvent_1', 'startEvent') // false
2405
+ studio.getState().nodeLimits // 上限配置的副本
2406
+ ```
2407
+
2408
+ 超限时 `createNode()` 与 `createTemplate()` 抛出含 `limit` 的错误,`quickAdd()` 返回 `null`,`changeNodeType()` 返回 `false`,导入超限 XML 抛错且不改变当前模型;失败都不触发 `modelChanged`、不写入撤销栈。默认 Palette(含宿主注册的自定义项)会禁用对应按钮并显示原因,含超限类型的**模板项**同样置灰;画布快捷添加菜单与属性面板“节点类型”下拉直接过滤超限类型,拖放和点击创建(含模板拖放)静默返回 `null`,不把异常抛进 DOM 事件回调;模型变化后 Palette 自动恢复可用,`shell.canvas.revealElement()` 等其他能力不受影响。自建 UI 可复用 `interactions.createBlockedReason(intent)` 得到同一条原因文案。完整契约见 [API](../api/index.md#节点数量限制)。
2409
+
2394
2410
  ## 嵌入宿主工作台
2395
2411
 
2396
2412
  默认 `BpmnStudioShell` 仍是包含 Header、Palette、Canvas、Properties 和 Statusbar 的完整工作台。宿主要复用自己的业务属性面板时,应显式隐藏 Nova 右侧区域,并把业务面板作为 Nova 根节点的外部兄弟区域:
@@ -2739,7 +2755,7 @@ BPMN Nova 的 Vue 3.3+ Adapter,提供 Studio、Designer、Viewer、审批轨
2739
2755
 
2740
2756
  > **English summary:** Vue 3.3+ components and exposed instance methods for BPMN Nova process design, viewing, approval traces, properties, themes, and SVG export.
2741
2757
 
2742
- > 当前版本为 `0.3.7-preview`。Vue 由宿主工程提供,本包不会替应用选择或升级框架版本。
2758
+ > 当前版本为 `0.3.8-preview`。Vue 由宿主工程提供,本包不会替应用选择或升级框架版本。
2743
2759
 
2744
2760
  ![BPMN Nova Vue 流程工作台](../../assets/bpmn-nova-designer.jpg)
2745
2761
 
@@ -2769,6 +2785,8 @@ import type {
2769
2785
 
2770
2786
  公共类型门面还包含 `BpmnEdge`、`EngineId` 和 `LayoutOptions`。
2771
2787
 
2788
+ 自 0.3.8-preview 起,门面补齐了组件签名中用到的全部公开类型,包括 `BpmnStudioController`、`BpmnStudioShell`、`CanvasInstance`、`DesignerInstance`、`ViewerInstance`、`StudioState`、`StudioCommands`、`PaletteRegistry`、`PropertiesRegistry`、`ContextMenuRegistry`、`TemplateRegistry`、`IconRegistry`、`NovaThemeInput`、`NovaThemeState`、`SvgExportOptions` 等,以及本轮新增的 `StudioNodeLimits`、`CanvasRevealElementOptions` 与 `BpmnStudioEmits` / `BpmnDesignerEmits` / `BpmnViewerEmits`。它们都能从 `@bpmn-nova/vue` 直接 `import type`,pnpm 严格模式下也不需要为类型增加 Studio 直依赖。
2789
+
2772
2790
  使用代码生成助手或 IDE Agent 接入时,从随包的 `llms.txt` 开始;需要完整接口和定制资料时再读取 `llms-full.txt`。两份文件都包含在 npm tarball 中,不依赖源码仓库可见性。
2773
2791
 
2774
2792
  ## 流程设计
@@ -2804,10 +2822,91 @@ function handleChange(model, reason, nextXml) {
2804
2822
  </template>
2805
2823
  ```
2806
2824
 
2807
- Expose 提供 `getActions()`、`validate()`、`exportXml()`、`fitView()`、`setTheme()`、`exportSvg()` 和 `openSvgExportPreview()`。
2825
+ Expose 提供 `getActions()`、`validate()`、`exportXml()`、`fitView()`、`revealElement()`、`setTheme()`、`exportSvg()` 和 `openSvgExportPreview()`。
2808
2826
 
2809
2827
  `xml`/`model` 是外部替换输入,`change` 的 XML 是草稿输出。宿主回写完全相同的导出 XML 不会重新导入或清空撤销历史;切换服务器 revision 或流程时传入不同 XML 会替换模型。Activiti 宿主应显式使用 `engine="activiti"`。
2810
2828
 
2829
+ ## 事件参数是不可变快照
2830
+
2831
+ 自 `0.3.8-preview` 起,`change`、`selection-change`、`scope-change` 传出的模型、选择、元素和 `state` 都是控制器事件里已经克隆好的快照,不再是组件内部的可变对象。宿主可以直接把 `model` 赋给 `ref` / `reactive` 状态,每次变化都是新引用;改写这些参数不会影响画布、`exportXml()` 结果或撤销历史。
2832
+
2833
+ ```vue
2834
+ <script setup>
2835
+ import { ref } from 'vue'
2836
+
2837
+ const model = ref(null)
2838
+ const selected = ref(null)
2839
+
2840
+ function handleChange(nextModel, reason, nextXml) {
2841
+ model.value = nextModel
2842
+ }
2843
+ function handleSelectionChange(selection, element) {
2844
+ selected.value = selection ? element : null
2845
+ }
2846
+ </script>
2847
+
2848
+ <template>
2849
+ <BpmnStudio :xml="xml" @change="handleChange" @selection-change="handleSelectionChange" />
2850
+ </template>
2851
+ ```
2852
+
2853
+ `BpmnDesigner` 的 `change` / `selection-change` 同样是快照。`change` 的第三个参数保持原语义,仍是当前草稿的导出 XML。
2854
+
2855
+ ## XML 导入失败的受控出口
2856
+
2857
+ 自 `0.3.8-preview` 起,`xml` 无法解析,或 `config.modeling.allowedNodeTypes` / `nodeLimits` 拒绝该模型时,组件不再向上抛出异常(那会中断挂载),而是发出 `import-error` 事件:
2858
+
2859
+ ```vue
2860
+ <template>
2861
+ <BpmnStudio
2862
+ :xml="serverXml"
2863
+ :config="{ modeling: { allowedNodeTypes: ['startEvent', 'userTask', 'endEvent'] } }"
2864
+ @import-error="handleImportError"
2865
+ />
2866
+ </template>
2867
+
2868
+ <script setup>
2869
+ function handleImportError(error, xml) {
2870
+ console.error('[bpmn-nova] import failed', error, xml) // 原始消息进日志
2871
+ notifyUser('流程图无法打开,请检查该版本是否已损坏') // 用户看宿主自己的文案
2872
+ }
2873
+ </script>
2874
+ ```
2875
+
2876
+ - 首次导入失败:挂载空流程并发出一次事件,页面不白屏。
2877
+ - 更新导入失败(例如切到一个损坏的 revision):保留当前模型与撤销历史,发出一次事件。
2878
+ - `BpmnStudio`、`BpmnDesigner`、`BpmnViewer` 都声明了 `import-error`;`useBpmnStudio({ xml, onImportError })` 使用同名选项。
2879
+ - 同一份 `xml` 只上报一次;换成另一份 `xml`(例如切换 revision)会重新上报。与 React 适配包的去重语义一致。
2880
+ - 未监听该事件时仍不抛出,改为 `console.error` 输出一次,避免静默失败。
2881
+ - 宿主自己创建并通过 `studio` Prop 传入控制器时不涉及 `xml` 导入,行为不变。
2882
+
2883
+ `error.message` 面向开发者:解析失败时会拼接浏览器 `DOMParser` 的英文原文,不同浏览器措辞不同,**不要直接展示给终端用户**。需要区分失败类型时按消息前缀判断:`BPMN XML 解析失败:`、`未找到 <process> 元素。`、`BPMN node type is not allowed:`、`BPMN edge type is not allowed:`、`BPMN node limit exceeded:`。
2884
+
2885
+ ## 节点数量限制
2886
+
2887
+ 自 `0.3.8-preview` 起,`config.modeling.nodeLimits` 在类型白名单之外再限制数量,例如审批流只允许一个开始事件:
2888
+
2889
+ ```vue
2890
+ <BpmnStudio
2891
+ :xml="xml"
2892
+ :config="{ modeling: { nodeLimits: { startEvent: { max: 1 }, endEvent: { max: 1 } } } }"
2893
+ />
2894
+ ```
2895
+
2896
+ 超限时调色板对应项(含宿主自定义 Palette 项)自动禁用并显示原因,画布快捷添加菜单与属性面板“节点类型”下拉会过滤该类型,点击和拖放都不创建节点;含超限类型的**模板项**同样置灰,拖入时静默返回 `null` 而不抛异常。删除该节点后界面自动恢复可用,无需重新挂载。程序化调用沿用既有约定:`createNode()` 与 `createTemplate()` 抛出含 `limit` 的错误,`quickAdd()` 返回 `null`,`changeNodeType()` 返回 `false`,导入超限 XML 抛错且不改变当前模型;这些失败都不发出 `change`、不写入撤销栈。宿主可用 `studio.canAddNode()`、`studio.canChangeNodeType()` 和 `studio.nodeLimitReason()` 复现同一判断。该配置与 `allowedNodeTypes` 一样只在内部 Controller 创建时生效。
2897
+
2898
+ ## 按元素定位
2899
+
2900
+ 自 `0.3.8-preview` 起,Expose 的 `revealElement(id, options?)` 把视口移动到指定节点或连线,节点与连线都支持,自动布线的连线也可以定位:
2901
+
2902
+ ```js
2903
+ studioRef.value?.revealElement('UserTask_Manager') // 平移居中并保持缩放,同时选中
2904
+ studioRef.value?.revealElement('Flow_Approve', { kind: 'edge', zoom: 'fit' }) // 按 fitSelection 的缩放定位
2905
+ studioRef.value?.revealElement('Task_InSubProcess', { zoom: 1 }) // 元素在子流程时先切换作用域
2906
+ ```
2907
+
2908
+ `zoom` 默认 `'keep'`(只平移),`'fit'` 与 `fitSelection()` 结果一致,数字表示目标缩放并夹在渲染器 0.25~2.25 之间;`select` 默认 `true`。元素不存在或设计画布未挂载(例如 Instance 模式)时返回 `false`,视口与选择都不变。自建布局时,`BpmnCanvas` 的 Expose 另提供 `revealElement()` 与 `setViewportState()`。
2909
+
2811
2910
  ## 组合宿主头部与业务属性面板
2812
2911
 
2813
2912
  默认 `BpmnStudio` 是包含 Header、Palette、Canvas、Properties 和 Statusbar 的完整工作台。下面的接入显式隐藏 Nova Properties,保留 Nova Palette,并只替换 Header 左侧品牌区:
@@ -3113,7 +3212,7 @@ BPMN Nova 的 React 18+ Adapter,提供 Studio、Designer、Viewer、审批轨
3113
3212
 
3114
3213
  > **English summary:** React 18+ components and refs for BPMN Nova process design, viewing, approval traces, properties, themes, and SVG export.
3115
3214
 
3116
- > 当前版本为 `0.3.7-preview`。React 与 React DOM 由宿主工程提供,本包不会替应用选择或升级框架版本。
3215
+ > 当前版本为 `0.3.8-preview`。React 与 React DOM 由宿主工程提供,本包不会替应用选择或升级框架版本。
3117
3216
 
3118
3217
  ![BPMN Nova React 流程工作台](../../assets/bpmn-nova-designer.jpg)
3119
3218
 
@@ -3143,6 +3242,8 @@ import type {
3143
3242
 
3144
3243
  公共类型门面还包含 `BpmnEdge`、`EngineId` 和 `LayoutOptions`。
3145
3244
 
3245
+ 自 0.3.8-preview 起,门面补齐了组件签名中用到的全部公开类型,包括 `BpmnStudioController`、`BpmnStudioShell`、`CanvasInstance`、`DesignerInstance`、`ViewerInstance`、`StudioState`、`StudioCommands`、`PaletteRegistry`、`PropertiesRegistry`、`ContextMenuRegistry`、`TemplateRegistry`、`IconRegistry`、`NovaThemeInput`、`NovaThemeState`、`SvgExportOptions` 等,以及本轮新增的 `StudioNodeLimits` 与 `CanvasRevealElementOptions`。它们都能从 `@bpmn-nova/react` 直接 `import type`,pnpm 严格模式下也不需要为类型增加 Studio 直依赖。
3246
+
3146
3247
  使用代码生成助手或 IDE Agent 接入时,从随包的 `llms.txt` 开始;需要完整接口和定制资料时再读取 `llms-full.txt`。两份文件都包含在 npm tarball 中,不依赖源码仓库可见性。
3147
3248
 
3148
3249
  ## 流程设计
@@ -3176,10 +3277,75 @@ export function WorkflowEditor({ initialXml }) {
3176
3277
  }
3177
3278
  ```
3178
3279
 
3179
- Ref 提供 `actions`、`validate()`、`exportXml()`、`fitView()`、`setTheme()`、`exportSvg()` 和 `openSvgExportPreview()`。
3280
+ Ref 提供 `actions`、`validate()`、`exportXml()`、`fitView()`、`revealElement()`、`setTheme()`、`exportSvg()` 和 `openSvgExportPreview()`。
3180
3281
 
3181
3282
  `xml`/`model` 是外部替换输入,`onChange` 的 XML 是草稿输出。宿主回写完全相同的导出 XML 不会重新导入或清空撤销历史;切换服务器 revision 或流程时传入不同 XML 会替换模型。Activiti 宿主应显式使用 `engine="activiti"`。
3182
3283
 
3284
+ ## 回调参数是不可变快照
3285
+
3286
+ 自 `0.3.8-preview` 起,`onChange`、`onSelectionChange`、`onScopeChange` 传出的模型、选择、元素和 `state` 都是控制器事件里已经克隆好的快照,不再是组件内部的可变对象。宿主可以直接把 `model` 放进 React 状态,每次变化都会拿到新引用并正常触发重新渲染(开启 React Compiler 时也不会读到旧值);改写这些参数不会影响画布、`exportXml()` 结果或撤销历史。
3287
+
3288
+ ```jsx
3289
+ const [model, setModel] = useState(null)
3290
+
3291
+ <BpmnStudio
3292
+ xml={xml}
3293
+ onChange={(nextModel, reason, nextXml) => setModel(nextModel)}
3294
+ onSelectionChange={(selection, element) => setSelected(element)}
3295
+ />
3296
+ ```
3297
+
3298
+ `BpmnDesigner` 的 `onChange` / `onSelectionChange` 同样是快照。`xml` 参数保持原语义,仍是当前草稿的导出结果。
3299
+
3300
+ ## XML 导入失败的受控出口
3301
+
3302
+ 自 `0.3.8-preview` 起,`xml` 无法解析,或 `config.modeling.allowedNodeTypes` / `nodeLimits` 拒绝该模型时,组件不再把异常抛给 React(那会卸载整棵组件树),而是走 `onImportError`:
3303
+
3304
+ ```jsx
3305
+ <BpmnStudio
3306
+ xml={serverXml}
3307
+ config={{ modeling: { allowedNodeTypes: ['startEvent', 'userTask', 'endEvent'] } }}
3308
+ onImportError={(error, xml) => {
3309
+ console.error('[bpmn-nova] import failed', error, xml) // 原始消息进日志
3310
+ notifyUser('流程图无法打开,请检查该版本是否已损坏') // 用户看宿主自己的文案
3311
+ }}
3312
+ />
3313
+ ```
3314
+
3315
+ - 首次导入失败:挂载空流程并调用一次回调,页面不白屏。
3316
+ - 更新导入失败(例如切到一个损坏的 revision):保留当前模型与撤销历史,调用一次回调。
3317
+ - `BpmnStudio`、`BpmnDesigner`、`BpmnViewer` 与 `useBpmnStudio({ xml, onImportError })` 都支持。
3318
+ - 同一份 `xml` 只上报一次。React 18 `StrictMode` 在开发模式下会把每个 effect 挂载两次,Nova 按 `xml` 值去重,宿主不会收到重复错误;换成另一份 `xml` 会重新上报。
3319
+ - 未传回调时仍不抛出,改为 `console.error` 输出一次,避免静默失败。
3320
+ - 宿主自己创建并传入 `studio` 控制器时不涉及 `xml` 导入,行为不变。
3321
+
3322
+ `error.message` 面向开发者:解析失败时会拼接浏览器 `DOMParser` 的英文原文,不同浏览器措辞不同,**不要直接展示给终端用户**。需要区分失败类型时按消息前缀判断:`BPMN XML 解析失败:`、`未找到 <process> 元素。`、`BPMN node type is not allowed:`、`BPMN edge type is not allowed:`、`BPMN node limit exceeded:`。
3323
+
3324
+ ## 节点数量限制
3325
+
3326
+ 自 `0.3.8-preview` 起,`config.modeling.nodeLimits` 在类型白名单之外再限制数量,例如审批流只允许一个开始事件:
3327
+
3328
+ ```jsx
3329
+ <BpmnStudio
3330
+ xml={xml}
3331
+ config={{ modeling: { nodeLimits: { startEvent: { max: 1 }, endEvent: { max: 1 } } } }}
3332
+ />
3333
+ ```
3334
+
3335
+ 超限时调色板对应项(含宿主自定义 Palette 项)自动禁用并显示原因,画布快捷添加菜单与属性面板“节点类型”下拉会过滤该类型,点击和拖放都不创建节点;含超限类型的**模板项**同样置灰,拖入时静默返回 `null` 而不抛异常。删除该节点后界面自动恢复可用,无需重新挂载。程序化调用沿用既有约定:`createNode()` 与 `createTemplate()` 抛出含 `limit` 的错误,`quickAdd()` 返回 `null`,`changeNodeType()` 返回 `false`,导入超限 XML 抛错且不改变当前模型;这些失败都不触发 `onChange`、不写入撤销栈。宿主可用 `studio.canAddNode()`、`studio.canChangeNodeType()` 和 `studio.nodeLimitReason()` 复现同一判断。该配置与 `allowedNodeTypes` 一样只在内部 Controller 创建时生效。
3336
+
3337
+ ## 按元素定位
3338
+
3339
+ 自 `0.3.8-preview` 起,Ref 的 `revealElement(id, options?)` 把视口移动到指定节点或连线,节点与连线都支持,自动布线的连线也可以定位:
3340
+
3341
+ ```jsx
3342
+ studioRef.current?.revealElement('UserTask_Manager') // 平移居中并保持缩放,同时选中
3343
+ studioRef.current?.revealElement('Flow_Approve', { kind: 'edge', zoom: 'fit' }) // 按 fitSelection 的缩放定位
3344
+ studioRef.current?.revealElement('Task_InSubProcess', { zoom: 1 }) // 元素在子流程时先切换作用域
3345
+ ```
3346
+
3347
+ `zoom` 默认 `'keep'`(只平移),`'fit'` 与 `fitSelection()` 结果一致,数字表示目标缩放并夹在渲染器 0.25~2.25 之间;`select` 默认 `true`。元素不存在或设计画布未挂载(例如 Instance 模式)时返回 `false`,视口与选择都不变。自建布局时,`BpmnCanvas` 的句柄另提供 `revealElement()` 与 `setViewportState()`。
3348
+
3183
3349
  ## 组合宿主头部与业务属性面板
3184
3350
 
3185
3351
  默认 `BpmnStudio` 是完整工作台。下面展示宿主拥有外部面板的接法:通过 `config.ui.regions.right = 'hidden'` 隐藏 Nova Properties,Canvas 获得该轨道的全部宽度。若希望复用 Nova 侧栏布局,使用下文的 `right` Render Prop,不必放到外部。
@@ -3454,7 +3620,7 @@ Apache-2.0. See [LICENSE](https://github.com/daxiangme/bpmn-nova/blob/dev/packag
3454
3620
 
3455
3621
  # BPMN Nova 组件参数
3456
3622
 
3457
- 本手册记录 `0.3.7-preview` 的公开组件参数、回调和实例方法。所有视觉组件都需要具有实际尺寸的容器,并显式导入所属包的 `styles.css`。
3623
+ 本手册记录 `0.3.8-preview` 的公开组件参数、回调和实例方法。所有视觉组件都需要具有实际尺寸的容器,并显式导入所属包的 `styles.css`。
3458
3624
 
3459
3625
  ## 在线体验
3460
3626
 
@@ -3504,14 +3670,37 @@ Controller 不创建 DOM,负责模型、命令、历史、选择与子流程
3504
3670
  | 方法 | 返回值 | 说明 |
3505
3671
  | --- | --- | --- |
3506
3672
  | `subscribe(listener)` | `() => void` | 订阅模型、选择、历史和作用域事件 |
3507
- | `getState()` | `StudioState` | 获取不可直接编辑的状态快照 |
3673
+ | `getState()` | `StudioState` | 获取不可直接编辑的状态快照;含 `allowedNodeTypes`、`allowedEdgeTypes` 和 `nodeLimits` 副本 |
3674
+ | `allowsNodeType(type)` / `allowsEdgeType(type)` | `boolean` | 类型白名单查询,供宿主 UI 与扩展复用 |
3675
+ | `canAddNode(type, count?)` | `boolean` | 类型允许且新增 `count`(默认 1)个后不超 `nodeLimits`;按整个模型统计(含全部子流程作用域) |
3676
+ | `canChangeNodeType(id, type)` | `boolean` | 类型允许且转换后不超限;节点原本就是该类型时不重复计数 |
3677
+ | `nodeLimitReason(type)` | `string \| null` | 超限时返回可读原因(例如 `最多 1 个开始事件`),未超限返回 `null` |
3508
3678
  | `setModel(model, options?)` | `void` | 替换模型,可用 `resetHistory: false` 保留历史 |
3509
3679
  | `exportXml(engine?)` | `string` | 导出 BPMN XML |
3510
- | `importXml(xml, engine?)` | `ProcessModel` | 导入并替换当前模型 |
3680
+ | `importXml(xml, engine?)` | `ProcessModel` | 导入并替换当前模型;类型白名单或 `nodeLimits` 不满足时抛错,且不改变当前模型与历史 |
3511
3681
  | `validate()` | `StudioValidationIssue[]` | 返回结构化错误和警告,不触发宿主 UI |
3512
3682
  | `undo()` / `redo()` | `boolean` | 执行历史操作 |
3513
3683
  | `destroy()` | `void` | 清理扩展和订阅 |
3514
3684
 
3685
+ `config.modeling.nodeLimits` 声明每种节点类型的数量上限(自 0.3.8-preview 起):
3686
+
3687
+ ```js
3688
+ const studio = createStudioController({
3689
+ model,
3690
+ config: { modeling: { nodeLimits: { startEvent: { max: 1 }, endEvent: { max: 1 } } } },
3691
+ })
3692
+
3693
+ studio.canAddNode('startEvent') // 已有开始事件时为 false
3694
+ studio.nodeLimitReason('startEvent') // '最多 1 个开始事件'
3695
+ studio.createNode({ nodeType: 'startEvent' }) // 抛出 BPMN node limit reached: startEvent (max 1)
3696
+ studio.commands.quickAdd('Task_1', 'startEvent') // 返回 null
3697
+ studio.changeNodeType('EndEvent_1', 'startEvent') // 返回 false
3698
+ ```
3699
+
3700
+ `max` 必须是不小于 0 的整数,键必须是已知 `NodeType`,否则抛 `TypeError`。与 `allowedNodeTypes` 一样只在构造 Controller 时生效,`setConfig()` 不会改变它。失败路径沿用各自既有约定:`createNode()` / `createTemplate()` / 导入抛 `Error`,`quickAdd()` 返回 `null`,`changeNodeType()` 返回 `false`;失败时不提交、不触发 `modelChanged`、不写入撤销栈。模板按其内部各类型数量合计判断。
3701
+
3702
+ 默认调色板、内置“节点类型”下拉与画布快捷添加菜单都改用上述判断:调色板项(含宿主通过 `PaletteRegistry.registerProvider` 注册的自定义项)在超限时按钮 `disabled`、不可拖拽,`title` 与 `aria-disabled` 显示原因,并在 `modelChanged` 后自动恢复可用,无需重新挂载组件;下拉与快捷菜单直接过滤掉超限类型。拖放与点击创建在超限时静默返回 `null`,不向界面事件回调抛异常。
3703
+
3515
3704
  主要命令位于 `studio.commands`:创建节点/模板、连接、修改、删除、布局、分组、Lane containment、作用域导航和历史操作。
3516
3705
 
3517
3706
  ## `createStudioShell(options)`
@@ -3556,7 +3745,7 @@ Controller 不创建 DOM,负责模型、命令、历史、选择与子流程
3556
3745
 
3557
3746
  首次进入 ≤720px 的 Shell 容器时,可折叠面板默认收起且保留按钮,宽窄屏分别记忆状态。折叠动画为 200ms,支持减少动态效果,不卸载 Slot、不执行 Fit。Design 默认左右可见,Viewer 仅右侧可见,Instance 默认两侧隐藏;显式 `regions.right: 'default'` 可在 Instance 开启,`'hidden'` 隐藏整个区域和按钮,不能用右侧 Slot 覆盖。
3558
3747
 
3559
- `BpmnStudioConfig` 分为四组:`modeling`(Profile 和节点/连线白名单)、`ui`(`controlSize`、Regions、侧栏宽度、折叠与内容布局)、`viewer`(响应式投影、投影选项、Timeline/Details/Trace)和 `export`。`setConfig()` 先完整校验,再原地更新 UI、Viewer 与 Export,不重建 Canvas。`controlSize` 默认 `medium`,接受 `small | medium | large | '24px'…'48px'`;`null`、裸数字、其他单位及范围外值会抛出包含 `config.ui.controlSize` 的错误。
3748
+ `BpmnStudioConfig` 分为四组:`modeling`(Profile、节点/连线白名单与 `nodeLimits` 数量上限)、`ui`(`controlSize`、Regions、侧栏宽度、折叠与内容布局)、`viewer`(响应式投影、投影选项、Timeline/Details/Trace)和 `export`。`setConfig()` 先完整校验,再原地更新 UI、Viewer 与 Export,不重建 Canvas。`controlSize` 默认 `medium`,接受 `small | medium | large | '24px'…'48px'`;`null`、裸数字、其他单位及范围外值会抛出包含 `config.ui.controlSize` 的错误。
3560
3749
 
3561
3750
  `shell.actions` 是默认 Header 与宿主自定义 Header 共用的稳定 Interface,提供 `undo()`、`redo()`、`beautify()`、`rerouteEdges()`、`fitView()`、`validate()`、`importXml()`、`exportXml()`、`exportSvg()` 和 `openSvgExportPreview()`。它不包含保存、发布、权限或文件上传等宿主业务动作。
3562
3751
 
@@ -3629,7 +3818,25 @@ new BpmnDesigner(options)
3629
3818
  | `pointerMode` | `'select' \| 'marquee' \| 'pan'` | `'select'` | 指针模式 |
3630
3819
  | `theme` | `NovaThemeInput` | `light` | 实例主题 |
3631
3820
 
3632
- 常用方法:`clientToWorld()`、`fitView()`、`fitSelection()`、`setPointerMode()`、`zoomBy()`、`actualSize()`、`refreshPresentation()` 和 `destroy()`。
3821
+ 常用方法:`clientToWorld()`、`fitView()`、`fitSelection()`、`revealElement()`、`setViewportState()`、`getViewportState()`、`setPointerMode()`、`zoomBy()`、`actualSize()`、`refreshPresentation()` 和 `destroy()`。
3822
+
3823
+ `revealElement(id, options?)`(自 0.3.8-preview 起)按元素定位,节点与连线都支持:
3824
+
3825
+ ```js
3826
+ canvas.revealElement('UserTask_Manager') // 平移居中,保持当前缩放,并选中该节点
3827
+ canvas.revealElement('Flow_Approve', { kind: 'edge', zoom: 'fit' }) // 连线(含自动布线)按 fitSelection 的缩放定位
3828
+ canvas.revealElement('Task_InSubProcess', { zoom: 1, select: false }) // 指定缩放,不改变选择
3829
+ canvas.setViewportState({ zoom: 0.8, pan: { x: 0, y: 0 } }) // 直接应用视口
3830
+ ```
3831
+
3832
+ | 选项 | 类型 | 默认 | 说明 |
3833
+ | --- | --- | --- | --- |
3834
+ | `kind` | `'node' \| 'edge'` | 先按节点、再按连线查找 | 编号在两类元素中重复时用于消歧 |
3835
+ | `select` | `boolean` | `true` | 定位后选中该元素,触发一次 `selectionChanged` |
3836
+ | `zoom` | `'keep' \| 'fit' \| number` | `'keep'` | `keep` 只平移;`fit` 沿用 `fitSelection()` 的缩放计算;数字为目标缩放,夹在渲染器 0.25~2.25 之间 |
3837
+ | `padding` | `number` | `72` | `fit` 的留白,同时用于零宽/零高连线的包围盒扩展 |
3838
+
3839
+ 元素位于子流程而当前不在该作用域时,先切换到元素所在作用域再定位;编号不存在时返回 `false`,视口与选择都不变。`getSelectionBounds()` 与 `fitSelection()` 的行为不变,选中工具栏与右键菜单的定位不受影响。
3633
3840
 
3634
3841
  ## `PalettePanel`
3635
3842
 
@@ -3644,6 +3851,8 @@ new BpmnDesigner(options)
3644
3851
  | `renderItem` / `renderSection` | 否 | 局部 DOM Renderer |
3645
3852
  | `theme` / `onThemeChange` | 否 | 实例主题 |
3646
3853
 
3854
+ 配置了 `config.modeling.nodeLimits` 时(自 0.3.8-preview 起),默认渲染的 Palette 项会在超限时自动 `disabled`、不可拖拽,并用 `title` / `aria-disabled` 显示 `nodeLimitReason()` 的原因;面板订阅控制器事件,在 `modelChanged` 后原位刷新可用状态,保留分组展开状态与焦点,`destroy()` 时取消订阅。宿主通过 `registerProvider` 注册的自定义项同样受这套判断约束,不需要自己实现 `visible`:`create.kind === 'node'` 的项按该类型判断,`create.kind === 'template'` 的项按模板内各类型数量合计判断(与 `createTemplate()` 一致),任一类超限即置灰。使用 `renderItem` 完全接管 DOM 时,可自行调用 `studio.canAddNode()`、`studio.nodeLimitReason()` 或 `interactions.createBlockedReason(item.create)` 呈现同等状态。
3855
+
3647
3856
  ## `PropertiesPanel`
3648
3857
 
3649
3858
  | 参数 | 必填/默认 | 说明 |
@@ -3682,11 +3891,42 @@ new BpmnDesigner(options)
3682
3891
  | `headerStart` / `headerActions` / `header` / `right` | React Node 或 Render Prop;使用 Portal 保留宿主 Context;`right` 仅替换侧栏内容 |
3683
3892
  | `onValidation` | Nova 内部校验展示完成后的只读结果事件 |
3684
3893
  | `onSidebarChange` | 只读侧栏折叠事件,来源 `button \| api \| responsive \| config` |
3685
- | `onChange(model, reason, xml)` | 模型变化 |
3686
- | `onSelectionChange(selection, element)` | 选择变化 |
3687
- | `onScopeChange(activeScopeId, scopePath, state)` | 子流程作用域变化 |
3894
+ | `onImportError(error, xml)` | 自 0.3.8-preview 起;`xml` 导入失败的受控出口,见下文 |
3895
+ | `onChange(model, reason, xml)` | 模型变化;`model` 是不可变快照 |
3896
+ | `onSelectionChange(selection, element)` | 选择变化;两个参数都是不可变快照 |
3897
+ | `onScopeChange(activeScopeId, scopePath, state)` | 子流程作用域变化;`state` 是该事件的不可变状态快照 |
3898
+
3899
+ 回调参数是快照(自 0.3.8-preview 起的行为修正):`onChange`、`onSelectionChange`、`onScopeChange` 传出的是控制器事件里已经克隆好的副本,不再是内部可变对象。因此宿主可以直接 `setState(model)`,每次变化都拿到新引用并正常触发重新渲染;修改这些参数不会影响组件内部模型、`exportXml()` 结果或撤销历史。`xml` 参数仍是 `studio.exportXml()` 的草稿输出。
3900
+
3901
+ `onImportError(error, xml)`(自 0.3.8-preview 起)是 `xml` 导入失败的受控出口,`BpmnStudio`、`BpmnDesigner`、`BpmnViewer` 与 `useBpmnStudio()` 都支持:
3902
+
3903
+ - 首次导入失败(XML 无法解析,或 `config.modeling.allowedNodeTypes` / `nodeLimits` 拒绝该模型):组件挂载为空流程,调用一次回调,不向 React 抛异常、不卸载组件树。
3904
+ - 更新导入失败:保留当前模型与撤销历史,调用一次回调。
3905
+ - 同一份 `xml` 只上报一次:React 18 `StrictMode` 在开发模式下会把每个 effect 挂载两次,Nova 按 `xml` 值去重,宿主不会收到重复错误;换成另一份 `xml`(例如切换 revision)会重新上报。
3906
+ - 未提供回调时仍不抛出,改为 `console.error` 输出一次,避免静默失败。
3907
+ - 宿主传入自己的 `studio` 控制器时不涉及 `xml` 导入,行为不变。
3908
+
3909
+ `error.message` 面向开发者:解析失败时它会拼接浏览器 `DOMParser` 的英文原文(例如 `BPMN XML 解析失败: This page contains the following errors:…`),不同浏览器措辞不同。因此**不要直接把 `error.message` 展示给终端用户**,宿主应给出自己的文案,把原始消息写进日志;需要区分失败类型时按消息前缀判断:
3688
3910
 
3689
- Ref:`studio`、`shell`、`actions`、`mode`、`getConfig()`、`setConfig()`、`getMode()`、`setMode()`、`setAllowedModes()`、`validate()`、`refreshPresentation()`、`exportXml()`、`fitView()`、`setTheme()`。Header Render Context 额外提供只读 `ui`。
3911
+ | 前缀 | 含义 |
3912
+ | --- | --- |
3913
+ | `BPMN XML 解析失败:` | XML 不是合法文档 |
3914
+ | `未找到 <process> 元素。` | 文档合法但没有流程定义 |
3915
+ | `BPMN node type is not allowed:` | 被 `config.modeling.allowedNodeTypes` 拒绝 |
3916
+ | `BPMN edge type is not allowed:` | 被 `config.modeling.allowedEdgeTypes` 拒绝 |
3917
+ | `BPMN node limit exceeded:` | 被 `config.modeling.nodeLimits` 拒绝 |
3918
+
3919
+ ```jsx
3920
+ <BpmnStudio
3921
+ xml={serverXml}
3922
+ onImportError={(error, xml) => {
3923
+ console.error('[bpmn-nova] import failed', error, xml) // 原始消息进日志
3924
+ notifyUser('流程图无法打开,请检查该版本是否已损坏') // 用户看宿主自己的文案
3925
+ }}
3926
+ />
3927
+ ```
3928
+
3929
+ Ref:`studio`、`shell`、`actions`、`mode`、`getConfig()`、`setConfig()`、`getMode()`、`setMode()`、`setAllowedModes()`、`validate()`、`refreshPresentation()`、`exportXml()`、`fitView()`、`revealElement()`、`setTheme()`。Header Render Context 额外提供只读 `ui`。`revealElement(id, options?)`(自 0.3.8-preview 起)委托当前 Shell 画布按元素定位,选项与返回值同 `BpmnCanvas.revealElement()`;设计画布未挂载(例如 Instance 模式)或编号不存在时返回 `false`。
3690
3930
 
3691
3931
  Studio Ref 同时提供五个侧栏/面板选择方法:`getSidebarState()`、`setSidebarCollapsed()`、`subscribeSidebarChange()`、`getPanelSelection()`、`subscribePanelSelection()`。Header/Right Render Context 共享响应式 `state`、`mode`、`ui`、`panelSelection`,以及 `studio`、`shell`、`actions`;只读选择使用 `panelSelection`,不将 `state.selection` 误当作轨迹当前选择。
3692
3932
 
@@ -3694,11 +3934,13 @@ Studio Ref 同时提供五个侧栏/面板选择方法:`getSidebarState()`、`
3694
3934
 
3695
3935
  ### `BpmnDesigner`
3696
3936
 
3697
- Props:`model`、`xml`、`engine`、`theme`、`onChange`、`onSelectionChange`。Ref:`instance`、`model`、`exportXml()`、`fitView()`、`beautify()`、`rerouteEdges()`、`validate()`、`setTheme()`。
3937
+ Props:`model`、`xml`、`engine`、`theme`、`onChange`、`onSelectionChange`、`onImportError`。Ref:`instance`、`model`、`exportXml()`、`fitView()`、`beautify()`、`rerouteEdges()`、`validate()`、`setTheme()`。
3938
+
3939
+ `onChange` 与 `onSelectionChange` 传出的模型、选择和元素都是不可变快照(自 0.3.8-preview 起);`onImportError(error, xml)` 与 `BpmnStudio` 语义一致。
3698
3940
 
3699
3941
  ### `BpmnViewer`
3700
3942
 
3701
- 接受除 `container/model` 外的 `ViewerOptions`,并通过 `model` 或 `xml` 输入流程。Ref:`instance`、`fitView()`、`refreshPresentation()`、`setProjection()`、`setRuntime()`、`setDisplayOptions()`、`setTheme()`。
3943
+ 接受除 `container/model` 外的 `ViewerOptions`,并通过 `model` 或 `xml` 输入流程。Ref:`instance`、`fitView()`、`refreshPresentation()`、`setProjection()`、`setRuntime()`、`setDisplayOptions()`、`setTheme()`。`onImportError(error, xml)`(自 0.3.8-preview 起)在 `xml` 导入失败时接管错误:首次失败挂载空流程,更新失败保留当前模型。
3702
3944
 
3703
3945
  ### `BpmnCanvas` / `BpmnPalettePanel` / `BpmnPropertiesPanel`
3704
3946
 
@@ -3710,9 +3952,11 @@ Vue 组件与 React 使用同一底层接口,主要差异为:
3710
3952
 
3711
3953
  - Studio 提供原生 `#header-start`、`#header-actions`、`#header` 和 `#right` Slot,通过 Teleport 保留宿主 provide/inject、响应式状态和生命周期;同名原生 Slot 高于 Core DOM Slot。
3712
3954
  - `slotsConfig` 继续保留,作为高级 Core DOM Slot 入口;完整 Header 高于局部 Header Slots,原生局部 Slot 高于对应 Core Slot。
3713
- - 事件为 `change`、`selection-change`、`scope-change`、`element-click`、`trace-click`、`update:mode`、`mode-change`、`validation`、`sidebar-change`;支持 `v-model:mode`。
3714
- - `BpmnDesigner` 发出 `change`、`selection-change`。
3715
- - Header Slot Context 的 `mode` 是响应式实际状态。Ref Expose 使用 `getStudio()`、`getShell()`、`getActions()`、`getMode()`、`setMode()`、`setAllowedModes()`、`validate()`、`refreshPresentation()` 或 `getInstance()`,不直接暴露可替换字段。
3955
+ - 事件为 `change`、`selection-change`、`scope-change`、`element-click`、`trace-click`、`update:mode`、`mode-change`、`validation`、`sidebar-change`、`import-error`;支持 `v-model:mode`。
3956
+ - `change`、`selection-change`、`scope-change` 传出的模型、选择、元素和 `state` 都是不可变快照(自 0.3.8-preview 起),可直接放进响应式状态而不担心内部对象被外部改写。
3957
+ - `import-error(error, xml)`(自 0.3.8-preview 起)是 `xml` 导入失败的受控出口:首次失败挂载空流程,更新失败保留当前模型,未监听时改为 `console.error` 输出一次。`BpmnStudio`、`BpmnDesigner`、`BpmnViewer` 与 `useBpmnStudio({ onImportError })` 都覆盖。同一份 `xml` 只上报一次,换成另一份 `xml` 会重新上报。`error.message` 可能拼接浏览器解析器英文原文,只适合写日志,展示给用户的文案由宿主决定(前缀对照表见上文 React 章节)。
3958
+ - `BpmnDesigner` 发出 `change`、`selection-change`、`import-error`;`BpmnViewer` 发出 `element-click`、`trace-click`、`import-error`。
3959
+ - Header Slot Context 的 `mode` 是响应式实际状态。Ref Expose 使用 `getStudio()`、`getShell()`、`getActions()`、`getMode()`、`setMode()`、`setAllowedModes()`、`validate()`、`refreshPresentation()`、`revealElement()` 或 `getInstance()`,不直接暴露可替换字段。`revealElement(id, options?)`(自 0.3.8-preview 起)与 React Ref 同语义;`BpmnCanvas` 的 Expose 另提供 `revealElement()` 与 `setViewportState()`。
3716
3960
  - Studio Prop 与 `useBpmnStudio()` 支持 `config`;Expose 提供 `getConfig()` / `setConfig()`,Header Slot Context 提供响应式只读 `ui`。
3717
3961
  - Studio Expose 提供与 React 相同的五个侧栏/面板选择方法;Header/Right Slot Context 共享响应式 `panelSelection`。
3718
3962
 
@@ -3738,7 +3982,7 @@ Runtime Details、Timeline 和 Transition Details 组件通过对应 `createReac
3738
3982
 
3739
3983
  <!-- SOURCE: docs/src/api/index.md -->
3740
3984
 
3741
- # BPMN Nova v0.3.7 Preview API
3985
+ # BPMN Nova v0.3.8 Preview API
3742
3986
 
3743
3987
  ## Framework Adapter 类型门面
3744
3988
 
@@ -3756,6 +4000,24 @@ import type {
3756
4000
 
3757
4001
  React 使用相同名称,并将入口替换为 `@bpmn-nova/react`。这些是 TypeScript-only export,不会增加 Adapter 的浏览器运行时代码。
3758
4002
 
4003
+ 自 0.3.8-preview 起,两个 Adapter 入口补齐了签名中用到的全部公开类型,宿主在 pnpm 严格模式或 `moduleResolution: bundler` 下无需 `@bpmn-nova/studio` 直依赖即可 `import type`:
4004
+
4005
+ ```ts
4006
+ import type {
4007
+ BpmnStudioController, BpmnStudioShell, CanvasInstance, ContextMenuRegistry,
4008
+ DesignerInstance, IconRegistry, InteractionController, NovaThemeInput, NovaThemeState,
4009
+ PaletteItemRenderer, PalettePanelInstance, PaletteProvider, PaletteRegistry,
4010
+ PaletteSectionRenderer, PropertiesContext, PropertiesProvider, PropertiesRegistry,
4011
+ PropertyEntry, RuntimeAppearanceOptions, RuntimeDetailsRenderer, RuntimeTimelineRenderer,
4012
+ RuntimeTransitionDetailsRenderer, StudioCommands, StudioMode, StudioModeChangeEvent,
4013
+ StudioShellActions, StudioShellOptions, StudioShellRegions, StudioShellSlots, StudioState,
4014
+ SvgExportArtifact, SvgExportOptions, SvgExportPreviewController, TemplateRegistry,
4015
+ ViewerInstance, ViewerOptions, ViewerProjection,
4016
+ } from '@bpmn-nova/react'
4017
+ ```
4018
+
4019
+ 同一批名称也从 `@bpmn-nova/vue` 导出。此外两个入口都导出本轮新增的 `StudioNodeLimits`、`CanvasRevealElementOptions`,Vue 侧另有 `BpmnStudioEmits`、`BpmnDesignerEmits`、`BpmnViewerEmits`。这些同样只是类型出口,不改变运行时打包结果。
4020
+
3759
4021
  ### Runtime 类型门面
3760
4022
 
3761
4023
  自 `0.3.5-preview` 起,Vue/React 根入口新增显式 `export type`:`ProcessInstanceSnapshot`、`ActivityInstance`、`ActivityStatus`、`RuntimeParticipant`、`RuntimeApprovalAction`、`RuntimeApprovalActionType`、`RuntimeApprovalContent`、`RuntimeApprovalContentBlock`、`RuntimeAssetRef`、`RuntimeTransition`、`RuntimeEdgeVisit`、`RuntimeTraceClickEvent`、`RuntimeAssetResolver`、`RuntimeAssetPurpose`。Studio 原有出口保持不变。
@@ -3786,11 +4048,16 @@ interface StudioUiConfig {
3786
4048
  rightPanel?: StudioRightPanelConfig
3787
4049
  }
3788
4050
 
4051
+ /** 自 0.3.8-preview 起:每种节点类型的数量上限,按整个模型(含全部子流程作用域)统计。 */
4052
+ type StudioNodeLimits = Partial<Record<NodeType, { max: number }>>
4053
+
3789
4054
  interface BpmnStudioConfig {
3790
4055
  modeling?: {
3791
4056
  propertiesProfile?: 'business' | 'developer'
3792
4057
  allowedNodeTypes?: readonly NodeType[]
3793
4058
  allowedEdgeTypes?: readonly EdgeType[]
4059
+ /** 自 0.3.8-preview 起。`max` 必须是不小于 0 的整数;未知节点类型抛 TypeError。 */
4060
+ nodeLimits?: StudioNodeLimits
3794
4061
  }
3795
4062
  ui?: StudioUiConfig
3796
4063
  viewer?: {
@@ -3970,6 +4237,35 @@ const off = studio.subscribe((event) => {
3970
4237
 
3971
4238
  `SubProcess`、`Event SubProcess`、`Transaction` 和 `Ad-hoc SubProcess` 支持作用域下钻;`Call Activity` 仍通过 `calledElement` 引用独立流程。连线不能跨作用域,删除子流程会级联删除其内部元素。
3972
4239
 
4240
+ ## Studio 画布按元素定位
4241
+
4242
+ 自 `0.3.8-preview` 起,`BpmnCanvas` 新增 `revealElement()` 与 `setViewportState()`,用于把视口移动到指定节点或连线,而不改变 `getSelectionBounds()` / `fitSelection()` 的既有语义(选中工具栏与右键菜单仍用它们定位):
4243
+
4244
+ ```ts
4245
+ interface CanvasRevealElementOptions {
4246
+ /** 编号在节点与连线间重复时消歧;缺省先按节点、再按连线查找。 */
4247
+ kind?: 'node' | 'edge'
4248
+ /** 定位后是否选中该元素,默认 true,触发一次 selectionChanged。 */
4249
+ select?: boolean
4250
+ /** 'keep'(默认)只平移;'fit' 沿用 fitSelection 的缩放计算;数字为目标缩放,夹在渲染器 0.25~2.25 之间。 */
4251
+ zoom?: 'keep' | 'fit' | number
4252
+ /** fit 的留白,同时用于零宽/零高连线包围盒的扩展,默认 72。 */
4253
+ padding?: number
4254
+ }
4255
+ ```
4256
+
4257
+ ```js
4258
+ canvas.revealElement('UserTask_Manager') // true,居中且被选中,缩放不变
4259
+ canvas.revealElement('Flow_Approve', { kind: 'edge', zoom: 'fit' }) // 连线用路径点包围盒
4260
+ canvas.revealElement('Task_InSubProcess') // 不在该作用域时先 navigateToScope 再定位
4261
+ canvas.revealElement('NO_SUCH_ID') // false,视口与选择都不变
4262
+ canvas.setViewportState({ zoom: 0.8, pan: { x: 0, y: 0 } }) // 直接委托渲染器
4263
+ ```
4264
+
4265
+ 连线包围盒来自公开的 `edgeWaypoints(model, edge)`,因此 `waypoints` 为空的自动布线连线同样可定位;水平或垂直直线的零宽/零高包围盒会按 `padding` 扩展。视口一律通过渲染器既有的 `setViewportState()` 修改,没有第二套平移逻辑。
4266
+
4267
+ React Ref 与 Vue Expose 都透传 `revealElement(id, options?)`(内部委托 Shell 画布,画布未挂载时返回 `false`);框架侧 `BpmnCanvas` 组件的句柄 / Expose 另提供 `revealElement()` 与 `setViewportState()`。
4268
+
3973
4269
  ## Studio 模型与模式约束
3974
4270
 
3975
4271
  生产宿主可以把支持的 BPMN 子集声明在 Controller 上:
@@ -3997,6 +4293,52 @@ const shell = createStudioShell({
3997
4293
 
3998
4294
  React/Vue Adapter 的 `BpmnStudio` 接受同名 `allowedNodeTypes`、`allowedEdgeTypes` 和 `allowedModes`。框架 `xml`/`model` 是外部替换输入;回写与当前导出完全相同的 XML 不会重新导入或清空历史,不同 XML 会替换模型并重置历史。
3999
4295
 
4296
+ ### 节点数量限制
4297
+
4298
+ 自 `0.3.8-preview` 起,`config.modeling.nodeLimits` 在白名单之外再声明每种类型的数量上限,同样只在构造 Controller 时生效:
4299
+
4300
+ ```js
4301
+ const studio = createStudioController({
4302
+ model,
4303
+ config: {
4304
+ modeling: {
4305
+ allowedNodeTypes: ['startEvent', 'userTask', 'exclusiveGateway', 'endEvent'],
4306
+ nodeLimits: { startEvent: { max: 1 } },
4307
+ },
4308
+ },
4309
+ })
4310
+
4311
+ studio.canAddNode('startEvent') // false:已有一个开始事件
4312
+ studio.canAddNode('userTask') // true:未配置上限
4313
+ studio.canChangeNodeType('EndEvent_1', 'startEvent') // false
4314
+ studio.canChangeNodeType('EndEvent_1', 'endEvent') // true:原本就是该类型,不重复计数
4315
+ studio.nodeLimitReason('startEvent') // '最多 1 个开始事件'
4316
+ studio.getState().nodeLimits // { startEvent: { max: 1 } } 的副本
4317
+ ```
4318
+
4319
+ | 方法 | 契约 |
4320
+ | --- | --- |
4321
+ | `canAddNode(nodeType, count = 1)` | `allowsNodeType()` 通过且新增 `count` 个后不超限;统计范围是整个模型,含全部子流程作用域 |
4322
+ | `canChangeNodeType(id, type)` | 类型允许,且把该节点改成 `type` 后不超限;节点原本就是该类型时不重复计数;`id` 不存在返回 `false` |
4323
+ | `nodeLimitReason(nodeType, count = 1)` | 新增 `count` 个(默认 1)会超限时返回可读原因,否则 `null`;供宿主 UI、Palette 与模板判断共用 |
4324
+
4325
+ 五条会新增节点或改变类型的路径都走同一判断,并沿用各自既有的失败方式:`createNode()` 与 `createTemplate()` 抛出含 `limit` 的 `Error`(例如 `BPMN node limit reached: startEvent (max 1)`),`quickAdd()` 返回 `null`,`changeNodeType()` 返回 `false`,构造与 `setModel()` / `importXml()` 经模型校验抛出 `BPMN node limit exceeded: startEvent (max 1, found 2)`。失败时不提交、不触发 `modelChanged`、不写入撤销栈。模板按内部各类型数量合计判断。
4326
+
4327
+ 界面入口同步生效:默认调色板项与宿主自定义 Palette 项在超限时 `disabled`、不可拖拽并显示原因,`modelChanged` 后原位恢复;内置“节点类型”下拉与画布快捷添加菜单直接过滤超限类型;拖放与点击创建在超限时静默返回 `null`,不把异常抛进 DOM 事件回调。不配置 `nodeLimits` 时全部行为与现状一致。
4328
+
4329
+ 模板同样受约束。`InteractionController` 暴露与 `drop()` 共用的判断,供 Palette 与宿主 UI 复用:
4330
+
4331
+ ```ts
4332
+ class InteractionController {
4333
+ /** 该 create intent 会超出 nodeLimits 时返回可读原因,否则 null;模板按各类型数量合计判断。 */
4334
+ createBlockedReason(intent: CreateIntent, point?: Point | null): string | null
4335
+ /** 已构造出的模板定义是否超限,超限返回原因。 */
4336
+ templateLimitReason(definition: TemplateDefinition | null | undefined): string | null
4337
+ }
4338
+ ```
4339
+
4340
+ 调色板的 `create.kind === 'template'` 项走同一判断:模板内含超限类型时按钮置灰、不可拖拽并显示原因。拖放路径在调用 `createTemplate()` 之前拦截并返回 `null`,因此不会把 `BPMN node limit reached` 抛进浏览器事件回调;程序化调用 `studio.commands.createTemplate()` 仍按原约定抛错。宿主模板的 `create()` 在没有真实落点时以 `{ x: 0, y: 0 }` 调用一次用于计数,若它在此情况下抛错则视为“不限制”,保持既有可用状态(不静默置灰)。
4341
+
4000
4342
  ### Studio Mode Interface
4001
4343
 
4002
4344
  ```ts
@@ -5519,7 +5861,7 @@ Default ●
5519
5861
 
5520
5862
  # BPMN Nova NPM 包与发布
5521
5863
 
5522
- 版本:`0.3.7-preview`。BPMN Nova 只发布三个 `@bpmn-nova` 公共包,均使用 ESM、附带 TypeScript 声明、采用 Apache-2.0 License,并通过 `preview` dist-tag 发布。
5864
+ 版本:`0.3.8-preview`。BPMN Nova 只发布三个 `@bpmn-nova` 公共包,均使用 ESM、附带 TypeScript 声明、采用 Apache-2.0 License,并通过 `preview` dist-tag 发布。
5523
5865
 
5524
5866
  ## 公共包
5525
5867
 
@@ -5541,6 +5883,8 @@ React/Vue 的声明入口显式重导出宿主常用的 Core 类型:`BpmnEdge`
5541
5883
 
5542
5884
  `0.3.7-preview` 在 Compact 移动时间线的人工任务卡展示处理人头像,SVG 导出与确认预览同步;无 `avatarUrl` 时用名字首字,与默认节点详情一致。详见更新日志与审批轨迹接入指南。
5543
5885
 
5886
+ `0.3.8-preview` 新增 `config.modeling.nodeLimits` 节点数量限制、`BpmnCanvas.revealElement()` 按元素定位、框架入口完整公开类型、`xml` 导入失败的受控出口(`onImportError` / `import-error`),并把框架回调参数改为不可变快照。详见更新日志、组件参数与 API 文档。
5887
+
5544
5888
  ## Studio 子路径
5545
5889
 
5546
5890
  Studio 根入口重新导出稳定的完整能力;以下子路径用于让导入意图更清晰:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bpmn-nova/studio",
3
- "version": "0.3.7-preview",
3
+ "version": "0.3.8-preview",
4
4
  "description": "Complete BPMN Nova Studio with Designer, Viewer, Palette, Properties and runtime visualization.",
5
5
  "keywords": [
6
6
  "bpmn",