@invana/canvas-core 0.0.14 → 0.0.15

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/dist/index.js CHANGED
@@ -352,8 +352,20 @@ var Behaviour = class {
352
352
  * from the constructor — subclasses don't need to re-declare.
353
353
  */
354
354
  scope;
355
+ /**
356
+ * Whether the behaviour is **live**: the developer's flag ({@link enabled})
357
+ * *and* the current interaction mode being one of {@link BehaviourOptions.modes}.
358
+ * Subclasses gate their handlers on this (or {@link isEnabled}); only the base
359
+ * writes it.
360
+ */
355
361
  _enabled;
356
362
  ctx;
363
+ /** The developer's enable flag — what {@link enabled} reports and snapshots capture. */
364
+ _wanted;
365
+ /** `false` while the canvas's mode is outside {@link BehaviourOptions.modes}. */
366
+ _inMode = true;
367
+ /** Releases the `viewMode` subscription, or `null` when not watching. */
368
+ _modeUnsub = null;
357
369
  /**
358
370
  * The construction options, merged in-place by {@link setOptions}. Named
359
371
  * `_options` (not `options`) so subclasses that expose a bespoke
@@ -373,11 +385,13 @@ var Behaviour = class {
373
385
  this.targetLayerId = opts.targetLayerId;
374
386
  this.scope = opts.targetLayerId !== void 0 ? "layer" : "canvas";
375
387
  this.shortcuts = opts.shortcuts;
376
- this._enabled = opts.enabled ?? false;
388
+ this._wanted = opts.enabled ?? false;
389
+ this._enabled = this._wanted;
377
390
  this._options = opts;
378
391
  }
392
+ /** The developer's enable flag. A behaviour suspended by its `modes` still reports `true`. */
379
393
  get enabled() {
380
- return this._enabled;
394
+ return this._wanted;
381
395
  }
382
396
  get isRegistered() {
383
397
  return this.ctx !== void 0;
@@ -389,6 +403,8 @@ var Behaviour = class {
389
403
  }
390
404
  this.ctx = ctx;
391
405
  this.onRegister(ctx);
406
+ this.watchMode();
407
+ this._enabled = this._wanted && this._inMode;
392
408
  if (this._enabled) this.onEnable();
393
409
  }
394
410
  /** Called by `BehaviourRegistry.unregister(id)`. Drops subscriptions. */
@@ -396,20 +412,66 @@ var Behaviour = class {
396
412
  if (this.ctx === void 0) return;
397
413
  const ctx = this.ctx;
398
414
  this._enabled = false;
415
+ this._wanted = false;
416
+ this.unwatchMode();
399
417
  this.onDestroy(ctx);
400
418
  this.releaseGesture();
401
419
  this.ctx = void 0;
402
420
  }
403
421
  enable() {
404
- if (this._enabled) return;
405
- this._enabled = true;
406
- this.onEnable();
422
+ if (this._wanted) return;
423
+ this._wanted = true;
424
+ this.syncLive();
407
425
  }
408
426
  disable() {
409
- if (!this._enabled) return;
410
- this._enabled = false;
411
- this.onDisable();
412
- this.releaseGesture();
427
+ if (!this._wanted) return;
428
+ this._wanted = false;
429
+ this.syncLive();
430
+ }
431
+ /**
432
+ * Bring {@link _enabled} in line with `_wanted && _inMode`, running the
433
+ * matching hook on a change. The single place a behaviour goes live or idle.
434
+ */
435
+ syncLive() {
436
+ const live = this._wanted && this._inMode;
437
+ if (live === this._enabled) return;
438
+ this._enabled = live;
439
+ if (live) {
440
+ this.onEnable();
441
+ } else {
442
+ this.onDisable();
443
+ this.releaseGesture();
444
+ }
445
+ }
446
+ /** Is `mode` one this behaviour is live in? */
447
+ matchesMode(mode) {
448
+ const modes = this._options.modes;
449
+ return modes === void 0 || modes.includes(mode);
450
+ }
451
+ /**
452
+ * Follow `view.interaction.viewMode` while registered and `modes` is set;
453
+ * otherwise stop following and count as in-mode. Idempotent — `setOptions`
454
+ * calls it again when `modes` changes.
455
+ */
456
+ watchMode() {
457
+ const ctx = this.ctx;
458
+ if (ctx === void 0 || this._options.modes === void 0) {
459
+ this.unwatchMode();
460
+ this._inMode = true;
461
+ return;
462
+ }
463
+ const view = ctx.store.view;
464
+ this._inMode = this.matchesMode(view.getState().interaction.viewMode);
465
+ if (this._modeUnsub !== null) return;
466
+ this._modeUnsub = view.subscribe((state, prev) => {
467
+ if (state.interaction.viewMode === prev.interaction.viewMode) return;
468
+ this._inMode = this.matchesMode(state.interaction.viewMode);
469
+ this.syncLive();
470
+ });
471
+ }
472
+ unwatchMode() {
473
+ this._modeUnsub?.();
474
+ this._modeUnsub = null;
413
475
  }
414
476
  /**
415
477
  * Merge a serialisable options patch and apply it live. Reflects an `enabled`
@@ -425,12 +487,51 @@ var Behaviour = class {
425
487
  */
426
488
  setOptions(changes) {
427
489
  this._options = { ...this._options, ...changes };
428
- if (changes.enabled !== void 0) {
429
- if (changes.enabled) this.enable();
430
- else this.disable();
431
- }
490
+ if ("modes" in changes) this.setModes(changes.modes);
491
+ if (changes.enabled !== void 0) this.applyEnabled(changes.enabled);
432
492
  this.onOptionsChanged(changes);
433
493
  }
494
+ /**
495
+ * Apply an `enabled` option. While this instance is the one mounted under its
496
+ * id, the toggle goes through the registry so `scene:behaviour:enable` /
497
+ * `disable` and the gesture-conflict warning fire — calling {@link enable}
498
+ * directly would leave the registry's own `setEnabled` (the engine's
499
+ * `canvas.update` path) a silent no-op. Unmounted, or superseded by a newer
500
+ * instance under the same id, it toggles itself directly.
501
+ */
502
+ applyEnabled(enabled) {
503
+ const registry = this.ctx?.behaviours;
504
+ if (registry && registry.get(this.id) === this) {
505
+ registry.setEnabled(this.id, enabled);
506
+ } else if (enabled) {
507
+ this.enable();
508
+ } else {
509
+ this.disable();
510
+ }
511
+ }
512
+ /**
513
+ * Replace {@link BehaviourOptions.modes} and re-evaluate liveness against the
514
+ * current interaction mode. `undefined` = live in every mode.
515
+ */
516
+ setModes(modes) {
517
+ this._options = { ...this._options, modes };
518
+ this.watchMode();
519
+ this.syncLive();
520
+ }
521
+ /**
522
+ * Merge `changes` into the options {@link getOptions} returns — and nothing
523
+ * else: no enable / disable, no mode re-wiring, no {@link onOptionsChanged}.
524
+ *
525
+ * For subclasses that override {@link setOptions} with their own apply logic
526
+ * and don't call `super`: call this first so `getOptions()` (a settings
527
+ * editor's seed, the engine's undo baseline) stays current. Prefer it to
528
+ * `super.setOptions` there: the engine routes `enabled` / `modes` through
529
+ * the registry itself, and the base's direct `enable()` would pre-empt the
530
+ * registry's `scene:behaviour:enable` event.
531
+ */
532
+ recordOptions(changes) {
533
+ this._options = { ...this._options, ...changes };
534
+ }
434
535
  /** Snapshot of the current (merged) options — seeds a settings editor. */
435
536
  getOptions() {
436
537
  return this._options;
@@ -442,7 +543,8 @@ var Behaviour = class {
442
543
  * JSON-serialisable options should override and spread `super.serializeDefinition()`.
443
544
  */
444
545
  serializeDefinition() {
445
- return { enabled: this._enabled };
546
+ const modes = this._options.modes;
547
+ return modes === void 0 ? { enabled: this._wanted } : { enabled: this._wanted, modes: [...modes] };
446
548
  }
447
549
  /** Cleanup on destroy. Default no-op. */
448
550
  onDestroy(_ctx) {
@@ -465,7 +567,7 @@ var Behaviour = class {
465
567
  }
466
568
  /**
467
569
  * Convenience `if (!enabled) return;` for use inside event handlers
468
- * (without rebinding `this` cost).
570
+ * (without rebinding `this` cost). `false` while suspended by `modes`.
469
571
  */
470
572
  get isEnabled() {
471
573
  return this._enabled;
@@ -547,9 +649,22 @@ var Layout = class {
547
649
  * emitter on top (`override readonly events = new EventEmitter<MyEvents>()`).
548
650
  */
549
651
  events = new EventEmitter();
652
+ /**
653
+ * Options of the run in flight, or of the last one once it has ended.
654
+ * Implementations record them at the top of {@link apply}, so an `end`
655
+ * listener can tell what kind of run just finished — e.g. a fitter skipping
656
+ * a {@link LayoutRunOptions.preserveCamera} run.
657
+ */
658
+ runOptions = {};
659
+ /**
660
+ * How data-triggered re-runs behave while this layout is active (throttle,
661
+ * keep the camera). Mutable: the wiring reads it on every data change.
662
+ */
663
+ onData;
550
664
  constructor(opts = {}) {
551
665
  this.id = opts.id ?? "layout";
552
666
  this.targetLayerId = opts.targetLayerId;
667
+ this.onData = { ...opts.onData ?? {} };
553
668
  }
554
669
  /**
555
670
  * Live-reconfigure. Called by `Canvas.update({ layouts: { id: patch } })`.
@@ -566,7 +681,10 @@ var Layout = class {
566
681
  * JSON-safe copy of those params.
567
682
  */
568
683
  serializeDefinition() {
569
- return this.targetLayerId !== void 0 ? { targetLayerId: this.targetLayerId } : void 0;
684
+ const out = {};
685
+ if (this.targetLayerId !== void 0) out.targetLayerId = this.targetLayerId;
686
+ if (Object.keys(this.onData).length > 0) out.onData = { ...this.onData };
687
+ return Object.keys(out).length > 0 ? out : void 0;
570
688
  }
571
689
  };
572
690
 
@@ -763,6 +881,7 @@ var Camera = class {
763
881
  zoom: this.clampScale(opts.initialScale ?? 1)
764
882
  });
765
883
  this._offBindingChange = this.binding.onTransformChange((kind) => {
884
+ this.cancelAnimation();
766
885
  const t = this.binding.getTransform();
767
886
  if (kind === "zoom") {
768
887
  this.bus?.emit("input:camera:zoom", {
@@ -955,15 +1074,32 @@ var Camera = class {
955
1074
  * maps to the screen centre, keeping the current zoom. The pan-only
956
1075
  * counterpart to {@link fitContent}: use it for "focus" / "go to" actions
957
1076
  * that should locate a target without rescaling the view.
1077
+ *
1078
+ * By default the pan is applied at once. Pass a positive `durationMs` to
1079
+ * glide there instead — the move then runs through {@link animateTo}, so it
1080
+ * follows the same rules: eased, and cancelled by any other camera write.
1081
+ *
1082
+ * @param durationMs Length of the glide. Absent or `<= 0` pans immediately.
1083
+ * @param easing Named curve for the glide; defaults to `'easeOutCubic'`.
1084
+ * @param onDone Called once the camera is on target (immediately when
1085
+ * not gliding; never when a glide is cancelled).
958
1086
  */
959
- centerOn(worldX, worldY) {
960
- this.cancelAnimation();
1087
+ centerOn(worldX, worldY, { durationMs = 0, easing, onDone } = {}) {
961
1088
  const scale = this.scale;
962
1089
  const tx = this._screenWidth / 2 - worldX * scale;
963
1090
  const ty = this._screenHeight / 2 - worldY * scale;
1091
+ if (durationMs > 0) {
1092
+ this.animateTo(
1093
+ { x: tx, y: ty, zoom: scale },
1094
+ { durationMs, ...easing ? { easing } : {}, ...onDone ? { onDone } : {} }
1095
+ );
1096
+ return;
1097
+ }
1098
+ this.cancelAnimation();
964
1099
  this.binding.setTransform({ x: tx, y: ty, zoom: scale });
965
1100
  this.bus?.emit("input:camera:pan", { x: tx, y: ty });
966
1101
  this.pushToStore();
1102
+ onDone?.();
967
1103
  }
968
1104
  /** Update on viewport resize. Forwarded so the binding's own math stays correct. */
969
1105
  resize(screenWidth, screenHeight) {
@@ -1243,6 +1379,11 @@ var BehaviourRegistry = class {
1243
1379
  * Register a Behaviour. Wires it (`behaviour.register(ctx)` + events) now if
1244
1380
  * the Canvas is initialised; otherwise it's stored and wired later by
1245
1381
  * `registerAll()` (called by `Canvas.init`). Throws on duplicate id.
1382
+ *
1383
+ * When wiring throws (the behaviour rejects its context — a missing target
1384
+ * layer, a second instance of a one-per-layer kind), the entry is removed
1385
+ * before the error propagates, so a rejected behaviour never shows up in
1386
+ * {@link list} and its id stays free.
1246
1387
  */
1247
1388
  register(behaviour) {
1248
1389
  if (this.behaviours.has(behaviour.id)) {
@@ -1250,14 +1391,26 @@ var BehaviourRegistry = class {
1250
1391
  }
1251
1392
  this.behaviours.set(behaviour.id, behaviour);
1252
1393
  const ctx = this.getContext();
1253
- if (ctx) this.wire(behaviour, ctx);
1394
+ if (!ctx) return;
1395
+ try {
1396
+ this.wire(behaviour, ctx);
1397
+ } catch (err) {
1398
+ this.behaviours.delete(behaviour.id);
1399
+ throw err;
1400
+ }
1254
1401
  }
1255
1402
  /** Wire every not-yet-registered behaviour. Called by `Canvas.init` (after layers mount). */
1256
1403
  registerAll() {
1257
1404
  const ctx = this.getContext();
1258
1405
  if (!ctx) return;
1259
- for (const behaviour of this.behaviours.values()) {
1260
- if (!behaviour.isRegistered) this.wire(behaviour, ctx);
1406
+ for (const behaviour of [...this.behaviours.values()]) {
1407
+ if (behaviour.isRegistered) continue;
1408
+ try {
1409
+ this.wire(behaviour, ctx);
1410
+ } catch (err) {
1411
+ this.behaviours.delete(behaviour.id);
1412
+ throw err;
1413
+ }
1261
1414
  }
1262
1415
  }
1263
1416
  /** `behaviour.register(ctx)` + the registered/enabled events. */
@@ -1269,7 +1422,11 @@ var BehaviourRegistry = class {
1269
1422
  this.warnOnShortcutConflict(behaviour);
1270
1423
  }
1271
1424
  }
1272
- /** Remove a behaviour. Calls `destroy()`. No-op if not registered. */
1425
+ /**
1426
+ * Remove a behaviour. Calls `destroy()`, then fires
1427
+ * `'scene:behaviour:unregister'` (after `'scene:behaviour:disable'` when it
1428
+ * was enabled). No-op if not registered.
1429
+ */
1273
1430
  unregister(id) {
1274
1431
  const b = this.behaviours.get(id);
1275
1432
  if (!b) return;
@@ -1279,6 +1436,7 @@ var BehaviourRegistry = class {
1279
1436
  }
1280
1437
  this.behaviours.delete(id);
1281
1438
  b.destroy();
1439
+ this.bus.emit("scene:behaviour:unregister", { id });
1282
1440
  }
1283
1441
  /** Enable / disable a behaviour. Fires the corresponding bus event. */
1284
1442
  setEnabled(id, enabled) {
@@ -1366,6 +1524,208 @@ var LayoutRegistry = class {
1366
1524
  }
1367
1525
  };
1368
1526
 
1527
+ // src/abstracts/registries/CommandRegistry.ts
1528
+ function isDevBuild() {
1529
+ try {
1530
+ return process.env.NODE_ENV !== "production";
1531
+ } catch {
1532
+ return false;
1533
+ }
1534
+ }
1535
+ function argProblem(spec, value) {
1536
+ switch (spec.kind) {
1537
+ case "string":
1538
+ case "layer":
1539
+ case "behaviour":
1540
+ case "layout":
1541
+ return typeof value === "string" ? null : `expected a string (${spec.kind}), got ${describe(value)}`;
1542
+ case "number": {
1543
+ if (typeof value === "number" && Number.isFinite(value)) return null;
1544
+ if (spec.pick && typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return null;
1545
+ return `expected a finite number, got ${describe(value)}`;
1546
+ }
1547
+ case "boolean":
1548
+ return typeof value === "boolean" ? null : `expected a boolean, got ${describe(value)}`;
1549
+ case "enum": {
1550
+ const allowed = (spec.options ?? []).map((o) => o.value);
1551
+ return typeof value === "string" && allowed.includes(value) ? null : `expected one of ${allowed.map((v) => JSON.stringify(v)).join(", ")}, got ${describe(value)}`;
1552
+ }
1553
+ case "strings":
1554
+ return Array.isArray(value) && value.every((v) => typeof v === "string") ? null : `expected an array of strings, got ${describe(value)}`;
1555
+ case "json":
1556
+ return null;
1557
+ }
1558
+ }
1559
+ function describe(value) {
1560
+ if (Array.isArray(value)) return "an array";
1561
+ if (value === null) return "null";
1562
+ return typeof value === "string" ? JSON.stringify(value) : typeof value;
1563
+ }
1564
+ var CommandRegistry = class {
1565
+ /** Per name, the registrations oldest → newest; the last one is live. */
1566
+ stacks = /* @__PURE__ */ new Map();
1567
+ listeners = /* @__PURE__ */ new Set();
1568
+ /** Bumped on every {@link subscribe} signal — see {@link version}. */
1569
+ _version = 0;
1570
+ getContext;
1571
+ validateArgs;
1572
+ /** `command|key|problem` already warned about, so a bound button doesn't flood the console. */
1573
+ warned = /* @__PURE__ */ new Set();
1574
+ constructor(opts) {
1575
+ this.getContext = opts.getContext;
1576
+ this.validateArgs = opts.validateArgs ?? isDevBuild();
1577
+ }
1578
+ /**
1579
+ * Register `name`, overriding any existing registration. Returns a disposer
1580
+ * that removes **this** registration only: if it is live, the one underneath
1581
+ * becomes live again; if it was already overridden, the override stays.
1582
+ */
1583
+ register(name, command) {
1584
+ const entry = { command };
1585
+ const stack = this.stacks.get(name) ?? [];
1586
+ stack.push(entry);
1587
+ this.stacks.set(name, stack);
1588
+ this.notify();
1589
+ return () => {
1590
+ const current = this.stacks.get(name);
1591
+ const i = current?.indexOf(entry) ?? -1;
1592
+ if (!current || i < 0) return;
1593
+ current.splice(i, 1);
1594
+ if (current.length === 0) this.stacks.delete(name);
1595
+ this.notify();
1596
+ };
1597
+ }
1598
+ /** Remove every registration of `name`. No-op when absent. */
1599
+ unregister(name) {
1600
+ if (this.stacks.delete(name)) this.notify();
1601
+ }
1602
+ has(name) {
1603
+ return this.stacks.has(name);
1604
+ }
1605
+ /** The live (most recent) registration of `name`. */
1606
+ get(name) {
1607
+ const stack = this.stacks.get(name);
1608
+ return stack?.[stack.length - 1]?.command;
1609
+ }
1610
+ /** Registered command names, in first-registration order. */
1611
+ list() {
1612
+ return [...this.stacks.keys()];
1613
+ }
1614
+ /**
1615
+ * Run `name` with `args`. Returns `false` (and does nothing) when the command
1616
+ * is missing or disabled. With `validateArgs` on, first warns about any
1617
+ * described key whose value doesn't fit its descriptor — the run proceeds
1618
+ * regardless.
1619
+ */
1620
+ run(name, args) {
1621
+ const cmd = this.get(name);
1622
+ if (!cmd) return false;
1623
+ if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);
1624
+ const ctx = this.getContext();
1625
+ if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;
1626
+ void cmd.run(ctx, args);
1627
+ return true;
1628
+ }
1629
+ /**
1630
+ * {@link run}, awaiting the command's work: resolves once the promise a
1631
+ * command's `run` returned settles (`layout.run` resolves when the layout
1632
+ * run ends). Resolves `false` — without running anything — when the command
1633
+ * is missing or disabled; a synchronous command resolves `true` at once. A
1634
+ * playbook step's `do` verbs go through here, so each finishes before the
1635
+ * next starts.
1636
+ */
1637
+ async runAsync(name, args) {
1638
+ const cmd = this.get(name);
1639
+ if (!cmd) return false;
1640
+ if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);
1641
+ const ctx = this.getContext();
1642
+ if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;
1643
+ await cmd.run(ctx, args);
1644
+ return true;
1645
+ }
1646
+ /** `isActive` of `name`; `false` when missing or not a toggle. */
1647
+ isActive(name, args) {
1648
+ const cmd = this.get(name);
1649
+ return cmd?.isActive ? cmd.isActive(this.getContext(), args) : false;
1650
+ }
1651
+ /** `isEnabled` of `name`; `false` when missing, `true` when it declares no check. */
1652
+ isEnabled(name, args) {
1653
+ const cmd = this.get(name);
1654
+ if (!cmd) return false;
1655
+ return cmd.isEnabled ? cmd.isEnabled(this.getContext(), args) : true;
1656
+ }
1657
+ /** `value` of a pick-one command; `null` when missing or not a picker. */
1658
+ value(name, args) {
1659
+ const cmd = this.get(name);
1660
+ return cmd?.value ? cmd.value(this.getContext(), args) : null;
1661
+ }
1662
+ /** `options` of a pick-one command; `[]` when missing or it declares none. */
1663
+ options(name, args) {
1664
+ const cmd = this.get(name);
1665
+ return cmd?.options ? cmd.options(this.getContext(), args) : [];
1666
+ }
1667
+ /**
1668
+ * Tell subscribers that command state changed **outside** the view store (a
1669
+ * history stack, a clipboard buffer, a layer's edge defaults, a registry), so
1670
+ * a bound control re-reads `isEnabled` / `isActive` / `value` / `options`.
1671
+ *
1672
+ * Call it from the state's **owner** — a bridge from the owner's own change
1673
+ * signal, set up once (the engine bridges the registries, layer visibility and
1674
+ * `canvas.history`; `GraphCanvas` its layers' edge templates; a provider its
1675
+ * own history / clipboard) — never from the write sites, where another
1676
+ * writer would forget it. A command whose state lives in the view store
1677
+ * needs none.
1678
+ */
1679
+ invalidate() {
1680
+ this.notify();
1681
+ }
1682
+ /**
1683
+ * A counter bumped on every {@link subscribe} signal (register, unregister,
1684
+ * dispose, {@link invalidate}, {@link clear}) — and only then. Use it as a
1685
+ * `useSyncExternalStore` snapshot when a UI must re-read *everything* on a
1686
+ * signal: a snapshot derived from `list()` stays equal when only a command's
1687
+ * `options` / state changed, and React would skip the re-render.
1688
+ */
1689
+ get version() {
1690
+ return this._version;
1691
+ }
1692
+ /** Hear every register / unregister / {@link invalidate}. Returns an unsubscribe. */
1693
+ subscribe(listener) {
1694
+ this.listeners.add(listener);
1695
+ return () => this.listeners.delete(listener);
1696
+ }
1697
+ /** Drop every command and listener. */
1698
+ clear() {
1699
+ this.stacks.clear();
1700
+ this.notify();
1701
+ this.listeners.clear();
1702
+ }
1703
+ /** Warn (once each) about `args` values that don't fit `specs`. */
1704
+ checkArgs(name, specs, args) {
1705
+ if (args === void 0 || args === null) return;
1706
+ if (typeof args !== "object" || Array.isArray(args)) {
1707
+ this.warn(name, "", `args should be an object, got ${describe(args)}`);
1708
+ return;
1709
+ }
1710
+ for (const [key, spec] of Object.entries(specs)) {
1711
+ const value = args[key];
1712
+ if (value === void 0) continue;
1713
+ const problem = argProblem(spec, value);
1714
+ if (problem) this.warn(name, key, problem);
1715
+ }
1716
+ }
1717
+ warn(name, key, problem) {
1718
+ const id = `${name}|${key}|${problem}`;
1719
+ if (this.warned.has(id)) return;
1720
+ this.warned.add(id);
1721
+ console.warn(`[canvas] command "${name}"${key ? ` arg "${key}"` : ""}: ${problem}`);
1722
+ }
1723
+ notify() {
1724
+ this._version++;
1725
+ for (const l of [...this.listeners]) l();
1726
+ }
1727
+ };
1728
+
1369
1729
  // src/specs/geometry.ts
1370
1730
  function connectorGeometryKey(spec) {
1371
1731
  const { stroke: _stroke, ...geometry } = spec;
@@ -2343,6 +2703,9 @@ function noopOverlay() {
2343
2703
  poly: () => self,
2344
2704
  fill: () => self,
2345
2705
  stroke: () => self,
2706
+ setVisible: () => self,
2707
+ setZIndex: () => self,
2708
+ setPosition: () => self,
2346
2709
  destroy: () => {
2347
2710
  }
2348
2711
  };
@@ -2402,6 +2765,45 @@ var HeadlessElementRenderer = class {
2402
2765
  const s = this.shapes.get(id);
2403
2766
  return s ? { x: s.x, y: s.y } : null;
2404
2767
  }
2768
+ /**
2769
+ * Display overrides by shape id — recorded so a test can assert what a
2770
+ * behaviour asked to draw. Nothing is drawn, and positions stay logical.
2771
+ */
2772
+ displayOverrides = /* @__PURE__ */ new Map();
2773
+ setShapeDisplayOverride(id, override) {
2774
+ if (!this.shapes.has(id)) return;
2775
+ if (override === null) this.displayOverrides.delete(id);
2776
+ else this.displayOverrides.set(id, override);
2777
+ }
2778
+ clearShapeDisplayOverrides() {
2779
+ this.displayOverrides.clear();
2780
+ }
2781
+ /**
2782
+ * Ids whose text the LOD channel has hidden (`setShapeTextVisible` /
2783
+ * `setConnectorTextVisible` with `false`) — recorded so a behaviour test can
2784
+ * assert what a text LOD asked for.
2785
+ */
2786
+ textHidden = /* @__PURE__ */ new Set();
2787
+ setShapeTextVisible(id, visible) {
2788
+ if (visible) this.textHidden.delete(id);
2789
+ else this.textHidden.add(id);
2790
+ }
2791
+ setConnectorTextVisible(id, visible) {
2792
+ if (visible) this.textHidden.delete(id);
2793
+ else this.textHidden.add(id);
2794
+ }
2795
+ isTextVisible(id) {
2796
+ if (!this.shapes.has(id) && !this.connectors.has(id)) return false;
2797
+ return !this.textHidden.has(id);
2798
+ }
2799
+ /** The label-size policy last pushed per target — recorded for assertions. */
2800
+ labelSizePolicies = {
2801
+ shape: null,
2802
+ connector: null
2803
+ };
2804
+ setLabelSizePolicy(target, policy) {
2805
+ this.labelSizePolicies[target] = policy;
2806
+ }
2405
2807
  // Everything below is a no-op or a null answer: these are the calls a layer
2406
2808
  // makes for pixels, and there are none here.
2407
2809
  scaleShape() {
@@ -2412,8 +2814,6 @@ var HeadlessElementRenderer = class {
2412
2814
  }
2413
2815
  setRaised() {
2414
2816
  }
2415
- setShapeTextVisible() {
2416
- }
2417
2817
  setShapeIconVisible() {
2418
2818
  }
2419
2819
  setShapeImageVisible() {
@@ -4482,6 +4882,22 @@ function resolveConnectorBadgePosition(path, badgeLocalBounds, options, clearanc
4482
4882
  };
4483
4883
  }
4484
4884
 
4885
+ // src/lib/geometry/labels/labelScale.ts
4886
+ function resolveLabelScale(fontSize, zoom, hostScale, policy, contained = false) {
4887
+ if (policy === null) return 1;
4888
+ if (!(fontSize > 0) || !(zoom > 0) || !(hostScale > 0)) return 1;
4889
+ const natural = fontSize * zoom * hostScale;
4890
+ let target = policy.zoomGrowth === void 0 ? natural : fontSize * Math.pow(zoom, clampUnit(policy.zoomGrowth));
4891
+ if (policy.minFontPx !== void 0 && target < policy.minFontPx) target = policy.minFontPx;
4892
+ if (policy.maxFontPx !== void 0 && target > policy.maxFontPx) target = policy.maxFontPx;
4893
+ const scale = target / natural;
4894
+ return contained && scale > 1 ? 1 : scale;
4895
+ }
4896
+ function clampUnit(v) {
4897
+ if (!Number.isFinite(v)) return 1;
4898
+ return v < 0 ? 0 : v > 1 ? 1 : v;
4899
+ }
4900
+
4485
4901
  // src/lib/animation/animatePositions.ts
4486
4902
  var DEFAULT_POSITION_TRANSITION_MS = 500;
4487
4903
  function animatePositions(opts) {
@@ -4498,7 +4914,7 @@ function animatePositions(opts) {
4498
4914
  let last = 0;
4499
4915
  const finish = () => {
4500
4916
  done = true;
4501
- onFrame(to);
4917
+ onFrame(to, 1);
4502
4918
  onComplete?.();
4503
4919
  };
4504
4920
  const raf2 = typeof requestAnimationFrame === "function" ? requestAnimationFrame : null;
@@ -4522,7 +4938,7 @@ function animatePositions(opts) {
4522
4938
  }
4523
4939
  const t = tween.value;
4524
4940
  for (let i = 0; i < n2; i++) buffer[i] = from[i] + (to[i] - from[i]) * t;
4525
- onFrame(buffer);
4941
+ onFrame(buffer, t);
4526
4942
  rafId = raf2(step);
4527
4943
  };
4528
4944
  rafId = raf2(step);
@@ -4867,7 +5283,8 @@ function defaultCanvasView() {
4867
5283
  layouts: {},
4868
5284
  activeLayout: null,
4869
5285
  templates: [],
4870
- theme: {}
5286
+ theme: {},
5287
+ controlPanels: {}
4871
5288
  },
4872
5289
  interaction: {
4873
5290
  selection: /* @__PURE__ */ new Set(),
@@ -4876,8 +5293,11 @@ function defaultCanvasView() {
4876
5293
  raised: {},
4877
5294
  camera: { x: 0, y: 0, zoom: 1 },
4878
5295
  focus: null,
5296
+ inspect: null,
5297
+ cameraIntent: null,
4879
5298
  transientPins: /* @__PURE__ */ new Set(),
4880
- viewMode: "select"
5299
+ viewMode: "select",
5300
+ viewModeArgs: {}
4881
5301
  },
4882
5302
  runtime: {
4883
5303
  layout: { running: false, activeId: null, animate: false, progress: null },
@@ -5032,6 +5452,20 @@ function createActions(view, layer, events) {
5032
5452
  s.interaction.raised = next;
5033
5453
  })
5034
5454
  },
5455
+ // ── VIEW · interaction mode (the modeller "tool") ─────────────────────────
5456
+ viewMode: {
5457
+ /**
5458
+ * Switch the active mode. `args`, when given, **replaces** the mode's
5459
+ * parameters; omit it to keep the current ones (a tool's node kind
5460
+ * survives a trip through Select).
5461
+ */
5462
+ set: (mode, args) => v("view:viewMode:set", (s) => {
5463
+ s.interaction.viewMode = mode;
5464
+ if (args !== void 0) s.interaction.viewModeArgs = { ...args };
5465
+ }),
5466
+ /** Shallow-merge `patch` into the mode parameters. */
5467
+ setArgs: (patch) => v("view:viewMode:setArgs", (s) => void (s.interaction.viewModeArgs = { ...s.interaction.viewModeArgs, ...patch }))
5468
+ },
5035
5469
  // ── VIEW · templates (e.g. node templates) ────────────────────────────────
5036
5470
  templates: {
5037
5471
  create: (template) => v("view:template:create", (s) => void (s.definition.templates = [...s.definition.templates, template])),
@@ -5042,6 +5476,25 @@ function createActions(view, layer, events) {
5042
5476
  }),
5043
5477
  remove: (id) => v("view:template:remove", (s) => void (s.definition.templates = s.definition.templates.filter((t) => t.id !== id)))
5044
5478
  },
5479
+ // ── VIEW · control panels (floating chrome over the canvas) ───────────────
5480
+ controlPanels: {
5481
+ /** Add (or replace) the panel `id`. */
5482
+ add: (id, spec) => v("view:controlPanel:add", (s) => void (s.definition.controlPanels[id] = spec)),
5483
+ /** Shallow-merge `patch` into panel `id` (`items` replaces). No-op when absent. */
5484
+ update: (id, patch) => v("view:controlPanel:update", (s) => {
5485
+ const cur = s.definition.controlPanels[id];
5486
+ if (cur) s.definition.controlPanels[id] = { ...cur, ...patch };
5487
+ }),
5488
+ show: (id) => v("view:controlPanel:show", (s) => {
5489
+ const cur = s.definition.controlPanels[id];
5490
+ if (cur) s.definition.controlPanels[id] = { ...cur, visible: true };
5491
+ }),
5492
+ hide: (id) => v("view:controlPanel:hide", (s) => {
5493
+ const cur = s.definition.controlPanels[id];
5494
+ if (cur) s.definition.controlPanels[id] = { ...cur, visible: false };
5495
+ }),
5496
+ remove: (id) => v("view:controlPanel:remove", (s) => void delete s.definition.controlPanels[id])
5497
+ },
5045
5498
  // ── VIEW · theme ──────────────────────────────────────────────────────────
5046
5499
  theme: {
5047
5500
  set: (patch) => v("view:theme:set", (s) => void (s.definition.theme = { ...s.definition.theme, ...patch }))
@@ -5068,6 +5521,19 @@ function createActions(view, layer, events) {
5068
5521
  set: (ids, dim = true) => v("view:focus:set", (s) => void (s.interaction.focus = { ids: new Set(ids), dim })),
5069
5522
  clear: () => v("view:focus:clear", (s) => void (s.interaction.focus = null))
5070
5523
  },
5524
+ // ── VIEW · inspect (whose properties are open) ────────────────────────────
5525
+ inspect: {
5526
+ set: (id) => v("view:inspect:set", (s) => void (s.interaction.inspect = id)),
5527
+ clear: () => v("view:inspect:clear", (s) => void (s.interaction.inspect = null))
5528
+ },
5529
+ // ── VIEW · camera intent (frame the focus / the visible / everything) ─────
5530
+ cameraIntent: {
5531
+ /** Ask for a framing; the owner performs it once the canvas settles. */
5532
+ request: (intent) => v(
5533
+ "view:cameraIntent:request",
5534
+ (s) => void (s.interaction.cameraIntent = { intent, seq: (s.interaction.cameraIntent?.seq ?? 0) + 1 })
5535
+ )
5536
+ },
5071
5537
  // ── VIEW · transient pins (drag/resize gesture locks; NOT data `pinned`) ───
5072
5538
  transientPins: {
5073
5539
  add: (ids) => v("view:transientPins:add", (s) => void (s.interaction.transientPins = /* @__PURE__ */ new Set([...s.interaction.transientPins, ...ids]))),
@@ -5759,6 +6225,6 @@ var LayerData = class {
5759
6225
  }
5760
6226
  };
5761
6227
 
5762
- export { Behaviour, BehaviourRegistry, CANVAS_SOURCE, Camera, CanvasEventBus, CanvasThemeState, ColumnStore, DEFAULT_ENDPOINT_BADGE_GAP_PX, DEFAULT_POSITION_TRANSITION_MS, DefaultGestureArbiter, DirtyBatcher, EASING_NAMES, EventEmitter, HeadlessCameraBinding, HeadlessElementRenderer, HeadlessRenderer, HeadlessSurface, INHERIT, LOOP_CURVE_PRESETS, Layer, LayerData, LayerRegistry, Layout, LayoutRegistry, NODE_FLAG, SourceEmitter, SpecProjector, SpecStore, Tween, animatePositions, attrs, bezierPathStyle, boundaryAnchor, boundsOfArc, boundsOfCircle, boundsOfComposite, boundsOfCompositeRoot, boundsOfEllipse, boundsOfPath, boundsOfPolygon, boundsOfRect, boundsOfRegularPolygon, boundsOfSpec, boundsOfStar, bumpHorizontalPathStyle, bumpRadialPathStyle, bundlePathStyle, centerAnchor, collapsedSpec, collapsedTabbedRect, compositeRootOffset, connectorGeometryKey, connectorToSvg, containsArc, containsCircle, containsComposite, containsEllipse, containsPath, containsPolygon, containsRect, containsRegularPolygon, containsSpec, containsStar, containsTabbedRect, createActions, defaultCanvasView, defaultEqual, distanceToOutlineSq, distanceToPolylineSq, distanceToSegmentSq, easeInOutCubic, easeInOutSine, easeOutCubic, easeOutQuad, edgePortAnchor, erRouter, esc, fillPaint, fitSpecToContent, fitTabbedRectToContent, hasSilhouetteFill, hexToCss, isInherit, linear, loopCurvePathStyle, loopPolylinePathStyle, manhattanRouter, metroRouter, normalPathStyle, offsetPolygon, oneSideRouter, originToBadgeLocal, orthRouter, pathBounds, pathToSvgD, perpendicularAnchor, pointInPolygon, pointsAttr, polygonBounds, polygonContainsInflated, quadraticPathStyle, rayPolygonIntersection, regularPolygonVertices, resolveBadgePosition, resolveCompositeRoot, resolveConnectorBadgePosition, resolveEasing, resolveThemed, roundedPathStyle, roundedPolygonOutline, samplePath, samplePathAt, scaleArc, scaleCircle, scaleEllipse, scalePath, scalePolygon, scaleRect, scaleRegularPolygon, scaleSpec, scaleStar, scaleTabbedRect, scheduleFlush, select, shallowEqual, shapeSpecToSvg, silhouettePortAnchor, smoothPathStyle, starVertices, stepRadialPathStyle, straightRouter, strokeBandOf, strokePaint, n as svgNum, tabbedRectBounds, tabbedRectFoldLine, tabbedRectGeometry, tabbedRectOutline, tabbedRectTabBox, tabbedRectTabWidth, tangentAt, textContent, trimPathEnds, verticesOfRegularPolygon, verticesOfStar };
6228
+ export { Behaviour, BehaviourRegistry, CANVAS_SOURCE, Camera, CanvasEventBus, CanvasThemeState, ColumnStore, CommandRegistry, DEFAULT_ENDPOINT_BADGE_GAP_PX, DEFAULT_POSITION_TRANSITION_MS, DefaultGestureArbiter, DirtyBatcher, EASING_NAMES, EventEmitter, HeadlessCameraBinding, HeadlessElementRenderer, HeadlessRenderer, HeadlessSurface, INHERIT, LOOP_CURVE_PRESETS, Layer, LayerData, LayerRegistry, Layout, LayoutRegistry, NODE_FLAG, SourceEmitter, SpecProjector, SpecStore, Tween, animatePositions, attrs, bezierPathStyle, boundaryAnchor, boundsOfArc, boundsOfCircle, boundsOfComposite, boundsOfCompositeRoot, boundsOfEllipse, boundsOfPath, boundsOfPolygon, boundsOfRect, boundsOfRegularPolygon, boundsOfSpec, boundsOfStar, bumpHorizontalPathStyle, bumpRadialPathStyle, bundlePathStyle, centerAnchor, collapsedSpec, collapsedTabbedRect, compositeRootOffset, connectorGeometryKey, connectorToSvg, containsArc, containsCircle, containsComposite, containsEllipse, containsPath, containsPolygon, containsRect, containsRegularPolygon, containsSpec, containsStar, containsTabbedRect, createActions, defaultCanvasView, defaultEqual, distanceToOutlineSq, distanceToPolylineSq, distanceToSegmentSq, easeInOutCubic, easeInOutSine, easeOutCubic, easeOutQuad, edgePortAnchor, erRouter, esc, fillPaint, fitSpecToContent, fitTabbedRectToContent, hasSilhouetteFill, hexToCss, isInherit, linear, loopCurvePathStyle, loopPolylinePathStyle, manhattanRouter, metroRouter, normalPathStyle, offsetPolygon, oneSideRouter, originToBadgeLocal, orthRouter, pathBounds, pathToSvgD, perpendicularAnchor, pointInPolygon, pointsAttr, polygonBounds, polygonContainsInflated, quadraticPathStyle, rayPolygonIntersection, regularPolygonVertices, resolveBadgePosition, resolveCompositeRoot, resolveConnectorBadgePosition, resolveEasing, resolveLabelScale, resolveThemed, roundedPathStyle, roundedPolygonOutline, samplePath, samplePathAt, scaleArc, scaleCircle, scaleEllipse, scalePath, scalePolygon, scaleRect, scaleRegularPolygon, scaleSpec, scaleStar, scaleTabbedRect, scheduleFlush, select, shallowEqual, shapeSpecToSvg, silhouettePortAnchor, smoothPathStyle, starVertices, stepRadialPathStyle, straightRouter, strokeBandOf, strokePaint, n as svgNum, tabbedRectBounds, tabbedRectFoldLine, tabbedRectGeometry, tabbedRectOutline, tabbedRectTabBox, tabbedRectTabWidth, tangentAt, textContent, trimPathEnds, verticesOfRegularPolygon, verticesOfStar };
5763
6229
  //# sourceMappingURL=index.js.map
5764
6230
  //# sourceMappingURL=index.js.map