@bpmn-nova/studio 0.3.7-preview → 0.3.9-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.9-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') {
@@ -141,6 +159,34 @@ export function normalizeStudioRegions(regions, current = DEFAULT_STUDIO_SHELL_R
141
159
  return { ...current, ...regions };
142
160
  }
143
161
 
162
+ const CANVAS_HEAD_KEYS = Object.freeze(['editingMode', 'scopePath']);
163
+ const CANVAS_HEAD_SCOPE_PATHS = Object.freeze(['always', 'nested']);
164
+
165
+ export const DEFAULT_STUDIO_CANVAS_HEAD = Object.freeze({
166
+ editingMode: true,
167
+ scopePath: 'always',
168
+ });
169
+
170
+ export function normalizeStudioCanvasHead(value) {
171
+ if (value === undefined || value === null) return DEFAULT_STUDIO_CANVAS_HEAD;
172
+ assertObject(value, 'config.ui.canvasHead');
173
+ for (const key of Object.keys(value)) {
174
+ if (!CANVAS_HEAD_KEYS.includes(key)) {
175
+ throw new TypeError(`config.ui.canvasHead contains unknown option "${key}"; expected editingMode or scopePath.`);
176
+ }
177
+ }
178
+ if (value.editingMode !== undefined && typeof value.editingMode !== 'boolean') {
179
+ throw new TypeError('config.ui.canvasHead.editingMode must be a boolean.');
180
+ }
181
+ if (value.scopePath !== undefined && !CANVAS_HEAD_SCOPE_PATHS.includes(value.scopePath)) {
182
+ throw new TypeError('config.ui.canvasHead.scopePath must be "always" or "nested".');
183
+ }
184
+ return Object.freeze({
185
+ editingMode: value.editingMode ?? DEFAULT_STUDIO_CANVAS_HEAD.editingMode,
186
+ scopePath: value.scopePath ?? DEFAULT_STUDIO_CANVAS_HEAD.scopePath,
187
+ });
188
+ }
189
+
144
190
  function normalizeProjectionOptions(value) {
145
191
  if (value === undefined || value === null) return undefined;
146
192
  if (!Array.isArray(value)) throw new TypeError('config.viewer.projectionOptions must be a readonly array.');
@@ -216,6 +262,7 @@ export function normalizeStudioConfig(config, { fallback = null, legacy = null }
216
262
  const controlSize = normalizeStudioControlSize(uiInput.controlSize);
217
263
  const allowedNodeTypes = optionalTypeList(modelingInput.allowedNodeTypes, 'config.modeling.allowedNodeTypes');
218
264
  const allowedEdgeTypes = optionalTypeList(modelingInput.allowedEdgeTypes, 'config.modeling.allowedEdgeTypes');
265
+ const nodeLimits = normalizeNodeLimits(modelingInput.nodeLimits);
219
266
  const responsive = viewerInput.responsive === undefined ? false : viewerInput.responsive;
220
267
  if (typeof responsive !== 'boolean') throw new TypeError('config.viewer.responsive must be a boolean.');
221
268
 
@@ -223,6 +270,7 @@ export function normalizeStudioConfig(config, { fallback = null, legacy = null }
223
270
  propertiesProfile: normalizePropertiesProfile(modelingInput.propertiesProfile),
224
271
  ...(allowedNodeTypes ? { allowedNodeTypes } : {}),
225
272
  ...(allowedEdgeTypes ? { allowedEdgeTypes } : {}),
273
+ ...(nodeLimits ? { nodeLimits } : {}),
226
274
  };
227
275
  const ui = {
228
276
  controlSize,
@@ -231,6 +279,7 @@ export function normalizeStudioConfig(config, { fallback = null, legacy = null }
231
279
  regions: Object.freeze(normalizeStudioRegions(uiInput.regions, {})),
232
280
  leftPanel: normalizeSidebarConfig(uiInput.leftPanel, 'left'),
233
281
  rightPanel: normalizeSidebarConfig(uiInput.rightPanel, 'right'),
282
+ canvasHead: normalizeStudioCanvasHead(uiInput.canvasHead),
234
283
  sidebarWidth: Object.freeze({
235
284
  left: normalizeSidebarWidth(leftWidth, 244, 'config.ui.sidebarWidth.left'),
236
285
  right: normalizeSidebarWidth(rightWidth, 360, 'config.ui.sidebarWidth.right'),
@@ -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. */
@@ -247,11 +252,23 @@ export interface StudioRightPanelConfig extends StudioSidebarConfig {
247
252
  /** Defaults to flex. In scroll mode Nova scrolls the entire supplied content. */
248
253
  layout?: 'flex' | 'scroll'
249
254
  }
255
+ /** Floating head in the top-left corner of the design canvas. Since 0.3.9-preview. */
256
+ export interface StudioCanvasHeadConfig {
257
+ /** Show the "编辑模式" badge. Defaults to true. */
258
+ editingMode?: boolean
259
+ /**
260
+ * `always` (default) shows the scope path at every level; `nested` shows it only
261
+ * inside nested scopes such as sub-processes. The back button only appears in
262
+ * nested scopes either way. With nothing to show, the head takes no space.
263
+ */
264
+ scopePath?: 'always' | 'nested'
265
+ }
250
266
  export interface StudioUiConfig {
251
267
  controlSize?: StudioControlSize
252
268
  regions?: StudioShellRegions
253
269
  leftPanel?: StudioSidebarConfig
254
270
  rightPanel?: StudioRightPanelConfig
271
+ canvasHead?: StudioCanvasHeadConfig
255
272
  sidebarWidth?: {
256
273
  left?: number
257
274
  right?: number
@@ -358,6 +375,12 @@ export class BpmnStudioController {
358
375
  setPropertiesProfile(profile: 'business' | 'developer'): void
359
376
  allowsNodeType(nodeType: NodeType): boolean
360
377
  allowsEdgeType(edgeType: EdgeType): boolean
378
+ /** Type is allowed and adding `count` nodes (default 1) stays within config.modeling.nodeLimits, counted across the whole model. */
379
+ canAddNode(nodeType: NodeType, count?: number): boolean
380
+ /** Type is allowed and converting node `id` to it stays within node limits; a node already of that type does not count again. */
381
+ canChangeNodeType(id: string, type: NodeType): boolean
382
+ /** Human-readable limit reason (for example `最多 1 个开始事件`) when adding `count` nodes (default 1) would exceed the cap, otherwise null. */
383
+ nodeLimitReason(nodeType: NodeType, count?: number): string | null
361
384
  startConnect(sourceId: string): boolean
362
385
  cancelConnect(): void
363
386
  createNode(input: Parameters<StudioCommands['createNode']>[0]): BpmnNode
@@ -407,6 +430,10 @@ export class InteractionController {
407
430
  beginCreate(intent: CreateIntent): { intent: CreateIntent; startedAt: number }
408
431
  serialize(session: unknown): string
409
432
  deserialize(value: string): unknown
433
+ /** Readable reason when this create intent would exceed config.modeling.nodeLimits, otherwise null. Templates are judged by their combined per-type counts. */
434
+ createBlockedReason(intent: CreateIntent, point?: Point | null): string | null
435
+ /** Readable reason when a template definition would exceed node limits, otherwise null. */
436
+ templateLimitReason(definition: TemplateDefinition | null | undefined): string | null
410
437
  drop(session: unknown, pointer: { clientX: number; clientY: number }, canvas: { clientToWorld(x: number, y: number): Point }): unknown
411
438
  }
412
439
  export function createTemplateRegistry(templates?: TemplateRegistration[]): TemplateRegistry
@@ -480,6 +507,16 @@ export interface BpmnCanvasOptions {
480
507
  theme?: NovaThemeInput
481
508
  onThemeChange?: (state: NovaThemeState) => void
482
509
  }
510
+ export interface CanvasRevealElementOptions {
511
+ /** Restrict the lookup to nodes or edges; by id alone nodes are searched first. */
512
+ kind?: 'node' | 'edge'
513
+ /** Select the element after revealing it. Defaults to true. */
514
+ select?: boolean
515
+ /** '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. */
516
+ zoom?: 'keep' | 'fit' | number
517
+ /** Padding around the element for fit zoom and zero-size edge boxes. Defaults to 72. */
518
+ padding?: number
519
+ }
483
520
  export class BpmnCanvas {
484
521
  constructor(options: BpmnCanvasOptions)
485
522
  clientToWorld(clientX: number, clientY: number): Point
@@ -487,6 +524,10 @@ export class BpmnCanvas {
487
524
  fitView(padding?: number, options?: Record<string, unknown>): void
488
525
  refreshPresentation(): void
489
526
  fitSelection(padding?: number): boolean
527
+ /** 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. */
528
+ revealElement(id: string, options?: CanvasRevealElementOptions): boolean
529
+ /** Delegate to the renderer viewport: apply zoom and pan in one step. */
530
+ setViewportState(state: { zoom: number; pan: Point }): boolean
490
531
  setPointerMode(mode: 'select' | 'marquee' | 'pan'): boolean
491
532
  getPointerMode(): 'select' | 'marquee' | 'pan'
492
533
  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);