@knowvah/dot-engine 2.12.3 → 2.13.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 (92) hide show
  1. package/dist/api.js +13 -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/errors.d.ts +11 -3
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/gvc/anchor.d.ts +17 -19
  14. package/dist/gvc/anchor.d.ts.map +1 -1
  15. package/dist/gvc/context.d.ts +7 -0
  16. package/dist/gvc/context.d.ts.map +1 -1
  17. package/dist/gvc/device-cluster.d.ts +9 -0
  18. package/dist/gvc/device-cluster.d.ts.map +1 -1
  19. package/dist/gvc/device.d.ts +2 -1
  20. package/dist/gvc/device.d.ts.map +1 -1
  21. package/dist/gvc/emit-walk.d.ts +7 -0
  22. package/dist/gvc/emit-walk.d.ts.map +1 -1
  23. package/dist/gvc/job.d.ts +13 -6
  24. package/dist/gvc/job.d.ts.map +1 -1
  25. package/dist/gvc/viewport.d.ts +14 -0
  26. package/dist/gvc/viewport.d.ts.map +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +631 -498
  29. package/dist/index.js.map +4 -4
  30. package/dist/layout/dot/classify.d.ts.map +1 -1
  31. package/dist/layout/dot/compound.d.ts +0 -4
  32. package/dist/layout/dot/compound.d.ts.map +1 -1
  33. package/dist/layout/dot/ns-range.d.ts.map +1 -1
  34. package/dist/layout/fdp/cluster-edges.d.ts.map +1 -1
  35. package/dist/model/cgraph-ops.d.ts +7 -0
  36. package/dist/model/cgraph-ops.d.ts.map +1 -1
  37. package/dist/model/graph.d.ts +12 -2
  38. package/dist/model/graph.d.ts.map +1 -1
  39. package/dist/parser/builder.d.ts +11 -10
  40. package/dist/parser/builder.d.ts.map +1 -1
  41. package/dist/parser/graph-attr-syms.d.ts +35 -0
  42. package/dist/parser/graph-attr-syms.d.ts.map +1 -0
  43. package/dist/render/dot/agwrite.d.ts +6 -7
  44. package/dist/render/dot/agwrite.d.ts.map +1 -1
  45. package/dist/render/dot/attrs.d.ts +5 -0
  46. package/dist/render/dot/attrs.d.ts.map +1 -1
  47. package/dist/render/json-cluster-edge.d.ts +3 -2
  48. package/dist/render/json-cluster-edge.d.ts.map +1 -1
  49. package/dist/render/json.d.ts +7 -1
  50. package/dist/render/json.d.ts.map +1 -1
  51. package/dist/render/map.d.ts +14 -10
  52. package/dist/render/map.d.ts.map +1 -1
  53. package/dist/render/svg-graph.d.ts.map +1 -1
  54. package/dist/render/svg-id.d.ts +9 -0
  55. package/dist/render/svg-id.d.ts.map +1 -1
  56. package/dist/render.js +713 -581
  57. package/dist/render.js.map +4 -4
  58. package/dist/util/printf-round.d.ts +8 -0
  59. package/dist/util/printf-round.d.ts.map +1 -1
  60. package/package.json +1 -1
  61. package/src/common/clust-map.ts +58 -0
  62. package/src/common/htmltable-emit.ts +87 -7
  63. package/src/common/layers.ts +25 -4
  64. package/src/common/poly-gencode.ts +3 -11
  65. package/src/common/xlabels-place.ts +22 -4
  66. package/src/errors.ts +13 -3
  67. package/src/gvc/anchor.ts +18 -30
  68. package/src/gvc/context.ts +21 -6
  69. package/src/gvc/device-cluster.ts +16 -0
  70. package/src/gvc/device.ts +20 -20
  71. package/src/gvc/emit-walk.ts +11 -1
  72. package/src/gvc/job.ts +17 -9
  73. package/src/gvc/viewport.ts +27 -6
  74. package/src/index.ts +1 -0
  75. package/src/layout/dot/classify.ts +23 -1
  76. package/src/layout/dot/compound.ts +1 -21
  77. package/src/layout/dot/ns-range.ts +41 -5
  78. package/src/layout/fdp/cluster-edges.ts +2 -23
  79. package/src/model/cgraph-ops.ts +12 -0
  80. package/src/model/graph.ts +13 -2
  81. package/src/parser/builder.ts +67 -100
  82. package/src/parser/graph-attr-syms.ts +62 -0
  83. package/src/render/dot/agwrite.ts +12 -12
  84. package/src/render/dot/attrs.ts +6 -2
  85. package/src/render/json-cluster-edge.ts +8 -4
  86. package/src/render/json.ts +15 -8
  87. package/src/render/map.ts +49 -58
  88. package/src/render/svg-cluster.ts +3 -3
  89. package/src/render/svg-graph.ts +1 -3
  90. package/src/render/svg-helpers.ts +6 -6
  91. package/src/render/svg-id.ts +23 -5
  92. package/src/util/printf-round.ts +11 -0
