spinne-html 0.3.0

HTML representation of component graph for spinne
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
<!DOCTYPE html>
<html>
<head>
    <title>Component Dependency Graph</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        .node {
            stroke: #fff;
            stroke-width: 1.5px;
        }

        .link {
            stroke: #999;
            stroke-opacity: 0.6;
            stroke-width: 1px;
        }

        .node text {
            font-size: 12px;
            font-family: Arial, sans-serif;
        }

        .tooltip {
            position: absolute;
            padding: 8px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            border-radius: 4px;
            font-size: 12px;
            pointer-events: none;
        }

        #graph {
            width: 100%;
            height: 100vh;
            overflow: hidden;
        }

        svg {
            width: 100%;
            height: 100%;
        }

        .search-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .search-input {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            width: 200px;
            font-size: 14px;
        }

        .export-container {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            gap: 8px;
        }

        .export-button {
            padding: 8px 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background: white;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .export-button:hover {
            background: #f0f0f0;
        }
    </style>
</head>
<body>
    <div class="search-container">
        <input type="text" 
               class="search-input" 
               placeholder="Search components..."
               oninput="filterNodes(this.value)">
    </div>
    <div class="export-container">
        <button class="export-button" onclick="exportAsSVG()">Export SVG</button>
        <button class="export-button" onclick="exportAsPNG()">Export PNG</button>
    </div>
    <div id="graph"></div>
    <script>
        // The graph data will be injected here
        const graphData = {"nodes":[{"name":"ComponentA","file_path":"/path/to/ComponentA.tsx","prop_usage":{}},{"name":"ComponentB","file_path":"/path/to/ComponentB.tsx","prop_usage":{}},{"name":"ComponentC","file_path":"/path/to/ComponentC.tsx","prop_usage":{}},{"name":"ComponentD","file_path":"/path/to/ComponentD.tsx","prop_usage":{}},{"name":"ComponentE","file_path":"/path/to/ComponentE.tsx","prop_usage":{}}],"edges":[[0,1],[2,1],[3,1],[3,4]]};

        // Width and height of the visualization
        const width = window.innerWidth;
        const height = window.innerHeight;

        // Create tooltip div
        const tooltip = d3.select("body")
            .append("div")
            .attr("class", "tooltip")
            .style("opacity", 0);

        // Create SVG container
        const svg = d3.select("#graph")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

        const g = svg.append("g");
        const zoom = d3.zoom().scaleExtent([0.5, 4]).on("zoom", function(event) {
            g.attr("transform", event.transform);
        });
        svg.call(zoom);

        // Create the force simulation
        const simulation = d3.forceSimulation()
            .force("link", d3.forceLink().distance(100))
            .force("charge", d3.forceManyBody().strength(-300))
            .force("center", d3.forceCenter(width / 2, height / 2))
            .force("collision", d3.forceCollide().radius(50));

        // Calculate the number of incoming edges for each node
        const incomingEdges = {};
            graphData.edges.forEach(edge => {
                const targetId = edge[1];
                incomingEdges[targetId] = (incomingEdges[targetId] || 0) + 1;
            });

        renderGraph(graphData);

        function renderGraph(data) {
            debugger
            const links = data.edges.map(edge => ({
                source: edge[0],
                target: edge[1]
            }));

            // Create links
            const link = g.append("g")
                .selectAll("line")
                .data(links)
                .enter()
                .append("line")
                .attr("class", "link")
                .attr("marker-end", "url(#arrowhead)");

            // Create nodes
            const node = g.append("g")
                .selectAll("g")
                .data(data.nodes)
                .enter()
                .append("g")
                .call(d3.drag()
                    .on("start", dragstarted)
                    .on("drag", dragged)
                    .on("end", dragended))
                .on("mouseover", function(event, d) {
                    const transform = d3.zoomTransform(svg.node());
                    tooltip.transition()
                        .duration(200)
                        .style("opacity", .9);
                    tooltip.html(`Path: ${d.file_path}<br/>Props: ${Object.entries(d.prop_usage).map(([prop, count]) => `${prop}(${count})`).join(', ')}`)
                        .style("left", (event.pageX + 10) + "px")
                        .style("top", (event.pageY - 28) + "px");
                })
                .on("mouseout", function(d) {
                    tooltip.transition()
                        .duration(500)
                        .style("opacity", 0);
                });

            // Add circles to nodes
            node.append("circle")
                .attr("class", "node")
                .attr("r", getNodeRadius)
                .attr("fill", getNodeColor);

            // Add labels to nodes
            node.append("text")
                .attr("dx", 12)
                .attr("dy", ".35em")
                .text(d => d.name);
            
            // Tick function to update positions
            function ticked() {
                link
                    .attr("x1", d => d.source.x)
                    .attr("y1", d => d.source.y)
                    .attr("x2", d => {
                        const dx = d.target.x - d.source.x;
                        const dy = d.target.y - d.source.y;
                        const length = Math.sqrt(dx * dx + dy * dy);
                        if (length === 0) return d.target.x;
                        
                        // Get target node radius
                        const targetRadius = getNodeRadius(d.target, d.target.index);
                        return d.target.x - (dx * (targetRadius + 5)) / length;  // Add offset for arrow
                    })
                    .attr("y2", d => {
                        const dx = d.target.x - d.source.x;
                        const dy = d.target.y - d.source.y;
                        const length = Math.sqrt(dx * dx + dy * dy);
                        if (length === 0) return d.target.y;
                        
                        // Get target node radius
                        const targetRadius = getNodeRadius(d.target, d.target.index);
                        return d.target.y - (dy * (targetRadius + 5)) / length;  // Add offset for arrow
                    });

                node
                    .attr("transform", d => `translate(${d.x},${d.y})`);
            }

            // Update positions on simulation tick
            simulation
                .nodes(data.nodes)
                .on("tick", ticked);

            simulation.force("link")
                .links(links);
        }

        // Function to calculate node radius based on incoming edges
        function getNodeRadius(d, i) {
            const baseRadius = 5;
            const edgeCount = incomingEdges[i] || 0;
            return baseRadius + (edgeCount * 2); // Increase radius by 2px per incoming edge
        }

        
        // Update the arrowhead marker
        svg.append("defs").append("marker")
            .attr("id", "arrowhead")
            .attr("viewBox", "0 -5 10 10")
            .attr("refX", 5)  // Adjust this value if needed
            .attr("refY", 0)
            .attr("markerWidth", 8)
            .attr("markerHeight", 8)
            .attr("orient", "auto")
            .append("path")
            .attr("d", "M0,-5L10,0L0,5")
            .attr("fill", "#999");

        // Helper function to determine node color based on type and incoming edges
        function getNodeColor(node) {
            const edgeCount = incomingEdges[node.index] || 0;
            // Color based on number of incoming edges
            if (edgeCount === 0) return "#69b3a2";
            if (edgeCount < 3) return "#3498db";
            if (edgeCount < 5) return "#e67e22";
            return "#e74c3c";
        }

        // Drag functions
        function dragstarted(event, d) {
            if (!event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(event, d) {
            d.fx = event.x;
            d.fy = event.y;
        }

        function dragended(event, d) {
            if (!event.active) simulation.alphaTarget(0);
        }

        function filterNodes(searchTerm) {
            searchTerm = searchTerm.toLowerCase();

            // Filter nodes based on search term
            const filteredNodes = searchTerm === "" 
                ? graphData.nodes 
                : graphData.nodes.filter(d => d.name.toLowerCase().includes(searchTerm));

            // Get indices of filtered nodes for edge filtering
            const filteredIndices = new Set(filteredNodes.map((_, i) => i));

            // Filter edges to only include connections between visible nodes
            const filteredEdges = searchTerm === ""
                ? graphData.edges
                : graphData.edges.filter(d => 
                    filteredIndices.has(d[0]) && filteredIndices.has(d[1]));

            // Clear existing graph
            g.selectAll("*").remove();

            // Create filtered graph data
            const filteredData = {
                nodes: filteredNodes,
                edges: filteredEdges
            };

            // Rerender the graph with filtered data
            renderGraph(filteredData);
        }

        function showTooltip(event, d) {
            tooltip.transition()
                .duration(200)
                .style("opacity", .9);
            const edgeCount = incomingEdges[d.index] || 0;
            tooltip.html(`Path: ${d.file_path}<br/>Props: ${Object.entries(d.prop_usage).map(([prop, count]) => `${prop}(${count})`).join(', ')}<br/>Incoming Edges: ${edgeCount}`)
                .style("left", (event.pageX + 10) + "px")
                .style("top", (event.pageY - 28) + "px");
        }

        function hideTooltip() {
            tooltip.transition()
                .duration(500)
                .style("opacity", 0);
        }

        document.addEventListener('keydown', function(e) {
            // Press '/' to focus search
            if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
                e.preventDefault();
                document.querySelector('.search-input').focus();
            }
            // Press 'Escape' to clear search
            if (e.key === 'Escape') {
                document.querySelector('.search-input').value = '';
                filterNodes('');
            }
        });

        // Function to export as SVG
        function exportAsSVG() {
            // Get the SVG element
            const svgElement = document.querySelector('svg');
            
            // Deep clone the SVG to avoid modifying the original
            const clonedSvg = svgElement.cloneNode(true);
            
            // Add necessary styles inline
            const styleElement = document.createElement('style');
            styleElement.textContent = `
                .node {
                    stroke: #fff;
                    stroke-width: 1.5px;
                }
                .link {
                    stroke: #999;
                    stroke-opacity: 0.6;
                    stroke-width: 1px;
                }
                .node text {
                    font-size: 12px;
                    font-family: Arial, sans-serif;
                }
                marker#arrowhead path {
                    fill: #999;
                }
            `;
            clonedSvg.insertBefore(styleElement, clonedSvg.firstChild);
            
            // Ensure the SVG has the correct size attributes
            const bbox = svgElement.getBBox();
            clonedSvg.setAttribute('width', bbox.width + bbox.x * 2);
            clonedSvg.setAttribute('height', bbox.height + bbox.y * 2);
            clonedSvg.setAttribute('viewBox', `${bbox.x} ${bbox.y} ${bbox.width + bbox.x} ${bbox.height + bbox.y}`);
            
            // Get the SVG source with the added styles
            const serializer = new XMLSerializer();
            const source = serializer.serializeToString(clonedSvg);
            
            // Add XML declaration and SVG namespace
            const svgData = '<?xml version="1.0" standalone="no"?>\r\n' + source;
            
            // Create Blob and download
            const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
            const svgUrl = URL.createObjectURL(svgBlob);
            
            // Create download link
            const downloadLink = document.createElement('a');
            downloadLink.href = svgUrl;
            downloadLink.download = 'component-graph.svg';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            
            // Clean up
            URL.revokeObjectURL(svgUrl);
        }

        // Function to export as PNG
        function exportAsPNG() {
            // Get the SVG element
            const svgElement = document.querySelector('svg');
            
            // Get the SVG dimensions
            const bbox = svgElement.getBBox();
            const width = bbox.width + bbox.x * 2;
            const height = bbox.height + bbox.y * 2;
            
            // Create a canvas element
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // Set canvas size to match SVG
            canvas.width = width;
            canvas.height = height;
            
            // Clone and prepare SVG for export (similar to SVG export)
            const clonedSvg = svgElement.cloneNode(true);
            const styleElement = document.createElement('style');
            styleElement.textContent = `
                .node {
                    stroke: #fff;
                    stroke-width: 1.5px;
                }
                .link {
                    stroke: #999;
                    stroke-opacity: 0.6;
                    stroke-width: 1px;
                }
                .node text {
                    font-size: 12px;
                    font-family: Arial, sans-serif;
                }
                marker#arrowhead path {
                    fill: #999;
                }
            `;
            clonedSvg.insertBefore(styleElement, clonedSvg.firstChild);
            clonedSvg.setAttribute('width', width);
            clonedSvg.setAttribute('height', height);
            clonedSvg.setAttribute('viewBox', `${bbox.x} ${bbox.y} ${bbox.width + bbox.x} ${bbox.height + bbox.y}`);
            
            // Create an image from the SVG
            const image = new Image();
            const svgData = new XMLSerializer().serializeToString(clonedSvg);
            const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
            const svgUrl = URL.createObjectURL(svgBlob);
            
            image.onload = function() {
                // Draw the image on the canvas
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, width, height);
                ctx.drawImage(image, 0, 0);
                
                // Convert canvas to PNG and download
                const pngUrl = canvas.toDataURL('image/png');
                const downloadLink = document.createElement('a');
                downloadLink.href = pngUrl;
                downloadLink.download = 'component-graph.png';
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
                
                // Clean up
                URL.revokeObjectURL(svgUrl);
            };
            
            image.src = svgUrl;
        }
    </script>
</body>
</html>