@knowvah/dot-engine 2.12.3 → 2.12.4

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 (80) hide show
  1. package/dist/api.js +12 -2
  2. package/dist/api.js.map +2 -2
  3. package/dist/common/clust-map.d.ts +16 -0
  4. package/dist/common/clust-map.d.ts.map +1 -0
  5. package/dist/common/htmltable-emit.d.ts +9 -6
  6. package/dist/common/htmltable-emit.d.ts.map +1 -1
  7. package/dist/common/layers.d.ts +9 -0
  8. package/dist/common/layers.d.ts.map +1 -1
  9. package/dist/common/poly-gencode.d.ts.map +1 -1
  10. package/dist/common/xlabels-place.d.ts.map +1 -1
  11. package/dist/gvc/anchor.d.ts +17 -19
  12. package/dist/gvc/anchor.d.ts.map +1 -1
  13. package/dist/gvc/device-cluster.d.ts +9 -0
  14. package/dist/gvc/device-cluster.d.ts.map +1 -1
  15. package/dist/gvc/device.d.ts +2 -1
  16. package/dist/gvc/device.d.ts.map +1 -1
  17. package/dist/gvc/emit-walk.d.ts +7 -0
  18. package/dist/gvc/emit-walk.d.ts.map +1 -1
  19. package/dist/gvc/job.d.ts +13 -6
  20. package/dist/gvc/job.d.ts.map +1 -1
  21. package/dist/gvc/viewport.d.ts +14 -0
  22. package/dist/gvc/viewport.d.ts.map +1 -1
  23. package/dist/index.js +557 -469
  24. package/dist/index.js.map +4 -4
  25. package/dist/layout/dot/compound.d.ts +0 -4
  26. package/dist/layout/dot/compound.d.ts.map +1 -1
  27. package/dist/layout/fdp/cluster-edges.d.ts.map +1 -1
  28. package/dist/model/cgraph-ops.d.ts +7 -0
  29. package/dist/model/cgraph-ops.d.ts.map +1 -1
  30. package/dist/model/graph.d.ts +12 -2
  31. package/dist/model/graph.d.ts.map +1 -1
  32. package/dist/parser/builder.d.ts +11 -10
  33. package/dist/parser/builder.d.ts.map +1 -1
  34. package/dist/parser/graph-attr-syms.d.ts +35 -0
  35. package/dist/parser/graph-attr-syms.d.ts.map +1 -0
  36. package/dist/render/dot/agwrite.d.ts +6 -7
  37. package/dist/render/dot/agwrite.d.ts.map +1 -1
  38. package/dist/render/dot/attrs.d.ts +5 -0
  39. package/dist/render/dot/attrs.d.ts.map +1 -1
  40. package/dist/render/json-cluster-edge.d.ts +3 -2
  41. package/dist/render/json-cluster-edge.d.ts.map +1 -1
  42. package/dist/render/json.d.ts +7 -1
  43. package/dist/render/json.d.ts.map +1 -1
  44. package/dist/render/map.d.ts +14 -10
  45. package/dist/render/map.d.ts.map +1 -1
  46. package/dist/render/svg-graph.d.ts.map +1 -1
  47. package/dist/render/svg-id.d.ts +9 -0
  48. package/dist/render/svg-id.d.ts.map +1 -1
  49. package/dist/render.js +643 -555
  50. package/dist/render.js.map +4 -4
  51. package/dist/util/printf-round.d.ts +8 -0
  52. package/dist/util/printf-round.d.ts.map +1 -1
  53. package/package.json +1 -1
  54. package/src/common/clust-map.ts +58 -0
  55. package/src/common/htmltable-emit.ts +87 -7
  56. package/src/common/layers.ts +25 -4
  57. package/src/common/poly-gencode.ts +3 -11
  58. package/src/common/xlabels-place.ts +22 -4
  59. package/src/gvc/anchor.ts +18 -30
  60. package/src/gvc/device-cluster.ts +16 -0
  61. package/src/gvc/device.ts +20 -20
  62. package/src/gvc/emit-walk.ts +11 -1
  63. package/src/gvc/job.ts +17 -9
  64. package/src/gvc/viewport.ts +27 -6
  65. package/src/layout/dot/compound.ts +1 -21
  66. package/src/layout/fdp/cluster-edges.ts +2 -23
  67. package/src/model/cgraph-ops.ts +12 -0
  68. package/src/model/graph.ts +13 -2
  69. package/src/parser/builder.ts +67 -100
  70. package/src/parser/graph-attr-syms.ts +62 -0
  71. package/src/render/dot/agwrite.ts +12 -12
  72. package/src/render/dot/attrs.ts +6 -2
  73. package/src/render/json-cluster-edge.ts +8 -4
  74. package/src/render/json.ts +15 -8
  75. package/src/render/map.ts +49 -58
  76. package/src/render/svg-cluster.ts +3 -3
  77. package/src/render/svg-graph.ts +1 -3
  78. package/src/render/svg-helpers.ts +6 -6
  79. package/src/render/svg-id.ts +23 -5
  80. package/src/util/printf-round.ts +11 -0
