@graphty/layout 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ npx --no-install commitlint --edit "$1"
@@ -0,0 +1 @@
1
+ exec < /dev/tty && git cz --hook || true
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # Layout.js
2
+
3
+ Layout.js is a JavaScript library for node positioning in graphs. It is a JavaScript port of the [layout algorithms](https://networkx.org/documentation/stable/reference/drawing.html) found in the Python [NetworkX library](https://networkx.org/documentation/stable/).
4
+
5
+ ## Features
6
+
7
+ The library offers various graph layout algorithms, including:
8
+
9
+ - [Random Layout](https://graphty-org.github.io/layout/examples/random-layout.html)
10
+ - [Circular Layout](https://graphty-org.github.io/layout/examples/circular-layout.html)
11
+ - [Shell Layout](https://graphty-org.github.io/layout/examples/shell-layout.html)
12
+ - [Spring Layout (Fruchterman-Reingold)](https://graphty-org.github.io/layout/examples/spring-layout.html)
13
+ - [Spectral Layout](https://graphty-org.github.io/layout/examples/spectral-layout.html)
14
+ - [Spiral Layout](https://graphty-org.github.io/layout/examples/spiral-layout.html)
15
+ - [Bipartite Layout](https://graphty-org.github.io/layout/examples/bipartite-layout.html)
16
+ - [Multipartite Layout](https://graphty-org.github.io/layout/examples/multipartite-layout.html)
17
+ - [BFS Layout](https://graphty-org.github.io/layout/examples/bfs-html)
18
+ - [Planar Layout](https://graphty-org.github.io/layout/examples/planar.html)
19
+ - [Kamada-Kawai Layout](https://graphty-org.github.io/layout/examples/kamada-kawai-layout.html)
20
+ - [ForceAtlas2 Layout](https://graphty-org.github.io/layout/examples/forceatlas2-layout.html)
21
+ - [ARF Layout (Attractive and Repulsive Forces)](https://graphty-org.github.io/layout/examples/arf-layout.html)
22
+
23
+ ## How to Use
24
+
25
+ Import the library into your JavaScript project:
26
+
27
+ ```javascript
28
+ import {
29
+ randomLayout,
30
+ circularLayout,
31
+ springLayout
32
+ // other layout functions...
33
+ } from './layout.js'
34
+ ```
35
+
36
+ Usage example:
37
+
38
+ ```javascript
39
+ // Create a graph (data structure with nodes() and edges())
40
+ const graph = {
41
+ nodes: () => [0, 1, 2, 3],
42
+ edges: () => [
43
+ [0, 1],
44
+ [1, 2],
45
+ [2, 3],
46
+ [3, 0]
47
+ ]
48
+ }
49
+
50
+ // Apply a layout
51
+ const positions = circularLayout(graph)
52
+
53
+ // positions will be an object with x,y coordinates for each node
54
+ // { 0: [1, 0], 1: [0, 1], 2: [-1, 0], 3: [0, -1] }
55
+ ```
56
+
57
+ ## Requirements
58
+
59
+ - Modern browser with ES6 support
@@ -0,0 +1,37 @@
1
+ module.exports = {
2
+ parserPreset: "conventional-changelog-conventionalcommits",
3
+ rules: {
4
+ "body-leading-blank": [1, "always"],
5
+ "body-max-line-length": [2, "always", 100],
6
+ "footer-leading-blank": [1, "always"],
7
+ "footer-max-line-length": [2, "always", 100],
8
+ "header-max-length": [2, "always", 100],
9
+ "scope-case": [2, "always", "lower-case"],
10
+ "subject-case": [
11
+ 2,
12
+ "never",
13
+ ["sentence-case", "start-case", "pascal-case", "upper-case"],
14
+ ],
15
+ "subject-empty": [2, "never"],
16
+ "subject-full-stop": [2, "never", "."],
17
+ "type-case": [2, "always", "lower-case"],
18
+ "type-empty": [2, "never"],
19
+ "type-enum": [
20
+ 2,
21
+ "always",
22
+ [
23
+ "build",
24
+ "chore",
25
+ "ci",
26
+ "docs",
27
+ "feat",
28
+ "fix",
29
+ "perf",
30
+ "refactor",
31
+ "revert",
32
+ "style",
33
+ "test",
34
+ ],
35
+ ],
36
+ },
37
+ };
@@ -0,0 +1,512 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>ARF Layout Test</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ margin: 0;
11
+ padding: 20px;
12
+ background-color: #f5f5f5;
13
+ }
14
+ .container {
15
+ max-width: 1400px;
16
+ margin: 0 auto;
17
+ display: grid;
18
+ grid-template-columns: 250px 1fr 250px;
19
+ gap: 20px;
20
+ }
21
+ .graph-controls {
22
+ background: white;
23
+ padding: 20px;
24
+ border-radius: 8px;
25
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
26
+ height: fit-content;
27
+ }
28
+ .layout-controls {
29
+ background: white;
30
+ padding: 20px;
31
+ border-radius: 8px;
32
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
33
+ height: fit-content;
34
+ }
35
+ .visualization {
36
+ background: white;
37
+ border-radius: 8px;
38
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
39
+ padding: 20px;
40
+ }
41
+ .control-group {
42
+ margin-bottom: 15px;
43
+ }
44
+ label {
45
+ display: block;
46
+ margin-bottom: 5px;
47
+ font-weight: bold;
48
+ color: #333;
49
+ }
50
+ input[type="range"], input[type="number"], select {
51
+ width: 100%;
52
+ padding: 5px;
53
+ border: 1px solid #ddd;
54
+ border-radius: 4px;
55
+ }
56
+ button {
57
+ background: #4CAF50;
58
+ color: white;
59
+ border: none;
60
+ padding: 10px 15px;
61
+ border-radius: 4px;
62
+ cursor: pointer;
63
+ width: 100%;
64
+ margin: 5px 0;
65
+ }
66
+ button:hover {
67
+ background: #45a049;
68
+ }
69
+ #graph-svg {
70
+ border: 1px solid #ddd;
71
+ border-radius: 4px;
72
+ }
73
+ .back-link {
74
+ margin-bottom: 20px;
75
+ }
76
+ .back-link a {
77
+ color: #2c5aa0;
78
+ text-decoration: none;
79
+ }
80
+ .back-link a:hover {
81
+ text-decoration: underline;
82
+ }
83
+ .info-box {
84
+ background: #f0f7ff;
85
+ border: 1px solid #c0d7f0;
86
+ border-radius: 4px;
87
+ padding: 10px;
88
+ margin-top: 15px;
89
+ font-size: 0.85em;
90
+ }
91
+ .loading {
92
+ text-align: center;
93
+ color: #666;
94
+ font-style: italic;
95
+ margin-top: 10px;
96
+ }
97
+ .parameter-warning {
98
+ background: #fff3cd;
99
+ border: 1px solid #ffeaa7;
100
+ color: #856404;
101
+ padding: 8px;
102
+ border-radius: 4px;
103
+ margin-top: 5px;
104
+ font-size: 0.8em;
105
+ }
106
+ </style>
107
+ </head>
108
+ <body>
109
+ <div class="back-link">
110
+ <a href="index.html">← Back to Index</a>
111
+ </div>
112
+
113
+ <h1>ARF Layout Test</h1>
114
+
115
+ <div class="container">
116
+ <div class="graph-controls">
117
+ <h3>Graph Settings</h3>
118
+
119
+ <div class="control-group">
120
+ <label for="num-nodes">Number of nodes:</label>
121
+ <input type="range" id="num-nodes" min="5" max="30" value="15">
122
+ <span id="num-nodes-value">15</span>
123
+ </div>
124
+
125
+ <div class="control-group">
126
+ <label for="graph-type">Graph type:</label>
127
+ <select id="graph-type">
128
+ <option value="random">Random</option>
129
+ <option value="scale-free">Scale-free</option>
130
+ <option value="small-world">Small World</option>
131
+ <option value="complete">Complete</option>
132
+ <option value="cycle">Cycle</option>
133
+ <option value="star">Star</option>
134
+ </select>
135
+ </div>
136
+
137
+ <button onclick="newGraph()">New Graph</button>
138
+
139
+ <div class="info-box">
140
+ <strong>ARF Layout:</strong> Attractive and Repulsive Forces algorithm.
141
+ Uses spring forces between connected nodes (attraction) and repulsive forces
142
+ between all nodes. The parameter 'a' controls the strength of springs -
143
+ higher values create tighter clustering of connected components.
144
+ </div>
145
+ </div>
146
+
147
+ <div class="visualization">
148
+ <svg id="graph-svg" width="800" height="600"></svg>
149
+ </div>
150
+
151
+ <div class="layout-controls">
152
+ <h3>Layout Parameters</h3>
153
+
154
+ <div class="control-group">
155
+ <label for="scaling">Scaling factor:</label>
156
+ <input type="range" id="scaling" min="0.5" max="5" step="0.1" value="1">
157
+ <span id="scaling-value">1.0</span>
158
+ </div>
159
+
160
+ <div class="control-group">
161
+ <label for="spring-strength">Spring strength (a):</label>
162
+ <input type="range" id="spring-strength" min="1.1" max="5" step="0.1" value="1.1">
163
+ <span id="spring-strength-value">1.1</span>
164
+ <div id="spring-warning" class="parameter-warning" style="display: none;">
165
+ Parameter 'a' must be > 1 for stability
166
+ </div>
167
+ </div>
168
+
169
+ <div class="control-group">
170
+ <label for="max-iterations">Max iterations:</label>
171
+ <input type="range" id="max-iterations" min="100" max="3000" step="100" value="1000">
172
+ <span id="max-iterations-value">1000</span>
173
+ </div>
174
+
175
+ <button onclick="applyLayout()">Apply Layout</button>
176
+ <div id="loading" class="loading" style="display: none;">Computing layout...</div>
177
+ </div>
178
+ </div>
179
+
180
+ <script type="module">
181
+ import { arfLayout } from './layout.js';
182
+
183
+ let currentGraph = null;
184
+ let currentSeed = Math.floor(Math.random() * 1000);
185
+
186
+ function generateGraph(type, numNodes) {
187
+ const nodes = Array.from({length: numNodes}, (_, i) => i);
188
+ const edges = [];
189
+
190
+ switch(type) {
191
+ case 'complete':
192
+ for(let i = 0; i < numNodes; i++) {
193
+ for(let j = i + 1; j < numNodes; j++) {
194
+ edges.push([i, j]);
195
+ }
196
+ }
197
+ break;
198
+
199
+ case 'cycle':
200
+ for(let i = 0; i < numNodes; i++) {
201
+ edges.push([i, (i + 1) % numNodes]);
202
+ }
203
+ break;
204
+
205
+ case 'star':
206
+ for(let i = 1; i < numNodes; i++) {
207
+ edges.push([0, i]);
208
+ }
209
+ break;
210
+
211
+ case 'scale-free':
212
+ // Barabási–Albert model
213
+ for(let i = 1; i < Math.min(4, numNodes); i++) {
214
+ edges.push([0, i]);
215
+ }
216
+
217
+ for(let i = 4; i < numNodes; i++) {
218
+ const newEdges = Math.min(2, i);
219
+ const nodeDegrees = new Array(i).fill(0);
220
+
221
+ for(const edge of edges) {
222
+ nodeDegrees[edge[0]]++;
223
+ nodeDegrees[edge[1]]++;
224
+ }
225
+
226
+ const totalDegree = nodeDegrees.reduce((sum, deg) => sum + deg, 0);
227
+ const added = new Set();
228
+
229
+ for(let j = 0; j < newEdges; j++) {
230
+ let targetNode;
231
+ do {
232
+ let rand = Math.random() * totalDegree;
233
+ targetNode = 0;
234
+ while(targetNode < i && rand > 0) {
235
+ rand -= nodeDegrees[targetNode];
236
+ if(rand > 0) targetNode++;
237
+ }
238
+ if(targetNode >= i) targetNode = Math.floor(Math.random() * i);
239
+ } while(added.has(targetNode));
240
+
241
+ edges.push([i, targetNode]);
242
+ added.add(targetNode);
243
+ }
244
+ }
245
+ break;
246
+
247
+ case 'small-world':
248
+ // Watts-Strogatz model
249
+ const k = Math.max(2, Math.min(6, Math.floor(numNodes / 3)));
250
+
251
+ // Start with ring lattice
252
+ for(let i = 0; i < numNodes; i++) {
253
+ for(let j = 1; j <= k / 2; j++) {
254
+ const target = (i + j) % numNodes;
255
+ if(!edges.some(e => (e[0] === i && e[1] === target) || (e[0] === target && e[1] === i))) {
256
+ edges.push([i, target]);
257
+ }
258
+ }
259
+ }
260
+
261
+ // Rewire with probability 0.1
262
+ const rewireProbability = 0.1;
263
+ const edgesToRewire = [];
264
+
265
+ edges.forEach((edge, idx) => {
266
+ if(Math.random() < rewireProbability) {
267
+ edgesToRewire.push(idx);
268
+ }
269
+ });
270
+
271
+ edgesToRewire.forEach(idx => {
272
+ const [source] = edges[idx];
273
+ let newTarget;
274
+ do {
275
+ newTarget = Math.floor(Math.random() * numNodes);
276
+ } while(newTarget === source ||
277
+ edges.some(e => (e[0] === source && e[1] === newTarget) ||
278
+ (e[0] === newTarget && e[1] === source)));
279
+
280
+ edges[idx][1] = newTarget;
281
+ });
282
+ break;
283
+
284
+ case 'random':
285
+ default:
286
+ const density = 0.15;
287
+ const possibleEdges = (numNodes * (numNodes - 1)) / 2;
288
+ const targetEdges = Math.ceil(possibleEdges * density);
289
+
290
+ // Ensure connectivity with spanning tree
291
+ for(let i = 1; i < numNodes; i++) {
292
+ const parent = Math.floor(Math.random() * i);
293
+ edges.push([parent, i]);
294
+ }
295
+
296
+ // Add random edges
297
+ let additionalEdges = targetEdges - (numNodes - 1);
298
+ let attempts = 0;
299
+
300
+ while(additionalEdges > 0 && attempts < 1000) {
301
+ const a = Math.floor(Math.random() * numNodes);
302
+ const b = Math.floor(Math.random() * numNodes);
303
+
304
+ if(a !== b && !edges.some(e => (e[0] === a && e[1] === b) || (e[0] === b && e[1] === a))) {
305
+ edges.push([a, b]);
306
+ additionalEdges--;
307
+ }
308
+
309
+ attempts++;
310
+ }
311
+ break;
312
+ }
313
+
314
+ return {
315
+ nodes: () => nodes,
316
+ edges: () => edges
317
+ };
318
+ }
319
+
320
+ function visualizeGraph(graph, positions) {
321
+ const svg = document.getElementById('graph-svg');
322
+ const svgRect = svg.getBoundingClientRect();
323
+ const width = svgRect.width;
324
+ const height = svgRect.height;
325
+
326
+ svg.innerHTML = '';
327
+
328
+ const margin = 50;
329
+ const scaleX = (width - 2 * margin);
330
+ const scaleY = (height - 2 * margin);
331
+
332
+ const nodes = graph.nodes();
333
+ const posValues = nodes.map(n => positions[n]);
334
+
335
+ if (posValues.length === 0) return;
336
+
337
+ const minX = Math.min(...posValues.map(p => p[0]));
338
+ const maxX = Math.max(...posValues.map(p => p[0]));
339
+ const minY = Math.min(...posValues.map(p => p[1]));
340
+ const maxY = Math.max(...posValues.map(p => p[1]));
341
+
342
+ const rangeX = maxX - minX || 1;
343
+ const rangeY = maxY - minY || 1;
344
+
345
+ // Calculate node degrees for sizing
346
+ const nodeDegrees = {};
347
+ nodes.forEach(node => { nodeDegrees[node] = 0; });
348
+
349
+ const edges = graph.edges();
350
+ edges.forEach(([source, target]) => {
351
+ nodeDegrees[source]++;
352
+ nodeDegrees[target]++;
353
+ });
354
+
355
+ // Draw edges
356
+ edges.forEach(([source, target]) => {
357
+ const sourcePos = positions[source];
358
+ const targetPos = positions[target];
359
+
360
+ const x1 = margin + (sourcePos[0] - minX) / rangeX * scaleX;
361
+ const y1 = margin + (sourcePos[1] - minY) / rangeY * scaleY;
362
+ const x2 = margin + (targetPos[0] - minX) / rangeX * scaleX;
363
+ const y2 = margin + (targetPos[1] - minY) / rangeY * scaleY;
364
+
365
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
366
+ line.setAttribute('x1', x1);
367
+ line.setAttribute('y1', y1);
368
+ line.setAttribute('x2', x2);
369
+ line.setAttribute('y2', y2);
370
+ line.setAttribute('stroke', '#999');
371
+ line.setAttribute('stroke-width', '1.5');
372
+ line.setAttribute('stroke-opacity', '0.7');
373
+ svg.appendChild(line);
374
+ });
375
+
376
+ // Draw nodes
377
+ nodes.forEach(node => {
378
+ const pos = positions[node];
379
+ const x = margin + (pos[0] - minX) / rangeX * scaleX;
380
+ const y = margin + (pos[1] - minY) / rangeY * scaleY;
381
+
382
+ // Node size based on degree
383
+ const degree = nodeDegrees[node];
384
+ const radius = 5 + Math.sqrt(degree + 1) * 2;
385
+
386
+ // Color based on degree
387
+ const maxDegree = Math.max(...Object.values(nodeDegrees));
388
+ const normalizedDegree = maxDegree > 0 ? degree / maxDegree : 0;
389
+ const hue = 220 - normalizedDegree * 60; // Blue to orange
390
+ const color = `hsl(${hue}, 70%, 50%)`;
391
+
392
+ const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
393
+ circle.setAttribute('cx', x);
394
+ circle.setAttribute('cy', y);
395
+ circle.setAttribute('r', radius);
396
+ circle.setAttribute('fill', color);
397
+ circle.setAttribute('stroke', '#333');
398
+ circle.setAttribute('stroke-width', '1.5');
399
+ svg.appendChild(circle);
400
+
401
+ // Add node label for smaller graphs
402
+ if(nodes.length <= 20) {
403
+ const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
404
+ text.setAttribute('x', x);
405
+ text.setAttribute('y', y + 3);
406
+ text.setAttribute('text-anchor', 'middle');
407
+ text.setAttribute('font-size', '10');
408
+ text.setAttribute('fill', 'white');
409
+ text.setAttribute('font-weight', 'bold');
410
+ text.textContent = node;
411
+ svg.appendChild(text);
412
+ }
413
+ });
414
+ }
415
+
416
+ window.newGraph = function() {
417
+ const numNodes = parseInt(document.getElementById('num-nodes').value);
418
+ const graphType = document.getElementById('graph-type').value;
419
+
420
+ try {
421
+ // Generate new graph
422
+ currentGraph = generateGraph(graphType, numNodes);
423
+ currentSeed = Math.floor(Math.random() * 1000);
424
+
425
+ // Just visualize with random positions initially
426
+ const positions = {};
427
+ currentGraph.nodes().forEach(node => {
428
+ positions[node] = [
429
+ (Math.random() - 0.5) * 1.5,
430
+ (Math.random() - 0.5) * 1.5
431
+ ];
432
+ });
433
+
434
+ visualizeGraph(currentGraph, positions);
435
+
436
+ } catch (error) {
437
+ console.error('Error in graph generation:', error);
438
+ const svg = document.getElementById('graph-svg');
439
+ svg.innerHTML = `<text x="50%" y="50%" text-anchor="middle" fill="red">Error: ${error.message}</text>`;
440
+ }
441
+ };
442
+
443
+ window.applyLayout = async function() {
444
+ if (!currentGraph) return;
445
+
446
+ const loadingDiv = document.getElementById('loading');
447
+ loadingDiv.style.display = 'block';
448
+
449
+ try {
450
+ await runARFLayout();
451
+ } catch (error) {
452
+ console.error('Error in ARF layout:', error);
453
+ const svg = document.getElementById('graph-svg');
454
+ svg.innerHTML = `<text x="50%" y="50%" text-anchor="middle" fill="red">Error: ${error.message}</text>`;
455
+ } finally {
456
+ loadingDiv.style.display = 'none';
457
+ }
458
+ };
459
+
460
+ async function runARFLayout() {
461
+ const scaling = parseFloat(document.getElementById('scaling').value);
462
+ const springStrength = parseFloat(document.getElementById('spring-strength').value);
463
+ const maxIterations = parseInt(document.getElementById('max-iterations').value);
464
+
465
+ // Validate spring strength parameter
466
+ if (springStrength <= 1) {
467
+ throw new Error("Spring strength parameter 'a' must be > 1");
468
+ }
469
+
470
+ // Run layout with a small delay to allow UI update
471
+ await new Promise(resolve => setTimeout(resolve, 10));
472
+
473
+ const positions = arfLayout(
474
+ currentGraph,
475
+ null, // pos - let algorithm initialize
476
+ scaling,
477
+ springStrength,
478
+ maxIterations,
479
+ currentSeed
480
+ );
481
+
482
+ visualizeGraph(currentGraph, positions);
483
+ }
484
+
485
+ function setupControls() {
486
+ const sliders = ['num-nodes', 'scaling', 'spring-strength', 'max-iterations'];
487
+ sliders.forEach(id => {
488
+ const slider = document.getElementById(id);
489
+ const valueSpan = document.getElementById(id + '-value');
490
+ slider.oninput = function() {
491
+ valueSpan.textContent = this.value;
492
+
493
+ // Show warning for spring strength
494
+ if (id === 'spring-strength') {
495
+ const warning = document.getElementById('spring-warning');
496
+ if (parseFloat(this.value) <= 1.0) {
497
+ warning.style.display = 'block';
498
+ } else {
499
+ warning.style.display = 'none';
500
+ }
501
+ }
502
+ };
503
+ });
504
+
505
+ document.getElementById('graph-type').onchange = null;
506
+ }
507
+
508
+ setupControls();
509
+ newGraph();
510
+ </script>
511
+ </body>
512
+ </html>