@bpmn-nova/studio 0.3.6-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.6-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
  }
@@ -588,6 +588,95 @@ async function resolvedImageData(asset, action, context, warnings, signal) {
588
588
  }
589
589
  }
590
590
 
591
+ const AVATAR_SIZE = 32;
592
+ const AVATAR_OVERLAP = 8;
593
+ const AVATAR_VISIBLE_LIMIT = 2;
594
+ let avatarClipSequence = 0;
595
+
596
+ function timelineAvatarPeople(item) {
597
+ if (!item || item.kind === 'transition' || item.predicted || item.automated) return [];
598
+ return (item.participants || []).filter((participant) => String(participant?.name || '').trim());
599
+ }
600
+
601
+ function participantInitial(participant) {
602
+ return String(participant?.name || '').trim().slice(0, 1) || '?';
603
+ }
604
+
605
+ async function resolvedAvatarData(url, context, warnings, signal, item) {
606
+ const source = String(url || '').trim();
607
+ if (!source) return null;
608
+ const cache = context.avatarCache || (context.avatarCache = new Map());
609
+ if (cache.has(source)) return cache.get(source);
610
+ try {
611
+ signal?.throwIfAborted?.();
612
+ let data = source;
613
+ if (source.startsWith('data:')) {
614
+ if (!source.startsWith('data:image/')) throw new Error('Unexpected Data URL MIME type.');
615
+ } else {
616
+ const ownerWindow = context.document?.defaultView || globalThis;
617
+ const response = await ownerWindow.fetch(source, { signal });
618
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
619
+ const blob = await response.blob();
620
+ if (!blob.type.startsWith('image/')) throw new Error(`Unexpected MIME type: ${blob.type || 'unknown'}`);
621
+ data = await new Promise((resolve, reject) => {
622
+ const reader = new ownerWindow.FileReader();
623
+ reader.addEventListener('load', () => resolve(String(reader.result)), { once: true });
624
+ reader.addEventListener('error', () => reject(reader.error || new Error('Unable to read image.')), { once: true });
625
+ reader.readAsDataURL(blob);
626
+ });
627
+ }
628
+ cache.set(source, data);
629
+ return data;
630
+ } catch (error) {
631
+ cache.delete(source);
632
+ if (signal?.aborted) throw error;
633
+ warnings.push({ code: 'avatar-unavailable', message: '处理人头像无法嵌入 SVG,已显示姓名首字。', elementId: item?.elementId });
634
+ return null;
635
+ }
636
+ }
637
+
638
+ async function renderTimelineAvatars({ document, parent, people, x, y, theme, context, warnings, signal, item }) {
639
+ const visible = people.slice(0, AVATAR_VISIBLE_LIMIT);
640
+ const overflow = people.length - AVATAR_VISIBLE_LIMIT;
641
+ const count = visible.length + (overflow > 0 ? 1 : 0);
642
+ const primary = tone(theme, 'primary');
643
+ for (let index = 0; index < visible.length; index += 1) {
644
+ const left = x + index * (AVATAR_SIZE - AVATAR_OVERLAP);
645
+ const cx = left + AVATAR_SIZE / 2;
646
+ const cy = y + AVATAR_SIZE / 2;
647
+ const person = visible[index];
648
+ const data = await resolvedAvatarData(person.avatarUrl, context, warnings, signal, item);
649
+ parent.appendChild(svgElement(document, 'circle', {
650
+ cx, cy, r: AVATAR_SIZE / 2, fill: theme.colors.primarySoft, stroke: theme.colors.surface, 'stroke-width': 2,
651
+ }));
652
+ if (data) {
653
+ avatarClipSequence += 1;
654
+ const clipId = `nova-timeline-avatar-${avatarClipSequence}`;
655
+ const clip = svgElement(document, 'clipPath', { id: clipId });
656
+ clip.appendChild(svgElement(document, 'circle', { cx, cy, r: AVATAR_SIZE / 2 }));
657
+ parent.appendChild(clip);
658
+ parent.appendChild(svgElement(document, 'image', {
659
+ x: left, y, width: AVATAR_SIZE, height: AVATAR_SIZE, href: data, preserveAspectRatio: 'xMidYMid slice', 'clip-path': `url(#${clipId})`,
660
+ }));
661
+ } else {
662
+ parent.appendChild(svgElement(document, 'text', {
663
+ x: cx, y: y + 21, 'text-anchor': 'middle', fill: primary.foreground, 'font-size': 12, 'font-weight': 600, 'font-family': theme.fontFamily,
664
+ }, participantInitial(person)));
665
+ }
666
+ }
667
+ if (overflow > 0) {
668
+ const left = x + visible.length * (AVATAR_SIZE - AVATAR_OVERLAP);
669
+ const cx = left + AVATAR_SIZE / 2;
670
+ parent.appendChild(svgElement(document, 'circle', {
671
+ cx, cy: y + AVATAR_SIZE / 2, r: AVATAR_SIZE / 2, fill: theme.colors.primarySoft, stroke: theme.colors.surface, 'stroke-width': 2,
672
+ }));
673
+ parent.appendChild(svgElement(document, 'text', {
674
+ x: cx, y: y + 21, 'text-anchor': 'middle', fill: primary.foreground, 'font-size': 10, 'font-weight': 600, 'font-family': theme.fontFamily,
675
+ }, `+${overflow}`));
676
+ }
677
+ return count > 0 ? AVATAR_SIZE + (count - 1) * (AVATAR_SIZE - AVATAR_OVERLAP) : 0;
678
+ }
679
+
591
680
  function timelineSequence(projection) {
592
681
  const groupedIds = new Set((projection.groups || []).flatMap((group) => group.itemIds || []));
593
682
  return [
@@ -670,9 +759,17 @@ async function renderTimelineItem({ document, parent, item, x, y, width, theme,
670
759
  parent.appendChild(svgElement(document, 'circle', { cx: railX, cy: y + 22, r: 4.5, fill: itemTone.strong }));
671
760
  const contentX = x + 46;
672
761
  const contentWidth = width - 46;
673
- parent.appendChild(svgElement(document, 'text', { x: contentX, y: y + 20, fill: theme.colors.text, 'font-size': 15, 'font-weight': 650, 'font-family': theme.fontFamily }, `${item.name}${item.round > 1 ? ` 第 ${item.round} 次` : ''}`));
762
+ const people = timelineAvatarPeople(item);
763
+ let textX = contentX;
764
+ if (people.length) {
765
+ const stackWidth = await renderTimelineAvatars({
766
+ document, parent, people, x: contentX, y: y + 6, theme, context, warnings, signal, item,
767
+ });
768
+ textX = contentX + stackWidth + 8;
769
+ }
770
+ parent.appendChild(svgElement(document, 'text', { x: textX, y: y + 20, fill: theme.colors.text, 'font-size': 15, 'font-weight': 650, 'font-family': theme.fontFamily }, `${item.name}${item.round > 1 ? ` 第 ${item.round} 次` : ''}`));
674
771
  parent.appendChild(svgElement(document, 'text', { x: contentX + contentWidth, y: y + 20, 'text-anchor': 'end', fill: itemTone.foreground, 'font-size': 12, 'font-weight': 600, 'font-family': theme.fontFamily }, resultLabel(item)));
675
- parent.appendChild(svgElement(document, 'text', { x: contentX, y: y + 42, fill: theme.colors.textSecondary, 'font-size': 11.5, 'font-family': theme.fontFamily }, item.summary || ''));
772
+ parent.appendChild(svgElement(document, 'text', { x: textX, y: y + 42, fill: theme.colors.textSecondary, 'font-size': 11.5, 'font-family': theme.fontFamily }, item.summary || ''));
676
773
  parent.appendChild(svgElement(document, 'text', { x: contentX + contentWidth, y: y + 42, 'text-anchor': 'end', fill: theme.colors.textMuted, 'font-size': 11, 'font-family': theme.fontFamily }, formatTime(item.time)));
677
774
  let actionY = y + 56;
678
775
  for (const action of actions) {
@@ -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();