mbeditor 0.12.0 → 0.12.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.
@@ -2,19 +2,29 @@
2
2
 
3
3
  // ModelGraph — an SVG entity diagram of the host app's ActiveRecord models.
4
4
  //
5
- // Laid out radially rather than left-to-right: the model with the most
6
- // associations sits at the centre and everything else fans out in rings by how
7
- // many hops away it is. A Rails schema is usually a hub with satellites, and a
8
- // column layout turns that into one very wide, very short strip.
5
+ // Laid out by the Sugiyama method the same one Graphviz `dot` uses, and so
6
+ // the same one Rails ERD produces this picture with. See the layout section
7
+ // below for the phases.
8
+ //
9
+ // Two earlier attempts are worth knowing about, because both looked reasonable
10
+ // on a demo app and failed on a real one. A radial layout put the busiest model
11
+ // at the centre and fanned the rest out in rings; at 300 models that is a single
12
+ // enormous circle, fitted so far out that no box is legible. A clustered grid
13
+ // was scannable but placed models by traversal order, so a box's position
14
+ // carried no information at all. Only a layered layout derives position from
15
+ // the associations themselves.
9
16
  var ModelGraph = (function () {
10
17
  var NODE_W = 188;
11
18
  var HEADER_H = 34; // model name + table name
12
19
  var FIELD_H = 15;
13
20
  var MAX_FIELDS = 8; // the rest are one click away in the schema modal
14
- var RING_GAP = 150;
15
- var MIN_RADIUS = 210;
16
- var NODE_GAP = 56; // clear space between neighbours on the same ring
17
- var BARYCENTRE_PASSES = 4;
21
+ var ROW_GAP = 36;
22
+ var LAYER_GAP = 110; // horizontal space between layers
23
+ var ORDER_PASSES = 4; // median sweeps for crossing reduction
24
+ var STRAIGHTEN_PASSES = 3;
25
+ var MAX_ASSOC_LISTED = 12; // the card stays readable; the rest are counted
26
+ var BLOCK_PAD = 26; // breathing room inside a cluster's boundary
27
+ var BLOCK_GAP = 56; // space between neighbouring clusters
18
28
 
19
29
  function nodeHeight(model) {
20
30
  var shown = Math.min((model.columns || []).length, MAX_FIELDS);
@@ -35,167 +45,283 @@ var ModelGraph = (function () {
35
45
  return adj;
36
46
  }
37
47
 
38
- function degreeOf(adj, name) { return Object.keys(adj[name] || {}).length; }
48
+ // ── Layout: Sugiyama layered, the standard for entity diagrams ────────────
49
+ //
50
+ // Associations are directed (belongs_to points a child at its parent), which
51
+ // is exactly the input a layered layout wants, and it is what Graphviz `dot`
52
+ // uses — and therefore Rails ERD, the usual tool for drawing this picture.
53
+ // The four classic phases: break cycles, assign layers, order within layers
54
+ // to cut crossings, then assign coordinates.
55
+ //
56
+ // Earlier attempts placed models by traversal order poured into grid cells.
57
+ // That put related models near each other only by accident: a box's position
58
+ // carried no information, so the diagram could not actually be read.
59
+
60
+ // Unique directed edges; self-references are dropped as placement constraints.
61
+ function directedEdges(models, edges) {
62
+ var known = {};
63
+ models.forEach(function (m) { known[m.name] = true; });
64
+ var seen = {};
65
+ var out = [];
66
+ edges.forEach(function (e) {
67
+ if (!known[e.from] || !known[e.to] || e.from === e.to) return;
68
+ var key = e.from + ' ' + e.to;
69
+ if (seen[key]) return;
70
+ seen[key] = true;
71
+ out.push({ from: e.from, to: e.to });
72
+ });
73
+ return out;
74
+ }
75
+
76
+ // Phase 1 — break cycles. Rails schemas are full of them (a belongs_to paired
77
+ // with a has_many the other way, or a genuine loop), and layering needs a DAG.
78
+ // Depth-first search, dropping any edge that points back at a node still on
79
+ // the stack. Those edges are still drawn in their true direction; they just
80
+ // stop constraining which layer a node lands in.
81
+ function breakCycles(names, edges) {
82
+ var out = {}, state = {}; // 0 unvisited, 1 on stack, 2 done
83
+ names.forEach(function (n) { out[n] = []; state[n] = 0; });
84
+ edges.forEach(function (e) { out[e.from].push(e.to); });
85
+
86
+ var acyclic = [];
87
+ names.forEach(function (root) {
88
+ if (state[root] !== 0) return;
89
+ // Iterative: a 300-model schema nests deeper than is comfortable for
90
+ // recursion.
91
+ var stack = [{ node: root, i: 0 }];
92
+ state[root] = 1;
93
+ while (stack.length) {
94
+ var top = stack[stack.length - 1];
95
+ if (top.i < out[top.node].length) {
96
+ var next = out[top.node][top.i++];
97
+ if (state[next] === 1) continue;
98
+ acyclic.push({ from: top.node, to: next });
99
+ if (state[next] === 0) { state[next] = 1; stack.push({ node: next, i: 0 }); }
100
+ } else {
101
+ state[top.node] = 2;
102
+ stack.pop();
103
+ }
104
+ }
105
+ });
106
+ return acyclic;
107
+ }
39
108
 
40
- // Rings by hop count from the busiest model. Disconnected islands are picked
41
- // up afterwards by their own local hub, so nothing is silently dropped.
42
- function assignRings(models, adj) {
43
- var remaining = {};
44
- models.forEach(function (m) { remaining[m.name] = true; });
109
+ // Phase 2 longest-path layering. A node sits one layer past its deepest
110
+ // predecessor, so every edge points forwards and depth reads left to right.
111
+ function assignLayers(names, acyclic) {
112
+ var incoming = {}, outgoing = {}, indeg = {};
113
+ names.forEach(function (n) { incoming[n] = []; outgoing[n] = []; indeg[n] = 0; });
114
+ acyclic.forEach(function (e) {
115
+ outgoing[e.from].push(e.to);
116
+ incoming[e.to].push(e.from);
117
+ indeg[e.to]++;
118
+ });
45
119
 
46
- var ring = {};
47
- var order = [];
120
+ var layer = {};
121
+ var queue = names.filter(function (n) { return indeg[n] === 0; });
122
+ queue.forEach(function (n) { layer[n] = 0; });
48
123
 
49
- while (Object.keys(remaining).length > 0) {
50
- var hub = Object.keys(remaining).sort(function (a, b) {
51
- var d = degreeOf(adj, b) - degreeOf(adj, a);
52
- return d !== 0 ? d : (a < b ? -1 : 1);
53
- })[0];
124
+ var pending = {};
125
+ names.forEach(function (n) { pending[n] = indeg[n]; });
54
126
 
55
- var queue = [hub];
56
- ring[hub] = order.length === 0 ? 0 : 1;
57
- delete remaining[hub];
58
- order.push(hub);
127
+ while (queue.length) {
128
+ var n = queue.shift();
129
+ outgoing[n].forEach(function (m) {
130
+ layer[m] = Math.max(layer[m] || 0, layer[n] + 1);
131
+ if (--pending[m] === 0) queue.push(m);
132
+ });
133
+ }
134
+ // Anything left sits in a knot the cycle-breaker could not fully unwind;
135
+ // park it past its deepest known predecessor rather than dropping it.
136
+ names.forEach(function (n) {
137
+ if (layer[n] !== undefined) return;
138
+ var base = 0;
139
+ incoming[n].forEach(function (p) { base = Math.max(base, (layer[p] || 0) + 1); });
140
+ layer[n] = base;
141
+ });
142
+ return layer;
143
+ }
59
144
 
60
- while (queue.length) {
61
- var current = queue.shift();
62
- Object.keys(adj[current] || {}).sort().forEach(function (next) {
63
- if (!remaining[next]) return;
64
- delete remaining[next];
65
- ring[next] = ring[current] + 1;
66
- order.push(next);
67
- queue.push(next);
145
+ // Phase 3 — crossing reduction by the median heuristic, swept down then up.
146
+ // Each node moves to the median position of its neighbours in the adjacent
147
+ // layer; repeated sweeps settle into far fewer crossings than any fixed
148
+ // ordering. This is the same heuristic dot uses.
149
+ function orderLayers(layers, adjIn, adjOut) {
150
+ var pos = {};
151
+ layers.forEach(function (names) {
152
+ names.forEach(function (n, i) { pos[n] = i; });
153
+ });
154
+
155
+ var medianOf = function (name, neighbours) {
156
+ var ps = (neighbours[name] || []).map(function (nb) { return pos[nb]; })
157
+ .filter(function (v) { return v !== undefined; })
158
+ .sort(function (a, b) { return a - b; });
159
+ if (!ps.length) return -1;
160
+ var mid = Math.floor(ps.length / 2);
161
+ return ps.length % 2 ? ps[mid] : (ps[mid - 1] + ps[mid]) / 2;
162
+ };
163
+
164
+ var sweep = function (from, to, step, neighbours) {
165
+ for (var li = from; li !== to; li += step) {
166
+ var names = layers[li];
167
+ if (!names || !names.length) continue;
168
+ var keyed = names.map(function (n, i) { return { n: n, m: medianOf(n, neighbours), i: i }; });
169
+ keyed.sort(function (a, b) {
170
+ // A node with no neighbour in the reference layer keeps its relative
171
+ // place rather than being bunched at one end.
172
+ if (a.m < 0 && b.m < 0) return a.i - b.i;
173
+ if (a.m < 0) return -1;
174
+ if (b.m < 0) return 1;
175
+ return a.m - b.m || a.i - b.i;
68
176
  });
177
+ layers[li] = keyed.map(function (k) { return k.n; });
178
+ layers[li].forEach(function (n, i) { pos[n] = i; });
69
179
  }
180
+ };
181
+
182
+ for (var pass = 0; pass < ORDER_PASSES; pass++) {
183
+ sweep(1, layers.length, 1, adjIn);
184
+ sweep(layers.length - 2, -1, -1, adjOut);
70
185
  }
71
- return ring;
186
+ return layers;
72
187
  }
73
188
 
74
- // Ordering within a ring is what decides how many lines cross. Repeatedly
75
- // move each node to the average angle of its already-placed neighbours
76
- // (a barycentre sweep) cheap, and it untangles most of the crossings a
77
- // naive alphabetical ring would create.
78
- function orderRing(names, angleOf, adj, ringOf, thisRing) {
79
- var ordered = names.slice();
80
- for (var pass = 0; pass < BARYCENTRE_PASSES; pass++) {
81
- var target = {};
82
- ordered.forEach(function (name) {
83
- var xs = 0, ys = 0, n = 0;
84
- Object.keys(adj[name] || {}).forEach(function (nb) {
85
- // Only anchor to neighbours already pinned by an inner ring;
86
- // same-ring ties would just chase each other.
87
- if (ringOf[nb] >= thisRing) return;
88
- var a = angleOf[nb];
89
- if (a === undefined) return;
90
- xs += Math.cos(a); ys += Math.sin(a); n++;
91
- });
92
- target[name] = n === 0 ? null : Math.atan2(ys, xs);
189
+ // Phase 4 coordinates. x is the layer; y stacks within a layer, then a few
190
+ // relaxation passes pull each node toward the average of its neighbours so
191
+ // chains come out straight instead of stepped. After each pass the layer is
192
+ // re-separated in order, so relaxation can never overlap two boxes.
193
+ function assignCoords(layers, byName, adjIn, adjOut) {
194
+ var y = {};
195
+ layers.forEach(function (names) {
196
+ if (!names) return;
197
+ var cursor = 0;
198
+ names.forEach(function (n) {
199
+ y[n] = cursor;
200
+ cursor += nodeHeight(byName[n]) + ROW_GAP;
93
201
  });
202
+ });
94
203
 
95
- var anchored = ordered.filter(function (n) { return target[n] !== null; });
96
- var floating = ordered.filter(function (n) { return target[n] === null; });
97
- anchored.sort(function (a, b) { return target[a] - target[b]; });
98
- ordered = anchored.concat(floating);
204
+ for (var pass = 0; pass < STRAIGHTEN_PASSES; pass++) {
205
+ layers.forEach(function (names) {
206
+ if (!names || !names.length) return;
207
+ names.forEach(function (n) {
208
+ var ns = (adjIn[n] || []).concat(adjOut[n] || []);
209
+ var vals = ns.map(function (nb) { return y[nb]; })
210
+ .filter(function (v) { return v !== undefined; });
211
+ if (!vals.length) return;
212
+ var want = vals.reduce(function (a, b) { return a + b; }, 0) / vals.length;
213
+ y[n] = y[n] + (want - y[n]) * 0.5;
214
+ });
215
+ var cursor = -Infinity;
216
+ names.forEach(function (n) {
217
+ if (y[n] < cursor) y[n] = cursor;
218
+ cursor = y[n] + nodeHeight(byName[n]) + ROW_GAP;
219
+ });
220
+ });
99
221
  }
100
- return ordered;
222
+
223
+ var minY = Infinity;
224
+ Object.keys(y).forEach(function (n) { minY = Math.min(minY, y[n]); });
225
+ if (!isFinite(minY)) minY = 0;
226
+
227
+ var positions = {};
228
+ var maxX = 0, maxY = 0;
229
+ layers.forEach(function (names, li) {
230
+ if (!names) return;
231
+ names.forEach(function (n) {
232
+ var x = li * (NODE_W + LAYER_GAP);
233
+ var yy = y[n] - minY;
234
+ positions[n] = { x: x, y: yy, model: byName[n] };
235
+ maxX = Math.max(maxX, x + NODE_W);
236
+ maxY = Math.max(maxY, yy + nodeHeight(byName[n]));
237
+ });
238
+ });
239
+ return { positions: positions, width: maxX, height: maxY };
240
+ }
241
+
242
+ // Connected components are laid out independently and stacked, the way dot
243
+ // handles a disconnected graph. Packing them together would interleave
244
+ // unrelated parts of the schema for no reason.
245
+ function components(names, adj) {
246
+ var seen = {}, out = [];
247
+ names.forEach(function (start) {
248
+ if (seen[start]) return;
249
+ var group = [], queue = [start];
250
+ seen[start] = true;
251
+ while (queue.length) {
252
+ var cur = queue.shift();
253
+ group.push(cur);
254
+ Object.keys(adj[cur] || {}).forEach(function (nb) {
255
+ if (seen[nb]) return;
256
+ seen[nb] = true;
257
+ queue.push(nb);
258
+ });
259
+ }
260
+ out.push(group);
261
+ });
262
+ return out.sort(function (a, b) { return b.length - a.length; });
101
263
  }
102
264
 
103
265
  function layout(models, edges) {
104
266
  var byName = {};
105
267
  models.forEach(function (m) { byName[m.name] = m; });
106
268
 
269
+ var dir = directedEdges(models, edges);
107
270
  var adj = adjacency(models, edges);
108
- var ringOf = assignRings(models, adj);
109
-
110
- var rings = [];
111
- models.forEach(function (m) {
112
- var r = ringOf[m.name] || 0;
113
- (rings[r] = rings[r] || []).push(m.name);
114
- });
271
+ var allNames = models.map(function (m) { return m.name; });
115
272
 
116
273
  var positions = {};
117
- var angleOf = {};
118
- var maxExtent = 0;
119
- // Radius and half-footprint of the ring inside this one, so each ring is
120
- // pushed clear of it. Without this an inner ring with many nodes gets a
121
- // large circumference-derived radius and the next ring lands inside it.
122
- var prevRadius = 0;
123
- var prevHalf = 0;
124
-
125
- rings.forEach(function (names, ringIndex) {
126
- if (!names) return;
274
+ var regions = [];
275
+ var pad = 60;
276
+ var cursorY = pad;
277
+ var maxRight = pad;
127
278
 
128
- if (ringIndex === 0) {
129
- names.forEach(function (name) {
130
- // Centred on the origin, like every other node. Placing the hub by
131
- // its top-left instead shifts it half a box down and right, straight
132
- // into the ring around it.
133
- var h = nodeHeight(byName[name]);
134
- positions[name] = { x: -NODE_W / 2, y: -h / 2, model: byName[name] };
135
- angleOf[name] = 0;
136
- prevHalf = Math.max(prevHalf, Math.max(NODE_W, h) / 2);
137
- });
138
- return;
139
- }
279
+ components(allNames, adj).forEach(function (group) {
280
+ var inGroup = {};
281
+ group.forEach(function (n) { inGroup[n] = true; });
282
+ var groupEdges = dir.filter(function (e) { return inGroup[e.from] && inGroup[e.to]; });
140
283
 
141
- var ordered = orderRing(names, angleOf, adj, ringOf, ringIndex);
284
+ var acyclic = breakCycles(group, groupEdges);
285
+ var layerOf = assignLayers(group, acyclic);
142
286
 
143
- // Boxes vary in height with their field count, so each one claims arc
144
- // proportional to its own footprint. Spacing them evenly by count is what
145
- // makes a tall box collide with its neighbours.
146
- var extents = ordered.map(function (name) {
147
- return Math.max(NODE_W, nodeHeight(byName[name])) + NODE_GAP;
287
+ var layers = [];
288
+ group.forEach(function (n) {
289
+ var l = layerOf[n] || 0;
290
+ (layers[l] = layers[l] || []).push(n);
148
291
  });
149
- var totalExtent = extents.reduce(function (a, b) { return a + b; }, 0);
150
- var thisHalf = Math.max.apply(null, extents) / 2;
151
- var radius = Math.max(
152
- MIN_RADIUS,
153
- totalExtent / (2 * Math.PI), // wide enough that neighbours clear
154
- prevRadius + prevHalf + thisHalf + 40 // and outside the ring within
155
- );
156
- prevRadius = radius;
157
- prevHalf = thisHalf;
158
-
159
- var cumulative = 0;
160
- ordered.forEach(function (name, i) {
161
- var angle = (2 * Math.PI * (cumulative + extents[i] / 2)) / totalExtent - Math.PI / 2;
162
- cumulative += extents[i];
163
- angleOf[name] = angle;
164
- var h = nodeHeight(byName[name]);
165
- positions[name] = {
166
- x: Math.cos(angle) * radius - NODE_W / 2,
167
- y: Math.sin(angle) * radius - h / 2,
168
- model: byName[name]
169
- };
170
- maxExtent = Math.max(maxExtent, radius + NODE_W, radius + h);
292
+ for (var i = 0; i < layers.length; i++) if (!layers[i]) layers[i] = [];
293
+ layers.forEach(function (names) { names.sort(); }); // deterministic start
294
+
295
+ var adjIn = {}, adjOut = {};
296
+ group.forEach(function (n) { adjIn[n] = []; adjOut[n] = []; });
297
+ acyclic.forEach(function (e) { adjOut[e.from].push(e.to); adjIn[e.to].push(e.from); });
298
+
299
+ orderLayers(layers, adjIn, adjOut);
300
+ var laid = assignCoords(layers, byName, adjIn, adjOut);
301
+
302
+ Object.keys(laid.positions).forEach(function (n) {
303
+ var p = laid.positions[n];
304
+ positions[n] = { x: pad + p.x, y: cursorY + p.y, model: p.model };
171
305
  });
172
- });
173
306
 
174
- // Shift everything positive and size the canvas to what was actually drawn.
175
- var pad = 60;
176
- var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
177
- Object.keys(positions).forEach(function (name) {
178
- var p = positions[name];
179
- var h = nodeHeight(p.model);
180
- minX = Math.min(minX, p.x); minY = Math.min(minY, p.y);
181
- maxX = Math.max(maxX, p.x + NODE_W); maxY = Math.max(maxY, p.y + h);
182
- });
183
- if (!isFinite(minX)) { minX = 0; minY = 0; maxX = NODE_W; maxY = HEADER_H; }
307
+ regions.push({
308
+ x: pad - BLOCK_PAD, y: cursorY - BLOCK_PAD,
309
+ w: laid.width + BLOCK_PAD * 2, h: laid.height + BLOCK_PAD * 2,
310
+ label: group.length > 1 ? group.length + ' related models' : group[0]
311
+ });
184
312
 
185
- Object.keys(positions).forEach(function (name) {
186
- positions[name].x += pad - minX;
187
- positions[name].y += pad - minY;
313
+ maxRight = Math.max(maxRight, pad + laid.width);
314
+ cursorY += laid.height + BLOCK_GAP;
188
315
  });
189
316
 
190
317
  return {
191
318
  positions: positions,
192
- width: (maxX - minX) + pad * 2,
193
- height: (maxY - minY) + pad * 2
319
+ regions: regions,
320
+ width: maxRight + pad,
321
+ height: cursorY - BLOCK_GAP + pad
194
322
  };
195
323
  }
196
324
 
197
- // Anchor on whichever side of each box faces the other, so lines leave and
198
- // arrive at the near edge instead of cutting through their own node.
199
325
  function anchors(a, b) {
200
326
  var ah = nodeHeight(a.model), bh = nodeHeight(b.model);
201
327
  var acx = a.x + NODE_W / 2, acy = a.y + ah / 2;
@@ -245,7 +371,10 @@ var ModelGraph = (function () {
245
371
  has_and_belongs_to_many: 'many ↔ many'
246
372
  };
247
373
 
248
- var MIN_ZOOM = 0.2;
374
+ // Low enough that a few hundred models genuinely fit on screen. At the old
375
+ // 0.2 floor a large app could not be framed at all, so fit-to-pane produced a
376
+ // view the zoom controls then refused to honour.
377
+ var MIN_ZOOM = 0.04;
249
378
  var MAX_ZOOM = 2.5;
250
379
 
251
380
  return function ModelGraphComponent(_ref) {
@@ -254,8 +383,30 @@ var ModelGraph = (function () {
254
383
  var onRefresh = _ref.onRefresh;
255
384
  var loading = _ref.loading;
256
385
 
257
- var _view = React.useState({ k: 1, x: 0, y: 0 });
258
- var view = _view[0], setView = _view[1];
386
+ // The view is a ref, not state, and is written straight onto the <g>'s
387
+ // transform. Every pan and zoom tick used to be a setState, which re-ran the
388
+ // whole layout (it was computed in the render body) and rebuilt every box,
389
+ // field and edge — around 10,000 SVG elements on a 300-model app. That is
390
+ // what made the graph unusable at real scale rather than anything about the
391
+ // drawing itself.
392
+ var viewRef = React.useRef({ k: 1, x: 0, y: 0 });
393
+ var sceneRef = React.useRef(null);
394
+ // Which layout we have already framed, so reopening the tab refits but a
395
+ // re-render for any other reason does not yank the view back.
396
+ var fittedForRef = React.useRef(null);
397
+
398
+ var applyView = React.useCallback(function () {
399
+ var g = sceneRef.current;
400
+ if (!g) return;
401
+ var v = viewRef.current;
402
+ g.setAttribute('transform', 'translate(' + v.x + ',' + v.y + ') scale(' + v.k + ')');
403
+ }, []);
404
+
405
+ var setView = React.useCallback(function (next) {
406
+ viewRef.current = typeof next === 'function' ? next(viewRef.current) : next;
407
+ applyView();
408
+ }, [applyView]);
409
+
259
410
  var _search = React.useState('');
260
411
  var search = _search[0], setSearch = _search[1];
261
412
  var _focused = React.useState(null);
@@ -267,27 +418,104 @@ var ModelGraph = (function () {
267
418
  var dragRef = React.useRef(null);
268
419
  var svgRef = React.useRef(null);
269
420
 
270
- // Laid out before the early returns so the fit effect below can see it.
271
- var placed = (graph && graph.ok && (graph.models || []).length)
272
- ? layout(graph.models, graph.edges || [])
273
- : null;
421
+ // Memoised on the graph payload. This used to run on every render — which,
422
+ // with the view in state, meant on every wheel tick and every mousemove of a
423
+ // drag.
424
+ var placed = React.useMemo(function () {
425
+ return (graph && graph.ok && (graph.models || []).length)
426
+ ? layout(graph.models, graph.edges || [])
427
+ : null;
428
+ }, [graph]);
429
+
430
+ // Every association each model takes part in, both directions, built once.
431
+ // Scanning the edge list per hover would be 513 comparisons on every
432
+ // mouseenter across a canvas of 300 boxes.
433
+ var associationsBy = React.useMemo(function () {
434
+ var byModel = {};
435
+ (graph && graph.edges || []).forEach(function (e) {
436
+ (byModel[e.from] = byModel[e.from] || []).push({ edge: e, outgoing: true });
437
+ if (e.to !== e.from) (byModel[e.to] = byModel[e.to] || []).push({ edge: e, outgoing: false });
438
+ });
439
+ return byModel;
440
+ }, [graph]);
441
+
442
+ var hoverCardRef = React.useRef(null);
443
+ var _modelHover = React.useState(null);
444
+ var modelHover = _modelHover[0], setModelHover = _modelHover[1];
445
+
446
+ // Highlighting is done by touching the DOM directly. Routing it through
447
+ // React would rebuild all ~7,000 elements of the scene on every mouseenter,
448
+ // which is the same trap the pan/zoom transform was in.
449
+ var litRef = React.useRef([]);
450
+ var clearLit = React.useCallback(function () {
451
+ litRef.current.forEach(function (el) { el.classList.remove('mg-lit'); });
452
+ litRef.current = [];
453
+ if (sceneRef.current) sceneRef.current.classList.remove('mg-focus-mode');
454
+ }, []);
455
+
456
+ var moveHoverCard = React.useCallback(function (ev) {
457
+ var card = hoverCardRef.current;
458
+ var el = svgRef.current;
459
+ if (!card || !el) return;
460
+ var rect = el.getBoundingClientRect();
461
+ var x = ev.clientX - rect.left;
462
+ var y = ev.clientY - rect.top;
463
+ // Flip before the card would run off the pane rather than after.
464
+ card.style.left = (x > rect.width - 300 ? x - 290 : x + 18) + 'px';
465
+ card.style.top = Math.min(y + 18, Math.max(0, rect.height - 240)) + 'px';
466
+ }, []);
467
+
468
+ var enterModel = React.useCallback(function (name, ev) {
469
+ if (dragRef.current) return; // panning, not inspecting
470
+ clearLit();
471
+ var scene = sceneRef.current;
472
+ if (scene) {
473
+ scene.classList.add('mg-focus-mode');
474
+ var sel = '[data-from="' + name + '"],[data-to="' + name + '"]';
475
+ litRef.current = Array.prototype.slice.call(scene.querySelectorAll(sel));
476
+ litRef.current.forEach(function (el) { el.classList.add('mg-lit'); });
477
+ }
478
+ setModelHover(name);
479
+ moveHoverCard(ev);
480
+ }, [clearLit, moveHoverCard]);
481
+
482
+ var leaveModel = React.useCallback(function () {
483
+ clearLit();
484
+ setModelHover(null);
485
+ }, [clearLit]);
274
486
 
275
487
  // Frame the whole graph on load. Without this the view starts at the
276
488
  // top-left of a canvas much larger than the pane and the diagram looks
277
489
  // empty until you go looking for it.
278
- var fitToPane = React.useCallback(function () {
490
+ var fitToPane = React.useCallback(function (attempt) {
279
491
  var el = svgRef.current;
280
492
  if (!el || !placed) return;
281
493
  var rect = el.getBoundingClientRect();
282
- if (!rect.width || !rect.height) return;
494
+ // The pane can still be unsized on the commit that mounts the SVG — the
495
+ // graph tab is opening at the same time. Bailing out here left the view at
496
+ // its 1:1 default and nothing ever retried, so a 300-model graph opened
497
+ // showing one corner of itself. Retry on the next frames until it has a
498
+ // size, then give up rather than spin.
499
+ if (!rect.width || !rect.height) {
500
+ if ((attempt || 0) < 10) {
501
+ window.requestAnimationFrame(function () { fitRef.current((attempt || 0) + 1); });
502
+ }
503
+ return;
504
+ }
283
505
 
284
- var k = Math.min(1, Math.min(rect.width / placed.width, rect.height / placed.height));
506
+ // Clamped to the same range the wheel enforces. Without the MIN_ZOOM
507
+ // clamp a large graph fitted to something like k=0.04, which is below the
508
+ // floor — so the first scroll snapped it up to MIN_ZOOM, a five-fold jump
509
+ // anchored on the cursor, and the diagram appeared to leap somewhere
510
+ // random. The view must never sit outside the range the controls allow.
511
+ var raw = Math.min(rect.width / placed.width, rect.height / placed.height);
512
+ var k = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min(1, raw)));
285
513
  setView({
286
514
  k: k,
287
515
  x: (rect.width - placed.width * k) / 2,
288
516
  y: (rect.height - placed.height * k) / 2
289
517
  });
290
- }, [placed && placed.width, placed && placed.height]);
518
+ }, [placed, setView]);
291
519
 
292
520
  React.useEffect(function () { fitToPane(); }, [fitToPane]);
293
521
 
@@ -316,6 +544,11 @@ var ModelGraph = (function () {
316
544
  // Same mounting problem as the wheel listener: the fit effect can run
317
545
  // before the SVG exists and not again afterwards. Kept current so the
318
546
  // callback ref can fit as soon as the element is really there.
547
+ // Held in a ref so the memoised node elements can call it without listing it
548
+ // as a dependency — otherwise every centre would rebuild the whole scene.
549
+ var centreRef = React.useRef(centreOn);
550
+ centreRef.current = centreOn;
551
+
319
552
  var fitRef = React.useRef(fitToPane);
320
553
  fitRef.current = fitToPane;
321
554
 
@@ -334,9 +567,25 @@ var ModelGraph = (function () {
334
567
  svgRef.current = el;
335
568
  if (!el) return;
336
569
 
570
+ // getBoundingClientRect forces a synchronous layout, and we had just
571
+ // written a new transform onto a <g> holding thousands of elements — so
572
+ // reading it per wheel tick made the browser re-lay-out the entire scene
573
+ // before the handler could continue. Measured at 27 ms a tick on a
574
+ // 300-model graph. The pane's own rect only changes when the window or
575
+ // the panel layout does, so cache it and refresh once per frame.
576
+ var rectRef = { current: null };
577
+ var invalidateRect = function () { rectRef.current = null; };
578
+ var paneRect = function () {
579
+ if (!rectRef.current) {
580
+ rectRef.current = el.getBoundingClientRect();
581
+ window.requestAnimationFrame(invalidateRect);
582
+ }
583
+ return rectRef.current;
584
+ };
585
+
337
586
  var onWheel = function (e) {
338
587
  e.preventDefault();
339
- var rect = el.getBoundingClientRect();
588
+ var rect = paneRect();
340
589
  var px = e.clientX - rect.left;
341
590
  var py = e.clientY - rect.top;
342
591
  setView(function (v) {
@@ -352,6 +601,133 @@ var ModelGraph = (function () {
352
601
  window.requestAnimationFrame(function () { fitRef.current(); });
353
602
  }, []);
354
603
 
604
+ // Memoised so hovering a model does not rebuild every box and edge.
605
+ // The highlight itself is applied by toggling DOM classes; only the
606
+ // association card is React state, and it lives outside this subtree.
607
+ var sceneChildren = React.useMemo(function () {
608
+ if (!placed) return null;
609
+ var models = (graph && graph.models) || [];
610
+ var edges = (graph && graph.edges) || [];
611
+ return [
612
+ // Behind everything: one soft area per connected cluster, so the
613
+ // grouping is something you can see rather than infer.
614
+ (placed.regions || []).map(function (r, i) {
615
+ return React.createElement(
616
+ 'g',
617
+ { key: 'r' + i, className: 'mg-region' },
618
+ React.createElement('rect', {
619
+ className: 'mg-region-box',
620
+ x: r.x, y: r.y, width: r.w, height: r.h, rx: 10
621
+ }),
622
+ React.createElement('text', {
623
+ className: 'mg-region-label', x: r.x + 12, y: r.y + 17
624
+ }, r.label)
625
+ );
626
+ }),
627
+ edges.map(function (e, i) {
628
+ var a = placed.positions[e.from];
629
+ var b = placed.positions[e.to];
630
+ if (!a || !b || e.from === e.to) return null;
631
+ var d = edgePath(a, b);
632
+ var isHovered = hovered && hovered.index === i;
633
+ return React.createElement(
634
+ 'g',
635
+ // Tagged so a node hover can find its own edges with one DOM query
636
+ // instead of a React pass over every edge.
637
+ { key: 'e' + i, 'data-from': e.from, 'data-to': e.to },
638
+ // A transparent, much thicker copy of the line under the real
639
+ // one. A 1.2px stroke is its own hit area, which makes hovering
640
+ // an association essentially impossible without this.
641
+ React.createElement('path', {
642
+ d: d,
643
+ className: 'mg-edge-hit',
644
+ onMouseEnter: function () { setHovered({ index: i, edge: e }); },
645
+ onMouseMove: function (ev) {
646
+ var rect = svgRef.current.getBoundingClientRect();
647
+ setPointer({ x: ev.clientX - rect.left, y: ev.clientY - rect.top });
648
+ },
649
+ onMouseLeave: function () { setHovered(null); }
650
+ }),
651
+ React.createElement('path', {
652
+ d: d,
653
+ className: 'mg-edge ' + (MACRO_CLASS[e.macro] || '') + (isHovered ? ' mg-edge-hovered' : ''),
654
+ markerEnd: 'url(#mg-arrow)'
655
+ })
656
+ );
657
+ }),
658
+ models.map(function (m) {
659
+ var pos = placed.positions[m.name];
660
+ if (!pos) return null;
661
+ var fields = (m.columns || []).slice(0, MAX_FIELDS);
662
+ var hidden = (m.columnCount || 0) - fields.length;
663
+ var h = nodeHeight(m);
664
+ return React.createElement(
665
+ 'g',
666
+ {
667
+ key: m.name,
668
+ className: 'mg-node' + (focused === m.name ? ' mg-focused' : ''),
669
+ transform: 'translate(' + pos.x + ',' + pos.y + ')',
670
+ onMouseEnter: function (ev) { enterModel(m.name, ev); },
671
+ onMouseMove: function (ev) { moveHoverCard(ev); },
672
+ onMouseLeave: function () { leaveModel(); },
673
+ onClick: function () {
674
+ // A drag that ends over a box must not also act on it.
675
+ if (dragRef.current && dragRef.current.moved) return;
676
+ // Clicking the box navigates: zoom to it. Opening the schema
677
+ // is the explicit button in the header, so a stray click while
678
+ // exploring no longer throws a modal in your way.
679
+ centreRef.current(m.name);
680
+ }
681
+ },
682
+ React.createElement('rect', { className: 'mg-box', width: NODE_W, height: h, rx: 4 }),
683
+ React.createElement('rect', { className: 'mg-box-header', width: NODE_W, height: HEADER_H, rx: 4 }),
684
+ React.createElement('text', { className: 'mg-name', x: 10, y: 15 }, m.name),
685
+ React.createElement('text', { className: 'mg-table', x: 10, y: 27 },
686
+ (m.table || '—') + (m.columnCount ? ' · ' + m.columnCount + ' cols' : '')),
687
+ // Opening the full schema is now an explicit target rather than
688
+ // anything-anywhere on the box, so clicking around to navigate
689
+ // cannot keep throwing a modal at you.
690
+ React.createElement(
691
+ 'g',
692
+ {
693
+ className: 'mg-open-btn',
694
+ onClick: function (ev) {
695
+ ev.stopPropagation();
696
+ if (dragRef.current && dragRef.current.moved) return;
697
+ if (onOpenModel) onOpenModel(m);
698
+ }
699
+ },
700
+ React.createElement('title', null, 'Open the full schema for ' + m.name),
701
+ React.createElement('rect', {
702
+ className: 'mg-open-btn-bg', x: NODE_W - 26, y: 7, width: 19, height: 19, rx: 3
703
+ }),
704
+ // Three stacked bars — a table, matching what the button opens.
705
+ React.createElement('rect', { className: 'mg-open-btn-bar', x: NODE_W - 22, y: 11, width: 11, height: 2 }),
706
+ React.createElement('rect', { className: 'mg-open-btn-bar', x: NODE_W - 22, y: 15.5, width: 11, height: 2 }),
707
+ React.createElement('rect', { className: 'mg-open-btn-bar', x: NODE_W - 22, y: 20, width: 11, height: 2 })
708
+ ),
709
+ fields.map(function (c, i) {
710
+ var y = HEADER_H + 11 + i * FIELD_H;
711
+ return React.createElement(
712
+ React.Fragment,
713
+ { key: c.name },
714
+ React.createElement('text', { className: 'mg-field', x: 10, y: y }, c.name),
715
+ React.createElement('text', { className: 'mg-field-type', x: NODE_W - 10, y: y, textAnchor: 'end' }, c.type)
716
+ );
717
+ }),
718
+ hidden > 0 && React.createElement('text', {
719
+ className: 'mg-field-more', x: 10, y: HEADER_H + 11 + fields.length * FIELD_H
720
+ }, '+' + hidden + ' more…'),
721
+ // No connection means no columns to show; say so rather than
722
+ // rendering an empty box that looks like a model with no fields.
723
+ fields.length === 0 && React.createElement('text', {
724
+ className: 'mg-field-more', x: 10, y: HEADER_H + 11
725
+ }, 'no database connection')
726
+ );
727
+ })
728
+ ];
729
+ }, [placed, graph, focused, onOpenModel]);
730
+
355
731
  if (loading) {
356
732
  return React.createElement('div', { className: 'ide-model-graph-empty' }, 'Building the model graph…');
357
733
  }
@@ -377,7 +753,9 @@ var ModelGraph = (function () {
377
753
 
378
754
  var onMouseDown = function (e) {
379
755
  if (e.button !== 0) return;
380
- dragRef.current = { sx: e.clientX, sy: e.clientY, ox: view.x, oy: view.y, moved: false };
756
+ var v = viewRef.current;
757
+ dragRef.current = { sx: e.clientX, sy: e.clientY, ox: v.x, oy: v.y, moved: false };
758
+ if (svgRef.current) svgRef.current.classList.add('mg-dragging');
381
759
  };
382
760
  var onMouseMove = function (e) {
383
761
  var d = dragRef.current;
@@ -386,7 +764,10 @@ var ModelGraph = (function () {
386
764
  if (Math.abs(dx) > 3 || Math.abs(dy) > 3) d.moved = true;
387
765
  setView(function (v) { return { k: v.k, x: d.ox + dx, y: d.oy + dy }; });
388
766
  };
389
- var endDrag = function () { dragRef.current = null; };
767
+ var endDrag = function () {
768
+ dragRef.current = null;
769
+ if (svgRef.current) svgRef.current.classList.remove('mg-dragging');
770
+ };
390
771
 
391
772
  return React.createElement(
392
773
  'div',
@@ -396,7 +777,7 @@ var ModelGraph = (function () {
396
777
  { className: 'ide-model-graph-toolbar' },
397
778
  React.createElement('span', null, models.length + ' models, ' + edges.length + ' associations'),
398
779
  graph.truncated && React.createElement('span', { className: 'ide-model-graph-warn' }, ' (truncated)'),
399
- React.createElement('span', { className: 'ide-model-graph-hint' }, 'drag to pan · scroll to zoom · click a model for its schema'),
780
+ React.createElement('span', { className: 'ide-model-graph-hint' }, 'drag to pan · scroll to zoom · click a model to zoom to it · hover for its associations'),
400
781
  React.createElement(
401
782
  'div',
402
783
  { className: 'ide-model-graph-actions' },
@@ -439,6 +820,48 @@ var ModelGraph = (function () {
439
820
  }, React.createElement('i', { className: 'fas fa-sync' }))
440
821
  )
441
822
  ),
823
+ // Every association a hovered model takes part in. The graph shows that a
824
+ // line exists; this says what it actually is, which is the thing you need
825
+ // when a model has a dozen of them fanning out.
826
+ React.createElement(
827
+ 'div',
828
+ {
829
+ ref: hoverCardRef,
830
+ className: 'mg-assoc-card' + (modelHover ? '' : ' mg-assoc-card-hidden')
831
+ },
832
+ modelHover && React.createElement('div', { className: 'mg-assoc-title' }, modelHover),
833
+ modelHover && (function () {
834
+ var list = associationsBy[modelHover] || [];
835
+ if (!list.length) {
836
+ return React.createElement('div', { className: 'mg-assoc-empty' }, 'No associations');
837
+ }
838
+ return React.createElement(
839
+ 'div',
840
+ { className: 'mg-assoc-list' },
841
+ React.createElement('div', { className: 'mg-assoc-count' },
842
+ list.length + (list.length === 1 ? ' association' : ' associations')),
843
+ list.slice(0, MAX_ASSOC_LISTED).map(function (a, i) {
844
+ var e = a.edge;
845
+ var other = a.outgoing ? e.to : e.from;
846
+ return React.createElement(
847
+ 'div',
848
+ { key: i, className: 'mg-assoc-row' },
849
+ React.createElement('span', {
850
+ className: 'mg-assoc-dot ' + (MACRO_CLASS[e.macro] || '')
851
+ }),
852
+ React.createElement('span', { className: 'mg-assoc-macro' }, e.macro),
853
+ React.createElement('span', { className: 'mg-assoc-name' }, ':' + e.name),
854
+ React.createElement('span', { className: 'mg-assoc-dir' },
855
+ (a.outgoing ? '→ ' : '← ') + other),
856
+ e.through && React.createElement('span', { className: 'mg-assoc-through' },
857
+ 'through :' + e.through)
858
+ );
859
+ }),
860
+ list.length > MAX_ASSOC_LISTED && React.createElement('div', { className: 'mg-assoc-more' },
861
+ '+' + (list.length - MAX_ASSOC_LISTED) + ' more')
862
+ );
863
+ })()
864
+ ),
442
865
  hovered && React.createElement(
443
866
  'div',
444
867
  {
@@ -483,79 +906,25 @@ var ModelGraph = (function () {
483
906
  ),
484
907
  React.createElement(
485
908
  'g',
486
- { transform: 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')' },
487
- edges.map(function (e, i) {
488
- var a = placed.positions[e.from];
489
- var b = placed.positions[e.to];
490
- if (!a || !b || e.from === e.to) return null;
491
- var d = edgePath(a, b);
492
- var isHovered = hovered && hovered.index === i;
493
- return React.createElement(
494
- 'g',
495
- { key: 'e' + i },
496
- // A transparent, much thicker copy of the line under the real
497
- // one. A 1.2px stroke is its own hit area, which makes hovering
498
- // an association essentially impossible without this.
499
- React.createElement('path', {
500
- d: d,
501
- className: 'mg-edge-hit',
502
- onMouseEnter: function () { setHovered({ index: i, edge: e }); },
503
- onMouseMove: function (ev) {
504
- var rect = svgRef.current.getBoundingClientRect();
505
- setPointer({ x: ev.clientX - rect.left, y: ev.clientY - rect.top });
506
- },
507
- onMouseLeave: function () { setHovered(null); }
508
- }),
509
- React.createElement('path', {
510
- d: d,
511
- className: 'mg-edge ' + (MACRO_CLASS[e.macro] || '') + (isHovered ? ' mg-edge-hovered' : ''),
512
- markerEnd: 'url(#mg-arrow)'
513
- })
514
- );
515
- }),
516
- models.map(function (m) {
517
- var pos = placed.positions[m.name];
518
- if (!pos) return null;
519
- var fields = (m.columns || []).slice(0, MAX_FIELDS);
520
- var hidden = (m.columnCount || 0) - fields.length;
521
- var h = nodeHeight(m);
522
- return React.createElement(
523
- 'g',
524
- {
525
- key: m.name,
526
- className: 'mg-node' + (focused === m.name ? ' mg-focused' : ''),
527
- transform: 'translate(' + pos.x + ',' + pos.y + ')',
528
- onClick: function () {
529
- // A drag that ends over a box must not also open it.
530
- if (dragRef.current && dragRef.current.moved) return;
531
- if (onOpenModel) onOpenModel(m);
532
- }
533
- },
534
- React.createElement('title', null, m.name + ' — click for the full schema'),
535
- React.createElement('rect', { className: 'mg-box', width: NODE_W, height: h, rx: 4 }),
536
- React.createElement('rect', { className: 'mg-box-header', width: NODE_W, height: HEADER_H, rx: 4 }),
537
- React.createElement('text', { className: 'mg-name', x: 10, y: 15 }, m.name),
538
- React.createElement('text', { className: 'mg-table', x: 10, y: 27 },
539
- (m.table || '—') + (m.columnCount ? ' · ' + m.columnCount + ' cols' : '')),
540
- fields.map(function (c, i) {
541
- var y = HEADER_H + 11 + i * FIELD_H;
542
- return React.createElement(
543
- React.Fragment,
544
- { key: c.name },
545
- React.createElement('text', { className: 'mg-field', x: 10, y: y }, c.name),
546
- React.createElement('text', { className: 'mg-field-type', x: NODE_W - 10, y: y, textAnchor: 'end' }, c.type)
547
- );
548
- }),
549
- hidden > 0 && React.createElement('text', {
550
- className: 'mg-field-more', x: 10, y: HEADER_H + 11 + fields.length * FIELD_H
551
- }, '+' + hidden + ' more…'),
552
- // No connection means no columns to show; say so rather than
553
- // rendering an empty box that looks like a model with no fields.
554
- fields.length === 0 && React.createElement('text', {
555
- className: 'mg-field-more', x: 10, y: HEADER_H + 11
556
- }, 'no database connection')
557
- );
558
- })
909
+ {
910
+ // No transform prop: applyView writes it directly, so panning and
911
+ // zooming never touch React.
912
+ ref: function (el) {
913
+ sceneRef.current = el;
914
+ if (!el) return;
915
+ applyView();
916
+ // Fit here rather than only from an effect. The effect fires
917
+ // before the tab has been given its size, so it measured a
918
+ // zero-width pane and bailed, leaving a 300-model graph opening at
919
+ // 1:1 showing one corner. This runs once per layout, on the frame
920
+ // after the scene actually exists.
921
+ if (fittedForRef.current !== placed) {
922
+ fittedForRef.current = placed;
923
+ window.requestAnimationFrame(function () { fitRef.current(); });
924
+ }
925
+ }
926
+ },
927
+ sceneChildren
559
928
  )
560
929
  )
561
930
  );