package/src/gvc/job.ts CHANGED
@@ -309,20 +309,28 @@ export class RenderJob {
309
309
  /** GD_fontnames of the root graph — selects which PostScript-alias fields the
310
310
  * SVG emitter uses. @see plugin/core/gvrender_core_svg.c:464 */
311
311
  fontnames: FontnameKind = FontnameKind.NativeFonts;
312
- /** Root graph's `id` attribute (GD_drawing(root)->id), '' if unset. Used as
313
- * the `<gid>_` prefix for non-root object ids. @see lib/common/emit.c:getObjId */
312
+ /** GD_drawing(root)->id: the root graph's `id`, substituted, '' if unset. Set
313
+ * by render() for every renderer (drawingIdOf); the `<gid>_` prefix of
314
+ * non-root object ids. @see lib/common/emit.c:getObjId */
314
315
  drawingId: string = '';
315
316
 
316
317
  /**
317
- * Resolve an object's SVG id like C's getObjId (steps after layerPagePrefix):
318
- * a non-empty DOT `id` attr wins verbatim; otherwise non-root objects are
319
- * prefixed with `<drawingId>_` when the root graph has an id.
320
- * @see lib/common/emit.c:getObjId:209
318
+ * Resolve an object's id like C's getObjId. The layer half of
319
+ * layerPagePrefix comes first (`<layer>_` after the first layer), ahead of
320
+ * every other step. Then a non-empty DOT `id` attr wins verbatim; otherwise
321
+ * non-root objects are prefixed with `<drawingId>_` when the root graph has
322
+ * an id. The root's id gets the same prefix in emit_page (NotFirstPage).
323
+ * The page half (`page<x>,<y>_`) is left out: only ps and quartz page, and
324
+ * neither prints an id.
325
+ * @see lib/common/emit.c:getObjId
326
+ * @see lib/common/emit.c:layerPagePrefix
327
+ * @see lib/common/emit.c:emit_page
321
328
  */
322
329
  objId(idAttr: string | undefined, defaultId: string, isRoot = false): string {
323
- if (idAttr !== undefined && idAttr.length > 0) return idAttr;
324
- if (!isRoot && this.drawingId.length > 0) return this.drawingId + '_' + defaultId;
325
- return defaultId;
330
+ const pfx = this.idLayerPrefix();
331
+ if (idAttr !== undefined && idAttr.length > 0) return pfx + idAttr;
332
+ if (!isRoot && this.drawingId.length > 0) return pfx + this.drawingId + '_' + defaultId;
333
+ return pfx + defaultId;
326
334
  }
327
335
 
328
336
  /** Active renderer plugin; set by render() before walkNodes. */
@@ -190,6 +190,22 @@ export function initJobViewportZoom(bb: Box, size: DrawingSize | null, pad: Poin
190
190
  * @see lib/common/emit.c:init_job_viewport, init_job_pagination, setup_page
191
191
  */
192
192
  export function setupPageClip(bb: Box, size: DrawingSize | null, pad: Point, z: number): Box {
193
+ const focus = { x: 0.5 * (bb.ll.x + bb.ur.x), y: 0.5 * (bb.ll.y + bb.ur.y) };
194
+ const pageSize = setupPageSize(bb, size, pad, z);
195
+ const ll = {
196
+ x: focus.x + pageSize.x * (0 - 1 / 2.0),
197
+ y: focus.y + pageSize.y * (0 - 1 / 2.0),
198
+ };
199
+ return { ll, ur: { x: ll.x + pageSize.x, y: ll.y + pageSize.y } };
200
+ }
201
+
202
+ /**
203
+ * job->pageSize, the size of one page in graph units: imageSize / zoom, where
204
+ * imageSize = view = Z * sz and sz is the padded bb's extent (see
205
+ * setupPageClip). Not always sz: (Z * sz) / Z can round one ulp away from it.
206
+ * @see lib/common/emit.c:init_job_viewport, init_job_pagination
207
+ */
208
+ export function setupPageSize(bb: Box, size: DrawingSize | null, pad: Point, z: number): Point {
193
209
  const jbLL = { x: bb.ll.x - pad.x, y: bb.ll.y - pad.y };
194
210
  const jbUR = { x: bb.ur.x + pad.x, y: bb.ur.y + pad.y };
195
211
  const sz = { x: jbUR.x - jbLL.x, y: jbUR.y - jbLL.y };
@@ -197,11 +213,16 @@ export function setupPageClip(bb: Box, size: DrawingSize | null, pad: Point, z:
197
213
  if (sz.x <= 0.001) sz.x = size.x;
198
214
  if (sz.y <= 0.001) sz.y = size.y;
199
215
  }
200
- const focus = { x: 0.5 * (bb.ll.x + bb.ur.x), y: 0.5 * (bb.ll.y + bb.ur.y) };
201
- const pageSize = { x: (z * sz.x) / z, y: (z * sz.y) / z };
202
- const ll = {
203
- x: focus.x + pageSize.x * (0 - 1 / 2.0),
204
- y: focus.y + pageSize.y * (0 - 1 / 2.0),
205
- };
216
+ return { x: (z * sz.x) / z, y: (z * sz.y) / z };
217
+ }
218
+
219
+ /**
220
+ * job->pageBox for the single page (pagesArrayElem 0): LL = elem * pageSize -
221
+ * pad, UR = LL + pageSize. Its origin is -pad whatever the bb's is, and it is
222
+ * derived apart from job->clip, so the two can differ in their last bits.
223
+ * @see lib/common/emit.c:setup_page (1515-1518)
224
+ */
225
+ export function setupPageBox(pageSize: Point, pad: Point): Box {
226
+ const ll = { x: 0 * pageSize.x - pad.x, y: 0 * pageSize.y - pad.y };
206
227
  return { ll, ur: { x: ll.x + pageSize.x, y: ll.y + pageSize.y } };
207
228
  }
@@ -15,6 +15,7 @@ import {
15
15
  import { arrowEndClip, tailArrowEndClip, arrowClipLength, distFused } from './edge-route-clip.js';
16
16
  import { arrowDrawOpsForEnd, edgeArrowName, edgeArrowsize } from './edge-route-arrow.js';
17
17
  import { edgePenwidthAttr, edgeRenderPenwidth } from './edge-route-helpers.js';
18
+ import { mkClustMap } from '../../common/clust-map.js';
18
19
 
19
20
  // Re-export geometry helpers so existing callers (tests) import from one place.
20
21
  export {
@@ -24,27 +25,6 @@ export {
24
25
  tryLeftSide, tryRightSide, tryBottomSide, tryTopSide, boxIntersectf,
25
26
  } from './compound-clip.js';
26
27
 
27
- // ---------------------------------------------------------------------------
28
- // Cluster map
29
- // ---------------------------------------------------------------------------
30
-
31
- /** Recursively populate name→cluster map. @see lib/common/utils.c:fillMap */
32
- export function fillClustMap(g: Graph, map: Map<string, Graph>): void {
33
- const nc = g.info.n_cluster ?? 0;
34
- for (let c = 1; c <= nc; c++) {
35
- const cl = g.info.clust![c - 1];
36
- if (!map.has(cl.name)) map.set(cl.name, cl);
37
- fillClustMap(cl, map);
38
- }
39
- }
40
-
41
- /** Build a name→cluster map for all clusters reachable from g. @see lib/common/utils.c:mkClustMap */
42
- export function mkClustMap(g: Graph): Map<string, Graph> {
43
- const map = new Map<string, Graph>();
44
- fillClustMap(g, map);
45
- return map;
46
- }
47
-
48
28
  // ---------------------------------------------------------------------------
49
29
  // ClipState — shared between head/tail clip helpers
50
30
  // ---------------------------------------------------------------------------
@@ -27,33 +27,12 @@ import type { Graph } from '../../model/graph.js';
27
27
  import type { Node } from '../../model/node.js';
28
28
  import { Edge } from '../../model/edge.js';
29
29
  import { agnode, agsubnode } from '../../model/cgraph-ops.js';
30
+ import { mkClustMap } from '../../common/clust-map.js';
30
31
 
31
32
  // ---------------------------------------------------------------------------
32
- // Cluster name map (mkClustMap / fillMap / findCluster)
33
+ // Cluster name lookup (mapc); the map is common/clust-map.ts
33
34
  // ---------------------------------------------------------------------------
34
35
 
35
- /**
36
- * Map every cluster's name to its subgraph, recursing the cluster tree
37
- * (info.clust, built by mkClusters). A duplicate name keeps the first.
38
- * @see lib/common/utils.c:fillMap
39
- */
40
- function fillMap(g: Graph, map: Map<string, Graph>): void {
41
- const n = g.info.n_cluster ?? 0;
42
- for (let c = 0; c < n; c++) {
43
- const cl = g.info.clust![c]!;
44
- const s = cl.name;
45
- if (!map.has(s)) map.set(s, cl);
46
- fillMap(cl, map);
47
- }
48
- }
49
-
50
- /** @see lib/common/utils.c:mkClustMap */
51
- function mkClustMap(g: Graph): Map<string, Graph> {
52
- const map = new Map<string, Graph>();
53
- fillMap(g, map);
54
- return map;
55
- }
56
-
57
36
  /**
58
37
  * A node maps to a cluster iff its name starts with "cluster" AND a cluster of
59
38
  * that exact name exists. @see lib/common/utils.c:mapc
@@ -193,3 +193,15 @@ export function agGraphAttr(g: Graph, name: string): string | undefined {
193
193
  if (own !== undefined) return own;
194
194
  return g.root.declaredGraphAttrs.has(name) ? '' : undefined;
195
195
  }
196
+
197
+ /**
198
+ * The graph attributes of `g` that have a local dict symbol: `attrs` without
199
+ * the keys the builder seeded from the parent. Writers that copy a subgraph's
200
+ * own attributes use it, as `write_dict` prints local symbols only.
201
+ * @see lib/cgraph/attr.c:aglocaldictsym
202
+ */
203
+ export function localGraphAttrs(g: Graph): Map<string, string> {
204
+ const local = new Map(g.attrs);
205
+ for (const key of g.seededAttrs ?? []) local.delete(key);
206
+ return local;
207
+ }
@@ -108,8 +108,8 @@ export class Graph {
108
108
 
109
109
  /**
110
110
  * Keys in `attrs` the BUILDER seeded from `graphDefaultsSnapshot` rather than
111
- * the input declaring them in this scope (see builder.ts GRAPH_LABEL_INHERIT_
112
- * KEYS). cgraph distinguishes these structurally — a seeded value is inherited
111
+ * the input declaring them in this scope: every key of the snapshot the
112
+ * scope did not set (agmakeattrs). cgraph distinguishes these structurally — a seeded value is inherited
113
113
  * through the dict view and has no local symbol, while a local declaration
114
114
  * creates one even when its value equals the inherited value — so the
115
115
  * serializer needs the provenance to decide what write_dict would print.
@@ -118,6 +118,17 @@ export class Graph {
118
118
  */
119
119
  seededAttrs?: Set<string>;
120
120
 
121
+ /**
122
+ * Graph-attribute keys this subgraph holds a local symbol for without having
123
+ * declared them: `unviewsubgraphsattr` gives each direct subgraph one, with
124
+ * its current value, when the parent updates its own symbol. The value is
125
+ * the `attrs` entry (absent for the empty default). A subgraph opened in
126
+ * this one later copies that value, not a nearer ancestor's newer one.
127
+ * Undefined on the root and on a subgraph that was never pinned.
128
+ * @see lib/cgraph/attr.c:232 unviewsubgraphsattr
129
+ */
130
+ pinnedAttrs?: Set<string>;
131
+
121
132
  /**
122
133
  * Graph-attribute keys whose declaration in THIS scope was the first anywhere
123
134
  * in the graph. cgraph's `setattr` splits on exactly this: a key with no
@@ -11,6 +11,7 @@ import { Node } from '../model/node.js';
11
11
  import { Edge } from '../model/edge.js';
12
12
  import { assignSubgSeq } from '../model/cgraph-ops.js';
13
13
  import { htmlValueContent, isHtmlValue } from '../common/html-string.js';
14
+ import { effectiveGraphDefaults, hasLocalGraphSym, pinSubgraphsAttr } from './graph-attr-syms.js';
14
15
  import type {
15
16
  AttrPair,
16
17
  NodeId,
@@ -74,28 +75,6 @@ function effectiveNodeDefaults(scope: Graph): Map<string, string> {
74
75
  return eff;
75
76
  }
76
77
 
77
- /** Graph-attr keys do_graph_label inherits; seeded into subgraph attrs so the
78
- * inherited value survives the layout's cluster rebuilds (which copy attrs but
79
- * not the snapshot). `labelloc`/`labeljust` drive cluster label position and
80
- * inherit via C `agget` just like label/font — @see input.c:858-877. */
81
- const GRAPH_LABEL_INHERIT_KEYS = ['label', 'fontname', 'fontsize', 'fontcolor', 'labelloc', 'labeljust'] as const;
82
-
83
- /**
84
- * Collect the graph-attribute defaults in effect at `scope`: walk scope -> root,
85
- * inner overriding outer (first-found wins), reading each graph's own `attrs`.
86
- * Snapshotted when a subgraph opens so an ancestor attribute set LATER in
87
- * statement order does not retroactively apply (DOT's order-sensitive defaults).
88
- */
89
- function effectiveGraphDefaults(scope: Graph): Map<string, string> {
90
- const eff = new Map<string, string>();
91
- for (let g: Graph | null = scope; g !== null; g = g.parent) {
92
- for (const [k, v] of g.attrs) {
93
- if (!eff.has(k)) eff.set(k, v);
94
- }
95
- }
96
- return eff;
97
- }
98
-
99
78
  /** Manages the per-parse node ID counter and node creation. */
100
79
  export class NodeRegistry {
101
80
  private nextId = 0;
@@ -117,35 +96,6 @@ export class NodeRegistry {
117
96
  }
118
97
  }
119
98
 
120
- // ── Endpoint / name collection ────────────────────────────────────────────────
121
-
122
- /** Collects node names from AST statement lists (for edge endpoint expansion). */
123
- export class NameCollector {
124
- static fromStmts(stmts: ParsedStmt[]): string[] {
125
- const out: string[] = [];
126
- for (const s of stmts) NameCollector.fromStmt(s, out);
127
- return out;
128
- }
129
-
130
- static fromStmt(stmt: ParsedStmt, out: string[]): void {
131
- if (stmt.type === 'node') {
132
- out.push(stmt.id.id);
133
- } else if (stmt.type === 'edge') {
134
- for (const item of stmt.nodes) NameCollector.fromEndpoint(item, out);
135
- } else if (stmt.type === 'subgraph') {
136
- out.push(...NameCollector.fromStmts(stmt.stmts));
137
- }
138
- }
139
-
140
- static fromEndpoint(item: NodeId | SubgraphStmt, out: string[]): void {
141
- if ('type' in item && item.type === 'subgraph') {
142
- out.push(...NameCollector.fromStmts(item.stmts));
143
- } else {
144
- out.push((item as NodeId).id);
145
- }
146
- }
147
- }
148
-
149
99
  // ── Statement processors ──────────────────────────────────────────────────────
150
100
 
151
101
  /** Processes individual parsed statements into graph model objects. */
@@ -226,26 +176,36 @@ export class StmtProcessor {
226
176
  }
227
177
 
228
178
  processAssign(stmt: AssignStmt, graph: Graph): void {
229
- graph.attrs.set(stmt.key, normaliseAttrValue(stmt.value));
230
179
  // cgraph: assigning a graph attr on any (sub)graph declares it graph-wide
231
180
  // with an empty default → the root sees "" for it. @see agattr declaration.
232
181
  this.declareGraphAttr(graph, stmt.key);
182
+ graph.attrs.set(stmt.key, normaliseAttrValue(stmt.value));
233
183
  }
234
184
 
235
- /** Record a graph-attribute declaration, noting whether THIS scope was the
236
- * first to declare the key anywhere — the branch selector in cgraph's
237
- * setattr. @see lib/cgraph/attr.c:257 · model/graph.ts firstGraphDecl */
185
+ /** Record a graph-attribute declaration, BEFORE its value is stored, noting
186
+ * whether THIS scope was the first to declare the key anywhere — the branch
187
+ * selector in cgraph's setattr. @see model/graph.ts firstGraphDecl
188
+ * A scope that already holds a symbol for the key (the root always; the
189
+ * first declarer, through bindattrs' empty declaration) updates it, which
190
+ * first pins its direct subgraphs; a new local definition pins nothing.
191
+ * A key declared in a re-opened subgraph's later body gets a local symbol,
192
+ * so it is no longer a seeded one. @see lib/cgraph/attr.c:setattr */
238
193
  private declareGraphAttr(graph: Graph, key: string): void {
239
- if (!graph.root.declaredGraphAttrs.has(key)) {
194
+ const first = !graph.root.declaredGraphAttrs.has(key);
195
+ if (first) {
240
196
  (graph.firstGraphDecl ??= new Set()).add(key);
241
197
  graph.root.declaredGraphAttrs.add(key);
242
198
  }
199
+ if (first || hasLocalGraphSym(graph, key)) pinSubgraphsAttr(graph, key);
200
+ graph.seededAttrs?.delete(key);
243
201
  }
244
202
 
245
203
  processAttr(stmt: AttrStmt, graph: Graph): void {
246
204
  if (stmt.target === 'graph') {
247
- applyAttrs(stmt.attrs, graph.attrs);
248
- for (const a of stmt.attrs) this.declareGraphAttr(graph, a.key);
205
+ for (const a of stmt.attrs) {
206
+ this.declareGraphAttr(graph, a.key);
207
+ applyAttrs([a], graph.attrs);
208
+ }
249
209
  } else if (stmt.target === 'node') {
250
210
  applyAttrs(stmt.attrs, graph.nodeDefaults);
251
211
  } else {
@@ -269,10 +229,21 @@ export class StmtProcessor {
269
229
  // (A -> {S} -> B) appears in two adjacent pairs, so resolving once avoids
270
230
  // double-creating it. Endpoints (incl. subgraphs) open before any edge of the
271
231
  // statement is built — matching cgraph's grammar. @see lib/cgraph/grammar.y
272
- const ends = stmt.nodes.map((item) => ({
273
- nodes: this.resolveEndpoint(item, root, graph, directed),
232
+ const refs = stmt.nodes.map((item) => ({
233
+ ref: this.resolveEndpoint(item, root, graph, directed),
274
234
  port: portStringOf(item),
275
235
  }));
236
+ // A subgraph endpoint expands to the nodes the subgraph holds once the
237
+ // WHOLE statement is parsed, walked in sequence (node id) order: an earlier
238
+ // body of a re-opened subgraph and a later endpoint naming the same
239
+ // subgraph both count. Walking the node dictionary rather than the written
240
+ // order gives graphs-world `37 -> {39;41;38;40}` heads 38,40,39,41, and
241
+ // makes a name written twice in the endpoint one member (1902 drew a1->a3
242
+ // twice). @see lib/cgraph/grammar.y:endedge, edgerhs (agfstnode/agnxtnode)
243
+ const ends = refs.map(({ ref, port }) => ({
244
+ nodes: ref instanceof Graph ? [...ref.nodes.values()].sort((a, b) => a.id - b.id) : ref,
245
+ port,
246
+ }));
276
247
  for (let i = 0; i < ends.length - 1; i++) {
277
248
  this.connectEndpoints(ends[i], ends[i + 1], stmt.attrs, graph, root);
278
249
  }
@@ -294,34 +265,45 @@ export class StmtProcessor {
294
265
  // enclosing scope have already advanced it — matching native's %N exactly.
295
266
  // @see lib/cgraph/graph.c:agsubg, lib/cgraph/id.c:idmap
296
267
  const sgName = stmt.id ?? `%${this.nextAnonId()}`;
297
- // AGSEQ is assigned when the subgraph opens, before its body — matching C's
298
- // agopen, which calls agnextseq before processing the subgraph contents.
299
- // A reopened named subgraph (`subgraph X {…} … subgraph X {…}`) consumes no
300
- // new AGSEQ in cgraph, so reuse the prior seq rather than re-incrementing.
301
- // (Content still overwrites; merge semantics are unchanged and out of scope.)
268
+ // A re-opened named subgraph (`subgraph X {…} … subgraph X {…}`) is the one
269
+ // the parent already holds: agsubg finds it by name among the parent's OWN
270
+ // subgraphs and returns it. The body adds to it; it takes no new AGSEQ, and
271
+ // the attribute values it copied when it first opened stay as they were.
272
+ // @see lib/cgraph/subg.c:agsubg, lib/cgraph/grammar.y:opensubg
302
273
  const prior = graph.subgraphs.get(sgName);
274
+ if (prior !== undefined) {
275
+ buildGraph(stmt.stmts, prior, root, directed, this);
276
+ return prior;
277
+ }
303
278
  const sg = new Graph(sgName, graph.kind);
304
279
  sg.parent = graph;
305
280
  sg.root = root;
306
- if (prior !== undefined) sg.seq = prior.seq;
307
- else assignSubgSeq(graph, sg);
281
+ // AGSEQ is assigned when the subgraph opens, before its body — matching C's
282
+ // agopen, which calls agnextseq before processing the subgraph contents.
283
+ assignSubgSeq(graph, sg);
308
284
  // Snapshot the enclosing graph-attribute defaults at OPEN time (before the
309
285
  // body) so a later ancestor `graph [label=…]` does not apply to this
310
286
  // subgraph — matching cgraph's parse-time defval copy (order-sensitive).
311
287
  sg.graphDefaultsSnapshot = effectiveGraphDefaults(graph);
312
288
  buildGraph(stmt.stmts, sg, root, directed, this);
313
- // Seed the order-correct inherited label-family defaults into the subgraph's
314
- // OWN attrs (body wins) so they survive the layout's cluster rebuilds, which
315
- // copy attrs but not the snapshot. Mirrors cgraph's agsubg defval copy; kept
316
- // to the keys do_graph_label reads so the blast radius stays in label render.
317
- // @see lib/common/input.c:do_graph_label (agget label/font*)
318
- // The seeded keys are recorded so the -Tdot serializer can tell them from a
319
- // genuine local declaration: cgraph gives a local declaration its own dict
320
- // symbol (printed by write_dict) even when the value equals the inherited
321
- // one, whereas a seeded value must stay invisible. @see src/render/dot.ts
322
- for (const key of GRAPH_LABEL_INHERIT_KEYS) {
323
- const v = sg.graphDefaultsSnapshot.get(key);
324
- if (v !== undefined && !sg.attrs.has(key)) {
289
+ // Seed every inherited value into the subgraph's OWN attrs (body wins):
290
+ // agmakeattrs copies each graph attribute in effect in the parent into a
291
+ // new subgraph's record, and every agget(subg, …) reads that copy — the
292
+ // label family (do_graph_label; labelloc/labeljust too, input.c:858-877),
293
+ // `cluster` (is_a_cluster), `ordering`, `rank`, and the rest. Seeding,
294
+ // unlike a read of the snapshot, survives every copy that takes `attrs`
295
+ // alone: the layout's cluster rebuilds and dot's pack projection (C's
296
+ // agcopyattr copies the effective values there).
297
+ // @see lib/cgraph/attr.c:agmakeattrs
298
+ // @see lib/common/input.c:do_graph_label
299
+ // @see lib/common/utils.c:is_a_cluster
300
+ // The seeded keys are recorded so the writers can tell them from a local
301
+ // declaration: cgraph gives a local declaration its own dict symbol
302
+ // (printed by write_dict) even when the value equals the inherited one,
303
+ // whereas a seeded value has none and must stay invisible.
304
+ // @see src/render/dot/attrs.ts, src/model/cgraph-ops.ts:localGraphAttrs
305
+ for (const [key, v] of sg.graphDefaultsSnapshot) {
306
+ if (!sg.attrs.has(key)) {
325
307
  sg.attrs.set(key, v);
326
308
  (sg.seededAttrs ??= new Set()).add(key);
327
309
  }
@@ -360,35 +342,20 @@ export class StmtProcessor {
360
342
  }
361
343
  }
362
344
 
345
+ /** One endpoint of an edge statement: a node item's node, or a subgraph
346
+ * item's subgraph, which the caller expands after the whole statement. */
363
347
  private resolveEndpoint(
364
348
  item: NodeId | SubgraphStmt,
365
349
  root: Graph,
366
350
  scope: Graph,
367
351
  directed: boolean,
368
- ): Node[] {
352
+ ): Node[] | Graph {
369
353
  if ('type' in item && item.type === 'subgraph') {
370
354
  // Create the subgraph as a first-class object so its rank-set attr
371
355
  // (rank=same/min/max/source/sink), node membership, and anon-id/AGSEQ are
372
- // registered for collapse_sets; then expand the edge over its node names.
373
- this.processSubgraph(item, scope, root, directed);
374
- // Ensure (create/look-up) the member nodes in written order, so NEW nodes
375
- // take their AGSEQ in source order — then iterate them in AGSEQ (node id)
376
- // order for edge creation. C builds `tail -> {set}` edges by walking the
377
- // endpoint subgraph's node dictionary (sequence-ordered), not the written
378
- // order; iterating out of order assigns the wrong graphSeq (SVG edge id)
379
- // when the set lists pre-existing nodes out of creation order (graphs-world
380
- // `37 -> {39;41;38;40}`: heads 38,40,39,41 by AGSEQ, not 39,41,38,40).
381
- // @see lib/cgraph/edge.c:agedge — edges follow agfstnode/agnxtnode order
382
- // Dedup by node identity: a name appearing in several statements of the
383
- // endpoint subgraph (e.g. a1 in both `a1->a2` and `b2->a1`) is ONE member
384
- // in cgraph's node dictionary, so `subg -> x` expands to a single a1->x —
385
- // not one per textual occurrence (1902 drew a1->a3 twice).
386
- // @see lib/cgraph/edge.c:agedge (walks agfstnode/agnxtnode — unique nodes)
387
- const seen = new Set<number>();
388
- const nodes = NameCollector.fromStmts(item.stmts)
389
- .map((n) => this.registry.ensure(n, root, scope))
390
- .filter((nd) => (seen.has(nd.id) ? false : (seen.add(nd.id), true)));
391
- return nodes.sort((a, b) => a.id - b.id);
356
+ // registered for collapse_sets. Its body creates the member nodes in
357
+ // written order, so NEW nodes take their AGSEQ in source order.
358
+ return this.processSubgraph(item, scope, root, directed);
392
359
  }
393
360
  return [this.registry.ensure((item as NodeId).id, root, scope)];
394
361
  }
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: EPL-2.0
2
+ /**
3
+ * The builder's model of cgraph's graph-attribute symbols: which graphs hold
4
+ * a local dict symbol for a key, and what a subgraph copies when it opens.
5
+ * @see lib/cgraph/attr.c
6
+ */
7
+ import type { Graph } from '../model/graph.js';
8
+
9
+ /**
10
+ * Whether `g` holds a local dict symbol for graph attribute `key`. The root
11
+ * holds every declared key (a global definition goes into its dict); a
12
+ * subgraph holds the keys it declared and the ones it was pinned with. A
13
+ * seeded value is inherited through the dict view and has no symbol.
14
+ * @see lib/cgraph/attr.c:aglocaldictsym
15
+ */
16
+ export function hasLocalGraphSym(g: Graph, key: string): boolean {
17
+ if (g.parent === null) return g.declaredGraphAttrs.has(key);
18
+ if (g.pinnedAttrs?.has(key) === true) return true;
19
+ return g.attrs.has(key) && g.seededAttrs?.has(key) !== true;
20
+ }
21
+
22
+ /**
23
+ * Give each direct subgraph of `parent` with no local symbol for `key` one
24
+ * holding its current value: `parent` is about to update its own symbol.
25
+ * The value stays in the subgraph's `attrs` (absent for the empty default).
26
+ * @see lib/cgraph/attr.c:unviewsubgraphsattr
27
+ */
28
+ export function pinSubgraphsAttr(parent: Graph, key: string): void {
29
+ for (const sub of parent.subgraphs.values()) {
30
+ if (!hasLocalGraphSym(sub, key)) (sub.pinnedAttrs ??= new Set()).add(key);
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The graph-attribute values a subgraph opening in `scope` copies: for each
36
+ * key, the `defval` of the nearest local symbol on the dict view scope ->
37
+ * root, which is what `agmakeattrs` iterates. A graph's value for a key it
38
+ * holds a symbol for is its `attrs` entry (absent: the empty default, which
39
+ * the copy leaves out). Until a subgraph is re-opened these are the current
40
+ * values of the enclosing graphs; a re-opened one may hold a seeded value
41
+ * that a nearer symbol above it overrides, or a pin that hides a later one.
42
+ * Snapshotted when a subgraph opens so an ancestor attribute set LATER in
43
+ * statement order does not retroactively apply (DOT's order-sensitive defaults).
44
+ * @see lib/cgraph/attr.c:agmakeattrs
45
+ */
46
+ export function effectiveGraphDefaults(scope: Graph): Map<string, string> {
47
+ const eff = new Map<string, string>();
48
+ const found = new Set<string>();
49
+ const take = (g: Graph, key: string): void => {
50
+ if (found.has(key)) return;
51
+ found.add(key);
52
+ const v = g.attrs.get(key);
53
+ if (v !== undefined) eff.set(key, v);
54
+ };
55
+ for (let g: Graph | null = scope; g !== null; g = g.parent) {
56
+ for (const key of g.attrs.keys()) {
57
+ if (g.seededAttrs?.has(key) !== true) take(g, key);
58
+ }
59
+ for (const key of g.pinnedAttrs ?? []) take(g, key);
60
+ }
61
+ return eff;
62
+ }
@@ -26,7 +26,7 @@ import {
26
26
  COMPUTED_EDGE_ATTRS, COMPUTED_NODE_ATTRS, appendRecordRects, computedPart, dictParts,
27
27
  echoAttr, echoGraphAttr, edgeAttrsAttached, edgeConnector, edgePosRaw,
28
28
  effectiveEdgeDefaults, effectiveNodeDefaults, graphInputParts, graphLabelAttrs,
29
- isDirected, nodeDictParts, nodePosRaw, nodeRecord, objInputParts,
29
+ inClusterTree, isDirected, nodeDictParts, nodePosRaw, nodeRecord, objInputParts,
30
30
  } from './attrs.js';
31
31
  import { withLinelength } from './agwrite-linelength.js';
32
32
  import { nodesInSeq } from '../../layout/dot/decomp.js';
@@ -36,7 +36,7 @@ import type { XdotDraws, SerCtx } from './types.js';
36
36
  export abstract class DotWriterBase {
37
37
  /** @see dot.ts XdotRenderer.emitDraws */
38
38
  protected abstract readonly emitDraws: boolean;
39
- /** Clusters in render order (GD_clust); filled by the renderer's endCluster. */
39
+ /** The clusters xdot_end_cluster ran for (not all of GD_clust: inClusterTree). */
40
40
  protected clusters: Graph[] = [];
41
41
  /** Draw strings for `obj`, or undefined in a format that emits none. */
42
42
  protected abstract drawsOf(obj: Node | Edge | Graph): XdotDraws | undefined;
@@ -112,7 +112,7 @@ export abstract class DotWriterBase {
112
112
  * a boxed graph and an unboxed child — the driver that makes an anon subgraph
113
113
  * under the root or a cluster "relevant". @see lib/common/output.c:safe_dcl */
114
114
  private hasBb(g: Graph): boolean {
115
- return g === g.root || this.clusters.includes(g);
115
+ return g === g.root || inClusterTree(g);
116
116
  }
117
117
 
118
118
  /** Anonymous subgraph with no own node/edge defaults and no graph attrs
@@ -121,7 +121,7 @@ export abstract class DotWriterBase {
121
121
  * the parent, empty on the child) and `rank`. @see write.c:irrelevant_subgraph */
122
122
  private irrelevantSubgraph(g: Graph): boolean {
123
123
  if (!this.isAnonymous(g)) return false;
124
- if (this.clusters.includes(g)) return false;
124
+ if (inClusterTree(g)) return false;
125
125
  if (g.nodeDefaults.size > 0 || g.edgeDefaults.size > 0) return false;
126
126
  if (g.parent) {
127
127
  if (this.hasBb(g) !== this.hasBb(g.parent)) return false;
@@ -140,9 +140,8 @@ export abstract class DotWriterBase {
140
140
  * `rec_attach_bb` walks the ROOT and then `GD_clust` recursively, so a
141
141
  * subgraph the layout did not box is attached NEITHER `bb` NOR the label
142
142
  * triple — both keep the INPUT's values, which agwrite echoes. circo and
143
- * twopi lay out no clusters at all (`GD_clust` empty — mirrored here by
144
- * `this.clusters`, filled from endCluster), so on a re-fed dot output their
145
- * `cluster0` comes back carrying the *previous* run's `bb` and `lp`.
143
+ * twopi lay out no clusters (`GD_clust` empty, `inClusterTree` false), so on a
144
+ * re-fed dot output `cluster0` carries the *previous* run's `bb` and `lp`.
146
145
  * @see lib/common/output.c:249 rec_attach_bb */
147
146
  private subgGraphAttrs(sg: Graph): string[] {
148
147
  // `rank` is not special-cased here: it is an ordinary input attribute and
@@ -183,7 +182,7 @@ export abstract class DotWriterBase {
183
182
  private writeDicts(g: Graph, top: boolean, ctx: SerCtx): void {
184
183
  const graphParts = top
185
184
  ? this.graphAttrs(g)
186
- : this.clusters.includes(g)
185
+ : inClusterTree(g)
187
186
  ? this.clusterAttrs(g)
188
187
  : this.subgGraphAttrs(g);
189
188
  this.writeDict('graph', graphParts, ctx);
@@ -391,13 +390,14 @@ export abstract class DotWriterBase {
391
390
  return parts;
392
391
  }
393
392
 
394
- /** Cluster attribute block. C's xdot_end_cluster ALWAYS agsets `_draw_` when
395
- * the graph has clusters (even empty, e.g. peripheries=0), so emit it
396
- * unconditionally; `_ldraw_` only when the cluster has a label.
393
+ /** Cluster attribute block. C's xdot_end_cluster ALWAYS agsets `_draw_` for a
394
+ * cluster it ran for (even empty, e.g. peripheries=0); one that emit_clusters
395
+ * skipped (clust_in_layer) keeps only a stored one. `_ldraw_` only with a label.
397
396
  * @see plugin/core/gvrender_core_dot.c:284 xdot_end_cluster */
398
397
  private clusterAttrs(sg: Graph): string[] {
399
398
  const d = this.drawsOf(sg);
400
- const parts: string[] = this.emitDraws || d?.draw ? [this.drawAttr('_draw_', d?.draw ?? '')] : [];
399
+ const drawn = this.emitDraws && this.clusters.includes(sg);
400
+ const parts: string[] = drawn || d?.draw ? [this.drawAttr('_draw_', d?.draw ?? '')] : [];
401
401
  if (d?.ldraw) parts.push(this.drawAttr('_ldraw_', d.ldraw));
402
402
  if (sg.info.bb) parts.push('bb="' + this.bbStr(sg) + '"');
403
403
  // rec_attach_bb recurses into GD_clust, so a labelled cluster carries the
@@ -240,8 +240,10 @@ function ownComputedAttrs(g: Graph, top: boolean, computed: Set<string>): Readon
240
240
  }
241
241
 
242
242
  /** Whether an ancestor's GD_clust holds `g` (a cluster inside an anonymous
243
- * subgraph belongs to the nearest cluster or root above it). */
244
- function inClusterTree(g: Graph): boolean {
243
+ * subgraph belongs to the nearest cluster or root above it). This is the set
244
+ * rec_attach_bb walks: every cluster the layout made, drawn or not.
245
+ * @see lib/common/output.c:rec_attach_bb */
246
+ export function inClusterTree(g: Graph): boolean {
245
247
  for (let a = g.parent; a !== null; a = a.parent) {
246
248
  if ((a.info.clust ?? []).slice(0, a.info.n_cluster ?? 0).includes(g)) return true;
247
249
  }
@@ -404,6 +406,8 @@ export function writeDictSkips(v: string, inherited: string | undefined): boolea
404
406
  export function echoGraphAttr(g: Graph, key: string): string[] {
405
407
  const v = g.attrs.get(key);
406
408
  if (v === undefined) return [];
409
+ // A seeded value has no local dict symbol: write_dict does not print it.
410
+ if (g.seededAttrs?.has(key) === true) return [];
407
411
  if (writeDictSkips(v, g.graphDefaultsSnapshot?.get(key))) return [];
408
412
  return [`${key}=${agstrcanon(v)}`];
409
413
  }
@@ -6,8 +6,11 @@
6
6
  * proxy nodes `__<i>:<cluster>` never print. The port's writers otherwise read
7
7
  * the proxies as they print and undo at the next layout (`layout-reset.ts`);
8
8
  * json prints from the graph itself, so it takes the undo at C's point, through
9
- * the same helper. A graph with no cluster edges keeps the usual order (attach
10
- * after the write): nothing there can differ.
9
+ * the same helper. json0 attaches before it writes on every graph: it prints
10
+ * what the write-back stored (`bb`, an edge's `pos`) and has nothing else to
11
+ * take them from. json, on a graph with no cluster edges, defers its held
12
+ * write-back until after the write: its xdot draw lookup overlays the same
13
+ * values, so nothing there can differ.
11
14
  *
12
15
  * Also the json cluster map: write_graph's top pass numbers the subgraphs and
13
16
  * maps each cluster's name to its gid (label_subgs, insert), which is where a
@@ -27,8 +30,9 @@ import type { Node } from '../model/node.js';
27
30
 
28
31
  /**
29
32
  * With cluster edges on `g`: runs `attach` (attach_attrs' write-back) and the
30
- * undo now, and returns a no-op. Otherwise returns `attach`, for the caller to
31
- * run after the write.
33
+ * undo now, and returns a no-op. Otherwise returns `attach` uncalled: json runs
34
+ * it after the write (its draw lookup overlays the values), and json0 runs it
35
+ * at once, before the write.
32
36
  * @see lib/common/output.c:416 attach_attrs
33
37
  */
34
38
  export function attachBeforeWriteWithClusterEdges(g: Graph, attach: () => void): () => void {