@@ -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 {
@@ -47,6 +47,7 @@ import { gfmt5, XdotRenderer, type XdotDraws } from './dot.js';
47
47
  import { attachAttrs, nodeLayoutAttrs } from './dot/write-back.js';
48
48
  import { attachBeforeWriteWithClusterEdges as attachFirst, jsonNodes, labelSubgs, lookupCluster } from './json-cluster-edge.js';
49
49
  import { attrsWithoutLayoutBb } from '../gvc/layout-bb.js';
50
+ import { agNameOf, localGraphAttrs } from '../model/cgraph-ops.js';
50
51
  import { CHAR_LATIN1 } from '../common/graph-init.js';
51
52
  import { parse } from '../parser/index.js';
52
53
  import { render as deviceRender } from '../gvc/device.js';
@@ -276,7 +277,7 @@ function collectDrawLookup(g: Graph): DrawLookup | undefined {
276
277
  for (const [nm, gChild] of gSub.subgraphs) {
277
278
  const xgChild = xgSub.subgraphs.get(nm);
278
279
  if (xgChild !== undefined) {
279
- cluster.set(gChild, new Map(xgChild.attrs));
280
+ cluster.set(gChild, localGraphAttrs(xgChild));
280
281
  correlate(gChild, xgChild);
281
282
  } else {
282
283
  correlate(gChild, xgSub);
@@ -518,8 +519,9 @@ function buildNodeObject(n: Node, ctx: BuildCtx): JObj {
518
519
  const eff = nodeEffectiveAttrs(n);
519
520
  const xd = ctx.draws?.node.get(n.name);
520
521
  if (xd === undefined) {
521
- // Fallback (json0 / hand-built graph): no xdot render supplies the layout
522
- // attrs, so take the strings attach_attrs writes (output.c:296-309).
522
+ // Fallback for a json render whose xdot re-render failed (a hand-built
523
+ // graph): take the strings attach_attrs writes (output.c:296-309). json0
524
+ // has no draw lookup either, so it repeats what attachAttrs just stored.
523
525
  const layout = nodeLayoutAttrs(n);
524
526
  eff.set('pos', layout.pos).set('width', layout.width).set('height', layout.height);
525
527
  }
@@ -577,8 +579,7 @@ function buildEdgesArray(g: Graph, ctx: BuildCtx): JObj[] {
577
579
  /** @see plugin/core/gvrender_core_json.c:write_graph */
578
580
  function buildGraphObject(g: Graph, top: boolean, ctx: BuildCtx): JObj {
579
581
  const o: JObj = {};
580
- // write_hdr
581
- o.name = g.name;
582
+ o.name = agNameOf(g); // write_hdr: agnameof (%1 for a nameless root)
582
583
  if (top) {
583
584
  o.directed = g.kind === 'directed' || g.kind === 'strict-directed';
584
585
  o.strict = g.kind === 'strict-directed' || g.kind === 'strict-undirected';
@@ -682,10 +683,16 @@ export class Json0Renderer extends JsonRendererBase implements RendererPlugin {
682
683
 
683
684
  beginGraph(_g: Graph, _job: RenderJob): void { /* no-op */ }
684
685
 
685
- /** C's json_begin_graph runs attach_attrs; buildJson overlays the same values. */
686
+ /**
687
+ * Attach, then write: C's json_begin_graph runs attach_attrs (which ends by
688
+ * undoing cluster edges) before json_end_graph writes, and json0 prints what
689
+ * that stored. Nothing overlays `bb` or an edge's `pos` here, as json's xdot
690
+ * draw lookup does, so the write-back cannot wait until after the write.
691
+ * @see plugin/core/gvrender_core_json.c:json_begin_graph
692
+ */
686
693
  endGraph(g: Graph, job: RenderJob): void {
687
- const later = attachFirst(g, () => attachAttrs(g));
688
- job.write(buildJson(g, false)); later();
694
+ attachFirst(g, () => attachAttrs(g))();
695
+ job.write(buildJson(g, false));
689
696
  }
690
697
  }
691
698