@stocksharp/diagram 1.3.0 → 1.5.0

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.
Files changed (41) hide show
  1. package/README.md +84 -1
  2. package/dist/esm/canvas-renderer.js +178 -31
  3. package/dist/esm/canvas-renderer.js.map +1 -1
  4. package/dist/esm/color.js +110 -0
  5. package/dist/esm/color.js.map +1 -1
  6. package/dist/esm/core/document.js +11 -0
  7. package/dist/esm/core/document.js.map +1 -1
  8. package/dist/esm/core/model.js.map +1 -1
  9. package/dist/esm/diagram/stocksharp-diagram.js +23 -3
  10. package/dist/esm/diagram/stocksharp-diagram.js.map +1 -1
  11. package/dist/esm/embed.js +104 -20
  12. package/dist/esm/embed.js.map +1 -1
  13. package/dist/esm/index.js +1 -1
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/ssdiagram-headless.js +247 -26
  16. package/dist/ssdiagram-headless.js.map +2 -2
  17. package/dist/ssdiagram.js +352 -48
  18. package/dist/ssdiagram.js.map +3 -3
  19. package/dist/types/canvas-renderer.d.ts +26 -3
  20. package/dist/types/canvas-renderer.d.ts.map +1 -1
  21. package/dist/types/color.d.ts +9 -0
  22. package/dist/types/color.d.ts.map +1 -1
  23. package/dist/types/core/model.d.ts +7 -0
  24. package/dist/types/core/model.d.ts.map +1 -1
  25. package/dist/types/diagram/api.d.ts +6 -0
  26. package/dist/types/diagram/api.d.ts.map +1 -1
  27. package/dist/types/diagram/stocksharp-diagram.d.ts +11 -0
  28. package/dist/types/diagram/stocksharp-diagram.d.ts.map +1 -1
  29. package/dist/types/embed.d.ts +21 -0
  30. package/dist/types/embed.d.ts.map +1 -1
  31. package/dist/types/index.d.ts +2 -2
  32. package/dist/types/index.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/src/canvas-renderer.ts +182 -30
  35. package/src/color.ts +130 -0
  36. package/src/core/document.ts +12 -0
  37. package/src/core/model.ts +7 -0
  38. package/src/diagram/api.ts +6 -0
  39. package/src/diagram/stocksharp-diagram.ts +27 -3
  40. package/src/embed.ts +147 -29
  41. package/src/index.ts +2 -0
@@ -1,6 +1,6 @@
1
1
  import type { DrawSurface } from './draw-surface.js';
2
2
  import { SvgSurface } from './svg-surface.js';
3
- import { readableOutlineOn, readableTextOn } from './color.js';
3
+ import { cappedLightness, legibleOn, readableOutlineOn, readableTextOn, resolveCssVariables } from './color.js';
4
4
  // Internal dependency-free canvas renderer used by StockSharpDiagram.
5
5
  //
6
6
  // Dependency-free, pure 2D canvas. Demonstrates the hard parts: typed
