figdown 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/figdown.mjs CHANGED
@@ -1,8 +1,8 @@
1
- // figdown.mjs — FigDown embeddable library (0.4.0)
1
+ // figdown.mjs — FigDown embeddable library (0.4.1)
2
2
  // GENERATED FILE, DO NOT EDIT. Built from editor/figdown.html.
3
3
  // Regenerate with: node tools/make-lib.js
4
4
  'use strict';
5
- var VERSION = "0.4.0";
5
+ var VERSION = "0.4.1";
6
6
 
7
7
  // ---- engine (extracted verbatim from editor/figdown.html) ----
8
8
  var __engine = (function () {
@@ -16,7 +16,7 @@ const SHAPES = ['box','rounded','circle','ellipse','diamond','cylinder'];
16
16
  // input to that promise, and under core §13 a 0.x renderer may differ from
17
17
  // the next — which makes the recorded version the only thing that can
18
18
  // explain a diff between two renderings of one source.
19
- const FIGDOWN_VERSION = '0.4.0';
19
+ const FIGDOWN_VERSION = '0.4.1';
20
20
  // `STATECHART-GENRE-SCOPE`: the language number moved for the first time. The dev
21
21
  // counter does NOT reset (core §13.0.4 — `N` counts source states of the
22
22
  // engine and only ever increases), so 0.1 is followed by
@@ -31,7 +31,7 @@ const FIGDOWN_VERSION = '0.4.0';
31
31
  // fixes only. No new features. The language does not move." Shipping `note=`
32
32
  // under `v0.2.z` would make `figdown 0.2` name two different languages: the one
33
33
  // `v0.2.0` published and the one with `note=`. So the language number moves.
34
- // `SEQUENCE-SOURCE-STANDARD`-R182: `figdown 0.4` joins the set, and it joins it for the
34
+ // `SEQUENCE-GENRE-VOCABULARY`: `figdown 0.4` joins the set, and it joins it for the
35
35
  // same reason `0.2` did — a GENRE token is language surface, and core §13.0
36
36
  // makes added surface a `Y` and never a `Z`. `sequence` is that token. It adds
37
37
  // no keyword yet (see GENRES_BY_VERSION below), which is exactly `STATECHART-GENRE-SCOPE`'s shape:
@@ -44,7 +44,7 @@ const GENRES_BY_VERSION = {
44
44
  '0.1': ['block','topology','flowchart','bitfield','table','timing'],
45
45
  '0.2': ['block','topology','flowchart','bitfield','table','timing','statechart'],
46
46
  '0.3': ['block','topology','flowchart','bitfield','table','timing','statechart'],
47
- // `SEQUENCE-SOURCE-STANDARD`-R182: `sequence` is dispatchable from here on. Like
47
+ // `SEQUENCE-GENRE-VOCABULARY`: `sequence` is dispatchable from here on. Like
48
48
  // `statechart` at `STATECHART-GENRE-SCOPE` it arrived with NO vocabulary of its own, and the
49
49
  // consequence was stated here rather than left to be discovered: there was no
50
50
  // `GENRE_KW.sequence` row, and the allowlist guard is written
@@ -52,7 +52,7 @@ const GENRES_BY_VERSION = {
52
52
  // row is NOT narrowed — a `figdown 0.4 sequence` document could write any
53
53
  // registered keyword and it parsed. The document that increment meant to
54
54
  // land was the header ALONE.
55
- // `SEQUENCE-SOURCE-STANDARD`-R182: CLOSED. `GENRE_KW.sequence` exists below, so the
55
+ // `SEQUENCE-GENRE-VOCABULARY`: CLOSED. `GENRE_KW.sequence` exists below, so the
56
56
  // genre now constrains what it names — five keywords of its own, `class`,
57
57
  // and the genre-free core — and `flow`/`rank`/`group` are line errors under
58
58
  // it. The genre still has NO RENDERER: a valid `sequence` document parses to
@@ -366,7 +366,7 @@ const DIRECTIVE_OPTS={
366
366
  // keyed by the surface word an author actually wrote.
367
367
  flowline:['style','class','fill','stroke','label','taillabel','headlabel','note'],
368
368
  transition:['style','class','fill','stroke','label','taillabel','headlabel','note'],
369
- // `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` genre's four own rows. `message` is
369
+ // `SEQUENCE-GENRE-VOCABULARY`: the `sequence` genre's four own rows. `message` is
370
370
  // the fourth connector spelling and takes the connector set — `fill=` and
371
371
  // the three retired label keys stay listed for the same reason they are
372
372
  // listed on the other three, so their dedicated diagnostics fire instead of
@@ -432,7 +432,7 @@ const DIRECTIVE_OPTS={
432
432
  cell:['fill','stroke','class'], width:[],
433
433
  signal:['data','fill','stroke'], gap:[]
434
434
  };
435
- // `SEQUENCE-SOURCE-STANDARD`-R182: the FIRST genre-conditional option row, and it
435
+ // `SEQUENCE-GENRE-VOCABULARY`: the FIRST genre-conditional option row, and it
436
436
  // exists because `DIRECTIVE_OPTS` is keyed by the SURFACE WORD an author
437
437
  // wrote, while `GENRE-VOCABULARY-OBLIGATION` makes a surface word a per-genre declaration. Every other
438
438
  // shared spelling in the language names the same construct in every genre
@@ -1015,7 +1015,7 @@ const FLOWCHART_SUBJECT_KW=['external'];
1015
1015
  // none of the six; `external` is additionally UML 2.5.1 §14's own
1016
1016
  // `TransitionKind` literal and is reserved for it (`RESERVED-SPELLINGS`).
1017
1017
  const STATECHART_SUBJECT_KW=[];
1018
- // `sequence` (EXPERIMENTAL, 0.4, `SEQUENCE-SOURCE-STANDARD`-R182): THREE, and the array is
1018
+ // `sequence` (EXPERIMENTAL, 0.4, `SEQUENCE-GENRE-VOCABULARY`): THREE, and the array is
1019
1019
  // this genre's whole declaration of what a sequence figure is OF. `state` and
1020
1020
  // `fragment` and `operand` describe referents UML clause 17 defines —
1021
1021
  // `StateInvariant` (§17.12.25), `CombinedFragment` (§17.12.3) and
@@ -1047,6 +1047,23 @@ const FLOWCHART_ROLE_KW=['process','decision','terminator'];
1047
1047
  // only its default drawing, and `shape=` on the same line overrides the
1048
1048
  // drawing without touching the role (§12.7).
1049
1049
  const ROLE_SHAPE={process:'box',decision:'diamond',terminator:'rounded'};
1050
+ // Geometry DERIVED from the NODE DIRECTIVE ITSELF, for a genre whose node has
1051
+ // exactly one kind and therefore no role to map (backlog 52).
1052
+ // `statechart`'s own §Defaults rules "do not encode state-ness in a shape (`SHAPE-ENUM-VOCABULARY`)
1053
+ // — the genre already says it", and until now the engine contradicted it: a
1054
+ // `state` fell through to `box`, so every author who obeyed the rule got
1055
+ // right-angle rectangles that read as ISO 5807 process boxes, and four of the
1056
+ // six shipped statechart figures wrote `shape=rounded` on EVERY state line to
1057
+ // get out of it — twenty-one hand-keyed presentation keys restating one genre
1058
+ // fact. The derivation is the same move `flowchart` already makes through
1059
+ // ROLE_SHAPE, one level up: there the ROLE picks the drawing, here the
1060
+ // DIRECTIVE does, because `state` is the whole model (`GENRE-NODE-SPELLING` — no role is
1061
+ // recorded and none is missing). `SHAPE-ENUM-VOCABULARY` is satisfied for the same reason it is
1062
+ // satisfied for `decision`: the SOURCE says what the thing is, and the shape
1063
+ // is only how that thing happens to be drawn. `shape=` on the same line stays
1064
+ // legal and still overrides the DRAWING ONLY (§12.7), exactly as on a
1065
+ // `decision` — a `state x "S" shape=box` is still a state in the model.
1066
+ const KW_SHAPE={state:'rounded'};
1050
1067
 
1051
1068
  // `GENRE-CONNECTOR-SPELLING`/`GENRE-NODE-SPELLING`: PER-GENRE NODE AND CONNECTOR SPELLINGS.
1052
1069
  // Each scene genre takes the word its own domain uses for the line between
@@ -1074,7 +1091,7 @@ const GENRE_NODE_KW={block:'node',topology:'node',flowchart:'node',statechart:'s
1074
1091
  const GENRE_CONNECTOR_KW={block:'edge',topology:'edge',flowchart:'flowline',statechart:'transition',sequence:'message'};
1075
1092
  const NODE_SPELLINGS=new Set(['node','state','lifeline']);
1076
1093
  const CONNECTOR_SPELLINGS=new Set(['edge','flowline','transition','message']);
1077
- // `SEQUENCE-SOURCE-STANDARD`-R182: WHERE EACH GENRE'S NODE ROWS LIVE IN THE PARSED DOC.
1094
+ // `SEQUENCE-GENRE-VOCABULARY`: WHERE EACH GENRE'S NODE ROWS LIVE IN THE PARSED DOC.
1078
1095
  // `GENRE_NODE_KW` above says what the WORD is; this says which `doc`
1079
1096
  // collection the parser puts that word's rows in. The two are separate facts
1080
1097
  // and only one of them is `nodes`: `statechart` renames the word and keeps the
@@ -1083,11 +1100,11 @@ const CONNECTOR_SPELLINGS=new Set(['edge','flowline','transition','message']);
1083
1100
  // the form "is this id a thing this genre declares" has to ask through here.
1084
1101
  // Hand-writing `doc.nodes` is the defect it closes: the Fill/Delete/Raise/
1085
1102
  // Lower enablement asked `lastDoc.nodes` and so was permanently false under
1086
- // `sequence`, greying out four buttons whose edits (`SEQUENCE-SOURCE-STANDARD`-R182) already worked.
1103
+ // `sequence`, greying out four buttons whose edits (`SEQUENCE-GENRE-VOCABULARY`) already worked.
1087
1104
  const GENRE_NODE_COLL={block:'nodes',topology:'nodes',flowchart:'nodes',
1088
1105
  statechart:'nodes',sequence:'lifelines'};
1089
1106
  const docNodes=(doc)=>(doc&&doc[GENRE_NODE_COLL[doc.genre]||'nodes'])||[];
1090
- // `SEQUENCE-SOURCE-STANDARD`-R182: the four `sequence` directives that have their own
1107
+ // `SEQUENCE-GENRE-VOCABULARY`: the four `sequence` directives that have their own
1091
1108
  // parser (`message` rides the connector scanner). The set is what dispatches
1092
1109
  // to `parseSeqDirective`, and it is scoped by `doc.genre` at the call site so
1093
1110
  // `state` still reaches `statechart`'s node parser under `statechart`.
@@ -1155,7 +1172,7 @@ const WORD_WHY={
1155
1172
  transition:'the connecting line in a statechart is a TRANSITION — the term UML 2.5.1 §14 uses for it',
1156
1173
  node:'this genre has more kinds of thing than it has words for, so `node` is the general one',
1157
1174
  state:'a statechart has exactly ONE kind of node and it is a STATE (UML 2.5.1 §14)',
1158
- // `SEQUENCE-SOURCE-STANDARD`-R182: both are WHOLE borrows from the genre's source
1175
+ // `SEQUENCE-GENRE-VOCABULARY`: both are WHOLE borrows from the genre's source
1159
1176
  // standard, verified against the clause text rather than against a
1160
1177
  // secondary description (spec/standards-claims.tsv).
1161
1178
  lifeline:'a sequence figure has exactly ONE kind of participant column and it is a LIFELINE — the term UML 2.5.1 §17.3.3.1 defines and §17.3.4.1 draws',
@@ -1304,7 +1321,7 @@ const GENRE_KW={
1304
1321
  // chart is experimental and attaches to a table id in the same document
1305
1322
  table:new Set(GENRE_FREE_KW.concat(['class','table','chart'])),
1306
1323
  timing:new Set(GENRE_FREE_KW.concat(['class','timing'])),
1307
- // `SEQUENCE-SOURCE-STANDARD`-R182: `sequence` gets its row, and the row is what
1324
+ // `SEQUENCE-GENRE-VOCABULARY`: `sequence` gets its row, and the row is what
1308
1325
  // closes the Batch-1 finding that the genre "states a reading and constrains
1309
1326
  // nothing". It is NOT built on `SCENE_HOST_KW`, and the three absences are
1310
1327
  // each a decision rather than an oversight:
@@ -1348,7 +1365,7 @@ function splitFigdownSections(text){
1348
1365
  return secs;
1349
1366
  }
1350
1367
 
1351
- // `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` genre's DERIVED reading, in one
1368
+ // `SEQUENCE-GENRE-VOCABULARY`: the `sequence` genre's DERIVED reading, in one
1352
1369
  // function so the parser's checks and (from a later increment) the renderer
1353
1370
  // cannot disagree about what a document says.
1354
1371
  //
@@ -1447,7 +1464,7 @@ function parseOne(text){
1447
1464
  const doc={title:null,note:null,nodes:[],groups:[],edges:[],planes:[{id:'base',label:null,z:0}],
1448
1465
  flow:'right',ranks:[],pins:{},blocks:[],trunks:[],thresholds:[],bands:[],
1449
1466
  classes:[],boundaries:[],
1450
- // `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` model. FIVE collections,
1467
+ // `SEQUENCE-GENRE-VOCABULARY`: the `sequence` model. FIVE collections,
1451
1468
  // one per keyword, and they are separate arrays rather than
1452
1469
  // aliases of `nodes`/`edges` because a message is not an edge: an
1453
1470
  // edge is a relation between two nodes and has no position, while
@@ -1601,7 +1618,7 @@ function parseOne(text){
1601
1618
  if(ro && ro[u2[0]]!==undefined) err(n,REFUSED_OPT_IN_GENRE(u2[0],doc.genre));
1602
1619
  else err(n,'unknown option "'+u2[0]+'="');
1603
1620
  return; }
1604
- // `SEQUENCE-SOURCE-STANDARD`-R182: `message` adds ONE trailing positional — the
1621
+ // `SEQUENCE-GENRE-VOCABULARY`: `message` adds ONE trailing positional — the
1605
1622
  // quoted message label — to the connector grammar, because that is where
1606
1623
  // every sequence source in the corpus writes it and the `[mid]` form
1607
1624
  // reads as an annotation rather than as the message itself. Every other
@@ -1660,7 +1677,7 @@ function parseOne(text){
1660
1677
  if(!pc.ok){ err(n,pc.err); return; }
1661
1678
  ecls=pc.ids;
1662
1679
  }
1663
- // `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` fork. It is the SAME scanner with
1680
+ // `SEQUENCE-GENRE-VOCABULARY`: the `sequence` fork. It is the SAME scanner with
1664
1681
  // a different reading, and the model it writes is a different collection:
1665
1682
  // a message is an OCCURRENCE with a place in the figure's total order
1666
1683
  // (draft §31), an edge is a relation with no position at all.
@@ -1700,7 +1717,7 @@ function parseOne(text){
1700
1717
  plane:o2.plane||'base',line:n});
1701
1718
  }
1702
1719
 
1703
- // `SEQUENCE-SOURCE-STANDARD`-R182: the four `sequence` directives that are not the
1720
+ // `SEQUENCE-GENRE-VOCABULARY`: the four `sequence` directives that are not the
1704
1721
  // connector. Reached only from the `doc.genre==='sequence'` dispatch, so
1705
1722
  // `state` under `statechart` never arrives here. Every option-VALUE check
1706
1723
  // (colours, `style=` enum, `class=` list, `in=` id spelling, `note=` and
@@ -1862,7 +1879,7 @@ function parseOne(text){
1862
1879
  // the dispatch cannot be narrowed to the genre's own word — a `flowline`
1863
1880
  // under `block` would then fall through to `unrecognized line`, which is
1864
1881
  // exactly the answer these rulings owe an author better than.
1865
- // `SEQUENCE-SOURCE-STANDARD`-R182: `message` is the FOURTH spelling scanned here,
1882
+ // `SEQUENCE-GENRE-VOCABULARY`: `message` is the FOURTH spelling scanned here,
1866
1883
  // and it is derived from `CONNECTOR_SPELLINGS` rather than spelled again,
1867
1884
  // so a fifth genre's connector reaches the named diagnostic by joining
1868
1885
  // that set and not by remembering to edit a regex.
@@ -1908,7 +1925,7 @@ function parseOne(text){
1908
1925
  // Directives not in DIRECTIVE_OPTS (title's single quoted string, unknown
1909
1926
  // keywords) are handled by their own paths.
1910
1927
  const badOpts=(k)=>{
1911
- // `SEQUENCE-SOURCE-STANDARD`-R182: the row is read GENRE-FIRST. `state` is one
1928
+ // `SEQUENCE-GENRE-VOCABULARY`: the row is read GENRE-FIRST. `state` is one
1912
1929
  // spelling with two declarations and two option sets (`GENRE-VOCABULARY-OBLIGATION`), and
1913
1930
  // `GENRE_DIRECTIVE_OPTS` is the only place that fact is recorded.
1914
1931
  const allowed=directiveOpts(k,doc.genre);
@@ -2468,7 +2485,7 @@ function parseOne(text){
2468
2485
  continue;
2469
2486
  }
2470
2487
 
2471
- // `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` genre's four own directives.
2488
+ // `SEQUENCE-GENRE-VOCABULARY`: the `sequence` genre's four own directives.
2472
2489
  // Dispatched BEFORE the switch and scoped by `doc.genre`, which is what
2473
2490
  // keeps `state` reaching `statechart`'s node parser under `statechart` —
2474
2491
  // `GENRE-VOCABULARY-OBLIGATION` in the dispatcher, not only in the allowlist.
@@ -2549,8 +2566,10 @@ function parseOne(text){
2549
2566
  // `GENRE-NODE-SPELLING`: `state` joins the same case. It is `node` renamed
2550
2567
  // for one genre, not a role — a statechart node has exactly one kind,
2551
2568
  // so there is no role to record and `role` stays null, exactly as a
2552
- // bare `node` does. The DRAWING is unchanged too (`shape=box` default),
2553
- // which is what let the five corpus figures migrate byte-identically.
2569
+ // bare `node` does. The DRAWING was unchanged too (`shape=box` default),
2570
+ // which is what let the five corpus figures migrate byte-identically;
2571
+ // 0.4 gave `state` its own derived geometry (KW_SHAPE, rounded)
2572
+ // because the box default was making the genre's `SHAPE-ENUM-VOCABULARY` rule unfollowable.
2554
2573
  case 'process': case 'decision': case 'terminator':
2555
2574
  case 'state':
2556
2575
  case 'node': {
@@ -2563,7 +2582,7 @@ function parseOne(text){
2563
2582
  // DRAWING only. §12.7: presentation is not meaning on its own, so
2564
2583
  // `decision q "…" shape=box` is still a decision in the model — the
2565
2584
  // role is the model, the shape is how it happens to be drawn.
2566
- const shape=opts.shape||(role?ROLE_SHAPE[role]:'box');
2585
+ const shape=opts.shape||(role?ROLE_SHAPE[role]:KW_SHAPE[kw]||'box');
2567
2586
  if(RETIRED_SHAPES[shape]){ err(n,RETIRED_SHAPES[shape]); break; }
2568
2587
  if(!SHAPES.includes(shape)){ err(n,'unknown shape "'+shape+'" ('+SHAPES.join('|')+')'); break; }
2569
2588
  if(pos[2]!==undefined&&!posq[2]){ err(n,kw+' label must be quoted: '+kw+' '+id+' "'+pos[2]+'" — '+Q_WHY); break; }
@@ -2976,7 +2995,7 @@ function parseOne(text){
2976
2995
  else if(groupIds.has(e.b)) errs.push('Line '+e.line+': edge endpoint "'+e.b+'" is a group — connect to a member node (group edges are not in v0.1)');
2977
2996
  if(e.plane && !planeIds.has(e.plane)) errs.push('Line '+e.line+': unknown plane "'+e.plane+'"');
2978
2997
  }
2979
- // ── `SEQUENCE-SOURCE-STANDARD`-R182: the `sequence` genre's semantic checks ────────
2998
+ // ── `SEQUENCE-GENRE-VOCABULARY`: the `sequence` genre's semantic checks ────────
2980
2999
  // Everything here needs the WHOLE document, so none of it can live in
2981
3000
  // `parseSeqDirective`: forward references are legal (fixture 021 pins that
2982
3001
  // for the scene genres and the rule is language-wide), so an id can only be
@@ -3025,12 +3044,51 @@ function parseOne(text){
3025
3044
  // is never restated, so a genuine duplicate is always a mistake — and
3026
3045
  // because a transition is DERIVED from an adjacent pair, a reader
3027
3046
  // "tidying duplicates" could otherwise silently delete a fact.
3047
+ //
3048
+ // THE CHECK IS OPERAND-SCOPED (item 35, ruled 2026-08-17).
3049
+ // It used to compare each occurrence with the previous one IN DECLARATION
3050
+ // ORDER and never asked whether the two are reachable together, so an
3051
+ // `alt` whose `granted` operand ends `state c "INIT"` and whose `refused`
3052
+ // operand ends `state c "INIT"` was refused — while AT MOST ONE OF THOSE
3053
+ // TWO EVER HAPPENS, so neither can restate the other. The diagnostic was
3054
+ // right about the sequence and wrong about the figure, and
3055
+ // `examples/sequence/dhcp-lease.fd` carried the fact it could not draw in
3056
+ // a `description=` because of it.
3057
+ //
3058
+ // The scope is the CONTAINER (UML 2.5.1 §17.12.13: a StateInvariant is an
3059
+ // InteractionFragment, and an InteractionOperand contains the fragments
3060
+ // that occur when its branch is taken). So an occurrence is compared with
3061
+ // the most recent occurrence in a scope that ENCLOSES OR IS its own —
3062
+ // itself, its fragment, the document — and never with one in a SIBLING
3063
+ // operand, which is on a path it is exclusive with. Two consequences are
3064
+ // deliberate and are the answer to the "what is the lifeline in after the
3065
+ // fragment" question the item asked: an occurrence in an operand still
3066
+ // restates one written outside it (the outer state is on every path into
3067
+ // the branch), and an occurrence AFTER a fragment is compared with the
3068
+ // last one outside it, because which branch ran is exactly what the
3069
+ // figure does not say. Outside operands nothing changes: the linear
3070
+ // sequence is compared as before.
3071
+ const scopeOwner={};
3072
+ for(const o of doc.operands) scopeOwner[o.id]=o['in']||'';
3073
+ for(const f of doc.fragments) scopeOwner[f.id]=f['in']||'';
3074
+ const chainOf=id=>{
3075
+ const out=[], seen=new Set();
3076
+ let cur=id||'';
3077
+ while(cur&&!seen.has(cur)){ seen.add(cur); out.push(cur); cur=scopeOwner[cur]||''; }
3078
+ out.push('');
3079
+ return out;
3080
+ };
3028
3081
  const lastState={};
3029
3082
  for(const st of doc.states.slice().sort((a,b)=>a.line-b.line)){
3030
- if(lastState[st.ref]===st.name)
3083
+ const chain=chainOf(st['in']);
3084
+ const seen=lastState[st.ref]||(lastState[st.ref]={});
3085
+ let prev=null;
3086
+ for(const sc of chain){ const r=seen[sc]; if(r&&(!prev||r.line>prev.line)) prev=r; }
3087
+ if(prev&&prev.name===st.name)
3031
3088
  errs.push('Line '+st.line+': lifeline "'+st.ref+'" is already in state "'+st.name+
3032
- '" — a state that has not changed is never restated, and a transition is derived from the adjacent pair, so a restatement would assert a transition that did not happen (draft §23.2)');
3033
- lastState[st.ref]=st.name;
3089
+ '" — a state that has not changed is never restated, and a transition is derived from the adjacent pair, so a restatement would assert a transition that did not happen (draft §23.2)'+
3090
+ (doc.operands.length?'. Occurrences in DIFFERENT operands of one fragment are exclusive and do not restate each other; this pair is not that':''));
3091
+ seen[chain[0]]={name:st.name,line:st.line};
3034
3092
  }
3035
3093
  const SM=seqModel(doc);
3036
3094
  // A containment CYCLE is checked before anything that walks the chain, or
@@ -3578,7 +3636,33 @@ function cwMax(s){ return Math.max(...String(s).split('\n').map(cw)); }
3578
3636
  // glyph with it is what lets a reader recognise the box as an aside without a
3579
3637
  // legend entry). It is deliberately unlike a `node`: no rounded corners, a
3580
3638
  // paler wash, smaller type, and a corner no node shape has.
3581
- const NOTE_FS=10, NOTE_PAD=6, NOTE_FOLD=9, NOTE_MAXCH=30;
3639
+ // NOTE_MAXW is the note's CORRIDOR: the widest line of note text the box will
3640
+ // hold, in pixels, measured in the type the note is actually SET in.
3641
+ //
3642
+ // It replaces `NOTE_MAXCH=30`, a CHARACTER count, and the character count was
3643
+ // wrong twice over (item 56a). It was width-blind — thirty `i`s and thirty
3644
+ // `W`s are not one measure — and, worse, the box built around it was sized by
3645
+ // `tw()`, which measures at the NODE font (13 px) and adds the NODE padding.
3646
+ // A note is set at 10 px. So a note wrapped at thirty characters was fitted
3647
+ // into a box a third wider than the text it wrapped for: `annotated-datapath`
3648
+ // broke "Only valid while the port is up." across two lines and then drew it
3649
+ // in a 250 px box with 70 px of empty paper on the right. A line that fits
3650
+ // its corridor now stays on one line, and the box is the text's own width.
3651
+ //
3652
+ // 230 px is chosen to KEEP the box the old rule produced (230 + padding +
3653
+ // fold = 251 px, the width every wide note in the corpus already draws at)
3654
+ // and make the wrap actually mean it. Measured over the whole corpus: the two
3655
+ // short notes lose 60 px of empty box each, "Only valid while the port is up."
3656
+ // goes from two lines to one, and the figure-level note from three to two.
3657
+ const NOTE_FS=10, NOTE_PAD=6, NOTE_FOLD=9, NOTE_MAXW=230;
3658
+ // The note's own per-unit advance: `CH` is calibrated for FONT (13 px), and a
3659
+ // note is set at NOTE_FS. One constant, so the wrap and the box cannot
3660
+ // disagree about how wide a line is.
3661
+ const NOTE_CH=CH*NOTE_FS/FONT;
3662
+ // A bold run is wider than the same glyphs regular. 6% is the usual figure for
3663
+ // a synthesised/duplexed weight and is charged so the target-label prefix
3664
+ // (item 56b) cannot overflow the corridor it was measured against.
3665
+ const NOTE_BOLD=1.06;
3582
3666
  const NOTE_FILL='#fdfaf0', NOTE_STROKE='#c9c4b2', NOTE_INK='#5c584c';
3583
3667
  // The leader is deliberately DARKER than the box outline. Drawn in the box's
3584
3668
  // own stroke it was legible in the SVG and invisible on the page at 1x — a
@@ -3590,24 +3674,46 @@ const NOTE_LEADER='#9c968a';
3590
3674
  // Deterministic greedy word wrap. Author newlines are honoured and never
3591
3675
  // merged; a run longer than the wrap width is broken only between words, so a
3592
3676
  // long identifier keeps its shape and simply widens the box.
3593
- function noteWrap(text){
3594
- const out=[];
3595
- for(const para of String(text).split('\n')){
3596
- const words=para.split(/ +/).filter(w=>w.length);
3597
- if(!words.length){ out.push(''); continue; }
3598
- let cur=words[0];
3599
- for(let i=1;i<words.length;i++){
3600
- if((cur+' '+words[i]).length<=NOTE_MAXCH) cur+=' '+words[i];
3601
- else { out.push(cur); cur=words[i]; }
3602
- }
3603
- out.push(cur);
3677
+ // A wrapped line is a list of RUNS — {t: text, b: bold} — because a note may
3678
+ // open with its target's label in bold (item 56b) and the prefix can wrap into
3679
+ // the body like any other words. A note with no prefix is one regular run per
3680
+ // line, which is what every note was before.
3681
+ function noteRunW(r){ return cw(r.t)*NOTE_CH*(r.b?NOTE_BOLD:1); }
3682
+ function noteLineW(runs){ return runs.reduce((a,r)=>a+noteRunW(r),0); }
3683
+ // Deterministic greedy word wrap, measured in PIXELS against NOTE_MAXW.
3684
+ // Author newlines are honoured and never merged; a single word wider than the
3685
+ // corridor is never broken, so a long identifier keeps its shape and simply
3686
+ // widens the box.
3687
+ function noteWrap(text,prefix){
3688
+ const words=[];
3689
+ if(prefix) for(const w of String(prefix).split(/ +/).filter(w=>w.length)) words.push({t:w,b:true,br:false});
3690
+ const paras=String(text).split('\n');
3691
+ paras.forEach((para,pi)=>{
3692
+ const ws=para.split(/ +/).filter(w=>w.length);
3693
+ if(!ws.length){ words.push({t:'',b:false,br:pi>0}); return; }
3694
+ ws.forEach((w,wi)=>words.push({t:w,b:false,br:pi>0&&wi===0}));
3695
+ });
3696
+ const SPW=cw(' ')*NOTE_CH;
3697
+ const out=[]; let cur=[], curW=0;
3698
+ const push=()=>{ out.push(cur.length?cur:[{t:'',b:false}]); cur=[]; curW=0; };
3699
+ for(const w of words){
3700
+ const ww=cw(w.t)*NOTE_CH*(w.b?NOTE_BOLD:1);
3701
+ if(w.br&&cur.length) push();
3702
+ const sp=cur.length?SPW:0;
3703
+ if(cur.length&&curW+sp+ww>NOTE_MAXW){ push(); }
3704
+ const gap=cur.length?' ':'';
3705
+ const last=cur[cur.length-1];
3706
+ if(last&&last.b===w.b) last.t+=gap+w.t;
3707
+ else cur.push({t:gap+w.t,b:w.b});
3708
+ curW+=(gap?SPW:0)+ww;
3604
3709
  }
3710
+ push();
3605
3711
  return out;
3606
3712
  }
3607
- function noteBox(text){
3608
- const lines=noteWrap(text);
3713
+ function noteBox(text,prefix){
3714
+ const lines=noteWrap(text,prefix);
3609
3715
  const lh=NOTE_FS*1.35;
3610
- const w=Math.max(28, Math.max.apply(null,lines.map(tw))+NOTE_PAD*2+NOTE_FOLD);
3716
+ const w=Math.max(28, Math.max.apply(null,lines.map(noteLineW))+NOTE_PAD*2+NOTE_FOLD);
3611
3717
  const h=lines.length*lh+NOTE_PAD*2-lh*0.15;
3612
3718
  return {w:Math.round(w*100)/100, h:Math.round(h*100)/100, lines, lh};
3613
3719
  }
@@ -3618,13 +3724,51 @@ function noteSvg(x,y,box,carrier){
3618
3724
  const F=NOTE_FOLD, w=box.w, h=box.h;
3619
3725
  const d='M'+x+' '+y+' H'+(x+w-F)+' L'+(x+w)+' '+(y+F)+' V'+(y+h)+' H'+x+' Z';
3620
3726
  const fold='M'+(x+w-F)+' '+y+' V'+(y+F)+' H'+(x+w)+' Z';
3621
- const out=['<g class="fd-note"'+(carrier&&carrier.kind?' data-note-on="'+carrier.kind+'"':'')+'>',
3727
+ // `data-note-on` names the KIND; `data-note-for` names the TARGET (item 40b).
3728
+ // Without the second attribute a machine reader holding only the drawing
3729
+ // cannot recover WHICH element a note is about — it can see that a note is
3730
+ // about "a group" and no more — so the association the source states was
3731
+ // lost on the way to the page even when the placement was perfect. The pair
3732
+ // (kind, ref) is unambiguous: `ref` is the element's identity in this very
3733
+ // drawing — a `data-node` id, a `data-group` id, or the `data-edge` line
3734
+ // number a connector is keyed by, since a connector has no id to carry.
3735
+ // `title` is the one kind with no ref and needs none: it names the FIGURE,
3736
+ // and there is exactly one. The attribute changes no pixel.
3737
+ const ref=carrier&&carrier.ref!==undefined&&carrier.ref!==null?' data-note-for="'+esc(String(carrier.ref))+'"':'';
3738
+ const out=['<g class="fd-note"'+(carrier&&carrier.kind?' data-note-on="'+carrier.kind+'"':'')+ref+'>',
3622
3739
  '<path d="'+d+'" fill="'+NOTE_FILL+'" stroke="'+NOTE_STROKE+'" stroke-width="1"/>',
3623
3740
  '<path d="'+fold+'" fill="'+NOTE_STROKE+'" fill-opacity="0.35" stroke="'+NOTE_STROKE+'" stroke-width="1"/>'];
3624
3741
  const first=y+NOTE_PAD+NOTE_FS*0.85;
3742
+ // A line is a list of RUNS (item 56b): the target-label prefix is bold, the
3743
+ // note's own words are regular. One `<text>` per line either way, so a note
3744
+ // with no prefix emits exactly what it always did but for the tspan wrapper
3745
+ // — and a single regular run is written bare, so those notes are unchanged
3746
+ // byte for byte.
3625
3747
  box.lines.forEach((ln,i)=>{
3626
- out.push('<text x="'+(x+NOTE_PAD)+'" y="'+Math.round((first+i*box.lh)*100)/100+
3627
- '" font-size="'+NOTE_FS+'" text-anchor="start" fill="'+NOTE_INK+'">'+esc(ln)+'</text>');
3748
+ const yy=Math.round((first+i*box.lh)*100)/100;
3749
+ const runs=Array.isArray(ln)?ln:[{t:ln,b:false}];
3750
+ let body;
3751
+ if(runs.length===1&&!runs[0].b) body=esc(runs[0].t);
3752
+ else {
3753
+ // EVERY RUN CARRIES ITS OWN `x`. A bare `<tspan>` is supposed to
3754
+ // continue where the last one stopped, and browsers do that — but a
3755
+ // note is an ARTIFACT that outlives this engine and gets rasterised by
3756
+ // whatever the reader has. Two library rasterisers restart each tspan
3757
+ // at the parent's `x`, which draws the prefix and the sentence on top
3758
+ // of each other. The advance is already measured (the wrap measured it
3759
+ // to decide this line), so it is written down rather than inferred.
3760
+ let off=0; const parts=[];
3761
+ for(const r of runs){
3762
+ const lead=/^ /.test(r.t)?1:0, t=lead?r.t.slice(1):r.t;
3763
+ off+=lead*cw(' ')*NOTE_CH;
3764
+ parts.push('<tspan x="'+Math.round((x+NOTE_PAD+off)*100)/100+'" y="'+yy+'"'+
3765
+ (r.b?' font-weight="600"':'')+'>'+esc(t)+'</tspan>');
3766
+ off+=cw(t)*NOTE_CH*(r.b?NOTE_BOLD:1);
3767
+ }
3768
+ body=parts.join('');
3769
+ }
3770
+ out.push('<text x="'+(x+NOTE_PAD)+'" y="'+yy+
3771
+ '" font-size="'+NOTE_FS+'" text-anchor="start" fill="'+NOTE_INK+'">'+body+'</text>');
3628
3772
  });
3629
3773
  out.push('</g>');
3630
3774
  return out.join('');
@@ -3632,7 +3776,7 @@ function noteSvg(x,y,box,carrier){
3632
3776
  // The leader is drawn ONLY when adjacency failed, and it is drawn AFTER the
3633
3777
  // box is placed, so it is correct by construction: it runs from the box edge
3634
3778
  // facing the carrier to the carrier's nearest point, and cannot be stale.
3635
- function noteLeader(best,box,rect){
3779
+ function noteLeaderPts(best,box,rect){
3636
3780
  const bx=best.x, by=best.y, bw=box.w, bh=box.h;
3637
3781
  const cx=rect.x+rect.w/2, cy=rect.y+rect.h/2;
3638
3782
  let x1,y1;
@@ -3644,7 +3788,15 @@ function noteLeader(best,box,rect){
3644
3788
  // thing it points at
3645
3789
  const x2=Math.max(rect.x, Math.min(rect.x+rect.w, x1));
3646
3790
  const y2=Math.max(rect.y, Math.min(rect.y+rect.h, y1));
3647
- return '<line x1="'+x1+'" y1="'+y1+'" x2="'+(rect.w||rect.h?x2:cx)+'" y2="'+(rect.w||rect.h?y2:cy)+
3791
+ return [[x1,y1],[rect.w||rect.h?x2:cx, rect.w||rect.h?y2:cy]];
3792
+ }
3793
+ // A LEADER IS INK AND A LATER NOTE MUST YIELD TO IT (item 40). The pass hands
3794
+ // the drawn segment back so the notes placed after this one are charged for
3795
+ // crossing it — a leader covered by the next note's box is a leader that is
3796
+ // not there, which is the same defect the LEADER's own colour was fixed for.
3797
+ function noteLeader(best,box,rect){
3798
+ const [p,q]=noteLeaderPts(best,box,rect);
3799
+ return '<line x1="'+p[0]+'" y1="'+p[1]+'" x2="'+q[0]+'" y2="'+q[1]+
3648
3800
  '" stroke="'+NOTE_LEADER+'" stroke-width="1" stroke-dasharray="4 3"/>';
3649
3801
  }
3650
3802
  // A band's optional edge stroke. `renderScene` has had this as a local since
@@ -4171,6 +4323,22 @@ function renderScene(doc,y0){
4171
4323
  // decided after, and a figure that suppresses and then declines draws
4172
4324
  // straight through its own boxes (bfd-session: score 30 -> 35 with a new
4173
4325
  // `thru`). That belongs with item 27's ordering change, priced.
4326
+ // THE ADMISSIBILITY KEY, WRITTEN OUT (item 60). Members share a trunk only
4327
+ // if they share the target, the label, the stroke, the dash AND THE CLASS
4328
+ // SET. The first four were always tested; the class was implied by them,
4329
+ // because the class cascade has already resolved `stroke=` and `style=` onto
4330
+ // the edge by the time this runs — but "implied" is not "stated", and two
4331
+ // classes that happen to paint alike are still two meanings. So the key says
4332
+ // it. Same class (or all unclassed with identical labels) → admissible;
4333
+ // MIXED CLASSES → refused, which is item 46's refusal and the reason
4334
+ // `bfd-session`'s three returns into DOWN (advance/fail/admin, three
4335
+ // different sentences) stay three lanes while its three `admin disable`
4336
+ // transitions become one trunk. Narrowing only: no group admitted before is
4337
+ // admitted less.
4338
+ const clsKey=x=>{
4339
+ const ids=(x.cls===undefined||x.cls===null)?[]:(Array.isArray(x.cls)?x.cls:[x.cls]);
4340
+ return ids.slice().sort().join(',');
4341
+ };
4174
4342
  const busGroups=[];
4175
4343
  {
4176
4344
  const g=new Map();
@@ -4179,11 +4347,52 @@ function renderScene(doc,y0){
4179
4347
  if(!A||!B||e.a===e.b||isBack.has(e)) continue;
4180
4348
  if(e.op!=='->'||e.tail||e.head) continue;
4181
4349
  if(pinned(e.a)||pinned(e.b)||B.rank<=A.rank) continue;
4182
- const k=e.b+' '+(e.mid||'')+' '+(e.stroke||'')+' '+(e.style||'');
4350
+ const k=e.b+' '+(e.mid||'')+' '+(e.stroke||'')+' '+(e.style||'')+' '+clsKey(e);
4183
4351
  if(!g.has(k)) g.set(k,[]); g.get(k).push(e);
4184
4352
  }
4185
4353
  for(const [,m] of g) if(m.length>=3) busGroups.push(m);
4186
4354
  }
4355
+ // ── RETURN MERGE BUS (item 46, and item 26's >=3 rule reaching the RETURNS) ──
4356
+ // The forward bus (above) collapses three or more arrows arriving at one
4357
+ // target into one trunk. The same statement is made just as often by RETURN
4358
+ // edges — N states falling back to one — and the forward construct cannot
4359
+ // reach them, because a return is drawn by the side-channel plan and not by
4360
+ // the straight router (item 26 recorded `patterns/state-b`'s four `reset`
4361
+ // edges as exactly this decline). `state-b` draws four CONCENTRIC RINGS, each
4362
+ // labelled "reset", 818 px wide for a 500 px figure: four copies of one
4363
+ // sentence.
4364
+ //
4365
+ // A return bus is the ring stack COLLAPSED ONTO ITS INNERMOST RING — not a
4366
+ // new geometry. Every member drops from its own source to the shared rail,
4367
+ // the rail and the trunk and the entry point are the innermost member's, one
4368
+ // arrowhead lands on the target and one label rides the shared run. The
4369
+ // members' own drops stay distinct and carry the junction dots, so the reader
4370
+ // still counts the lines. Because the collapsed route is a route the
4371
+ // innermost member already drew, no member can gain a crossing the figure did
4372
+ // not already have — which is why this construct needs no adoption test where
4373
+ // the forward rail (a NEW line across the figure) does.
4374
+ //
4375
+ // The admission rule is the forward bus's, unchanged, because the reasons are
4376
+ // the same: ONE label (a trunk draws one, so members that say different things
4377
+ // may not share it), ONE stroke and ONE dash (the trunk is stroked once per
4378
+ // member; three colours on one line is three claims about one stroke, and in a
4379
+ // classed figure those colours carry the legend's meaning), no endpoint
4380
+ // labels, distinct sources. Measured over the corpus, exactly one group
4381
+ // qualifies and two are refused for stated reasons — see the DONE note on 46.
4382
+ const retBusGroups=[];
4383
+ {
4384
+ const g=new Map();
4385
+ for(const e of doc.edges){
4386
+ const A=byId[e.a], B=byId[e.b];
4387
+ if(!A||!B||e.a===e.b||!isBack.has(e)) continue;
4388
+ if(e.op!=='->'||e.tail||e.head) continue;
4389
+ if(pinned(e.a)||pinned(e.b)) continue; // the channel plan skips those
4390
+ const k=e.b+' '+(e.mid||'')+' '+(e.stroke||'')+' '+(e.style||'')+' '+clsKey(e);
4391
+ if(!g.has(k)) g.set(k,[]); g.get(k).push(e);
4392
+ }
4393
+ for(const [,m] of g)
4394
+ if(m.length>=3&&new Set(m.map(e=>e.a)).size===m.length) retBusGroups.push(m);
4395
+ }
4187
4396
  for(const e of doc.edges){
4188
4397
  const A=byId[e.a], B=byId[e.b];
4189
4398
  if(!A||!B||isBack.has(e)) continue;
@@ -4492,6 +4701,165 @@ function renderScene(doc,y0){
4492
4701
  if(o){ n.x=o.x+p.fx; n.y=o.y+p.fy; }
4493
4702
  else { n.x=p.fx; n.y=y0+20+p.fy; }
4494
4703
  }
4704
+ // ── CORRIDOR BUDGETING (item 44) ─────────────────────────────────────────
4705
+ // A SEAM IS ASKED WHAT LIVES IN IT. Until this pass, every gap in a scene —
4706
+ // between two ranks, between two neighbours in one rank — was derived from
4707
+ // NODE GEOMETRY ALONE: `GAPX`/`GAPY` plus, for horizontal flow only, the
4708
+ // width of a mid label that rides on the edge. Nothing else in the drawing
4709
+ // was ever asked for its area. But a gap is where a figure keeps most of its
4710
+ // non-node ink: endpoint labels, bundle lassos and their captions, and the
4711
+ // padded band a group draws around its members (whose TOP strip, `BAND.t`,
4712
+ // exists precisely to hold the group's name). The reference topology figure
4713
+ // is what that blindness costs — measured on the 0.4 artifact, the
4714
+ // spine→leaf corridor was 4 px of clearance asked to house three lassos
4715
+ // (2 x ry 26 each), eight endpoint labels, two bundle captions and the
4716
+ // `Leaf` band's whole label strip; the l1—l2 gap was 56 px asked to house a
4717
+ // 92 px-wide lasso, which therefore ate both node boxes.
4718
+ //
4719
+ // THE MODEL. For each seam the demand is derived FIRST, from ink alone —
4720
+ // no coordinate is read to compute it:
4721
+ // need = max( bandGap , max(lasso, endpointLabels) + nameStrip )
4722
+ // `bandGap` is what the two sides' group BANDS need of each other: the
4723
+ // padding each projects into the seam plus `SEP_BAND` of white, so two bands
4724
+ // read as two (nothing when one group spans the seam — its band covers the
4725
+ // seam anyway). `lasso` is the breadth a bundle ring needs to cross the seam
4726
+ // without reaching a node box, from the ring's own MINIMUM radii.
4727
+ // `endpointLabels` is the tail/head labels an edge through the seam must
4728
+ // stack. `nameStrip` is the ONE part of a band that is ink rather than
4729
+ // backdrop — the strip carrying the group's NAME.
4730
+ //
4731
+ // WHY MAX AND NOT SUM. A band is a BACKDROP: every figure in this corpus
4732
+ // draws edges across one, and a lasso crossing a band's fill is ordinary
4733
+ // layering, not a collision. So the band requirement and the free-ink
4734
+ // requirement are two claims on the same span and the binding one is the
4735
+ // larger — only the band's NAME is ink the free ink must clear, and that is
4736
+ // the term which adds. Summing them was built and measured first: it put the
4737
+ // reference figure's corridor at 108 px, which then DETACHED the endpoint
4738
+ // labels from their ports (they are anchored at a FRACTION of edge length —
4739
+ // item 42 — so they drift as the seam deepens) and cost four new F5
4740
+ // label-association defects on a figure that had none. A seam wide enough to
4741
+ // break the ink it was widened for is the wrong answer; item 42's fixed-
4742
+ // distance anchoring is what would lift that ceiling.
4743
+ //
4744
+ // IT IS APPLIED TO THE REALISED SEAM, NOT TO `mainGap`. A pre-coordinate
4745
+ // widening cannot see a PIN: pins are absolute canvas coordinates, applied
4746
+ // above, and the reference figure's spine pin spends 40 px of its own rank's
4747
+ // gap — a `mainGap` bumped to 108 would have produced a 68 px corridor and
4748
+ // reported success. So the demand is measured against the geometry that
4749
+ // exists, here, after the pins have had their say.
4750
+ //
4751
+ // THREE THINGS IT DOES NOT DO, ON PURPOSE. It never moves a PINNED node
4752
+ // (the group-band precedent: the coordinate is the author's word). It never
4753
+ // NARROWS a seam — an adequate seam is left bit-for-bit alone, which is why
4754
+ // 31 of the corpus's 34 scene figures are byte-identical across this change.
4755
+ // And it changes no ROUTE and no SHAPE: edge paths, lasso radii and label
4756
+ // anchors are all computed downstream from these coordinates and are
4757
+ // untouched — they simply get room. The lasso that is still drawn as a
4758
+ // near-circle regardless of its members' direction is item 43; the endpoint
4759
+ // label still anchored by fraction rather than distance is item 42; the note
4760
+ // and element-label association frontiers are items 40 and 45. This pass
4761
+ // buys those fixes the space they need and deliberately leaves them open.
4762
+ //
4763
+ // WHERE IT DECLINES. If two ranks OVERLAP on the main axis — the author
4764
+ // pinned them into each other, or into a different order than the ranking —
4765
+ // there is no seam to budget and the pass says nothing. 39 of the corpus's
4766
+ // 204 seams are that shape, all of them in substantially pinned scenes.
4767
+ {
4768
+ const SEP_BAND=6, // white left between two distinct group bands
4769
+ LASSO_CLEAR=6, // a bundle ring's clearance from a node box
4770
+ RY_MIN=26, RX_MIN=46, // the ring's own floor radii (see doc.trunks)
4771
+ EPL_H=13, EPL_PAD=4; // an endpoint label's line box and its gutter
4772
+ const mLo=n=>horiz?n.x:n.y, mSz=n=>horiz?n.w:n.h;
4773
+ const cLo=n=>horiz?n.y:n.x, cSz=n=>horiz?n.h:n.w;
4774
+ const mvM=(n,d)=>{ if(horiz) n.x+=d; else n.y+=d; };
4775
+ const mvC=(n,d)=>{ if(horiz) n.y+=d; else n.x+=d; };
4776
+ const ranked=nodes.filter(n=>!n.boundary&&n.rank!==undefined);
4777
+ const byRank=new Map();
4778
+ for(const n of ranked){ if(!byRank.has(n.rank)) byRank.set(n.rank,[]); byRank.get(n.rank).push(n); }
4779
+ // Ranks are ordered by where they ACTUALLY sit, not by their index: `flow
4780
+ // up`/`flow left` mirror the main axis after placement, so rank order and
4781
+ // coordinate order are opposite there, and a seam is a fact about the
4782
+ // drawing.
4783
+ const rMid=r=>{ const a=byRank.get(r); return a.reduce((s,n)=>s+mLo(n)+mSz(n)/2,0)/a.length; };
4784
+ const rks=[...byRank.keys()].sort((a,b)=>rMid(a)-rMid(b));
4785
+ // A group's rank span, so a band that runs THROUGH a seam asks for nothing.
4786
+ const gSpan={};
4787
+ for(const g of doc.groups){
4788
+ const m=ranked.filter(n=>n.group===g.id); if(!m.length) continue;
4789
+ gSpan[g.id]={lo:Math.min(...m.map(n=>n.rank)), hi:Math.max(...m.map(n=>n.rank))};
4790
+ }
4791
+ const lblW=s=>(s===null||s===undefined||s==='')?0:lblPx(s);
4792
+ // ── main axis: rank against rank ──────────────────────────────────────
4793
+ for(let k=0;k+1<rks.length;k++){
4794
+ const i=rks[k], j=rks[k+1];
4795
+ const hiI=Math.max(...byRank.get(i).map(n=>mLo(n)+mSz(n)));
4796
+ const loJ=Math.min(...byRank.get(j).map(n=>mLo(n)));
4797
+ const actual=loJ-hiI;
4798
+ if(actual<0) continue; // ranks interleave: not a seam
4799
+ let bA=0,bB=0;
4800
+ for(const id in gSpan){ const s=gSpan[id];
4801
+ if(s.lo<=i&&s.hi>=j) continue; // the band spans the seam itself
4802
+ if(s.hi===i) bA=Math.max(bA,horiz?BAND.r:BAND.b);
4803
+ if(s.lo===j) bB=Math.max(bB,horiz?BAND.l:BAND.t);
4804
+ }
4805
+ const bandGap=bA+bB+((bA&&bB)?SEP_BAND:0);
4806
+ // The one piece of band padding that is INK rather than backdrop: under
4807
+ // vertical flow the lower group's `BAND.t` strip is where its NAME is
4808
+ // written, and a lasso or a label drawn through it lands on that name.
4809
+ // Under horizontal flow the name strip is on the cross axis, so a
4810
+ // main-axis seam does not contain it and the guard is nothing.
4811
+ const guard=horiz?0:bB;
4812
+ const spans=(a,b)=>{ const A=byId[a],B=byId[b];
4813
+ return A&&B&&A.rank!==undefined&&B.rank!==undefined
4814
+ &&Math.min(A.rank,B.rank)<=i&&Math.max(A.rank,B.rank)>=j; };
4815
+ // A ONE-MEMBER bundle draws no ring (item 53), so it asks the seam for
4816
+ // no ring breadth. Its caption is placed by the collision-aware label
4817
+ // pass, which can use any white the figure already has.
4818
+ let lasso=0;
4819
+ for(const t of doc.trunks||[]) if(t.pairs.length>1) for(const [a,b] of t.pairs) if(spans(a,b))
4820
+ lasso=Math.max(lasso, 2*(horiz?RX_MIN:RY_MIN)+2*LASSO_CLEAR,
4821
+ horiz?lblW(t.label)+2*LASSO_CLEAR:0);
4822
+ let epl=0;
4823
+ for(const e of doc.edges){ if(!spans(e.a,e.b)) continue;
4824
+ const c=(e.tail?1:0)+(e.head?1:0); if(!c) continue;
4825
+ epl=Math.max(epl, c*EPL_H+(c+1)*EPL_PAD); }
4826
+ const d=Math.max(bandGap, Math.max(lasso,epl)+guard)-actual;
4827
+ if(d<=0) continue;
4828
+ // Everything at or beyond the far lip travels; a pinned node holds its
4829
+ // ground. The movers are selected by POSITION, not by rank membership:
4830
+ // boundary anchors and long-edge waypoints have ranks of their own that
4831
+ // may hold no drawn node at all, and selecting by rank left the
4832
+ // reference figure's `WAN` anchor behind while the leaf rank it hangs
4833
+ // off moved 86 px away — the external's label then landed on the leaf
4834
+ // group's name. `actual >= 0` guarantees no near-side node is past the
4835
+ // lip, so this cannot pick up the rank the seam is measured from.
4836
+ for(const n of lay) if(mLo(n)>=loJ-0.001&&!(n.id&&pinned(n.id))) mvM(n,d);
4837
+ }
4838
+ // ── cross axis: neighbour against neighbour inside one rank ───────────
4839
+ for(const r of rks){
4840
+ const lane=byRank.get(r).slice().sort((a,b)=>cLo(a)-cLo(b));
4841
+ for(let q=0;q+1<lane.length;q++){
4842
+ const A=lane[q], B=lane[q+1];
4843
+ const actual=cLo(B)-(cLo(A)+cSz(A));
4844
+ if(actual<0) continue;
4845
+ let bandGap=0, guard=0;
4846
+ if(A.group!==B.group){
4847
+ const pa=A.group?(horiz?BAND.b:BAND.r):0, pb=B.group?(horiz?BAND.t:BAND.l):0;
4848
+ bandGap=pa+pb+((pa&&pb)?SEP_BAND:0);
4849
+ guard=horiz?pb:0; // the name strip, on the cross axis this time
4850
+ }
4851
+ let lasso=0;
4852
+ for(const t of doc.trunks||[]) if(t.pairs.length>1) for(const [a,b] of t.pairs)
4853
+ if((a===A.id&&b===B.id)||(a===B.id&&b===A.id))
4854
+ lasso=Math.max(lasso, 2*(horiz?RY_MIN:RX_MIN)+2*LASSO_CLEAR,
4855
+ horiz?0:lblW(t.label)+2*LASSO_CLEAR);
4856
+ const d=Math.max(bandGap, lasso?lasso+guard:0)-actual;
4857
+ if(d<=0) continue;
4858
+ const from=cLo(B);
4859
+ for(const n of lay) if(n.rank===r&&cLo(n)>=from&&!(n.id&&pinned(n.id))) mvC(n,d);
4860
+ }
4861
+ }
4862
+ }
4495
4863
  // ── GROUP BAND CONTIGUITY ────────────────────────────────────────────────
4496
4864
  // A group's band is the BOUNDING BOX of its members (see gBox below), and
4497
4865
  // until this pass nothing checked that the box contained only members. A
@@ -4643,6 +5011,55 @@ function renderScene(doc,y0){
4643
5011
  if(mem.length) gOrigin[g.id]={x:Math.min(...mem.map(n=>n.x)),
4644
5012
  y:Math.min(...mem.map(n=>n.y))};
4645
5013
  }
5014
+ // ── A NODE THAT COVERS ANOTHER COMPLETELY IS A FALSE DRAWING (item 47b) ──
5015
+ // The group-band precedent, one construct over. There the rule is: whoever
5016
+ // chose the position bears responsibility, and an author pin that forces a
5017
+ // drawing to state something the source does not is a GEOMETRY-TIME error,
5018
+ // not a lint number. `examples/rpf-check.fd` is the case that asked the
5019
+ // question: `pin drop at=(-30,0)` aged against a moving layout until
5020
+ // `Drop (RPF fail)` sat entirely ON `Accept and forward` — PIN ROT — and the
5021
+ // covered node was not merely crowded but INVISIBLE, which is the line
5022
+ // between "ugly is not an error" and "wrong is". PARTIAL overlap stays on
5023
+ // the `novlp` axis and is never an error: two boxes that clip each other are
5024
+ // ugly and both readable, and drawing tools let them.
5025
+ //
5026
+ // THE MEASUREMENT NARROWED THE RULE, AND THE NARROWING IS THE FINDING.
5027
+ // Over the corpus (59 figures, 231 nodes, 1640 ordered node pairs) full
5028
+ // containment occurs 28 times and every one of them is `examples/rainbow.fd`
5029
+ // — seven concentric pinned ellipses around a pinned core, the figure whose
5030
+ // entire subject is that DOCUMENT ORDER IS PAINT ORDER (`PAINT-ORDER-CONSTRUCT`). So the
5031
+ // premise a blanket rule would rest on ("if the cover is intentional the
5032
+ // figure cannot state it — there is no z-order construct") is FALSE in this
5033
+ // language: line order is that construct, and this corpus ships its
5034
+ // reference figure. What distinguishes rainbow from rpf-check is not the
5035
+ // geometry, which is identical, but WHO CHOSE IT: rainbow's covered node is
5036
+ // pinned by the author on its own line, while rpf-check's was placed by the
5037
+ // engine and drifted underneath. So the error fires when the cover is not
5038
+ // wholly the author's: at least one of the two boxes is at a coordinate the
5039
+ // author never wrote. Both pinned = an author statement in the one paint
5040
+ // order the language has, and it is drawn.
5041
+ {
5042
+ const real=nodes.filter(n=>!n.boundary&&n.w>0&&n.h>0);
5043
+ const inside=(a,b)=>a.x>=b.x-0.01&&a.y>=b.y-0.01
5044
+ &&a.x+a.w<=b.x+b.w+0.01&&a.y+a.h<=b.y+b.h+0.01;
5045
+ const covered=new Set();
5046
+ for(const a of real) for(const b of real){
5047
+ if(a===b||covered.has(a.id+' '+b.id)) continue;
5048
+ if(!inside(a,b)) continue;
5049
+ if(pinned(a.id)&&pinned(b.id)) continue; // both coordinates are the author's
5050
+ covered.add(a.id+' '+b.id);
5051
+ const who=pinned(b.id)?b.id:(pinned(a.id)?a.id:null);
5052
+ const ln=who!==null?srcLine(doc.pins[who].line):srcLine(a.line);
5053
+ gErrs.push('Line '+ln+': '+(who!==null?'pin puts':'the layout puts')+' "'+b.id+'" completely over "'
5054
+ +a.id+'" — a node drawn entirely inside another is invisible, so the figure states that "'
5055
+ +a.id+'" is not there. '+(who!==null
5056
+ ? 'Move the pin off "'+a.id+'", or pin "'+a.id+'" too if the cover is deliberate — '
5057
+ +'document order is paint order (`PAINT-ORDER-CONSTRUCT`), so two author-placed boxes may overlap however '
5058
+ +'the author says.'
5059
+ : 'Pin one of them clear of the other.')
5060
+ +' Partial overlap is not this error; only a complete cover is.');
5061
+ }
5062
+ }
4646
5063
  // Boundary adjacency in pinned scenes (presentation-only): auto-layout ranks
4647
5064
  // a degree-1 boundary relative to the free lanes, so in a scene where the
4648
5065
  // real content is pinned to a compact box the boundary can drift to a far
@@ -4715,9 +5132,83 @@ function renderScene(doc,y0){
4715
5132
  // drawn as a full concentric ring — drop row, channel, return row and hub
4716
5133
  // entry nested in the same order, entering the hub's top edge on the
4717
5134
  // channel side — so fan-in hubs (N states -> IDLE reset) have no crossings.
5135
+ // ── A RECIPROCAL PAIR RUNS ANTIPARALLEL-ADJACENT (item 58) ───────────────
5136
+ // `A -> B` and `B -> A` between one node pair are ONE EXCHANGE: request
5137
+ // beside reply, and reading it means reading them together. The engine
5138
+ // already had the drawing — `apOff` below fans a same-pair straight group
5139
+ // onto opposite sides of its own centre line, and the label pass puts each
5140
+ // label on the OUTER flank of its own stroke — but it could not reach the
5141
+ // common case, because the second direction of any pair CLOSES A CYCLE and
5142
+ // is therefore a back edge, which the channel plan takes and routes the
5143
+ // long way round the figure. `showcase/arp-resolution` is the case: the ARP
5144
+ // reply left Host B, ran down under the whole figure and climbed back into
5145
+ // Host A, 236 px of detour to say the thing the request says in 100.
5146
+ //
5147
+ // So a reciprocal partner is EXEMPTED FROM THE CHANNEL PLAN and drawn
5148
+ // straight, which puts both members into `apOff` and gives the pair its
5149
+ // two adjacent lines. Note what is NOT touched: `isBack` itself. That set
5150
+ // ranks the figure — it is what breaks the cycle so the layers can be
5151
+ // computed at all — and a rank DAG with the cycle put back has no layering.
5152
+ // This is a ROUTING exemption and nothing else, so it is a second set that
5153
+ // the three routing decisions consult and the ranking never sees.
5154
+ //
5155
+ // THE PAIR MUST BE EXACTLY A PAIR: one edge each way, neither a self-loop,
5156
+ // and the forward member drawn straight itself (a multi-rank forward edge
5157
+ // rides a waypoint chain, and a chain has no single centre line to fan a
5158
+ // partner about). Anything else is a different figure and keeps the routing
5159
+ // it had.
5160
+ const recip=new Set();
5161
+ {
5162
+ const dir=new Map();
5163
+ for(const e of doc.edges){
5164
+ if(!byId[e.a]||!byId[e.b]||e.a===e.b) continue;
5165
+ const k=e.a+'\t'+e.b;
5166
+ if(!dir.has(k)) dir.set(k,[]); dir.get(k).push(e);
5167
+ }
5168
+ // A MERGE BUS OUTRANKS A PAIR. `state_a -> idle` is BOTH the return
5169
+ // half of a reciprocal pair AND one of four returns that item 46 merges
5170
+ // into one trunk, and only one of the two drawings can be on the page.
5171
+ // The bus wins, on its own argument: it says something about FOUR edges
5172
+ // ("all of these fall back to one place") that the pairwise reading
5173
+ // cannot say, and `patterns/state-b` measured 397 ink/edge as four
5174
+ // concentric rings against 101 as four straight lines — but the four
5175
+ // straight lines are four separate statements where the figure makes
5176
+ // one. Taking the pair here would also have silently deleted item 54's
5177
+ // acceptance figure.
5178
+ const inBus=new Set();
5179
+ for(const m of busGroups) for(const e of m) inBus.add(e);
5180
+ for(const m of retBusGroups) for(const e of m) inBus.add(e);
5181
+ // EACH LABEL MUST FIT BESIDE ITS OWN LINE. This is not a nicety bolted
5182
+ // on: it is the second half of the direction ("labels on outer flanks,
5183
+ // each label unambiguously beside its own line"), and a label longer
5184
+ // than the line it names cannot satisfy it — it overhangs both ends and
5185
+ // lands on whatever is past them. Measured: `statechart/bfd-session`'s
5186
+ // `INIT -> DOWN` carries a 200 px two-line label on an 80 px run, and
5187
+ // forcing the pair there cost the figure 3 new label collisions, 3
5188
+ // coincident lines and a label emitted off the canvas. 1.25 is the
5189
+ // allowance — a quarter of the run may overhang, which is what a label
5190
+ // centred on a short link needs and what a label that has nothing to do
5191
+ // with the link exceeds.
5192
+ const RECIP_FIT=1.25;
5193
+ const fits=(e,len)=>!e.mid||lblPx(e.mid)<=len*RECIP_FIT;
5194
+ for(const [k,fwd] of dir){
5195
+ const [a,b]=k.split('\t');
5196
+ const rev=dir.get(b+'\t'+a);
5197
+ if(!rev||fwd.length!==1||rev.length!==1) continue;
5198
+ if(chains.get(fwd[0])||chains.get(rev[0])) continue;
5199
+ if(inBus.has(fwd[0])||inBus.has(rev[0])) continue;
5200
+ const A=byId[a], B=byId[b];
5201
+ const p=borderPoint(A,B.x+B.w/2,B.y+B.h/2), q=borderPoint(B,A.x+A.w/2,A.y+A.h/2);
5202
+ const len=Math.hypot(q[0]-p[0],q[1]-p[1]);
5203
+ if(!fits(fwd[0],len)||!fits(rev[0],len)) continue;
5204
+ recip.add(fwd[0]); recip.add(rev[0]);
5205
+ }
5206
+ }
5207
+ // A back edge the routing treats as straight, for item 58's reason.
5208
+ const chBack=e=>isBack.has(e)&&!recip.has(e);
4718
5209
  const chPlan=new Map(); let chTop=0, chShift=0;
4719
5210
  {
4720
- const chList=doc.edges.filter(e=>byId[e.a]&&byId[e.b]&&isBack.has(e)&&!pinned(e.a)&&!pinned(e.b));
5211
+ const chList=doc.edges.filter(e=>byId[e.a]&&byId[e.b]&&chBack(e)&&!pinned(e.a)&&!pinned(e.b));
4721
5212
  const near=e=>{ const A=byId[e.a]; return horiz?A.y+A.h/2:A.x+A.w/2; };
4722
5213
  const order=chList.map((e,i)=>({e,i}));
4723
5214
  order.sort((p,q)=>near(q.e)-near(p.e)||p.i-q.i);
@@ -4765,6 +5256,45 @@ function renderScene(doc,y0){
4765
5256
  const m=g.length;
4766
5257
  g.forEach((e,k)=>{ chPlan.get(e).ef=(m-k)/(m+1); });
4767
5258
  }
5259
+ // RETURN BUS COLLAPSE (item 46). Every member of an admitted group takes
5260
+ // the INNERMOST member's ring, slot, entry point and entry fraction, so the
5261
+ // rail, the trunk and the arrival are one line instead of N nested ones.
5262
+ // Deterministic: the innermost member is the one the sort above already put
5263
+ // closest to the channel (lowest ring; ties by document order). The LAST
5264
+ // member in document order draws the arrowhead, the junction dots and the
5265
+ // single label; every other member draws its path only. The label rides the
5266
+ // SHARED run rather than one member's source stub — a stub label would say
5267
+ // the word names that one member, and what the bus asserts is that all of
5268
+ // them say it.
5269
+ //
5270
+ // A group whose members disagree about `ringOK` is not collapsed: the two
5271
+ // route forms enter the target on different edges of the box, so a part-ring
5272
+ // part-channel bus would be two trunks, not one.
5273
+ for(const m of retBusGroups){
5274
+ if(!m.every(e=>chPlan.has(e))) continue;
5275
+ const P0=chPlan.get(m.reduce((a,b)=>chPlan.get(a).ring<=chPlan.get(b).ring?a:b));
5276
+ if(!m.every(e=>chPlan.get(e).ringOK===P0.ringOK)) continue;
5277
+ // Two roles, and they are not the same member. The LABEL goes to the
5278
+ // member whose own leg into the trunk is LONGEST — the forward bus's rule
5279
+ // verbatim, and the reason is the same: the longest leg is the one whose
5280
+ // longest segment is the shared rail, so the word lands on ink every
5281
+ // member draws instead of on the return row above the figure (where the
5282
+ // canvas, which grows right and down only, clips it). The ARROWHEAD and
5283
+ // the junction dots go to the LAST member in document order, because the
5284
+ // dots can only be drawn once every member's own join point exists.
5285
+ const T=byId[m[0].b], tc=horiz?T.y+T.h/2:T.x+T.w/2;
5286
+ let lead=m[0], bestD=-1;
5287
+ for(const e of m){
5288
+ const A2=byId[e.a], d=Math.abs((horiz?A2.y+A2.h/2:A2.x+A2.w/2)-tc);
5289
+ if(d>bestD+0.5){ bestD=d; lead=e; }
5290
+ }
5291
+ const last=m[m.length-1];
5292
+ for(const e of m){
5293
+ const P=chPlan.get(e);
5294
+ P.ring=P0.ring; P.slot=P0.slot; P.ex=P0.ex; P.ef=P0.ef;
5295
+ P.bus=e.b; P.busLead=(e===lead); P.busTail=(e===last);
5296
+ }
5297
+ }
4768
5298
  // ring return rows run above the top rank; shift the whole scene down
4769
5299
  // when they would spill into the title band. The shift is uniform
4770
5300
  // (relative geometry, incl. pins, is preserved) and meta.top reports
@@ -4786,7 +5316,7 @@ function renderScene(doc,y0){
4786
5316
  // opposite sides; endpoints and labels shift together.
4787
5317
  const apOff=new Map();
4788
5318
  {
4789
- const straight=e=>byId[e.a]&&byId[e.b]&&!(isBack.has(e)&&!pinned(e.a)&&!pinned(e.b))&&!chains.get(e);
5319
+ const straight=e=>byId[e.a]&&byId[e.b]&&!(chBack(e)&&!pinned(e.a)&&!pinned(e.b))&&!chains.get(e);
4790
5320
  const pk=e=>e.a<e.b?e.a+'\t'+e.b:e.b+'\t'+e.a;
4791
5321
  const pairN={}, seen={};
4792
5322
  for(const e of doc.edges) if(straight(e)){ const k=pk(e); pairN[k]=(pairN[k]||0)+1; }
@@ -4801,6 +5331,391 @@ function renderScene(doc,y0){
4801
5331
  apOff.set(e,[-dy/L*off, dx/L*off]);
4802
5332
  }
4803
5333
  }
5334
+ // ── LONG-EDGE CORRIDOR ROUTER — SIDE BY OCCUPANCY, THEN LANES ────────────
5335
+ // Items 41 and 46, and the approach-column half of item 26, for the long
5336
+ // edges the side-channel plan above does not reach: multi-rank forward edges,
5337
+ // and returns whose endpoints are PINNED (the channel plan takes only the
5338
+ // unpinned ones, so a hand-placed statechart's returns were routed by the
5339
+ // straight router and had no corridor at all).
5340
+ //
5341
+ // TWO DEFECTS, ONE MECHANISM.
5342
+ // 41 — `patterns/flowchart-b` routes BOTH its long edges down the right of a
5343
+ // single-column spine and they cross, while the left margin is empty
5344
+ // for the figure's whole height. The router never asked which side was
5345
+ // free: the diagonal took the geometric straight line and the channel
5346
+ // defaults to one side, so two long edges on one side of one spine are
5347
+ // guaranteed to meet.
5348
+ // 46 — `statechart/dhcp-client` sends `REQUESTING -> INIT` and
5349
+ // `BOUND -> INIT` over the top of the figure at near-identical y. They
5350
+ // read as ONE line with two label stacks.
5351
+ // Both are the same missing question — WHICH corridor, at WHAT height — so
5352
+ // they are answered by one pass: a long edge is offered an orthogonal
5353
+ // corridor route on each margin, at a LANE within that corridor, and the
5354
+ // figure keeps whichever costs least.
5355
+ //
5356
+ // THE COST, and it is item 26's, unchanged:
5357
+ // 10000*(crossings + pierces) + 1000*corridor conflicts + 40*bends + ink
5358
+ // Crossings and pierces dominate because a line through a box or through
5359
+ // another line is a misreading; the CONFLICT term is what this pass adds —
5360
+ // two routes running parallel within a lane width over more than 40 px are
5361
+ // one line to the reader, which is exactly dhcp-client's defect and is
5362
+ // invisible to a crossing count. Ink is charged 1/px so a corridor that buys
5363
+ // nothing loses to the straight line. **The incumbent stays in the candidate
5364
+ // set and is kept unless STRICTLY beaten**, which is what makes this pass
5365
+ // monotone rather than a gamble: a figure whose long edges are already clean
5366
+ // is byte-identical after it.
5367
+ //
5368
+ // THE LANE ORDER IS NOT A CHOICE — it is forced, and the rule is the one the
5369
+ // ring plan above already states. Sources are ordered by DISTANCE FROM THE
5370
+ // TARGET along the flow axis (ties by document order, so one document has one
5371
+ // assignment); the NEAREST source takes lane 0, hard against the figure, and
5372
+ // the FARTHEST takes the outermost lane. It has to be that way round: a far
5373
+ // source on an inner lane has its long run cut by every nearer source's climb
5374
+ // out to an outer lane. For the same reason the ARRIVAL fans across the
5375
+ // target's border — an outer lane must land BEYOND where every inner lane
5376
+ // stops, or it crosses them all on the way in.
5377
+ //
5378
+ // A GROUP IS (target, side of approach). Sources on opposite sides of one
5379
+ // target are two corridors, not one, and laning them together would send a
5380
+ // route the long way round the figure to reach a lane it has no reason to be
5381
+ // in.
5382
+ //
5383
+ // THE LEFT MARGIN EXISTS NOW. The canvas grows right and down only, so a
5384
+ // corridor on the low side needs the scene shifted — the uniform-shift
5385
+ // pattern `bShift`/`chShift` already use, and the thing the self-loop note
5386
+ // below records as missing. Relative geometry (pins included) is preserved
5387
+ // and `meta.left`/`meta.top` report the shifted origin, so the editor's
5388
+ // drag->pin round-trip stays stable.
5389
+ const longPlan=new Map(); // edge -> {side, lane, frac}
5390
+ let lShift=0, tShift=0;
5391
+ if(nodes.length){
5392
+ const CORR_GAP=26, LANE_PITCH=18, PAR_MIN=40;
5393
+ // group bands, computed exactly as gBox draws them below
5394
+ const gbb=[];
5395
+ for(const g of doc.groups){
5396
+ const mem=nodes.filter(n=>n.group===g.id); if(!mem.length) continue;
5397
+ const x0=Math.min(...mem.map(n=>n.x))-BAND.l, x1=Math.max(...mem.map(n=>n.x+n.w))+BAND.r;
5398
+ const yA=Math.min(...mem.map(n=>n.y))-BAND.t, yB=Math.max(...mem.map(n=>n.y+n.h))+BAND.b;
5399
+ gbb.push({x:x0,y:yA,w:x1-x0,h:yB-yA});
5400
+ }
5401
+ const cLo=n=>horiz?n.y:n.x, cHi=n=>horiz?n.y+n.h:n.x+n.w;
5402
+ const fC =n=>horiz?n.x+n.w/2:n.y+n.h/2;
5403
+ const bLo=Math.min(...nodes.map(cLo), ...gbb.map(b=>horiz?b.y:b.x));
5404
+ const bHi=Math.max(...nodes.map(cHi), ...gbb.map(b=>horiz?b.y+b.h:b.x+b.w));
5405
+ const corrAt=(side,off)=>side<0?bLo-CORR_GAP-off:bHi+CORR_GAP+off;
5406
+ // A LANE IS AS WIDE AS WHAT IT CARRIES. A fixed 18 px pitch put
5407
+ // dhcp-client's second return straight through the first one's two-line
5408
+ // label, which is the ink-blind spacing item 44 removed from ranks arriving
5409
+ // again one axis over. The step between two lanes is therefore the inner
5410
+ // lane's own LABEL extent — height when the corridor runs along the flow
5411
+ // axis, width when it runs across it — floored at the bare pitch.
5412
+ const lblExt=e=>Math.max(LANE_PITCH,
5413
+ !e.mid?0:(horiz?String(e.mid).split('\n').length*13+10:lblPx(e.mid)+10));
5414
+ // Lanes are allocated from a per-side pool, not per convergence: two
5415
+ // components that were decided separately (their INCUMBENTS did not share a
5416
+ // corridor) still share the corridor once both are adopted, and dhcp-client
5417
+ // drew exactly that — `RENEWING -> INIT` and `REBINDING -> INIT` laid on one
5418
+ // line along the bottom, `coinc 2`. The pool remembers every adopted run's
5419
+ // span, so a later component takes the next free height over the stretch it
5420
+ // actually occupies and nothing else.
5421
+ const usedLanes=new Map();
5422
+ const allocOff=(side,lo,hi,ext,taken)=>{
5423
+ const list=(usedLanes.get(side)||[]).concat(taken||[]);
5424
+ let off=0;
5425
+ for(let guard=0;guard<64;guard++){
5426
+ let clash=null;
5427
+ for(const u of list)
5428
+ if(Math.min(u.hi,hi)-Math.max(u.lo,lo)>PAR_MIN&&Math.abs(u.off-off)<Math.max(u.ext,ext)
5429
+ &&(!clash||u.off>clash.off)) clash=u;
5430
+ if(!clash) break;
5431
+ off=clash.off+Math.max(clash.ext,ext);
5432
+ }
5433
+ return off;
5434
+ };
5435
+ // A CORRIDOR ROUTE IS BUILT ORTHOGONALLY OR NOT OFFERED AT ALL.
5436
+ // The first cut handed the four-point L to `routeAround` when it hit
5437
+ // something, which is the wrong tool here: Dijkstra over a visibility graph
5438
+ // returns the SHORTEST clear polyline, not an orthogonal one, and on
5439
+ // `patterns/block-b` it returned a five-bend zigzag that doubled back
5440
+ // across the figure (0 -> 9 on the lint, 3 crossings and a `thru`). A
5441
+ // corridor's whole claim is "this margin is free"; when it is not free for
5442
+ // this edge, the honest answer is to withdraw the candidate, not to bend it
5443
+ // until it fits.
5444
+ //
5445
+ // So a leg out of a node is one of exactly two shapes: straight across to
5446
+ // the corridor, or — when something stands in that column — out of the
5447
+ // node's FLOW side, along to the nearest clear column, and across. That is
5448
+ // the escape the side-channel plan above already uses (`blockedV`/
5449
+ // `blockedH`), in the same two forms, and it keeps every corridor route
5450
+ // axis-aligned end to end. If neither shape is clear, `build` returns null
5451
+ // and the figure keeps its incumbent.
5452
+ //
5453
+ // Because the planned route is clean of every node and every group band by
5454
+ // construction, the draw pass runs NO detour on it: plan and drawing are the
5455
+ // same polyline, which is what makes the cost above a prediction rather
5456
+ // than a guess.
5457
+ const P=(f,c)=>horiz?[f,c]:[c,f];
5458
+ const fLoN=n=>horiz?n.x:n.y, fHiN=n=>horiz?n.x+n.w:n.y+n.h;
5459
+ const cLoN=n=>horiz?n.y:n.x, cHiN=n=>horiz?n.y+n.h:n.x+n.w;
5460
+ const oF=o=>horiz?[o.x,o.x+o.w]:[o.y,o.y+o.h];
5461
+ const oC=o=>horiz?[o.y,o.y+o.h]:[o.x,o.x+o.w];
5462
+ const blockCol=(f,c0,c1,obs)=>obs.some(o=>{
5463
+ const [fa,fb]=oF(o), [ca,cb]=oC(o);
5464
+ return f>fa-2&&f<fb+2&&Math.min(c1,cb)>Math.max(c0,ca)+0.5;
5465
+ });
5466
+ const blockRow=(c,f0,f1,obs)=>obs.some(o=>{
5467
+ const [fa,fb]=oF(o), [ca,cb]=oC(o);
5468
+ return c>ca-2&&c<cb+2&&Math.min(f1,fb)>Math.max(f0,fa)+0.5;
5469
+ });
5470
+ // the leg from node N (at flow position f) out to the corridor at cross c,
5471
+ // ordered node-first; null when neither shape is clear
5472
+ const legTo=(N,f,c,obs)=>{
5473
+ const cb=c>cHiN(N)?cHiN(N):cLoN(N);
5474
+ if(!blockCol(f,Math.min(cb,c),Math.max(cb,c),obs)) return [P(f,cb),P(f,c)];
5475
+ const cc=(cLoN(N)+cHiN(N))/2, gs=[];
5476
+ for(const o of obs){ const [fa,fb]=oF(o); gs.push(fa-10,fb+10); }
5477
+ gs.sort((a,b)=>Math.abs(a-f)-Math.abs(b-f)||b-a);
5478
+ for(const g of gs){
5479
+ if(blockCol(g,Math.min(cc,c),Math.max(cc,c),obs)) continue;
5480
+ if(blockRow(cc,Math.min(f,g),Math.max(f,g),obs)) continue;
5481
+ return [P(g>f?fHiN(N):fLoN(N),cc),P(g,cc),P(g,c)];
5482
+ }
5483
+ return null;
5484
+ };
5485
+ const build=(e,q)=>{
5486
+ const A=byId[e.a], B=byId[e.b], c=corrAt(q.side,q.off);
5487
+ const obs=obsFor(A,B);
5488
+ const la=legTo(A,fC(A),c,obs);
5489
+ const lb=legTo(B,horiz?B.x+B.w*q.frac:B.y+B.h*q.frac,c,obs);
5490
+ if(!la||!lb) return null;
5491
+ const fa=la[la.length-1][horiz?0:1], fb=lb[lb.length-1][horiz?0:1];
5492
+ if(blockRow(c,Math.min(fa,fb),Math.max(fa,fb),obs)) return null;
5493
+ const pts=la.concat(lb.slice().reverse());
5494
+ // drop a zero-length hop where the two legs meet on one column
5495
+ for(let i=1;i<pts.length;i++)
5496
+ if(Math.hypot(pts[i][0]-pts[i-1][0],pts[i][1]-pts[i-1][1])<0.5){ pts.splice(i,1); i--; }
5497
+ return pts;
5498
+ };
5499
+ // TWO OBSTACLE SETS, AND THE DIFFERENCE IS DELIBERATE.
5500
+ // `obsFor` — nodes AND foreign group bands — is what a corridor candidate
5501
+ // must be CLEAR OF to be offered at all: a corridor drawn through a band it
5502
+ // neither starts nor ends inside asserts a membership the document does not.
5503
+ // `nodeObs` — nodes only — is what the pierce TERM charges, because that is
5504
+ // what the drawing is measured on (`thru` counts node rectangles). Charging
5505
+ // the incumbent for a band crossing instead made `patterns/block-b`'s `ptr`
5506
+ // edge look two pierces worse than it is measured to be, and the corridor
5507
+ // won a comparison the figure then paid for in crossings it did not have
5508
+ // (0 -> 9). An edge crossing a foreign band is a real defect and it is
5509
+ // backlog items 6 and 19; it is not this pass's to trade measured axes for.
5510
+ const obsFor=(A,B)=>{
5511
+ const o=nodeObs(A,B);
5512
+ const inb=(b,q)=>q[0]>b.x&&q[0]<b.x+b.w&&q[1]>b.y&&q[1]<b.y+b.h;
5513
+ const pa=[A.x+A.w/2,A.y+A.h/2], pb=[B.x+B.w/2,B.y+B.h/2];
5514
+ for(const b of gbb) if(!inb(b,pa)&&!inb(b,pb)) o.push(b);
5515
+ return o;
5516
+ };
5517
+ const nodeObs=(A,B)=>nodes.filter(n=>n!==A&&n!==B&&!n.boundary)
5518
+ .map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}));
5519
+ // occupancy the channel plan will use, recomputed from the same inputs so
5520
+ // the two cannot drift; the shift below moves both together.
5521
+ let occRg=0, occBg=0;
5522
+ for(const n of nodes){ occRg=Math.max(occRg,n.x+n.w); occBg=Math.max(occBg,n.y+n.h); }
5523
+ for(const b of gbb){ occRg=Math.max(occRg,b.x+b.w); occBg=Math.max(occBg,b.y+b.h); }
5524
+ if(!horiz) chains.forEach((chain,e)=>{ if(!e.mid) return;
5525
+ const v=chain[1+Math.floor((chain.length-3)/2)];
5526
+ occRg=Math.max(occRg, v.x+v.w/2+9+lblPx(e.mid)); });
5527
+ // A channel route reconstructed as the draw pass will build it — the plain
5528
+ // form of each of the three shapes. The blocked-detour variants are not
5529
+ // reconstructed: they differ only in a short escape leg near an endpoint,
5530
+ // and this is a comparison of corridors, not of stubs.
5531
+ const chGuess=e=>{
5532
+ const A=byId[e.a], B=byId[e.b], P=chPlan.get(e);
5533
+ if(A===B) return null;
5534
+ if(horiz){
5535
+ const chY=occBg+28+P.slot;
5536
+ return [[A.x+A.w/2,outSide(A,'b')],[A.x+A.w/2,chY],[B.x+B.w*P.ef,chY],[B.x+B.w*P.ef,outSide(B,'b')]];
5537
+ }
5538
+ if(P.ringOK){
5539
+ const sx=A.x+A.w/2, gy=occBg+14+P.ring*12, chX=occRg+28+P.slot, topY=chTop-14-P.ring*12;
5540
+ return [[sx,outSide(A,'b')],[sx,gy],[chX,gy],[chX,topY],[P.ex,topY],[P.ex,outSide(B,'t')]];
5541
+ }
5542
+ const chX=occRg+28+P.slot;
5543
+ return [[outSide(A,'r'),A.y+A.h/2],[chX,A.y+A.h/2],[chX,B.y+B.h*P.ef],[outSide(B,'r'),B.y+B.h*P.ef]];
5544
+ };
5545
+ const guess=e=>{
5546
+ const A=byId[e.a], B=byId[e.b];
5547
+ if(!A||!B||A===B) return null;
5548
+ if(longPlan.has(e)) return longPlan.get(e).pts;
5549
+ if(chPlan.has(e)) return chGuess(e);
5550
+ const ch=chains.get(e), pp=[];
5551
+ if(ch) for(const v of ch.slice(1,-1)) pp.push([v.x+v.w/2,v.y+v.h/2]);
5552
+ const f=pp.length?pp[0]:[B.x+B.w/2,B.y+B.h/2];
5553
+ const l=pp.length?pp[pp.length-1]:[A.x+A.w/2,A.y+A.h/2];
5554
+ const st=[borderPoint(A,f[0],f[1]),...pp,borderPoint(B,l[0],l[1])];
5555
+ // THE INCUMBENT MUST BE GUESSED AS IT WILL BE DRAWN, DETOURS INCLUDED.
5556
+ // Guessing the undetoured line charged the incumbent for pierces the
5557
+ // drawing never contains, and the corridor then won a comparison it had
5558
+ // not earned: `patterns/block-b`'s `ptr` edge scored the incumbent at two
5559
+ // pierces (a chain run measured straight through `Unit B`, which the
5560
+ // chain branch detours around) and took a top corridor that cost the
5561
+ // figure 3 crossings and a `thru` — 0 -> 9. Every guess now runs the same
5562
+ // routeAround pass the draw branches run.
5563
+ const obs=obsFor(A,B);
5564
+ if(st.length>2){
5565
+ for(let i=0;i+1<st.length;i++){
5566
+ const d=routeAround(st[i],st[i+1],obs);
5567
+ if(!d) continue;
5568
+ const ins=d.slice(1,-1); st.splice(i+1,0,...ins); i+=ins.length;
5569
+ }
5570
+ return st;
5571
+ }
5572
+ const rr=routeAround(st[0],st[1],obs);
5573
+ if(!rr) return st;
5574
+ rr[0]=borderPoint(A,rr[1][0],rr[1][1]);
5575
+ rr[rr.length-1]=borderPoint(B,rr[rr.length-2][0],rr[rr.length-2][1]);
5576
+ return rr;
5577
+ };
5578
+ const xseg=(a,b,c,d)=>{
5579
+ const rx=b[0]-a[0], ry=b[1]-a[1], sx=d[0]-c[0], sy=d[1]-c[1];
5580
+ const den=rx*sy-ry*sx; if(Math.abs(den)<1e-9) return false;
5581
+ const t=((c[0]-a[0])*sy-(c[1]-a[1])*sx)/den, u=((c[0]-a[0])*ry-(c[1]-a[1])*rx)/den;
5582
+ return t>1e-6&&t<1-1e-6&&u>1e-6&&u<1-1e-6;
5583
+ };
5584
+ const crossN=(r,o)=>{ let n=0;
5585
+ for(let i=0;i+1<r.length;i++) for(let j=0;j+1<o.length;j++)
5586
+ if(xseg(r[i],r[i+1],o[j],o[j+1])) n++;
5587
+ return n; };
5588
+ const pierceN=(r,A,B)=>{ const obs=nodeObs(A,B); let n=0;
5589
+ for(let i=0;i+1<r.length;i++) if(segHitsObs(r[i],r[i+1],obs)) n++;
5590
+ return n; };
5591
+ const runsOf=r=>{ const out=[];
5592
+ for(let i=0;i+1<r.length;i++){
5593
+ const p=r[i], q=r[i+1], dx=q[0]-p[0], dy=q[1]-p[1];
5594
+ if(Math.abs(dx)<0.5&&Math.abs(dy)>=PAR_MIN) out.push({v:1,c:p[0],lo:Math.min(p[1],q[1]),hi:Math.max(p[1],q[1])});
5595
+ else if(Math.abs(dy)<0.5&&Math.abs(dx)>=PAR_MIN) out.push({v:0,c:p[1],lo:Math.min(p[0],q[0]),hi:Math.max(p[0],q[0])});
5596
+ }
5597
+ return out; };
5598
+ const conflictN=(r,o)=>{ let n=0;
5599
+ for(const a of runsOf(r)) for(const b of runsOf(o))
5600
+ if(a.v===b.v&&Math.abs(a.c-b.c)<LANE_PITCH-1&&Math.min(a.hi,b.hi)-Math.max(a.lo,b.lo)>PAR_MIN) n++;
5601
+ return n; };
5602
+ const inkOf=r=>{ let s=0;
5603
+ for(let i=0;i+1<r.length;i++){
5604
+ const dx=r[i+1][0]-r[i][0], dy=r[i+1][1]-r[i][1], L=Math.hypot(dx,dy);
5605
+ s+=(Math.abs(dx)<0.5||Math.abs(dy)<0.5)?L:L*1.7;
5606
+ }
5607
+ return s; };
5608
+ const costOf=(r,e,peers)=>{
5609
+ if(!r) return Infinity;
5610
+ const A=byId[e.a], B=byId[e.b];
5611
+ let cr=0, cf=0;
5612
+ for(const q of peers){ if(q.e===e||!q.r) continue; cr+=crossN(r,q.r); cf+=conflictN(r,q.r); }
5613
+ return 10000*(cr+pierceN(r,A,B))+1000*cf+40*Math.max(0,r.length-2)+inkOf(r);
5614
+ };
5615
+ const inBus=new Set();
5616
+ for(const m of busGroups) for(const e of m) inBus.add(e);
5617
+ for(const m of retBusGroups) for(const e of m) inBus.add(e);
5618
+ const longE=doc.edges.filter(e=>{
5619
+ const A=byId[e.a], B=byId[e.b];
5620
+ return A&&B&&e.a!==e.b&&!inBus.has(e)&&!chPlan.has(e)
5621
+ &&(isBack.has(e)||Math.abs(B.rank-A.rank)>1);
5622
+ });
5623
+ const grp=new Map();
5624
+ for(const e of longE){
5625
+ const A=byId[e.a], B=byId[e.b];
5626
+ const k=e.b+'|'+(fC(A)>=fC(B)?'+':'-');
5627
+ if(!grp.has(k)) grp.set(k,[]); grp.get(k).push(e);
5628
+ }
5629
+ // THE UNIT OF DECISION IS THE CONFLICT COMPONENT, not the whole convergence.
5630
+ // Measured on dhcp-client: laning ALL FIVE returns to INIT costs 8 crossings
5631
+ // and 9 conflicts against the incumbent's 3 and 2 — the five sources sit in
5632
+ // three different rows, so four of them have to climb PAST the figure to
5633
+ // reach one corridor and cross everything on the way. What is actually
5634
+ // defective there is the PAIR whose runs already share a corridor
5635
+ // (`REQUESTING -> INIT` and `BOUND -> INIT`, one line to the reader). So a
5636
+ // group is split into connected components under "your incumbent route runs
5637
+ // parallel to mine inside one lane width", and each component is decided on
5638
+ // its own. A component of one is still decided — that is item 41's
5639
+ // single-edge side choice, and flowchart-b is a component of one.
5640
+ const comps=[];
5641
+ for(const [,mem] of grp){
5642
+ const inc0=new Map(); for(const e of mem) inc0.set(e,guess(e));
5643
+ const par=mem.map((_,i)=>i);
5644
+ const find=i=>par[i]===i?i:(par[i]=find(par[i]));
5645
+ for(let i=0;i<mem.length;i++) for(let j=i+1;j<mem.length;j++)
5646
+ if(conflictN(inc0.get(mem[i]),inc0.get(mem[j]))) par[find(j)]=find(i);
5647
+ const byRoot=new Map();
5648
+ mem.forEach((e,i)=>{ const r=find(i); if(!byRoot.has(r)) byRoot.set(r,[]); byRoot.get(r).push(e); });
5649
+ for(const [,c] of byRoot) comps.push(c);
5650
+ }
5651
+ for(const mem of comps){
5652
+ const T=byId[mem[0].b], tf=fC(T);
5653
+ const ord=mem.map((e,i)=>({e,i}))
5654
+ .sort((p,q)=>Math.abs(fC(byId[p.e.a])-tf)-Math.abs(fC(byId[q.e.a])-tf)||p.i-q.i)
5655
+ .map(o=>o.e);
5656
+ const nM=ord.length, up=fC(byId[ord[0].a])>=tf;
5657
+ // arrival fractions: lane 0 lands nearest the sources, the outermost
5658
+ // lane beyond every inner lane's turn-in
5659
+ const fracs=ord.map((e,k)=>nM===1?0.5:(up?(nM-k)/(nM+1):(k+1)/(nM+1)));
5660
+ const peerE=doc.edges.filter(x=>byId[x.a]&&byId[x.b]&&x.a!==x.b&&mem.indexOf(x)<0);
5661
+ const peers=peerE.map(x=>({e:x,r:guess(x)}));
5662
+ const inc=ord.map(e=>({e,r:guess(e)}));
5663
+ const base=inc.reduce((s,q)=>s+costOf(q.r,q.e,peers.concat(inc)),0);
5664
+ let best=null, bestC=base, bestSide=0;
5665
+ for(const side of [-1,1]){
5666
+ const taken=[], cand=[];
5667
+ for(let k=0;k<ord.length;k++){
5668
+ const e=ord[k], A=byId[e.a], B=byId[e.b], frac=fracs[k];
5669
+ const a=fC(A), b=horiz?B.x+B.w*frac:B.y+B.h*frac;
5670
+ const lo=Math.min(a,b), hi=Math.max(a,b), ext=lblExt(e);
5671
+ const off=allocOff(side,lo,hi,ext,taken);
5672
+ taken.push({off,lo,hi,ext});
5673
+ const q={side,off,frac};
5674
+ cand.push({e,q,r:build(e,q),u:{off,lo,hi,ext}});
5675
+ }
5676
+ if(cand.some(z=>!z.r)) continue; // a corridor that is not free here
5677
+ const c=cand.reduce((s,z)=>s+costOf(z.r,z.e,peers.concat(cand)),0);
5678
+ if(c<bestC-1e-6){ bestC=c; best=cand; bestSide=side; }
5679
+ }
5680
+ if(best){
5681
+ if(!usedLanes.has(bestSide)) usedLanes.set(bestSide,[]);
5682
+ for(const z of best){ z.q.pts=z.r; longPlan.set(z.e,z.q); usedLanes.get(bestSide).push(z.u); }
5683
+ }
5684
+ }
5685
+ // the low-side margin the adopted corridors need, taken as a uniform shift
5686
+ let minC=Infinity;
5687
+ for(const [,q] of longPlan) if(q.side<0) minC=Math.min(minC,corrAt(q.side,q.off));
5688
+ if(minC!==Infinity){
5689
+ if(horiz) tShift=Math.max(0,(y0+26)-minC);
5690
+ else lShift=Math.max(0,6-minC);
5691
+ }
5692
+ if(lShift||tShift){
5693
+ for(const n of lay){ n.x+=lShift; n.y+=tShift; }
5694
+ for(const k in gOrigin){ gOrigin[k].x+=lShift; gOrigin[k].y+=tShift; }
5695
+ for(const [,q] of longPlan) q.pts=q.pts.map(z=>[z[0]+lShift,z[1]+tShift]);
5696
+ chTop+=tShift;
5697
+ }
5698
+ }
5699
+ // THE SOURCE STUB a long edge's label rides: the first stretch of the route as
5700
+ // it LEAVES the source, capped so the box lands beside the box the line comes
5701
+ // out of rather than halfway down the corridor. The cap scales with the LABEL
5702
+ // (a stub shorter than the label puts the box back on top of the source
5703
+ // whatever parameter is chosen), and it is shared by the channel routes and
5704
+ // the corridor routes because both have the same problem: a long run whose
5705
+ // far end is nowhere near either endpoint.
5706
+ const srcStubOf=(pp,wpx)=>{
5707
+ const a=pp[0], b=pp[1], L=Math.hypot(b[0]-a[0],b[1]-a[1])||1;
5708
+ const k=Math.min(1,Math.max(64,wpx+24)/L);
5709
+ return [a,[a[0]+(b[0]-a[0])*k, a[1]+(b[1]-a[1])*k]];
5710
+ };
5711
+ // THE DRAWN ROUTE IS THE PLANNED ROUTE, to the pixel. An earlier cut rebuilt
5712
+ // the polyline at draw time from the final coordinates, and the rebuild was a
5713
+ // SIMPLER builder than the planner's — it had no escape leg — so a corridor
5714
+ // whose arrival the planner had routed around a node was redrawn straight
5715
+ // through it (`dhcp-client` gained a `thru` that way). The plan carries its
5716
+ // own points, translated once with the scene shift, and nothing recomputes
5717
+ // them: whatever the cost function scored is exactly what the reader sees.
5718
+ const longRoute=e=>{ const q=longPlan.get(e); return q?q.pts.map(z=>z.slice()):null; };
4804
5719
  let W=0,Hh=0;
4805
5720
  for(const n of lay){ W=Math.max(W,n.x+n.w); Hh=Math.max(Hh,n.y+n.h-y0-20); }
4806
5721
  if(W===0){W=480;} if(Hh===0){Hh=280;}
@@ -4834,6 +5749,230 @@ function renderScene(doc,y0){
4834
5749
  const [bx,by,bw,bh]=bandRect(f,B.x0,B.yA,B.x1,B.yB);
4835
5750
  gsvg.push('<rect x="'+bx+'" y="'+by+'" width="'+bw+'" height="'+bh+'" fill="'+f.fill+'" opacity="0.9"'+bandEdge(f)+'/>');
4836
5751
  }
5752
+ // ── ELEMENT LABELS ARE INK, AND A ROUTE MUST GO ROUND THEM (item 45a) ─────
5753
+ // §14.4's frontier, on the drawing side. `showcase/arp-resolution` ran the
5754
+ // GREEN unicast shaft straight through `rest of the LAN (hosts C, D, ...)`,
5755
+ // and the misreading it invites — that the unicast reaches the rest of the
5756
+ // LAN — is the exact claim the figure exists to deny. The router's obstacle
5757
+ // set was node boxes and group rects: geometry that is DRAWN AS A SHAPE. An
5758
+ // external is never drawn as a shape (`EXTERNAL-EDGE-ENDPOINTS`) and a band NAME is not a shape at
5759
+ // all, so both were invisible to routing while being fully visible on the
5760
+ // page.
5761
+ //
5762
+ // The mechanism is the SMALLEST one consistent with the router that exists:
5763
+ // these two label boxes join the obstacle list `routeAround` already takes,
5764
+ // so a shaft detours around them exactly as it detours around a node. The
5765
+ // alternative — making the LABEL yield — was rejected: an external's label
5766
+ // has one meaningful place (beyond the open end, away from the figure, `EXTERNAL-EDGE-ENDPOINTS`)
5767
+ // and a band's name has one place (the strip it names), so a yielding label
5768
+ // has nowhere to go, and moving it would break the very adjacency that makes
5769
+ // it readable. A node's own label needs nothing here: it lives inside the
5770
+ // node box, which is already an obstacle.
5771
+ //
5772
+ // An external's label is NOT an obstacle to its OWN edge — that edge must
5773
+ // reach the anchor the label names.
5774
+ const extLbl=n=>{
5775
+ const cx=n.x+n.w/2, cy=n.y+n.h/2, [bdx,bdy]=bDir(n);
5776
+ const bw=lblPx(n.label), bl=String(n.label).split('\n').length, bh=13*bl;
5777
+ let ox,oy;
5778
+ if(Math.abs(bdx)>=Math.abs(bdy)){ ox=bdx>=0?cx+10:cx-10-bw; oy=cy+3.5-13*bl/2-1.5; }
5779
+ else { ox=cx-bw/2; oy=(bdy>=0?cy+17:cy-10)-13*bl/2-1.5; }
5780
+ return {x:ox,y:oy,w:bw,h:bh};
5781
+ };
5782
+ const extObs=[];
5783
+ for(const n of nodes) if(n.boundary&&n.label) extObs.push(Object.assign(extLbl(n),{id:n.id}));
5784
+ const nameObs=[];
5785
+ for(const k in gBox){ const g=doc.groups.find(z=>z.id===k);
5786
+ if(!g||!g.label) continue;
5787
+ const B=gBox[k];
5788
+ nameObs.push({x:B.x0+10, y:B.yA+16-11.5*0.85, w:cwMax(g.label)*6.5*11.5/11, h:11.5*1.1});
5789
+ }
5790
+ // The obstacle list a given edge must respect: every band name, plus every
5791
+ // external label except the ones this edge itself terminates at.
5792
+ // A label's ink is its glyphs plus the clearance that keeps a line from
5793
+ // READING as struck through it. 4 px on every side — the same number the
5794
+ // legibility floor uses for a label's association margin — so a shaft that
5795
+ // grazes a name at 3 px is detoured rather than tolerated.
5796
+ const LBL_PAD=4;
5797
+ const padded=o=>({x:o.x-LBL_PAD,y:o.y-LBL_PAD,w:o.w+2*LBL_PAD,h:o.h+2*LBL_PAD});
5798
+ const lblObs=e=>extObs.filter(o=>o.id!==e.a&&o.id!==e.b).map(padded)
5799
+ .concat(nameObs.map(padded));
5800
+ // ── A BUNDLE RING IS ORIENTED BY ITS MEMBERS (item 43) ───────────────────
5801
+ // Until now the ring was derived from the member links' MIDPOINTS and
5802
+ // nothing else: `rx = max(46, x-spread + 38)`, `ry = max(26, y-spread + 22)`.
5803
+ // Two facts about that formula are the defect. It is DIRECTION-BLIND — the
5804
+ // axes are the canvas's, never the links' — and its floors are large enough
5805
+ // that a bundle of two short legs draws a near-circle whatever the legs do.
5806
+ // Measured on `patterns/topology-b`: rx 46 / ry 42.7, aspect
5807
+ // 1.07, sitting on two legs that fan VERTICALLY, with the caption lying
5808
+ // across the waist and on top of the `p3` endpoint label.
5809
+ //
5810
+ // The drawing convention for a link bundle is a loop THROUGH which the
5811
+ // links run: narrow along the links, long across them. So the ring is now
5812
+ // derived from the members' own frame.
5813
+ //
5814
+ // 1. DIRECTION. The mean UNDIRECTED direction of the members, by the
5815
+ // doubled-angle circular mean — doubling is what makes `a--b` and
5816
+ // `b--a` the same direction, so a bundle does not change shape when an
5817
+ // author writes a member the other way round (conformance 394).
5818
+ // 2. THE BAND. The ring sits at the MIDPOINT OF THE MEMBERS' SHARED RUN
5819
+ // along that direction — the stretch of the corridor every member is
5820
+ // actually in. That is the placement rule because it is the only band
5821
+ // at which "the spread of the members" is a fact about all of them: a
5822
+ // fanning set (the reference topology's ECMP pair, which leaves two
5823
+ // different spines and arrives at one leaf) has a different spread at
5824
+ // every station, and the shared run is the interval over which the
5825
+ // question is even well posed. Members with no shared run at all fall
5826
+ // back to the mean of their midpoints, which is the old centre.
5827
+ // 3. THE AXES. MINOR along the mean direction, sized to clear the strokes;
5828
+ // MAJOR across it, the members' spread at the band plus padding. A ring
5829
+ // needs a long axis to read as a ring, and it takes it from the spread
5830
+ // when the members fan (`rA >= rL`) and from its own RUN when they do
5831
+ // not — a single-member bundle (`reference/topology`'s multi-home link)
5832
+ // has zero spread, and the shape that hugs one link is an ellipse lying
5833
+ // ALONG it, never a circle straddling it.
5834
+ // 4. NO NODE CONTACT. The ring is shrunk along its minor axis until it
5835
+ // clears every node box, and if it cannot it reverts to the pre-0.4
5836
+ // geometry rather than inventing a shape (no corpus figure does).
5837
+ //
5838
+ // The caption is NOT placed here — it is registered with the label pass
5839
+ // below, so it can see the endpoint labels and the edges it has to avoid.
5840
+ const rnd3=v=>Math.round(v*1000)/1000; // ring coordinates, printed short
5841
+ const RING_ALONG=15, // semi-minor: the ring's body along the links
5842
+ RING_ACROSS=20, // clearance beyond the outermost member
5843
+ RING_LONG=34, // the long axis a ring needs to read as a ring
5844
+ RING_FAN=2, // below this spread the members are one line
5845
+ RING_FLOOR=7, // how thin the minor axis may be squeezed
5846
+ RING_SOLO=4; // a ONE-member bundle: the caption's stand-off
5847
+ // ── A ONE-MEMBER BUNDLE IS ITS CAPTION (item 53) ─────────────────────────
5848
+ // `bundle mh "multi-home" l1--l2` is legal and means something real (a
5849
+ // one-link LAG, an Ethernet Segment with a single member), so the
5850
+ // declaration is not an error and is not dropped. But a ring exists to
5851
+ // UNITE lines, and around ONE line it unites nothing: it is ink that adds
5852
+ // no fact, and on the reference topology it also bought the seam a 104 px
5853
+ // corridor demand (2*RX_MIN + clearance) for a shape nobody had to see.
5854
+ //
5855
+ // So a single-member bundle DRAWS NO ELLIPSE. What it draws is its
5856
+ // CAPTION, bundle-styled (the trunk's own stroke, the ring caption's type)
5857
+ // and placed BY THE LINK — which is exactly the statement the construct
5858
+ // makes: this link is the bundle, and here is its name. The frame below is
5859
+ // therefore kept as a PLACEMENT frame and not as a drawing: the caption
5860
+ // pass already sites a caption around a ring's rim, so a ring squeezed to
5861
+ // `RING_SOLO` across gives the same pass a candidate family hugging the
5862
+ // link. Nothing else in the pass changes.
5863
+ //
5864
+ // AN EMPTY CAPTION ON A ONE-MEMBER BUNDLE THEREFORE DRAWS NOTHING AT ALL.
5865
+ // That is a real consequence and it is not hidden: the reference figure
5866
+ // keeps `bundle unlabelled "" s2--l2` — it is the form demonstrator for
5867
+ // the empty label — and states in a comment that this form is now
5868
+ // MODEL-ONLY. The model still carries the trunk, `read` still reports it,
5869
+ // and the drawing says nothing because there is nothing a ring around one
5870
+ // unnamed line could say.
5871
+ // Does the ring's disc meet an axis-aligned rect? Both are mapped into the
5872
+ // frame where the ring is the unit circle; the rect becomes a convex quad,
5873
+ // and the test is "is the quad within 1 of the origin".
5874
+ const ringHitsRect=(R,RL,RA,b)=>{
5875
+ const q=[[b.x,b.y],[b.x+b.w,b.y],[b.x+b.w,b.y+b.h],[b.x,b.y+b.h]].map(p=>{
5876
+ const dx=p[0]-R.cx, dy=p[1]-R.cy;
5877
+ return [(R.ux*dx+R.uy*dy)/RL, (R.vx*dx+R.vy*dy)/RA];
5878
+ });
5879
+ let inside=false;
5880
+ for(let i=0,j=3;i<4;j=i++)
5881
+ if((q[i][1]>0)!==(q[j][1]>0) &&
5882
+ 0 < (q[j][0]-q[i][0])*(0-q[i][1])/(q[j][1]-q[i][1])+q[i][0]) inside=!inside;
5883
+ if(inside) return true;
5884
+ for(let i=0,j=3;i<4;j=i++){
5885
+ const vx=q[j][0]-q[i][0], vy=q[j][1]-q[i][1], L2=vx*vx+vy*vy;
5886
+ const t=L2?Math.max(0,Math.min(1,-(q[i][0]*vx+q[i][1]*vy)/L2)):0;
5887
+ if(Math.hypot(q[i][0]+t*vx, q[i][1]+t*vy)<1) return true;
5888
+ }
5889
+ return false;
5890
+ };
5891
+ const ringOf=t=>{
5892
+ const segs=[];
5893
+ for(const [a,b] of t.pairs){
5894
+ const A=byId[a], B=byId[b]; if(!A||!B) continue;
5895
+ const p=borderPoint(A,B.x+B.w/2,B.y+B.h/2), q=borderPoint(B,A.x+A.w/2,A.y+A.h/2);
5896
+ if(Math.hypot(q[0]-p[0],q[1]-p[1])>1e-9) segs.push([p,q]);
5897
+ }
5898
+ if(!segs.length) return null;
5899
+ // (1) mean undirected direction
5900
+ let c2=0,s2=0;
5901
+ for(const [p,q] of segs){
5902
+ const L=Math.hypot(q[0]-p[0],q[1]-p[1]);
5903
+ const c=(q[0]-p[0])/L, s=(q[1]-p[1])/L;
5904
+ c2+=c*c-s*s; s2+=2*c*s;
5905
+ }
5906
+ const th=Math.hypot(c2,s2)<1e-9
5907
+ ? Math.atan2(segs[0][1][1]-segs[0][0][1], segs[0][1][0]-segs[0][0][0])
5908
+ : 0.5*Math.atan2(s2,c2);
5909
+ const ux=Math.cos(th), uy=Math.sin(th), vx=-uy, vy=ux;
5910
+ // (2) the band: the midpoint of the shared run
5911
+ const iv=segs.map(([p,q])=>{
5912
+ const a=ux*p[0]+uy*p[1], b=ux*q[0]+uy*q[1];
5913
+ return a<=b?[a,b,p,q]:[b,a,q,p];
5914
+ });
5915
+ const lo=Math.max(...iv.map(z=>z[0])), hi=Math.min(...iv.map(z=>z[1]));
5916
+ const s=lo<hi ? (lo+hi)/2 : iv.reduce((x,z)=>x+(z[0]+z[1])/2,0)/iv.length;
5917
+ const P=iv.map(z=>{
5918
+ const f=Math.min(1,Math.max(0,(s-z[0])/((z[1]-z[0])||1)));
5919
+ return [z[2][0]+(z[3][0]-z[2][0])*f, z[2][1]+(z[3][1]-z[2][1])*f];
5920
+ });
5921
+ const cx=P.reduce((a,p)=>a+p[0],0)/P.length, cy=P.reduce((a,p)=>a+p[1],0)/P.length;
5922
+ const spread=Math.max(...P.map(p=>Math.abs(vx*(p[0]-cx)+vy*(p[1]-cy))));
5923
+ const runHalf=Math.min(...iv.map(z=>Math.min(s-z[0],z[1]-s)));
5924
+ // (3) axes. Two shapes, and which one is drawn is decided by whether the
5925
+ // members FAN at all. A set that fans is CROSSED by the ring: thin along
5926
+ // the links, long enough across them to take the whole spread with room
5927
+ // to spare, so each member passes through a part of the rim where the
5928
+ // ring is still visibly open. A set that does not fan — one link, or
5929
+ // members lying on top of each other — has no spread to take, and the
5930
+ // shape that says "this link is the bundle" is an ellipse lying ALONG it.
5931
+ let rA, rL;
5932
+ if(spread<RING_FAN){ rL=Math.max(RING_ALONG,Math.min(RING_LONG,Math.max(0,runHalf))); rA=RING_ACROSS; }
5933
+ else { rL=RING_ALONG; rA=Math.max(spread+RING_ACROSS,RING_LONG); }
5934
+ const R={cx,cy,ux,uy,vx,vy,th};
5935
+ // (0) ONE MEMBER (item 53): no ellipse is drawn, so this is a caption
5936
+ // frame and not a shape. It is squeezed across to `RING_SOLO` so the
5937
+ // caption pass's rim stations sit beside the link rather than a ring's
5938
+ // radius away from it, and the node-clearance step below is skipped —
5939
+ // there is no ink to keep out of a box.
5940
+ if(segs.length===1){
5941
+ R.solo=true; R.rL=rL; R.rA=RING_SOLO;
5942
+ R.hw=Math.hypot(rL*ux, RING_SOLO*vx); R.hh=Math.hypot(rL*uy, RING_SOLO*vy);
5943
+ return R;
5944
+ }
5945
+ // (4) out of every node box
5946
+ const boxes=nodes.filter(n=>!n.boundary).map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}));
5947
+ if(boxes.some(b=>ringHitsRect(R,rL,rA,b))){
5948
+ let ok=false;
5949
+ for(let k=1;k<=24&&!ok;k++){
5950
+ const RL=rL-(rL-RING_FLOOR)*k/24;
5951
+ if(!boxes.some(b=>ringHitsRect(R,RL,rA,b))){ rL=RL; ok=true; }
5952
+ }
5953
+ // No orientation of this ring clears the drawing. Rather than publish a
5954
+ // ring lying over a node, revert to the pre-0.4 derivation, which is at
5955
+ // least the shape every earlier artifact recorded. No corpus figure
5956
+ // takes this branch; it exists so that a hostile geometry degrades to
5957
+ // the old defect instead of a new one.
5958
+ if(!ok){
5959
+ const M=segs.map(([p,q])=>[(p[0]+q[0])/2,(p[1]+q[1])/2]);
5960
+ const mx=M.reduce((a,m)=>a+m[0],0)/M.length, my=M.reduce((a,m)=>a+m[1],0)/M.length;
5961
+ const lx=Math.max(46,Math.max(...M.map(m=>Math.abs(m[0]-mx)))+38);
5962
+ const ly=Math.max(26,Math.max(...M.map(m=>Math.abs(m[1]-my)))+22);
5963
+ return {cx:mx, cy:my, ux:1, uy:0, vx:0, vy:1, th:0, legacy:true,
5964
+ rL:lx, rA:ly, hw:lx, hh:ly};
5965
+ }
5966
+ }
5967
+ R.rL=rL; R.rA=rA;
5968
+ // the axis-aligned box the caption is placed beside and the canvas grows to
5969
+ R.hw=Math.hypot(rL*ux, rA*vx); R.hh=Math.hypot(rL*uy, rA*vy);
5970
+ return R;
5971
+ };
5972
+ const rings=new Map();
5973
+ for(const t of doc.trunks||[]){ const R=ringOf(t); if(R) rings.set(t,R); }
5974
+ // filled by the label pass below, consumed by the ring drawing further down
5975
+ const ringLbl=new Map(), ringLeads=[];
4837
5976
  // edges (sorted by plane z, then doc order)
4838
5977
  const edges=zsort(doc.edges);
4839
5978
  const esvg=[], lblsvg=[]; // labels paint last = closest to the viewer
@@ -4854,6 +5993,12 @@ function renderScene(doc,y0){
4854
5993
  // (direction: from→tip). Geometry matches #arr marker (viewBox 0 0 10 10,
4855
5994
  // refX=9, refY=5, markerWidth=7, markerHeight=7, markerUnits=strokeWidth=1.6):
4856
5995
  // arm = 9*(7/10)*1.6 ≈ 10.08 px, half-width = 5*(7/10)*1.6 ≈ 5.6 px.
5996
+ // Which edge is currently drawing, and which `lblsvg` slots its arrowheads
5997
+ // took. Item 55 recolours an edge AFTER the label pass has run, and an
5998
+ // arrowhead in a different colour from its own shaft is not a discrimination
5999
+ // aid, it is a bug. Recorded rather than inferred: the arrowhead carries no
6000
+ // id of its own.
6001
+ let arrowOwner=null; const arrowIdx=new Map();
4857
6002
  const arrowTri=(tip,from,col)=>{
4858
6003
  const dx=tip[0]-from[0], dy=tip[1]-from[1], L=Math.hypot(dx,dy)||1;
4859
6004
  const ux=dx/L, uy=dy/L; // unit vector from→tip
@@ -4865,6 +6010,9 @@ function renderScene(doc,y0){
4865
6010
  arrowBox.push({x:Math.min(tip[0],lx,rx), y:Math.min(tip[1],ly,ry),
4866
6011
  w:Math.max(tip[0],lx,rx)-Math.min(tip[0],lx,rx),
4867
6012
  h:Math.max(tip[1],ly,ry)-Math.min(tip[1],ly,ry)});
6013
+ if(arrowOwner){ let a=arrowIdx.get(arrowOwner);
6014
+ if(!a){ a=[]; arrowIdx.set(arrowOwner,a); }
6015
+ a.push(lblsvg.length-1); }
4868
6016
  };
4869
6017
  // back-edge side channel: beyond the occupied lanes (nodes AND group boxes)
4870
6018
  let occR=0, occB=0;
@@ -4916,6 +6064,9 @@ function renderScene(doc,y0){
4916
6064
  // figure where every convergence is a trunk, or none is, is one drawing
4917
6065
  // either way. There is deliberately no per-edge escape.
4918
6066
  const busRoute=new Map();
6067
+ // Where each RETURN-BUS member's own leg meets the shared trunk, collected as
6068
+ // the members draw so the last one can dot the joins (item 46).
6069
+ const busJoins=new Map();
4919
6070
  {
4920
6071
  const RAIL_GAP=22, RAIL_CLEAR=12, RAIL_ROOM=30;
4921
6072
  const fLo=n=>horiz?n.x:n.y, fHi=n=>horiz?n.x+n.w:n.y+n.h;
@@ -4953,7 +6104,7 @@ function renderScene(doc,y0){
4953
6104
  for(const e of edges){
4954
6105
  if(!byId[e.a]||!byId[e.b]||e.a===e.b) continue;
4955
6106
  if(busMem.has(e)) continue;
4956
- if(isBack.has(e)&&!pinned(e.a)&&!pinned(e.b)) continue; // channel routes: not reconstructible here
6107
+ if(chBack(e)&&!pinned(e.a)&&!pinned(e.b)) continue; // channel routes: not reconstructible here
4957
6108
  others.push(incumbent(e));
4958
6109
  }
4959
6110
  const xseg=(a,b,c,d)=>{
@@ -4987,6 +6138,51 @@ function renderScene(doc,y0){
4987
6138
  };
4988
6139
  const built=[];
4989
6140
  let figureOK=busGroups.length>0;
6141
+ // ── TWO TRUNK FORMS, AND WHY THERE HAD TO BE A SECOND (item 60) ────────
6142
+ // FORM 1, THE CROSS RAIL, is the construct as first built: the sources
6143
+ // spread across the cross axis, each drops onto a shared rail just short
6144
+ // of the target, and the rail carries them in. It assumes the sources are
6145
+ // BESIDE one another. When they are not — when the figure is a ladder and
6146
+ // the sources sit one above the other in a single column — the "drop"
6147
+ // from the far source runs straight down the column and through every
6148
+ // source between it and the target, so the form fails its own pierce test
6149
+ // and the figure declined. `statechart/bfd-session` is exactly that shape:
6150
+ // three purple dashed `admin disable` transitions, DOWN/INIT/UP -> ADMINDOWN,
6151
+ // one class and one meaning, drawn as three separate lines in a few pixels
6152
+ // of shared column with the one sentence written three times.
6153
+ //
6154
+ // FORM 2, THE COLUMN TRUNK, is the same statement rotated: each source
6155
+ // leaves on its cross-facing border, runs the short way out to a trunk
6156
+ // standing clear of the column, and the trunk runs ALONG the flow axis
6157
+ // into the target's side. One trunk, one stroke, one arrowhead, junction
6158
+ // dots at the interior joins, and item 54's per-leg labels at each origin
6159
+ // block edge — the same drawing `patterns/state-b` makes with its four
6160
+ // `reset` returns, which is the pattern the review named.
6161
+ //
6162
+ // Both forms face the same three tests, in the same order, and a form
6163
+ // that fails any of them is not offered: every leg clears every node and
6164
+ // band it does not touch; the form crosses no more of the figure than the
6165
+ // routes it replaces; and — clause 3 of the figure-level style rule above
6166
+ // — if NO form passes for ANY eligible group, the whole figure declines.
6167
+ // The rail is offered first and ties go to it, so no figure that draws a
6168
+ // rail today starts drawing a column instead.
6169
+ const TRUNK_GAP=24;
6170
+ // WHERE ON THE BORDER A BUS LEG LEAVES, AND WHY IT IS THREE EIGHTHS.
6171
+ // Not the centre: every other route in and out of a box is anchored there,
6172
+ // so a leg on the centre-line lies along whatever that border already
6173
+ // sends the same way — measured on `bfd-session`, the three legs ran
6174
+ // exactly down the three red teardown routes, coinc 0 -> 6 and F5 1 -> 8.
6175
+ // Not a quarter either, and that is the same lesson one step further in:
6176
+ // the side-channel plan spreads its own arrivals at k/(m+1) of a box's
6177
+ // extent, so a box with three of them anchors at 1/4, 1/2 and 3/4 and a
6178
+ // leg at 1/4 lands ON one — coinc 0 -> 2 (bfd's DOWN, 107 px of shared
6179
+ // ink), also measured. 3/8 sits BETWEEN the plan's own stations, and it
6180
+ // measures best of everything tried: leg fractions 1/8, 1/5, 1/4, 3/10,
6181
+ // 3/8 and 2/5 give score 38, 20, 22, 16, 16, 16 on bfd, with 3/8 the
6182
+ // middle of the three that tie. Toward the target, because that is the
6183
+ // way the bus is going.
6184
+ const BUS_OFF=3/8;
6185
+ const crossLo=n=>horiz?n.y:n.x, crossHi=n=>horiz?n.y+n.h:n.x+n.w;
4990
6186
  for(const mem of busGroups){
4991
6187
  if(!figureOK) break;
4992
6188
  const T=byId[mem[0].b], src=mem.map(e=>byId[e.a]);
@@ -4997,37 +6193,120 @@ function renderScene(doc,y0){
4997
6193
  const railF=dir>0
4998
6194
  ? Math.min(fLo(T)-RAIL_CLEAR, Math.max(fLo(T)-RAIL_GAP, Math.max(...src.map(fHi))+RAIL_CLEAR))
4999
6195
  : Math.max(fHi(T)+RAIL_CLEAR, Math.min(fHi(T)+RAIL_GAP, Math.min(...src.map(fLo))-RAIL_CLEAR));
5000
- const tc=cC(T);
5001
- const cand=[]; let ok=true;
5002
- for(const e of mem){
5003
- const s=byId[e.a], cs=cC(s);
5004
- const j=P(railF,cs), h=P(railF,tc);
5005
- const pts=Math.abs(cs-tc)<0.5
5006
- ? [borderPoint(s,h[0],h[1]), h, borderPoint(T,h[0],h[1])]
5007
- : [borderPoint(s,j[0],j[1]), j, h, borderPoint(T,h[0],h[1])];
5008
- const obs=obsFor(s,T);
5009
- for(let i=0;i+1<pts.length;i++) if(segHitsObs(pts[i],pts[i+1],obs)) ok=false;
5010
- if(!ok) break;
5011
- cand.push({e,cs,pts});
6196
+ // The trunk's ENTRY is off the target's centre-line for the same reason
6197
+ // its legs are off their sources' (see the leg comment below): on
6198
+ // `bfd-session` the entry ran back along the `admin enable` return
6199
+ // leaving ADMINDOWN's own border centre, 92 px of shared ink and coinc 4.
6200
+ // It enters a quarter of the box's flow extent on the side the bus comes
6201
+ // FROM, which is the side a reader traces it back along.
6202
+ const tc=cC(T), ftc0=(fLo(T)+fHi(T))/2;
6203
+ const forms=[];
6204
+ // FORM 1 — the cross rail. `u` is a member's position ALONG the trunk,
6205
+ // which is the cross axis here and the flow axis in form 2; everything
6206
+ // downstream (dots, lead) is written in `u` so it serves both.
6207
+ {
6208
+ const cand=[]; let ok=true;
6209
+ for(const e of mem){
6210
+ const s=byId[e.a], cs=cC(s);
6211
+ const j=P(railF,cs), h=P(railF,tc);
6212
+ const pts=Math.abs(cs-tc)<0.5
6213
+ ? [borderPoint(s,h[0],h[1]), h, borderPoint(T,h[0],h[1])]
6214
+ : [borderPoint(s,j[0],j[1]), j, h, borderPoint(T,h[0],h[1])];
6215
+ const obs=obsFor(s,T);
6216
+ for(let i=0;i+1<pts.length;i++) if(segHitsObs(pts[i],pts[i+1],obs)) ok=false;
6217
+ if(!ok) break;
6218
+ cand.push({e,u:cs,jp:j,pts});
6219
+ }
6220
+ if(ok) forms.push({cand,uT:tc,tp:P(railF,tc)});
6221
+ }
6222
+ // FORM 2 — the column trunk. The trunk stands one TRUNK_GAP clear of
6223
+ // every box the run passes, on whichever side is cleaner; a band it
6224
+ // cannot clear is caught by the same pierce test as a node.
6225
+ {
6226
+ const ftc=ftc0-dir*(fHi(T)-fLo(T))*BUS_OFF;
6227
+ const runLo=Math.min(...src.map(fLo).concat([fLo(T)])),
6228
+ runHi=Math.max(...src.map(fHi).concat([fHi(T)]));
6229
+ const thru=nodes.filter(n=>!n.boundary&&fHi(n)>runLo+0.5&&fLo(n)<runHi-0.5);
6230
+ // WHERE THE TRUNK STANDS, AND WHY "CLEAR OF THE BOXES" IS NOT ENOUGH.
6231
+ // The first build put the trunk one gap outside the widest BOX in the
6232
+ // run, and on `bfd-session` that is x=149 — straight through the
6233
+ // waypoint detour the green DOWN -> UP advance edge takes at x=193.
6234
+ // The bus crossed 3 where the three separate lines crossed 1, the
6235
+ // never-worse test refused it, and the refusal was right: a trunk
6236
+ // drawn across the figure's existing routes is not a tidier drawing.
6237
+ // So each side offers TWO stations — one just outside the boxes, one
6238
+ // outside every route the figure already draws across the same span —
6239
+ // and the tight one is offered first so a figure only pays the extra
6240
+ // width when the crossings say it must.
6241
+ const oX=[];
6242
+ for(const o of others) for(let i=0;i+1<o.length;i++){
6243
+ const a=o[i], b=o[i+1], af=horiz?a[0]:a[1], bf=horiz?b[0]:b[1];
6244
+ if(Math.max(af,bf)<runLo-0.5||Math.min(af,bf)>runHi+0.5) continue;
6245
+ oX.push(horiz?a[1]:a[0], horiz?b[1]:b[0]);
6246
+ }
6247
+ const stations=[];
6248
+ if(thru.length){
6249
+ const nHi=Math.max(...thru.map(crossHi)), nLo=Math.min(...thru.map(crossLo));
6250
+ stations.push(nHi+TRUNK_GAP, nLo-TRUNK_GAP);
6251
+ if(oX.length){
6252
+ const clearHi=Math.max(nHi,...oX)+TRUNK_GAP, clearLo=Math.min(nLo,...oX)-TRUNK_GAP;
6253
+ if(clearHi>nHi+TRUNK_GAP+0.5) stations.splice(1,0,clearHi);
6254
+ if(clearLo<nLo-TRUNK_GAP-0.5) stations.push(clearLo);
6255
+ }
6256
+ }
6257
+ for(const trunkC of stations){
6258
+ if(trunkC<TRUNK_GAP) continue; // off the left/top margin
6259
+ const cand=[]; let ok=true;
6260
+ for(const e of mem){
6261
+ // THE LEG DOES NOT LEAVE ON THE CENTRE-LINE. Every other route in
6262
+ // and out of a box is anchored on its border centre, so a bus leg
6263
+ // that leaves there lies along whatever that box already sends the
6264
+ // same way: on `bfd-session` the three legs ran EXACTLY down the
6265
+ // three red teardown routes leaving the same borders (coinc 0 -> 6,
6266
+ // F5 1 -> 8, both measured). The leg therefore leaves a quarter of
6267
+ // the box's flow extent TOWARD the target — the direction it is
6268
+ // going anyway — which frees the centre-line for the traffic that
6269
+ // has nowhere else to be.
6270
+ const s=byId[e.a], fsc=(fLo(s)+fHi(s))/2+dir*(fHi(s)-fLo(s))*BUS_OFF;
6271
+ const j=P(fsc,trunkC), h=P(ftc,trunkC);
6272
+ // The leg leaves the border AT its own flow position, not at the
6273
+ // point a ray from the box centre happens to cross: a bus is
6274
+ // axis-aligned by construction (see the style decision above), and
6275
+ // `borderPoint` would start the leg on the centre ray and slant it.
6276
+ const ex0=P(fsc, trunkC>cC(s)?crossHi(s):crossLo(s));
6277
+ const en0=P(ftc, trunkC>cC(T)?crossHi(T):crossLo(T));
6278
+ const pts=[ex0, j, h, en0];
6279
+ const obs=obsFor(s,T);
6280
+ for(let i=0;i+1<pts.length;i++) if(segHitsObs(pts[i],pts[i+1],obs)) ok=false;
6281
+ if(!ok) break;
6282
+ cand.push({e,u:fsc,jp:j,pts});
6283
+ }
6284
+ if(ok) forms.push({cand,uT:ftc,tp:P(ftc,trunkC)});
6285
+ }
5012
6286
  }
5013
- if(!ok){ figureOK=false; break; } // a leg pierces something
5014
- const bpts=cand.map(c=>c.pts), ipts=mem.map(incumbent);
5015
- const bc=crossCount(bpts)+pierceCount(bpts,mem);
6287
+ const ipts=mem.map(incumbent);
5016
6288
  const ic=crossCount(ipts)+pierceCount(ipts,mem);
5017
- if(bc>ic){
5018
- figureOK=false; break; // not beaten: keep the incumbents
6289
+ let pick=null, pickC=Infinity;
6290
+ for(const F of forms){
6291
+ const bpts=F.cand.map(c=>c.pts);
6292
+ const bc=crossCount(bpts)+pierceCount(bpts,mem);
6293
+ if(bc>ic) continue; // not beaten: keep the incumbents
6294
+ if(bc<pickC-0.5){ pickC=bc; pick=F; }
5019
6295
  }
5020
- // junction dots mark the interior joins only: the two ends of the rail
6296
+ if(!pick){ figureOK=false; break; }
6297
+ const cand=pick.cand, uT=pick.uT;
6298
+ // junction dots mark the interior joins only: the two ends of the trunk
5021
6299
  // are corners, not junctions, and a dot on a corner is wrong.
5022
- const xs=cand.map(c=>c.cs).concat([tc]);
5023
- const cLo=Math.min(...xs), cHi=Math.max(...xs);
6300
+ const us=cand.map(c=>c.u).concat([uT]);
6301
+ const uLo=Math.min(...us), uHi=Math.max(...us);
5024
6302
  const dots=[];
5025
- for(const c of cand) if(c.cs>cLo+0.5&&c.cs<cHi-0.5) dots.push(P(railF,c.cs));
5026
- if(tc>cLo+0.5&&tc<cHi-0.5&&!dots.some(d=>Math.abs(d[horiz?1:0]-tc)<0.5)) dots.push(P(railF,tc));
5027
- // one label and one arrowhead for the whole bus: the member whose rail
5028
- // run is longest carries the label, document order breaks the tie.
6303
+ for(const c of cand) if(c.u>uLo+0.5&&c.u<uHi-0.5) dots.push(c.jp);
6304
+ if(uT>uLo+0.5&&uT<uHi-0.5&&
6305
+ !dots.some(d=>Math.hypot(d[0]-pick.tp[0],d[1]-pick.tp[1])<0.5)) dots.push(pick.tp);
6306
+ // one arrowhead for the whole bus, and the member whose trunk run is
6307
+ // longest leads it; document order breaks the tie.
5029
6308
  let lead=cand[0], best=-1;
5030
- for(const c of cand){ const d=Math.abs(c.cs-tc); if(d>best+0.5){ best=d; lead=c; } }
6309
+ for(const c of cand){ const d=Math.abs(c.u-uT); if(d>best+0.5){ best=d; lead=c; } }
5031
6310
  built.push({T,cand,dots,lead});
5032
6311
  }
5033
6312
  // Nothing to undo when the figure declines: the bus is a routing pass and
@@ -5037,6 +6316,7 @@ function renderScene(doc,y0){
5037
6316
  dots:i===g.cand.length-1?g.dots:null, arrow:i===g.cand.length-1}));
5038
6317
  }
5039
6318
  for(const e of edges){
6319
+ arrowOwner=e;
5040
6320
  const A=byId[e.a], B=byId[e.b]; if(!A||!B) continue;
5041
6321
  // an edge is pure stroke: `stroke=` and `fill=` name the same channel
5042
6322
  // (stroke= wins), `text=` colours the [tail]/[mid]/[head] labels.
@@ -5054,31 +6334,99 @@ function renderScene(doc,y0){
5054
6334
  const wantsStart=e.op==='<->'||e.op==='<-', wantsEnd=e.op==='<->'||e.op==='->';
5055
6335
  const m1='', m2=''; // markers removed — arrowTri() paints triangles above nodes in lblsvg
5056
6336
  const halo=' paint-order="stroke" stroke="#fff" stroke-width="3"';
5057
- const seg=(p,q,t,lbl,fs)=>reqLabel({p,q,t0:t,text:lbl,fs,col:ecol,halo,e,A,B,kind:'end'});
6337
+ // ENDPOINT LABELS ANCHOR BY DISTANCE, NOT BY FRACTION (R? 0.4,
6338
+ // engine-backlog item 42). A `[tail]`/`[head]` label exists to say WHICH
6339
+ // END is called that; a placement at a FRACTION of the run says it only
6340
+ // when the run is long. On `patterns/topology-a`'s 70 px edge both `p1`s
6341
+ // landed mid-span, 23 px apart at the same y — two identical strings that
6342
+ // named neither end. So the request no longer carries a preferred
6343
+ // PARAMETER: it carries its OWN endpoint (`p`), the inward direction
6344
+ // (`q`), the OTHER end of the whole edge (`other`) and the edge's total
6345
+ // run (`tot`). The placement pass turns those into a fixed distance,
6346
+ // clamped to half the edge, and refuses any candidate whose box centre is
6347
+ // not strictly nearer its own endpoint than the other one.
6348
+ const runLen=pp=>{let s=0;for(let i=0;i+1<pp.length;i++)s+=Math.hypot(pp[i+1][0]-pp[i][0],pp[i+1][1]-pp[i][1]);return s;};
6349
+ // ── PORT MARKERS ARE THE TOPOLOGY CONVENTION (item 57) ────────────────
6350
+ // On a network diagram the interface name is written INSIDE the device
6351
+ // box, at the point the link crosses its border. That is not decoration:
6352
+ // it is what makes the name unambiguous, because a port belongs to a
6353
+ // DEVICE and the box is the device. `patterns/topology-a` is the case —
6354
+ // six links, twelve `p*` labels, every one of them floating in the seam
6355
+ // between two tiers where the reader has to decide by eye which box each
6356
+ // belongs to, and Access Node 1's two are the pair that cannot be
6357
+ // decided at all.
6358
+ //
6359
+ // So in the `topology` genre an endpoint label carries its OWN NODE, and
6360
+ // the placement pass below anchors it at the BORDER CROSSING, just inside
6361
+ // the box, instead of 16 px out along the shaft. Everything else about
6362
+ // the request is unchanged — same kind, same font, same collision
6363
+ // scoring, same `other`-end affinity filter — so the batch-2 machinery
6364
+ // does the work and only the candidate family is new.
6365
+ //
6366
+ // The owner is read from the GEOMETRY rather than passed in: `p` is the
6367
+ // point on a border and the owner is the box that border belongs to.
6368
+ // Every `seg()` call passes the tail end with A's border point and the
6369
+ // head end with B's, so this is the same answer with no call site to
6370
+ // keep in step.
6371
+ const portOwner=p=>{
6372
+ if(doc.genre!=='topology'||!A||!B||A.boundary||B.boundary) return null;
6373
+ const d=(N)=>Math.hypot(Math.max(N.x-p[0],0,p[0]-(N.x+N.w)),
6374
+ Math.max(N.y-p[1],0,p[1]-(N.y+N.h)));
6375
+ return A===B ? A : (d(A)<=d(B)?A:B);
6376
+ };
6377
+ const seg=(p,q,lbl,fs,other,tot)=>reqLabel({p,q,text:lbl,fs,col:ecol,halo,e,A,B,kind:'end',
6378
+ other,tot,port:portOwner(p)});
5058
6379
  const bus=busRoute.get(e);
5059
6380
  if(bus){
5060
6381
  const pts=bus.pts;
5061
6382
  // data-bus is written LAST so every reader that keys on the
5062
6383
  // `d=… fill=none stroke=… stroke-width=1.6` prefix is unaffected.
5063
- esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(pts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash+' data-bus="'+esc(bus.bus)+'"/>');
6384
+ // ONE TRUNK, ONE DASH (item 60). The shared trunk is stroked once per
6385
+ // member — that is the convention `data-bus` records — and each member's
6386
+ // dash pattern starts at ITS OWN path start, so three members whose legs
6387
+ // are different lengths lay three differently-phased dash patterns over
6388
+ // the same trunk and the gaps fill in: `bfd-session`'s admin trunk drew
6389
+ // SOLID purple under a legend that says the class is dashed, which is
6390
+ // the drawing contradicting the key. Every member's path ENDS at the
6391
+ // same point (the target's border), so aligning the phase there aligns
6392
+ // it along the whole shared run: the offset is whatever brings the
6393
+ // pattern to a period boundary at the path's end.
6394
+ const per=e.style==='dashed'?10:(e.style==='dotted'?6:0);
6395
+ const doff=per?' stroke-dashoffset="'+(((per-(runLen(pts)%per))%per).toFixed(2))+'"':'';
6396
+ esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(pts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash+doff+' data-bus="'+esc(bus.bus)+'"/>');
5064
6397
  noteSegs(e,pts);
5065
6398
  for(const p of pts){ W=Math.max(W,p[0]+4); Hh=Math.max(Hh,p[1]+4-y0-20); }
5066
6399
  if(bus.dots) for(const d of bus.dots)
5067
6400
  lblsvg.push('<circle cx="'+d[0]+'" cy="'+d[1]+'" r="3" fill="'+col+'" stroke="none"/>');
5068
- // the trunk is drawn once by every member; the label and the arrowhead
5069
- // are drawn ONCE for the bus, which is the whole point of merging it.
5070
- if(bus.lead&&e.mid){ // longest rail run carries the one label
5071
- let bi=0,bl=-1;
5072
- for(let i=0;i+1<pts.length;i++){
5073
- const l=Math.hypot(pts[i+1][0]-pts[i][0],pts[i+1][1]-pts[i][1]);
5074
- if(l>bl){ bl=l; bi=i; }
5075
- }
5076
- reqLabel({p:pts[bi],q:pts[bi+1],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:bi===0});
5077
- }
6401
+ // ── A MERGE-BUS LABELS AT EACH MEMBER'S OWN BLOCK EDGE (item 54) ───
6402
+ // A merged bus used to carry ONE label, on the shared trunk, because
6403
+ // that is what "they all say the same thing" seemed to mean. It reads
6404
+ // wrong. The trunk is the part of the drawing that belongs to no
6405
+ // member, and a word out there names the RAIL; what a reader wants to
6406
+ // know at each exit is what LEAVING THIS BLOCK means, and the place
6407
+ // they look for it is the connection point.
6408
+ //
6409
+ // So the text moves to the LEG and the trunk carries none: every
6410
+ // member with a label registers it as an ENDPOINT-kind request on its
6411
+ // own first segment, which anchors it 16 px from the source border —
6412
+ // the same distance and the same machinery a port label uses. On
6413
+ // `patterns/state-b` that is four small `reset` texts at the four
6414
+ // exits and one unlabelled trunk.
6415
+ //
6416
+ // THE REPETITION IS THE POINT, NOT A DEFECT. The admission rule for a
6417
+ // bus is that every member says the SAME thing (one label, one stroke,
6418
+ // one dash), so per-leg labelling necessarily repeats that one word
6419
+ // once per exit. That is the direction: the merge is about the INK of
6420
+ // the route, not about suppressing the statement at each origin.
6421
+ // the trunk is drawn once by every member; the arrowhead is drawn ONCE
6422
+ // for the bus, which is the whole point of merging its ink.
6423
+ if(e.mid)
6424
+ reqLabel({p:pts[0],q:pts[1],text:e.mid,fs:11,col:lcol,halo,e,A,B,
6425
+ kind:'end',other:pts[pts.length-1],tot:runLen(pts)});
5078
6426
  if(bus.arrow&&wantsEnd) arrowTri(pts[pts.length-1],pts[pts.length-2],col);
5079
6427
  continue;
5080
6428
  }
5081
- if(isBack.has(e)&&!pinned(e.a)&&!pinned(e.b)){
6429
+ if(chBack(e)&&!pinned(e.a)&&!pinned(e.b)){
5082
6430
  // ── ROUTING-CHANGE ARCHITECTURE NOTE (`SELF-EDGE-DRAWING`/`EDGE-BEND-RETENTION`) ──────────
5083
6431
  // Edge labels are DEFERRED: every label is registered against its
5084
6432
  // FINAL segment geometry (reqLabel/lblReq above) and placed by ONE
@@ -5146,8 +6494,8 @@ function renderScene(doc,y0){
5146
6494
  // is a placement a reader still reads as belonging to the loop.
5147
6495
  if(e.mid) reqLabel({p:sp[1],q:sp[2],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false,
5148
6496
  ts:[0.5,0.2,0.8,-0.7,1.7,-1.4,2.4],tw:10});
5149
- if(e.tail) seg(sp[0],sp[1],0.5,e.tail,10);
5150
- if(e.head) seg(sp[3],sp[2],0.5,e.head,10);
6497
+ if(e.tail) seg(sp[0],sp[1],e.tail,10,sp[3],runLen(sp));
6498
+ if(e.head) seg(sp[3],sp[2],e.head,10,sp[0],runLen(sp));
5151
6499
  if(wantsStart) arrowTri(sp[0],sp[1],col);
5152
6500
  if(wantsEnd) arrowTri(sp[sp.length-1],sp[sp.length-2],col);
5153
6501
  continue;
@@ -5177,11 +6525,7 @@ function renderScene(doc,y0){
5177
6525
  // shorter than the label puts the box back on top of the source box
5178
6526
  // whatever parameter is chosen (bfd-session's "Detect expired, Echo
5179
6527
  // failed" is 169 px wide and a fixed 64 px stub buried it in INIT).
5180
- const srcStub=(pp,wpx)=>{
5181
- const a=pp[0], b=pp[1], L=Math.hypot(b[0]-a[0],b[1]-a[1])||1;
5182
- const k=Math.min(1,Math.max(64,wpx+24)/L);
5183
- return [a,[a[0]+(b[0]-a[0])*k, a[1]+(b[1]-a[1])*k]];
5184
- };
6528
+ const srcStub=srcStubOf;
5185
6529
  if(horiz){ // channel runs below the lanes
5186
6530
  const chY=occB+28+P.slot; // labels ride ON the channel
5187
6531
  const colR=r=>Math.max(...lane(r).map(n=>n.x+n.w));
@@ -5195,7 +6539,7 @@ function renderScene(doc,y0){
5195
6539
  const gx=colR(B.rank)+10+ring*7;
5196
6540
  pts.push([gx,chY],[gx,B.y+B.h*P.ef],[outSide(B,'r'),B.y+B.h*P.ef]);
5197
6541
  } else pts.push([tx,chY],[tx,outSide(B,'b')]);
5198
- if(e.mid){
6542
+ if(e.mid&&!P.bus){
5199
6543
  const ss=srcStub(pts,lblPx(e.mid)), c1=pts.findIndex(p=>p[1]===chY);
5200
6544
  reqLabel({p:ss[0],q:ss[1],alt:[pts[c1],pts[c1+1]],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false});
5201
6545
  }
@@ -5203,7 +6547,7 @@ function renderScene(doc,y0){
5203
6547
  const sx=A.x+A.w/2;
5204
6548
  const gy=occB+14+ring*12, chX=occR+28+P.slot, topY=chTop-14-ring*12;
5205
6549
  pts.push([sx,outSide(A,'b')],[sx,gy],[chX,gy],[chX,topY],[P.ex,topY],[P.ex,outSide(B,'t')]);
5206
- if(e.mid){
6550
+ if(e.mid&&!P.bus){
5207
6551
  const ss=srcStub(pts,lblPx(e.mid)), c1=pts.findIndex(p=>p[0]===chX);
5208
6552
  reqLabel({p:ss[0],q:ss[1],alt:[pts[c1],pts[c1+1]],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false});
5209
6553
  }
@@ -5220,18 +6564,45 @@ function renderScene(doc,y0){
5220
6564
  const gy=laneB(B.rank)+10+ring*7;
5221
6565
  pts.push([chX,gy],[B.x+B.w*P.ef,gy],[B.x+B.w*P.ef,outSide(B,'b')]);
5222
6566
  } else pts.push([chX,ty],[outSide(B,'r'),ty]);
5223
- if(e.mid){
6567
+ if(e.mid&&!P.bus){
5224
6568
  const ss=srcStub(pts,lblPx(e.mid)), c1=pts.findIndex(p=>p[0]===chX);
5225
6569
  reqLabel({p:ss[0],q:ss[1],alt:[pts[c1],pts[c1+1]],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false});
5226
6570
  }
5227
6571
  }
6572
+ // A return-bus member's own leg is pts[0]->pts[1] on every form the plan
6573
+ // builds above; pts[1] is therefore where it joins the shared trunk. It is
6574
+ // recorded HERE, before the detour pass can splice points in front of it.
6575
+ if(P.bus&&pts.length>1){
6576
+ if(!busJoins.has(P.bus)) busJoins.set(P.bus,[]);
6577
+ busJoins.get(P.bus).push(pts[1]);
6578
+ }
5228
6579
  // non-incident nodes are obstacles for the channel runs too: a run
5229
6580
  // that would cut through a sibling (e.g. a pinned node parked on the
5230
6581
  // escape lane) detours around it instead of drawing across it. When
5231
6582
  // spanning the following corner point gives a shorter total run than
5232
6583
  // detour + remaining leg (a detour "spike"), the corner is dropped.
5233
- const obsN=nodes.filter(n=>n!==A&&n!==B&&!n.boundary).map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}));
6584
+ const obsN=nodes.filter(n=>n!==A&&n!==B&&!n.boundary).map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}))
6585
+ .concat(lblObs(e));
5234
6586
  const plen=pp=>{let s=0;for(let k=0;k+1<pp.length;k++)s+=Math.hypot(pp[k+1][0]-pp[k][0],pp[k+1][1]-pp[k][1]);return s;};
6587
+ // A SHORTCUT THAT BUYS A CROSSING IS NOT A SHORTCUT (item 45a). The
6588
+ // spike-prune below trades a planned channel corner for a straight span
6589
+ // whenever the span is shorter. It measures LENGTH and nothing else, so
6590
+ // on `showcase/arp-resolution` — where the element-label obstacle above
6591
+ // is what first pushed the shaft off the label — it happily replaced the
6592
+ // orthogonal channel corner with a long diagonal straight across the
6593
+ // broadcast arrow. Ink went down, the reader's job got harder. The prune
6594
+ // therefore also asks whether the span crosses a line already on the
6595
+ // canvas; `edgeSegs` holds exactly those, in draw order.
6596
+ const xseg=(a1,a2,b1,b2)=>{
6597
+ const d=(p1,p2,p3)=>(p2[0]-p1[0])*(p3[1]-p1[1])-(p2[1]-p1[1])*(p3[0]-p1[0]);
6598
+ const d1=d(a1,a2,b1), d2=d(a1,a2,b2), d3=d(b1,b2,a1), d4=d(b1,b2,a2);
6599
+ return ((d1>0)!==(d2>0))&&((d3>0)!==(d4>0));
6600
+ };
6601
+ const spanCuts=pp=>{
6602
+ for(let k=0;k+1<pp.length;k++)
6603
+ for(const g of edgeSegs) if(g.e!==e&&xseg(pp[k],pp[k+1],g.p,g.q)) return true;
6604
+ return false;
6605
+ };
5235
6606
  for(let i=0;i+1<pts.length;i++){
5236
6607
  const d=routeAround(pts[i],pts[i+1],obsN);
5237
6608
  if(!d) continue;
@@ -5239,7 +6610,7 @@ function renderScene(doc,y0){
5239
6610
  if(i+2<pts.length){
5240
6611
  const span=segHitsObs(pts[i],pts[i+2],obsN)
5241
6612
  ?routeAround(pts[i],pts[i+2],obsN):[pts[i],pts[i+2]];
5242
- if(span&&plen(span)<plen(d)+Math.hypot(pts[i+2][0]-pts[i+1][0],pts[i+2][1]-pts[i+1][1])-1e-6){
6613
+ if(span&&!spanCuts(span)&&plen(span)<plen(d)+Math.hypot(pts[i+2][0]-pts[i+1][0],pts[i+2][1]-pts[i+1][1])-1e-6){
5243
6614
  ins=span.slice(1,-1); drop=1;
5244
6615
  }
5245
6616
  }
@@ -5247,12 +6618,89 @@ function renderScene(doc,y0){
5247
6618
  i+=ins.length;
5248
6619
  }
5249
6620
  for(const p of pts){ W=Math.max(W,p[0]+4); Hh=Math.max(Hh,p[1]+16-y0-20); }
5250
- esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(pts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash+'/>');
6621
+ // RETURN BUS (item 46): the collapsed members draw the same trunk, so the
6622
+ // path carries `data-bus` for exactly the reason the forward bus does —
6623
+ // it is what lets a reader (and `layout-lint`'s coincident term) tell a
6624
+ // deliberate shared trunk from two lines hidden under each other. Written
6625
+ // LAST, after stroke-width, so no existing reader breaks.
6626
+ esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(pts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash
6627
+ +(P.bus?' data-bus="'+esc(P.bus)+'"':'')+'/>');
5251
6628
  noteSegs(e,pts);
5252
- if(e.tail) seg(pts[0],pts[1],0.5,e.tail,10);
5253
- if(e.head) seg(pts[pts.length-1],pts[pts.length-2],0.5,e.head,10);
5254
- if(wantsStart) arrowTri(pts[0],pts[1],col);
5255
- if(wantsEnd) arrowTri(pts[pts.length-1],pts[pts.length-2],col);
6629
+ if(P.busTail){
6630
+ // JUNCTION DOTS. Every member's OWN leg ends where the shared run
6631
+ // begins — pts[1] on every route form the channel plan builds (the drop
6632
+ // to the rail, the reach out to the trunk) — so the joins are collected
6633
+ // as the members draw and the last one dots them. The join FARTHEST
6634
+ // from the arrival is the rail's own end: a corner, not a junction, and
6635
+ // the forward bus does not dot its corners either.
6636
+ const jx=(busJoins.get(P.bus)||[]).slice(), tip=pts[pts.length-1];
6637
+ if(jx.length>1){
6638
+ let far=0;
6639
+ for(let i2=1;i2<jx.length;i2++)
6640
+ if(Math.hypot(jx[i2][0]-tip[0],jx[i2][1]-tip[1])>Math.hypot(jx[far][0]-tip[0],jx[far][1]-tip[1])) far=i2;
6641
+ jx.splice(far,1);
6642
+ }
6643
+ for(const d of jx)
6644
+ lblsvg.push('<circle cx="'+d[0]+'" cy="'+d[1]+'" r="3" fill="'+col+'" stroke="none"/>');
6645
+ }
6646
+ // ITEM 54: the label rides the member's OWN leg, at its origin block's
6647
+ // edge, and the shared trunk carries none. See the forward bus above
6648
+ // for why — the trunk belongs to no member, and the connection point
6649
+ // is where a branch's meaning is read.
6650
+ if(e.mid&&P.bus)
6651
+ reqLabel({p:pts[0],q:pts[1],text:e.mid,fs:11,col:lcol,halo,e,A,B,
6652
+ kind:'end',other:pts[pts.length-1],tot:runLen(pts)});
6653
+ if(e.tail) seg(pts[0],pts[1],e.tail,10,pts[pts.length-1],runLen(pts));
6654
+ if(e.head) seg(pts[pts.length-1],pts[pts.length-2],e.head,10,pts[0],runLen(pts));
6655
+ if(wantsStart&&(!P.bus||P.busTail)) arrowTri(pts[0],pts[1],col);
6656
+ if(wantsEnd&&(!P.bus||P.busTail)) arrowTri(pts[pts.length-1],pts[pts.length-2],col);
6657
+ continue;
6658
+ }
6659
+ // ── corridor route (items 41/46): side chosen by occupancy, lane by
6660
+ // distance from the shared target. Same detour and label discipline as
6661
+ // the channel routes — a corridor is a channel the figure chose.
6662
+ const lrPts=longRoute(e);
6663
+ if(lrPts){
6664
+ for(const p of lrPts){ W=Math.max(W,p[0]+4); Hh=Math.max(Hh,p[1]+16-y0-20); }
6665
+ esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(lrPts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash+'/>');
6666
+ noteSegs(e,lrPts);
6667
+ if(e.mid){
6668
+ // WHICH LEG CARRIES THE LABEL, and it is the OPPOSITE of the channel
6669
+ // router's answer. A channel run is the figure's outermost lane, so a
6670
+ // label out there says nothing about which line it names and the stub
6671
+ // wins. A CORRIDOR was chosen precisely because that margin is free —
6672
+ // that is the whole selection rule — so its long run is the clear ink
6673
+ // and the stub is the squeezed end, wedged between a source and the
6674
+ // figure's edge. Measured on dhcp-client: stub-first put
6675
+ // "server refuses / NAK -> drop IP" into the RENEWING/REBINDING corner
6676
+ // and took `lblcol` 2 -> 5; run-first leaves it on the open margin. The
6677
+ // stub stays as the ALTERNATE, so a corridor whose run is busy can
6678
+ // still fall back to it.
6679
+ const ss=srcStubOf(lrPts,lblPx(e.mid));
6680
+ let bi=0,bl=-1;
6681
+ for(let i=0;i+1<lrPts.length;i++){
6682
+ const dxx=lrPts[i+1][0]-lrPts[i][0], dyy=lrPts[i+1][1]-lrPts[i][1];
6683
+ if(Math.abs(dxx)>0.5&&Math.abs(dyy)>0.5) continue; // axis-aligned runs only
6684
+ const l=Math.hypot(dxx,dyy);
6685
+ if(l>bl){ bl=l; bi=i; }
6686
+ }
6687
+ // ...WITH ONE EXCEPTION, AND IT IS THE FLOWCHART CONVENTION (`FLOWCHART-ROLE-KEYWORDS`).
6688
+ // A short branch marker leaving a decision — `yes`, `no` — names that
6689
+ // BRANCH, and it reads as the branch's name only next to the decision.
6690
+ // The placement pass already knows this (its `branch` test), and it is
6691
+ // reachable only from the FIRST segment, so a corridor whose label is a
6692
+ // branch marker hands the stub back the primary carrier: flowchart-b's
6693
+ // left-margin `no` otherwise sat halfway down the figure, level with the
6694
+ // OTHER `no`, naming neither.
6695
+ const branch=A.role==='decision'&&String(e.mid).length<=3&&!String(e.mid).includes('\n');
6696
+ if(bl<0||branch) reqLabel({p:ss[0],q:ss[1],alt:bl<0?null:[lrPts[bi],lrPts[bi+1]],
6697
+ text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:true});
6698
+ else reqLabel({p:lrPts[bi],q:lrPts[bi+1],alt:[ss[0],ss[1]],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false});
6699
+ }
6700
+ if(e.tail) seg(lrPts[0],lrPts[1],e.tail,10,lrPts[lrPts.length-1],runLen(lrPts));
6701
+ if(e.head) seg(lrPts[lrPts.length-1],lrPts[lrPts.length-2],e.head,10,lrPts[0],runLen(lrPts));
6702
+ if(wantsStart) arrowTri(lrPts[0],lrPts[1],col);
6703
+ if(wantsEnd) arrowTri(lrPts[lrPts.length-1],lrPts[lrPts.length-2],col);
5256
6704
  continue;
5257
6705
  }
5258
6706
  const chain=chains.get(e);
@@ -5346,8 +6794,8 @@ function renderScene(doc,y0){
5346
6794
  esvg.push('<path data-edge="'+e.line+'" d="'+roundPath(pts)+'" fill="none" stroke="'+col+'" stroke-width="1.6"'+dash+'/>');
5347
6795
  noteSegs(e,pts);
5348
6796
  if(midSeg) reqLabel({p:midSeg[0],q:midSeg[1],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:false});
5349
- if(e.tail) seg(p0,pts[1],0.4,e.tail,10);
5350
- if(e.head) seg(p1,pts[pts.length-2],0.4,e.head,10);
6797
+ if(e.tail) seg(p0,pts[1],e.tail,10,p1,runLen(pts));
6798
+ if(e.head) seg(p1,pts[pts.length-2],e.head,10,p0,runLen(pts));
5351
6799
  if(wantsStart) arrowTri(pts[0],pts[1],col);
5352
6800
  if(wantsEnd) arrowTri(pts[pts.length-1],pts[pts.length-2],col);
5353
6801
  continue;
@@ -5362,7 +6810,8 @@ function renderScene(doc,y0){
5362
6810
  // (routeAround). Obstacle-free edges keep the plain line unchanged.
5363
6811
  let route=null;
5364
6812
  if(A!==B){
5365
- const obs=nodes.filter(n=>n!==A&&n!==B&&!n.boundary).map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}));
6813
+ const obs=nodes.filter(n=>n!==A&&n!==B&&!n.boundary).map(n=>({x:n.x,y:n.y,w:n.w,h:n.h}))
6814
+ .concat(lblObs(e));
5366
6815
  for(const k in gBox){
5367
6816
  const b=gBox[k];
5368
6817
  const inG=(px,py)=>px>b.x0&&px<b.x1&&py>b.yA&&py<b.yB;
@@ -5386,8 +6835,8 @@ function renderScene(doc,y0){
5386
6835
  }
5387
6836
  reqLabel({p:route[bi],q:route[bi+1],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:bi===0});
5388
6837
  }
5389
- if(e.tail) seg(route[0],route[1],0.25,e.tail,10);
5390
- if(e.head) seg(route[route.length-1],route[route.length-2],0.25,e.head,10);
6838
+ if(e.tail) seg(route[0],route[1],e.tail,10,route[route.length-1],runLen(route));
6839
+ if(e.head) seg(route[route.length-1],route[route.length-2],e.head,10,route[0],runLen(route));
5391
6840
  if(wantsStart) arrowTri(route[0],route[1],col);
5392
6841
  if(wantsEnd) arrowTri(route[route.length-1],route[route.length-2],col);
5393
6842
  for(const pP of route){ W=Math.max(W,pP[0]+4); Hh=Math.max(Hh,pP[1]+4-y0-20); }
@@ -5398,8 +6847,8 @@ function renderScene(doc,y0){
5398
6847
  if(e.mid)
5399
6848
  reqLabel({p:[x1,yy1],q:[x2,yy2],text:e.mid,fs:11,col:lcol,halo,e,A,B,kind:'mid',first:true});
5400
6849
  // endpoint labels at the tail/head positions (three-position model, `EDGE-LABEL-PLACEMENT`)
5401
- if(e.tail) seg([x1,yy1],[x2,yy2],0.18,e.tail,10);
5402
- if(e.head) seg([x1,yy1],[x2,yy2],0.82,e.head,10);
6850
+ if(e.tail) seg([x1,yy1],[x2,yy2],e.tail,10,[x2,yy2],runLen([[x1,yy1],[x2,yy2]]));
6851
+ if(e.head) seg([x2,yy2],[x1,yy1],e.head,10,[x1,yy1],runLen([[x1,yy1],[x2,yy2]]));
5403
6852
  if(wantsStart) arrowTri([x1,yy1],[x2,yy2],col);
5404
6853
  if(wantsEnd) arrowTri([x2,yy2],[x1,yy1],col);
5405
6854
  }
@@ -5434,6 +6883,9 @@ function renderScene(doc,y0){
5434
6883
  else { ox=cx-bw/2; oy=(bdy>=0?cy+17:cy-10)-13*bl/2-1.5; }
5435
6884
  obst.push({x:ox,y:oy,w:bw,h:bh,n:null});
5436
6885
  }
6886
+ // gap between two boxes, 0 when they touch or overlap (item 43's tie-break)
6887
+ const boxGap=(a,b)=>Math.hypot(Math.max(0,Math.max(a.x-(b.x+b.w), b.x-(a.x+a.w))),
6888
+ Math.max(0,Math.max(a.y-(b.y+b.h), b.y-(a.y+a.h))));
5437
6889
  const ovl=(a,b)=>{
5438
6890
  const ix=Math.min(a.x+a.w,b.x+b.w)-Math.max(a.x,b.x);
5439
6891
  const iy=Math.min(a.y+a.h,b.y+b.h)-Math.max(a.y,b.y);
@@ -5453,7 +6905,56 @@ function renderScene(doc,y0){
5453
6905
  }
5454
6906
  return t1>t0;
5455
6907
  };
6908
+ // distance from a segment to a label box, measured to the box CENTRE —
6909
+ // the same point F5 measures from, so the scorer and the gate agree.
6910
+ const segBoxD=(p,q,b)=>{
6911
+ const cx=b.x+b.w/2, cy=b.y+b.h/2;
6912
+ const vx=q[0]-p[0], vy=q[1]-p[1], L2=vx*vx+vy*vy;
6913
+ const t=L2?Math.max(0,Math.min(1,((cx-p[0])*vx+(cy-p[1])*vy)/L2)):0;
6914
+ return Math.hypot(cx-(p[0]+t*vx), cy-(p[1]+t*vy));
6915
+ };
6916
+ // STANDOFF (item 59): the shortest distance from a carrying segment to the
6917
+ // label's own box — 0 when the line enters it. This is the distance a
6918
+ // reader crosses to get from the word to the line, and it is the quantity
6919
+ // the cap below is written in. It is NOT `segBoxD`, which measures to the
6920
+ // box CENTRE: a 117 px label beside a near-vertical shaft has its centre
6921
+ // 57 px away and its nearest edge 6 px away, and only the second number
6922
+ // says whether the two touch on the page.
6923
+ const segBoxGap=(p,q,b)=>{
6924
+ if(segHit(p,q,b)) return 0;
6925
+ const ptRect=(x,y)=>Math.hypot(Math.max(b.x-x,0,x-(b.x+b.w)),
6926
+ Math.max(b.y-y,0,y-(b.y+b.h)));
6927
+ const segPt=(x,y)=>{
6928
+ const vx=q[0]-p[0], vy=q[1]-p[1], L2=vx*vx+vy*vy;
6929
+ const t=L2?Math.max(0,Math.min(1,((x-p[0])*vx+(y-p[1])*vy)/L2)):0;
6930
+ return Math.hypot(x-(p[0]+t*vx), y-(p[1]+t*vy));
6931
+ };
6932
+ let d=Math.min(ptRect(p[0],p[1]), ptRect(q[0],q[1]));
6933
+ for(const c of [[b.x,b.y],[b.x+b.w,b.y],[b.x,b.y+b.h],[b.x+b.w,b.y+b.h]])
6934
+ d=Math.min(d,segPt(c[0],c[1]));
6935
+ return d;
6936
+ };
6937
+ // THE CAP, AND WHERE THE NUMBER COMES FROM (item 59). Measured over the
6938
+ // 137 mid-labels the corpus places: min 0.3 px, median
6939
+ // 3.0, p75 5.3, p90 6.0, p95 6.0 — the base side offset is 6 px and nine
6940
+ // labels in ten sit at it or inside it. Above that the DRAWN corpus uses
6941
+ // 7.9, 11.0, 17.4 and 17.4 px (all four on `statechart/bfd-session`), and
6942
+ // one figure reaches 32.6 — `layout-compare/srl-evpn-irb-auto`, which is
6943
+ // refused at geometry time and never published.
6944
+ //
6945
+ // 18 px, and the corpus chose it. Caps of 8 and of 12 were both built and
6946
+ // measured: each one pulls bfd's two 17.4 px labels ("rx Down" and
6947
+ // "rx Init, rx Up") in to 6.0 px, where their own self-loop then draws
6948
+ // through them — lblcol 2 -> 4 on that figure, in both runs. That relief
6949
+ // is EARNED, so the cap has to sit above it; 18 is three times the base
6950
+ // offset, just clear of the largest standoff the corpus can justify, and
6951
+ // it still refuses a float half again as far. Past the cap a mid-label is
6952
+ // not simply placed further out — it takes a LEADER (below), so the
6953
+ // association is drawn rather than left to proximity.
6954
+ const STANDOFF_CAP=18;
5456
6955
  const CLAMP=t=>Math.max(0.06,Math.min(0.94,t));
6956
+ // Endpoint-label anchor distance (item 42). See the `kind==='end'` branch.
6957
+ const END_D=16;
5457
6958
  // SLOPE CLEARANCE (`cl`): "3 px above the line" clears the line only where
5458
6959
  // the box touches it. The offsets are axis-aligned while the segment is
5459
6960
  // not, so on a diagonal the line keeps climbing across the box's WIDTH and
@@ -5465,27 +6966,111 @@ function renderScene(doc,y0){
5465
6966
  // below: a label 7 px further out to stop being struck is worth it, a
5466
6967
  // 90 px shove for a long label on a 45 degree line is not, and the scorer
5467
6968
  // decides which case it is holding.
5468
- const cand=(r,t,side,cl)=>{
6969
+ const cand=(r,t,side,cl,ep)=>{
5469
6970
  const lines=String(r.text).split('\n'), n=lines.length;
5470
6971
  const w=Math.max(...lines.map(cw))*6.5*r.fs/11;
5471
6972
  const lh=r.fs*1.3, h=(n-1)*lh+r.fs*1.1;
5472
6973
  const up=(n-1)*lh/2+r.fs*0.85; // baseline y = box top + up
5473
6974
  const mx=r.p[0]+(r.q[0]-r.p[0])*t, my=r.p[1]+(r.q[1]-r.p[1])*t;
5474
6975
  const sdx=Math.abs(r.q[0]-r.p[0]), sdy=Math.abs(r.q[1]-r.p[1]);
5475
- let ex=0;
6976
+ let ex=ep||0; // extra perpendicular push (endpoint labels' escape)
5476
6977
  if(cl){
5477
- if(side==='above'||side==='below') ex=sdx>1e-9?Math.min(1,sdy/sdx)*w/2:0;
5478
- else if(side==='right'||side==='left') ex=sdy>1e-9?Math.min(1,sdx/sdy)*h/2:0;
6978
+ if(side==='above'||side==='below') ex+=sdx>1e-9?Math.min(1,sdy/sdx)*w/2:0;
6979
+ else if(side==='right'||side==='left') ex+=sdy>1e-9?Math.min(1,sdx/sdy)*h/2:0;
5479
6980
  }
6981
+ // FLUSH THE INK AGAINST THE SHAFT (item 59). `w` is an ESTIMATE — 6.5 px
6982
+ // per character at font-size 11 — and it runs about a sixth wide of what
6983
+ // the browser actually sets. That slack has to go somewhere, and until
6984
+ // this release it went on whichever side the anchor left it: a `left`
6985
+ // label was anchored `start` at the box's LEFT edge, so every pixel of
6986
+ // over-estimate opened up between the last glyph and the line the label
6987
+ // names. Measured on `showcase/tcp-state-machine`: both
6988
+ // "CLOSE / delete TCB" boxes hug their purple shaft at the placement's
6989
+ // own 6 px, and the TEXT stops 23 px short of it — which is the distance
6990
+ // the maintainer's review calls a drift the tone pairing cannot rescue.
6991
+ // A side label is therefore anchored on the edge that FACES its shaft:
6992
+ // `end` on the left, `start` on the right, so the ragged edge falls away
6993
+ // from the line and the estimate's slack can never be read as standoff.
6994
+ // The BOX is unchanged, so nothing in the collision scoring moves.
5480
6995
  let bx,by,x,anchor=n>1?'middle':'start';
5481
6996
  if(side==='on') { bx=mx-w/2; by=my-4-up; anchor='middle'; }
5482
6997
  else if(side==='above') { bx=mx-w/2; by=my-3-h-ex; anchor='middle'; }
5483
6998
  else if(side==='below') { bx=mx-w/2; by=my+3+ex; anchor='middle'; }
5484
- else if(side==='right') { bx=mx+6+ex; by=my-h/2; }
5485
- else { bx=mx-6-w-ex; by=my-h/2; }
5486
- x=anchor==='middle'?bx+w/2:bx;
6999
+ else if(side==='right') { bx=mx+6+ex; by=my-h/2; anchor='start'; }
7000
+ else { bx=mx-6-w-ex; by=my-h/2; anchor='end'; }
7001
+ x=anchor==='middle'?bx+w/2:anchor==='end'?bx+w:bx;
5487
7002
  return {x,y:by+up,anchor,t,side,ex,box:{x:bx,y:by,w,h}};
5488
7003
  };
7004
+ // ── PORT-MARKER CANDIDATES (item 57) ──────────────────────────────────
7005
+ // The 16 px own-port anchor of item 42 becomes a BORDER-CROSSING anchor:
7006
+ // the box sits just inside the node, on the side the link crosses, with
7007
+ // its along-border position free so two ports on one border spread
7008
+ // instead of stacking. `PORT_IN` is the gap from the border line to the
7009
+ // marker (enough that the box does not sit ON the stroke); `PORT_END` is
7010
+ // how near a corner a marker may be written; the offsets are one marker
7011
+ // width apart, which is exactly the pitch two ports need to be two.
7012
+ const PORT_IN=2, PORT_END=4, PORT_HUG=25, PORT_OUT=60;
7013
+ // The node's own drawn label, computed by the SAME formulas the node pass
7014
+ // emits it with (shrink-to-fit included), so the obstacle and the drawing
7015
+ // cannot disagree about where a name is.
7016
+ const nodeInk=n=>{
7017
+ if(!n||!n.label) return null;
7018
+ const nl=String(n.label).split('\n');
7019
+ const need=Math.max(...nl.map(cw))*CH;
7020
+ const avail=2*inscribedHalfW(shapeAxes(n),nl.length*8)-16;
7021
+ const fs=(n.rigid&&need>avail)?Math.max(8,FONT*avail/need):FONT;
7022
+ const lw=need*fs/FONT, lh=nl.length*fs*1.15;
7023
+ return {x:n.x+n.w/2-lw/2, y:n.y+n.h/2-lh/2, w:lw, h:lh};
7024
+ };
7025
+ // A label's box is its LINE box: full leading above and below. Its INK is
7026
+ // the glyph band inside that, and the two questions are different (see the
7027
+ // own-name term in the scorer).
7028
+ const inkBox=(b,fs)=>({x:b.x, y:b.y+fs*0.14, w:b.w, h:Math.max(1,b.h-fs*0.28)});
7029
+ const portCands=r=>{
7030
+ const N=r.port, P=r.p, out=[];
7031
+ if(!N) return out;
7032
+ const lines=String(r.text).split('\n'), nL=lines.length;
7033
+ const w=Math.max(...lines.map(cw))*6.5*r.fs/11;
7034
+ const lh=r.fs*1.3, h=(nL-1)*lh+r.fs*1.1, up=(nL-1)*lh/2+r.fs*0.85;
7035
+ // Which border did the link cross? The nearest side of the box.
7036
+ const dl=Math.abs(P[0]-N.x), dr=Math.abs(P[0]-(N.x+N.w)),
7037
+ dt=Math.abs(P[1]-N.y), db=Math.abs(P[1]-(N.y+N.h));
7038
+ const m=Math.min(dl,dr,dt,db);
7039
+ const side=m===dt?'top':m===db?'bottom':m===dl?'left':'right';
7040
+ const vert=(side==='top'||side==='bottom');
7041
+ // ROOM. A marker that cannot be written between the two corners of the
7042
+ // side it crosses has no inside form at all; the ordinary outside
7043
+ // family is then the only one offered, which is the stated fallback.
7044
+ const span=vert?N.w:N.h, need=(vert?w:h)+2*PORT_END;
7045
+ if(span<need) return out;
7046
+ const lo=(vert?N.x:N.y)+PORT_END, hi=(vert?N.x+N.w:N.y+N.h)-PORT_END;
7047
+ const pitch=(vert?w:h)+4;
7048
+ const u0=vert?P[0]:P[1];
7049
+ // TWO RINGS OF CANDIDATES, AND BOTH ARE AT THE CROSSING.
7050
+ // in = inside the border, the convention proper;
7051
+ // out = the mirror image, just OUTSIDE the same border.
7052
+ // The second exists because a small box genuinely runs out of room —
7053
+ // `reference/topology`'s L1 is 42 x 36 and holds one port name, not two
7054
+ // — and the alternative fallback (the ordinary 16 px-along-the-shaft
7055
+ // family) puts the second name out in the seam BETWEEN the two shafts
7056
+ // arriving at that box, which measured F5 margin 0.47 px: a label that
7057
+ // has stopped saying which of two lines it names. Hugging the border it
7058
+ // could not get inside keeps it on its own port, which is the fact it
7059
+ // exists to state. It is surcharged, so it is taken only after inside
7060
+ // has failed.
7061
+ for(const inside of [true,false]) for(const k of [0,1,-1,2,-2]){
7062
+ const u=Math.max(lo+(vert?w:h)/2, Math.min(hi-(vert?w:h)/2, u0+k*pitch));
7063
+ let bx,by;
7064
+ if(side==='bottom'){ bx=u-w/2; by=inside?N.y+N.h-PORT_IN-h:N.y+N.h+PORT_IN; }
7065
+ else if(side==='top'){ bx=u-w/2; by=inside?N.y+PORT_IN:N.y-PORT_IN-h; }
7066
+ else if(side==='left'){ bx=inside?N.x+PORT_IN:N.x-PORT_IN-w; by=u-h/2; }
7067
+ else { bx=inside?N.x+N.w-PORT_IN-w:N.x+N.w+PORT_IN; by=u-h/2; }
7068
+ out.push({x:bx+w/2, y:by+up, anchor:'middle', t:undefined, side,
7069
+ ex:Math.abs(k)*pitch, inPort:inside, hug:!inside,
7070
+ box:{x:bx,y:by,w,h}});
7071
+ }
7072
+ return out;
7073
+ };
5489
7074
  const placed=[];
5490
7075
  // A request may name a SECOND carrying segment (`alt`). Back edges do: the
5491
7076
  // stub leaving the source is the preferred carrier because it says which
@@ -5496,17 +7081,36 @@ function renderScene(doc,y0){
5496
7081
  // flat surcharge so it is taken only when the stub really has nowhere.
5497
7082
  if(lblReq.length) for(const r0 of lblReq){
5498
7083
  const carriers=[[r0.p,r0.q]].concat(r0.alt?[r0.alt]:[]);
5499
- let best=null,bestS=Infinity;
7084
+ let best=null,bestS=Infinity, anyBest=null,anyS=Infinity, offBest=null,offS=Infinity,
7085
+ farBest=null,farS=Infinity;
5500
7086
  for(let ci=0;ci<carriers.length;ci++){
5501
7087
  const r=ci?Object.assign({},r0,{p:carriers[ci][0],q:carriers[ci][1]}):r0;
5502
7088
  const dx=r.q[0]-r.p[0], dy=r.q[1]-r.p[1];
5503
7089
  const across=Math.abs(dx)>=Math.abs(dy);
5504
- let sides, ts, tPref, apWant=null;
7090
+ let sides, ts, tPref, apWant=null, tScale=r.tw||70;
5505
7091
  if(r.kind==='end'){
5506
- // endpoint labels keep their historical spot as first choice
7092
+ // DISTANCE, NOT FRACTION (item 42). `END_D` is 16 px, chosen from the
7093
+ // instrument rather than from taste: F5's own filter (2) treats a
7094
+ // label within 18 px of a node border as one the reader ties to the
7095
+ // NODE and not to an edge-edge ambiguity, and that is precisely the
7096
+ // reading a port label wants. Anchoring at 16 px puts every endpoint
7097
+ // label inside that reading on every edge long enough to hold it.
7098
+ // The clamp is half the edge's whole run AND half the carrying
7099
+ // segment: a label may never reach the middle of the thing it slides
7100
+ // along, because the middle names no end. Below the clamp the label
7101
+ // sits as near its port as the geometry allows.
7102
+ const Lseg=Math.hypot(dx,dy)||1;
7103
+ const cap=Math.min(0.5*(r.tot||Lseg), 0.5*Lseg);
7104
+ const d0=Math.min(END_D,cap);
7105
+ // The push set is in PIXELS along the edge, outward-biased: a label
7106
+ // driven off its anchor by a collision walks INTO the span (it can
7107
+ // never walk off the end), and it stops at the clamp.
7108
+ const dset=[0,5,-4,10,-8,16,24].map(k=>d0+k).filter(d=>d>=2&&d<=cap+1e-9);
7109
+ if(!dset.length) dset.push(Math.max(1,cap));
7110
+ tPref=d0/Lseg;
7111
+ ts=dset.map(d=>d/Lseg);
7112
+ tScale=1.2*Lseg; // the pull back to the anchor is priced in PIXELS
5507
7113
  sides=['on'].concat(across?['above','below']:['right','left']);
5508
- tPref=r.t0;
5509
- ts=[r.t0,r.t0-0.06,r.t0+0.06,r.t0-0.12,r.t0+0.12].map(CLAMP);
5510
7114
  } else {
5511
7115
  sides=across?['above','below']:['right','left'];
5512
7116
  // ANTI-PARALLEL PAIRS: the label belongs on the OUTSIDE of its own
@@ -5545,17 +7149,86 @@ function renderScene(doc,y0){
5545
7149
  tPref=branch?0.22:0.5;
5546
7150
  ts=r.ts?r.ts:(branch?[0.22,0.3,0.16,0.4,0.5,0.62]:[0.5,0.38,0.62,0.28,0.72]);
5547
7151
  }
5548
- for(let si=0;si<sides.length;si++) for(const t of ts) for(const cl of [0,1]){
5549
- const c=cand(r,t,sides[si],cl);
7152
+ // The perpendicular escape (item 42). When every in-line position is
7153
+ // blocked, an endpoint label must still be able to say which end it
7154
+ // names, and the only remaining freedom is ACROSS the line. 9 px is one
7155
+ // text line-height: enough to clear a co-located neighbour, priced per
7156
+ // pixel below like every other displacement, so it is taken only when
7157
+ // the in-line positions really have nowhere.
7158
+ const eps=r.kind==='end'?[0,9]:[0];
7159
+ // ── THE CANDIDATE FAMILY ──────────────────────────────────────────
7160
+ // Normally: sides x parameters x slope-clearance x escape, as above.
7161
+ // A PORT MARKER (item 57) adds a family in FRONT of it — positions
7162
+ // just inside its own node's border at the crossing — and keeps the
7163
+ // ordinary family behind, surcharged. That is the fallback the
7164
+ // direction asks for, and it is a PRICE rather than a test, so a
7165
+ // marker is pushed back outside exactly when inside is genuinely
7166
+ // blocked (a box too narrow to hold the text, or the node's own name
7167
+ // already there) and never merely because outside happens to be tidy.
7168
+ const cs=[];
7169
+ if(r.port) for(const c of portCands(r)) cs.push({c,si:0});
7170
+ for(let si=0;si<sides.length;si++) for(const t of ts) for(const cl of [0,1]) for(const ep of eps)
7171
+ cs.push({c:cand(r,t,sides[si],cl,ep),si,out:!!r.port});
7172
+ for(const CS of cs){
7173
+ const c=CS.c, si=CS.si, t=(c.t===undefined?tPref:c.t);
7174
+ c.car=[r.p,r.q]; // the carrier this candidate rides (item 59)
7175
+ // ENDPOINT AFFINITY IS A HARD FILTER, NOT A PRICE. A tail label whose
7176
+ // box centre is nearer the head than the tail has stopped stating the
7177
+ // one fact it exists to state, and no amount of collision relief buys
7178
+ // that back. Candidates that fail are dropped; `bestAny` keeps the
7179
+ // least-bad one so a figure with no legal position still draws.
7180
+ let owns=true;
7181
+ if(r.kind==='end'&&r.other){
7182
+ const ccx=c.box.x+c.box.w/2, ccy=c.box.y+c.box.h/2;
7183
+ owns=Math.hypot(ccx-r.p[0],ccy-r.p[1])<Math.hypot(ccx-r.other[0],ccy-r.other[1]);
7184
+ }
5550
7185
  let s=0;
5551
7186
  for(const b of placed) s+=3*ovl(c.box,b);
5552
- for(const o of obst) s+=(o.n===r.A||o.n===r.B?6:2.4)*ovl(c.box,o);
7187
+ // A PORT MARKER IS SUPPOSED TO BE INSIDE ITS OWN BOX (item 57), so
7188
+ // that one node is not charged for it. Every other box still is, at
7189
+ // the usual weights — a marker that has slid out of its own device
7190
+ // and into a neighbour is the defect this convention exists to end.
7191
+ for(const o of obst){ if(c.inPort&&o.n===r.port) continue;
7192
+ s+=(o.n===r.A||o.n===r.B?6:2.4)*ovl(c.box,o); }
7193
+ // ...but the node's own NAME is ink, and a port written across it is
7194
+ // the same misreading `band` captions were fixed for (item 49).
7195
+ //
7196
+ // MEASURED INK TO INK, not line box to line box. Everywhere else in
7197
+ // this pass a label is its generous LINE box, which is right when the
7198
+ // question is "is there room to put this somewhere". Here the two
7199
+ // boxes are already inside one 36 px node and the question is whether
7200
+ // the GLYPHS touch: a 13 px name's line box is 15 px tall and its
7201
+ // letters are about 9, so the line boxes overlap by a pixel or two in
7202
+ // every ordinary topology node and the marker was priced out of a box
7203
+ // it fits in perfectly well. `topology-a` measured 4 of 12 markers
7204
+ // inside on line boxes and 12 of 12 on ink.
7205
+ if(c.inPort){ const li=nodeInk(r.port);
7206
+ if(li) s+=6*ovl(inkBox(c.box,r.fs), {x:li.x,y:li.y+li.h*0.09,w:li.w,h:li.h*0.82}); }
7207
+ // the marker leaves its box only under duress, and leaves its PORT
7208
+ // only after that (PORT_HUG < PORT_OUT)
7209
+ s+=CS.out?PORT_OUT:(c.hug?PORT_HUG:0);
5553
7210
  for(const a of arrowBox) s+=4*ovl(c.box,a);
5554
7211
  // The label's OWN edge is charged like any other. It used to be exempt
5555
7212
  // (`g.e!==r.e`), which made a label lying across the line it names FREE
5556
7213
  // — and that is the single commonest way a label stops saying which
5557
7214
  // line it belongs to, so the exemption was paying for the defect.
5558
7215
  for(const g of edgeSegs) if(segHit(g.p,g.q,c.box)) s+=26;
7216
+ // THE PERPENDICULAR STEP STAYS CHEAP, AND THAT IS A MEASURED RESULT
7217
+ // (item 59). The direction was "relief slides along the shaft first,
7218
+ // steps away only within a cap", and the obvious way to write the
7219
+ // first half is to make the step dearer than the slide — the slide is
7220
+ // priced in parameter units, `tScale`/L per pixel, which is 0.35/px on
7221
+ // a 200 px run, exactly what the step costs. Tripling the step to
7222
+ // 0.9/px was built and measured, and the corpus refused it:
7223
+ // `showcase/tcp-state-machine` went lblcol 0 -> 4 and
7224
+ // `patterns/erd-a` 0 -> 1. The reason is that a mid-label's ENTIRE
7225
+ // perpendicular displacement is slope clearance — the smallest step
7226
+ // that gets the box off its own diagonal shaft — and a strike costs
7227
+ // 26 in this scorer, so at 0.9/px any clearance over 29 px is outbid
7228
+ // by lying across the line the label names. Pricing the step above
7229
+ // the strike buys strikes. So the along-first half of item 59 is
7230
+ // carried by the CAP below (a step can never exceed it) and by the
7231
+ // along-shaft candidate family, not by this coefficient.
5559
7232
  s+=0.35*c.ex; // price of the slope-clearance displacement
5560
7233
  s+=ci*30; // price of leaving the preferred carrier
5561
7234
  // Two identical texts sitting side by side is the defect in its purest
@@ -5571,16 +7244,203 @@ function renderScene(doc,y0){
5571
7244
  // offers parameters outside [0,1] states its own weight so its escape
5572
7245
  // positions cost what they are worth in pixels rather than being
5573
7246
  // priced out by the length of the thing they slide along.
5574
- s+=(r.tw||70)*Math.abs(t-tPref)+si*10;
5575
- if(c.box.x<2) s+=400; // would fall off the left margin
5576
- if(s<bestS-1e-9){ bestS=s; best=c; }
7247
+ s+=tScale*Math.abs(t-tPref)+si*10;
7248
+ // ASSOCIATION MARGIN, IN THE SCORER AT LAST (F5, §14).
7249
+ // The legibility floor asks how much NEARER a label is to the line it
7250
+ // names than to the next line, and until now that question was only
7251
+ // ever asked after the fact, by the lint. Two positions can both be
7252
+ // collision-free and one of them still sit in the gap BETWEEN two
7253
+ // lines, where the reader has to guess; nothing in the score saw the
7254
+ // difference and the side-order term then decided by index.
7255
+ // Measured on `showcase/arp-resolution` (item 58's acceptance
7256
+ // figure): `1: heard, ignored` scored 0 above its line and 0 below
7257
+ // it, took `above` by index, and parked in the 9.4 px gap between the
7258
+ // broadcast line and the reciprocal pair — which then left the ARP
7259
+ // REPLY's own 221 px label no clean position on a 194 px run, and it
7260
+ // drew struck. With the margin priced, that label takes the open
7261
+ // paper below and the reply's label follows it: `lblcol` 1 -> 0.
7262
+ // The bonus is capped so it can break a tie between two legal
7263
+ // positions and nothing more — it can never outrank an overlap,
7264
+ // which is an AREA and unbounded.
7265
+ { let own=Infinity, oth=Infinity;
7266
+ const perEdge=new Map();
7267
+ for(const g of edgeSegs){
7268
+ const d=segBoxD(g.p,g.q,c.box);
7269
+ if(g.e===r.e){ if(d<own) own=d; } else if(d<oth) oth=d;
7270
+ const cur=perEdge.get(g.e);
7271
+ if(cur===undefined||d<cur) perEdge.set(g.e,d);
7272
+ }
7273
+ if(own<Infinity&&oth<Infinity) s-=0.4*Math.min(45,Math.max(0,oth-own));
7274
+ // ...AND THE SCORER ALSO ASKS THE GATE'S OWN QUESTION (item 60).
7275
+ // The bonus above rewards a position that is NEARER ITS OWN line
7276
+ // than to the next one, and it is clamped at zero — so between two
7277
+ // positions that are BOTH nearer a foreign line, it says nothing,
7278
+ // and the figure falls back to the side-order index. The legibility
7279
+ // floor's F5 does not ask about ownership at that point: it asks
7280
+ // whether the two NEAREST lines are within M of each other, because
7281
+ // that is the reading where a human cannot tell which line the word
7282
+ // belongs to at all. Measured on `statechart/bfd-session` once the
7283
+ // admin transitions merged into one trunk (item 60): the green
7284
+ // "rx Init, rx Up" label sat 40.0 px from INIT's self-loop and
7285
+ // 40.0 px from UP's — margin 0.0, a coin toss — while sliding along
7286
+ // its own shaft to t=0.2 makes those 27 px and 53 px. Nothing in the
7287
+ // score could see the difference. The penalty is a CONSTANT, in the
7288
+ // band the identical-text and wrong-side terms already use, so it
7289
+ // can break the choice between two collision-free positions and can
7290
+ // never outbid an overlap.
7291
+ if(perEdge.size>1){
7292
+ const ds=[...perEdge.values()].sort((a,b)=>a-b);
7293
+ if(ds[1]-ds[0]<4) s+=26;
7294
+ } }
7295
+ // OFF THE CANVAS IS NOT A BAD PLACEMENT, IT IS NO PLACEMENT.
7296
+ // The canvas grows right and down and has no mechanism here to grow
7297
+ // up or left, so a box past those two margins is CLIPPED AWAY and the
7298
+ // text the author wrote is never seen. This was a score term worth
7299
+ // 400, and the note pass already records why a constant cannot do the
7300
+ // job: every other penalty is an AREA and grows without bound, so a
7301
+ // crowded right-hand alternative outbids the constant and the label
7302
+ // goes over the edge. Measured on `statechart/bfd-session` at
7303
+ // 0.4: "rx AdminDown / Detect expired, Echo failed" was
7304
+ // emitted at x = -88.6 and simply did not appear.
7305
+ // So it is a FILTER with its own fallback: an off-canvas candidate is
7306
+ // kept only as the last resort, behind every position that is on the
7307
+ // page at all, and behind the affinity filter for the same reason.
7308
+ // The LEFT margin only, which is the margin this pass has always
7309
+ // judged. The top is left alone deliberately: the two corridor labels
7310
+ // `statechart/dhcp-client` parks above its top rank sit at the canvas
7311
+ // origin BY DESIGN (the return rows run above the figure and the
7312
+ // scene is shifted down to make room), and filtering on `y` pushed
7313
+ // them into one band and cost an F5.
7314
+ const offCanvas=(c.box.x<2);
7315
+ if(offCanvas){ if(s<offS-1e-9){ offS=s; offBest=c; } continue; }
7316
+ // THE CAP IS A FILTER, NOT A PRICE (item 59), for the reason the
7317
+ // off-canvas term above records: every other penalty here is an AREA
7318
+ // and grows without bound, so a constant surcharge on distance is
7319
+ // always outbid by a crowded near position and the label goes for a
7320
+ // walk. A mid-label further from its own shaft than STANDOFF_CAP is
7321
+ // therefore held back behind every position that is inside the cap,
7322
+ // and if one of them wins anyway — the geometry really had nothing
7323
+ // closer — it is drawn with a LEADER back to the shaft. Never a free
7324
+ // float. Endpoint labels are exempt: their distance is governed by
7325
+ // the 16 px anchor and the affinity filter, both of item 42's.
7326
+ if(r.kind!=='end'&&segBoxGap(c.car[0],c.car[1],c.box)>STANDOFF_CAP){
7327
+ if(s<farS-1e-9){ farS=s; farBest=c; } continue; }
7328
+ if(s<anyS-1e-9){ anyS=s; anyBest=c; }
7329
+ if(owns&&s<bestS-1e-9){ bestS=s; best=c; }
5577
7330
  }
5578
7331
  }
7332
+ if(!best) best=anyBest||farBest||offBest; // no legal position — least bad
7333
+ r0.win=best; // kept for item 55's recolour pass
5579
7334
  lblsvg[r0.idx]=textEl(best.x,best.y,r0.fs,best.anchor,r0.col,r0.text,r0.halo);
7335
+ // THE LEADER (item 59). A mid-label that had to be placed past the cap
7336
+ // states its line explicitly: a hairline from the nearest point of its
7337
+ // box to the nearest point of its own carrying segment, in the label's
7338
+ // own colour. It is drawn UNDER nothing and over nothing — it is 1 px,
7339
+ // it starts at the box and it stops at the shaft — so it adds no ink
7340
+ // anywhere the reader is not already looking for the association.
7341
+ if(r0.kind!=='end'&&best.car&&segBoxGap(best.car[0],best.car[1],best.box)>STANDOFF_CAP){
7342
+ const b=best.box, cx=b.x+b.w/2, cy=b.y+b.h/2;
7343
+ const P0=best.car[0], Q0=best.car[1];
7344
+ const vx=Q0[0]-P0[0], vy=Q0[1]-P0[1], L2=vx*vx+vy*vy;
7345
+ const t=L2?Math.max(0,Math.min(1,((cx-P0[0])*vx+(cy-P0[1])*vy)/L2)):0;
7346
+ const fx=P0[0]+t*vx, fy=P0[1]+t*vy;
7347
+ // the box's own boundary point on the ray toward that foot
7348
+ const dx=fx-cx, dy=fy-cy, ax=Math.abs(dx)||1e-9, ay=Math.abs(dy)||1e-9;
7349
+ const k=Math.min((b.w/2+2)/ax,(b.h/2+2)/ay);
7350
+ r0.leadIdx=lblsvg.length;
7351
+ lblsvg.push('<line x1="'+(cx+dx*k)+'" y1="'+(cy+dy*k)+'" x2="'+fx+'" y2="'+fy+
7352
+ '" stroke="'+r0.col+'" stroke-width="1" opacity="0.6"/>');
7353
+ }
5580
7354
  placed.push(Object.assign({text:r0.text},best.box));
5581
7355
  W=Math.max(W, best.box.x+best.box.w+4);
5582
7356
  Hh=Math.max(Hh, best.box.y+best.box.h+4-y0-20);
5583
7357
  }
7358
+ // ── A BUNDLE CAPTION SITS BESIDE ITS RING (item 43) ────────────────────
7359
+ // It used to be written at the ring's CENTRE, which is the one place on a
7360
+ // bundle ring that is guaranteed to be occupied: the waist is where the
7361
+ // member links cross. On `reference/topology` the `ECMP uplink set`
7362
+ // caption lay across three edge segments; on `patterns/topology-b`
7363
+ // `Link Bundle 1` lay on top of the `p3` endpoint label.
7364
+ //
7365
+ // So it is placed like every other free label in this pass, against the
7366
+ // same `placed` / `obst` / `arrowBox` / `edgeSegs` evidence, and it enters
7367
+ // AFTER the edge labels: a port label names one end of one link and has
7368
+ // one place to be, while a caption names a ring and has a whole rim to
7369
+ // choose from, so the caption is the one that yields. (Notes still enter
7370
+ // last — nothing yields to a note.)
7371
+ //
7372
+ // The candidate set is twelve stations around the RIM, in the ring's own
7373
+ // frame, so the family follows the ring's orientation instead of the
7374
+ // canvas's. `40*|cos phi|` prices the two stations at the ring's ENDS: the
7375
+ // ends are where the member links leave and where their nodes are, so a
7376
+ // caption there is reaching across the very links the ring encircles. The
7377
+ // flanks — across the members — are free, and between the two the
7378
+ // evidence decides which is clearer. A second tier, 30 px out with a short
7379
+ // dashed leader, exists for the figure where no flank is clear; it is
7380
+ // priced high enough that it is taken only when every rim station is
7381
+ // genuinely occupied.
7382
+ for(const t of doc.trunks||[]){
7383
+ const R=rings.get(t);
7384
+ if(!R||t.label===null||t.label===undefined||t.label==='') continue;
7385
+ const lines=String(t.label).split('\n'), nL=lines.length;
7386
+ const w=Math.max(...lines.map(cw))*6.5*11.5/11, lh=11.5*1.3;
7387
+ const h=(nL-1)*lh+11.5*1.1, up=(nL-1)*lh/2+11.5*0.85;
7388
+ let best=null, bestS=Infinity;
7389
+ for(const tier of [0,1]){
7390
+ const gap=tier?30:7;
7391
+ for(let k=0;k<12;k++){
7392
+ const ph=k*Math.PI/6, cp=Math.cos(ph), sp=Math.sin(ph);
7393
+ const dx=R.ux*cp+R.vx*sp, dy=R.uy*cp+R.vy*sp;
7394
+ const rim=1/Math.hypot(cp/R.rL, sp/R.rA);
7395
+ const out=rim+gap+Math.abs(dx)*w/2+Math.abs(dy)*h/2;
7396
+ const cb={x:R.cx+dx*out-w/2, y:R.cy+dy*out-h/2, w, h};
7397
+ let sc=0;
7398
+ for(const b of placed) sc+=3*ovl(cb,b);
7399
+ for(const o of obst) sc+=2.4*ovl(cb,o);
7400
+ // a group's NAME is ink too (item 45), and a caption written over it
7401
+ // reads as that band's second line
7402
+ for(const o of nameObs) sc+=2.4*ovl(cb,o);
7403
+ for(const a of arrowBox) sc+=4*ovl(cb,a);
7404
+ for(const g of edgeSegs) if(segHit(g.p,g.q,cb)) sc+=26;
7405
+ // A caption lying across ANOTHER bundle's ring has stopped saying
7406
+ // which bundle it names — F5's mechanism again, between two rings
7407
+ // this time. It is charged like a strikethrough because that is
7408
+ // what it is, and measured against the ring's OUTLINE rather than
7409
+ // its bounding box: a tilted ring's box is mostly empty paper, and
7410
+ // charging the box drove the reference figure's caption off a clear
7411
+ // corner and onto an endpoint label. Its OWN ring is never charged
7412
+ // — being beside that one is the whole point.
7413
+ for(const [t2,R2] of rings)
7414
+ if(t2!==t&&!R2.solo&&ringHitsRect(R2,R2.rL,R2.rA,cb)) sc+=26;
7415
+ sc+=40*Math.abs(cp); // the ring's ENDS belong to the links
7416
+ // THE CLEARER FLANK, when two flanks are equally legal. Both of
7417
+ // `patterns/topology-b`'s across-stations score exactly 0 — the
7418
+ // caption fits above the ring and below it — and "first index wins"
7419
+ // then chose by the loop's order rather than by the drawing. This
7420
+ // term is the tie-break and only the tie-break: a bonus of at most
7421
+ // 2, for the candidate with the most white around it, capped so it
7422
+ // can never outrank a single overlap, let alone a strikethrough.
7423
+ let clr=40;
7424
+ for(const b2 of placed) clr=Math.min(clr,boxGap(cb,b2));
7425
+ for(const o of obst) clr=Math.min(clr,boxGap(cb,o));
7426
+ for(const o of nameObs) clr=Math.min(clr,boxGap(cb,o));
7427
+ sc-=0.05*Math.max(0,clr);
7428
+ sc+=tier*400; // the leader is a last resort
7429
+ if(cb.x<2||cb.y<y0) sc+=400; // off the top or left margin
7430
+ if(sc<bestS-1e-9){ bestS=sc; best={cb,tier,dx,dy,rim,gap}; }
7431
+ }
7432
+ }
7433
+ ringLbl.set(t,best);
7434
+ if(best.tier){
7435
+ const p=[R.cx+best.dx*best.rim, R.cy+best.dy*best.rim];
7436
+ const q=[R.cx+best.dx*(best.rim+best.gap), R.cy+best.dy*(best.rim+best.gap)];
7437
+ ringLeads.push([p,q,t]);
7438
+ }
7439
+ placed.push({text:t.label, x:best.cb.x, y:best.cb.y, w, h});
7440
+ best.tx=best.cb.x+w/2; best.ty=best.cb.y+up;
7441
+ W=Math.max(W, best.cb.x+w+4);
7442
+ Hh=Math.max(Hh, best.cb.y+h+4-y0-20);
7443
+ }
5584
7444
  // ── note placement (`DRAWN-ANNOTATION-FORM`) — the SAME pass, entered LAST ────────────────
5585
7445
  // Four rules, and they are in the spec rather than only here because two
5586
7446
  // engines have to agree on them:
@@ -5616,11 +7476,12 @@ function renderScene(doc,y0){
5616
7476
  // metaclass the spelling is borrowed from (RULE 4.1).
5617
7477
  const noteCarriers=[];
5618
7478
  for(const n of nodes) if(n.note!==undefined&&n.note!==null&&!n.boundary)
5619
- noteCarriers.push({line:n.line,text:n.note,kind:'node',rect:{x:n.x,y:n.y,w:n.w,h:n.h},n});
7479
+ noteCarriers.push({line:n.line,text:n.note,kind:'node',ref:n.id,rect:{x:n.x,y:n.y,w:n.w,h:n.h},n,
7480
+ lbl:n.label});
5620
7481
  for(const g of doc.groups) if(g.note!==undefined&&g.note!==null){
5621
7482
  const B=gBox[g.id]; if(!B) continue;
5622
- noteCarriers.push({line:g.line,text:g.note,kind:'group',
5623
- rect:{x:B.x0,y:B.yA,w:B.x1-B.x0,h:B.yB-B.yA}});
7483
+ noteCarriers.push({line:g.line,text:g.note,kind:'group',ref:g.id,
7484
+ rect:{x:B.x0,y:B.yA,w:B.x1-B.x0,h:B.yB-B.yA},lbl:g.label});
5624
7485
  }
5625
7486
  for(const e of doc.edges) if(e.note!==undefined&&e.note!==null){
5626
7487
  // An edge is a polyline, not a rect. Its carrier POINT is the midpoint of
@@ -5632,11 +7493,148 @@ function renderScene(doc,y0){
5632
7493
  const segs=edgeSegs.filter(g=>g.e===e); if(!segs.length) continue;
5633
7494
  const m=segs[Math.floor((segs.length-1)/2)];
5634
7495
  const cx=(m.p[0]+m.q[0])/2, cy=(m.p[1]+m.q[1])/2;
5635
- noteCarriers.push({line:e.line,text:e.note,kind:'edge',rect:{x:cx,y:cy,w:0,h:0},e});
7496
+ noteCarriers.push({line:e.line,text:e.note,kind:'edge',ref:e.line,rect:{x:cx,y:cy,w:0,h:0},e});
5636
7497
  }
5637
7498
  noteCarriers.sort((a,b)=>a.line-b.line);
7499
+ // ── ADJACENCY MUST BE DISCRIMINABLE (item 40) ─────────────────────────
7500
+ // "Adjacency where it can, a leader only when adjacency fails" was always
7501
+ // the rule; what was missing is that the failure test never asked whether
7502
+ // the adjacency SAYS ANYTHING. `annotated-datapath` — the `note=`
7503
+ // demonstrator itself — put the `mac` group note and the `pause` node note
7504
+ // at the same y, 3 px apart, one continuous strip that reads as a caption
7505
+ // row and binds neither box. Each was near-adjacent to the OTHER's target.
7506
+ //
7507
+ // This is F5's mechanism, a THIRD time (edge-label/edge = F5,
7508
+ // endpoint-label/endpoint = item 42, note/element = here): nearest versus
7509
+ // SECOND-nearest. A note is adjacent to its target only when
7510
+ // (a) it sits substantially OVER its target's span on the axis across
7511
+ // the side it takes — beside means beside THIS thing, and a box that
7512
+ // overhangs its target is already reaching for a neighbour; and
7513
+ // (b) its own target is the NEAREST annotatable element, by at least
7514
+ // NOTE_M, to the second-nearest.
7515
+ // `annotatable` is the set of things a note can be written ON — nodes,
7516
+ // groups, connectors — because those are exactly the readings a reader can
7517
+ // mistake it for. When both tests pass the note simply sits there, as
7518
+ // before. When either fails, adjacency has FAILED and the candidate is not
7519
+ // offered at all, so the pass falls through to the far tiers, which is
7520
+ // where the dashed leader already lives. No new drawing machinery.
7521
+ //
7522
+ // NOTE_M = 12 px, not F5's 4: a note is a BOX tens of pixels tall, and the
7523
+ // eye ties it to a neighbour long before the gap closes to a hair. 12 px
7524
+ // is one note line-height (NOTE_FS * 1.35 rounded) — below one line of the
7525
+ // note's own text, two elements are not told apart.
7526
+ const NOTE_M=12;
7527
+ const noteLeads=[];
7528
+ const annot=[];
7529
+ for(const n of nodes) if(!n.boundary) annot.push({k:'node',id:n.id,rect:{x:n.x,y:n.y,w:n.w,h:n.h}});
7530
+ for(const g of doc.groups){ const B=gBox[g.id];
7531
+ if(B) annot.push({k:'group',id:g.id,rect:{x:B.x0,y:B.yA,w:B.x1-B.x0,h:B.yB-B.yA}}); }
7532
+ const rdist=(px,py,r)=>Math.hypot(Math.max(r.x-px,0,px-(r.x+r.w)),Math.max(r.y-py,0,py-(r.y+r.h)));
7533
+ const ptSegD=(px,py,p,q)=>{
7534
+ const vx=q[0]-p[0], vy=q[1]-p[1], L2=vx*vx+vy*vy;
7535
+ const t=L2?Math.max(0,Math.min(1,((px-p[0])*vx+(py-p[1])*vy)/L2)):0;
7536
+ return Math.hypot(px-(p[0]+t*vx), py-(p[1]+t*vy));
7537
+ };
7538
+ // A connector is annotatable too, and it is measured as the polyline it is.
7539
+ const edgeDist=(px,py,e)=>{ let d=Infinity;
7540
+ for(const g of edgeSegs) if(g.e===e)
7541
+ d=Math.min(d,ptSegD(px,py,g.p,g.q));
7542
+ return d; };
7543
+ const noteEdges=[];
7544
+ for(const e of doc.edges) if(edgeSegs.some(g=>g.e===e)) noteEdges.push(e);
7545
+ // Does this candidate box read as belonging to THIS carrier and no other?
7546
+ //
7547
+ // The test is on SPANS, not on centre-to-centre distance, because that is
7548
+ // how the eye reads a note: it looks back along the side the box sits on
7549
+ // and takes the first thing it lands on. So a competitor is any
7550
+ // annotatable element whose PROJECTION across that side overlaps the note
7551
+ // — the reading the filed case describes exactly, the `pause` note's left
7552
+ // edge reaching "under the `mac` band's horizontal projection" — and the
7553
+ // margin is measured along the side, own gap versus second-nearest gap.
7554
+ const spanOf=(r,across)=>across?[r.y,r.y+r.h]:[r.x,r.x+r.w];
7555
+ const gapTo=(cb,r,side)=>side==='below'?cb.y-(r.y+r.h)
7556
+ :side==='above'?r.y-(cb.y+cb.h)
7557
+ :side==='right'?cb.x-(r.x+r.w)
7558
+ :r.x-(cb.x+cb.w);
7559
+ const discriminable=(cb,c,side)=>{
7560
+ const across=(side==='left'||side==='right');
7561
+ // (a) the note sits substantially OVER its target's span. `beside` means
7562
+ // beside THIS thing; a box that hangs off its target is already halfway
7563
+ // to the neighbour. The denominator is the SMALLER of the two spans, so
7564
+ // a wide note fully covering a narrow target passes and a note sliding
7565
+ // off the end of a wide target fails.
7566
+ const [nA,nB]=spanOf(cb,across), [tA,tB]=spanOf(c.rect,across);
7567
+ const denom=Math.min(nB-nA,tB-tA);
7568
+ if(denom>1&&(Math.min(nB,tB)-Math.max(nA,tA))/denom<0.6) return false;
7569
+ // (b) nearest versus second-nearest, along the side, among the elements
7570
+ // whose projection the note actually lies across.
7571
+ const claim=r=>{ const [rA,rB]=spanOf(r,across);
7572
+ return Math.min(nB,rB)>Math.max(nA,rA); };
7573
+ let own=gapTo(cb,c.rect,side), second=Infinity;
7574
+ if(own<0) return false; // the note overlaps its own target
7575
+ for(const a of annot){
7576
+ if(c.kind===a.k&&c.ref===a.id) continue;
7577
+ if(!claim(a.rect)) continue;
7578
+ const g=gapTo(cb,a.rect,side);
7579
+ if(g>=-1) second=Math.min(second,g);
7580
+ }
7581
+ for(const e of noteEdges){
7582
+ if(c.kind==='edge'&&c.e===e) continue;
7583
+ for(const g0 of edgeSegs){ if(g0.e!==e) continue;
7584
+ const r={x:Math.min(g0.p[0],g0.q[0]),y:Math.min(g0.p[1],g0.q[1]),
7585
+ w:Math.abs(g0.q[0]-g0.p[0]),h:Math.abs(g0.q[1]-g0.p[1])};
7586
+ if(!claim(r)) continue;
7587
+ const g=gapTo(cb,r,side);
7588
+ if(g>=-1) second=Math.min(second,g);
7589
+ }
7590
+ }
7591
+ return own+NOTE_M<=second;
7592
+ };
7593
+ // ── AN ADJACENCY NOTE NAMES ITS TARGET; A LEADER NOTE DOES NOT (item 56b) ──
7594
+ // A note sited by ADJACENCY carries its whole association in a gap: the
7595
+ // box is beside a thing, and the reader has to guess which thing. The
7596
+ // drawing already knows the answer — `data-note-for` has carried the
7597
+ // resolved target since item 40b — so the note says it, in words: the
7598
+ // target's LABEL, bold, then a colon, then the note's own sentence
7599
+ // ("MAC layer: Runs on the recovered RX clock…"). It is derived, never
7600
+ // authored: `DOMAIN-CONVENTION-DIRECTIVES` keeps the drawing convention with the engine.
7601
+ //
7602
+ // A note with a DRAWN LEADER does not take the prefix, and that is the
7603
+ // whole of the split. The leader IS the association — a line from the box
7604
+ // to the thing — and repeating it in the text is ink for a fact the
7605
+ // drawing already states unambiguously.
7606
+ //
7607
+ // ONLY A LABELLED NODE OR GROUP can be named this way. A connector has no
7608
+ // id and no name (`data-note-for` carries its source LINE, which is not a
7609
+ // thing a reader can see), and the figure-level note on `title` names the
7610
+ // FIGURE — there is exactly one and it needs no naming.
7611
+ //
7612
+ // ORDER, because the two decisions are circular (the prefix changes the
7613
+ // box, the box changes whether adjacency succeeds): the note is sited
7614
+ // WITH the prefix first, since adjacency is the preferred outcome and the
7615
+ // prefixed box is the one that has to fit. If that siting takes a leader,
7616
+ // the note is re-sited WITHOUT the prefix, and THAT placement stands —
7617
+ // there is no third pass. It terminates by construction and it is
7618
+ // deterministic, which is what `RENDERING-DETERMINISM` needs of it.
7619
+ const notePrefix=c=>((c.kind==='node'||c.kind==='group')&&c.lbl&&String(c.lbl).trim()
7620
+ ?String(c.lbl).replace(/\n/g,' ')+':':null);
5638
7621
  for(const c of noteCarriers){
5639
- const box=noteBox(c.text);
7622
+ const pfx=notePrefix(c);
7623
+ let box=noteBox(c.text,pfx), sited=siteNote(c,box);
7624
+ if(pfx&&sited.best&&sited.best.far){ box=noteBox(c.text,null); sited=siteNote(c,box); }
7625
+ let best=sited.best;
7626
+ // Only if EVERY candidate was off-canvas: take the least-bad one and
7627
+ // clamp it on. It may overlap something; visible and overlapping is
7628
+ // recoverable by an author, invisible is not.
7629
+ if(!best){ best=sited.fallback; best.x=Math.max(0,best.x); best.y=Math.max(y0,best.y); }
7630
+ lblsvg.push(noteSvg(best.x,best.y,box,c));
7631
+ if(best.far){ lblsvg.push(noteLeader(best,box,c.rect));
7632
+ noteLeads.push(noteLeaderPts(best,box,c.rect)); }
7633
+ placed.push({x:best.x,y:best.y,w:box.w,h:box.h});
7634
+ W=Math.max(W, best.x+box.w+4);
7635
+ Hh=Math.max(Hh, best.y+box.h+4-y0-20);
7636
+ }
7637
+ function siteNote(c,box){
5640
7638
  // Adjacency first, then the same four sides pushed out far enough that a
5641
7639
  // leader is legible. `si` orders the sides; `far` is what decides the
5642
7640
  // leader, and it costs enough that adjacency wins every time adjacency is
@@ -5670,6 +7668,11 @@ function renderScene(doc,y0){
5670
7668
  by=side==='below'?c.rect.y+c.rect.h+gap:c.rect.y-gap-box.h;
5671
7669
  }
5672
7670
  const cb={x:bx,y:by,w:box.w,h:box.h};
7671
+ // ADJACENCY THAT SAYS NOTHING IS NOT ADJACENCY (item 40). Tier 0 is
7672
+ // the no-leader tier; a candidate there must actually bind the note
7673
+ // to its carrier. If it does not, it is withdrawn and the far tiers
7674
+ // — which draw the dashed leader — are what remain.
7675
+ if(!far&&!discriminable(cb,c,side)) continue;
5673
7676
  let s=0;
5674
7677
  // A NOTE YIELDS; NOTHING YIELDS TO A NOTE. `placed` holds the edge
5675
7678
  // labels and the notes already sited, and its weight is the HIGHEST
@@ -5682,6 +7685,7 @@ function renderScene(doc,y0){
5682
7685
  for(const o of obst) s+=6*ovl(cb,o);
5683
7686
  for(const a of arrowBox) s+=8*ovl(cb,a);
5684
7687
  for(const g of edgeSegs) if(segHit(g.p,g.q,cb)) s+=26;
7688
+ for(const g of noteLeads) if(segHit(g[0],g[1],cb)) s+=26;
5685
7689
  for(const g of doc.groups){ const B=gBox[g.id];
5686
7690
  if(B) s+=1.2*ovl(cb,{x:B.x0,y:B.yA,w:B.x1-B.x0,h:B.yB-B.yA}); }
5687
7691
  s+=si*12;
@@ -5711,19 +7715,176 @@ function renderScene(doc,y0){
5711
7715
  if(s<bestS-1e-9){ bestS=s; best={x:bx,y:by,far,side}; }
5712
7716
  }
5713
7717
  }
5714
- // Only if EVERY candidate was off-canvas: take the least-bad one and
5715
- // clamp it on. It may overlap something; visible and overlapping is
5716
- // recoverable by an author, invisible is not.
5717
- if(!best){ best=fallback; best.x=Math.max(0,best.x); best.y=Math.max(y0,best.y); }
5718
- lblsvg.push(noteSvg(best.x,best.y,box,c));
5719
- if(best.far) lblsvg.push(noteLeader(best,box,c.rect));
5720
- placed.push({x:best.x,y:best.y,w:box.w,h:box.h});
5721
- W=Math.max(W, best.x+box.w+4);
5722
- Hh=Math.max(Hh, best.y+box.h+4-y0-20);
7718
+ return {best,fallback};
7719
+ }
7720
+ // ── TONE PAIRING FOR CROWDED UNCLASSED EDGES (item 55) ────────────────
7721
+ // Where several plain lines cross the middle of a figure, every one of
7722
+ // them is `#555` and every one of their labels is `#555`, so the reader
7723
+ // pairs word to line by tracing. `statechart/dhcp-client` is the case:
7724
+ // five long diagonals through one region, five two-line labels sitting
7725
+ // among them.
7726
+ //
7727
+ // The engine assigns those lines DISTINCT TONES, and each label takes its
7728
+ // own line's tone. That is all the tones do.
7729
+ //
7730
+ // THE `PRESENTATION-AS-MEANING-CARRIER` BOUNDARY, and it is the whole reason the palette looks like
7731
+ // this. `PRESENTATION-AS-MEANING-CARRIER` says presentation is never the sole carrier of meaning: a
7732
+ // reader must never have to read a colour to learn a fact. These tones
7733
+ // carry NO fact. They are not derived from anything the author wrote,
7734
+ // they earn NO legend entry, no `class` and no `stroke=` names them, and
7735
+ // a reader who goes looking for what "the olive one" means finds nothing
7736
+ // stated anywhere — because there is nothing. They are DISCRIMINATION,
7737
+ // the same job a fan-out offset does when two messages share a node pair,
7738
+ // and the palette is what keeps them readable as that: four MUTED hues,
7739
+ // none of them a signal colour and none of them one of the plane or
7740
+ // class colours a legend can name. A classed edge is never touched, because there
7741
+ // the colour DOES carry the legend's meaning and a second scheme on top
7742
+ // of it would be two claims about one stroke.
7743
+ //
7744
+ // ELIGIBILITY. An edge takes a tone only if it (a) joins no class,
7745
+ // (b) sets no `stroke=` of its own — both would be an authored choice —
7746
+ // (c) draws a `mid` label, since a line with nothing to pair needs no
7747
+ // pairing, and (d) is not a merge-bus member, whose whole construct is
7748
+ // that several edges are ONE line.
7749
+ //
7750
+ // CROWDING is measured on the FINISHED drawing, after every label is
7751
+ // sited: an eligible edge is crowded when its label box comes within
7752
+ // TONE_PROX of another edge's shaft or another edge's label. 30 px is the
7753
+ // threshold — a little over two label line-heights, the distance at which
7754
+ // a reader stops being able to sweep from word to line without crossing
7755
+ // something else.
7756
+ //
7757
+ // ASSIGNMENT is a greedy pass in DOCUMENT ORDER, and it asks about the
7758
+ // EYE rather than about the array: "not the same as its neighbour" was
7759
+ // never the requirement — the palette this replaced had two entries 8.7
7760
+ // apart in CIE L*a*b*, which is different and still not TELLABLE apart at
7761
+ // a glance, and that was the whole job. Every crowded edge takes a tone
7762
+ // clearly apart from every neighbour already assigned, and among those
7763
+ // the least-spent one, so a figure uses its whole palette instead of
7764
+ // ping-ponging between two extremes (see the choice below). Ordering by
7765
+ // source line and breaking ties by palette index makes it deterministic:
7766
+ // same source, same tones.
7767
+ {
7768
+ const TONE_PROX=30;
7769
+ // The palette (item 61). Four muted hues at essentially ONE lightness —
7770
+ // L* 38.6, 39.7, 38.9, 40.9 — so they differ by HUE and nothing else,
7771
+ // and no tone can be read as heavier or more important than another:
7772
+ // slate blue #3f5b8c warm brown #7a5638
7773
+ // olive drab #55611f steel #206a72
7774
+ // Pairwise separation in CIE L*a*b* is 28.6 to 68.1, against the 8.7 of
7775
+ // the four slate-greys this replaced (a just-noticeable difference is
7776
+ // about 2.3, so those two were "different" and not tellable apart).
7777
+ // Because a label takes its line's tone and a label is TEXT, every one
7778
+ // is legible as type on white: 6.80, 6.53, 6.74 and 6.24 to 1, all above
7779
+ // the 4.5:1 floor for body text. A tone that discriminates by being too
7780
+ // faint to read has traded one defect for a worse one. None of them is
7781
+ // near a plane or class colour, and none is near the #555 default an
7782
+ // untoned line keeps: the nearest approach is warm brown at 26.
7783
+ const TONES=['#3f5b8c','#7a5638','#55611f','#206a72'];
7784
+ const busMem=new Set();
7785
+ for(const [e2] of busRoute) busMem.add(e2);
7786
+ for(const [e2,P2] of chPlan) if(P2.bus) busMem.add(e2);
7787
+ const lblOf=new Map();
7788
+ for(const q of lblReq) if(q.kind==='mid'&&q.win&&!lblOf.has(q.e)) lblOf.set(q.e,q.win.box);
7789
+ const elig=[];
7790
+ for(const e2 of edges){
7791
+ if(e2.stroke!==undefined||busMem.has(e2)) continue;
7792
+ const cl=e2.cls; if(cl!==undefined&&cl!==null&&(!Array.isArray(cl)||cl.length)) continue;
7793
+ if(!lblOf.has(e2)) continue;
7794
+ elig.push(e2);
7795
+ }
7796
+ const segD=(b,e2)=>{ let d=Infinity;
7797
+ for(const g of edgeSegs) if(g.e===e2) d=Math.min(d,segBoxD(g.p,g.q,b));
7798
+ return d; };
7799
+ const crowded=new Set(), near=new Map();
7800
+ for(const e2 of elig){
7801
+ const b=lblOf.get(e2);
7802
+ for(const f of edges){
7803
+ if(f===e2) continue;
7804
+ const hit=segD(b,f)<TONE_PROX ||
7805
+ (lblOf.has(f)&&boxGap(b,lblOf.get(f))<TONE_PROX);
7806
+ if(!hit) continue;
7807
+ crowded.add(e2);
7808
+ if(elig.indexOf(f)>=0){
7809
+ if(!near.has(e2)) near.set(e2,new Set()); near.get(e2).add(f);
7810
+ if(!near.has(f)) near.set(f,new Set()); near.get(f).add(e2);
7811
+ }
7812
+ }
7813
+ }
7814
+ // DISTANCE IS MEASURED IN THE EYE, NOT IN THE ARRAY (item 61). The old
7815
+ // palette was ordered by darkness, so "furthest position in the list"
7816
+ // was a fair proxy for "most tellable apart". A palette that separates
7817
+ // by HUE has no such order — steel is not "between" slate blue and
7818
+ // olive — so the assignment asks the question directly, in CIE L*a*b*,
7819
+ // where a difference of about 2.3 is the just-noticeable one and these
7820
+ // four sit 28.6 to 68.1 apart.
7821
+ const tLab=h=>{
7822
+ const v=[1,3,5].map(i=>parseInt(h.slice(i,i+2),16)/255)
7823
+ .map(c=>c<=0.03928?c/12.92:Math.pow((c+0.055)/1.055,2.4));
7824
+ let X=(0.4124*v[0]+0.3576*v[1]+0.1805*v[2])/0.95047,
7825
+ Y=(0.2126*v[0]+0.7152*v[1]+0.0722*v[2]),
7826
+ Z=(0.0193*v[0]+0.1192*v[1]+0.9505*v[2])/1.08883;
7827
+ const f=t=>t>0.008856?Math.cbrt(t):(7.787*t+16/116);
7828
+ const fx=f(X), fy=f(Y), fz=f(Z);
7829
+ return [116*fy-16, 500*(fx-fy), 200*(fy-fz)];
7830
+ };
7831
+ const LAB=TONES.map(tLab);
7832
+ const dE=(i,j)=>Math.hypot(LAB[i][0]-LAB[j][0],LAB[i][1]-LAB[j][1],LAB[i][2]-LAB[j][2]);
7833
+ const tone=new Map(), used=TONES.map(()=>0);
7834
+ for(const e2 of elig.slice().sort((p,q)=>p.line-q.line)){
7835
+ if(!crowded.has(e2)) continue;
7836
+ const nb=[];
7837
+ for(const f of (near.get(e2)||[])) if(tone.has(f)) nb.push(TONES.indexOf(tone.get(f)));
7838
+ // ENOUGH IS ENOUGH, AND THEN SPREAD. Taking the FURTHEST tone from
7839
+ // each neighbour sounds right and collapses the palette: with one
7840
+ // assigned neighbour the furthest is always the same antipode, so a
7841
+ // figure whose crowding graph is a set of pairs paints itself in two
7842
+ // hues and the other two are never seen (dhcp-client, measured: 2 of
7843
+ // 4). Every pair in this palette is at least 28.6 apart — an order of
7844
+ // magnitude over the ~2.3 just-noticeable difference — so "furthest"
7845
+ // buys nothing a reader can use, while a THIRD identity in a crowded
7846
+ // corner buys a great deal. So: any tone clearly apart from every
7847
+ // neighbour (>= TONE_SEP) is admissible, and among the admissible the
7848
+ // LEAST-SPENT one wins; ties to the lowest index, so the same source
7849
+ // always paints the same figure. If nothing clears the bar — a future
7850
+ // palette with closer entries, or more crowding than tones — it falls
7851
+ // back to the plain furthest-from-the-neighbours choice.
7852
+ const TONE_SEP=25;
7853
+ let pick=-1, bestU=-1;
7854
+ for(let i=0;i<TONES.length;i++){
7855
+ const d=nb.length?Math.min(...nb.map(j=>dE(i,j))):Infinity;
7856
+ if(d<TONE_SEP) continue;
7857
+ const u=used[i]; // how many lines already wear it
7858
+ if(pick<0||u<bestU){ bestU=u; pick=i; }
7859
+ }
7860
+ if(pick<0){ let bestD=-1; pick=0;
7861
+ for(let i=0;i<TONES.length;i++){
7862
+ const d=nb.length?Math.min(...nb.map(j=>dE(i,j))):Infinity;
7863
+ if(d>bestD+1e-9){ bestD=d; pick=i; }
7864
+ } }
7865
+ tone.set(e2, TONES[pick]);
7866
+ used[pick]++;
7867
+ }
7868
+ if(tone.size>1) for(const [e2,col2] of tone){
7869
+ const key='data-edge="'+e2.line+'"';
7870
+ for(let i=0;i<esvg.length;i++)
7871
+ if(esvg[i].indexOf(key)>=0) esvg[i]=esvg[i].replace('stroke="#555"','stroke="'+col2+'"');
7872
+ for(const i of (arrowIdx.get(e2)||[]))
7873
+ lblsvg[i]=lblsvg[i].replace('fill="#555"','fill="'+col2+'"');
7874
+ for(const q of lblReq) if(q.e===e2&&q.win){
7875
+ lblsvg[q.idx]=textEl(q.win.x,q.win.y,q.fs,q.win.anchor,col2,q.text,q.halo);
7876
+ // a standoff leader (item 59) is part of the label, so it takes the
7877
+ // label's tone with it — otherwise the one line drawn to state the
7878
+ // association would be the one line still painted the old colour.
7879
+ if(q.leadIdx!==undefined)
7880
+ lblsvg[q.leadIdx]=lblsvg[q.leadIdx].replace('stroke="'+q.col+'"','stroke="'+col2+'"');
7881
+ }
7882
+ }
5723
7883
  }
5724
7884
  }
5725
7885
  // nodes on top (each wrapped in a draggable, identifiable group)
5726
7886
  const nsvg=[];
7887
+ const nodeLbl=new Map(); // node id -> its drawn label's box (item 49)
5727
7888
  for(const n of nodes){
5728
7889
  if(n.boundary){
5729
7890
  // never drawn as a shape (`EXTERNAL-EDGE-ENDPOINTS`): the edge already ended open at the
@@ -5781,32 +7942,43 @@ function renderScene(doc,y0){
5781
7942
  const avail=2*inscribedHalfW(shapeAxes(n),nl.length*8)-16;
5782
7943
  if(n.rigid && need>avail) fs=Math.max(8, FONT*avail/need);
5783
7944
  nsvg.push(textEl(n.x+n.w/2, n.y+n.h/2+fs*0.35, fs, 'middle', txt, n.label));
7945
+ // The node's own label as INK, for whoever else wants to write inside this
7946
+ // box — today the zone-band captions (item 49). Recorded here rather than
7947
+ // recomputed there, because `fs` is the shrink-to-fit size and only this
7948
+ // scope knows it.
7949
+ { const lw=need*fs/FONT, lh=nl.length*fs*1.15;
7950
+ nodeLbl.set(n.id,{x0:n.x+n.w/2-lw/2, x1:n.x+n.w/2+lw/2,
7951
+ y0:n.y+n.h/2-lh/2, y1:n.y+n.h/2+lh/2}); }
5784
7952
  nsvg.push('</g>');
5785
7953
  }
5786
7954
  // trunk rings (semantic LAG/ES bundles): the ellipse is DERIVED from the
5787
- // member links' midpoints — drag a node and the ring follows
7955
+ // member links — drag a node and the ring follows. Its geometry is computed
7956
+ // above (`ringOf`, item 43) because the caption has to be placed by the
7957
+ // label pass, which runs before this one; here the ring is only drawn.
7958
+ // `rL` is the semi-axis ALONG the members and `rA` the one ACROSS them, so
7959
+ // the SVG's rx/ry are the ring's own axes rotated onto the canvas.
5788
7960
  const tsvg=[];
5789
7961
  for(const t of zsort(doc.trunks)){
5790
- const mids=[];
5791
- for(const [a,b] of t.pairs){
5792
- const A=byId[a], B=byId[b]; if(!A||!B) continue;
5793
- const [x1,yy1]=borderPoint(A,B.x+B.w/2,B.y+B.h/2);
5794
- const [x2,yy2]=borderPoint(B,A.x+A.w/2,A.y+A.h/2);
5795
- mids.push([(x1+x2)/2,(yy1+yy2)/2]);
5796
- }
5797
- if(!mids.length) continue;
5798
- const cx=mids.reduce((s,m)=>s+m[0],0)/mids.length;
5799
- const cy=mids.reduce((s,m)=>s+m[1],0)/mids.length;
5800
- const rx=Math.max(46, Math.max(...mids.map(m=>Math.abs(m[0]-cx)))+38);
5801
- const ry=Math.max(26, Math.max(...mids.map(m=>Math.abs(m[1]-cy)))+22);
7962
+ const R=rings.get(t); if(!R) continue;
5802
7963
  // 0.1 (§8.4): the ring has no interior — `stroke=` is the one
5803
7964
  // name for its channel; `fill=` on a bundle is now a line error, so the
5804
7965
  // model field is always absent and the old `t.fill` fallback is gone.
5805
7966
  const col=t.stroke||'#64748b';
5806
- tsvg.push('<ellipse cx="'+cx+'" cy="'+cy+'" rx="'+rx+'" ry="'+ry+'" fill="transparent" stroke="'+(t.stroke||col)+'"'+dashOf(t.style,'6 4')+' stroke-width="1.6"/>');
5807
- tsvg.push(textEl(cx, cy+4, 11.5, 'middle', col, t.label,' paint-order="stroke" stroke="#fff" stroke-width="3"'));
5808
- W=Math.max(W,cx+rx); Hh=Math.max(Hh,cy+ry-y0-20);
7967
+ const deg=R.th*180/Math.PI;
7968
+ const rot=Math.abs(deg)<0.05?'':' transform="rotate('+rnd3(deg)+' '+rnd3(R.cx)+' '+rnd3(R.cy)+')"';
7969
+ // ONE MEMBER = NO ELLIPSE (item 53). The caption below is the whole
7970
+ // drawing, and an unlabelled one-member bundle draws nothing.
7971
+ if(!R.solo){
7972
+ tsvg.push('<ellipse cx="'+rnd3(R.cx)+'" cy="'+rnd3(R.cy)+'" rx="'+rnd3(R.rL)+'" ry="'+rnd3(R.rA)+'" fill="transparent" stroke="'+(t.stroke||col)+'"'+dashOf(t.style,'6 4')+' stroke-width="1.6"'+rot+'/>');
7973
+ W=Math.max(W,R.cx+R.hw); Hh=Math.max(Hh,R.cy+R.hh-y0-20);
7974
+ }
7975
+ const L=ringLbl.get(t);
7976
+ if(L) tsvg.push(textEl(rnd3(L.tx), rnd3(L.ty), 11.5, 'middle', col, t.label,' paint-order="stroke" stroke="#fff" stroke-width="3"'));
5809
7977
  }
7978
+ // the caption's leader, when no rim station was clear (item 43)
7979
+ for(const [p,q,t] of ringLeads)
7980
+ tsvg.push('<line x1="'+rnd3(p[0])+'" y1="'+rnd3(p[1])+'" x2="'+rnd3(q[0])+'" y2="'+rnd3(q[1])
7981
+ +'" stroke="'+(t.stroke||'#64748b')+'" stroke-width="1" stroke-dasharray="3 3"/>');
5810
7982
  // threshold markers + labels (top layer). The target is a GROUP box or,
5811
7983
  // a single NODE box — the same two scopes `band` has always
5812
7984
  // taken (§2.6, `AUTHORING-INTENT-OVER-RENDERING`); a node's box is spelled in the gBox coordinate shape.
@@ -5831,17 +8003,84 @@ function renderScene(doc,y0){
5831
8003
  // band already owns an area, so the name needs no gutter and the canvas box
5832
8004
  // does not grow — W and Hh are untouched, which is why adding the label moves
5833
8005
  // no existing geometry in any figure.
8006
+ // ── A BAND CAPTION CLEARS THE NAME OF THE THING IT IS DRAWN INSIDE ──────
8007
+ // (item 49.) Centred-in-the-band is right when the band is the
8008
+ // only ink in that area and wrong when the band is drawn INSIDE a node,
8009
+ // because the node's own label is already centred there: `block-experimental`
8010
+ // put "Drained", "Q2" and "Headroom" on one baseline 1.6 px apart and the
8011
+ // reader got `DrainedQ2Headroom`. This is item 44/45's finding at the
8012
+ // intra-node scale — ink-blind placement — so the answer is theirs: the node
8013
+ // label, and every caption already placed on the same node, are OBSTACLES.
8014
+ //
8015
+ // The caption keeps its band-centred position unless that box comes within
8016
+ // 4 px of one (F6's margin, and F6 is the axis that would charge it). It
8017
+ // then slides by the SMALLEST amount that opens the gap — along the band's
8018
+ // OWN long axis first, which keeps it inside the band it names, then across
8019
+ // — staying within the host node. Only when the interior can hold no such
8020
+ // position does it move OUTSIDE, just beyond the band's outer edge, which is
8021
+ // where a threshold's caption already goes. A group- or region-scope band is
8022
+ // untouched: there is no centred label in the middle of a group box, and
8023
+ // every such figure in the corpus is byte-identical.
8024
+ const bandBoxes=new Map();
5834
8025
  for(const f of zsort(doc.bands)){
5835
8026
  const bn=byId[f.target];
5836
8027
  const B=gBox[f.target] || (bn ? {x0:bn.x, x1:bn.x+bn.w, yA:bn.y, yB:bn.y+bn.h} : null);
5837
8028
  if(!B) continue;
5838
8029
  const [bx,by,bw,bh]=bandRect(f,B.x0,B.yA,B.x1,B.yB);
5839
- tsvg.push(textEl(bx+bw/2, by+bh/2+4, 11, 'middle', labelInk(f.fill,'#334155'), f.label,
8030
+ let tx=bx+bw/2, ty=by+bh/2+4, anchor='middle';
8031
+ const lw=cwMax(f.label)*6.5, M=4;
8032
+ const obst=[];
8033
+ if(bn){
8034
+ const nl=nodeLbl.get(bn.id); if(nl) obst.push(nl);
8035
+ for(const o of (bandBoxes.get(bn.id)||[])) obst.push(o);
8036
+ }
8037
+ const boxAt=(x,y)=>({x0:x-lw/2, x1:x+lw/2, y0:y-4-7.5, y1:y-4+3.5});
8038
+ const clear=b=>!obst.some(o=>b.x0<o.x1+M&&b.x1>o.x0-M&&b.y0<o.y1+M&&b.y1>o.y0-M);
8039
+ if(obst.length && !clear(boxAt(tx,ty))){
8040
+ // long axis first: a vertical slab slides up/down, a horizontal one
8041
+ // left/right. Inside the host node either way.
8042
+ const vert=(f.dir==='left'||f.dir==='right');
8043
+ const dirs=vert?[[0,-1],[0,1],[-1,0],[1,0]]:[[-1,0],[1,0],[0,-1],[0,1]];
8044
+ let done=false;
8045
+ for(let d=1; d<=160 && !done; d+=1){
8046
+ for(const [ux,uy] of dirs){
8047
+ const x=tx+ux*d, y=ty+uy*d, b=boxAt(x,y);
8048
+ // containment is asked of the axis being MOVED ALONG only. A
8049
+ // caption is routinely wider than the slab it names (a 30% band on
8050
+ // an 84 px node against a 45 px word), and it always was — sliding
8051
+ // it vertically must not be refused for an overhang the centred
8052
+ // placement already had.
8053
+ if(uy&&(b.y0<B.yA+1||b.y1>B.yB-1)) continue;
8054
+ if(ux&&(b.x0<B.x0+1||b.x1>B.x1-1)) continue;
8055
+ if(clear(b)){ tx=x; ty=y; done=true; break; }
8056
+ }
8057
+ }
8058
+ if(!done){
8059
+ // SIDE PLACEMENT: the interior cannot hold both, so the caption
8060
+ // leaves the node on the band's own outer side and keeps its
8061
+ // adjacency from outside.
8062
+ // `extend=` names the direction the band GROWS, so its outer side is
8063
+ // the edge it grew FROM: an `extend=right` band starts at the left
8064
+ // edge and leaves by the left.
8065
+ if(f.dir==='right') { anchor='end'; tx=B.x0-6; ty=by+bh/2+4; }
8066
+ else if(f.dir==='left') { anchor='start'; tx=B.x1+6; ty=by+bh/2+4; }
8067
+ else if(f.dir==='up') { anchor='middle'; tx=bx+bw/2; ty=B.yB+13; }
8068
+ else { anchor='middle'; tx=bx+bw/2; ty=B.yA-6; }
8069
+ W=Math.max(W, anchor==='end'?tx:tx+(anchor==='start'?lw:lw/2));
8070
+ Hh=Math.max(Hh, ty+4-y0-20);
8071
+ }
8072
+ }
8073
+ if(bn){
8074
+ const b=boxAt(anchor==='middle'?tx:(anchor==='end'?tx-lw/2:tx+lw/2), ty);
8075
+ if(!bandBoxes.has(bn.id)) bandBoxes.set(bn.id,[]);
8076
+ bandBoxes.get(bn.id).push(b);
8077
+ }
8078
+ tsvg.push(textEl(tx, ty, 11, anchor, labelInk(f.fill,'#334155'), f.label,
5840
8079
  ' paint-order="stroke" stroke="#fff" stroke-width="3"'));
5841
8080
  }
5842
8081
  const yEnd=y0+20+Hh+10;
5843
8082
  return {svg:gsvg.join('')+esvg.join('')+nsvg.join('')+tsvg.join('')+lblsvg.join(''), y:yEnd, w:W+2,
5844
- meta:{W:W, top:y0+20+chShift, Hh:Hh, left:bShift}, errs:gErrs};
8083
+ meta:{W:W, top:y0+20+chShift+tShift, Hh:Hh, left:bShift+lShift}, errs:gErrs};
5845
8084
  }
5846
8085
  // borderPoint: where the ray from n's centre toward (tx,ty) leaves the shape.
5847
8086
  // It must leave the DRAWN outline: a rectangle clip on a diamond or an ellipse
@@ -6014,7 +8253,7 @@ function edgeRuns(v, p, n, span, ownAt){
6014
8253
  // `lifeline` declaration order is the COLUMN axis, left to right. Both axes
6015
8254
  // are declaration-ordered, and that is why this genre has no `flow` and no
6016
8255
  // `rank`: a key that reordered the drawing would make the picture disagree
6017
- // with the text (`SEQUENCE-SOURCE-STANDARD`-R182). `fragment` and `operand` lines are
8256
+ // with the text (`SEQUENCE-GENRE-VOCABULARY`). `fragment` and `operand` lines are
6018
8257
  // DECLARATIONS and carry no time position of their own; a container's drawn
6019
8258
  // extent is the span of its members' positions. Implementation: every
6020
8259
  // element carries its source line number, so the row order is recovered by
@@ -6952,6 +9191,25 @@ function shade(hex,f){
6952
9191
  return '#'+c(((v>>16)&255)*f)+c(((v>>8)&255)*f)+c((v&255)*f);
6953
9192
  }
6954
9193
  const CHART_PALETTE=['#3b82f6','#22c55e','#f59e0b','#ef4444','#a855f7','#14b8a6','#eab308','#64748b'];
9194
+ // Does an axis-aligned box overlap a CONVEX polygon? Separating-axis test:
9195
+ // two convex shapes miss each other iff some edge normal of either separates
9196
+ // them. The bar faces this is asked about are quads by construction (three
9197
+ // per bar), so the test is exact and needs no clipping library.
9198
+ function chartQuadHitsBox(poly,box){
9199
+ const bx=[[box.x0,box.y0],[box.x1,box.y0],[box.x1,box.y1],[box.x0,box.y1]];
9200
+ const shapes=[poly,bx];
9201
+ for(const sh of shapes){
9202
+ for(let i=0;i<sh.length;i++){
9203
+ const a=sh[i], c=sh[(i+1)%sh.length];
9204
+ const nx=-(c[1]-a[1]), ny=(c[0]-a[0]);
9205
+ let a0=Infinity,a1=-Infinity,b0=Infinity,b1=-Infinity;
9206
+ for(const q of poly){ const d=q[0]*nx+q[1]*ny; if(d<a0)a0=d; if(d>a1)a1=d; }
9207
+ for(const q of bx){ const d=q[0]*nx+q[1]*ny; if(d<b0)b0=d; if(d>b1)b1=d; }
9208
+ if(a1<b0||b1<a0) return false;
9209
+ }
9210
+ }
9211
+ return true;
9212
+ }
6955
9213
  function renderChart(b,y0,doc){
6956
9214
  const t=doc.blocks.find(x=>x.type==='table'&&x.id===b.tid);
6957
9215
  const rows=t.rows.map(r=>r.cells.slice(1).map(c=>parseFloat(c.v)||0));
@@ -6976,41 +9234,114 @@ function renderChart(b,y0,doc){
6976
9234
  // gutter costs only the width it actually uses (0 when no label overhangs,
6977
9235
  // so every chart whose labels already fitted is byte-unchanged).
6978
9236
  const rLabPx=l=>cwMax(l)*6.5*10/11; // textEl draws these at font-size 10
6979
- const ox0=R*W2+8;
6980
- const gut=Math.max(0,...rLab.map((l,r)=>rLabPx(l)+4-(ox0-(r+0.65)*W2)));
6981
- const ox=ox0+gut, oy=y0+18+ZS*zmax+6;
6982
- const P=(r,c,z)=>[ox+(c-r)*W2, oy+(c+r)*H2-z*ZS];
6983
- const svg=[];
9237
+ const oy=y0+18+ZS*zmax+6;
9238
+ // EVERYTHING BELOW IS COMPUTED IN A FRAME WHOSE x IS RELATIVE TO THE FLOOR
9239
+ // ORIGIN `ox`, because the gutter that fixes `ox` is not known until the
9240
+ // labels have been placed, and label placement is invariant to it: a nudge
9241
+ // is a shift relative to the bars, and the bars shift with the origin.
9242
+ const PR=(r,c,z)=>[(c-r)*W2, oy+(c+r)*H2-z*ZS];
9243
+ const svg=[], lsvg=[];
6984
9244
  svg.push('<text x="0" y="'+(y0+14)+'" font-size="13" font-weight="600">'+esc(t.label)+' — bar3d</text>');
6985
- // floor grid edges
6986
- const F=[P(0,0,0),P(R,0,0),P(R,C,0),P(0,C,0)];
6987
- svg.push('<polygon points="'+F.map(p=>p.join(',')).join(' ')+'" fill="#f6f5ef" stroke="#d6d4cc"/>');
6988
- // bars, far to near
6989
- const order=[];
9245
+ // bars, far to near — polygons kept for the label occlusion test below
9246
+ const order=[], faces=[];
6990
9247
  for(let r=0;r<R;r++)for(let c=0;c<C;c++)order.push([r,c]);
6991
9248
  order.sort((a,b2)=>(a[0]+a[1])-(b2[0]+b2[1]));
9249
+ const bars=[];
6992
9250
  for(const [r,c] of order){
6993
9251
  const h=rows[r][c]; if(h<=0) continue;
6994
9252
  const col=CHART_PALETTE[c%CHART_PALETTE.length];
6995
9253
  const i0=r+(1-BAR)/2, i1=r+(1+BAR)/2, j0=c+(1-BAR)/2, j1=c+(1+BAR)/2;
6996
- const A=P(i0,j0,h),Bp=P(i1,j0,h),Cp=P(i1,j1,h),D=P(i0,j1,h);
6997
- const B0=P(i1,j0,0),C0=P(i1,j1,0),D0=P(i0,j1,0);
6998
- svg.push('<polygon points="'+[Bp,Cp,C0,B0].map(p=>p.join(',')).join(' ')+'" fill="'+shade(col,0.72)+'"/>');
6999
- svg.push('<polygon points="'+[Cp,D,D0,C0].map(p=>p.join(',')).join(' ')+'" fill="'+shade(col,0.55)+'"/>');
7000
- svg.push('<polygon points="'+[A,Bp,Cp,D].map(p=>p.join(',')).join(' ')+'" fill="'+col+'"/>');
9254
+ const A=PR(i0,j0,h),Bp=PR(i1,j0,h),Cp=PR(i1,j1,h),D=PR(i0,j1,h);
9255
+ const B0=PR(i1,j0,0),C0=PR(i1,j1,0),D0=PR(i0,j1,0);
9256
+ bars.push([Bp,Cp,C0,B0],[Cp,D,D0,C0],[A,Bp,Cp,D]);
9257
+ faces.push([[Bp,Cp,C0,B0],shade(col,0.72)],[[Cp,D,D0,C0],shade(col,0.55)],[[A,Bp,Cp,D],col]);
9258
+ }
9259
+ // AXIS LABELS ARE PLACED LAST AND PAINTED LAST (backlog 48).
9260
+ // They used to be emitted in WORLD space at the floor's edge and then left
9261
+ // where they landed, which put them inside the projection's own footprint:
9262
+ // a tall bar rises up-and-left across exactly the row line whose name sits
9263
+ // out there, so the categories a tall bar celebrates were the ones it hid
9264
+ // (`telemetry-export`: "Sampler" on the 12000 bar; `queue-heatmap`: P0, P1
9265
+ // and P2 on the bar field, and the Q captions under the bar feet). Paint
9266
+ // order alone does not fix it — dark grey on a saturated fill is unread
9267
+ // whichever is on top — so the label LEANS OUT along its own grid line,
9268
+ // the one direction that keeps it a label OF that row or column: a row
9269
+ // name travels outward at constant r (decreasing c), a column name outward
9270
+ // at constant c (increasing r), each stepping 2 px until its box clears
9271
+ // every bar face. Leaning out is bounded (40 px); the halo is what carries
9272
+ // the rare label that cannot fully clear. The nudge changes no bar, no
9273
+ // floor and no ruler — only where a name sits on the line it already
9274
+ // belonged to.
9275
+ const HALO=' paint-order="stroke" stroke="#fff" stroke-width="3"';
9276
+ const LEAN=2, LEAN_MAX=96, CEIL=y0+18;
9277
+ function leanBox(px,py,wpx,anchor){
9278
+ return {x0:anchor==='end'?px-wpx:px, x1:anchor==='end'?px:px+wpx, y0:py-8, y1:py+2.5};
7001
9279
  }
7002
- // axis labels
7003
- rLab.forEach((l,r)=>{ const p=P(r+0.5,-0.15,0); svg.push(textEl(p[0]-4,p[1]+10,10,'end','#6f6e69',l)); });
7004
- cLab.forEach((l,c)=>{ const p=P(R+0.15,c+0.5,0); svg.push(textEl(p[0]+4,p[1]+10,10,'start','#6f6e69',l)); });
9280
+ function leanOut(x,y,wpx,anchor,dx,dy){
9281
+ const n=Math.hypot(dx,dy), ux=dx/n, uy=dy/n;
9282
+ let last=[x,y,leanBox(x,y,wpx,anchor),false];
9283
+ for(let k=0;k<=LEAN_MAX/LEAN;k++){
9284
+ const px=x+ux*k*LEAN, py=y+uy*k*LEAN;
9285
+ const box=leanBox(px,py,wpx,anchor);
9286
+ // never lean up past the section's own caption line: a name that
9287
+ // escapes the bars by leaving the chart is not a fix.
9288
+ if(box.y0<CEIL) break;
9289
+ last=[px,py,box];
9290
+ // 3 px of air, so "clear" reads as clear rather than as a name
9291
+ // ruled off by the bar it is standing against.
9292
+ const pad={x0:box.x0-3,x1:box.x1+3,y0:box.y0-2,y1:box.y1+2};
9293
+ let hit=false;
9294
+ for(const q of bars) if(chartQuadHitsBox(q,pad)){ hit=true; break; }
9295
+ // an axis label already placed is ink too: the column captions of
9296
+ // `telemetry-export` are 20 px apart in x and 10 px in y, so two long
9297
+ // ones ("Rate (pps)", "Drops/min") overlap by a line's descender unless
9298
+ // each leans clear of the last.
9299
+ if(!hit) for(const o of laid)
9300
+ if(pad.x0<o.x1&&pad.x1>o.x0&&pad.y0<o.y1&&pad.y1>o.y0){ hit=true; break; }
9301
+ if(!hit) return [px,py,box,true];
9302
+ }
9303
+ return [last[0],last[1],last[2],false];
9304
+ }
9305
+ let overhang=0, farRight=-Infinity, farDown=-Infinity;
9306
+ const placed=[], laid=[];
9307
+ rLab.forEach((l,r)=>{
9308
+ const p=PR(r+0.5,-0.15,0);
9309
+ const [x,y,box,ok]=leanOut(p[0]-4,p[1]+10,rLabPx(l),'end',-W2,-H2);
9310
+ placed.push([x,y,'end',l,ok]); laid.push(box);
9311
+ overhang=Math.max(overhang,-box.x0); farRight=Math.max(farRight,box.x1); farDown=Math.max(farDown,box.y1);
9312
+ });
9313
+ cLab.forEach((l,c)=>{
9314
+ const p=PR(R+0.15,c+0.5,0);
9315
+ const [x,y,box,ok]=leanOut(p[0]+4,p[1]+10,rLabPx(l),'start',-W2,H2);
9316
+ placed.push([x,y,'start',l,ok]); laid.push(box);
9317
+ overhang=Math.max(overhang,-box.x0); farRight=Math.max(farRight,box.x1); farDown=Math.max(farDown,box.y1);
9318
+ });
9319
+ const ox=Math.max(R*W2+8, overhang+4);
9320
+ for(const [poly,fill] of faces)
9321
+ svg.push('<polygon points="'+poly.map(p=>(p[0]+ox)+','+p[1]).join(' ')+'" fill="'+fill+'"/>');
9322
+ // THE HALO IS THE LAST RESORT, NOT THE HABIT. A label that found clear air
9323
+ // is drawn plainly: `tools/layout-lint.js` tells an EDGE label from every
9324
+ // other label by the halo twin (two <text> at one point), so haloing a chart
9325
+ // axis caption enrols it in F5's denominator, and an axis whose denominator
9326
+ // silently absorbs five non-edge labels is measuring something other than
9327
+ // what it prints. Only a caption the lean could not clear keeps the halo,
9328
+ // which is the one case where it is carrying the legibility.
9329
+ for(const [x,y,anchor,l,ok] of placed)
9330
+ lsvg.push(textEl(x+ox,y,10,anchor,'#6f6e69',l,ok?'':HALO));
9331
+ // floor grid edges — drawn UNDER the bars, so it is spliced in ahead of them
9332
+ const F=[PR(0,0,0),PR(R,0,0),PR(R,C,0),PR(0,C,0)];
9333
+ svg.splice(1,0,'<polygon points="'+F.map(p=>(p[0]+ox)+','+p[1]).join(' ')+'" fill="#f6f5ef" stroke="#d6d4cc"/>');
7005
9334
  // z ruler at the right-back corner
7006
- const zr=P(0,C,0);
9335
+ const zr=[PR(0,C,0)[0]+ox, PR(0,C,0)[1]];
7007
9336
  svg.push('<line x1="'+(zr[0]+14)+'" y1="'+zr[1]+'" x2="'+(zr[0]+14)+'" y2="'+(zr[1]-zmax*ZS)+'" stroke="#8a8880"/>');
7008
9337
  for(const z of [0, Math.round(zmax/2), Math.round(zmax)]){
7009
9338
  svg.push('<line x1="'+(zr[0]+11)+'" y1="'+(zr[1]-z*ZS)+'" x2="'+(zr[0]+17)+'" y2="'+(zr[1]-z*ZS)+'" stroke="#8a8880"/>');
7010
9339
  svg.push(textEl(zr[0]+21, zr[1]-z*ZS+3.5, 9.5, 'start', '#6f6e69', String(z)));
7011
9340
  }
7012
- const w=P(R,C,0)[0]+70, hgt=P(R,C,0)[1]+24-y0;
7013
- return {svg:svg.join(''), y:y0+hgt, w:w};
9341
+ const near=[PR(R,C,0)[0]+ox, PR(R,C,0)[1]];
9342
+ const w=Math.max(near[0]+70, farRight+ox+4);
9343
+ const hgt=Math.max(near[1]+24, farDown+6)-y0;
9344
+ return {svg:svg.join('')+lsvg.join(''), y:y0+hgt, w:w};
7014
9345
  }
7015
9346
 
7016
9347
  // ---- timing ----