@@ -60,6 +60,8 @@ export interface DiagramNodeInit {
60
60
  id?: string;
61
61
  typeId?: string;
62
62
  name: string;
63
+ /** Smaller second line under the name. */
64
+ subtitle?: string;
63
65
  description?: string;
64
66
  groupName?: string;
65
67
  color?: string;
@@ -90,6 +92,8 @@ export interface LinkInit {
90
92
  toPort: string;
91
93
  /** Solid unless the link is one that may not be there - see DiagramLinkStyle. */
92
94
  style?: DiagramLinkStyle;
95
+ /** Short text drawn at the middle of the link. */
96
+ label?: string;
93
97
  metadata?: JsonObject;
94
98
  }
95
99
 
@@ -102,7 +106,7 @@ export interface DiagramSnapshot {
102
106
  // Endpoints alone made the snapshot lossy: a save()/load() round-trip dropped every link's
103
107
  // identity, style and metadata, and the links carried in loadFinished / undoRequested /
104
108
  // redoRequested arrived with an empty id, so selectLink(payload.link.id) matched nothing.
105
- links: Array<Required<Pick<LinkInit, 'id' | 'from' | 'fromPort' | 'to' | 'toPort' | 'style'>> & Pick<LinkInit, 'metadata'>>;
109
+ links: Array<Required<Pick<LinkInit, 'id' | 'from' | 'fromPort' | 'to' | 'toPort' | 'style'>> & Pick<LinkInit, 'label' | 'metadata'>>;
106
110
  }
107
111
 
108
112
  export interface DiagramOptions {
@@ -113,6 +117,12 @@ export interface DiagramOptions {
113
117
  gridSnap?: boolean;
114
118
  /** Tint for a zone that names no colour of its own. */
115
119
  zoneColor?: string;
120
+ /**
121
+ * Leave page scrolling to the page: a plain wheel scrolls it and only Ctrl/Meta+wheel zooms, and a
122
+ * one-finger vertical swipe scrolls it on touch screens. Defaults to false, where the canvas keeps
123
+ * every wheel and touch gesture for itself.
124
+ */
125
+ pageScroll?: boolean;
116
126
  /** Positive world-space grid step. Defaults to 28. */
117
127
  gridSize?: number;
118
128
  /** Optional explicit socket-type → colour map; unknown types hash to a hue. */
@@ -360,6 +370,7 @@ export class NodeModel {
360
370
  id: string;
361
371
  typeId: string;
362
372
  name: string;
373
+ subtitle: string;
363
374
  description: string;
364
375
  groupName: string;
365
376
  color: string;
@@ -385,6 +396,7 @@ export class NodeModel {
385
396
  this.id = id;
386
397
  this.typeId = init.typeId ?? id;
387
398
  this.name = init.name;
399
+ this.subtitle = init.subtitle ?? '';
388
400
  this.description = init.description ?? '';
389
401
  this.groupName = init.groupName ?? 'Common';
390
402
  this.color = init.color ?? '#d7d7d7';
@@ -411,6 +423,7 @@ export class NodeModel {
411
423
  id: this.id,
412
424
  typeId: this.typeId,
413
425
  name: this.name,
426
+ ...(this.subtitle === '' ? {} : { subtitle: this.subtitle }),
414
427
  description: this.description,
415
428
  groupName: this.groupName,
416
429
  color: this.color,
@@ -444,6 +457,7 @@ export class LinkModel {
444
457
  id: string = '',
445
458
  metadata?: JsonObject,
446
459
  public style: DiagramLinkStyle = 'solid',
460
+ public label: string = '',
447
461
  ) {
448
462
  this.id = id;
449
463
  this.metadata = copyJsonObject(metadata);
@@ -458,6 +472,7 @@ export class LinkModel {
458
472
  to: this.to,
459
473
  toPort: this.toPort,
460
474
  style: this.style,
475
+ ...(this.label === '' ? {} : { label: this.label }),
461
476
  metadata: copyJsonObject(this.metadata),
462
477
  };
463
478
  }
@@ -479,6 +494,15 @@ const INTRO_MS = 520; // entrance animation duration
479
494
  const INTRO_RISE = 70; // px the scheme rises from below
480
495
  const ERROR_FLASH_MS = 1100;
481
496
  const ERROR_RED = '#f6465d';
497
+ const DEFAULT_NODE_COLOR = '#d7d7d7';
498
+ const DEFAULT_NODE_BORDER = '#8c8c8c';
499
+ const DEFAULT_ZONE_TINT = '#8a8f98';
500
+ const TITLE_FONT = '600 12px Segoe UI, Tahoma, sans-serif';
501
+ const SUBTITLE_FONT = '11px Segoe UI, Tahoma, sans-serif';
502
+ const SUBTITLE_MIN_H = 62; // body height that fits a name and a subtitle line
503
+ const LINK_LABEL_FONT = '600 10px Segoe UI, Tahoma, sans-serif';
504
+ const ZONE_CAPTION_TOP = 9; // caption offset inside the zone's top-left corner
505
+ const ZONE_CAPTION_H = 14;
482
506
  const ERROR_BACKGROUND = '#7d2632';
483
507
 
484
508
  const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
@@ -494,9 +518,7 @@ function hashHue(s: string): number {
494
518
  // wash out; a light theme passes a low ceiling to darken the links just enough to stay readable
495
519
  // while keeping each hue distinct. Non-hsl inputs are returned untouched.
496
520
  function clampLightness(color: string, maxL: number): string {
497
- const m = color.match(/^hsl\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)$/i);
498
- if (m === null) return color;
499
- return `hsl(${m[1]}, ${m[2]}%, ${Math.min(+m[3], maxL * 100)}%)`;
521
+ return cappedLightness(color, maxL);
500
522
  }
501
523
 
502
524
  function colorLuminance(color: string | undefined): number {
@@ -602,6 +624,10 @@ export class Diagram {
602
624
 
603
625
  private validator: LinkValidator | null = null;
604
626
  private handlers = new Map<EvName, Set<(p: never) => void>>();
627
+ private pageScroll: boolean;
628
+ // Computed style of the host, read at most once per frame: colours written as var(--token)
629
+ // resolve against it, so a frame drawn after a theme switch picks up the new values.
630
+ private hostStyle: CSSStyleDeclaration | null = null;
605
631
 
606
632
  constructor(opts: DiagramOptions) {
607
633
  this.opts = opts;
@@ -610,6 +636,7 @@ export class Diagram {
610
636
  if (opts.typeColors !== undefined) this.setTypeColorsInternal(opts.typeColors);
611
637
  this.host = opts.host;
612
638
  this.gridSnapEnabled = opts.gridSnap ?? false;
639
+ this.pageScroll = opts.pageScroll ?? false;
613
640
  this.gridSize = this.normalizeGridSize(opts.gridSize ?? DEFAULT_GRID_SIZE);
614
641
  this.history = new DiagramCommandHistory(() => {
615
642
  // The gated values, not the raw stack: setInteractionPermissions and setReadOnly
@@ -621,9 +648,9 @@ export class Diagram {
621
648
  this.canvas.style.display = 'block';
622
649
  this.canvas.tabIndex = 0; // focusable → key events
623
650
  this.canvas.style.outline = 'none';
624
- // Eat browser-native touch gestures (page scroll / pinch-zoom) so
625
- // fingers actually drive our pan/zoom on mobile instead of the page.
626
- this.canvas.style.touchAction = 'none';
651
+ // Eat browser-native touch gestures (page scroll / pinch-zoom) so fingers actually drive our
652
+ // pan/zoom on mobile instead of the page - unless the page asked to keep its scrolling.
653
+ this.applyTouchAction();
627
654
  // No OS text-selection on long-press (would pop the iOS magnifier
628
655
  // and select node/link captions instead of firing our menu).
629
656
  this.canvas.style.userSelect = 'none';
@@ -672,6 +699,17 @@ export class Diagram {
672
699
  this.gridSize = nextSize;
673
700
  this.scheduleDraw();
674
701
  }
702
+ /** See DiagramOptions.pageScroll. */
703
+ setPageScroll(enabled: boolean): void {
704
+ this.pageScroll = enabled;
705
+ this.applyTouchAction();
706
+ }
707
+ isPageScrollEnabled(): boolean { return this.pageScroll; }
708
+ // pan-y hands a vertical swipe to the browser, which scrolls the page; a horizontal one and a
709
+ // two-finger pinch still reach the canvas.
710
+ private applyTouchAction(): void {
711
+ this.canvas.style.touchAction = this.pageScroll ? 'pan-y' : 'none';
712
+ }
675
713
  getGridSnap(): { enabled: boolean; size: number } {
676
714
  return { enabled: this.gridSnapEnabled, size: this.gridSize };
677
715
  }
@@ -877,7 +915,7 @@ export class Diagram {
877
915
  this.emit('linkValidation', { fromNode: fn, from: fp, toNode: tn, to: tp, ...validation });
878
916
  if (!validation.allowed) return false;
879
917
  }
880
- const link = new LinkModel(init.from, init.fromPort, init.to, init.toPort, init.id ?? this.nextLinkId(), init.metadata, init.style ?? 'solid');
918
+ const link = new LinkModel(init.from, init.fromPort, init.to, init.toPort, init.id ?? this.nextLinkId(), init.metadata, init.style ?? 'solid', init.label ?? '');
881
919
  if (this.links.some((l) => l.id === link.id)) return false;
882
920
  this.links.splice(clamp(Math.trunc(index), 0, this.links.length), 0, link);
883
921
  this.emit('linkAdded', { link });
@@ -1164,10 +1202,11 @@ export class Diagram {
1164
1202
 
1165
1203
  updateNode(
1166
1204
  nodeId: string,
1167
- patch: Partial<Pick<DiagramNodeInit, 'name' | 'description' | 'color' | 'border' | 'message' | 'openAction'>>,
1205
+ patch: Partial<Pick<DiagramNodeInit, 'name' | 'subtitle' | 'description' | 'color' | 'border' | 'message' | 'openAction'>>,
1168
1206
  ): boolean {
1169
1207
  return this.updateNodeState(nodeId, 'update node', (node) => {
1170
1208
  if (patch.name !== undefined) node.name = patch.name;
1209
+ if (patch.subtitle !== undefined) node.subtitle = patch.subtitle;
1171
1210
  if (patch.description !== undefined) node.description = patch.description;
1172
1211
  if (patch.color !== undefined) node.color = patch.color;
1173
1212
  if (patch.border !== undefined) node.border = patch.border;
@@ -1213,6 +1252,7 @@ export class Diagram {
1213
1252
  const restored = new NodeModel(snapshot, nodeId);
1214
1253
  node.typeId = restored.typeId;
1215
1254
  node.name = restored.name;
1255
+ node.subtitle = restored.subtitle;
1216
1256
  node.description = restored.description;
1217
1257
  node.groupName = restored.groupName;
1218
1258
  node.color = restored.color;
@@ -1244,6 +1284,10 @@ export class Diagram {
1244
1284
  return true;
1245
1285
  }
1246
1286
  load(nodes: DiagramNodeInit[], links: LinkInit[]): void {
1287
+ this.loadModel(nodes, links, []);
1288
+ }
1289
+ // Zones are placed before the view is fitted, so the first frame frames them too.
1290
+ private loadModel(nodes: DiagramNodeInit[], links: LinkInit[], zones: readonly DiagramDocumentZone[]): void {
1247
1291
  this.clear();
1248
1292
  this.idSeq = 1;
1249
1293
  this.linkSeq = 1;
@@ -1278,9 +1322,10 @@ export class Diagram {
1278
1322
  if (this.links.some((existing) => existing.id === id)) {
1279
1323
  throw new Error(`ssdiagram: duplicate link id "${id}"`);
1280
1324
  }
1281
- const model = new LinkModel(link.from, link.fromPort, link.to, link.toPort, id, link.metadata, link.style ?? 'solid');
1325
+ const model = new LinkModel(link.from, link.fromPort, link.to, link.toPort, id, link.metadata, link.style ?? 'solid', link.label ?? '');
1282
1326
  if (!this.links.some((existing) => existing.key() === model.key())) this.links.push(model);
1283
1327
  }
1328
+ this.zones = zones.map((zone) => ({ ...zone, metadata: copyJsonObject(zone.metadata) }));
1284
1329
  for (const node of this.nodes) {
1285
1330
  if (node.loadError.length === 0) continue;
1286
1331
  const state = createDiagramNodeRuntimeState();
@@ -1303,6 +1348,7 @@ export class Diagram {
1303
1348
  to: l.to,
1304
1349
  toPort: l.toPort,
1305
1350
  style: l.style,
1351
+ ...(l.label === '' ? {} : { label: l.label }),
1306
1352
  metadata: copyJsonObject(l.metadata),
1307
1353
  })),
1308
1354
  };
@@ -1310,7 +1356,7 @@ export class Diagram {
1310
1356
 
1311
1357
  loadDocument(source: DiagramDocument | string): void {
1312
1358
  const document = parseDiagramDocument(source);
1313
- this.load(
1359
+ this.loadModel(
1314
1360
  document.nodes,
1315
1361
  document.links.map((link) => ({
1316
1362
  id: link.id,
@@ -1319,10 +1365,11 @@ export class Diagram {
1319
1365
  to: link.to.nodeId,
1320
1366
  toPort: link.to.portId,
1321
1367
  style: link.style,
1368
+ label: link.label,
1322
1369
  metadata: link.metadata,
1323
1370
  })),
1371
+ document.zones,
1324
1372
  );
1325
- this.zones = document.zones.map((zone) => ({ ...zone, metadata: copyJsonObject(zone.metadata) }));
1326
1373
  this.documentMetadata = copyJsonObject(document.metadata);
1327
1374
  }
1328
1375
 
@@ -1334,6 +1381,7 @@ export class Diagram {
1334
1381
  from: { nodeId: link.from, portId: link.fromPort },
1335
1382
  to: { nodeId: link.to, portId: link.toPort },
1336
1383
  style: link.style,
1384
+ label: link.label,
1337
1385
  metadata: link.metadata,
1338
1386
  })),
1339
1387
  zones: this.zones.map((zone) => ({ ...zone, metadata: copyJsonObject(zone.metadata) })),
@@ -1803,13 +1851,22 @@ export class Diagram {
1803
1851
  if (t.overviewViewportFill !== undefined) this.opts.overviewViewportFill = t.overviewViewportFill;
1804
1852
  this.scheduleDraw();
1805
1853
  }
1854
+ // Zones count: fitting or exporting only the nodes cut off the places they sit in, captions
1855
+ // included. A caption that is taller than its zone still has to fit.
1806
1856
  private graphBounds(): { minX: number; minY: number; maxX: number; maxY: number } | null {
1807
- if (this.nodes.length === 0) return null;
1857
+ if (this.nodes.length === 0 && this.zones.length === 0) return null;
1808
1858
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1809
1859
  for (const n of this.nodes) {
1810
1860
  minX = Math.min(minX, n.x); minY = Math.min(minY, n.y);
1811
1861
  maxX = Math.max(maxX, n.x + n.w); maxY = Math.max(maxY, n.y + n.h);
1812
1862
  }
1863
+ for (const zone of this.zones) {
1864
+ const bottom = zone.name.length > 0
1865
+ ? Math.max(zone.height, ZONE_CAPTION_TOP + ZONE_CAPTION_H)
1866
+ : zone.height;
1867
+ minX = Math.min(minX, zone.x - 1); minY = Math.min(minY, zone.y - 1);
1868
+ maxX = Math.max(maxX, zone.x + zone.width + 1); maxY = Math.max(maxY, zone.y + bottom + 1);
1869
+ }
1813
1870
  return { minX, minY, maxX, maxY };
1814
1871
  }
1815
1872
  resize(w: number, h: number): void {
@@ -1863,12 +1920,17 @@ export class Diagram {
1863
1920
  // ---- geometry ---------------------------------------------------
1864
1921
  private layoutNode(n: NodeModel): void {
1865
1922
  const ctx = this.ctx;
1866
- ctx.font = '600 12px Segoe UI, Tahoma, sans-serif';
1923
+ ctx.font = TITLE_FONT;
1867
1924
  const titleW = ctx.measureText(n.name).width;
1925
+ let subtitleW = 0;
1926
+ if (n.subtitle.length > 0) {
1927
+ ctx.font = SUBTITLE_FONT;
1928
+ subtitleW = ctx.measureText(n.subtitle).width;
1929
+ }
1868
1930
  const rows = Math.max(n.inPorts.length, n.outPorts.length, 1);
1869
- // Node sizing: min 170 wide, height grows by rows.
1870
- n.w = Math.max(170, Math.ceil(titleW) + 28);
1871
- n.h = Math.max(48, rows * PORT_ROW_H + 16);
1931
+ // Node sizing: min 170 wide, height grows by rows; a subtitle adds a second text line.
1932
+ n.w = Math.max(170, Math.ceil(titleW) + 28, Math.ceil(subtitleW) + 28);
1933
+ n.h = Math.max(n.subtitle.length > 0 ? SUBTITLE_MIN_H : 48, rows * PORT_ROW_H + 16);
1872
1934
  // Each side's port stack is vertically centred; the socket
1873
1935
  // square sits OUTSIDE the body (its inner edge flush with the
1874
1936
  // node border).
@@ -1913,6 +1975,16 @@ export class Diagram {
1913
1975
  return this.portFeed.get(p) ?? p.type;
1914
1976
  }
1915
1977
 
1978
+ /// A type's colour as a wire.
1979
+ ///
1980
+ /// The same colour a socket of that type is filled with, moved into the band the canvas
1981
+ /// leaves room for. A socket can afford the host's exact colour because it is a filled
1982
+ /// square with an outline; a wire is a thin line with nothing behind it, and one drawn in
1983
+ /// #000000 on a dark canvas is not there at all.
1984
+ private linkColor(type: string): string {
1985
+ return legibleOn(this.portColor(type), this.opts.background ?? '#1b1b1f');
1986
+ }
1987
+
1916
1988
  private portColor(type: string): string {
1917
1989
  const maxL = this.opts.linkMaxLightness;
1918
1990
  const light = maxL !== undefined && maxL < 0.5;
@@ -2233,6 +2305,7 @@ export class Diagram {
2233
2305
  // The clipboard is built from saveDocument(), so it carries the style;
2234
2306
  // rebuilding without it silently turned every pasted dashed link solid.
2235
2307
  style: l.style,
2308
+ label: l.label,
2236
2309
  metadata: l.metadata,
2237
2310
  });
2238
2311
  }
@@ -2660,6 +2733,8 @@ export class Diagram {
2660
2733
  this.listen(window, 'pointerup', finish);
2661
2734
  this.listen(window, 'pointercancel', finish);
2662
2735
  this.listen(this.canvas, 'wheel', (e) => {
2736
+ // Ctrl+wheel is also what a trackpad pinch arrives as, so zoom stays one gesture away.
2737
+ if (this.pageScroll && !e.ctrlKey && !e.metaKey) return;
2663
2738
  e.preventDefault();
2664
2739
  const [sx, sy] = localXY(e);
2665
2740
  const [wx, wy] = this.toWorld(sx, sy);
@@ -2800,6 +2875,7 @@ export class Diagram {
2800
2875
  }
2801
2876
  private draw(options: DiagramRenderOptions = SCREEN_RENDER_OPTIONS): void {
2802
2877
  const ctx = this.ctx;
2878
+ this.hostStyle = null;
2803
2879
  ctx.clearRect(0, 0, this.width, this.height);
2804
2880
  const background = this.opts.background ?? '#1b1b1f';
2805
2881
  ctx.fillStyle = background;
@@ -2829,6 +2905,7 @@ export class Diagram {
2829
2905
  // Links next. Each link jumps over the verticals of the links
2830
2906
  // drawn before it (deterministic bridge — Link.JumpOver parity).
2831
2907
  const prior: Seg[] = []; // segments of links already drawn
2908
+ const labels: Array<{ pts: number[][]; text: string; color: string }> = [];
2832
2909
  const hoveredNode = this.hoverPort?.node ?? this.hoverNode;
2833
2910
  for (const l of this.links) {
2834
2911
  const a = this.endpoint(l, 'from');
@@ -2836,7 +2913,7 @@ export class Diagram {
2836
2913
  if (a === null || b === null) continue;
2837
2914
  const fp = this.nodes.find((n) => n.id === l.from)?.outPorts.find((p) => p.id === l.fromPort);
2838
2915
  const baseColor = (this.opts.typedLinkColors ?? false) && fp !== undefined
2839
- ? this.portColor(fp.type)
2916
+ ? this.linkColor(fp.type)
2840
2917
  : this.portColor('');
2841
2918
  const state = options.selection && l === this.selectedLink
2842
2919
  ? 'sel'
@@ -2849,6 +2926,7 @@ export class Diagram {
2849
2926
  const pts = this.routeLink(a, b, new Set([l.from, l.to]));
2850
2927
  this.strokeRoute(pts, color, width, prior, l.style);
2851
2928
  this.drawArrow(pts, color);
2929
+ if (l.label.length > 0) labels.push({ pts, text: l.label, color });
2852
2930
  for (let k = 1; k < pts.length; k += 1) {
2853
2931
  const [x1, y1] = pts[k - 1];
2854
2932
  const [x2, y2] = pts[k];
@@ -2856,6 +2934,8 @@ export class Diagram {
2856
2934
  else if (y1 === y2 && x1 !== x2) prior.push({ h: true, c: y1, a: Math.min(x1, x2), b: Math.max(x1, x2) });
2857
2935
  }
2858
2936
  }
2937
+ // After every wire, so no later wire runs across a label; before the nodes, which stay on top.
2938
+ for (const label of labels) this.drawLinkLabel(label.pts, label.text, label.color, background);
2859
2939
  if (options.transient && (this.linking !== null || this.relinking !== null)) this.drawPendingLink();
2860
2940
  this.portFeed = this.feedTypes();
2861
2941
  for (const n of this.nodes) this.drawNode(n, options.selection && this.selectedNodes.has(n), options);
@@ -3002,8 +3082,9 @@ export class Diagram {
3002
3082
 
3003
3083
  const ctx = this.ctx;
3004
3084
 
3085
+ const defaultTint = this.resolveColor(this.opts.zoneColor ?? DEFAULT_ZONE_TINT, DEFAULT_ZONE_TINT);
3005
3086
  for (const zone of this.zones) {
3006
- const tint = zone.color.length > 0 ? zone.color : (this.opts.zoneColor ?? '#8a8f98');
3087
+ const tint = zone.color.length > 0 ? this.resolveColor(zone.color, defaultTint) : defaultTint;
3007
3088
  ctx.save();
3008
3089
  roundRect(ctx, zone.x, zone.y, zone.width, zone.height, 10);
3009
3090
  ctx.globalAlpha = 0.12;
@@ -3021,12 +3102,12 @@ export class Diagram {
3021
3102
  ctx.save();
3022
3103
  ctx.globalAlpha = 0.75;
3023
3104
  ctx.fillStyle = tint;
3024
- ctx.font = '600 12px Segoe UI, Tahoma, sans-serif';
3105
+ ctx.font = TITLE_FONT;
3025
3106
  ctx.textAlign = 'left';
3026
3107
  ctx.textBaseline = 'top';
3027
3108
  // Inside the top-left corner: a caption outside the box would collide with whatever
3028
3109
  // sits above it, and the corner is the one spot a rectangle always has to spare.
3029
- ctx.fillText(zone.name, zone.x + 12, zone.y + 9, Math.max(0, zone.width - 24));
3110
+ ctx.fillText(zone.name, zone.x + 12, zone.y + ZONE_CAPTION_TOP, Math.max(0, zone.width - 24));
3030
3111
  ctx.restore();
3031
3112
  }
3032
3113
  }
@@ -3062,11 +3143,12 @@ export class Diagram {
3062
3143
  const runtime = options.runtime ? getJsonKey(this.runtimeState.nodes, n.id) : undefined;
3063
3144
  const active = options.runtime
3064
3145
  && (this.runtimeState.activeNodeId === n.id || runtime?.active === true);
3146
+ const fill = this.resolveColor(n.color, DEFAULT_NODE_COLOR);
3065
3147
  roundRect(ctx, n.x, n.y, n.w, n.h, 6);
3066
- ctx.fillStyle = hasLoadError ? ERROR_BACKGROUND : active ? '#ffd1dc' : n.color;
3148
+ ctx.fillStyle = hasLoadError ? ERROR_BACKGROUND : active ? '#ffd1dc' : fill;
3067
3149
  ctx.fill();
3068
3150
  ctx.lineWidth = selected ? 2 : 1.5;
3069
- ctx.strokeStyle = selected ? this.selectionColor() : n.border;
3151
+ ctx.strokeStyle = selected ? this.selectionColor() : this.resolveColor(n.border, DEFAULT_NODE_BORDER);
3070
3152
  ctx.stroke();
3071
3153
  if (hasLoadError || hasRuntimeError) {
3072
3154
  let alpha = 1;
@@ -3099,13 +3181,25 @@ export class Diagram {
3099
3181
  // takes its colour from the fill it sits on: that fill comes from the
3100
3182
  // scheme, so a node may well be darker than the title used to assume.
3101
3183
  const titleShift = n.icon ? iconW + 4 : 0;
3184
+ const textX = n.x + titleShift + (n.w - titleShift) / 2;
3185
+ const textWidth = n.w - titleShift - 14;
3102
3186
  ctx.fillStyle = hasLoadError
3103
3187
  ? '#ffffff'
3104
- : readableTextOn(active ? '#ffd1dc' : n.color);
3105
- ctx.font = '600 12px Segoe UI, Tahoma, sans-serif';
3188
+ : readableTextOn(active ? '#ffd1dc' : fill);
3189
+ ctx.font = TITLE_FONT;
3106
3190
  ctx.textAlign = 'center';
3107
3191
  ctx.textBaseline = 'middle';
3108
- ctx.fillText(n.name, n.x + titleShift + (n.w - titleShift) / 2, n.y + n.h / 2, n.w - titleShift - 14);
3192
+ if (n.subtitle.length === 0) {
3193
+ ctx.fillText(n.name, textX, n.y + n.h / 2, textWidth);
3194
+ } else {
3195
+ // Two lines centred as a pair: the name above, the subtitle smaller and muted below.
3196
+ ctx.fillText(n.name, textX, n.y + n.h / 2 - 8, textWidth);
3197
+ ctx.save();
3198
+ ctx.globalAlpha *= 0.72;
3199
+ ctx.font = SUBTITLE_FONT;
3200
+ ctx.fillText(n.subtitle, textX, n.y + n.h / 2 + 9, textWidth);
3201
+ ctx.restore();
3202
+ }
3109
3203
  for (const p of n.inPorts) this.drawPort(n, p, options);
3110
3204
  for (const p of n.outPorts) this.drawPort(n, p, options);
3111
3205
  }
@@ -3235,6 +3329,45 @@ export class Diagram {
3235
3329
  ctx.fill();
3236
3330
  ctx.restore();
3237
3331
  }
3332
+ // A plate of the canvas colour under the text, edged in the wire's colour: the label reads the same
3333
+ // whatever the wire crosses, and still says which wire it belongs to.
3334
+ private drawLinkLabel(pts: number[][], text: string, color: string, background: string): void {
3335
+ const [x, y] = pathMidpoint(pts);
3336
+ const ctx = this.ctx;
3337
+ ctx.save();
3338
+ ctx.font = LINK_LABEL_FONT;
3339
+ const w = Math.ceil(ctx.measureText(text).width) + 12;
3340
+ const h = 16;
3341
+ roundRect(ctx, x - w / 2, y - h / 2, w, h, h / 2);
3342
+ ctx.fillStyle = background;
3343
+ ctx.fill();
3344
+ ctx.lineWidth = 1;
3345
+ ctx.strokeStyle = color;
3346
+ ctx.stroke();
3347
+ ctx.fillStyle = readableTextOn(background);
3348
+ ctx.textAlign = 'center';
3349
+ ctx.textBaseline = 'middle';
3350
+ ctx.fillText(text, x, y);
3351
+ ctx.restore();
3352
+ }
3353
+ // Scheme colours may name a custom property of the page, var(--token), which a canvas cannot
3354
+ // paint. They resolve against the host element; one that resolves to nothing and has no
3355
+ // fallback of its own gets the renderer's default for that slot.
3356
+ private resolveColor(value: string, fallback: string): string {
3357
+ if (!value.includes('var(')) return value;
3358
+ return resolveCssVariables(value, (name) => this.hostProperty(name)) ?? fallback;
3359
+ }
3360
+ private hostProperty(name: string): string {
3361
+ if (this.hostStyle === null) {
3362
+ if (typeof getComputedStyle !== 'function') return '';
3363
+ try {
3364
+ this.hostStyle = getComputedStyle(this.host);
3365
+ } catch {
3366
+ return '';
3367
+ }
3368
+ }
3369
+ return this.hostStyle.getPropertyValue(name);
3370
+ }
3238
3371
  private drawSelectedLinkEndpoints(): void {
3239
3372
  if (this.selectedLink === null) return;
3240
3373
  const ctx = this.ctx;
@@ -3294,7 +3427,7 @@ export class Diagram {
3294
3427
  }
3295
3428
  if (snapped !== null) excludedNodes.add(snapped.node.id);
3296
3429
  const points = this.routeLink(a, b, excludedNodes);
3297
- ctx.strokeStyle = this.portColor(colorType);
3430
+ ctx.strokeStyle = this.linkColor(colorType);
3298
3431
  if (snapped !== null) { ctx.setLineDash([]); ctx.lineWidth = 2.6; }
3299
3432
  else { ctx.setLineDash([5, 4]); ctx.lineWidth = 2; }
3300
3433
  ctx.beginPath();
@@ -3350,9 +3483,9 @@ export class Diagram {
3350
3483
  ctx.stroke();
3351
3484
  ctx.clip();
3352
3485
  for (const n of this.nodes) {
3353
- ctx.fillStyle = n.color;
3486
+ ctx.fillStyle = this.resolveColor(n.color, DEFAULT_NODE_COLOR);
3354
3487
  ctx.fillRect(mx(n.x), my(n.y), Math.max(2, n.w * s), Math.max(2, n.h * s));
3355
- ctx.strokeStyle = n.border;
3488
+ ctx.strokeStyle = this.resolveColor(n.border, DEFAULT_NODE_BORDER);
3356
3489
  ctx.lineWidth = 1;
3357
3490
  ctx.strokeRect(mx(n.x), my(n.y), Math.max(2, n.w * s), Math.max(2, n.h * s));
3358
3491
  }
@@ -3400,6 +3533,25 @@ function roundRect(ctx: DrawSurface, x: number, y: number, w: number, h: number,
3400
3533
  // a 3-segment mid-X elbow. Backward/too-close: a 5-segment detour that
3401
3534
  // leaves the source rightward and re-enters the target from the left
3402
3535
  // (AvoidsNodes-style, never a diagonal).
3536
+ /** The point halfway along a polyline, measured by length rather than by vertex count. */
3537
+ function pathMidpoint(pts: number[][]): [number, number] {
3538
+ let total = 0;
3539
+ for (let i = 1; i < pts.length; i += 1) total += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
3540
+ let remaining = total / 2;
3541
+ for (let i = 1; i < pts.length; i += 1) {
3542
+ const [x1, y1] = pts[i - 1];
3543
+ const [x2, y2] = pts[i];
3544
+ const length = Math.hypot(x2 - x1, y2 - y1);
3545
+ if (length > 0 && remaining <= length) {
3546
+ const t = remaining / length;
3547
+ return [x1 + (x2 - x1) * t, y1 + (y2 - y1) * t];
3548
+ }
3549
+ remaining -= length;
3550
+ }
3551
+ const last = pts[pts.length - 1];
3552
+ return [last[0], last[1]];
3553
+ }
3554
+
3403
3555
  function route(a: [number, number], b: [number, number]): number[][] {
3404
3556
  const [ax, ay] = a;
3405
3557
  const [bx, by] = b;
package/src/color.ts CHANGED
@@ -149,3 +149,133 @@ export function readableOutlineOn(surface: string): string {
149
149
  ? LIGHT_OUTLINE
150
150
  : DARK_OUTLINE;
151
151
  }
152
+
153
+ /// A colour's hue, saturation and lightness, or null when it cannot be read.
154
+ function toHsl(color: string): [number, number, number] | null {
155
+ const hsl = color.trim().match(/^hsl\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)$/i);
156
+ if (hsl !== null)
157
+ return [+hsl[1], +hsl[2] / 100, +hsl[3] / 100];
158
+
159
+ const rgb = parseRgb(color);
160
+ if (rgb === null)
161
+ return null;
162
+
163
+ const [r, g, b] = rgb.map((channel) => channel / 255);
164
+ const max = Math.max(r, g, b);
165
+ const min = Math.min(r, g, b);
166
+ const lightness = (max + min) / 2;
167
+
168
+ if (max === min)
169
+ return [0, 0, lightness];
170
+
171
+ const span = max - min;
172
+ const saturation = lightness > 0.5 ? span / (2 - max - min) : span / (max + min);
173
+ const hue = max === r
174
+ ? ((g - b) / span + (g < b ? 6 : 0))
175
+ : max === g
176
+ ? (b - r) / span + 2
177
+ : (r - g) / span + 4;
178
+
179
+ return [hue * 60, saturation, lightness];
180
+ }
181
+
182
+ /// Lightest a colour may be drawn on a light canvas, and darkest on a dark one. Wide enough
183
+ /// that a hue is still itself, narrow enough that neither end of the palette disappears.
184
+ const DARK_CANVAS_FLOOR = 0.42;
185
+ const LIGHT_CANVAS_CEILING = 0.45;
186
+
187
+ /// The same colour, moved into the band the canvas leaves room for.
188
+ ///
189
+ /// A socket type's colour belongs to the host and spans the whole range -- StockSharp sends
190
+ /// #000000 for Any and near-white for Side. As a socket that is fine: it is a filled square
191
+ /// with an outline. As a wire it is a thin line with nothing behind it, so a colour at the
192
+ /// same end of the range as the canvas cannot be seen at all. Only the lightness moves; the
193
+ /// hue and saturation are the host's answer to which type this is, and are left alone.
194
+ ///
195
+ /// A colour that already sits in the band is returned exactly as it came, and one that cannot
196
+ /// be read is passed through: guessing at it would be worse than drawing what was asked for.
197
+ export function legibleOn(color: string, background: string): string {
198
+ const hsl = toHsl(color);
199
+ if (hsl === null)
200
+ return color;
201
+
202
+ const canvas = relativeLuminance(background);
203
+ const [hue, saturation, lightness] = hsl;
204
+ const moved = canvas < 0
205
+ ? lightness
206
+ : canvas > 0.18
207
+ ? Math.min(lightness, LIGHT_CANVAS_CEILING)
208
+ : Math.max(lightness, DARK_CANVAS_FLOOR);
209
+
210
+ if (moved === lightness && /^hsl/i.test(color.trim()))
211
+ return color;
212
+
213
+ return `hsl(${Math.round(hue * 10) / 10}, ${Math.round(saturation * 1000) / 10}%, ${Math.round(moved * 1000) / 10}%)`;
214
+ }
215
+
216
+ /// The same colour with its lightness capped at `maxLightness` (0..1), hue and saturation kept.
217
+ ///
218
+ /// Any colour, not only one already written as hsl(): a host's palette arrives as hex, and a
219
+ /// ceiling that only understood one notation left exactly those colours uncapped -- so a light
220
+ /// theme darkened the hues the control invents and left the ones it was given.
221
+ ///
222
+ /// A colour that cannot be read is returned untouched.
223
+ export function cappedLightness(color: string, maxLightness: number): string {
224
+ const hsl = toHsl(color);
225
+ if (hsl === null)
226
+ return color;
227
+
228
+ const [hue, saturation, lightness] = hsl;
229
+ if (lightness <= maxLightness)
230
+ return color;
231
+
232
+ return `hsl(${Math.round(hue * 10) / 10}, ${Math.round(saturation * 1000) / 10}%, ${Math.round(maxLightness * 1000) / 10}%)`;
233
+ }
234
+
235
+ /**
236
+ * Replaces every var(--name) or var(--name, fallback) in a CSS value with what `lookup` returns for the
237
+ * name, or with the fallback when the name is unset. Nested references resolve too, up to a fixed depth
238
+ * that also stops a cycle. Null when a reference resolves to nothing and names no fallback: the caller
239
+ * knows which default suits the slot, this does not.
240
+ */
241
+ export function resolveCssVariables(value: string, lookup: (name: string) => string): string | null {
242
+ return resolveAt(value, lookup, 0);
243
+ }
244
+
245
+ function resolveAt(value: string, lookup: (name: string) => string, depth: number): string | null {
246
+ const start = value.indexOf('var(');
247
+ if (start < 0)
248
+ return value;
249
+ if (depth > 8)
250
+ return null;
251
+
252
+ let level = 0;
253
+ let end = -1;
254
+ for (let i = start + 3; i < value.length; i += 1) {
255
+ if (value[i] === '(')
256
+ level += 1;
257
+ else if (value[i] === ')' && --level === 0) {
258
+ end = i;
259
+ break;
260
+ }
261
+ }
262
+ if (end < 0)
263
+ return null;
264
+
265
+ const inner = value.slice(start + 4, end);
266
+ const comma = inner.indexOf(',');
267
+ const name = (comma < 0 ? inner : inner.slice(0, comma)).trim();
268
+ const fallback = comma < 0 ? '' : inner.slice(comma + 1).trim();
269
+
270
+ let replacement = name.startsWith('--') ? lookup(name).trim() : '';
271
+ if (replacement === '')
272
+ replacement = fallback;
273
+ if (replacement === '')
274
+ return null;
275
+
276
+ const resolved = resolveAt(replacement, lookup, depth + 1);
277
+ const rest = resolveAt(value.slice(end + 1), lookup, depth);
278
+ if (resolved === null || rest === null)
279
+ return null;
280
+ return value.slice(0, start) + resolved + rest;
281
+ }